-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathblockchain.cpp
5283 lines (4779 loc) · 192 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-2019, 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/filesystem.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include "include_base_utils.h"
#include "cryptonote_basic/cryptonote_basic_impl.h"
#include "tx_pool.h"
#include "blockchain.h"
#include "blockchain_db/blockchain_db.h"
#include "cryptonote_basic/cryptonote_boost_serialization.h"
#include "cryptonote_config.h"
#include "cryptonote_basic/miner.h"
#include "hardforks/hardforks.h"
#include "misc_language.h"
#include "profile_tools.h"
#include "file_io_utils.h"
#include "int-util.h"
#include "common/threadpool.h"
#include "common/boost_serialization_helper.h"
#include "warnings.h"
#include "crypto/hash.h"
#include "cryptonote_core.h"
#include "ringct/rctSigs.h"
#include "common/perf_timer.h"
#include "common/notify.h"
#include "common/varint.h"
#include "common/pruning.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "blockchain"
#define FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE (100*1024*1024) // 100 MB
using namespace crypto;
//#include "serialization/json_archive.h"
/* TODO:
* Clean up code:
* Possibly change how outputs are referred to/indexed in blockchain and wallets
*
*/
using namespace cryptonote;
using epee::string_tools::pod_to_hex;
extern "C" void slow_hash_allocate_state();
extern "C" void slow_hash_free_state();
DISABLE_VS_WARNINGS(4267)
#define MERROR_VER(x) MCERROR("verify", x)
// used to overestimate the block reward when estimating a per kB to use
#define BLOCK_REWARD_OVERESTIMATE (10 * 1000000000000)
//------------------------------------------------------------------
Blockchain::Blockchain(tx_memory_pool& tx_pool) :
m_db(), m_tx_pool(tx_pool), m_hardfork(NULL), m_timestamps_and_difficulties_height(0), m_reset_timestamps_and_difficulties_height(true), m_current_block_cumul_weight_limit(0), m_current_block_cumul_weight_median(0),
m_enforce_dns_checkpoints(false), m_max_prepare_blocks_threads(4), m_db_sync_on_blocks(true), m_db_sync_threshold(1), m_db_sync_mode(db_async), m_db_default_sync(false), m_fast_sync(true), m_show_time_stats(false), m_sync_counter(0), m_bytes_to_sync(0), m_cancel(false),
m_long_term_block_weights_window(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE),
m_long_term_effective_median_block_weight(0),
m_long_term_block_weights_cache_tip_hash(crypto::null_hash),
m_long_term_block_weights_cache_rolling_median(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE),
m_difficulty_for_next_block_top_hash(crypto::null_hash),
m_difficulty_for_next_block(1),
m_btc_valid(false),
m_batch_success(true),
m_prepare_height(0)
{
LOG_PRINT_L3("Blockchain::" << __func__);
}
//------------------------------------------------------------------
Blockchain::~Blockchain()
{
try { deinit(); }
catch (const std::exception &e) { /* ignore */ }
}
//------------------------------------------------------------------
bool Blockchain::have_tx(const crypto::hash &id) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// WARNING: this function does not take m_blockchain_lock, and thus should only call read only
// m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
// well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
// lock if it is otherwise needed.
return m_db->tx_exists(id);
}
//------------------------------------------------------------------
bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// WARNING: this function does not take m_blockchain_lock, and thus should only call read only
// m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
// well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
// lock if it is otherwise needed.
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(size_t tx_version, const txin_to_key& tx_in_to_key, visitor_t &vis, const crypto::hash &tx_prefix_hash, uint64_t* pmax_related_block_height) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// ND: Disable locking and make method private.
//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<output_data_t> outputs;
bool found = false;
auto it = m_scan_table.find(tx_prefix_hash);
if (it != m_scan_table.end())
{
auto its = it->second.find(tx_in_to_key.k_image);
if (its != it->second.end())
{
outputs = its->second;
found = true;
}
}
if (!found)
{
try
{
m_db->get_output_key(epee::span<const uint64_t>(&tx_in_to_key.amount, 1), absolute_offsets, outputs, true);
if (absolute_offsets.size() != outputs.size())
{
MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
return false;
}
}
catch (...)
{
MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
return false;
}
}
else
{
// check for partial results and add the rest if needed;
if (outputs.size() < absolute_offsets.size() && outputs.size() > 0)
{
MDEBUG("Additional outputs needed: " << absolute_offsets.size() - outputs.size());
std::vector < uint64_t > add_offsets;
std::vector<output_data_t> add_outputs;
add_outputs.reserve(absolute_offsets.size() - outputs.size());
for (size_t i = outputs.size(); i < absolute_offsets.size(); i++)
add_offsets.push_back(absolute_offsets[i]);
try
{
m_db->get_output_key(epee::span<const uint64_t>(&tx_in_to_key.amount, 1), add_offsets, add_outputs, true);
if (add_offsets.size() != add_outputs.size())
{
MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
return false;
}
}
catch (...)
{
MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
return false;
}
outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end());
}
}
size_t count = 0;
for (const uint64_t& i : absolute_offsets)
{
try
{
output_data_t output_index;
try
{
// get tx hash and output index for output
if (count < outputs.size())
output_index = outputs.at(count);
else
output_index = m_db->get_output_key(tx_in_to_key.amount, i);
// call to the passed boost visitor to grab the public key for the output
if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment))
{
MERROR_VER("Failed to handle_output for output no = " << count << ", with absolute offset " << i);
return false;
}
}
catch (...)
{
MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount << ", 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 = output_index.height;
if(*pmax_related_block_height < h)
{
*pmax_related_block_height = h;
}
}
}
catch (const OUTPUT_DNE& e)
{
MERROR_VER("Output does not exist: " << e.what());
return false;
}
catch (const TX_DNE& e)
{
MERROR_VER("Transaction does not exist: " << e.what());
return false;
}
}
return true;
}
//------------------------------------------------------------------
uint64_t Blockchain::get_current_blockchain_height() const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// WARNING: this function does not take m_blockchain_lock, and thus should only call read only
// m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
// well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
// lock if it is otherwise needed.
return m_db->height();
}
//------------------------------------------------------------------
//FIXME: possibly move this into the constructor, to avoid accidentally
// dereferencing a null BlockchainDB pointer
bool Blockchain::init(BlockchainDB* db, const network_type nettype, bool offline, const cryptonote::test_options *test_options, difficulty_type fixed_difficulty, const GetCheckpointsCallback& get_checkpoints/* = nullptr*/)
{
LOG_PRINT_L3("Blockchain::" << __func__);
CHECK_AND_ASSERT_MES(nettype != FAKECHAIN || test_options, false, "fake chain network type used without options");
CRITICAL_REGION_LOCAL(m_tx_pool);
CRITICAL_REGION_LOCAL1(m_blockchain_lock);
if (db == nullptr)
{
LOG_ERROR("Attempted to init Blockchain with null DB");
return false;
}
if (!db->is_open())
{
LOG_ERROR("Attempted to init Blockchain with unopened DB");
delete db;
return false;
}
m_db = db;
m_nettype = test_options != NULL ? FAKECHAIN : nettype;
m_offline = offline;
m_fixed_difficulty = fixed_difficulty;
if (m_hardfork == nullptr)
{
if (m_nettype == FAKECHAIN || m_nettype == STAGENET)
m_hardfork = new HardFork(*db, 1, 0);
else if (m_nettype == TESTNET)
m_hardfork = new HardFork(*db, 1, testnet_hard_fork_version_1_till);
else
m_hardfork = new HardFork(*db, 1, mainnet_hard_fork_version_1_till);
}
if (m_nettype == FAKECHAIN)
{
for (size_t n = 0; test_options->hard_forks[n].first; ++n)
m_hardfork->add_fork(test_options->hard_forks[n].first, test_options->hard_forks[n].second, 0, n + 1);
}
else if (m_nettype == TESTNET)
{
for (size_t n = 0; n < num_testnet_hard_forks; ++n)
m_hardfork->add_fork(testnet_hard_forks[n].version, testnet_hard_forks[n].height, testnet_hard_forks[n].threshold, testnet_hard_forks[n].time);
}
else if (m_nettype == STAGENET)
{
for (size_t n = 0; n < num_stagenet_hard_forks; ++n)
m_hardfork->add_fork(stagenet_hard_forks[n].version, stagenet_hard_forks[n].height, stagenet_hard_forks[n].threshold, stagenet_hard_forks[n].time);
}
else
{
for (size_t n = 0; n < num_mainnet_hard_forks; ++n)
m_hardfork->add_fork(mainnet_hard_forks[n].version, mainnet_hard_forks[n].height, mainnet_hard_forks[n].threshold, mainnet_hard_forks[n].time);
}
m_hardfork->init();
m_db->set_hard_fork(m_hardfork);
// if the blockchain is new, add the genesis block
// this feels kinda kludgy to do it this way, but can be looked at later.
// TODO: add function to create and store genesis block,
// taking testnet into account
if(!m_db->height())
{
MINFO("Blockchain not loaded, generating genesis block.");
block bl;
block_verification_context bvc = {};
generate_genesis_block(bl, get_config(m_nettype).GENESIS_TX, get_config(m_nettype).GENESIS_NONCE);
db_wtxn_guard wtxn_guard(m_db);
add_new_block(bl, bvc);
CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain");
}
// TODO: if blockchain load successful, verify blockchain against both
// hard-coded and runtime-loaded (and enforced) checkpoints.
else
{
}
if (m_nettype != FAKECHAIN)
{
// ensure we fixup anything we found and fix in the future
m_db->fixup();
}
db_rtxn_guard rtxn_guard(m_db);
// 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 1397818133...
if(!top_block_timestamp)
timestamp_diff = time(NULL) - 1397818133;
// create general purpose async service queue
m_async_work_idle = std::unique_ptr < boost::asio::io_service::work > (new boost::asio::io_service::work(m_async_service));
// we only need 1
m_async_pool.create_thread(boost::bind(&boost::asio::io_service::run, &m_async_service));
#if defined(PER_BLOCK_CHECKPOINT)
if (m_nettype != FAKECHAIN)
load_compiled_in_block_hashes(get_checkpoints);
#endif
MINFO("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());
rtxn_guard.stop();
uint64_t num_popped_blocks = 0;
while (!m_db->is_read_only())
{
uint64_t top_height;
const crypto::hash top_id = m_db->top_block_hash(&top_height);
const block top_block = m_db->get_top_block();
const uint8_t ideal_hf_version = get_ideal_hard_fork_version(top_height);
if (ideal_hf_version <= 1 || ideal_hf_version == top_block.major_version)
{
if (num_popped_blocks > 0)
MGINFO("Initial popping done, top block: " << top_id << ", top height: " << top_height << ", block version: " << (uint64_t)top_block.major_version);
break;
}
else
{
if (num_popped_blocks == 0)
MGINFO("Current top block " << top_id << " at height " << top_height << " has version " << (uint64_t)top_block.major_version << " which disagrees with the ideal version " << (uint64_t)ideal_hf_version);
if (num_popped_blocks % 100 == 0)
MGINFO("Popping blocks... " << top_height);
++num_popped_blocks;
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)
{
MERROR("Error popping block from blockchain: " << e.what());
throw;
}
catch (...)
{
MERROR("Error popping block from blockchain, throwing!");
throw;
}
}
}
if (num_popped_blocks > 0)
{
m_timestamps_and_difficulties_height = 0;
m_reset_timestamps_and_difficulties_height = true;
m_hardfork->reorganize_from_chain_height(get_current_blockchain_height());
uint64_t top_block_height;
crypto::hash top_block_hash = get_tail_id(top_block_height);
m_tx_pool.on_blockchain_dec(top_block_height, top_block_hash);
}
if (test_options && test_options->long_term_block_weight_window)
{
m_long_term_block_weights_window = test_options->long_term_block_weight_window;
m_long_term_block_weights_cache_rolling_median = epee::misc_utils::rolling_median_t<uint64_t>(m_long_term_block_weights_window);
}
{
db_txn_guard txn_guard(m_db, m_db->is_read_only());
if (!update_next_cumulative_weight_limit())
return false;
}
return true;
}
//------------------------------------------------------------------
bool Blockchain::init(BlockchainDB* db, HardFork*& hf, const network_type nettype, bool offline)
{
if (hf != nullptr)
m_hardfork = hf;
bool res = init(db, nettype, offline, NULL);
if (hf == nullptr)
hf = m_hardfork;
return res;
}
//------------------------------------------------------------------
bool Blockchain::store_blockchain()
{
LOG_PRINT_L3("Blockchain::" << __func__);
// lock because the rpc_thread command handler also calls this
CRITICAL_REGION_LOCAL(m_db->m_synchronization_lock);
TIME_MEASURE_START(save);
// TODO: make sure sync(if this throws that it is not simply ignored higher
// up the call stack
try
{
m_db->sync();
}
catch (const std::exception& e)
{
MERROR(std::string("Error syncing blockchain db: ") + e.what() + "-- shutting down now to prevent issues!");
throw;
}
catch (...)
{
MERROR("There was an issue storing the blockchain, shutting down now to prevent issues!");
throw;
}
TIME_MEASURE_FINISH(save);
if(m_show_time_stats)
MINFO("Blockchain stored OK, took: " << save << " ms");
return true;
}
//------------------------------------------------------------------
bool Blockchain::deinit()
{
LOG_PRINT_L3("Blockchain::" << __func__);
MTRACE("Stopping blockchain read/write activity");
// stop async service
m_async_work_idle.reset();
m_async_pool.join_all();
m_async_service.stop();
// 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.
try
{
if (m_db)
{
m_db->close();
MTRACE("Local blockchain read/write activity stopped successfully");
}
}
catch (const std::exception& e)
{
LOG_ERROR(std::string("Error closing blockchain db: ") + e.what());
}
catch (...)
{
LOG_ERROR("There was an issue closing/storing the blockchain, shutting down now to prevent issues!");
}
delete m_hardfork;
m_hardfork = NULL;
delete m_db;
m_db = NULL;
return true;
}
//------------------------------------------------------------------
// This function removes blocks from the top of blockchain.
// It starts a batch and calls private method pop_block_from_blockchain().
void Blockchain::pop_blocks(uint64_t nblocks)
{
uint64_t i = 0;
CRITICAL_REGION_LOCAL(m_tx_pool);
CRITICAL_REGION_LOCAL1(m_blockchain_lock);
bool stop_batch = m_db->batch_start();
try
{
const uint64_t blockchain_height = m_db->height();
if (blockchain_height > 0)
nblocks = std::min(nblocks, blockchain_height - 1);
while (i < nblocks)
{
pop_block_from_blockchain();
++i;
}
}
catch (const std::exception& e)
{
LOG_ERROR("Error when popping blocks after processing " << i << " blocks: " << e.what());
if (stop_batch)
m_db->batch_abort();
return;
}
if (stop_batch)
m_db->batch_stop();
}
//------------------------------------------------------------------
// 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()
{
LOG_PRINT_L3("Blockchain::" << __func__);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_timestamps_and_difficulties_height = 0;
m_reset_timestamps_and_difficulties_height = true;
block popped_block;
std::vector<transaction> popped_txs;
CHECK_AND_ASSERT_THROW_MES(m_db->height() > 1, "Cannot pop the genesis block");
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;
}
// make sure the hard fork object updates its current version
m_hardfork->on_block_popped(1);
// return transactions from popped block to the tx_pool
size_t pruned = 0;
for (transaction& tx : popped_txs)
{
if (tx.pruned)
{
++pruned;
continue;
}
if (!is_coinbase(tx))
{
cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
// FIXME: HardFork
// Besides the below, popping a block should also remove the last entry
// in hf_versions.
uint8_t version = get_ideal_hard_fork_version(m_db->height());
// We assume that if they were in a block, the transactions are already
// known to the network as a whole. However, if we had mined that block,
// that might not be always true. Unlikely though, and always relaying
// these again might cause a spike of traffic as many nodes re-relay
// all the transactions in a popped block when a reorg happens.
bool r = m_tx_pool.add_tx(tx, tvc, relay_method::block, true, version);
if (!r)
{
LOG_ERROR("Error returning transaction to tx_pool");
}
}
}
if (pruned)
MWARNING(pruned << " pruned txes could not be added back to the txpool");
m_blocks_longhash_table.clear();
m_scan_table.clear();
m_blocks_txs_check.clear();
CHECK_AND_ASSERT_THROW_MES(update_next_cumulative_weight_limit(), "Error updating next cumulative weight limit");
uint64_t top_block_height;
crypto::hash top_block_hash = get_tail_id(top_block_height);
m_tx_pool.on_blockchain_dec(top_block_height, top_block_hash);
invalidate_block_template_cache();
return popped_block;
}
//------------------------------------------------------------------
bool Blockchain::reset_and_set_genesis_block(const block& b)
{
LOG_PRINT_L3("Blockchain::" << __func__);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_timestamps_and_difficulties_height = 0;
m_reset_timestamps_and_difficulties_height = true;
invalidate_block_template_cache();
m_db->reset();
m_db->drop_alt_blocks();
m_hardfork->init();
db_wtxn_guard wtxn_guard(m_db);
block_verification_context bvc = {};
add_new_block(b, bvc);
if (!update_next_cumulative_weight_limit())
return false;
return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed;
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_tail_id(uint64_t& height) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db->top_block_hash(&height);
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_tail_id() const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// WARNING: this function does not take m_blockchain_lock, and thus should only call read only
// m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
// well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
// lock if it is otherwise needed.
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) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
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;
db_rtxn_guard rtxn_guard(m_db);
bool genesis_included = false;
uint64_t current_back_offset = 1;
while(current_back_offset < sz)
{
ids.push_back(m_db->get_block_hash_from_height(sz - current_back_offset));
if(sz-current_back_offset == 0)
{
genesis_included = true;
}
if(i < 10)
{
++current_back_offset;
}
else
{
current_multiplier *= 2;
current_back_offset += current_multiplier;
}
++i;
}
if (!genesis_included)
{
ids.push_back(m_db->get_block_hash_from_height(0));
}
return true;
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
// WARNING: this function does not take m_blockchain_lock, and thus should only call read only
// m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
// well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
// lock if it is otherwise needed.
try
{
return m_db->get_block_hash_from_height(height);
}
catch (const BLOCK_DNE& e)
{
}
catch (const std::exception& e)
{
MERROR(std::string("Something went wrong fetching block hash by height: ") + e.what());
throw;
}
catch (...)
{
MERROR(std::string("Something went wrong fetching block hash by height"));
throw;
}
return null_hash;
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_pending_block_id_by_height(uint64_t height) const
{
if (m_prepare_height && height >= m_prepare_height && height - m_prepare_height < m_prepare_nblocks)
return (*m_prepare_blocks)[height - m_prepare_height].hash;
return get_block_id_by_height(height);
}
//------------------------------------------------------------------
bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const
{
LOG_PRINT_L3("Blockchain::" << __func__);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// try to find block in main chain
try
{
blk = m_db->get_block(h);
if (orphan)
*orphan = false;
return true;
}
// try to find block in alternative chain
catch (const BLOCK_DNE& e)
{
alt_block_data_t data;
cryptonote::blobdata blob;
if (m_db->get_alt_block(h, &data, &blob))
{
if (!cryptonote::parse_and_validate_block_from_blob(blob, blk))
{
MERROR("Found block " << h << " in alt chain, but failed to parse it");
throw std::runtime_error("Found block in alt chain, but failed to parse it");
}
if (orphan)
*orphan = true;
return true;
}
}
catch (const std::exception& e)
{
MERROR(std::string("Something went wrong fetching block by hash: ") + e.what());
throw;
}
catch (...)
{
MERROR(std::string("Something went wrong fetching block hash by hash"));
throw;
}
return false;
}
//------------------------------------------------------------------
// 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()
{
LOG_PRINT_L3("Blockchain::" << __func__);
std::stringstream ss;
bool print = false;
int done = 0;
ss << "get_difficulty_for_next_block: height " << m_db->height() << std::endl;
if (m_fixed_difficulty)
{
return m_db->height() ? m_fixed_difficulty : 1;
}
start:
difficulty_type D = 0;
crypto::hash top_hash = get_tail_id();
{
CRITICAL_REGION_LOCAL(m_difficulty_lock);
// we can call this without the blockchain lock, it might just give us
// something a bit out of date, but that's fine since anything which
// requires the blockchain lock will have acquired it in the first place,
// and it will be unlocked only when called from the getinfo RPC
ss << "Locked, tail id " << top_hash << ", cached is " << m_difficulty_for_next_block_top_hash << std::endl;
if (top_hash == m_difficulty_for_next_block_top_hash)
{
ss << "Same, using cached diff " << m_difficulty_for_next_block << std::endl;
D = m_difficulty_for_next_block;
}
}
CRITICAL_REGION_LOCAL(m_blockchain_lock);
std::vector<uint64_t> timestamps;
std::vector<difficulty_type> difficulties;
uint64_t height;
auto new_top_hash = get_tail_id(height); // get it again now that we have the lock
++height;
if (!(new_top_hash == top_hash)) D=0;
ss << "Re-locked, height " << height << ", tail id " << new_top_hash << (new_top_hash == top_hash ? "" : " (different)") << std::endl;
top_hash = new_top_hash;
// ND: Speedup
// 1. Keep a list of the last 735 (or less) blocks that is used to compute difficulty,
// then when the next block difficulty is queried, push the latest height data and
// pop the oldest one from the list. This only requires 1x read per height instead
// of doing 735 (DIFFICULTY_BLOCKS_COUNT).
bool check = false;
if (m_reset_timestamps_and_difficulties_height)
m_timestamps_and_difficulties_height = 0;
if (m_timestamps_and_difficulties_height != 0 && ((height - m_timestamps_and_difficulties_height) == 1) && m_timestamps.size() >= DIFFICULTY_BLOCKS_COUNT)
{
uint64_t index = height - 1;
m_timestamps.push_back(m_db->get_block_timestamp(index));
m_difficulties.push_back(m_db->get_block_cumulative_difficulty(index));
while (m_timestamps.size() > DIFFICULTY_BLOCKS_COUNT)
m_timestamps.erase(m_timestamps.begin());
while (m_difficulties.size() > DIFFICULTY_BLOCKS_COUNT)
m_difficulties.erase(m_difficulties.begin());
m_timestamps_and_difficulties_height = height;
timestamps = m_timestamps;
difficulties = m_difficulties;
check = true;
}
//else
std::vector<uint64_t> timestamps_from_cache = timestamps;
std::vector<difficulty_type> difficulties_from_cache = difficulties;
{
uint64_t offset = height - std::min <uint64_t> (height, static_cast<uint64_t>(DIFFICULTY_BLOCKS_COUNT));
if (offset == 0)
++offset;
timestamps.clear();
difficulties.clear();
if (height > offset)
{
timestamps.reserve(height - offset);
difficulties.reserve(height - offset);
}
ss << "Looking up " << (height - offset) << " from " << offset << std::endl;
for (; offset < height; offset++)
{
timestamps.push_back(m_db->get_block_timestamp(offset));
difficulties.push_back(m_db->get_block_cumulative_difficulty(offset));
}
if (check) if (timestamps != timestamps_from_cache || difficulties !=difficulties_from_cache)
{
ss << "Inconsistency XXX:" << std::endl;
ss << "top hash: "<<top_hash << std::endl;
ss << "timestamps: " << timestamps_from_cache.size() << " from cache, but " << timestamps.size() << " without" << std::endl;
ss << "difficulties: " << difficulties_from_cache.size() << " from cache, but " << difficulties.size() << " without" << std::endl;
ss << "timestamps_from_cache:" << std::endl; for (const auto &v :timestamps_from_cache) ss << " " << v << std::endl;
ss << "timestamps:" << std::endl; for (const auto &v :timestamps) ss << " " << v << std::endl;
ss << "difficulties_from_cache:" << std::endl; for (const auto &v :difficulties_from_cache) ss << " " << v << std::endl;
ss << "difficulties:" << std::endl; for (const auto &v :difficulties) ss << " " << v << std::endl;
uint64_t dbh = m_db->height();
uint64_t sh = dbh < 10000 ? 0 : dbh - 10000;
ss << "History from -10k at :" << dbh << ", from " << sh << std::endl;
for (uint64_t h = sh; h < dbh; ++h)
{
uint64_t ts = m_db->get_block_timestamp(h);
difficulty_type d = m_db->get_block_cumulative_difficulty(h);
ss << " " << h << " " << ts << " " << d << std::endl;
}
print = true;
}
m_timestamps_and_difficulties_height = height;
m_timestamps = timestamps;
m_difficulties = difficulties;
}
size_t target = get_difficulty_target();
difficulty_type diff = next_difficulty(timestamps, difficulties, target);
CRITICAL_REGION_LOCAL1(m_difficulty_lock);
m_difficulty_for_next_block_top_hash = top_hash;
m_difficulty_for_next_block = diff;
if (D && D != diff)
{
ss << "XXX Mismatch at " << height << "/" << top_hash << "/" << get_tail_id() << ": cached " << D << ", real " << diff << std::endl;
print = true;
}
++done;
if (done == 1 && D && D != diff)
{
print = true;
ss << "Might be a race. Let's see what happens if we try again..." << std::endl;
epee::misc_utils::sleep_no_w(100);
goto start;
}
ss << "Diff for " << top_hash << ": " << diff << std::endl;
if (print)
{
MGINFO("START DUMP");
MGINFO(ss.str());
MGINFO("END DUMP");
MGINFO("Please send moneromooo on Freenode the contents of this log, from a couple dozen lines before START DUMP to END DUMP");
}
return diff;
}
//------------------------------------------------------------------
std::vector<time_t> Blockchain::get_last_block_timestamps(unsigned int blocks) const
{
uint64_t height = m_db->height();
if (blocks > height)
blocks = height;
std::vector<time_t> timestamps(blocks);
while (blocks--)
timestamps[blocks] = m_db->get_block_timestamp(height - blocks - 1);
return timestamps;
}
//------------------------------------------------------------------
// 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, uint64_t rollback_height)
{
LOG_PRINT_L3("Blockchain::" << __func__);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// fail if rollback_height passed is too high
if (rollback_height > m_db->height())
{
return true;
}
m_timestamps_and_difficulties_height = 0;
m_reset_timestamps_and_difficulties_height = true;
// remove blocks from blockchain until we get back to where we should be.
while (m_db->height() != rollback_height)
{
pop_block_from_blockchain();
}
// make sure the hard fork object updates its current version
m_hardfork->reorganize_from_chain_height(rollback_height);
//return back original chain