Debian Codegraph @

src/cryptonote_core/blockchain.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <algorithm>
32 #include <cstdio>
33 #include <boost/asio/dispatch.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/range/adaptor/reversed.hpp>
36 #include <boost/format.hpp>
37
38 #include "include_base_utils.h"
39 #include "cryptonote_basic/cryptonote_basic_impl.h"
40 #include "tx_pool.h"
41 #include "blockchain.h"
42 #include "blockchain_db/blockchain_db.h"
43 #include "cryptonote_basic/cryptonote_boost_serialization.h"
44 #include "cryptonote_basic/events.h"
45 #include "cryptonote_config.h"
46 #include "cryptonote_basic/miner.h"
47 #include "hardforks/hardforks.h"
48 #include "misc_language.h"
49 #include "profile_tools.h"
50 #include "file_io_utils.h"
51 #include "int-util.h"
52 #include "common/threadpool.h"
53 #include "common/boost_serialization_helper.h"
54 #include "warnings.h"
55 #include "crypto/hash.h"
56 #include "cryptonote_core.h"
57 #include "ringct/rctSigs.h"
58 #include "common/perf_timer.h"
59 #include "common/notify.h"
60 #include "common/varint.h"
61 #include "common/pruning.h"
62 #include "common/data_cache.h"
63 #include "time_helper.h"
64
65 #undef MONERO_DEFAULT_LOG_CATEGORY
66 #define MONERO_DEFAULT_LOG_CATEGORY "blockchain"
67
68 #define FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE (100*1024*1024) // 100 MB
69
70 using namespace crypto;
71
72 //#include "serialization/json_archive.h"
73
74 /* TODO:
75 * Clean up code:
76 * Possibly change how outputs are referred to/indexed in blockchain and wallets
77 *
78 */
79
80 using namespace cryptonote;
81 using epee::string_tools::pod_to_hex;
82 extern "C" void slow_hash_allocate_state();
83 extern "C" void slow_hash_free_state();
84
85 DISABLE_VS_WARNINGS(4267)
86
87 #define MERROR_VER(x) MCERROR("verify", x)
88
89 // used to overestimate the block reward when estimating a per kB to use
90 #define BLOCK_REWARD_OVERESTIMATE (10 * 1000000000000)
91
92 //------------------------------------------------------------------
93 Blockchain::Blockchain(tx_memory_pool& tx_pool) :
94 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),
95 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),
96 m_long_term_block_weights_window(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE),
97 m_long_term_effective_median_block_weight(0),
98 m_long_term_block_weights_cache_tip_hash(crypto::null_hash),
99 m_long_term_block_weights_cache_rolling_median(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE),
100 m_difficulty_for_next_block_top_hash(crypto::null_hash),
101 m_difficulty_for_next_block(1),
102 m_btc_valid(false),
103 m_batch_success(true),
104 m_prepare_height(0),
105 m_rct_ver_cache()
106 {
107 LOG_PRINT_L3("Blockchain::" << __func__);
108 }
109 //------------------------------------------------------------------
110 Blockchain::~Blockchain()
111 {
112 try { deinit(); }
113 catch (const std::exception &e) { /* ignore */ }
114 }
115 //------------------------------------------------------------------
116 bool Blockchain::have_tx(const crypto::hash &id) const
117 {
118 LOG_PRINT_L3("Blockchain::" << __func__);
119 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
120 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
121 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
122 // lock if it is otherwise needed.
123 return m_db->tx_exists(id);
124 }
125 //------------------------------------------------------------------
126 bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const
127 {
128 LOG_PRINT_L3("Blockchain::" << __func__);
129 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
130 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
131 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
132 // lock if it is otherwise needed.
133 return m_db->has_key_image(key_im);
134 }
135 //------------------------------------------------------------------
136 // This function makes sure that each "input" in an input (mixins) exists
137 // and collects the public key for each from the transaction it was included in
138 // via the visitor passed to it.
139 template <class visitor_t>
140 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
141 {
142 LOG_PRINT_L3("Blockchain::" << __func__);
143
144 // ND: Disable locking and make method private.
145 //CRITICAL_REGION_LOCAL(m_blockchain_lock);
146
147 // verify that the input has key offsets (that it exists properly, really)
148 if(!tx_in_to_key.key_offsets.size())
149 return false;
150
151 // cryptonote_format_utils uses relative offsets for indexing to the global
152 // outputs list. that is to say that absolute offset #2 is absolute offset
153 // #1 plus relative offset #2.
154 // TODO: Investigate if this is necessary / why this is done.
155 std::vector<uint64_t> absolute_offsets = relative_output_offsets_to_absolute(tx_in_to_key.key_offsets);
156 std::vector<output_data_t> outputs;
157
158 bool found = false;
159 auto it = m_scan_table.find(tx_prefix_hash);
160 if (it != m_scan_table.end())
161 {
162 auto its = it->second.find(tx_in_to_key.k_image);
163 if (its != it->second.end())
164 {
165 outputs = its->second;
166 found = true;
167 }
168 }
169
170 if (!found)
171 {
172 try
173 {
174 m_db->get_output_key(epee::span<const uint64_t>(&tx_in_to_key.amount, 1), absolute_offsets, outputs, true);
175 if (absolute_offsets.size() != outputs.size())
176 {
177 MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
178 return false;
179 }
180 }
181 catch (...)
182 {
183 MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
184 return false;
185 }
186 }
187 else
188 {
189 // check for partial results and add the rest if needed;
190 if (outputs.size() < absolute_offsets.size() && outputs.size() > 0)
191 {
192 MDEBUG("Additional outputs needed: " << absolute_offsets.size() - outputs.size());
193 std::vector < uint64_t > add_offsets;
194 std::vector<output_data_t> add_outputs;
195 add_outputs.reserve(absolute_offsets.size() - outputs.size());
196 for (size_t i = outputs.size(); i < absolute_offsets.size(); i++)
197 add_offsets.push_back(absolute_offsets[i]);
198 try
199 {
200 m_db->get_output_key(epee::span<const uint64_t>(&tx_in_to_key.amount, 1), add_offsets, add_outputs, true);
201 if (add_offsets.size() != add_outputs.size())
202 {
203 MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
204 return false;
205 }
206 }
207 catch (...)
208 {
209 MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount);
210 return false;
211 }
212 outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end());
213 }
214 }
215
216 size_t count = 0;
217 for (const uint64_t& i : absolute_offsets)
218 {
219 try
220 {
221 output_data_t output_index;
222 try
223 {
224 // get tx hash and output index for output
225 if (count < outputs.size())
226 output_index = outputs.at(count);
227 else
228 output_index = m_db->get_output_key(tx_in_to_key.amount, i);
229
230 // call to the passed boost visitor to grab the public key for the output
231 if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment))
232 {
233 MERROR_VER("Failed to handle_output for output no = " << count << ", with absolute offset " << i);
234 return false;
235 }
236 }
237 catch (...)
238 {
239 MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount << ", absolute_offset = " << i);
240 return false;
241 }
242
243 // if on last output and pmax_related_block_height not null pointer
244 if(++count == absolute_offsets.size() && pmax_related_block_height)
245 {
246 // set *pmax_related_block_height to tx block height for this output
247 auto h = output_index.height;
248 if(*pmax_related_block_height < h)
249 {
250 *pmax_related_block_height = h;
251 }
252 }
253
254 }
255 catch (const OUTPUT_DNE& e)
256 {
257 MERROR_VER("Output does not exist: " << e.what());
258 return false;
259 }
260 catch (const TX_DNE& e)
261 {
262 MERROR_VER("Transaction does not exist: " << e.what());
263 return false;
264 }
265
266 }
267
268 return true;
269 }
270 //------------------------------------------------------------------
271 uint64_t Blockchain::get_current_blockchain_height() const
272 {
273 LOG_PRINT_L3("Blockchain::" << __func__);
274 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
275 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
276 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
277 // lock if it is otherwise needed.
278 return m_db->height();
279 }
280 //------------------------------------------------------------------
281 //FIXME: possibly move this into the constructor, to avoid accidentally
282 // dereferencing a null BlockchainDB pointer
283 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*/)
284 {
285 LOG_PRINT_L3("Blockchain::" << __func__);
286
287 CHECK_AND_ASSERT_MES(nettype != FAKECHAIN || test_options, false, "fake chain network type used without options");
288
289 CRITICAL_REGION_LOCAL(m_tx_pool);
290 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
291
292 if (db == nullptr)
293 {
294 LOG_ERROR("Attempted to init Blockchain with null DB");
295 return false;
296 }
297 if (!db->is_open())
298 {
299 LOG_ERROR("Attempted to init Blockchain with unopened DB");
300 delete db;
301 return false;
302 }
303
304 m_db = db;
305
306 m_nettype = test_options != NULL ? FAKECHAIN : nettype;
307 m_offline = offline;
308 m_fixed_difficulty = fixed_difficulty;
309 if (m_hardfork == nullptr)
310 {
311 if (m_nettype == FAKECHAIN || m_nettype == STAGENET)
312 m_hardfork = new HardFork(*db, 1, 0);
313 else if (m_nettype == TESTNET)
314 m_hardfork = new HardFork(*db, 1, testnet_hard_fork_version_1_till);
315 else
316 m_hardfork = new HardFork(*db, 1, mainnet_hard_fork_version_1_till);
317 }
318 if (m_nettype == FAKECHAIN)
319 {
320 for (size_t n = 0; test_options->hard_forks[n].first; ++n)
321 m_hardfork->add_fork(test_options->hard_forks[n].first, test_options->hard_forks[n].second, 0, n + 1);
322 }
323 else if (m_nettype == TESTNET)
324 {
325 for (size_t n = 0; n < num_testnet_hard_forks; ++n)
326 m_hardfork->add_fork(testnet_hard_forks[n].version, testnet_hard_forks[n].height, testnet_hard_forks[n].threshold, testnet_hard_forks[n].time);
327 }
328 else if (m_nettype == STAGENET)
329 {
330 for (size_t n = 0; n < num_stagenet_hard_forks; ++n)
331 m_hardfork->add_fork(stagenet_hard_forks[n].version, stagenet_hard_forks[n].height, stagenet_hard_forks[n].threshold, stagenet_hard_forks[n].time);
332 }
333 else
334 {
335 for (size_t n = 0; n < num_mainnet_hard_forks; ++n)
336 m_hardfork->add_fork(mainnet_hard_forks[n].version, mainnet_hard_forks[n].height, mainnet_hard_forks[n].threshold, mainnet_hard_forks[n].time);
337 }
338 m_hardfork->init();
339
340 m_db->set_hard_fork(m_hardfork);
341
342 // if the blockchain is new, add the genesis block
343 // this feels kinda kludgy to do it this way, but can be looked at later.
344 // TODO: add function to create and store genesis block,
345 // taking testnet into account
346 if(!m_db->height())
347 {
348 MINFO("Blockchain not loaded, generating genesis block.");
349 block bl;
350 block_verification_context bvc = {};
351 generate_genesis_block(bl, get_config(m_nettype).GENESIS_TX, get_config(m_nettype).GENESIS_NONCE);
352 db_wtxn_guard wtxn_guard(m_db);
353 add_new_block(bl, bvc);
354 CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain");
355 }
356 // TODO: if blockchain load successful, verify blockchain against both
357 // hard-coded and runtime-loaded (and enforced) checkpoints.
358 else
359 {
360 }
361
362 if (m_nettype != FAKECHAIN)
363 {
364 // ensure we fixup anything we found and fix in the future
365 m_db->fixup();
366 }
367
368 db_rtxn_guard rtxn_guard(m_db);
369
370 // check how far behind we are
371 uint64_t top_block_timestamp = m_db->get_top_block_timestamp();
372 uint64_t timestamp_diff = time(NULL) - top_block_timestamp;
373
374 // genesis block has no timestamp, could probably change it to have timestamp of 1397818133...
375 if(!top_block_timestamp)
376 timestamp_diff = time(NULL) - 1397818133;
377
378 // create general purpose async service queue
379
380 m_async_work_idle = std::make_unique<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>>(m_async_service.get_executor());
381 // we only need 1
382 m_async_pool.create_thread(boost::bind(&boost::asio::io_context::run, &m_async_service));
383
384 #if defined(PER_BLOCK_CHECKPOINT)
385 if (m_nettype != FAKECHAIN)
386 load_compiled_in_block_hashes(get_checkpoints);
387 #endif
388
389 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());
390
391 rtxn_guard.stop();
392
393 uint64_t num_popped_blocks = 0;
394 while (!m_db->is_read_only())
395 {
396 uint64_t top_height;
397 const crypto::hash top_id = m_db->top_block_hash(&top_height);
398 const block top_block = m_db->get_top_block();
399 const uint8_t ideal_hf_version = get_ideal_hard_fork_version(top_height);
400 if (ideal_hf_version <= 1 || ideal_hf_version == top_block.major_version)
401 {
402 if (num_popped_blocks > 0)
403 MGINFO("Initial popping done, top block: " << top_id << ", top height: " << top_height << ", block version: " << (uint64_t)top_block.major_version);
404 break;
405 }
406 else
407 {
408 if (num_popped_blocks == 0)
409 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);
410 if (num_popped_blocks % 100 == 0)
411 MGINFO("Popping blocks... " << top_height);
412 ++num_popped_blocks;
413 block popped_block;
414 std::vector<transaction> popped_txs;
415 try
416 {
417 m_db->pop_block(popped_block, popped_txs);
418 }
419 // anything that could cause this to throw is likely catastrophic,
420 // so we re-throw
421 catch (const std::exception& e)
422 {
423 MERROR("Error popping block from blockchain: " << e.what());
424 throw;
425 }
426 catch (...)
427 {
428 MERROR("Error popping block from blockchain, throwing!");
429 throw;
430 }
431 }
432 }
433 if (num_popped_blocks > 0)
434 {
435 m_timestamps_and_difficulties_height = 0;
436 m_reset_timestamps_and_difficulties_height = true;
437 m_hardfork->reorganize_from_chain_height(get_current_blockchain_height());
438 uint64_t top_block_height;
439 crypto::hash top_block_hash = get_tail_id(top_block_height);
440 m_tx_pool.on_blockchain_dec(top_block_height, top_block_hash);
441 }
442
443 if (test_options && test_options->long_term_block_weight_window)
444 {
445 m_long_term_block_weights_window = test_options->long_term_block_weight_window;
446 m_long_term_block_weights_cache_rolling_median = epee::misc_utils::rolling_median_t<uint64_t>(m_long_term_block_weights_window);
447 }
448
449 bool difficulty_ok;
450 uint64_t difficulty_recalc_height;
451 std::tie(difficulty_ok, difficulty_recalc_height) = check_difficulty_checkpoints();
452 if (!difficulty_ok)
453 {
454 MERROR("Difficulty drift detected!");
455 recalculate_difficulties(difficulty_recalc_height);
456 }
457
458 {
459 db_txn_guard txn_guard(m_db, m_db->is_read_only());
460 if (!update_next_cumulative_weight_limit())
461 return false;
462 }
463
464 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
465 {
466 const crypto::hash seedhash = get_block_id_by_height(crypto::rx_seedheight(m_db->height()));
467 if (seedhash != crypto::null_hash)
468 rx_set_main_seedhash(seedhash.data, tools::get_max_concurrency());
469 }
470
471 return true;
472 }
473 //------------------------------------------------------------------
474 bool Blockchain::init(BlockchainDB* db, HardFork*& hf, const network_type nettype, bool offline)
475 {
476 if (hf != nullptr)
477 m_hardfork = hf;
478 bool res = init(db, nettype, offline, NULL);
479 if (hf == nullptr)
480 hf = m_hardfork;
481 return res;
482 }
483 //------------------------------------------------------------------
484 bool Blockchain::store_blockchain()
485 {
486 LOG_PRINT_L3("Blockchain::" << __func__);
487 // lock because the rpc_thread command handler also calls this
488 CRITICAL_REGION_LOCAL(m_db->m_synchronization_lock);
489
490 TIME_MEASURE_START(save);
491 // TODO: make sure sync(if this throws that it is not simply ignored higher
492 // up the call stack
493 try
494 {
495 m_db->sync();
496 }
497 catch (const std::exception& e)
498 {
499 MERROR(std::string("Error syncing blockchain db: ") + e.what() + "-- shutting down now to prevent issues!");
500 throw;
501 }
502 catch (...)
503 {
504 MERROR("There was an issue storing the blockchain, shutting down now to prevent issues!");
505 throw;
506 }
507
508 TIME_MEASURE_FINISH(save);
509 if(m_show_time_stats)
510 MINFO("Blockchain stored OK, took: " << save << " ms");
511 return true;
512 }
513 //------------------------------------------------------------------
514 bool Blockchain::deinit()
515 {
516 LOG_PRINT_L3("Blockchain::" << __func__);
517
518 MTRACE("Stopping blockchain read/write activity");
519
520 // stop async service
521 m_async_work_idle.reset();
522 m_async_pool.join_all();
523 m_async_service.stop();
524
525 // as this should be called if handling a SIGSEGV, need to check
526 // if m_db is a NULL pointer (and thus may have caused the illegal
527 // memory operation), otherwise we may cause a loop.
528 try
529 {
530 if (m_db)
531 {
532 m_db->close();
533 MTRACE("Local blockchain read/write activity stopped successfully");
534 }
535 }
536 catch (const std::exception& e)
537 {
538 LOG_ERROR(std::string("Error closing blockchain db: ") + e.what());
539 }
540 catch (...)
541 {
542 LOG_ERROR("There was an issue closing/storing the blockchain, shutting down now to prevent issues!");
543 }
544
545 delete m_hardfork;
546 m_hardfork = NULL;
547 delete m_db;
548 m_db = NULL;
549 return true;
550 }
551 //------------------------------------------------------------------
552 // This function removes blocks from the top of blockchain.
553 // It starts a batch and calls private method pop_block_from_blockchain().
554 void Blockchain::pop_blocks(uint64_t nblocks)
555 {
556 uint64_t i = 0;
557 CRITICAL_REGION_LOCAL(m_tx_pool);
558 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
559
560 bool stop_batch = m_db->batch_start();
561
562 try
563 {
564 const uint64_t blockchain_height = m_db->height();
565 if (blockchain_height > 0)
566 nblocks = std::min(nblocks, blockchain_height - 1);
567 while (i < nblocks)
568 {
569 pop_block_from_blockchain();
570 ++i;
571 }
572 }
573 catch (const std::exception& e)
574 {
575 LOG_ERROR("Error when popping blocks after processing " << i << " blocks: " << e.what());
576 if (stop_batch)
577 m_db->batch_abort();
578 return;
579 }
580
581 CHECK_AND_ASSERT_THROW_MES(update_next_cumulative_weight_limit(), "Error updating next cumulative weight limit");
582
583 if (stop_batch)
584 m_db->batch_stop();
585
586 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
587 {
588 const crypto::hash seedhash = get_block_id_by_height(crypto::rx_seedheight(m_db->height()));
589 rx_set_main_seedhash(seedhash.data, tools::get_max_concurrency());
590 }
591 }
592 //------------------------------------------------------------------
593 // This function tells BlockchainDB to remove the top block from the
594 // blockchain and then returns all transactions (except the miner tx, of course)
595 // from it to the tx_pool
596 block Blockchain::pop_block_from_blockchain()
597 {
598 LOG_PRINT_L3("Blockchain::" << __func__);
599 CRITICAL_REGION_LOCAL(m_blockchain_lock);
600
601 m_timestamps_and_difficulties_height = 0;
602 m_reset_timestamps_and_difficulties_height = true;
603
604 block popped_block;
605 std::vector<transaction> popped_txs;
606
607 CHECK_AND_ASSERT_THROW_MES(m_db->height() > 1, "Cannot pop the genesis block");
608
609 const uint8_t previous_hf_version = get_current_hard_fork_version();
610 try
611 {
612 m_db->pop_block(popped_block, popped_txs);
613 }
614 // anything that could cause this to throw is likely catastrophic,
615 // so we re-throw
616 catch (const std::exception& e)
617 {
618 LOG_ERROR("Error popping block from blockchain: " << e.what());
619 throw;
620 }
621 catch (...)
622 {
623 LOG_ERROR("Error popping block from blockchain, throwing!");
624 throw;
625 }
626
627 // make sure the hard fork object updates its current version
628 m_hardfork->on_block_popped(1);
629
630 // return transactions from popped block to the tx_pool
631 size_t pruned = 0;
632 for (transaction& tx : popped_txs)
633 {
634 if (tx.pruned)
635 {
636 ++pruned;
637 continue;
638 }
639 if (!is_coinbase(tx))
640 {
641 cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
642
643 // FIXME: HardFork
644 // Besides the below, popping a block should also remove the last entry
645 // in hf_versions.
646 uint8_t version = get_ideal_hard_fork_version(m_db->height());
647
648 // We assume that if they were in a block, the transactions are already known to the network
649 // as a whole. However, if we had mined that block, that might not be always true. Unlikely
650 // though, and always relaying these again might cause a spike of traffic as many nodes
651 // re-relay all the transactions in a popped block when a reorg happens. You might notice that
652 // we also set the "nic_verified_hf_version" paramater. Since we know we took this transaction
653 // from the mempool earlier in this function call, when the mempool has the same current fork
654 // version, we can return it without re-verifying the consensus rules on it.
655 const bool r = m_tx_pool.add_tx(tx, tvc, relay_method::block, true, version, version);
656 if (!r)
657 {
658 LOG_ERROR("Error returning transaction to tx_pool");
659 }
660 }
661 }
662 if (pruned)
663 MWARNING(pruned << " pruned txes could not be added back to the txpool");
664
665 m_blocks_longhash_table.clear();
666 m_scan_table.clear();
667
668 uint64_t top_block_height;
669 crypto::hash top_block_hash = get_tail_id(top_block_height);
670 m_tx_pool.on_blockchain_dec(top_block_height, top_block_hash);
671 invalidate_block_template_cache();
672
673 const uint8_t new_hf_version = get_current_hard_fork_version();
674 if (new_hf_version != previous_hf_version)
675 {
676 MINFO("Validating txpool for v" << (unsigned)new_hf_version);
677 m_tx_pool.validate(new_hf_version);
678 }
679
680 return popped_block;
681 }
682 //------------------------------------------------------------------
683 bool Blockchain::reset_and_set_genesis_block(const block& b)
684 {
685 LOG_PRINT_L3("Blockchain::" << __func__);
686 CRITICAL_REGION_LOCAL(m_blockchain_lock);
687 m_timestamps_and_difficulties_height = 0;
688 m_reset_timestamps_and_difficulties_height = true;
689 invalidate_block_template_cache();
690 m_db->reset();
691 m_db->drop_alt_blocks();
692 m_hardfork->init();
693
694 db_wtxn_guard wtxn_guard(m_db);
695 block_verification_context bvc = {};
696 add_new_block(b, bvc);
697 if (!update_next_cumulative_weight_limit())
698 return false;
699 return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed;
700 }
701 //------------------------------------------------------------------
702 crypto::hash Blockchain::get_tail_id(uint64_t& height) const
703 {
704 LOG_PRINT_L3("Blockchain::" << __func__);
705 CRITICAL_REGION_LOCAL(m_blockchain_lock);
706 return m_db->top_block_hash(&height);
707 }
708 //------------------------------------------------------------------
709 crypto::hash Blockchain::get_tail_id() const
710 {
711 LOG_PRINT_L3("Blockchain::" << __func__);
712 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
713 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
714 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
715 // lock if it is otherwise needed.
716 return m_db->top_block_hash();
717 }
718 //------------------------------------------------------------------
719 /*TODO: this function was...poorly written. As such, I'm not entirely
720 * certain on what it was supposed to be doing. Need to look into this,
721 * but it doesn't seem terribly important just yet.
722 *
723 * puts into list <ids> a list of hashes representing certain blocks
724 * from the blockchain in reverse chronological order
725 *
726 * the blocks chosen, at the time of this writing, are:
727 * the most recent 11
728 * powers of 2 less recent from there, so 13, 17, 25, etc...
729 *
730 */
731 bool Blockchain::get_short_chain_history(std::list<crypto::hash>& ids, uint64_t& current_height) const
732 {
733 LOG_PRINT_L3("Blockchain::" << __func__);
734 CRITICAL_REGION_LOCAL(m_blockchain_lock);
735 uint64_t i = 0;
736 uint64_t current_multiplier = 1;
737 uint64_t sz = current_height = m_db->height();
738
739 if(!sz)
740 return true;
741
742 db_rtxn_guard rtxn_guard(m_db);
743 bool genesis_included = false;
744 uint64_t current_back_offset = 1;
745 while(current_back_offset < sz)
746 {
747 ids.push_back(m_db->get_block_hash_from_height(sz - current_back_offset));
748
749 if(sz-current_back_offset == 0)
750 {
751 genesis_included = true;
752 }
753 if(i < 10)
754 {
755 ++current_back_offset;
756 }
757 else
758 {
759 current_multiplier *= 2;
760 current_back_offset += current_multiplier;
761 }
762 ++i;
763 }
764
765 if (!genesis_included)
766 {
767 ids.push_back(m_db->get_block_hash_from_height(0));
768 }
769
770 return true;
771 }
772 //------------------------------------------------------------------
773 crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const
774 {
775 LOG_PRINT_L3("Blockchain::" << __func__);
776 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
777 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
778 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
779 // lock if it is otherwise needed.
780 try
781 {
782 return m_db->get_block_hash_from_height(height);
783 }
784 catch (const BLOCK_DNE& e)
785 {
786 }
787 catch (const std::exception& e)
788 {
789 MERROR(std::string("Something went wrong fetching block hash by height: ") + e.what());
790 throw;
791 }
792 catch (...)
793 {
794 MERROR(std::string("Something went wrong fetching block hash by height"));
795 throw;
796 }
797 return null_hash;
798 }
799 //------------------------------------------------------------------
800 crypto::hash Blockchain::get_pending_block_id_by_height(uint64_t height) const
801 {
802 if (m_prepare_height && height >= m_prepare_height && height - m_prepare_height < m_prepare_nblocks)
803 return (*m_prepare_blocks)[height - m_prepare_height].hash;
804 return get_block_id_by_height(height);
805 }
806 //------------------------------------------------------------------
807 bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const
808 {
809 LOG_PRINT_L3("Blockchain::" << __func__);
810 CRITICAL_REGION_LOCAL(m_blockchain_lock);
811
812 // try to find block in main chain
813 try
814 {
815 blk = m_db->get_block(h);
816 if (orphan)
817 *orphan = false;
818 return true;
819 }
820 // try to find block in alternative chain
821 catch (const BLOCK_DNE& e)
822 {
823 alt_block_data_t data;
824 cryptonote::blobdata blob;
825 if (m_db->get_alt_block(h, &data, &blob))
826 {
827 if (!cryptonote::parse_and_validate_block_from_blob(blob, blk))
828 {
829 MERROR("Found block " << h << " in alt chain, but failed to parse it");
830 throw std::runtime_error("Found block in alt chain, but failed to parse it");
831 }
832 if (orphan)
833 *orphan = true;
834 return true;
835 }
836 }
837 catch (const std::exception& e)
838 {
839 MERROR(std::string("Something went wrong fetching block by hash: ") + e.what());
840 throw;
841 }
842 catch (...)
843 {
844 MERROR(std::string("Something went wrong fetching block hash by hash"));
845 throw;
846 }
847
848 return false;
849 }
850 //------------------------------------------------------------------
851 // This function aggregates the cumulative difficulties and timestamps of the
852 // last DIFFICULTY_BLOCKS_COUNT blocks and passes them to next_difficulty,
853 // returning the result of that call. Ignores the genesis block, and can use
854 // less blocks than desired if there aren't enough.
855 difficulty_type Blockchain::get_difficulty_for_next_block()
856 {
857 if (m_fixed_difficulty)
858 {
859 return m_db->height() ? m_fixed_difficulty : 1;
860 }
861
862 LOG_PRINT_L3("Blockchain::" << __func__);
863
864 crypto::hash top_hash = get_tail_id();
865 {
866 CRITICAL_REGION_LOCAL(m_difficulty_lock);
867 // we can call this without the blockchain lock, it might just give us
868 // something a bit out of date, but that's fine since anything which
869 // requires the blockchain lock will have acquired it in the first place,
870 // and it will be unlocked only when called from the getinfo RPC
871 if (top_hash == m_difficulty_for_next_block_top_hash)
872 return m_difficulty_for_next_block;
873 }
874
875 CRITICAL_REGION_LOCAL(m_blockchain_lock);
876 std::vector<uint64_t> timestamps;
877 std::vector<difficulty_type> difficulties;
878 uint64_t height;
879 top_hash = get_tail_id(height); // get it again now that we have the lock
880 ++height; // top block height to blockchain height
881 // ND: Speedup
882 // 1. Keep a list of the last 735 (or less) blocks that is used to compute difficulty,
883 // then when the next block difficulty is queried, push the latest height data and
884 // pop the oldest one from the list. This only requires 1x read per height instead
885 // of doing 735 (DIFFICULTY_BLOCKS_COUNT).
886 if (m_reset_timestamps_and_difficulties_height)
887 m_timestamps_and_difficulties_height = 0;
888 if (m_timestamps_and_difficulties_height != 0 && ((height - m_timestamps_and_difficulties_height) == 1) && m_timestamps.size() >= DIFFICULTY_BLOCKS_COUNT)
889 {
890 uint64_t index = height - 1;
891 m_timestamps.push_back(m_db->get_block_timestamp(index));
892 m_difficulties.push_back(m_db->get_block_cumulative_difficulty(index));
893
894 while (m_timestamps.size() > DIFFICULTY_BLOCKS_COUNT)
895 m_timestamps.erase(m_timestamps.begin());
896 while (m_difficulties.size() > DIFFICULTY_BLOCKS_COUNT)
897 m_difficulties.erase(m_difficulties.begin());
898
899 m_timestamps_and_difficulties_height = height;
900 timestamps = m_timestamps;
901 difficulties = m_difficulties;
902 }
903 else
904 {
905 uint64_t offset = height - std::min <uint64_t> (height, static_cast<uint64_t>(DIFFICULTY_BLOCKS_COUNT));
906 if (offset == 0)
907 ++offset;
908
909 timestamps.clear();
910 difficulties.clear();
911 if (height > offset)
912 {
913 timestamps.reserve(height - offset);
914 difficulties.reserve(height - offset);
915 }
916 for (; offset < height; offset++)
917 {
918 timestamps.push_back(m_db->get_block_timestamp(offset));
919 difficulties.push_back(m_db->get_block_cumulative_difficulty(offset));
920 }
921
922 m_timestamps_and_difficulties_height = height;
923 m_timestamps = timestamps;
924 m_difficulties = difficulties;
925 }
926 size_t target = get_difficulty_target();
927 difficulty_type diff = next_difficulty(timestamps, difficulties, target);
928
929 CRITICAL_REGION_LOCAL1(m_difficulty_lock);
930 m_difficulty_for_next_block_top_hash = top_hash;
931 m_difficulty_for_next_block = diff;
932 return diff;
933 }
934 //------------------------------------------------------------------
935 std::pair<bool, uint64_t> Blockchain::check_difficulty_checkpoints() const
936 {
937 uint64_t res = 0;
938 for (const std::pair<const uint64_t, difficulty_type>& i : m_checkpoints.get_difficulty_points())
939 {
940 if (i.first >= m_db->height())
941 break;
942 if (m_db->get_block_cumulative_difficulty(i.first) != i.second)
943 return {false, res};
944 res = i.first;
945 }
946 return {true, res};
947 }
948 //------------------------------------------------------------------
949 size_t Blockchain::recalculate_difficulties(boost::optional<uint64_t> start_height_opt)
950 {
951 if (m_fixed_difficulty)
952 {
953 return 0;
954 }
955 LOG_PRINT_L3("Blockchain::" << __func__);
956 CRITICAL_REGION_LOCAL(m_blockchain_lock);
957
958 const uint64_t start_height = start_height_opt ? *start_height_opt : check_difficulty_checkpoints().second;
959 const uint64_t top_height = m_db->height() - 1;
960 MGINFO("Recalculating difficulties from height " << start_height << " to height " << top_height);
961
962 std::vector<uint64_t> timestamps;
963 std::vector<difficulty_type> difficulties;
964 timestamps.reserve(DIFFICULTY_BLOCKS_COUNT + 1);
965 difficulties.reserve(DIFFICULTY_BLOCKS_COUNT + 1);
966 if (start_height > 1)
967 {
968 for (uint64_t i = 0; i < DIFFICULTY_BLOCKS_COUNT; ++i)
969 {
970 uint64_t height = start_height - 1 - i;
971 if (height == 0)
972 break;
973 timestamps.insert(timestamps.begin(), m_db->get_block_timestamp(height));
974 difficulties.insert(difficulties.begin(), m_db->get_block_cumulative_difficulty(height));
975 }
976 }
977 difficulty_type last_cum_diff = start_height <= 1 ? start_height : difficulties.back();
978 uint64_t drift_start_height = 0;
979 std::vector<difficulty_type> new_cumulative_difficulties;
980 for (uint64_t height = start_height; height <= top_height; ++height)
981 {
982 size_t target = get_ideal_hard_fork_version(height) < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2;
983 difficulty_type recalculated_diff = next_difficulty(timestamps, difficulties, target);
984
985 boost::multiprecision::uint256_t recalculated_cum_diff_256 = boost::multiprecision::uint256_t(recalculated_diff) + last_cum_diff;
986 CHECK_AND_ASSERT_THROW_MES(recalculated_cum_diff_256 <= std::numeric_limits<difficulty_type>::max(), "Difficulty overflow!");
987 difficulty_type recalculated_cum_diff = recalculated_cum_diff_256.convert_to<difficulty_type>();
988
989 if (drift_start_height == 0)
990 {
991 difficulty_type existing_cum_diff = m_db->get_block_cumulative_difficulty(height);
992 if (recalculated_cum_diff != existing_cum_diff)
993 {
994 drift_start_height = height;
995 new_cumulative_difficulties.reserve(top_height + 1 - height);
996 LOG_ERROR("Difficulty drift found at height:" << height << ", hash:" << m_db->get_block_hash_from_height(height) << ", existing:" << existing_cum_diff << ", recalculated:" << recalculated_cum_diff);
997 }
998 }
999 if (drift_start_height > 0)
1000 {
1001 new_cumulative_difficulties.push_back(recalculated_cum_diff);
1002 if (height % 100000 == 0)
1003 LOG_ERROR(boost::format("%llu / %llu (%.1f%%)") % height % top_height % (100 * (height - drift_start_height) / float(top_height - drift_start_height)));
1004 }
1005
1006 if (height > 0)
1007 {
1008 timestamps.push_back(m_db->get_block_timestamp(height));
1009 difficulties.push_back(recalculated_cum_diff);
1010 }
1011 if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT)
1012 {
1013 CHECK_AND_ASSERT_THROW_MES(timestamps.size() == DIFFICULTY_BLOCKS_COUNT + 1, "Wrong timestamps size: " << timestamps.size());
1014 timestamps.erase(timestamps.begin());
1015 difficulties.erase(difficulties.begin());
1016 }
1017 last_cum_diff = recalculated_cum_diff;
1018 }
1019
1020 if (drift_start_height > 0)
1021 {
1022 LOG_ERROR("Writing to the DB...");
1023 try
1024 {
1025 m_db->correct_block_cumulative_difficulties(drift_start_height, new_cumulative_difficulties);
1026 }
1027 catch (const std::exception& e)
1028 {
1029 LOG_ERROR("Error correcting cumulative difficulties from height " << drift_start_height << ", what = " << e.what());
1030 }
1031 LOG_ERROR("Corrected difficulties for " << new_cumulative_difficulties.size() << " blocks");
1032 // clear cache
1033 m_difficulty_for_next_block_top_hash = crypto::null_hash;
1034 m_timestamps_and_difficulties_height = 0;
1035 }
1036
1037 return new_cumulative_difficulties.size();
1038 }
1039 //------------------------------------------------------------------
1040 std::vector<time_t> Blockchain::get_last_block_timestamps(unsigned int blocks) const
1041 {
1042 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1043 uint64_t height = m_db->height();
1044 if (blocks > height)
1045 blocks = height;
1046 std::vector<time_t> timestamps(blocks);
1047 while (blocks--)
1048 timestamps[blocks] = m_db->get_block_timestamp(height - blocks - 1);
1049 return timestamps;
1050 }
1051 //------------------------------------------------------------------
1052 // This function removes blocks from the blockchain until it gets to the
1053 // position where the blockchain switch started and then re-adds the blocks
1054 // that had been removed.
1055 bool Blockchain::rollback_blockchain_switching(std::list<block>& original_chain, uint64_t rollback_height)
1056 {
1057 LOG_PRINT_L3("Blockchain::" << __func__);
1058 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1059
1060 // fail if rollback_height passed is too high
1061 if (rollback_height > m_db->height())
1062 {
1063 return true;
1064 }
1065
1066 m_timestamps_and_difficulties_height = 0;
1067 m_reset_timestamps_and_difficulties_height = true;
1068
1069 // remove blocks from blockchain until we get back to where we should be.
1070 while (m_db->height() != rollback_height)
1071 {
1072 pop_block_from_blockchain();
1073 }
1074 CHECK_AND_ASSERT_THROW_MES(update_next_cumulative_weight_limit(), "Error updating next cumulative weight limit");
1075
1076 // make sure the hard fork object updates its current version
1077 m_hardfork->reorganize_from_chain_height(rollback_height);
1078
1079 //return back original chain
1080 for (auto& bl : original_chain)
1081 {
1082 block_verification_context bvc = {};
1083 bool r = handle_block_to_main_chain(bl, bvc);
1084 CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC! failed to add (again) block while chain switching during the rollback!");
1085 }
1086
1087 m_hardfork->reorganize_from_chain_height(rollback_height);
1088
1089 MINFO("Rollback to height " << rollback_height << " was successful.");
1090 if (!original_chain.empty())
1091 {
1092 MINFO("Restoration to previous blockchain successful as well.");
1093 }
1094 return true;
1095 }
1096 //------------------------------------------------------------------
1097 // This function attempts to switch to an alternate chain, returning
1098 // boolean based on success therein.
1099 bool Blockchain::switch_to_alternative_blockchain(std::list<block_extended_info>& alt_chain, bool discard_disconnected_chain)
1100 {
1101 LOG_PRINT_L3("Blockchain::" << __func__);
1102 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1103
1104 m_timestamps_and_difficulties_height = 0;
1105 m_reset_timestamps_and_difficulties_height = true;
1106
1107 // if empty alt chain passed (not sure how that could happen), return false
1108 CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed");
1109
1110 // verify that main chain has front of alt chain's parent block
1111 if (!m_db->block_exists(alt_chain.front().bl.prev_id))
1112 {
1113 LOG_ERROR("Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!");
1114 return false;
1115 }
1116
1117 // pop blocks from the blockchain until the top block is the parent
1118 // of the front block of the alt chain.
1119 std::list<block> disconnected_chain;
1120 while (m_db->top_block_hash() != alt_chain.front().bl.prev_id)
1121 {
1122 block b = pop_block_from_blockchain();
1123 disconnected_chain.push_front(b);
1124 }
1125 CHECK_AND_ASSERT_THROW_MES(update_next_cumulative_weight_limit(), "Error updating next cumulative weight limit");
1126
1127 auto split_height = m_db->height();
1128
1129 //connecting new alternative chain
1130 for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++)
1131 {
1132 const auto &bei = *alt_ch_iter;
1133 block_verification_context bvc = {};
1134
1135 // add block to main chain
1136 bool r = handle_block_to_main_chain(bei.bl, bvc);
1137
1138 // if adding block to main chain failed, rollback to previous state and
1139 // return false
1140 if(!r || !bvc.m_added_to_main_chain)
1141 {
1142 MERROR("Failed to switch to alternative blockchain");
1143
1144 // rollback_blockchain_switching should be moved to two different
1145 // functions: rollback and apply_chain, but for now we pretend it is
1146 // just the latter (because the rollback was done above).
1147 rollback_blockchain_switching(disconnected_chain, split_height);
1148
1149 const crypto::hash blkid = cryptonote::get_block_hash(bei.bl);
1150 m_db->remove_alt_block(blkid);
1151 alt_ch_iter++;
1152
1153 for(auto alt_ch_to_orph_iter = alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); )
1154 {
1155 const auto &bei = *alt_ch_to_orph_iter++;
1156 const crypto::hash blkid = cryptonote::get_block_hash(bei.bl);
1157 m_db->remove_alt_block(blkid);
1158 }
1159 return false;
1160 }
1161 }
1162
1163 // if we're to keep the disconnected blocks, add them as alternates
1164 const size_t discarded_blocks = disconnected_chain.size();
1165 if(!discard_disconnected_chain)
1166 {
1167 //pushing old chain as alternative chain
1168 for (auto& old_ch_ent : disconnected_chain)
1169 {
1170 block_verification_context bvc = {};
1171 pool_supplement ps{};
1172 bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc, ps);
1173 if(!r)
1174 {
1175 MERROR("Failed to push ex-main chain blocks to alternative chain ");
1176 // previously this would fail the blockchain switching, but I don't
1177 // think this is bad enough to warrant that.
1178 }
1179 }
1180 }
1181
1182 //removing alt_chain entries from alternative chains container
1183 for (const auto &bei: alt_chain)
1184 {
1185 m_db->remove_alt_block(cryptonote::get_block_hash(bei.bl));
1186 }
1187
1188 m_hardfork->reorganize_from_chain_height(split_height);
1189
1190 std::shared_ptr<tools::Notify> reorg_notify = m_reorg_notify;
1191 if (reorg_notify)
1192 reorg_notify->notify("%s", std::to_string(split_height).c_str(), "%h", std::to_string(m_db->height()).c_str(),
1193 "%n", std::to_string(m_db->height() - split_height).c_str(), "%d", std::to_string(discarded_blocks).c_str(), NULL);
1194
1195 const uint64_t new_height = m_db->height();
1196 const crypto::hash seedhash = get_block_id_by_height(crypto::rx_seedheight(new_height));
1197
1198 crypto::hash prev_id;
1199 if (!get_block_hash(alt_chain.back().bl, prev_id))
1200 MERROR("Failed to get block hash of an alternative chain's tip");
1201 else
1202 send_miner_notifications(new_height, seedhash, prev_id, alt_chain.back().already_generated_coins);
1203
1204 for (const auto& notifier : m_block_notifiers)
1205 {
1206 std::size_t notify_height = split_height;
1207 for (const auto& bei: alt_chain)
1208 {
1209 notifier(notify_height, {std::addressof(bei.bl), 1});
1210 ++notify_height;
1211 }
1212 }
1213
1214 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
1215 rx_set_main_seedhash(seedhash.data, tools::get_max_concurrency());
1216
1217 MGINFO_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_db->height());
1218 return true;
1219 }
1220 //------------------------------------------------------------------
1221 // This function calculates the difficulty target for the block being added to
1222 // an alternate chain.
1223 difficulty_type Blockchain::get_next_difficulty_for_alternative_chain(const std::list<block_extended_info>& alt_chain, block_extended_info& bei) const
1224 {
1225 if (m_fixed_difficulty)
1226 {
1227 return m_db->height() ? m_fixed_difficulty : 1;
1228 }
1229
1230 LOG_PRINT_L3("Blockchain::" << __func__);
1231 std::vector<uint64_t> timestamps;
1232 std::vector<difficulty_type> cumulative_difficulties;
1233
1234 // if the alt chain isn't long enough to calculate the difficulty target
1235 // based on its blocks alone, need to get more blocks from the main chain
1236 if(alt_chain.size()< DIFFICULTY_BLOCKS_COUNT)
1237 {
1238 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1239
1240 // Figure out start and stop offsets for main chain blocks
1241 size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front().height : bei.height;
1242 size_t main_chain_count = DIFFICULTY_BLOCKS_COUNT - std::min(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT), alt_chain.size());
1243 main_chain_count = std::min(main_chain_count, main_chain_stop_offset);
1244 size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count;
1245
1246 if(!main_chain_start_offset)
1247 ++main_chain_start_offset; //skip genesis block
1248
1249 // get difficulties and timestamps from relevant main chain blocks
1250 for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset)
1251 {
1252 timestamps.push_back(m_db->get_block_timestamp(main_chain_start_offset));
1253 cumulative_difficulties.push_back(m_db->get_block_cumulative_difficulty(main_chain_start_offset));
1254 }
1255
1256 // make sure we haven't accidentally grabbed too many blocks...maybe don't need this check?
1257 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);
1258
1259 for (const auto &bei : alt_chain)
1260 {
1261 timestamps.push_back(bei.bl.timestamp);
1262 cumulative_difficulties.push_back(bei.cumulative_difficulty);
1263 }
1264 }
1265 // if the alt chain is long enough for the difficulty calc, grab difficulties
1266 // and timestamps from it alone
1267 else
1268 {
1269 timestamps.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
1270 cumulative_difficulties.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
1271 size_t count = 0;
1272 size_t max_i = timestamps.size()-1;
1273 // get difficulties and timestamps from most recent blocks in alt chain
1274 for (const auto &bei: boost::adaptors::reverse(alt_chain))
1275 {
1276 timestamps[max_i - count] = bei.bl.timestamp;
1277 cumulative_difficulties[max_i - count] = bei.cumulative_difficulty;
1278 count++;
1279 if(count >= DIFFICULTY_BLOCKS_COUNT)
1280 break;
1281 }
1282 }
1283
1284 // FIXME: This will fail if fork activation heights are subject to voting
1285 size_t target = get_ideal_hard_fork_version(bei.height) < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2;
1286
1287 // calculate the difficulty target for the block and return it
1288 return next_difficulty(timestamps, cumulative_difficulties, target);
1289 }
1290 //------------------------------------------------------------------
1291 // This function does a sanity check on basic things that all miner
1292 // transactions have in common, such as:
1293 // one input, of type txin_gen, with height set to the block's height
1294 // correct miner tx unlock time
1295 // a non-overflowing tx amount (dubious necessity on this check)
1296 // valid output types
1297 bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, uint8_t hf_version)
1298 {
1299 LOG_PRINT_L3("Blockchain::" << __func__);
1300 CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs");
1301 CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type");
1302 CHECK_AND_ASSERT_MES(b.miner_tx.version > 1 || hf_version < HF_VERSION_MIN_V2_COINBASE_TX, false, "Invalid coinbase transaction version");
1303
1304 // for v2 txes (ringct), we only accept empty rct signatures for miner transactions,
1305 if (hf_version >= HF_VERSION_REJECT_SIGS_IN_COINBASE && b.miner_tx.version >= 2)
1306 {
1307 CHECK_AND_ASSERT_MES(b.miner_tx.rct_signatures.type == rct::RCTTypeNull, false, "RingCT signatures not allowed in coinbase transactions");
1308 }
1309
1310 if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height)
1311 {
1312 MWARNING("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height);
1313 return false;
1314 }
1315 MDEBUG("Miner tx hash: " << get_transaction_hash(b.miner_tx));
1316 CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction has the wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);
1317
1318 //check outs overflow
1319 if(!check_outs_overflow(b.miner_tx))
1320 {
1321 MERROR("miner transaction has money overflow in block " << get_block_hash(b));
1322 return false;
1323 }
1324
1325 CHECK_AND_ASSERT_MES(check_output_types(b.miner_tx, hf_version), false, "miner transaction has invalid output type(s) in block " << get_block_hash(b));
1326
1327 return true;
1328 }
1329 //------------------------------------------------------------------
1330 // This function validates the miner transaction reward
1331 bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_weight, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, bool &partial_block_reward, uint8_t version)
1332 {
1333 LOG_PRINT_L3("Blockchain::" << __func__);
1334 //validate reward
1335 uint64_t money_in_use = 0;
1336 for (auto& o: b.miner_tx.vout)
1337 money_in_use += o.amount;
1338 partial_block_reward = false;
1339
1340 if (version == 3) {
1341 for (auto &o: b.miner_tx.vout) {
1342 if (!is_valid_decomposed_amount(o.amount)) {
1343 MERROR_VER("miner tx output " << print_money(o.amount) << " is not a valid decomposed amount");
1344 return false;
1345 }
1346 }
1347 }
1348
1349 uint64_t median_weight;
1350 if (version >= HF_VERSION_EFFECTIVE_SHORT_TERM_MEDIAN_IN_PENALTY)
1351 {
1352 median_weight = m_current_block_cumul_weight_median;
1353 }
1354 else
1355 {
1356 std::vector<uint64_t> last_blocks_weights;
1357 get_last_n_blocks_weights(last_blocks_weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
1358 median_weight = epee::misc_utils::median(last_blocks_weights);
1359 }
1360 if (!get_block_reward(median_weight, cumulative_block_weight, already_generated_coins, base_reward, version))
1361 {
1362 MERROR_VER("block weight " << cumulative_block_weight << " is bigger than allowed for this blockchain");
1363 return false;
1364 }
1365 if(base_reward + fee < money_in_use)
1366 {
1367 MERROR_VER("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) << "), cumulative_block_weight " << cumulative_block_weight);
1368 return false;
1369 }
1370 // From hard fork 2 till 12, we allow a miner to claim less block reward than is allowed, in case a miner wants less dust
1371 if (version < 2 || version >= HF_VERSION_EXACT_COINBASE)
1372 {
1373 if(base_reward + fee != money_in_use)
1374 {
1375 MDEBUG("coinbase transaction doesn't use full amount of block reward: spent: " << money_in_use << ", block reward " << base_reward + fee << "(" << base_reward << "+" << fee << ")");
1376 return false;
1377 }
1378 }
1379 else
1380 {
1381 // from hard fork 2, since a miner can claim less than the full block reward, we update the base_reward
1382 // to show the amount of coins that were actually generated, the remainder will be pushed back for later
1383 // emission. This modifies the emission curve very slightly.
1384 CHECK_AND_ASSERT_MES(money_in_use - fee <= base_reward, false, "base reward calculation bug");
1385 if(base_reward + fee != money_in_use)
1386 partial_block_reward = true;
1387 base_reward = money_in_use - fee;
1388 }
1389 return true;
1390 }
1391 //------------------------------------------------------------------
1392 // get the block weights of the last <count> blocks, and return by reference <sz>.
1393 void Blockchain::get_last_n_blocks_weights(std::vector<uint64_t>& weights, size_t count) const
1394 {
1395 LOG_PRINT_L3("Blockchain::" << __func__);
1396 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1397 auto h = m_db->height();
1398
1399 // this function is meaningless for an empty blockchain...granted it should never be empty
1400 if(h == 0)
1401 return;
1402
1403 // add weight of last <count> blocks to vector <weights> (or less, if blockchain size < count)
1404 size_t start_offset = h - std::min<size_t>(h, count);
1405 weights = m_db->get_block_weights(start_offset, count);
1406 }
1407 //------------------------------------------------------------------
1408 uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, size_t count) const
1409 {
1410 LOG_PRINT_L3("Blockchain::" << __func__);
1411 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1412
1413 PERF_TIMER(get_long_term_block_weights);
1414
1415 CHECK_AND_ASSERT_THROW_MES(count > 0, "count == 0");
1416
1417 bool cached = false;
1418 uint64_t blockchain_height = m_db->height();
1419 uint64_t tip_height = start_height + count - 1;
1420 crypto::hash tip_hash = crypto::null_hash;
1421 if (tip_height < blockchain_height && count == (size_t)m_long_term_block_weights_cache_rolling_median.size())
1422 {
1423 tip_hash = m_db->get_block_hash_from_height(tip_height);
1424 cached = tip_hash == m_long_term_block_weights_cache_tip_hash;
1425 }
1426
1427 if (cached)
1428 {
1429 MTRACE("requesting " << count << " from " << start_height << ", cached");
1430 return m_long_term_block_weights_cache_rolling_median.median();
1431 }
1432
1433 // in the vast majority of uncached cases, most is still cached,
1434 // as we just move the window one block up:
1435 if (tip_height > 0 && count == (size_t)m_long_term_block_weights_cache_rolling_median.size() && tip_height < blockchain_height)
1436 {
1437 crypto::hash old_tip_hash = m_db->get_block_hash_from_height(tip_height - 1);
1438 if (old_tip_hash == m_long_term_block_weights_cache_tip_hash)
1439 {
1440 MTRACE("requesting " << count << " from " << start_height << ", incremental");
1441 m_long_term_block_weights_cache_tip_hash = tip_hash;
1442 m_long_term_block_weights_cache_rolling_median.insert(m_db->get_block_long_term_weight(tip_height));
1443 return m_long_term_block_weights_cache_rolling_median.median();
1444 }
1445 }
1446
1447 MTRACE("requesting " << count << " from " << start_height << ", uncached");
1448 std::vector<uint64_t> weights = m_db->get_long_term_block_weights(start_height, count);
1449 m_long_term_block_weights_cache_tip_hash = tip_hash;
1450 m_long_term_block_weights_cache_rolling_median.clear();
1451 for (uint64_t w: weights)
1452 m_long_term_block_weights_cache_rolling_median.insert(w);
1453 return m_long_term_block_weights_cache_rolling_median.median();
1454 }
1455 //------------------------------------------------------------------
1456 uint64_t Blockchain::get_current_cumulative_block_weight_limit() const
1457 {
1458 LOG_PRINT_L3("Blockchain::" << __func__);
1459 return m_current_block_cumul_weight_limit;
1460 }
1461 //------------------------------------------------------------------
1462 uint64_t Blockchain::get_current_cumulative_block_weight_median() const
1463 {
1464 LOG_PRINT_L3("Blockchain::" << __func__);
1465 return m_current_block_cumul_weight_median;
1466 }
1467 //------------------------------------------------------------------
1468 //TODO: This function only needed minor modification to work with BlockchainDB,
1469 // and *works*. As such, to reduce the number of things that might break
1470 // in moving to BlockchainDB, this function will remain otherwise
1471 // unchanged for the time being.
1472 //
1473 // This function makes a new block for a miner to mine the hash for
1474 //
1475 // FIXME: this codebase references #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1476 // in a lot of places. That flag is not referenced in any of the code
1477 // nor any of the makefiles, howeve. Need to look into whether or not it's
1478 // necessary at all.
1479 bool Blockchain::create_block_template(block& b, const crypto::hash *from_block, const account_public_address& miner_address, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash)
1480 {
1481 LOG_PRINT_L3("Blockchain::" << __func__);
1482 size_t median_weight;
1483 uint64_t already_generated_coins;
1484 uint64_t pool_cookie;
1485
1486 seed_hash = crypto::null_hash;
1487
1488 m_tx_pool.lock();
1489 const auto unlock_guard = epee::misc_utils::create_scope_leave_handler([&]() { m_tx_pool.unlock(); });
1490 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1491 if (m_btc_valid && !from_block) {
1492 // The pool cookie is atomic. The lack of locking is OK, as if it changes
1493 // just as we compare it, we'll just use a slightly old template, but
1494 // this would be the case anyway if we'd lock, and the change happened
1495 // just after the block template was created
1496 if (!memcmp(&miner_address, &m_btc_address, sizeof(cryptonote::account_public_address)) && m_btc_nonce == ex_nonce
1497 && m_btc_pool_cookie == m_tx_pool.cookie() && m_btc.prev_id == get_tail_id()) {
1498 MDEBUG("Using cached template");
1499 const uint64_t now = time(NULL);
1500 if (m_btc.timestamp < now) // ensures it can't get below the median of the last few blocks
1501 m_btc.timestamp = now;
1502 b = m_btc;
1503 diffic = m_btc_difficulty;
1504 height = m_btc_height;
1505 expected_reward = m_btc_expected_reward;
1506 seed_height = m_btc_seed_height;
1507 seed_hash = m_btc_seed_hash;
1508 return true;
1509 }
1510 MDEBUG("Not using cached template: address " << (!memcmp(&miner_address, &m_btc_address, sizeof(cryptonote::account_public_address))) << ", nonce " << (m_btc_nonce == ex_nonce) << ", cookie " << (m_btc_pool_cookie == m_tx_pool.cookie()) << ", from_block " << (!!from_block));
1511 invalidate_block_template_cache();
1512 }
1513
1514 if (from_block)
1515 {
1516 //build alternative subchain, front -> mainchain, back -> alternative head
1517 //block is not related with head of main chain
1518 //first of all - look in alternative chains container
1519 alt_block_data_t prev_data;
1520 bool parent_in_alt = m_db->get_alt_block(*from_block, &prev_data, NULL);
1521 bool parent_in_main = m_db->block_exists(*from_block);
1522 if (!parent_in_alt && !parent_in_main)
1523 {
1524 MERROR("Unknown from block");
1525 return false;
1526 }
1527
1528 //we have new block in alternative chain
1529 std::list<block_extended_info> alt_chain;
1530 block_verification_context bvc = {};
1531 std::vector<uint64_t> timestamps;
1532 if (!build_alt_chain(*from_block, alt_chain, timestamps, bvc))
1533 return false;
1534
1535 if (parent_in_main)
1536 {
1537 cryptonote::block prev_block;
1538 CHECK_AND_ASSERT_MES(get_block_by_hash(*from_block, prev_block), false, "From block not found"); // TODO
1539 uint64_t from_block_height = cryptonote::get_block_height(prev_block);
1540 height = from_block_height + 1;
1541 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
1542 {
1543 uint64_t next_height;
1544 crypto::rx_seedheights(height, &seed_height, &next_height);
1545 seed_hash = get_block_id_by_height(seed_height);
1546 }
1547 }
1548 else
1549 {
1550 height = alt_chain.back().height + 1;
1551 uint64_t next_height;
1552 crypto::rx_seedheights(height, &seed_height, &next_height);
1553
1554 if (alt_chain.size() && alt_chain.front().height <= seed_height)
1555 {
1556 for (auto it=alt_chain.begin(); it != alt_chain.end(); it++)
1557 {
1558 if (it->height == seed_height+1)
1559 {
1560 seed_hash = it->bl.prev_id;
1561 break;
1562 }
1563 }
1564 }
1565 else
1566 {
1567 seed_hash = get_block_id_by_height(seed_height);
1568 }
1569 }
1570 b.major_version = m_hardfork->get_ideal_version(height);
1571 b.minor_version = m_hardfork->get_ideal_version();
1572 b.prev_id = *from_block;
1573
1574 // cheat and use the weight of the block we start from, virtually certain to be acceptable
1575 // and use 1.9 times rather than 2 times so we're even more sure
1576 if (parent_in_main)
1577 {
1578 median_weight = m_db->get_block_weight(height - 1);
1579 already_generated_coins = m_db->get_block_already_generated_coins(height - 1);
1580 }
1581 else
1582 {
1583 median_weight = prev_data.cumulative_weight - prev_data.cumulative_weight / 20;
1584 already_generated_coins = alt_chain.back().already_generated_coins;
1585 }
1586
1587 // FIXME: consider moving away from block_extended_info at some point
1588 block_extended_info bei = {};
1589 bei.bl = b;
1590 bei.height = alt_chain.size() ? prev_data.height + 1 : m_db->get_block_height(*from_block) + 1;
1591
1592 diffic = get_next_difficulty_for_alternative_chain(alt_chain, bei);
1593 }
1594 else
1595 {
1596 height = m_db->height();
1597 b.major_version = m_hardfork->get_current_version();
1598 b.minor_version = m_hardfork->get_ideal_version();
1599 b.prev_id = get_tail_id();
1600 median_weight = m_current_block_cumul_weight_limit / 2;
1601 diffic = get_difficulty_for_next_block();
1602 already_generated_coins = m_db->get_block_already_generated_coins(height - 1);
1603 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
1604 {
1605 uint64_t next_height;
1606 crypto::rx_seedheights(height, &seed_height, &next_height);
1607 seed_hash = get_block_id_by_height(seed_height);
1608 }
1609 }
1610 b.timestamp = time(NULL);
1611
1612 uint64_t median_ts;
1613 if (!check_block_timestamp(b, median_ts))
1614 {
1615 b.timestamp = median_ts;
1616 }
1617
1618 CHECK_AND_ASSERT_MES(diffic, false, "difficulty overhead.");
1619
1620 size_t txs_weight;
1621 uint64_t fee;
1622 if (!m_tx_pool.fill_block_template(b, median_weight, already_generated_coins, txs_weight, fee, expected_reward, b.major_version))
1623 {
1624 return false;
1625 }
1626 pool_cookie = m_tx_pool.cookie();
1627 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1628 size_t real_txs_weight = 0;
1629 uint64_t real_fee = 0;
1630 for(crypto::hash &cur_hash: b.tx_hashes)
1631 {
1632 auto cur_res = m_tx_pool.m_transactions.find(cur_hash);
1633 if (cur_res == m_tx_pool.m_transactions.end())
1634 {
1635 LOG_ERROR("Creating block template: error: transaction not found");
1636 continue;
1637 }
1638 tx_memory_pool::tx_details &cur_tx = cur_res->second;
1639 real_txs_weight += cur_tx.weight;
1640 real_fee += cur_tx.fee;
1641 if (cur_tx.weight != get_transaction_weight(cur_tx.tx))
1642 {
1643 LOG_ERROR("Creating block template: error: invalid transaction weight");
1644 }
1645 if (cur_tx.tx.version == 1)
1646 {
1647 uint64_t inputs_amount;
1648 if (!get_inputs_money_amount(cur_tx.tx, inputs_amount))
1649 {
1650 LOG_ERROR("Creating block template: error: cannot get inputs amount");
1651 }
1652 else if (cur_tx.fee != inputs_amount - get_outs_money_amount(cur_tx.tx))
1653 {
1654 LOG_ERROR("Creating block template: error: invalid fee");
1655 }
1656 }
1657 else
1658 {
1659 if (cur_tx.fee != cur_tx.tx.rct_signatures.txnFee)
1660 {
1661 LOG_ERROR("Creating block template: error: invalid fee");
1662 }
1663 }
1664 }
1665 if (txs_weight != real_txs_weight)
1666 {
1667 LOG_ERROR("Creating block template: error: wrongly calculated transaction weight");
1668 }
1669 if (fee != real_fee)
1670 {
1671 LOG_ERROR("Creating block template: error: wrongly calculated fee");
1672 }
1673 MDEBUG("Creating block template: height " << height <<
1674 ", median weight " << median_weight <<
1675 ", already generated coins " << already_generated_coins <<
1676 ", transaction weight " << txs_weight <<
1677 ", fee " << fee);
1678 #endif
1679
1680 /*
1681 two-phase miner transaction generation: we don't know exact block weight until we prepare block, but we don't know reward until we know
1682 block weight, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block weight
1683 */
1684 //make blocks coin-base tx looks close to real coinbase tx to get truthful blob weight
1685 uint8_t hf_version = b.major_version;
1686 size_t max_outs = hf_version >= 4 ? 1 : 11;
1687 bool r = construct_miner_tx(height, median_weight, already_generated_coins, txs_weight, fee, miner_address, b.miner_tx, ex_nonce, max_outs, hf_version);
1688 CHECK_AND_ASSERT_MES(r, false, "Failed to construct miner tx, first chance");
1689 size_t cumulative_weight = txs_weight + get_transaction_weight(b.miner_tx);
1690 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1691 MDEBUG("Creating block template: miner tx weight " << get_transaction_weight(b.miner_tx) <<
1692 ", cumulative weight " << cumulative_weight);
1693 #endif
1694 for (size_t try_count = 0; try_count != 10; ++try_count)
1695 {
1696 r = construct_miner_tx(height, median_weight, already_generated_coins, cumulative_weight, fee, miner_address, b.miner_tx, ex_nonce, max_outs, hf_version);
1697
1698 CHECK_AND_ASSERT_MES(r, false, "Failed to construct miner tx, second chance");
1699 size_t coinbase_weight = get_transaction_weight(b.miner_tx);
1700 if (coinbase_weight > cumulative_weight - txs_weight)
1701 {
1702 cumulative_weight = txs_weight + coinbase_weight;
1703 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1704 MDEBUG("Creating block template: miner tx weight " << coinbase_weight <<
1705 ", cumulative weight " << cumulative_weight << " is greater than before");
1706 #endif
1707 continue;
1708 }
1709
1710 if (coinbase_weight < cumulative_weight - txs_weight)
1711 {
1712 size_t delta = cumulative_weight - txs_weight - coinbase_weight;
1713 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1714 MDEBUG("Creating block template: miner tx weight " << coinbase_weight <<
1715 ", cumulative weight " << txs_weight + coinbase_weight <<
1716 " is less than before, adding " << delta << " zero bytes");
1717 #endif
1718 b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0);
1719 //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.
1720 if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx))
1721 {
1722 CHECK_AND_ASSERT_MES(cumulative_weight + 1 == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " + 1 is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx));
1723 b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1);
1724 if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx))
1725 {
1726 //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_weight
1727 MDEBUG("Miner tx creation has no luck with delta_extra size = " << delta << " and " << delta - 1);
1728 cumulative_weight += delta - 1;
1729 continue;
1730 }
1731 MDEBUG("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count);
1732 }
1733 }
1734 CHECK_AND_ASSERT_MES(cumulative_weight == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx));
1735 #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
1736 MDEBUG("Creating block template: miner tx weight " << coinbase_weight <<
1737 ", cumulative weight " << cumulative_weight << " is now good");
1738 #endif
1739
1740 if (!from_block)
1741 cache_block_template(b, miner_address, ex_nonce, diffic, height, expected_reward, seed_height, seed_hash, pool_cookie);
1742 return true;
1743 }
1744 LOG_ERROR("Failed to create_block_template with " << 10 << " tries");
1745 return false;
1746 }
1747 //------------------------------------------------------------------
1748 bool Blockchain::create_block_template(block& b, const account_public_address& miner_address, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash)
1749 {
1750 return create_block_template(b, NULL, miner_address, diffic, height, expected_reward, ex_nonce, seed_height, seed_hash);
1751 }
1752 //------------------------------------------------------------------
1753 bool Blockchain::get_miner_data(uint8_t& major_version, uint64_t& height, crypto::hash& prev_id, crypto::hash& seed_hash, difficulty_type& difficulty, uint64_t& median_weight, uint64_t& already_generated_coins, std::vector<tx_block_template_backlog_entry>& tx_backlog)
1754 {
1755 prev_id = m_db->top_block_hash(&height);
1756 ++height;
1757
1758 major_version = m_hardfork->get_ideal_version(height);
1759
1760 seed_hash = crypto::null_hash;
1761 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
1762 {
1763 uint64_t seed_height, next_height;
1764 crypto::rx_seedheights(height, &seed_height, &next_height);
1765 seed_hash = get_block_id_by_height(seed_height);
1766 }
1767
1768 difficulty = get_difficulty_for_next_block();
1769 median_weight = m_current_block_cumul_weight_median;
1770 already_generated_coins = m_db->get_block_already_generated_coins(height - 1);
1771
1772 m_tx_pool.get_block_template_backlog(tx_backlog);
1773
1774 return true;
1775 }
1776 //------------------------------------------------------------------
1777 // for an alternate chain, get the timestamps from the main chain to complete
1778 // the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW.
1779 bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps) const
1780 {
1781 LOG_PRINT_L3("Blockchain::" << __func__);
1782
1783 if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
1784 return true;
1785
1786 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1787 size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size();
1788 CHECK_AND_ASSERT_MES(start_top_height < m_db->height(), false, "internal error: passed start_height not < " << " m_db->height() -- " << start_top_height << " >= " << m_db->height());
1789 size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements : 0;
1790 timestamps.reserve(timestamps.size() + start_top_height - stop_offset);
1791 while (start_top_height != stop_offset)
1792 {
1793 timestamps.push_back(m_db->get_block_timestamp(start_top_height));
1794 --start_top_height;
1795 }
1796 return true;
1797 }
1798 //------------------------------------------------------------------
1799 bool Blockchain::build_alt_chain(const crypto::hash &prev_id, std::list<block_extended_info>& alt_chain, std::vector<uint64_t> &timestamps, block_verification_context& bvc) const
1800 {
1801 //build alternative subchain, front -> mainchain, back -> alternative head
1802 cryptonote::alt_block_data_t data;
1803 cryptonote::blobdata blob;
1804 bool found = m_db->get_alt_block(prev_id, &data, &blob);
1805 timestamps.clear();
1806 while(found)
1807 {
1808 block_extended_info bei;
1809 CHECK_AND_ASSERT_MES(cryptonote::parse_and_validate_block_from_blob(blob, bei.bl), false, "Failed to parse alt block");
1810 bei.height = data.height;
1811 bei.block_cumulative_weight = data.cumulative_weight;
1812 bei.cumulative_difficulty = data.cumulative_difficulty_high;
1813 bei.cumulative_difficulty = (bei.cumulative_difficulty << 64) + data.cumulative_difficulty_low;
1814 bei.already_generated_coins = data.already_generated_coins;
1815 timestamps.push_back(bei.bl.timestamp);
1816 alt_chain.push_front(std::move(bei));
1817 found = m_db->get_alt_block(bei.bl.prev_id, &data, &blob);
1818 }
1819
1820 // if block to be added connects to known blocks that aren't part of the
1821 // main chain -- that is, if we're adding on to an alternate chain
1822 if(!alt_chain.empty())
1823 {
1824 // make sure alt chain doesn't somehow start past the end of the main chain
1825 CHECK_AND_ASSERT_MES(m_db->height() > alt_chain.front().height, false, "main blockchain wrong height");
1826
1827 // make sure that the blockchain contains the block that should connect
1828 // this alternate chain with it.
1829 if (!m_db->block_exists(alt_chain.front().bl.prev_id))
1830 {
1831 MERROR("alternate chain does not appear to connect to main chain...");
1832 return false;
1833 }
1834
1835 // make sure block connects correctly to the main chain
1836 auto h = m_db->get_block_hash_from_height(alt_chain.front().height - 1);
1837 CHECK_AND_ASSERT_MES(h == alt_chain.front().bl.prev_id, false, "alternative chain has wrong connection to main chain");
1838 complete_timestamps_vector(m_db->get_block_height(alt_chain.front().bl.prev_id), timestamps);
1839 }
1840 // if block not associated with known alternate chain
1841 else
1842 {
1843 // if block parent is not part of main chain or an alternate chain,
1844 // we ignore it
1845 bool parent_in_main = m_db->block_exists(prev_id);
1846 CHECK_AND_ASSERT_MES(parent_in_main, false, "internal error: broken imperative condition: parent_in_main");
1847
1848 complete_timestamps_vector(m_db->get_block_height(prev_id), timestamps);
1849 }
1850
1851 return true;
1852 }
1853 //------------------------------------------------------------------
1854 // If a block is to be added and its parent block is not the current
1855 // main chain top block, then we need to see if we know about its parent block.
1856 // If its parent block is part of a known forked chain, then we need to see
1857 // if that chain is long enough to become the main chain and re-org accordingly
1858 // if so. If not, we need to hang on to the block in case it becomes part of
1859 // a long forked chain eventually.
1860 bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id,
1861 block_verification_context& bvc, pool_supplement& extra_block_txs)
1862 {
1863 LOG_PRINT_L3("Blockchain::" << __func__);
1864 CRITICAL_REGION_LOCAL(m_blockchain_lock);
1865 m_timestamps_and_difficulties_height = 0;
1866 m_reset_timestamps_and_difficulties_height = true;
1867 uint64_t block_height = get_block_height(b);
1868 if(0 == block_height)
1869 {
1870 MERROR_VER("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative), but miner tx says height is 0.");
1871 bvc.m_verifivation_failed = true;
1872 return false;
1873 }
1874 // this basically says if the blockchain is smaller than the first
1875 // checkpoint then alternate blocks are allowed. Alternatively, if the
1876 // last checkpoint *before* the end of the current chain is also before
1877 // the block to be added, then this is fine.
1878 if (!m_checkpoints.is_alternative_block_allowed(get_current_blockchain_height(), block_height))
1879 {
1880 MERROR_VER("Block with id: " << id << std::endl << " can't be accepted for alternative chain, block height: " << block_height << std::endl << " blockchain height: " << get_current_blockchain_height());
1881 bvc.m_verifivation_failed = true;
1882 return false;
1883 }
1884
1885 // this is a cheap test
1886 const uint8_t hf_version = m_hardfork->get_ideal_version(block_height);
1887 if (!m_hardfork->check_for_height(b, block_height))
1888 {
1889 LOG_PRINT_L1("Block with id: " << id << std::endl << "has old version for height " << block_height);
1890 bvc.m_verifivation_failed = true;
1891 return false;
1892 }
1893
1894 //block is not related with head of main chain
1895 //first of all - look in alternative chains container
1896 alt_block_data_t prev_data;
1897 bool parent_in_alt = m_db->get_alt_block(b.prev_id, &prev_data, NULL);
1898 bool parent_in_main = m_db->block_exists(b.prev_id);
1899 if (parent_in_alt || parent_in_main)
1900 {
1901 //we have new block in alternative chain
1902 std::list<block_extended_info> alt_chain;
1903 std::vector<uint64_t> timestamps;
1904 if (!build_alt_chain(b.prev_id, alt_chain, timestamps, bvc))
1905 return false;
1906
1907 // FIXME: consider moving away from block_extended_info at some point
1908 block_extended_info bei = {};
1909 bei.bl = b;
1910 const uint64_t prev_height = alt_chain.size() ? prev_data.height : m_db->get_block_height(b.prev_id);
1911 bei.height = prev_height + 1;
1912 uint64_t block_reward = get_outs_money_amount(b.miner_tx);
1913 const uint64_t prev_generated_coins = alt_chain.size() ? prev_data.already_generated_coins : m_db->get_block_already_generated_coins(prev_height);
1914 bei.already_generated_coins = (block_reward < (MONEY_SUPPLY - prev_generated_coins)) ? prev_generated_coins + block_reward : MONEY_SUPPLY;
1915
1916 // verify that the block's timestamp is within the acceptable range
1917 // (not earlier than the median of the last X blocks)
1918 if(!check_block_timestamp(timestamps, b))
1919 {
1920 MERROR_VER("Block with id: " << id << std::endl << " for alternative chain, has invalid timestamp: " << b.timestamp);
1921 bvc.m_verifivation_failed = true;
1922 return false;
1923 }
1924
1925 bool is_a_checkpoint;
1926 if(!m_checkpoints.check_block(bei.height, id, is_a_checkpoint))
1927 {
1928 LOG_ERROR("CHECKPOINT VALIDATION FAILED");
1929 bvc.m_verifivation_failed = true;
1930 return false;
1931 }
1932
1933 // Check the block's hash against the difficulty target for its alt chain
1934 difficulty_type current_diff = get_next_difficulty_for_alternative_chain(alt_chain, bei);
1935 CHECK_AND_ASSERT_MES(current_diff, false, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!");
1936 crypto::hash proof_of_work;
1937 memset(proof_of_work.data, 0xff, sizeof(proof_of_work.data));
1938 if (b.major_version >= RX_BLOCK_VERSION)
1939 {
1940 crypto::hash seedhash = null_hash;
1941 uint64_t seedheight = rx_seedheight(bei.height);
1942 // seedblock is on the alt chain somewhere
1943 if (alt_chain.size() && alt_chain.front().height <= seedheight)
1944 {
1945 for (auto it=alt_chain.begin(); it != alt_chain.end(); it++)
1946 {
1947 if (it->height == seedheight+1)
1948 {
1949 seedhash = it->bl.prev_id;
1950 break;
1951 }
1952 }
1953 } else
1954 {
1955 seedhash = get_block_id_by_height(seedheight);
1956 }
1957 get_altblock_longhash(bei.bl, proof_of_work, seedhash);
1958 } else
1959 {
1960 get_block_longhash(this, bei.bl, proof_of_work, bei.height, 0);
1961 }
1962 if(!check_hash(proof_of_work, current_diff))
1963 {
1964 MERROR_VER("Block with id: " << id << std::endl << " for alternative chain, does not have enough proof of work: " << proof_of_work << std::endl << " expected difficulty: " << current_diff);
1965 bvc.m_verifivation_failed = true;
1966 bvc.m_bad_pow = true;
1967 return false;
1968 }
1969
1970 if(!prevalidate_miner_transaction(b, bei.height, hf_version))
1971 {
1972 MERROR_VER("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative) has incorrect miner transaction.");
1973 bvc.m_verifivation_failed = true;
1974 return false;
1975 }
1976
1977 // FIXME:
1978 // this brings up an interesting point: consider allowing to get block
1979 // difficulty both by height OR by hash, not just height.
1980 difficulty_type main_chain_cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->height() - 1);
1981 if (alt_chain.size())
1982 {
1983 bei.cumulative_difficulty = prev_data.cumulative_difficulty_high;
1984 bei.cumulative_difficulty = (bei.cumulative_difficulty << 64) + prev_data.cumulative_difficulty_low;
1985 }
1986 else
1987 {
1988 // passed-in block's previous block's cumulative difficulty, found on the main chain
1989 bei.cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->get_block_height(b.prev_id));
1990 }
1991 bei.cumulative_difficulty += current_diff;
1992
1993 // Now that we have the PoW verification out of the way, verify all pool supplement txs
1994 tx_verification_context tvc{};
1995 if (!ver_non_input_consensus(extra_block_txs, tvc, hf_version))
1996 {
1997 MERROR_VER("Transaction pool supplement verification failure for alt block " << id);
1998 bvc.m_verifivation_failed = true;
1999 return false;
2000 }
2001
2002 // Add pool supplement txs to the main mempool with relay_method::block
2003 CRITICAL_REGION_LOCAL(m_tx_pool);
2004 for (auto& extra_block_tx : extra_block_txs.txs_by_txid)
2005 {
2006 const crypto::hash& txid = extra_block_tx.first;
2007 transaction& tx = extra_block_tx.second.first;
2008 const blobdata &tx_blob = extra_block_tx.second.second;
2009
2010 tx_verification_context tvc{};
2011 if ((!m_tx_pool.have_tx(txid, relay_category::legacy) &&
2012 !m_db->tx_exists(txid) &&
2013 !m_tx_pool.add_tx(tx, tvc, relay_method::block, /*relayed=*/true, hf_version, hf_version))
2014 || tvc.m_verifivation_failed)
2015 {
2016 MERROR_VER("Transaction " << txid <<
2017 " in pool supplement failed to enter main pool for alt block " << id);
2018 bvc.m_verifivation_failed = true;
2019 return false;
2020 }
2021
2022 // If new incoming tx in alt block passed verification and entered the pool, notify ZMQ
2023 if (tvc.m_added_to_pool)
2024 notify_txpool_event({txpool_event{
2025 .tx = tx,
2026 .hash = txid,
2027 .blob_size = tx_blob.size(),
2028 .weight = get_transaction_weight(tx),
2029 .res = true}});
2030 }
2031 extra_block_txs.txs_by_txid.clear();
2032 extra_block_txs.nic_verified_hf_version = 0;
2033
2034 bei.block_cumulative_weight = cryptonote::get_transaction_weight(b.miner_tx);
2035 for (const crypto::hash &txid: b.tx_hashes)
2036 {
2037 cryptonote::tx_memory_pool::tx_details td;
2038 cryptonote::blobdata blob;
2039 if (m_tx_pool.have_tx(txid, relay_category::legacy))
2040 {
2041 if (m_tx_pool.get_transaction_info(txid, td, true/*include_sensitive_data*/))
2042 {
2043 bei.block_cumulative_weight += td.weight;
2044 }
2045 else
2046 {
2047 MERROR_VER("Transaction is in the txpool, but metadata not found");
2048 bvc.m_verifivation_failed = true;
2049 return false;
2050 }
2051 }
2052 else if (m_db->get_pruned_tx_blob(txid, blob))
2053 {
2054 cryptonote::transaction tx;
2055 if (!cryptonote::parse_and_validate_tx_base_from_blob(blob, tx))
2056 {
2057 MERROR_VER("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative) refers to unparsable transaction hash " << txid << ".");
2058 bvc.m_verifivation_failed = true;
2059 return false;
2060 }
2061 bei.block_cumulative_weight += cryptonote::get_pruned_transaction_weight(tx);
2062 }
2063 else
2064 {
2065 // we can't determine the block weight, set it to 0 and break out of the loop
2066 bei.block_cumulative_weight = 0;
2067 break;
2068 }
2069 }
2070
2071 // add block to alternate blocks storage,
2072 // as well as the current "alt chain" container
2073 CHECK_AND_ASSERT_MES(!m_db->get_alt_block(id, NULL, NULL), false, "insertion of new alternative block returned as it already exists");
2074 cryptonote::alt_block_data_t data;
2075 data.height = bei.height;
2076 data.cumulative_weight = bei.block_cumulative_weight;
2077 data.cumulative_difficulty_low = (bei.cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
2078 data.cumulative_difficulty_high = ((bei.cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
2079 data.already_generated_coins = bei.already_generated_coins;
2080 m_db->add_alt_block(id, data, cryptonote::block_to_blob(bei.bl));
2081 alt_chain.push_back(bei);
2082
2083 // FIXME: is it even possible for a checkpoint to show up not on the main chain?
2084 if(is_a_checkpoint)
2085 {
2086 //do reorganize!
2087 MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front().height << " of " << m_db->height() - 1 << ", checkpoint is found in alternative chain on height " << bei.height);
2088
2089 bool r = switch_to_alternative_blockchain(alt_chain, true);
2090
2091 if(r) bvc.m_added_to_main_chain = true;
2092 else bvc.m_verifivation_failed = true;
2093
2094 return r;
2095 }
2096 else if(main_chain_cumulative_difficulty < bei.cumulative_difficulty) //check if difficulty bigger then in main chain
2097 {
2098 //do reorganize!
2099 MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front().height << " of " << m_db->height() - 1 << " with cum_difficulty " << m_db->get_block_cumulative_difficulty(m_db->height() - 1) << std::endl << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << bei.cumulative_difficulty);
2100
2101 bool r = switch_to_alternative_blockchain(alt_chain, false);
2102 if (r)
2103 bvc.m_added_to_main_chain = true;
2104 else
2105 bvc.m_verifivation_failed = true;
2106 return r;
2107 }
2108 else
2109 {
2110 MGINFO_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << bei.height << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "difficulty:\t" << current_diff);
2111 return true;
2112 }
2113 }
2114 else
2115 {
2116 //block orphaned
2117 bvc.m_marked_as_orphaned = true;
2118 MERROR_VER("Block recognized as orphaned and rejected, id = " << id << ", height " << block_height
2119 << ", parent in alt " << parent_in_alt << ", parent in main " << parent_in_main
2120 << " (parent " << b.prev_id << ", current top " << get_tail_id() << ", chain height " << get_current_blockchain_height() << ")");
2121 }
2122
2123 return true;
2124 }
2125 //------------------------------------------------------------------
2126 bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks, std::vector<cryptonote::blobdata>& txs) const
2127 {
2128 LOG_PRINT_L3("Blockchain::" << __func__);
2129 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2130 if(start_offset >= m_db->height())
2131 return false;
2132
2133 if (!get_blocks(start_offset, count, blocks))
2134 {
2135 return false;
2136 }
2137
2138 for(const auto& blk : blocks)
2139 {
2140 std::vector<crypto::hash> missed_ids;
2141 get_transactions_blobs(blk.second.tx_hashes, txs, missed_ids);
2142 CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "has missed transactions in own block in main blockchain");
2143 }
2144
2145 return true;
2146 }
2147 //------------------------------------------------------------------
2148 bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks) const
2149 {
2150 LOG_PRINT_L3("Blockchain::" << __func__);
2151 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2152 const uint64_t height = m_db->height();
2153 if(start_offset >= height)
2154 return false;
2155
2156 blocks.reserve(blocks.size() + height - start_offset);
2157 for(size_t i = start_offset; i < start_offset + count && i < height;i++)
2158 {
2159 blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(i), block()));
2160 if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second))
2161 {
2162 LOG_ERROR("Invalid block");
2163 return false;
2164 }
2165 }
2166 return true;
2167 }
2168 //------------------------------------------------------------------
2169 //TODO: This function *looks* like it won't need to be rewritten
2170 // to use BlockchainDB, as it calls other functions that were,
2171 // but it warrants some looking into later.
2172 //
2173 //FIXME: This function appears to want to return false if any transactions
2174 // that belong with blocks are missing, but not if blocks themselves
2175 // are missing.
2176 bool Blockchain::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp)
2177 {
2178 LOG_PRINT_L3("Blockchain::" << __func__);
2179 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2180 db_rtxn_guard rtxn_guard (m_db);
2181 rsp.current_blockchain_height = get_current_blockchain_height();
2182 std::vector<std::pair<cryptonote::blobdata,block>> blocks;
2183 get_blocks(arg.blocks, blocks, rsp.missed_ids);
2184
2185 for (size_t i = 0; i < blocks.size(); ++i)
2186 {
2187 auto& bl = blocks[i];
2188 std::vector<crypto::hash> missed_tx_ids;
2189
2190 rsp.blocks.push_back(block_complete_entry());
2191 block_complete_entry& e = rsp.blocks.back();
2192
2193 // FIXME: s/rsp.missed_ids/missed_tx_id/ ? Seems like rsp.missed_ids
2194 // is for missed blocks, not missed transactions as well.
2195 e.pruned = arg.prune;
2196 get_transactions_blobs(bl.second.tx_hashes, e.txs, missed_tx_ids, arg.prune);
2197 if (missed_tx_ids.size() != 0)
2198 {
2199 // do not display an error if the peer asked for an unpruned block which we are not meant to have
2200 if (tools::has_unpruned_block(get_block_height(bl.second), get_current_blockchain_height(), get_blockchain_pruning_seed()))
2201 {
2202 LOG_ERROR("Error retrieving blocks, missed " << missed_tx_ids.size()
2203 << " transactions for block with hash: " << get_block_hash(bl.second)
2204 << std::endl
2205 );
2206 }
2207
2208 // append missed transaction hashes to response missed_ids field,
2209 // as done below if any standalone transactions were requested
2210 // and missed.
2211 rsp.missed_ids.insert(rsp.missed_ids.end(), missed_tx_ids.begin(), missed_tx_ids.end());
2212 return false;
2213 }
2214
2215 //pack block
2216 e.block = std::move(bl.first);
2217 e.block_weight = 0;
2218 if (arg.prune && m_db->block_exists(arg.blocks[i]))
2219 e.block_weight = m_db->get_block_weight(m_db->get_block_height(arg.blocks[i]));
2220 }
2221
2222 return true;
2223 }
2224 //------------------------------------------------------------------
2225 bool Blockchain::get_alternative_blocks(std::vector<block>& blocks) const
2226 {
2227 LOG_PRINT_L3("Blockchain::" << __func__);
2228 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2229
2230 blocks.reserve(m_db->get_alt_block_count());
2231 m_db->for_all_alt_blocks([&blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const cryptonote::blobdata_ref *blob) {
2232 if (!blob)
2233 {
2234 MERROR("No blob, but blobs were requested");
2235 return false;
2236 }
2237 cryptonote::block bl;
2238 if (cryptonote::parse_and_validate_block_from_blob(*blob, bl))
2239 blocks.push_back(std::move(bl));
2240 else
2241 MERROR("Failed to parse block from blob");
2242 return true;
2243 }, true);
2244 return true;
2245 }
2246 //------------------------------------------------------------------
2247 size_t Blockchain::get_alternative_blocks_count() const
2248 {
2249 LOG_PRINT_L3("Blockchain::" << __func__);
2250 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2251 return m_db->get_alt_block_count();
2252 }
2253 //------------------------------------------------------------------
2254 // This function adds the output specified by <amount, i> to the result_outs container
2255 // unlocked and other such checks should be done by here.
2256 uint64_t Blockchain::get_num_mature_outputs(uint64_t amount) const
2257 {
2258 uint64_t num_outs = m_db->get_num_outputs(amount);
2259 // ensure we don't include outputs that aren't yet eligible to be used
2260 // outpouts are sorted by height
2261 const uint64_t blockchain_height = m_db->height();
2262 while (num_outs > 0)
2263 {
2264 const tx_out_index toi = m_db->get_output_tx_and_index(amount, num_outs - 1);
2265 const uint64_t height = m_db->get_tx_block_height(toi.first);
2266 if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= blockchain_height)
2267 break;
2268 --num_outs;
2269 }
2270
2271 return num_outs;
2272 }
2273
2274 crypto::public_key Blockchain::get_output_key(uint64_t amount, uint64_t global_index) const
2275 {
2276 output_data_t data = m_db->get_output_key(amount, global_index);
2277 return data.pubkey;
2278 }
2279
2280 //------------------------------------------------------------------
2281 bool Blockchain::get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const
2282 {
2283 LOG_PRINT_L3("Blockchain::" << __func__);
2284 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2285
2286 res.outs.clear();
2287 res.outs.reserve(req.outputs.size());
2288
2289 std::vector<cryptonote::output_data_t> data;
2290 try
2291 {
2292 std::vector<uint64_t> amounts, offsets;
2293 amounts.reserve(req.outputs.size());
2294 offsets.reserve(req.outputs.size());
2295 for (const auto &i: req.outputs)
2296 {
2297 amounts.push_back(i.amount);
2298 offsets.push_back(i.index);
2299 }
2300 m_db->get_output_key(epee::span<const uint64_t>(amounts.data(), amounts.size()), offsets, data);
2301 if (data.size() != req.outputs.size())
2302 {
2303 MERROR("Unexpected output data size: expected " << req.outputs.size() << ", got " << data.size());
2304 return false;
2305 }
2306 const uint8_t hf_version = m_hardfork->get_current_version();
2307 for (const auto &t: data)
2308 res.outs.push_back({t.pubkey, t.commitment, is_tx_spendtime_unlocked(t.unlock_time, hf_version), t.height, crypto::null_hash});
2309
2310 if (req.get_txid)
2311 {
2312 for (size_t i = 0; i < req.outputs.size(); ++i)
2313 {
2314 tx_out_index toi = m_db->get_output_tx_and_index(req.outputs[i].amount, req.outputs[i].index);
2315 res.outs[i].txid = toi.first;
2316 }
2317 }
2318 }
2319 catch (const std::exception &e)
2320 {
2321 return false;
2322 }
2323 return true;
2324 }
2325 //------------------------------------------------------------------
2326 void Blockchain::get_output_key_mask_unlocked(const uint64_t& amount, const uint64_t& index, crypto::public_key& key, rct::key& mask, bool& unlocked) const
2327 {
2328 const auto o_data = m_db->get_output_key(amount, index);
2329 key = o_data.pubkey;
2330 mask = o_data.commitment;
2331 tx_out_index toi = m_db->get_output_tx_and_index(amount, index);
2332 const uint8_t hf_version = m_hardfork->get_current_version();
2333 unlocked = is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first), hf_version);
2334 }
2335 //------------------------------------------------------------------
2336 bool Blockchain::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, uint64_t &start_height, std::vector<uint64_t> &distribution, uint64_t &base) const
2337 {
2338 // rct outputs don't exist before v4
2339 if (amount == 0 && m_nettype != network_type::FAKECHAIN)
2340 start_height = m_hardfork->get_earliest_ideal_height_for_version(HF_VERSION_DYNAMIC_FEE);
2341 else
2342 start_height = 0;
2343 base = 0;
2344
2345 if (to_height > 0 && to_height < from_height)
2346 return false;
2347
2348 if (from_height > start_height)
2349 start_height = from_height;
2350
2351 distribution.clear();
2352 uint64_t db_height = m_db->height();
2353 if (db_height == 0)
2354 return false;
2355 if (start_height >= db_height || to_height >= db_height)
2356 return false;
2357 if (amount == 0)
2358 {
2359 std::vector<uint64_t> heights;
2360 heights.reserve(to_height + 1 - start_height);
2361 const uint64_t real_start_height = start_height > 0 ? start_height-1 : start_height;
2362 for (uint64_t h = real_start_height; h <= to_height; ++h)
2363 heights.push_back(h);
2364 distribution = m_db->get_block_cumulative_rct_outputs(heights);
2365 if (start_height > 0)
2366 {
2367 base = distribution[0];
2368 distribution.erase(distribution.begin());
2369 }
2370 return true;
2371 }
2372 else
2373 {
2374 return m_db->get_output_distribution(amount, start_height, to_height, distribution, base);
2375 }
2376 }
2377 //------------------------------------------------------------------
2378 // This function takes a list of block hashes from another node
2379 // on the network to find where the split point is between us and them.
2380 // This is used to see what to send another node that needs to sync.
2381 bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const
2382 {
2383 LOG_PRINT_L3("Blockchain::" << __func__);
2384 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2385
2386 // make sure the request includes at least the genesis block, otherwise
2387 // how can we expect to sync from the client that the block list came from?
2388 if(qblock_ids.empty())
2389 {
2390 MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << ", dropping connection");
2391 return false;
2392 }
2393
2394 db_rtxn_guard rtxn_guard(m_db);
2395 // make sure that the last block in the request's block list matches
2396 // the genesis block
2397 auto gen_hash = m_db->get_block_hash_from_height(0);
2398 if(qblock_ids.back() != gen_hash)
2399 {
2400 MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: " << std::endl << "id: " << qblock_ids.back() << ", " << std::endl << "expected: " << gen_hash << "," << std::endl << " dropping connection");
2401 return false;
2402 }
2403
2404 // Find the first block the foreign chain has that we also have.
2405 // Assume qblock_ids is in reverse-chronological order.
2406 auto bl_it = qblock_ids.begin();
2407 uint64_t split_height = 0;
2408 for(; bl_it != qblock_ids.end(); bl_it++)
2409 {
2410 try
2411 {
2412 if (m_db->block_exists(*bl_it, &split_height))
2413 break;
2414 }
2415 catch (const std::exception& e)
2416 {
2417 MWARNING("Non-critical error trying to find block by hash in BlockchainDB, hash: " << *bl_it);
2418 return false;
2419 }
2420 }
2421
2422 // this should be impossible, as we checked that we share the genesis block,
2423 // but just in case...
2424 if(bl_it == qblock_ids.end())
2425 {
2426 MERROR("Internal error handling connection, can't find split point");
2427 return false;
2428 }
2429
2430 //we start to put block ids INCLUDING last known id, just to make other side be sure
2431 starter_offset = split_height;
2432 return true;
2433 }
2434 //------------------------------------------------------------------
2435 difficulty_type Blockchain::block_difficulty(uint64_t i) const
2436 {
2437 LOG_PRINT_L3("Blockchain::" << __func__);
2438 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
2439 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
2440 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
2441 // lock if it is otherwise needed.
2442 try
2443 {
2444 return m_db->get_block_difficulty(i);
2445 }
2446 catch (const BLOCK_DNE& e)
2447 {
2448 MERROR("Attempted to get block difficulty for height above blockchain height");
2449 }
2450 return 0;
2451 }
2452 //------------------------------------------------------------------
2453 template<typename T> void reserve_container(std::vector<T> &v, size_t N) { v.reserve(N); }
2454 template<typename T> void reserve_container(std::list<T> &v, size_t N) { }
2455 //------------------------------------------------------------------
2456 //TODO: return type should be void, throw on exception
2457 // alternatively, return true only if no blocks missed
2458 template<class t_ids_container, class t_blocks_container, class t_missed_container>
2459 bool Blockchain::get_blocks(const t_ids_container& block_ids, t_blocks_container& blocks, t_missed_container& missed_bs) const
2460 {
2461 LOG_PRINT_L3("Blockchain::" << __func__);
2462 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2463
2464 reserve_container(blocks, block_ids.size());
2465 for (const auto& block_hash : block_ids)
2466 {
2467 try
2468 {
2469 uint64_t height = 0;
2470 if (m_db->block_exists(block_hash, &height))
2471 {
2472 blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(height), block()));
2473 if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second))
2474 {
2475 LOG_ERROR("Invalid block: " << block_hash);
2476 blocks.pop_back();
2477 missed_bs.push_back(block_hash);
2478 }
2479 }
2480 else
2481 missed_bs.push_back(block_hash);
2482 }
2483 catch (const std::exception& e)
2484 {
2485 return false;
2486 }
2487 }
2488 return true;
2489 }
2490 //------------------------------------------------------------------
2491 static bool fill(BlockchainDB *db, const crypto::hash &tx_hash, cryptonote::blobdata &tx, bool pruned)
2492 {
2493 if (pruned)
2494 {
2495 if (!db->get_pruned_tx_blob(tx_hash, tx))
2496 {
2497 MDEBUG("Pruned transaction blob not found for " << tx_hash);
2498 return false;
2499 }
2500 }
2501 else
2502 {
2503 if (!db->get_tx_blob(tx_hash, tx))
2504 {
2505 MDEBUG("Transaction blob not found for " << tx_hash);
2506 return false;
2507 }
2508 }
2509 return true;
2510 }
2511 //------------------------------------------------------------------
2512 static bool fill(BlockchainDB *db, const crypto::hash &tx_hash, tx_blob_entry &tx, bool pruned)
2513 {
2514 if (!fill(db, tx_hash, tx.blob, pruned))
2515 return false;
2516 if (pruned)
2517 {
2518 if (is_v1_tx(tx.blob))
2519 {
2520 // v1 txes aren't pruned, so fetch the whole thing
2521 cryptonote::blobdata prunable_blob;
2522 if (!db->get_prunable_tx_blob(tx_hash, prunable_blob))
2523 {
2524 MDEBUG("Prunable transaction blob not found for " << tx_hash);
2525 return false;
2526 }
2527 tx.blob.append(prunable_blob);
2528 tx.prunable_hash = crypto::null_hash;
2529 }
2530 else
2531 {
2532 if (!db->get_prunable_tx_hash(tx_hash, tx.prunable_hash))
2533 {
2534 MDEBUG("Prunable transaction data hash not found for " << tx_hash);
2535 return false;
2536 }
2537 }
2538 }
2539 return true;
2540 }
2541 //------------------------------------------------------------------
2542 //TODO: return type should be void, throw on exception
2543 // alternatively, return true only if no transactions missed
2544 bool Blockchain::get_transactions_blobs(const std::vector<crypto::hash>& txs_ids, std::vector<cryptonote::blobdata>& txs, std::vector<crypto::hash>& missed_txs, bool pruned) const
2545 {
2546 LOG_PRINT_L3("Blockchain::" << __func__);
2547 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2548
2549 txs.reserve(txs_ids.size());
2550 for (const auto& tx_hash : txs_ids)
2551 {
2552 try
2553 {
2554 cryptonote::blobdata tx;
2555 if (fill(m_db, tx_hash, tx, pruned))
2556 txs.push_back(std::move(tx));
2557 else
2558 missed_txs.push_back(tx_hash);
2559 }
2560 catch (const std::exception& e)
2561 {
2562 return false;
2563 }
2564 }
2565 return true;
2566 }
2567 //------------------------------------------------------------------
2568 bool Blockchain::get_transactions_blobs(const std::vector<crypto::hash>& txs_ids, std::vector<tx_blob_entry>& txs, std::vector<crypto::hash>& missed_txs, bool pruned) const
2569 {
2570 LOG_PRINT_L3("Blockchain::" << __func__);
2571 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2572
2573 txs.reserve(txs_ids.size());
2574 for (const auto& tx_hash : txs_ids)
2575 {
2576 try
2577 {
2578 tx_blob_entry tx;
2579 if (fill(m_db, tx_hash, tx, pruned))
2580 txs.push_back(std::move(tx));
2581 else
2582 missed_txs.push_back(tx_hash);
2583 }
2584 catch (const std::exception& e)
2585 {
2586 return false;
2587 }
2588 }
2589 return true;
2590 }
2591 //------------------------------------------------------------------
2592 size_t get_transaction_version(const cryptonote::blobdata &bd)
2593 {
2594 size_t version;
2595 const char* begin = static_cast<const char*>(bd.data());
2596 const char* end = begin + bd.size();
2597 int read = tools::read_varint(begin, end, version);
2598 if (read <= 0)
2599 throw std::runtime_error("Internal error getting transaction version");
2600 return version;
2601 }
2602 //------------------------------------------------------------------
2603 template<class t_ids_container, class t_tx_container, class t_missed_container>
2604 bool Blockchain::get_split_transactions_blobs(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs) const
2605 {
2606 LOG_PRINT_L3("Blockchain::" << __func__);
2607 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2608
2609 reserve_container(txs, txs_ids.size());
2610 for (const auto& tx_hash : txs_ids)
2611 {
2612 try
2613 {
2614 cryptonote::blobdata tx;
2615 if (m_db->get_pruned_tx_blob(tx_hash, tx))
2616 {
2617 txs.push_back(std::make_tuple(tx_hash, std::move(tx), crypto::null_hash, cryptonote::blobdata()));
2618 if (!is_v1_tx(std::get<1>(txs.back())) && !m_db->get_prunable_tx_hash(tx_hash, std::get<2>(txs.back())))
2619 {
2620 MERROR("Prunable data hash not found for " << tx_hash);
2621 return false;
2622 }
2623 if (!m_db->get_prunable_tx_blob(tx_hash, std::get<3>(txs.back())))
2624 std::get<3>(txs.back()).clear();
2625 }
2626 else
2627 missed_txs.push_back(tx_hash);
2628 }
2629 catch (const std::exception& e)
2630 {
2631 return false;
2632 }
2633 }
2634 return true;
2635 }
2636 //------------------------------------------------------------------
2637 template<class t_ids_container, class t_tx_container, class t_missed_container>
2638 bool Blockchain::get_transactions(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs, bool pruned) const
2639 {
2640 LOG_PRINT_L3("Blockchain::" << __func__);
2641 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2642
2643 reserve_container(txs, txs_ids.size());
2644 for (const auto& tx_hash : txs_ids)
2645 {
2646 try
2647 {
2648 cryptonote::blobdata tx;
2649 bool res = pruned ? m_db->get_pruned_tx_blob(tx_hash, tx) : m_db->get_tx_blob(tx_hash, tx);
2650 if (res)
2651 {
2652 txs.push_back(transaction());
2653 res = pruned ? parse_and_validate_tx_base_from_blob(tx, txs.back()) : parse_and_validate_tx_from_blob(tx, txs.back());
2654 if (!res)
2655 {
2656 LOG_ERROR("Invalid transaction");
2657 return false;
2658 }
2659 }
2660 else
2661 missed_txs.push_back(tx_hash);
2662 }
2663 catch (const std::exception& e)
2664 {
2665 return false;
2666 }
2667 }
2668 return true;
2669 }
2670 //------------------------------------------------------------------
2671 // Find the split point between us and foreign blockchain and return
2672 // (by reference) the most recent common block hash along with up to
2673 // BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes.
2674 bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::vector<crypto::hash>& hashes, std::vector<uint64_t>* weights, uint64_t& start_height, uint64_t& current_height, bool clip_pruned) const
2675 {
2676 LOG_PRINT_L3("Blockchain::" << __func__);
2677 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2678
2679 // if we can't find the split point, return false
2680 if(!find_blockchain_supplement(qblock_ids, start_height))
2681 {
2682 return false;
2683 }
2684
2685 db_rtxn_guard rtxn_guard(m_db);
2686 current_height = get_current_blockchain_height();
2687 uint64_t stop_height = current_height;
2688 if (clip_pruned)
2689 {
2690 const uint32_t pruning_seed = get_blockchain_pruning_seed();
2691 if (start_height < tools::get_next_unpruned_block_height(start_height, current_height, pruning_seed))
2692 {
2693 MDEBUG("We only have a pruned version of the common ancestor");
2694 return false;
2695 }
2696 stop_height = tools::get_next_pruned_block_height(start_height, current_height, pruning_seed);
2697 }
2698 size_t count = 0;
2699 const size_t reserve = std::min((size_t)(stop_height - start_height), (size_t)BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT);
2700 hashes.reserve(reserve);
2701 if (weights)
2702 weights->reserve(reserve);
2703 for(size_t i = start_height; i < stop_height && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++)
2704 {
2705 hashes.push_back(m_db->get_block_hash_from_height(i));
2706 if (weights)
2707 weights->push_back(m_db->get_block_weight(i));
2708 }
2709
2710 return true;
2711 }
2712
2713 bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, bool clip_pruned, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const
2714 {
2715 LOG_PRINT_L3("Blockchain::" << __func__);
2716 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2717
2718 bool result = find_blockchain_supplement(qblock_ids, resp.m_block_ids, &resp.m_block_weights, resp.start_height, resp.total_height, clip_pruned);
2719 if (result)
2720 {
2721 cryptonote::difficulty_type wide_cumulative_difficulty = m_db->get_block_cumulative_difficulty(resp.total_height - 1);
2722 resp.cumulative_difficulty = (wide_cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
2723 resp.cumulative_difficulty_top64 = ((wide_cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
2724 }
2725
2726 return result;
2727 }
2728 //------------------------------------------------------------------
2729 //FIXME: change argument to std::vector, low priority
2730 // find split point between ours and foreign blockchain (or start at
2731 // blockchain height <req_start_block>), and return up to max_count FULL
2732 // blocks by reference.
2733 bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, const std::list<crypto::hash>& qblock_ids, std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata> > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_block_count, size_t max_tx_count) const
2734 {
2735 LOG_PRINT_L3("Blockchain::" << __func__);
2736 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2737
2738 // if a specific start height has been requested
2739 if(req_start_block > 0)
2740 {
2741 // if requested height is higher than our chain, return false -- we can't help
2742 if (req_start_block >= m_db->height())
2743 {
2744 return false;
2745 }
2746 start_height = req_start_block;
2747 }
2748 else
2749 {
2750 if(!find_blockchain_supplement(qblock_ids, start_height))
2751 {
2752 return false;
2753 }
2754 }
2755
2756 db_rtxn_guard rtxn_guard(m_db);
2757 total_height = get_current_blockchain_height();
2758 blocks.reserve(std::min(std::min(max_block_count, (size_t)10000), (size_t)(total_height - start_height)));
2759 CHECK_AND_ASSERT_MES(m_db->get_blocks_from(start_height, 3, max_block_count, max_tx_count, FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE, blocks, pruned, true, get_miner_tx_hash),
2760 false, "Error getting blocks");
2761
2762 return true;
2763 }
2764 //------------------------------------------------------------------
2765 bool Blockchain::add_block_as_invalid(const block& bl, const crypto::hash& h)
2766 {
2767 LOG_PRINT_L3("Blockchain::" << __func__);
2768 block_extended_info bei = AUTO_VAL_INIT(bei);
2769 bei.bl = bl;
2770 return add_block_as_invalid(bei, h);
2771 }
2772 //------------------------------------------------------------------
2773 bool Blockchain::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h)
2774 {
2775 LOG_PRINT_L3("Blockchain::" << __func__);
2776 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2777 auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei));
2778 CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed");
2779 MINFO("BLOCK ADDED AS INVALID: " << h << std::endl << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size());
2780 return true;
2781 }
2782 //------------------------------------------------------------------
2783 void Blockchain::flush_invalid_blocks()
2784 {
2785 LOG_PRINT_L3("Blockchain::" << __func__);
2786 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2787 m_invalid_blocks.clear();
2788 }
2789 //------------------------------------------------------------------
2790 bool Blockchain::have_block_unlocked(const crypto::hash& id, int *where) const
2791 {
2792 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
2793 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
2794 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
2795 // lock if it is otherwise needed.
2796 LOG_PRINT_L3("Blockchain::" << __func__);
2797
2798 if(m_db->block_exists(id))
2799 {
2800 LOG_PRINT_L2("block " << id << " found in main chain");
2801 if (where) *where = HAVE_BLOCK_MAIN_CHAIN;
2802 return true;
2803 }
2804
2805 if(m_db->get_alt_block(id, NULL, NULL))
2806 {
2807 LOG_PRINT_L2("block " << id << " found in alternative chains");
2808 if (where) *where = HAVE_BLOCK_ALT_CHAIN;
2809 return true;
2810 }
2811
2812 if(m_invalid_blocks.count(id))
2813 {
2814 LOG_PRINT_L2("block " << id << " found in m_invalid_blocks");
2815 if (where) *where = HAVE_BLOCK_INVALID;
2816 return true;
2817 }
2818
2819 return false;
2820 }
2821 //------------------------------------------------------------------
2822 bool Blockchain::have_block(const crypto::hash& id, int *where) const
2823 {
2824 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2825 return have_block_unlocked(id, where);
2826 }
2827 //------------------------------------------------------------------
2828 bool Blockchain::handle_block_to_main_chain(const block& bl, block_verification_context& bvc)
2829 {
2830 LOG_PRINT_L3("Blockchain::" << __func__);
2831 crypto::hash id = get_block_hash(bl);
2832 pool_supplement ps{};
2833 return handle_block_to_main_chain(bl, id, bvc, ps);
2834 }
2835 //------------------------------------------------------------------
2836 size_t Blockchain::get_total_transactions() const
2837 {
2838 LOG_PRINT_L3("Blockchain::" << __func__);
2839 // WARNING: this function does not take m_blockchain_lock, and thus should only call read only
2840 // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as
2841 // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must
2842 // lock if it is otherwise needed.
2843 return m_db->get_tx_count();
2844 }
2845 //------------------------------------------------------------------
2846 // This function checks each input in the transaction <tx> to make sure it
2847 // has not been used already, and adds its key to the container <keys_this_block>.
2848 //
2849 // This container should be managed by the code that validates blocks so we don't
2850 // have to store the used keys in a given block in the permanent storage only to
2851 // remove them later if the block fails validation.
2852 bool Blockchain::check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const
2853 {
2854 LOG_PRINT_L3("Blockchain::" << __func__);
2855 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2856 struct add_transaction_input_visitor: public boost::static_visitor<bool>
2857 {
2858 key_images_container& m_spent_keys;
2859 BlockchainDB* m_db;
2860 add_transaction_input_visitor(key_images_container& spent_keys, BlockchainDB* db) :
2861 m_spent_keys(spent_keys), m_db(db)
2862 {
2863 }
2864 bool operator()(const txin_to_key& in) const
2865 {
2866 const crypto::key_image& ki = in.k_image;
2867
2868 // attempt to insert the newly-spent key into the container of
2869 // keys spent this block. If this fails, the key was spent already
2870 // in this block, return false to flag that a double spend was detected.
2871 //
2872 // if the insert into the block-wide spent keys container succeeds,
2873 // check the blockchain-wide spent keys container and make sure the
2874 // key wasn't used in another block already.
2875 auto r = m_spent_keys.insert(ki);
2876 if(!r.second || m_db->has_key_image(ki))
2877 {
2878 //double spend detected
2879 return false;
2880 }
2881
2882 // if no double-spend detected, return true
2883 return true;
2884 }
2885
2886 bool operator()(const txin_gen& tx) const
2887 {
2888 return true;
2889 }
2890 bool operator()(const txin_to_script& tx) const
2891 {
2892 return false;
2893 }
2894 bool operator()(const txin_to_scripthash& tx) const
2895 {
2896 return false;
2897 }
2898 };
2899
2900 for (const txin_v& in : tx.vin)
2901 {
2902 if(!boost::apply_visitor(add_transaction_input_visitor(keys_this_block, m_db), in))
2903 {
2904 LOG_ERROR("Double spend detected!");
2905 return false;
2906 }
2907 }
2908
2909 return true;
2910 }
2911 //------------------------------------------------------------------
2912 bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector<std::vector<uint64_t>>& indexs) const
2913 {
2914 LOG_PRINT_L3("Blockchain::" << __func__);
2915 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2916 uint64_t tx_index;
2917 if (!m_db->tx_exists(tx_id, tx_index))
2918 {
2919 MERROR_VER("get_tx_outputs_gindexs failed to find transaction with id = " << tx_id);
2920 return false;
2921 }
2922 indexs = m_db->get_tx_amount_output_indices(tx_index, n_txes);
2923 CHECK_AND_ASSERT_MES(n_txes == indexs.size(), false, "Wrong indexs size");
2924
2925 return true;
2926 }
2927 //------------------------------------------------------------------
2928 bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const
2929 {
2930 LOG_PRINT_L3("Blockchain::" << __func__);
2931 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2932 uint64_t tx_index;
2933 if (!m_db->tx_exists(tx_id, tx_index))
2934 {
2935 MERROR_VER("get_tx_outputs_gindexs failed to find transaction with id = " << tx_id);
2936 return false;
2937 }
2938 std::vector<std::vector<uint64_t>> indices = m_db->get_tx_amount_output_indices(tx_index, 1);
2939 CHECK_AND_ASSERT_MES(indices.size() == 1, false, "Wrong indices size");
2940 indexs = indices.front();
2941 return true;
2942 }
2943 //------------------------------------------------------------------
2944 //FIXME: it seems this function is meant to be merely a wrapper around
2945 // another function of the same name, this one adding one bit of
2946 // functionality. Should probably move anything more than that
2947 // (getting the hash of the block at height max_used_block_id)
2948 // to the other function to keep everything in one place.
2949 // This function overloads its sister function with
2950 // an extra value (hash of highest block that holds an output used as input)
2951 // as a return-by-reference.
2952 bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block) const
2953 {
2954 LOG_PRINT_L3("Blockchain::" << __func__);
2955 CRITICAL_REGION_LOCAL(m_blockchain_lock);
2956
2957 #if defined(PER_BLOCK_CHECKPOINT)
2958 // check if we're doing per-block checkpointing
2959 if (m_db->height() < m_blocks_hash_check.size() && kept_by_block)
2960 {
2961 max_used_block_id = null_hash;
2962 max_used_block_height = 0;
2963 return true;
2964 }
2965 #endif
2966
2967 TIME_MEASURE_START(a);
2968 bool res = check_tx_inputs(tx, tvc, &max_used_block_height);
2969 TIME_MEASURE_FINISH(a);
2970 if(m_show_time_stats)
2971 {
2972 size_t ring_size = !tx.vin.empty() && tx.vin[0].type() == typeid(txin_to_key) ? boost::get<txin_to_key>(tx.vin[0]).key_offsets.size() : 0;
2973 MINFO("HASH: " << get_transaction_hash(tx) << " I/M/O: " << tx.vin.size() << "/" << ring_size << "/" << tx.vout.size() << " H: " << max_used_block_height << " ms: " << a + m_fake_scan_time << " B: " << get_object_blobsize(tx) << " W: " << get_transaction_weight(tx));
2974 }
2975 if (!res)
2976 return false;
2977
2978 CHECK_AND_ASSERT_MES(max_used_block_height < m_db->height(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_db->height());
2979 max_used_block_id = m_db->get_block_hash_from_height(max_used_block_height);
2980 return true;
2981 }
2982 //------------------------------------------------------------------
2983 bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context &tvc, std::uint8_t hf_version)
2984 {
2985 LOG_PRINT_L3("Blockchain::" << __func__);
2986
2987 // from hard fork 2, we forbid dust and compound outputs
2988 if (hf_version >= 2) {
2989 for (auto &o: tx.vout) {
2990 if (tx.version == 1)
2991 {
2992 if (!is_valid_decomposed_amount(o.amount)) {
2993 tvc.m_invalid_output = true;
2994 return false;
2995 }
2996 }
2997 }
2998 }
2999
3000 // in a v2 tx, all outputs must have 0 amount
3001 if (hf_version >= 3) {
3002 if (tx.version >= 2) {
3003 for (auto &o: tx.vout) {
3004 if (o.amount != 0) {
3005 tvc.m_invalid_output = true;
3006 return false;
3007 }
3008 }
3009 }
3010 }
3011
3012 // from v8, allow bulletproofs
3013 if (hf_version < 8) {
3014 if (tx.version >= 2) {
3015 const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type);
3016 if (bulletproof || !tx.rct_signatures.p.bulletproofs.empty())
3017 {
3018 MERROR_VER("Bulletproofs are not allowed before v8");
3019 tvc.m_invalid_output = true;
3020 return false;
3021 }
3022 }
3023 }
3024
3025 // from v9, forbid borromean range proofs
3026 if (hf_version > 8) {
3027 if (tx.version >= 2) {
3028 const bool borromean = rct::is_rct_borromean(tx.rct_signatures.type);
3029 if (borromean)
3030 {
3031 MERROR_VER("Borromean range proofs are not allowed after v8");
3032 tvc.m_invalid_output = true;
3033 return false;
3034 }
3035 }
3036 }
3037
3038 // from v10, allow bulletproofs v2
3039 if (hf_version < HF_VERSION_SMALLER_BP) {
3040 if (tx.version >= 2) {
3041 if (tx.rct_signatures.type == rct::RCTTypeBulletproof2)
3042 {
3043 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeBulletproof2 << " is not allowed before v" << HF_VERSION_SMALLER_BP);
3044 tvc.m_invalid_output = true;
3045 return false;
3046 }
3047 }
3048 }
3049
3050 // from v11, allow only bulletproofs v2
3051 if (hf_version > HF_VERSION_SMALLER_BP) {
3052 if (tx.version >= 2) {
3053 if (tx.rct_signatures.type == rct::RCTTypeBulletproof)
3054 {
3055 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeBulletproof << " is not allowed from v" << (HF_VERSION_SMALLER_BP + 1));
3056 tvc.m_invalid_output = true;
3057 return false;
3058 }
3059 }
3060 }
3061
3062 // from v13, allow CLSAGs
3063 if (hf_version < HF_VERSION_CLSAG) {
3064 if (tx.version >= 2) {
3065 if (tx.rct_signatures.type == rct::RCTTypeCLSAG)
3066 {
3067 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeCLSAG << " is not allowed before v" << HF_VERSION_CLSAG);
3068 tvc.m_invalid_output = true;
3069 return false;
3070 }
3071 }
3072 }
3073
3074 // from v14, allow only CLSAGs
3075 if (hf_version > HF_VERSION_CLSAG) {
3076 if (tx.version >= 2) {
3077 if (tx.rct_signatures.type <= rct::RCTTypeBulletproof2)
3078 {
3079 // two MLSAG txes went in due to a bug with txes that went into the txpool before the fork, grandfather them in
3080 static const char * grandfathered[2] = { "c5151944f0583097ba0c88cd0f43e7fabb3881278aa2f73b3b0a007c5d34e910", "6f2f117cde6fbcf8d4a6ef8974fcac744726574ac38cf25d3322c996b21edd4c" };
3081 crypto::hash h0, h1;
3082 epee::string_tools::hex_to_pod(grandfathered[0], h0);
3083 epee::string_tools::hex_to_pod(grandfathered[1], h1);
3084 if (cryptonote::get_transaction_hash(tx) == h0 || cryptonote::get_transaction_hash(tx) == h1)
3085 {
3086 MDEBUG("Grandfathering cryptonote::get_transaction_hash(tx) in");
3087 }
3088 else
3089 {
3090 MERROR_VER("Ringct type " << (unsigned)tx.rct_signatures.type << " is not allowed from v" << (HF_VERSION_CLSAG + 1));
3091 tvc.m_invalid_output = true;
3092 return false;
3093 }
3094 }
3095 }
3096 }
3097
3098 // from v15, allow bulletproofs plus
3099 if (hf_version < HF_VERSION_BULLETPROOF_PLUS) {
3100 if (tx.version >= 2) {
3101 const bool bulletproof_plus = rct::is_rct_bulletproof_plus(tx.rct_signatures.type);
3102 if (bulletproof_plus || !tx.rct_signatures.p.bulletproofs_plus.empty())
3103 {
3104 MERROR_VER("Bulletproofs plus are not allowed before v" << std::to_string(HF_VERSION_BULLETPROOF_PLUS));
3105 tvc.m_invalid_output = true;
3106 return false;
3107 }
3108 }
3109 }
3110
3111 // from v16, forbid bulletproofs
3112 if (hf_version > HF_VERSION_BULLETPROOF_PLUS) {
3113 if (tx.version >= 2) {
3114 const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type);
3115 if (bulletproof)
3116 {
3117 MERROR_VER("Bulletproof range proofs are not allowed after v" + std::to_string(HF_VERSION_BULLETPROOF_PLUS));
3118 tvc.m_invalid_output = true;
3119 return false;
3120 }
3121 }
3122 }
3123
3124 // from v15, require view tags on outputs
3125 if (!check_output_types(tx, hf_version))
3126 {
3127 tvc.m_invalid_output = true;
3128 return false;
3129 }
3130
3131 return true;
3132 }
3133 //------------------------------------------------------------------
3134 bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const
3135 {
3136 LOG_PRINT_L3("Blockchain::" << __func__);
3137 for (const txin_v& in: tx.vin)
3138 {
3139 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true);
3140 if(have_tx_keyimg_as_spent(in_to_key.k_image))
3141 return true;
3142 }
3143 return false;
3144 }
3145 bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys)
3146 {
3147 PERF_TIMER(expand_transaction_2);
3148 CHECK_AND_ASSERT_MES(tx.version == 2, false, "Transaction version is not 2");
3149
3150 rct::rctSig &rv = tx.rct_signatures;
3151
3152 // message - hash of the transaction prefix
3153 rv.message = rct::hash2rct(tx_prefix_hash);
3154
3155 // mixRing - full and simple store it in opposite ways
3156 if (rv.type == rct::RCTTypeFull)
3157 {
3158 CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys");
3159 rv.mixRing.resize(pubkeys[0].size());
3160 for (size_t m = 0; m < pubkeys[0].size(); ++m)
3161 rv.mixRing[m].clear();
3162 for (size_t n = 0; n < pubkeys.size(); ++n)
3163 {
3164 CHECK_AND_ASSERT_MES(pubkeys[n].size() <= pubkeys[0].size(), false, "More inputs that first ring");
3165 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3166 {
3167 rv.mixRing[m].push_back(pubkeys[n][m]);
3168 }
3169 }
3170 }
3171 else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof || rv.type == rct::RCTTypeBulletproof2 || rv.type == rct::RCTTypeCLSAG || rv.type == rct::RCTTypeBulletproofPlus)
3172 {
3173 CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys");
3174 rv.mixRing.resize(pubkeys.size());
3175 for (size_t n = 0; n < pubkeys.size(); ++n)
3176 {
3177 rv.mixRing[n].clear();
3178 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3179 {
3180 rv.mixRing[n].push_back(pubkeys[n][m]);
3181 }
3182 }
3183 }
3184 else
3185 {
3186 CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type));
3187 }
3188
3189 // II
3190 if (rv.type == rct::RCTTypeFull)
3191 {
3192 if (!tx.pruned)
3193 {
3194 rv.p.MGs.resize(1);
3195 rv.p.MGs[0].II.resize(tx.vin.size());
3196 for (size_t n = 0; n < tx.vin.size(); ++n)
3197 rv.p.MGs[0].II[n] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3198 }
3199 }
3200 else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof || rv.type == rct::RCTTypeBulletproof2)
3201 {
3202 if (!tx.pruned)
3203 {
3204 CHECK_AND_ASSERT_MES(rv.p.MGs.size() == tx.vin.size(), false, "Bad MGs size");
3205 for (size_t n = 0; n < tx.vin.size(); ++n)
3206 {
3207 rv.p.MGs[n].II.resize(1);
3208 rv.p.MGs[n].II[0] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3209 }
3210 }
3211 }
3212 else if (rv.type == rct::RCTTypeCLSAG || rv.type == rct::RCTTypeBulletproofPlus)
3213 {
3214 if (!tx.pruned)
3215 {
3216 CHECK_AND_ASSERT_MES(rv.p.CLSAGs.size() == tx.vin.size(), false, "Bad CLSAGs size");
3217 for (size_t n = 0; n < tx.vin.size(); ++n)
3218 {
3219 rv.p.CLSAGs[n].I = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3220 }
3221 }
3222 }
3223 else
3224 {
3225 CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type));
3226 }
3227
3228 // outPk was already done by handle_incoming_tx
3229
3230 return true;
3231 }
3232 //------------------------------------------------------------------
3233 // This function validates transaction inputs and their keys.
3234 // FIXME: consider moving functionality specific to one input into
3235 // check_tx_input() rather than here, and use this function simply
3236 // to iterate the inputs as necessary (splitting the task
3237 // using threads, etc.)
3238 bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height) const
3239 {
3240 PERF_TIMER(check_tx_inputs);
3241 LOG_PRINT_L3("Blockchain::" << __func__);
3242 size_t sig_index = 0;
3243 if(pmax_used_block_height)
3244 *pmax_used_block_height = 0;
3245
3246 crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx);
3247
3248 const uint8_t hf_version = m_hardfork->get_current_version();
3249
3250 if (hf_version >= HF_VERSION_MIN_2_OUTPUTS)
3251 {
3252 if (tx.version >= 2)
3253 {
3254 if (tx.vout.size() < 2)
3255 {
3256 MERROR_VER("Tx " << get_transaction_hash(tx) << " has fewer than two outputs");
3257 tvc.m_too_few_outputs = true;
3258 return false;
3259 }
3260 }
3261 }
3262
3263 // from hard fork 2, we require mixin at least 2 unless one output cannot mix with 2 others
3264 // if one output cannot mix with 2 others, we accept at most 1 output that can mix
3265 if (hf_version >= 2)
3266 {
3267 size_t n_unmixable = 0, n_mixable = 0;
3268 size_t min_actual_mixin = std::numeric_limits<size_t>::max();
3269 size_t max_actual_mixin = 0;
3270 const size_t min_mixin = hf_version >= HF_VERSION_MIN_MIXIN_15 ? 15 : hf_version >= HF_VERSION_MIN_MIXIN_10 ? 10 : hf_version >= HF_VERSION_MIN_MIXIN_6 ? 6 : hf_version >= HF_VERSION_MIN_MIXIN_4 ? 4 : 2;
3271 for (const auto& txin : tx.vin)
3272 {
3273 // non txin_to_key inputs will be rejected below
3274 if (txin.type() == typeid(txin_to_key))
3275 {
3276 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3277 if (in_to_key.amount == 0)
3278 {
3279 // always consider rct inputs mixable. Even if there's not enough rct
3280 // inputs on the chain to mix with, this is going to be the case for
3281 // just a few blocks right after the fork at most
3282 ++n_mixable;
3283 }
3284 else
3285 {
3286 uint64_t n_outputs = m_db->get_num_outputs(in_to_key.amount);
3287 MDEBUG("output size " << print_money(in_to_key.amount) << ": " << n_outputs << " available");
3288 // n_outputs includes the output we're considering
3289 if (n_outputs <= min_mixin)
3290 ++n_unmixable;
3291 else
3292 ++n_mixable;
3293 }
3294 size_t ring_mixin = in_to_key.key_offsets.size() - 1;
3295 if (ring_mixin < min_actual_mixin)
3296 min_actual_mixin = ring_mixin;
3297 if (ring_mixin > max_actual_mixin)
3298 max_actual_mixin = ring_mixin;
3299 }
3300 }
3301 MDEBUG("Mixin: " << min_actual_mixin << "-" << max_actual_mixin);
3302
3303 if (hf_version >= HF_VERSION_SAME_MIXIN)
3304 {
3305 if (min_actual_mixin != max_actual_mixin)
3306 {
3307 MERROR_VER("Tx " << get_transaction_hash(tx) << " has varying ring size (" << (min_actual_mixin + 1) << "-" << (max_actual_mixin + 1) << "), it should be constant");
3308 tvc.m_low_mixin = true;
3309 return false;
3310 }
3311 }
3312
3313 // The only circumstance where ring sizes less than expected are
3314 // allowed is when spending unmixable non-RCT outputs in the chain.
3315 // Caveat: at HF_VERSION_MIN_MIXIN_15, temporarily allow ring sizes
3316 // of 11 to allow a grace period in the transition to larger ring size.
3317 if (min_actual_mixin < min_mixin && !(hf_version == HF_VERSION_MIN_MIXIN_15 && min_actual_mixin == 10))
3318 {
3319 if (n_unmixable == 0)
3320 {
3321 MERROR_VER("Tx " << get_transaction_hash(tx) << " has too low ring size (" << (min_actual_mixin + 1) << "), and no unmixable inputs");
3322 tvc.m_low_mixin = true;
3323 return false;
3324 }
3325 if (n_mixable > 1)
3326 {
3327 MERROR_VER("Tx " << get_transaction_hash(tx) << " has too low ring size (" << (min_actual_mixin + 1) << "), and more than one mixable input with unmixable inputs");
3328 tvc.m_low_mixin = true;
3329 return false;
3330 }
3331 } else if ((hf_version > HF_VERSION_MIN_MIXIN_15 && min_actual_mixin > 15)
3332 || (hf_version == HF_VERSION_MIN_MIXIN_15 && min_actual_mixin != 15 && min_actual_mixin != 10) // grace period to allow either 15 or 10
3333 || (hf_version < HF_VERSION_MIN_MIXIN_15 && hf_version >= HF_VERSION_MIN_MIXIN_10+2 && min_actual_mixin > 10)
3334 || ((hf_version == HF_VERSION_MIN_MIXIN_10 || hf_version == HF_VERSION_MIN_MIXIN_10+1) && min_actual_mixin != 10)
3335 )
3336 {
3337 MERROR_VER("Tx " << get_transaction_hash(tx) << " has invalid ring size (" << (min_actual_mixin + 1) << "), it should be " << (min_mixin + 1));
3338 tvc.m_low_mixin = true;
3339 return false;
3340 }
3341
3342 // min/max tx version based on HF, and we accept v1 txes if having a non mixable
3343 const size_t max_tx_version = (hf_version <= 3) ? 1 : 2;
3344 if (tx.version > max_tx_version)
3345 {
3346 MERROR_VER("transaction version " << (unsigned)tx.version << " is higher than max accepted version " << max_tx_version);
3347 tvc.m_verifivation_failed = true;
3348 return false;
3349 }
3350 const size_t min_tx_version = (n_unmixable > 0 ? 1 : (hf_version >= HF_VERSION_ENFORCE_RCT) ? 2 : 1);
3351 if (tx.version < min_tx_version)
3352 {
3353 MERROR_VER("transaction version " << (unsigned)tx.version << " is lower than min accepted version " << min_tx_version);
3354 tvc.m_verifivation_failed = true;
3355 return false;
3356 }
3357 }
3358
3359 // from v7, sorted ins
3360 if (hf_version >= 7) {
3361 const crypto::key_image *last_key_image = NULL;
3362 for (size_t n = 0; n < tx.vin.size(); ++n)
3363 {
3364 const txin_v &txin = tx.vin[n];
3365 if (txin.type() == typeid(txin_to_key))
3366 {
3367 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3368 if (last_key_image && memcmp(&in_to_key.k_image, last_key_image, sizeof(*last_key_image)) >= 0)
3369 {
3370 MERROR_VER("transaction has unsorted inputs");
3371 tvc.m_verifivation_failed = true;
3372 return false;
3373 }
3374 last_key_image = &in_to_key.k_image;
3375 }
3376 }
3377 }
3378
3379 std::vector<std::vector<rct::ctkey>> pubkeys(tx.vin.size());
3380 std::vector < uint64_t > results;
3381 results.resize(tx.vin.size(), 0);
3382
3383 tools::threadpool& tpool = tools::threadpool::getInstanceForCompute();
3384 tools::threadpool::waiter waiter(tpool);
3385 int threads = tpool.get_max_concurrency();
3386
3387 uint64_t max_used_block_height = 0;
3388 if (!pmax_used_block_height)
3389 pmax_used_block_height = &max_used_block_height;
3390 for (const auto& txin : tx.vin)
3391 {
3392 // make sure output being spent is of type txin_to_key, rather than
3393 // e.g. txin_gen, which is only used for miner transactions
3394 CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at Blockchain::check_tx_inputs");
3395 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3396
3397 // make sure tx output has key offset(s) (is signed to be used)
3398 CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "empty in_to_key.key_offsets in transaction with id " << get_transaction_hash(tx));
3399
3400 if(have_tx_keyimg_as_spent(in_to_key.k_image))
3401 {
3402 MERROR_VER("Key image already spent in blockchain: " << epee::string_tools::pod_to_hex(in_to_key.k_image));
3403 tvc.m_double_spend = true;
3404 return false;
3405 }
3406
3407 if (tx.version == 1)
3408 {
3409 // basically, make sure number of inputs == number of signatures
3410 CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index);
3411 }
3412
3413 // make sure that output being spent matches up correctly with the
3414 // signature spending it.
3415 if (!check_tx_input(tx.version, in_to_key, tx_prefix_hash, tx.version == 1 ? tx.signatures[sig_index] : std::vector<crypto::signature>(), tx.rct_signatures, pubkeys[sig_index], pmax_used_block_height, hf_version))
3416 {
3417 MERROR_VER("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index);
3418 if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain()
3419 {
3420 MERROR_VER(" *pmax_used_block_height: " << *pmax_used_block_height);
3421 }
3422
3423 return false;
3424 }
3425
3426 if (tx.version == 1)
3427 {
3428 if (threads > 1)
3429 {
3430 // ND: Speedup
3431 // 1. Thread ring signature verification if possible.
3432 tpool.submit(&waiter, boost::bind(&Blockchain::check_ring_signature, this, std::cref(tx_prefix_hash), std::cref(in_to_key.k_image), std::cref(pubkeys[sig_index]), std::cref(tx.signatures[sig_index]), std::ref(results[sig_index])), true);
3433 }
3434 else
3435 {
3436 check_ring_signature(tx_prefix_hash, in_to_key.k_image, pubkeys[sig_index], tx.signatures[sig_index], results[sig_index]);
3437 if (!results[sig_index])
3438 {
3439 MERROR_VER("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index);
3440
3441 if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain()
3442 {
3443 MERROR_VER("*pmax_used_block_height: " << *pmax_used_block_height);
3444 }
3445
3446 return false;
3447 }
3448 }
3449 }
3450
3451 sig_index++;
3452 }
3453 if (tx.version == 1 && threads > 1)
3454 if (!waiter.wait())
3455 return false;
3456
3457 // enforce min output age
3458 if (hf_version >= HF_VERSION_ENFORCE_MIN_AGE)
3459 {
3460 CHECK_AND_ASSERT_MES(*pmax_used_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= m_db->height(),
3461 false, "Transaction spends at least one output which is too young");
3462 }
3463
3464 // Warn that new RCT types are present, and thus the cache is not being used effectively
3465 static constexpr const std::uint8_t RCT_CACHE_TYPE = rct::RCTTypeBulletproofPlus;
3466 if (tx.rct_signatures.type > RCT_CACHE_TYPE)
3467 {
3468 MWARNING("RCT cache is not caching new verification results. Please update RCT_CACHE_TYPE!");
3469 }
3470
3471 if (tx.version == 1)
3472 {
3473 if (threads > 1)
3474 {
3475 // save results to table, passed or otherwise
3476 bool failed = false;
3477 for (size_t i = 0; i < tx.vin.size(); i++)
3478 {
3479 if(!failed && !results[i])
3480 failed = true;
3481 }
3482
3483 if (failed)
3484 {
3485 MERROR_VER("Failed to check ring signatures!");
3486 return false;
3487 }
3488 }
3489 }
3490 else
3491 {
3492 // from version 2, check ringct signatures
3493 // obviously, the original and simple rct APIs use a mixRing that's indexes
3494 // in opposite orders, because it'd be too simple otherwise...
3495 const rct::rctSig &rv = tx.rct_signatures;
3496 switch (rv.type)
3497 {
3498 case rct::RCTTypeNull: {
3499 // we only accept no signatures for coinbase txes
3500 MERROR_VER("Null rct signature on non-coinbase tx");
3501 return false;
3502 }
3503 case rct::RCTTypeSimple:
3504 case rct::RCTTypeBulletproof:
3505 case rct::RCTTypeBulletproof2:
3506 case rct::RCTTypeCLSAG:
3507 case rct::RCTTypeBulletproofPlus:
3508 {
3509 if (!ver_rct_non_semantics_simple_cached(tx, pubkeys, m_rct_ver_cache, RCT_CACHE_TYPE))
3510 {
3511 MERROR_VER("Failed to check ringct signatures!");
3512 return false;
3513 }
3514 break;
3515 }
3516 case rct::RCTTypeFull:
3517 {
3518 if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys))
3519 {
3520 MERROR_VER("Failed to expand rct signatures!");
3521 return false;
3522 }
3523
3524 // check all this, either reconstructed (so should really pass), or not
3525 {
3526 bool size_matches = true;
3527 for (size_t i = 0; i < pubkeys.size(); ++i)
3528 size_matches &= pubkeys[i].size() == rv.mixRing.size();
3529 for (size_t i = 0; i < rv.mixRing.size(); ++i)
3530 size_matches &= pubkeys.size() == rv.mixRing[i].size();
3531 if (!size_matches)
3532 {
3533 MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size");
3534 return false;
3535 }
3536
3537 for (size_t n = 0; n < pubkeys.size(); ++n)
3538 {
3539 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3540 {
3541 if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest))
3542 {
3543 MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m);
3544 return false;
3545 }
3546 if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask))
3547 {
3548 MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m);
3549 return false;
3550 }
3551 }
3552 }
3553 }
3554
3555 if (rv.p.MGs.size() != 1)
3556 {
3557 MERROR_VER("Failed to check ringct signatures: Bad MGs size");
3558 return false;
3559 }
3560 if (rv.p.MGs.empty() || rv.p.MGs[0].II.size() != tx.vin.size())
3561 {
3562 MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes");
3563 return false;
3564 }
3565 for (size_t n = 0; n < tx.vin.size(); ++n)
3566 {
3567 if (memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32))
3568 {
3569 MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes");
3570 return false;
3571 }
3572 }
3573
3574 if (!rct::verRct(rv, false))
3575 {
3576 MERROR_VER("Failed to check ringct signatures!");
3577 return false;
3578 }
3579 break;
3580 }
3581 default:
3582 MERROR_VER("Unsupported rct type: " << rv.type);
3583 return false;
3584 }
3585
3586 // for bulletproofs, check they're only multi-output after v8
3587 if (rct::is_rct_bulletproof(rv.type))
3588 {
3589 if (hf_version < 8)
3590 {
3591 for (const rct::Bulletproof &proof: rv.p.bulletproofs)
3592 {
3593 if (proof.V.size() > 1)
3594 {
3595 MERROR_VER("Multi output bulletproofs are invalid before v8");
3596 return false;
3597 }
3598 }
3599 }
3600 }
3601 }
3602 return true;
3603 }
3604
3605 //------------------------------------------------------------------
3606 void Blockchain::check_ring_signature(const crypto::hash &tx_prefix_hash, const crypto::key_image &key_image, const std::vector<rct::ctkey> &pubkeys, const std::vector<crypto::signature>& sig, uint64_t &result) const
3607 {
3608 std::vector<const crypto::public_key *> p_output_keys;
3609 p_output_keys.reserve(pubkeys.size());
3610 for (auto &key : pubkeys)
3611 {
3612 // rct::key and crypto::public_key have the same structure, avoid object ctor/memcpy
3613 p_output_keys.push_back(&(const crypto::public_key&)key.dest);
3614 }
3615
3616 result = crypto::check_ring_signature(tx_prefix_hash, key_image, p_output_keys, sig.data()) ? 1 : 0;
3617 }
3618
3619 //------------------------------------------------------------------
3620 uint64_t Blockchain::get_dynamic_base_fee(uint64_t block_reward, size_t median_block_weight, uint8_t version)
3621 {
3622 const uint64_t min_block_weight = get_min_block_weight(version);
3623 if (median_block_weight < min_block_weight)
3624 median_block_weight = min_block_weight;
3625 uint64_t hi, lo;
3626
3627 if (version >= HF_VERSION_PER_BYTE_FEE)
3628 {
3629 lo = mul128(block_reward, DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT, &hi);
3630 div128_64(hi, lo, median_block_weight, &hi, &lo, NULL, NULL);
3631 if (version >= HF_VERSION_2021_SCALING)
3632 {
3633 // min_fee_per_byte = round_up( 0.95 * block_reward * ref_weight / (fee_median^2) )
3634 // note: since hardfork HF_VERSION_2021_SCALING, fee_median (a.k.a. median_block_weight) equals effective long term median
3635 div128_64(hi, lo, median_block_weight, &hi, &lo, NULL, NULL);
3636 assert(hi == 0);
3637 lo -= lo / 20;
3638 return lo == 0 ? 1 : lo;
3639 }
3640 else
3641 {
3642 // min_fee_per_byte = 0.2 * block_reward * ref_weight / (min_penalty_free_zone * fee_median)
3643 div128_64(hi, lo, min_block_weight, &hi, &lo, NULL, NULL);
3644 assert(hi == 0);
3645 lo /= 5;
3646 return lo;
3647 }
3648 }
3649
3650 const uint64_t fee_base = version >= 5 ? DYNAMIC_FEE_PER_KB_BASE_FEE_V5 : DYNAMIC_FEE_PER_KB_BASE_FEE;
3651
3652 uint64_t unscaled_fee_base = (fee_base * min_block_weight / median_block_weight);
3653 lo = mul128(unscaled_fee_base, block_reward, &hi);
3654 div128_64(hi, lo, DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD, &hi, &lo, NULL, NULL);
3655 assert(hi == 0);
3656
3657 // quantize fee up to 8 decimals
3658 uint64_t mask = get_fee_quantization_mask();
3659 uint64_t qlo = (lo + mask - 1) / mask * mask;
3660 MDEBUG("lo " << print_money(lo) << ", qlo " << print_money(qlo) << ", mask " << mask);
3661
3662 return qlo;
3663 }
3664
3665 //------------------------------------------------------------------
3666 bool Blockchain::check_fee(size_t tx_weight, uint64_t fee) const
3667 {
3668 const uint8_t version = get_current_hard_fork_version();
3669
3670 uint64_t median = 0;
3671 uint64_t already_generated_coins = 0;
3672 uint64_t base_reward = 0;
3673 if (version >= HF_VERSION_DYNAMIC_FEE)
3674 {
3675 median = m_current_block_cumul_weight_limit / 2;
3676 const uint64_t blockchain_height = m_db->height();
3677 already_generated_coins = blockchain_height ? m_db->get_block_already_generated_coins(blockchain_height - 1) : 0;
3678 if (!get_block_reward(median, 1, already_generated_coins, base_reward, version))
3679 return false;
3680 }
3681
3682 uint64_t needed_fee;
3683 if (version >= HF_VERSION_PER_BYTE_FEE)
3684 {
3685 const bool use_long_term_median_in_fee = version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT;
3686 uint64_t fee_per_byte = get_dynamic_base_fee(base_reward, use_long_term_median_in_fee ? std::min<uint64_t>(median, m_long_term_effective_median_block_weight) : median, version);
3687 MDEBUG("Using " << print_money(fee_per_byte) << "/byte fee");
3688 needed_fee = tx_weight * fee_per_byte;
3689 // quantize fee up to 8 decimals
3690 const uint64_t mask = get_fee_quantization_mask();
3691 needed_fee = (needed_fee + mask - 1) / mask * mask;
3692 }
3693 else
3694 {
3695 uint64_t fee_per_kb;
3696 if (version < HF_VERSION_DYNAMIC_FEE)
3697 {
3698 fee_per_kb = FEE_PER_KB;
3699 }
3700 else
3701 {
3702 fee_per_kb = get_dynamic_base_fee(base_reward, median, version);
3703 }
3704 MDEBUG("Using " << print_money(fee_per_kb) << "/kB fee");
3705
3706 needed_fee = tx_weight / 1024;
3707 needed_fee += (tx_weight % 1024) ? 1 : 0;
3708 needed_fee *= fee_per_kb;
3709 }
3710
3711 if (fee < needed_fee - needed_fee / 50) // keep a little 2% buffer on acceptance - no integer overflow
3712 {
3713 MERROR_VER("transaction fee is not enough: " << print_money(fee) << ", minimum fee: " << print_money(needed_fee));
3714 return false;
3715 }
3716 return true;
3717 }
3718
3719 //------------------------------------------------------------------
3720 void Blockchain::get_dynamic_base_fee_estimate_2021_scaling(uint64_t grace_blocks, uint64_t base_reward, uint64_t Mnw, uint64_t Mlw, std::vector<uint64_t> &fees) const
3721 {
3722 // variable names and calculations as per https://github.com/ArticMine/Monero-Documents/blob/master/MoneroScaling2021-02.pdf
3723 // from (earlier than) this fork, the base fee is per byte
3724 const uint64_t Mfw = std::min(Mnw, Mlw);
3725
3726 // 3 kB divided by something ? It's going to be either 0 or *very* quantized, so fold it into integer steps below
3727 //const uint64_t Brlw = DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / Mfw;
3728
3729 // constant.... equal to 0, unless floating point, so fold it into integer steps below
3730 //const uint64_t Br = DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5
3731
3732 //const uint64_t Fl = base_reward * Brlw / Mfw; fold Brlw from above
3733 const uint64_t Fl = base_reward * /*Brlw*/ DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (Mfw * Mfw);
3734
3735 // fold Fl into this for better precision (and to match the test cases in the PDF)
3736 // const uint64_t Fn = 4 * Fl;
3737 const uint64_t Fn = 4 * base_reward * /*Brlw*/ DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (Mfw * Mfw);
3738
3739 // const uint64_t Fm = 16 * base_reward * Br / Mfw; fold Br from above
3740 const uint64_t Fm = 16 * base_reward * DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5 * Mfw);
3741
3742 // const uint64_t Fp = 2 * base_reward / Mnw;
3743
3744 // fold Br from above, move 4Fm in the max to decrease quantization effect
3745 //const uint64_t Fh = 4 * Fm * std::max<uint64_t>(1, Mfw / (32 * DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT * Mnw / CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5));
3746 const uint64_t Fh = std::max<uint64_t>(4 * Fm, 4 * Fm * Mfw / (32 * DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT * Mnw / CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5));
3747
3748 fees.resize(4);
3749 fees[0] = cryptonote::round_money_up(Fl, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3750 fees[1] = cryptonote::round_money_up(Fn, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3751 fees[2] = cryptonote::round_money_up(Fm, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3752 fees[3] = cryptonote::round_money_up(Fh, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3753 }
3754
3755 void Blockchain::get_dynamic_base_fee_estimate_2021_scaling(uint64_t grace_blocks, std::vector<uint64_t> &fees) const
3756 {
3757 const uint8_t version = get_current_hard_fork_version();
3758 const uint64_t db_height = m_db->height();
3759
3760 CHECK_AND_ASSERT_THROW_MES(grace_blocks <= CRYPTONOTE_REWARD_BLOCKS_WINDOW, "Grace blocks invalid In 2021 fee scaling estimate.");
3761
3762 // we want Mlw = median of max((min(Mbw, 1.7 * Ml), Zm), Ml / 1.7)
3763 // Mbw: block weight for the last 99990 blocks, 0 for the next 10
3764 // Ml: penalty free zone (dynamic), aka long_term_median, aka median of max((min(Mb, 1.7 * Ml), Zm), Ml / 1.7)
3765 // Zm: 300000 (minimum penalty free zone)
3766 //
3767 // So we copy the current rolling median state, add 10 (grace_blocks) zeroes to it, and get back Mlw
3768
3769 epee::misc_utils::rolling_median_t<uint64_t> rm = m_long_term_block_weights_cache_rolling_median;
3770 for (size_t i = 0; i < grace_blocks; ++i)
3771 rm.insert(0);
3772 const uint64_t Mlw_penalty_free_zone_for_wallet = std::max<uint64_t>(rm.median(), CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5);
3773
3774 // Msw: median over [100 - grace blocks] past + [grace blocks] future blocks
3775 std::vector<uint64_t> weights;
3776 get_last_n_blocks_weights(weights, 100 - grace_blocks);
3777 weights.reserve(100);
3778 for (size_t i = 0; i < grace_blocks; ++i)
3779 weights.push_back(0);
3780 const uint64_t Msw_effective_short_term_median = std::max(epee::misc_utils::median(weights), Mlw_penalty_free_zone_for_wallet);
3781
3782 const uint64_t Mnw = std::min(Msw_effective_short_term_median, 50 * Mlw_penalty_free_zone_for_wallet);
3783
3784 uint64_t already_generated_coins = db_height ? m_db->get_block_already_generated_coins(db_height - 1) : 0;
3785 uint64_t base_reward;
3786 if (!get_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, version))
3787 {
3788 MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound");
3789 base_reward = BLOCK_REWARD_OVERESTIMATE;
3790 }
3791
3792 get_dynamic_base_fee_estimate_2021_scaling(grace_blocks, base_reward, Mnw, Mlw_penalty_free_zone_for_wallet, fees);
3793 }
3794
3795 //------------------------------------------------------------------
3796 uint64_t Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_blocks) const
3797 {
3798 const uint8_t version = get_current_hard_fork_version();
3799 const uint64_t db_height = m_db->height();
3800
3801 if (version < HF_VERSION_DYNAMIC_FEE)
3802 return FEE_PER_KB;
3803
3804 if (grace_blocks >= CRYPTONOTE_REWARD_BLOCKS_WINDOW)
3805 grace_blocks = CRYPTONOTE_REWARD_BLOCKS_WINDOW - 1;
3806
3807 if (version >= HF_VERSION_2021_SCALING)
3808 {
3809 std::vector<uint64_t> fees;
3810 get_dynamic_base_fee_estimate_2021_scaling(grace_blocks, fees);
3811 return fees[0];
3812 }
3813
3814 const uint64_t min_block_weight = get_min_block_weight(version);
3815 std::vector<uint64_t> weights;
3816 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW - grace_blocks);
3817 weights.reserve(grace_blocks);
3818 for (size_t i = 0; i < grace_blocks; ++i)
3819 weights.push_back(min_block_weight);
3820
3821 uint64_t median = epee::misc_utils::median(weights);
3822 if(median <= min_block_weight)
3823 median = min_block_weight;
3824
3825 uint64_t already_generated_coins = db_height ? m_db->get_block_already_generated_coins(db_height - 1) : 0;
3826 uint64_t base_reward;
3827 if (!get_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, version))
3828 {
3829 MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound");
3830 base_reward = BLOCK_REWARD_OVERESTIMATE;
3831 }
3832
3833 const bool use_long_term_median_in_fee = version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT;
3834 const uint64_t use_median_value = use_long_term_median_in_fee ? std::min<uint64_t>(median, m_long_term_effective_median_block_weight) : median;
3835 const uint64_t fee = get_dynamic_base_fee(base_reward, use_median_value, version);
3836 const bool per_byte = version < HF_VERSION_PER_BYTE_FEE;
3837 MDEBUG("Estimating " << grace_blocks << "-block fee at " << print_money(fee) << "/" << (per_byte ? "byte" : "kB"));
3838 return fee;
3839 }
3840
3841 //------------------------------------------------------------------
3842 // This function checks to see if a tx is unlocked. unlock_time is either
3843 // a block index or a unix time.
3844 bool Blockchain::is_tx_spendtime_unlocked(uint64_t unlock_time, uint8_t hf_version) const
3845 {
3846 LOG_PRINT_L3("Blockchain::" << __func__);
3847 if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
3848 {
3849 // ND: Instead of calling get_current_blockchain_height(), call m_db->height()
3850 // directly as get_current_blockchain_height() locks the recursive mutex.
3851 if(m_db->height()-1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time)
3852 return true;
3853 else
3854 return false;
3855 }
3856 else
3857 {
3858 //interpret as time
3859 const uint64_t current_time = hf_version >= HF_VERSION_DETERMINISTIC_UNLOCK_TIME ? get_adjusted_time(m_db->height()) : static_cast<uint64_t>(time(NULL));
3860 if(current_time + (get_current_hard_fork_version() < 2 ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2) >= unlock_time)
3861 return true;
3862 else
3863 return false;
3864 }
3865 return false;
3866 }
3867 //------------------------------------------------------------------
3868 // This function locates all outputs associated with a given input (mixins)
3869 // and validates that they exist and are usable. It also checks the ring
3870 // signature for each input.
3871 bool Blockchain::check_tx_input(size_t tx_version, const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, const rct::rctSig &rct_signatures, std::vector<rct::ctkey> &output_keys, uint64_t* pmax_related_block_height, uint8_t hf_version) const
3872 {
3873 LOG_PRINT_L3("Blockchain::" << __func__);
3874
3875 // ND:
3876 // 1. Disable locking and make method private.
3877 //CRITICAL_REGION_LOCAL(m_blockchain_lock);
3878
3879 struct outputs_visitor
3880 {
3881 std::vector<rct::ctkey >& m_output_keys;
3882 const Blockchain& m_bch;
3883 const uint8_t hf_version;
3884 outputs_visitor(std::vector<rct::ctkey>& output_keys, const Blockchain& bch, uint8_t hf_version) :
3885 m_output_keys(output_keys), m_bch(bch), hf_version(hf_version)
3886 {
3887 }
3888 bool handle_output(uint64_t unlock_time, const crypto::public_key &pubkey, const rct::key &commitment)
3889 {
3890 //check tx unlock time
3891 if (!m_bch.is_tx_spendtime_unlocked(unlock_time, hf_version))
3892 {
3893 MERROR_VER("One of outputs for one of inputs has wrong tx.unlock_time = " << unlock_time);
3894 return false;
3895 }
3896
3897 // The original code includes a check for the output corresponding to this input
3898 // to be a txout_to_key. This is removed, as the database does not store this info.
3899 // Only txout_to_key (and since HF_VERSION_VIEW_TAGS, txout_to_tagged_key)
3900 // outputs are stored in the DB in the first place, done in Blockchain*::add_output.
3901 // Additional type checks on outputs were also added via cryptonote::check_output_types
3902 // and cryptonote::get_output_public_key (see Blockchain::check_tx_outputs).
3903
3904 m_output_keys.push_back(rct::ctkey({rct::pk2rct(pubkey), commitment}));
3905 return true;
3906 }
3907 };
3908
3909 output_keys.clear();
3910
3911 // collect output keys
3912 outputs_visitor vi(output_keys, *this, hf_version);
3913 if (!scan_outputkeys_for_indexes(tx_version, txin, vi, tx_prefix_hash, pmax_related_block_height))
3914 {
3915 MERROR_VER("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size());
3916 return false;
3917 }
3918
3919 if(txin.key_offsets.size() != output_keys.size())
3920 {
3921 MERROR_VER("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size());
3922 return false;
3923 }
3924 if (tx_version == 1) {
3925 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());
3926 }
3927 // rct_signatures will be expanded after this
3928 return true;
3929 }
3930 //------------------------------------------------------------------
3931 // only works on the main chain
3932 uint64_t Blockchain::get_adjusted_time(uint64_t height) const
3933 {
3934 LOG_PRINT_L3("Blockchain::" << __func__);
3935
3936 // if not enough blocks, no proper median yet, return current time
3937 if(height < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
3938 {
3939 return static_cast<uint64_t>(time(NULL));
3940 }
3941 std::vector<uint64_t> timestamps;
3942
3943 // need most recent 60 blocks, get index of first of those
3944 size_t offset = height - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW;
3945 timestamps.reserve(height - offset);
3946 for(;offset < height; ++offset)
3947 {
3948 timestamps.push_back(m_db->get_block_timestamp(offset));
3949 }
3950 uint64_t median_ts = epee::misc_utils::median(timestamps);
3951
3952 // project the median to match approximately when the block being validated will appear
3953 // the median is calculated from a chunk of past blocks, so we use +1 to offset onto the current block
3954 median_ts += (BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW + 1) * DIFFICULTY_TARGET_V2 / 2;
3955
3956 // project the current block's time based on the previous block's time
3957 // we don't use the current block's time directly to mitigate timestamp manipulation
3958 uint64_t adjusted_current_block_ts = timestamps.back() + DIFFICULTY_TARGET_V2;
3959
3960 // return minimum of ~current block time and adjusted median time
3961 // we do this since it's better to report a time in the past than a time in the future
3962 return (adjusted_current_block_ts < median_ts ? adjusted_current_block_ts : median_ts);
3963 }
3964 //------------------------------------------------------------------
3965 //TODO: revisit, has changed a bit on upstream
3966 bool Blockchain::check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b, uint64_t& median_ts) const
3967 {
3968 LOG_PRINT_L3("Blockchain::" << __func__);
3969 median_ts = epee::misc_utils::median(timestamps);
3970
3971 if(b.timestamp < median_ts)
3972 {
3973 MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts);
3974 return false;
3975 }
3976
3977 return true;
3978 }
3979 //------------------------------------------------------------------
3980 // This function grabs the timestamps from the most recent <n> blocks,
3981 // where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many
3982 // blocks in the blockchain, the timestap is assumed to be valid. If there
3983 // are, this function returns:
3984 // true if the block's timestamp is not less than the timestamp of the
3985 // median of the selected blocks
3986 // false otherwise
3987 bool Blockchain::check_block_timestamp(const block& b, uint64_t& median_ts) const
3988 {
3989 LOG_PRINT_L3("Blockchain::" << __func__);
3990 if(b.timestamp > (uint64_t)time(NULL) + CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT)
3991 {
3992 MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than local time + 2 hours");
3993 return false;
3994 }
3995
3996 const auto h = m_db->height();
3997
3998 // if not enough blocks, no proper median yet, return true
3999 if(h < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
4000 {
4001 return true;
4002 }
4003
4004 std::vector<uint64_t> timestamps;
4005
4006 // need most recent 60 blocks, get index of first of those
4007 size_t offset = h - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW;
4008 timestamps.reserve(h - offset);
4009 for(;offset < h; ++offset)
4010 {
4011 timestamps.push_back(m_db->get_block_timestamp(offset));
4012 }
4013
4014 return check_block_timestamp(timestamps, b, median_ts);
4015 }
4016 //------------------------------------------------------------------
4017 bool Blockchain::flush_txes_from_pool(const std::vector<crypto::hash> &txids)
4018 {
4019 CRITICAL_REGION_LOCAL(m_tx_pool);
4020
4021 bool res = true;
4022 for (const auto &txid: txids)
4023 {
4024 cryptonote::transaction tx;
4025 cryptonote::blobdata txblob;
4026 size_t tx_weight;
4027 uint64_t fee;
4028 bool relayed, do_not_relay, double_spend_seen, pruned;
4029 MINFO("Removing txid " << txid << " from the pool");
4030 if(m_tx_pool.have_tx(txid, relay_category::all) && !m_tx_pool.take_tx(txid, tx, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen, pruned))
4031 {
4032 MERROR("Failed to remove txid " << txid << " from the pool");
4033 res = false;
4034 }
4035 }
4036 return res;
4037 }
4038 //------------------------------------------------------------------
4039 // Needs to validate the block and acquire each transaction from the
4040 // transaction mem_pool, then pass the block and transactions to
4041 // m_db->add_block()
4042 bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id,
4043 block_verification_context& bvc, pool_supplement& extra_block_txs)
4044 {
4045 LOG_PRINT_L3("Blockchain::" << __func__);
4046
4047 TIME_MEASURE_START(block_processing_time);
4048 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4049 TIME_MEASURE_START(t1);
4050
4051 static bool seen_future_version = false;
4052
4053 db_rtxn_guard rtxn_guard(m_db);
4054 uint64_t blockchain_height;
4055 const crypto::hash top_hash = get_tail_id(blockchain_height);
4056 ++blockchain_height; // block height to chain height
4057 if(bl.prev_id != top_hash)
4058 {
4059 MERROR_VER("Block with id: " << id << std::endl << "has wrong prev_id: " << bl.prev_id << std::endl << "expected: " << top_hash);
4060 bvc.m_verifivation_failed = true;
4061 leave:
4062 return false;
4063 }
4064
4065 // warn users if they're running an old version
4066 if (!seen_future_version && bl.major_version > m_hardfork->get_ideal_version())
4067 {
4068 seen_future_version = true;
4069 const el::Level level = el::Level::Warning;
4070 MCLOG_RED(level, "global", "**********************************************************************");
4071 MCLOG_RED(level, "global", "A block was seen on the network with a version higher than the last");
4072 MCLOG_RED(level, "global", "known one. This may be an old version of the daemon, and a software");
4073 MCLOG_RED(level, "global", "update may be required to sync further. Try running: update check");
4074 MCLOG_RED(level, "global", "**********************************************************************");
4075 }
4076
4077 // this is a cheap test
4078 const uint8_t hf_version = get_current_hard_fork_version();
4079 if (!m_hardfork->check(bl))
4080 {
4081 MERROR_VER("Block with id: " << id << std::endl << "has old version: " << (unsigned)bl.major_version << std::endl << "current: " << (unsigned)hf_version);
4082 bvc.m_verifivation_failed = true;
4083 goto leave;
4084 }
4085
4086 TIME_MEASURE_FINISH(t1);
4087 TIME_MEASURE_START(t2);
4088
4089 // make sure block timestamp is not less than the median timestamp
4090 // of a set number of the most recent blocks.
4091 if(!check_block_timestamp(bl))
4092 {
4093 MERROR_VER("Block with id: " << id << std::endl << "has invalid timestamp: " << bl.timestamp);
4094 bvc.m_verifivation_failed = true;
4095 goto leave;
4096 }
4097
4098 TIME_MEASURE_FINISH(t2);
4099 //check proof of work
4100 TIME_MEASURE_START(target_calculating_time);
4101
4102 // get the target difficulty for the block.
4103 // the calculation can overflow, among other failure cases,
4104 // so we need to check the return type.
4105 // FIXME: get_difficulty_for_next_block can also assert, look into
4106 // changing this to throwing exceptions instead so we can clean up.
4107 difficulty_type current_diffic = get_difficulty_for_next_block();
4108 CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!");
4109
4110 TIME_MEASURE_FINISH(target_calculating_time);
4111
4112 TIME_MEASURE_START(longhash_calculating_time);
4113
4114 crypto::hash proof_of_work;
4115 memset(proof_of_work.data, 0xff, sizeof(proof_of_work.data));
4116
4117 // Formerly the code below contained an if loop with the following condition
4118 // !m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height())
4119 // however, this caused the daemon to not bother checking PoW for blocks
4120 // before checkpoints, which is very dangerous behaviour. We moved the PoW
4121 // validation out of the next chunk of code to make sure that we correctly
4122 // check PoW now.
4123 // FIXME: height parameter is not used...should it be used or should it not
4124 // be a parameter?
4125 // validate proof_of_work versus difficulty target
4126 bool precomputed = false;
4127 bool fast_check = false;
4128 #if defined(PER_BLOCK_CHECKPOINT)
4129 if (blockchain_height < m_blocks_hash_check.size())
4130 {
4131 const auto &expected_hash = m_blocks_hash_check[blockchain_height].first;
4132 if (expected_hash != crypto::null_hash)
4133 {
4134 if (memcmp(&id, &expected_hash, sizeof(hash)) != 0)
4135 {
4136 MERROR_VER("Block with id is INVALID: " << id << ", expected " << expected_hash);
4137 bvc.m_verifivation_failed = true;
4138 goto leave;
4139 }
4140 fast_check = true;
4141 }
4142 else
4143 {
4144 MCINFO("verify", "No pre-validated hash at height " << blockchain_height << ", verifying fully");
4145 }
4146 }
4147 #endif
4148 if (!fast_check)
4149 {
4150 auto it = m_blocks_longhash_table.find(id);
4151 if (it != m_blocks_longhash_table.end())
4152 {
4153 precomputed = true;
4154 proof_of_work = it->second;
4155 }
4156 else
4157 proof_of_work = get_block_longhash(this, bl, blockchain_height, 0);
4158
4159 // validate proof_of_work versus difficulty target
4160 if(!check_hash(proof_of_work, current_diffic))
4161 {
4162 MERROR_VER("Block with id: " << id << std::endl << "does not have enough proof of work: " << proof_of_work << " at height " << blockchain_height << ", unexpected difficulty: " << current_diffic);
4163 bvc.m_verifivation_failed = true;
4164 bvc.m_bad_pow = true;
4165 goto leave;
4166 }
4167 }
4168
4169 // If we're at a checkpoint, ensure that our hardcoded checkpoint hash
4170 // is correct.
4171 if(m_checkpoints.is_in_checkpoint_zone(blockchain_height))
4172 {
4173 if(!m_checkpoints.check_block(blockchain_height, id))
4174 {
4175 LOG_ERROR("CHECKPOINT VALIDATION FAILED");
4176 bvc.m_verifivation_failed = true;
4177 goto leave;
4178 }
4179 }
4180
4181 TIME_MEASURE_FINISH(longhash_calculating_time);
4182 if (precomputed)
4183 longhash_calculating_time += m_fake_pow_calc_time;
4184
4185 TIME_MEASURE_START(t3);
4186
4187 // sanity check basic miner tx properties;
4188 if(!prevalidate_miner_transaction(bl, blockchain_height, hf_version))
4189 {
4190 MERROR_VER("Block with id: " << id << " failed to pass prevalidation");
4191 bvc.m_verifivation_failed = true;
4192 goto leave;
4193 }
4194
4195 // verify all non-input consensus rules for txs inside the pool supplement (if not inside checkpoint zone)
4196 #if defined(PER_BLOCK_CHECKPOINT)
4197 if (!fast_check)
4198 #endif
4199 {
4200 tx_verification_context tvc{};
4201 // If fail non-input consensus rule checking...
4202 if (!ver_non_input_consensus(extra_block_txs, tvc, hf_version))
4203 {
4204 MERROR_VER("Pool supplement provided for block with id: " << id << " failed to pass validation");
4205 bvc.m_verifivation_failed = true;
4206 goto leave;
4207 }
4208 }
4209
4210 size_t coinbase_weight = get_transaction_weight(bl.miner_tx);
4211 size_t cumulative_block_weight = coinbase_weight;
4212
4213 std::vector<std::pair<transaction, blobdata>> txs;
4214 // txid weight mempool?
4215 std::vector<std::tuple<crypto::hash, size_t, bool>> txs_meta;
4216
4217 // This will be the data sent to the ZMQ pool listeners for txs which skipped the mempool
4218 std::vector<txpool_event> txpool_events;
4219
4220 // this lambda returns relevant txs back to the mempool
4221 auto return_txs_to_pool = [this, &txs, &txs_meta, &hf_version]()
4222 {
4223 if (txs_meta.size() != txs.size())
4224 {
4225 MERROR("BUG: txs_meta and txs not matching size!!!");
4226 return;
4227 }
4228
4229 for (size_t i = 0; i < txs.size(); ++i)
4230 {
4231 // if this transaction wasn't ever in the pool, don't return it back to the pool
4232 const bool found_in_pool = std::get<2>(txs_meta[i]);
4233 if (!found_in_pool)
4234 continue;
4235
4236 transaction &tx = txs[i].first;
4237 const crypto::hash &txid = std::get<0>(txs_meta[i]);
4238 const blobdata &tx_blob = txs[i].second;
4239 const size_t tx_weight = std::get<1>(txs_meta[i]);
4240
4241 // We assume that if they were in a block, the transactions are already known to the network
4242 // as a whole. However, if we had mined that block, that might not be always true. Unlikely
4243 // though, and always relaying these again might cause a spike of traffic as many nodes
4244 // re-relay all the transactions in a popped block when a reorg happens. You might notice that
4245 // we also set the "nic_verified_hf_version" paramater. Since we know we took this transaction
4246 // from the mempool earlier in this function call, when the mempool has the same current fork
4247 // version, we can return it without re-verifying the consensus rules on it.
4248 cryptonote::tx_verification_context tvc{};
4249 if (!m_tx_pool.add_tx(tx, txid, tx_blob, tx_weight, tvc, relay_method::block, true,
4250 hf_version, hf_version))
4251 MERROR("Failed to return taken transaction with hash: " << txid << " to tx_pool");
4252 }
4253 };
4254
4255 key_images_container keys;
4256
4257 uint64_t fee_summary = 0;
4258 uint64_t t_checktx = 0;
4259 uint64_t t_exists = 0;
4260 uint64_t t_pool = 0;
4261 uint64_t t_dblspnd = 0;
4262 uint64_t n_pruned = 0;
4263 TIME_MEASURE_FINISH(t3);
4264
4265 // XXX old code adds miner tx here
4266
4267 // Iterate over the block's transaction hashes, grabbing each
4268 // from the tx_pool (or from extra_block_txs) and validating them. Each is then added
4269 // to txs. Keys spent in each are added to <keys> by the double spend check.
4270 txs.reserve(bl.tx_hashes.size());
4271 txs_meta.reserve(bl.tx_hashes.size());
4272 txpool_events.reserve(bl.tx_hashes.size());
4273 for (const crypto::hash& tx_id : bl.tx_hashes)
4274 {
4275 TIME_MEASURE_START(aa);
4276
4277 // XXX old code does not check whether tx exists
4278 if (m_db->tx_exists(tx_id))
4279 {
4280 MERROR("Block with id: " << id << " attempting to add transaction already in blockchain with id: " << tx_id);
4281 bvc.m_verifivation_failed = true;
4282 return_txs_to_pool();
4283 return false;
4284 }
4285
4286 TIME_MEASURE_FINISH(aa);
4287 t_exists += aa;
4288 TIME_MEASURE_START(bb);
4289
4290 // get transaction with hash <tx_id> from m_tx_pool or extra_block_txs
4291 // tx info we want:
4292 // * tx as `cryptonote::transaction`
4293 // * blob
4294 // * weight
4295 // * fee
4296 // * is pruned?
4297 txs.emplace_back();
4298 transaction &tx = txs.back().first;
4299 blobdata &txblob = txs.back().second;
4300 size_t tx_weight{};
4301 uint64_t fee{};
4302 bool pruned{};
4303
4304 /*
4305 * Try pulling transaction data from the mempool proper first. If that fails, then try pulling
4306 * from the block supplement. We add txs pulled from the block to the txpool events for future
4307 * notifications, since if the tx skipped the mempool, then listeners have not yet received a
4308 * notification for this tx.
4309 */
4310 bool _unused1, _unused2, _unused3;
4311 const bool found_tx_in_pool{
4312 m_tx_pool.take_tx(tx_id, tx, txblob, tx_weight, fee,
4313 _unused1, _unused2, _unused3, pruned, /*suppress_missing_msgs=*/true)
4314 };
4315 bool find_tx_failure{!found_tx_in_pool};
4316 if (!found_tx_in_pool) // if not in mempool:
4317 {
4318 const auto extra_txs_it{extra_block_txs.txs_by_txid.find(tx_id)};
4319 if (extra_txs_it != extra_block_txs.txs_by_txid.end()) // if in block supplement:
4320 {
4321 tx = std::move(extra_txs_it->second.first);
4322 txblob = std::move(extra_txs_it->second.second);
4323 tx_weight = tx.pruned ? get_pruned_transaction_weight(tx) : get_transaction_weight(tx, txblob.size());
4324 fee = get_tx_fee(tx);
4325 pruned = tx.pruned;
4326 extra_block_txs.txs_by_txid.erase(extra_txs_it);
4327 txpool_events.emplace_back(txpool_event{tx, tx_id, txblob.size(), tx_weight, true});
4328 find_tx_failure = false;
4329 }
4330 }
4331
4332 // @TODO: We should move this section (checking if the daemon has all txs from the block) to
4333 // right after the PoW check. Since it's now expected the node will sometimes not have all txs
4334 // in its pool at this point nor the txs included as fluffy txs (and will need to re-request
4335 // missing fluffy txs), then the node will sometimes waste cycles doing verification for some
4336 // txs twice.
4337 if (find_tx_failure) // did not find txid in mempool or provided extra block txs
4338 {
4339 const bool fully_supplemented_block = extra_block_txs.txs_by_txid.size() >= bl.tx_hashes.size();
4340 if (fully_supplemented_block)
4341 MERROR_VER("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id);
4342 else
4343 LOG_PRINT_L2("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id);
4344 txs.pop_back(); // We push to the back preemptively. On fail, we need txs & txs_meta to match size
4345 bvc.m_verifivation_failed = true;
4346 bvc.m_missing_txs = true;
4347 return_txs_to_pool();
4348 return false;
4349 }
4350 if (pruned)
4351 ++n_pruned;
4352
4353 TIME_MEASURE_FINISH(bb);
4354 t_pool += bb;
4355 // add the transaction to the temp list of transactions, so we can either
4356 // store the list of transactions all at once or return the ones we've
4357 // taken from the tx_pool back to it if the block fails verification.
4358 txs_meta.emplace_back(tx_id, tx_weight, found_tx_in_pool);
4359 TIME_MEASURE_START(dd);
4360
4361 // FIXME: the storage should not be responsible for validation.
4362 // If it does any, it is merely a sanity check.
4363 // Validation is the purview of the Blockchain class
4364 // - TW
4365 //
4366 // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly.
4367 // if (!check_for_double_spend(tx, keys))
4368 // {
4369 // LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id);
4370 // bvc.m_verifivation_failed = true;
4371 // break;
4372 // }
4373
4374 TIME_MEASURE_FINISH(dd);
4375 t_dblspnd += dd;
4376 TIME_MEASURE_START(cc);
4377
4378 #if defined(PER_BLOCK_CHECKPOINT)
4379 if (!fast_check)
4380 #endif
4381 {
4382 // validate that transaction inputs and the keys spending them are correct.
4383 tx_verification_context tvc;
4384 if(!check_tx_inputs(tx, tvc))
4385 {
4386 MERROR_VER("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs.");
4387
4388 //TODO: why is this done? make sure that keeping invalid blocks makes sense.
4389 add_block_as_invalid(bl, id);
4390 MERROR_VER("Block with id " << id << " added as invalid because of wrong inputs in transactions");
4391 bvc.m_verifivation_failed = true;
4392 return_txs_to_pool();
4393 return false;
4394 }
4395 }
4396
4397 TIME_MEASURE_FINISH(cc);
4398 t_checktx += cc;
4399 fee_summary += fee;
4400 cumulative_block_weight += tx_weight;
4401 }
4402
4403 // if we were syncing pruned blocks
4404 if (n_pruned > 0)
4405 {
4406 if (blockchain_height >= m_blocks_hash_check.size() || m_blocks_hash_check[blockchain_height].second == 0)
4407 {
4408 MERROR("Block at " << blockchain_height << " is pruned, but we do not have a weight for it");
4409 goto leave;
4410 }
4411 cumulative_block_weight = m_blocks_hash_check[blockchain_height].second;
4412 }
4413
4414 TIME_MEASURE_START(vmt);
4415 uint64_t base_reward = 0;
4416 uint64_t already_generated_coins = blockchain_height ? m_db->get_block_already_generated_coins(blockchain_height - 1) : 0;
4417 if(!validate_miner_transaction(bl, cumulative_block_weight, fee_summary, base_reward, already_generated_coins, bvc.m_partial_block_reward, m_hardfork->get_current_version()))
4418 {
4419 MERROR_VER("Block with id: " << id << " has incorrect miner transaction");
4420 bvc.m_verifivation_failed = true;
4421 return_txs_to_pool();
4422 return false;
4423 }
4424
4425 TIME_MEASURE_FINISH(vmt);
4426 size_t block_weight;
4427 difficulty_type cumulative_difficulty;
4428
4429 // populate various metadata about the block to be stored alongside it.
4430 block_weight = cumulative_block_weight;
4431 cumulative_difficulty = current_diffic;
4432 // In the "tail" state when the minimum subsidy (implemented in get_block_reward) is in effect, the number of
4433 // coins will eventually exceed MONEY_SUPPLY and overflow a uint64. To prevent overflow, cap already_generated_coins
4434 // at MONEY_SUPPLY. already_generated_coins is only used to compute the block subsidy and MONEY_SUPPLY yields a
4435 // subsidy of 0 under the base formula and therefore the minimum subsidy >0 in the tail state.
4436 already_generated_coins = base_reward < (MONEY_SUPPLY-already_generated_coins) ? already_generated_coins + base_reward : MONEY_SUPPLY;
4437 if(blockchain_height)
4438 cumulative_difficulty += m_db->get_block_cumulative_difficulty(blockchain_height - 1);
4439
4440 TIME_MEASURE_FINISH(block_processing_time);
4441 if(precomputed)
4442 block_processing_time += m_fake_pow_calc_time;
4443
4444 rtxn_guard.stop();
4445 TIME_MEASURE_START(addblock);
4446 uint64_t new_height = 0;
4447 if (!bvc.m_verifivation_failed)
4448 {
4449 try
4450 {
4451 uint64_t long_term_block_weight = get_next_long_term_block_weight(block_weight);
4452 cryptonote::blobdata bd = cryptonote::block_to_blob(bl);
4453 new_height = m_db->add_block(std::make_pair(std::move(bl), std::move(bd)), block_weight, long_term_block_weight, cumulative_difficulty, already_generated_coins, txs);
4454 }
4455 catch (const KEY_IMAGE_EXISTS& e)
4456 {
4457 LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what());
4458 m_batch_success = false;
4459 bvc.m_verifivation_failed = true;
4460 return_txs_to_pool();
4461 return false;
4462 }
4463 catch (const std::exception& e)
4464 {
4465 //TODO: figure out the best way to deal with this failure
4466 LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what());
4467 m_batch_success = false;
4468 bvc.m_verifivation_failed = true;
4469 return_txs_to_pool();
4470 return false;
4471 }
4472 }
4473 else
4474 {
4475 LOG_ERROR("Blocks that failed verification should not reach here");
4476 }
4477
4478 TIME_MEASURE_FINISH(addblock);
4479
4480 // do this after updating the hard fork state since the weight limit may change due to fork
4481 if (!update_next_cumulative_weight_limit())
4482 {
4483 MERROR("Failed to update next cumulative weight limit");
4484 pop_block_from_blockchain();
4485 return false;
4486 }
4487
4488 MINFO("+++++ BLOCK SUCCESSFULLY ADDED" << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "HEIGHT " << new_height-1 << ", difficulty:\t" << current_diffic << std::endl << "block reward: " << print_money(fee_summary + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_summary) << "), coinbase_weight: " << coinbase_weight << ", cumulative weight: " << cumulative_block_weight << ", " << block_processing_time << "(" << target_calculating_time << "/" << longhash_calculating_time << ")ms");
4489 if(m_show_time_stats)
4490 {
4491 MINFO("Height: " << new_height << " coinbase weight: " << coinbase_weight << " cumm: "
4492 << cumulative_block_weight << " p/t: " << block_processing_time << " ("
4493 << target_calculating_time << "/" << longhash_calculating_time << "/"
4494 << t1 << "/" << t2 << "/" << t3 << "/" << t_exists << "/" << t_pool
4495 << "/" << t_checktx << "/" << t_dblspnd << "/" << vmt << "/" << addblock << ")ms");
4496 }
4497
4498 bvc.m_added_to_main_chain = true;
4499 ++m_sync_counter;
4500
4501 // appears to be a NOP *and* is called elsewhere. wat?
4502 m_tx_pool.on_blockchain_inc(new_height, id);
4503 get_difficulty_for_next_block(); // just to cache it
4504 invalidate_block_template_cache();
4505
4506 const uint8_t new_hf_version = get_current_hard_fork_version();
4507 if (new_hf_version != hf_version)
4508 {
4509 // the genesis block is added before everything's setup, and the txpool is empty
4510 // when we start from scratch, so we skip this
4511 const bool is_genesis_block = new_height == 1;
4512 if (!is_genesis_block)
4513 {
4514 MGINFO("Validating txpool for v" << (unsigned)new_hf_version);
4515 m_tx_pool.validate(new_hf_version);
4516 }
4517 }
4518
4519 const crypto::hash seedhash = get_block_id_by_height(crypto::rx_seedheight(new_height));
4520
4521 // Make sure that txpool notifications happen BEFORE block and miner data notifications
4522 notify_txpool_event(std::move(txpool_events));
4523
4524 // send miner notifications to switch as soon as possible
4525 send_miner_notifications(new_height, seedhash, id, already_generated_coins);
4526
4527 // then send block notifications
4528 for (const auto& notifier: m_block_notifiers)
4529 notifier(new_height - 1, {std::addressof(bl), 1});
4530
4531 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
4532 rx_set_main_seedhash(seedhash.data, tools::get_max_concurrency());
4533
4534 return true;
4535 }
4536 //------------------------------------------------------------------
4537 bool Blockchain::prune_blockchain(uint32_t pruning_seed)
4538 {
4539 m_tx_pool.lock();
4540 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4541 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4542
4543 return m_db->prune_blockchain(pruning_seed);
4544 }
4545 //------------------------------------------------------------------
4546 bool Blockchain::update_blockchain_pruning()
4547 {
4548 m_tx_pool.lock();
4549 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4550 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4551
4552 return m_db->update_pruning();
4553 }
4554 //------------------------------------------------------------------
4555 bool Blockchain::check_blockchain_pruning()
4556 {
4557 m_tx_pool.lock();
4558 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4559 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4560
4561 return m_db->check_pruning();
4562 }
4563 //------------------------------------------------------------------
4564 // returns min(Mb, 1.7*Ml) as per https://github.com/ArticMine/Monero-Documents/blob/master/MoneroScaling2021-02.pdf from HF_VERSION_LONG_TERM_BLOCK_WEIGHT
4565 uint64_t Blockchain::get_next_long_term_block_weight(uint64_t block_weight) const
4566 {
4567 PERF_TIMER(get_next_long_term_block_weight);
4568
4569 const uint64_t db_height = m_db->height();
4570 const uint64_t nblocks = std::min<uint64_t>(m_long_term_block_weights_window, db_height);
4571
4572 const uint8_t hf_version = get_current_hard_fork_version();
4573 if (hf_version < HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
4574 return block_weight;
4575
4576 uint64_t long_term_median = get_long_term_block_weight_median(db_height - nblocks, nblocks);
4577 uint64_t long_term_effective_median_block_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, long_term_median);
4578
4579 uint64_t short_term_constraint;
4580 if (hf_version >= HF_VERSION_2021_SCALING)
4581 {
4582 // long_term_block_weight = block_weight bounded to range [long-term-median/1.7, long-term-median*1.7]
4583 block_weight = std::max<uint64_t>(block_weight, long_term_effective_median_block_weight * 10 / 17);
4584 short_term_constraint = long_term_effective_median_block_weight + long_term_effective_median_block_weight * 7 / 10;
4585 }
4586 else
4587 {
4588 // long_term_block_weight = block_weight bounded to range [0, long-term-median*1.4]
4589 short_term_constraint = long_term_effective_median_block_weight + long_term_effective_median_block_weight * 2 / 5;
4590 }
4591 uint64_t long_term_block_weight = std::min<uint64_t>(block_weight, short_term_constraint);
4592
4593 return long_term_block_weight;
4594 }
4595 //------------------------------------------------------------------
4596 bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight)
4597 {
4598 PERF_TIMER(update_next_cumulative_weight_limit);
4599
4600 LOG_PRINT_L3("Blockchain::" << __func__);
4601
4602 // when we reach this, the last hf version is not yet written to the db
4603 const uint64_t db_height = m_db->height();
4604 const uint8_t hf_version = get_current_hard_fork_version();
4605 uint64_t full_reward_zone = get_min_block_weight(hf_version);
4606
4607 if (hf_version < HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
4608 {
4609 std::vector<uint64_t> weights;
4610 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
4611 m_current_block_cumul_weight_median = epee::misc_utils::median(weights);
4612 }
4613 else
4614 {
4615 const uint64_t nblocks = std::min<uint64_t>(m_long_term_block_weights_window, db_height);
4616 const uint64_t long_term_median = get_long_term_block_weight_median(db_height - nblocks, nblocks);
4617
4618 m_long_term_effective_median_block_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, long_term_median);
4619
4620 std::vector<uint64_t> weights;
4621 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
4622
4623 uint64_t short_term_median = epee::misc_utils::median(weights);
4624 uint64_t effective_median_block_weight;
4625 if (hf_version >= HF_VERSION_2021_SCALING)
4626 {
4627 // effective median = short_term_median bounded to range [long_term_median, 50*long_term_median], but it can't be smaller than the
4628 // minimum penalty free zone (a.k.a. 'full reward zone')
4629 effective_median_block_weight = std::min<uint64_t>(std::max<uint64_t>(m_long_term_effective_median_block_weight, short_term_median), CRYPTONOTE_SHORT_TERM_BLOCK_WEIGHT_SURGE_FACTOR * m_long_term_effective_median_block_weight);
4630 }
4631 else
4632 {
4633 // effective median = short_term_median bounded to range [0, 50*long_term_median], but it can't be smaller than the
4634 // minimum penalty free zone (a.k.a. 'full reward zone')
4635 effective_median_block_weight = std::min<uint64_t>(std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, short_term_median), CRYPTONOTE_SHORT_TERM_BLOCK_WEIGHT_SURGE_FACTOR * m_long_term_effective_median_block_weight);
4636 }
4637
4638 m_current_block_cumul_weight_median = effective_median_block_weight;
4639 }
4640
4641 if (m_current_block_cumul_weight_median <= full_reward_zone)
4642 m_current_block_cumul_weight_median = full_reward_zone;
4643
4644 m_current_block_cumul_weight_limit = m_current_block_cumul_weight_median * 2;
4645
4646 if (long_term_effective_median_block_weight)
4647 *long_term_effective_median_block_weight = m_long_term_effective_median_block_weight;
4648
4649 if (!m_db->is_read_only())
4650 m_db->add_max_block_size(m_current_block_cumul_weight_limit);
4651
4652 return true;
4653 }
4654 //------------------------------------------------------------------
4655 bool Blockchain::add_new_block(const block& bl_, block_verification_context& bvc)
4656 {
4657 pool_supplement ps{};
4658 return add_new_block(bl_, bvc, ps);
4659 }
4660 //------------------------------------------------------------------
4661 bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc,
4662 pool_supplement& extra_block_txs)
4663 {
4664 try
4665 {
4666
4667 LOG_PRINT_L3("Blockchain::" << __func__);
4668 crypto::hash id = get_block_hash(bl);
4669 CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process
4670 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
4671 db_rtxn_guard rtxn_guard(m_db);
4672 if(have_block(id))
4673 {
4674 LOG_PRINT_L3("block with id = " << id << " already exists");
4675 bvc.m_already_exists = true;
4676 return false;
4677 }
4678
4679 //check that block refers to chain tail
4680 if(!(bl.prev_id == get_tail_id()))
4681 {
4682 //chain switching or wrong block
4683 bvc.m_added_to_main_chain = false;
4684 rtxn_guard.stop();
4685 return handle_alternative_block(bl, id, bvc, extra_block_txs);
4686 //never relay alternative blocks
4687 }
4688
4689 rtxn_guard.stop();
4690 return handle_block_to_main_chain(bl, id, bvc, extra_block_txs);
4691
4692 }
4693 catch (const std::exception &e)
4694 {
4695 LOG_ERROR("Exception at [add_new_block], what=" << e.what());
4696 bvc.m_verifivation_failed = true;
4697 return false;
4698 }
4699 }
4700 //------------------------------------------------------------------
4701 //TODO: Refactor, consider returning a failure height and letting
4702 // caller decide course of action.
4703 void Blockchain::check_against_checkpoints(const checkpoints& points, bool enforce)
4704 {
4705 const auto& pts = points.get_points();
4706 bool stop_batch;
4707
4708 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4709 stop_batch = m_db->batch_start();
4710 const uint64_t blockchain_height = m_db->height();
4711 for (const auto& pt : pts)
4712 {
4713 // if the checkpoint is for a block we don't have yet, move on
4714 if (pt.first >= blockchain_height)
4715 {
4716 continue;
4717 }
4718
4719 if (!points.check_block(pt.first, m_db->get_block_hash_from_height(pt.first)))
4720 {
4721 // if asked to enforce checkpoints, roll back to a couple of blocks before the checkpoint
4722 if (enforce)
4723 {
4724 LOG_ERROR("Local blockchain failed to pass a checkpoint, rolling back!");
4725 std::list<block> empty;
4726 rollback_blockchain_switching(empty, pt.first - 2);
4727 }
4728 else
4729 {
4730 LOG_ERROR("WARNING: local blockchain failed to pass a MoneroPulse checkpoint, and you could be on a fork. You should either sync up from scratch, OR download a fresh blockchain bootstrap, OR enable checkpoint enforcing with the --enforce-dns-checkpointing command-line option");
4731 }
4732 }
4733 }
4734 if (stop_batch)
4735 m_db->batch_stop();
4736 }
4737 //------------------------------------------------------------------
4738 // returns false if any of the checkpoints loading returns false.
4739 // That should happen only if a checkpoint is added that conflicts
4740 // with an existing checkpoint.
4741 bool Blockchain::update_checkpoints(const std::string& file_path, bool check_dns)
4742 {
4743 if (!m_checkpoints.load_checkpoints_from_json(file_path))
4744 {
4745 return false;
4746 }
4747
4748 // if we're checking both dns and json, load checkpoints from dns.
4749 // if we're not hard-enforcing dns checkpoints, handle accordingly
4750 if (m_enforce_dns_checkpoints && check_dns && !m_offline)
4751 {
4752 if (!m_checkpoints.load_checkpoints_from_dns())
4753 {
4754 return false;
4755 }
4756 }
4757 else if (check_dns && !m_offline)
4758 {
4759 checkpoints dns_points;
4760 dns_points.load_checkpoints_from_dns();
4761 if (m_checkpoints.check_for_conflicts(dns_points))
4762 {
4763 check_against_checkpoints(dns_points, false);
4764 }
4765 else
4766 {
4767 MERROR("One or more checkpoints fetched from DNS conflicted with existing checkpoints!");
4768 }
4769 }
4770
4771 check_against_checkpoints(m_checkpoints, true);
4772
4773 return true;
4774 }
4775 //------------------------------------------------------------------
4776 void Blockchain::set_enforce_dns_checkpoints(bool enforce_checkpoints)
4777 {
4778 m_enforce_dns_checkpoints = enforce_checkpoints;
4779 }
4780
4781 //------------------------------------------------------------------
4782 void Blockchain::block_longhash_worker(uint64_t height, const epee::span<const block> &blocks, std::unordered_map<crypto::hash, crypto::hash> &map) const
4783 {
4784 TIME_MEASURE_START(t);
4785 slow_hash_allocate_state();
4786
4787 for (const auto & block : blocks)
4788 {
4789 if (m_cancel)
4790 break;
4791 crypto::hash id = get_block_hash(block);
4792 crypto::hash pow = get_block_longhash(this, block, height++, 0);
4793 map.emplace(id, pow);
4794 }
4795
4796 slow_hash_free_state();
4797 TIME_MEASURE_FINISH(t);
4798 }
4799
4800 //------------------------------------------------------------------
4801 bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync)
4802 {
4803 bool success = false;
4804
4805 MTRACE("Blockchain::" << __func__);
4806 CRITICAL_REGION_BEGIN(m_blockchain_lock);
4807 TIME_MEASURE_START(t1);
4808
4809 try
4810 {
4811 if (m_batch_success)
4812 {
4813 m_db->batch_stop();
4814 if (m_reset_timestamps_and_difficulties_height)
4815 {
4816 m_timestamps_and_difficulties_height = 0;
4817 m_reset_timestamps_and_difficulties_height = false;
4818 }
4819 }
4820 else
4821 m_db->batch_abort();
4822 success = true;
4823 }
4824 catch (const std::exception &e)
4825 {
4826 MERROR("Exception in cleanup_handle_incoming_blocks: " << e.what());
4827 }
4828
4829 if (success && m_sync_counter > 0)
4830 {
4831 if (force_sync)
4832 {
4833 if(m_db_sync_mode != db_nosync)
4834 store_blockchain();
4835 m_sync_counter = 0;
4836 }
4837 else if (m_db_sync_threshold && ((m_db_sync_on_blocks && m_sync_counter >= m_db_sync_threshold) || (!m_db_sync_on_blocks && m_bytes_to_sync >= m_db_sync_threshold)))
4838 {
4839 MDEBUG("Sync threshold met, syncing");
4840 if(m_db_sync_mode == db_async)
4841 {
4842 m_sync_counter = 0;
4843 m_bytes_to_sync = 0;
4844 boost::asio::dispatch(m_async_service, boost::bind(&Blockchain::store_blockchain, this));
4845 }
4846 else if(m_db_sync_mode == db_sync)
4847 {
4848 store_blockchain();
4849 }
4850 else // db_nosync
4851 {
4852 // DO NOTHING, not required to call sync.
4853 }
4854 }
4855 }
4856
4857 TIME_MEASURE_FINISH(t1);
4858 m_blocks_longhash_table.clear();
4859 m_scan_table.clear();
4860
4861 // when we're well clear of the precomputed hashes, free the memory
4862 if (!m_blocks_hash_check.empty() && m_db->height() > m_blocks_hash_check.size() + 4096)
4863 {
4864 MINFO("Dumping block hashes, we're now 4k past " << m_blocks_hash_check.size());
4865 m_blocks_hash_check.clear();
4866 m_blocks_hash_check.shrink_to_fit();
4867 }
4868
4869 CRITICAL_REGION_END();
4870 m_tx_pool.unlock();
4871
4872 update_blockchain_pruning();
4873
4874 return success;
4875 }
4876
4877 //------------------------------------------------------------------
4878 void Blockchain::output_scan_worker(const uint64_t amount, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs) const
4879 {
4880 try
4881 {
4882 m_db->get_output_key(epee::span<const uint64_t>(&amount, 1), offsets, outputs, true);
4883 }
4884 catch (const std::exception& e)
4885 {
4886 MERROR_VER("EXCEPTION: " << e.what());
4887 }
4888 catch (...)
4889 {
4890
4891 }
4892 }
4893
4894 uint64_t Blockchain::prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights)
4895 {
4896 // new: . . . . . X X X X X . . . . . .
4897 // pre: A A A A B B B B C C C C D D D D
4898
4899 CHECK_AND_ASSERT_MES(weights.empty() || weights.size() == hashes.size(), 0, "Unexpected weights size");
4900
4901 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4902
4903 // easy case: height >= hashes
4904 if (height >= m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP)
4905 return hashes.size();
4906
4907 // if we're getting old blocks, we might have jettisoned the hashes already
4908 if (m_blocks_hash_check.empty())
4909 return hashes.size();
4910
4911 // find hashes encompassing those block
4912 size_t first_index = height / HASH_OF_HASHES_STEP;
4913 size_t last_index = (height + hashes.size() - 1) / HASH_OF_HASHES_STEP;
4914 MDEBUG("Blocks " << height << " - " << (height + hashes.size() - 1) << " start at " << first_index << " and end at " << last_index);
4915
4916 // case of not enough to calculate even a single hash
4917 if (first_index == last_index && hashes.size() < HASH_OF_HASHES_STEP && (height + hashes.size()) % HASH_OF_HASHES_STEP)
4918 return hashes.size();
4919
4920 // build hashes vector to hash hashes together
4921 std::vector<crypto::hash> data_hashes;
4922 std::vector<uint64_t> data_weights;
4923 data_hashes.reserve(hashes.size() + HASH_OF_HASHES_STEP - 1); // may be a bit too much
4924 if (!weights.empty())
4925 data_weights.reserve(data_hashes.size());
4926
4927 // we expect height to be either equal or a bit below db height
4928 bool disconnected = (height > m_db->height());
4929 size_t pop;
4930 if (disconnected && height % HASH_OF_HASHES_STEP)
4931 {
4932 ++first_index;
4933 pop = HASH_OF_HASHES_STEP - height % HASH_OF_HASHES_STEP;
4934 }
4935 else
4936 {
4937 // we might need some already in the chain for the first part of the first hash
4938 for (uint64_t h = first_index * HASH_OF_HASHES_STEP; h < height; ++h)
4939 {
4940 data_hashes.push_back(m_db->get_block_hash_from_height(h));
4941 if (!weights.empty())
4942 data_weights.push_back(m_db->get_block_weight(h));
4943 }
4944 pop = 0;
4945 }
4946
4947 // push the data to check
4948 for (size_t i = 0; i < hashes.size(); ++i)
4949 {
4950 if (pop)
4951 --pop;
4952 else
4953 {
4954 data_hashes.push_back(hashes[i]);
4955 if (!weights.empty())
4956 data_weights.push_back(weights[i]);
4957 }
4958 }
4959
4960 // hash and check
4961 uint64_t usable = first_index * HASH_OF_HASHES_STEP - height; // may start negative, but unsigned under/overflow is not UB
4962 for (size_t n = first_index; n <= last_index; ++n)
4963 {
4964 if (n < m_blocks_hash_of_hashes.size())
4965 {
4966 // if the last index isn't fully filled, we can't tell if valid
4967 if (data_hashes.size() < (n - first_index) * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP)
4968 break;
4969
4970 crypto::hash hash;
4971 cn_fast_hash(data_hashes.data() + (n - first_index) * HASH_OF_HASHES_STEP, HASH_OF_HASHES_STEP * sizeof(crypto::hash), hash);
4972 bool valid = hash == m_blocks_hash_of_hashes[n].first;
4973 if (valid && !weights.empty())
4974 {
4975 cn_fast_hash(data_weights.data() + (n - first_index) * HASH_OF_HASHES_STEP, HASH_OF_HASHES_STEP * sizeof(uint64_t), hash);
4976 valid &= hash == m_blocks_hash_of_hashes[n].second;
4977 }
4978
4979 // add to the known hashes array
4980 if (!valid)
4981 {
4982 MDEBUG("invalid hash for blocks " << n * HASH_OF_HASHES_STEP << " - " << (n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP - 1));
4983 break;
4984 }
4985
4986 size_t end = n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP;
4987 for (size_t i = n * HASH_OF_HASHES_STEP; i < end; ++i)
4988 {
4989 CHECK_AND_ASSERT_MES(m_blocks_hash_check[i].first == crypto::null_hash || m_blocks_hash_check[i].first == data_hashes[i - first_index * HASH_OF_HASHES_STEP],
4990 0, "Consistency failure in m_blocks_hash_check construction");
4991 m_blocks_hash_check[i].first = data_hashes[i - first_index * HASH_OF_HASHES_STEP];
4992 if (!weights.empty())
4993 {
4994 CHECK_AND_ASSERT_MES(m_blocks_hash_check[i].second == 0 || m_blocks_hash_check[i].second == data_weights[i - first_index * HASH_OF_HASHES_STEP],
4995 0, "Consistency failure in m_blocks_hash_check construction");
4996 m_blocks_hash_check[i].second = data_weights[i - first_index * HASH_OF_HASHES_STEP];
4997 }
4998 }
4999 usable += HASH_OF_HASHES_STEP;
5000 }
5001 else
5002 {
5003 // if after the end of the precomputed blocks, accept anything
5004 usable += HASH_OF_HASHES_STEP;
5005 if (usable > hashes.size())
5006 usable = hashes.size();
5007 }
5008 }
5009 MDEBUG("usable: " << usable << " / " << hashes.size());
5010 CHECK_AND_ASSERT_MES(usable < std::numeric_limits<uint64_t>::max() / 2, 0, "usable is negative");
5011 return usable;
5012 }
5013
5014 bool Blockchain::has_block_weights(uint64_t height, uint64_t nblocks) const
5015 {
5016 CHECK_AND_ASSERT_MES(nblocks > 0, false, "nblocks is 0");
5017 uint64_t last_block_height = height + nblocks - 1;
5018 if (last_block_height >= m_blocks_hash_check.size())
5019 return false;
5020 for (uint64_t h = height; h <= last_block_height; ++h)
5021 if (m_blocks_hash_check[h].second == 0)
5022 return false;
5023 return true;
5024 }
5025
5026 //------------------------------------------------------------------
5027 // ND: Speedups:
5028 // 1. Thread long_hash computations if possible (m_max_prepare_blocks_threads = nthreads, default = 4)
5029 // 2. Group all amounts (from txs) and related absolute offsets and form a table of tx_prefix_hash
5030 // vs [k_image, output_keys] (m_scan_table). This is faster because it takes advantage of bulk queries
5031 // and is threaded if possible. The table (m_scan_table) will be used later when querying output
5032 // keys.
5033 bool Blockchain::prepare_handle_incoming_blocks(const std::vector<block_complete_entry> &blocks_entry, std::vector<block> &blocks)
5034 {
5035 MTRACE("Blockchain::" << __func__);
5036 TIME_MEASURE_START(prepare);
5037 bool stop_batch;
5038 uint64_t bytes = 0;
5039 size_t total_txs = 0;
5040 blocks.clear();
5041
5042 // Order of locking must be:
5043 // m_incoming_tx_lock (optional)
5044 // m_tx_pool lock
5045 // blockchain lock
5046 //
5047 // Something which takes the blockchain lock may never take the txpool lock
5048 // if it has not provably taken the txpool lock earlier
5049 //
5050 // The txpool lock is now taken in prepare_handle_incoming_blocks
5051 // and released in cleanup_handle_incoming_blocks. This avoids issues
5052 // when something uses the pool, which now uses the blockchain and
5053 // needs a batch, since a batch could otherwise be active while the
5054 // txpool and blockchain locks were not held
5055
5056 m_tx_pool.lock();
5057 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
5058
5059 if(blocks_entry.size() == 0)
5060 return false;
5061
5062 for (const auto &entry : blocks_entry)
5063 {
5064 bytes += entry.block.size();
5065 for (const auto &tx_blob : entry.txs)
5066 {
5067 bytes += tx_blob.blob.size();
5068 }
5069 total_txs += entry.txs.size();
5070 }
5071 m_bytes_to_sync += bytes;
5072 while (!(stop_batch = m_db->batch_start(blocks_entry.size(), bytes))) {
5073 m_blockchain_lock.unlock();
5074 m_tx_pool.unlock();
5075 epee::misc_utils::sleep_no_w(1000);
5076 m_tx_pool.lock();
5077 m_blockchain_lock.lock();
5078 }
5079 m_batch_success = true;
5080
5081 const uint64_t height = m_db->height();
5082 if ((height + blocks_entry.size()) < m_blocks_hash_check.size())
5083 return true;
5084
5085 bool blocks_exist = false;
5086 tools::threadpool& tpool = tools::threadpool::getInstanceForCompute();
5087 unsigned threads = tpool.get_max_concurrency();
5088 blocks.resize(blocks_entry.size());
5089
5090 if (1)
5091 {
5092 // limit threads, default limit = 4
5093 if(threads > m_max_prepare_blocks_threads)
5094 threads = m_max_prepare_blocks_threads;
5095
5096 unsigned int batches = blocks_entry.size() / threads;
5097 unsigned int extra = blocks_entry.size() % threads;
5098 MDEBUG("block_batches: " << batches);
5099 std::vector<std::unordered_map<crypto::hash, crypto::hash>> maps(threads);
5100 auto it = blocks_entry.begin();
5101 unsigned blockidx = 0;
5102
5103 const crypto::hash tophash = m_db->top_block_hash();
5104 for (unsigned i = 0; i < threads; i++)
5105 {
5106 for (unsigned int j = 0; j < batches; j++, ++blockidx)
5107 {
5108 block &block = blocks[blockidx];
5109 crypto::hash block_hash;
5110
5111 if (!parse_and_validate_block_from_blob(it->block, block, block_hash))
5112 return false;
5113
5114 // check first block and skip all blocks if its not chained properly
5115 if (blockidx == 0)
5116 {
5117 if (block.prev_id != tophash)
5118 {
5119 MDEBUG("Skipping prepare blocks. New blocks don't belong to chain.");
5120 blocks.clear();
5121 return true;
5122 }
5123 }
5124 if (have_block(block_hash))
5125 blocks_exist = true;
5126
5127 std::advance(it, 1);
5128 }
5129 }
5130
5131 for (unsigned i = 0; i < extra && !blocks_exist; i++, blockidx++)
5132 {
5133 block &block = blocks[blockidx];
5134 crypto::hash block_hash;
5135
5136 if (!parse_and_validate_block_from_blob(it->block, block, block_hash))
5137 return false;
5138
5139 if (have_block(block_hash))
5140 blocks_exist = true;
5141
5142 std::advance(it, 1);
5143 }
5144
5145 if (!blocks_exist)
5146 {
5147 m_blocks_longhash_table.clear();
5148 uint64_t thread_height = height;
5149 tools::threadpool::waiter waiter(tpool);
5150 m_prepare_height = height;
5151 m_prepare_nblocks = blocks_entry.size();
5152 m_prepare_blocks = &blocks;
5153 for (unsigned int i = 0; i < threads; i++)
5154 {
5155 unsigned nblocks = batches;
5156 if (i < extra)
5157 ++nblocks;
5158 if (nblocks == 0)
5159 break;
5160 tpool.submit(&waiter, boost::bind(&Blockchain::block_longhash_worker, this, thread_height, epee::span<const block>(&blocks[thread_height - height], nblocks), std::ref(maps[i])), true);
5161 thread_height += nblocks;
5162 }
5163
5164 if (!waiter.wait())
5165 return false;
5166 m_prepare_height = 0;
5167
5168 if (m_cancel)
5169 return false;
5170
5171 for (const auto & map : maps)
5172 {
5173 m_blocks_longhash_table.insert(map.begin(), map.end());
5174 }
5175 }
5176 }
5177
5178 if (m_cancel)
5179 return false;
5180
5181 if (blocks_exist)
5182 {
5183 MDEBUG("Skipping remainder of prepare blocks. Blocks exist.");
5184 return true;
5185 }
5186
5187 m_fake_scan_time = 0;
5188 m_fake_pow_calc_time = 0;
5189
5190 m_scan_table.clear();
5191
5192 TIME_MEASURE_FINISH(prepare);
5193 m_fake_pow_calc_time = prepare / blocks_entry.size();
5194
5195 if (blocks_entry.size() > 1 && threads > 1 && m_show_time_stats)
5196 MDEBUG("Prepare blocks took: " << prepare << " ms");
5197
5198 TIME_MEASURE_START(scantable);
5199
5200 // [input] stores all unique amounts found
5201 std::vector < uint64_t > amounts;
5202 // [input] stores all absolute_offsets for each amount
5203 std::map<uint64_t, std::vector<uint64_t>> offset_map;
5204 // [output] stores all output_data_t for each absolute_offset
5205 std::map<uint64_t, std::vector<output_data_t>> tx_map;
5206 std::vector<std::pair<cryptonote::transaction, crypto::hash>> txes(total_txs);
5207
5208 #define SCAN_TABLE_QUIT(m) \
5209 do { \
5210 MERROR_VER(m) ;\
5211 m_scan_table.clear(); \
5212 return false; \
5213 } while(0); \
5214
5215 // generate sorted tables for all amounts and absolute offsets
5216 size_t tx_index = 0, block_index = 0;
5217 for (const auto &entry : blocks_entry)
5218 {
5219 if (m_cancel)
5220 return false;
5221
5222 for (const auto &tx_blob : entry.txs)
5223 {
5224 if (tx_index >= txes.size())
5225 SCAN_TABLE_QUIT("tx_index is out of sync");
5226 transaction &tx = txes[tx_index].first;
5227 crypto::hash &tx_prefix_hash = txes[tx_index].second;
5228 ++tx_index;
5229
5230 if (!parse_and_validate_tx_base_from_blob(tx_blob.blob, tx))
5231 SCAN_TABLE_QUIT("Could not parse tx from incoming blocks.");
5232 cryptonote::get_transaction_prefix_hash(tx, tx_prefix_hash);
5233
5234 auto its = m_scan_table.find(tx_prefix_hash);
5235 if (its != m_scan_table.end())
5236 SCAN_TABLE_QUIT("Duplicate tx found from incoming blocks.");
5237
5238 m_scan_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>());
5239 its = m_scan_table.find(tx_prefix_hash);
5240 assert(its != m_scan_table.end());
5241
5242 // get all amounts from tx.vin(s)
5243 for (const auto &txin : tx.vin)
5244 {
5245 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5246
5247 // check for duplicate
5248 auto it = its->second.find(in_to_key.k_image);
5249 if (it != its->second.end())
5250 SCAN_TABLE_QUIT("Duplicate key_image found from incoming blocks.");
5251
5252 amounts.push_back(in_to_key.amount);
5253 }
5254
5255 // sort and remove duplicate amounts from amounts list
5256 std::sort(amounts.begin(), amounts.end());
5257 auto last = std::unique(amounts.begin(), amounts.end());
5258 amounts.erase(last, amounts.end());
5259
5260 // add amount to the offset_map and tx_map
5261 for (const uint64_t &amount : amounts)
5262 {
5263 if (offset_map.find(amount) == offset_map.end())
5264 offset_map.emplace(amount, std::vector<uint64_t>());
5265
5266 if (tx_map.find(amount) == tx_map.end())
5267 tx_map.emplace(amount, std::vector<output_data_t>());
5268 }
5269
5270 // add new absolute_offsets to offset_map
5271 for (const auto &txin : tx.vin)
5272 {
5273 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5274 // no need to check for duplicate here.
5275 auto absolute_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets);
5276 for (const auto & offset : absolute_offsets)
5277 offset_map[in_to_key.amount].push_back(offset);
5278
5279 }
5280 }
5281 ++block_index;
5282 }
5283
5284 // sort and remove duplicate absolute_offsets in offset_map
5285 for (auto &offsets : offset_map)
5286 {
5287 std::sort(offsets.second.begin(), offsets.second.end());
5288 auto last = std::unique(offsets.second.begin(), offsets.second.end());
5289 offsets.second.erase(last, offsets.second.end());
5290 }
5291
5292 // gather all the output keys
5293 threads = tpool.get_max_concurrency();
5294 if (!m_db->can_thread_bulk_indices())
5295 threads = 1;
5296
5297 if (threads > 1 && amounts.size() > 1)
5298 {
5299 tools::threadpool::waiter waiter(tpool);
5300
5301 for (size_t i = 0; i < amounts.size(); i++)
5302 {
5303 uint64_t amount = amounts[i];
5304 tpool.submit(&waiter, boost::bind(&Blockchain::output_scan_worker, this, amount, std::cref(offset_map[amount]), std::ref(tx_map[amount])), true);
5305 }
5306 if (!waiter.wait())
5307 return false;
5308 }
5309 else
5310 {
5311 for (size_t i = 0; i < amounts.size(); i++)
5312 {
5313 uint64_t amount = amounts[i];
5314 output_scan_worker(amount, offset_map[amount], tx_map[amount]);
5315 }
5316 }
5317
5318 // now generate a table for each tx_prefix and k_image hashes
5319 tx_index = 0;
5320 for (const auto &entry : blocks_entry)
5321 {
5322 if (m_cancel)
5323 return false;
5324
5325 for (size_t i = 0; i < entry.txs.size(); ++i)
5326 {
5327 if (tx_index >= txes.size())
5328 SCAN_TABLE_QUIT("tx_index is out of sync");
5329 const transaction &tx = txes[tx_index].first;
5330 const crypto::hash &tx_prefix_hash = txes[tx_index].second;
5331 ++tx_index;
5332
5333 auto its = m_scan_table.find(tx_prefix_hash);
5334 if (its == m_scan_table.end())
5335 SCAN_TABLE_QUIT("Tx not found on scan table from incoming blocks.");
5336
5337 for (const auto &txin : tx.vin)
5338 {
5339 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5340 auto needed_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets);
5341
5342 std::vector<output_data_t> outputs;
5343 for (const uint64_t & offset_needed : needed_offsets)
5344 {
5345 size_t pos = 0;
5346 bool found = false;
5347
5348 for (const uint64_t &offset_found : offset_map[in_to_key.amount])
5349 {
5350 if (offset_needed == offset_found)
5351 {
5352 found = true;
5353 break;
5354 }
5355
5356 ++pos;
5357 }
5358
5359 if (found && pos < tx_map[in_to_key.amount].size())
5360 outputs.push_back(tx_map[in_to_key.amount].at(pos));
5361 else
5362 break;
5363 }
5364
5365 its->second.emplace(in_to_key.k_image, outputs);
5366 }
5367 }
5368 }
5369
5370 TIME_MEASURE_FINISH(scantable);
5371 if (total_txs > 0)
5372 {
5373 m_fake_scan_time = scantable / total_txs;
5374 if(m_show_time_stats)
5375 MDEBUG("Prepare scantable took: " << scantable << " ms");
5376 }
5377
5378 return true;
5379 }
5380
5381 void Blockchain::prepare_handle_incoming_block_no_preprocess(const size_t block_byte_estimate)
5382 {
5383 // acquire locks
5384 m_tx_pool.lock();
5385 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
5386
5387 // increment sync byte counter to trigger sync against database backing store
5388 // later in cleanup_handle_incoming_blocks()
5389 m_bytes_to_sync += block_byte_estimate;
5390
5391 // spin until we start a batch
5392 while (!m_db->batch_start(1, block_byte_estimate)) {
5393 m_blockchain_lock.unlock();
5394 m_tx_pool.unlock();
5395 epee::misc_utils::sleep_no_w(1000);
5396 m_tx_pool.lock();
5397 m_blockchain_lock.lock();
5398 }
5399 m_batch_success = true;
5400 }
5401
5402 void Blockchain::add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata &blob, const txpool_tx_meta_t &meta)
5403 {
5404 m_db->add_txpool_tx(txid, blob, meta);
5405 }
5406
5407 void Blockchain::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta)
5408 {
5409 m_db->update_txpool_tx(txid, meta);
5410 }
5411
5412 void Blockchain::remove_txpool_tx(const crypto::hash &txid)
5413 {
5414 m_db->remove_txpool_tx(txid);
5415 }
5416
5417 uint64_t Blockchain::get_txpool_tx_count(bool include_sensitive) const
5418 {
5419 return m_db->get_txpool_tx_count(include_sensitive ? relay_category::all : relay_category::broadcasted);
5420 }
5421
5422 bool Blockchain::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const
5423 {
5424 return m_db->get_txpool_tx_meta(txid, meta);
5425 }
5426
5427 bool Blockchain::get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const
5428 {
5429 return m_db->get_txpool_tx_blob(txid, bd, tx_category);
5430 }
5431
5432 cryptonote::blobdata Blockchain::get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const
5433 {
5434 return m_db->get_txpool_tx_blob(txid, tx_category);
5435 }
5436
5437 bool Blockchain::for_all_txpool_txes(std::function<bool(const crypto::hash&, const txpool_tx_meta_t&, const cryptonote::blobdata_ref*)> f, bool include_blob, relay_category tx_category) const
5438 {
5439 return m_db->for_all_txpool_txes(f, include_blob, tx_category);
5440 }
5441
5442 bool Blockchain::txpool_tx_matches_category(const crypto::hash& tx_hash, relay_category category)
5443 {
5444 return m_db->txpool_tx_matches_category(tx_hash, category);
5445 }
5446
5447 void Blockchain::set_user_options(uint64_t maxthreads, bool sync_on_blocks, uint64_t sync_threshold, blockchain_db_sync_mode sync_mode, bool fast_sync)
5448 {
5449 if (sync_mode == db_defaultsync)
5450 {
5451 m_db_default_sync = true;
5452 sync_mode = db_async;
5453 }
5454 m_db_sync_mode = sync_mode;
5455 m_fast_sync = fast_sync;
5456 m_db_sync_on_blocks = sync_on_blocks;
5457 m_db_sync_threshold = sync_threshold;
5458 m_max_prepare_blocks_threads = maxthreads;
5459 }
5460
5461 void Blockchain::set_txpool_notify(TxpoolNotifyCallback&& notify)
5462 {
5463 std::lock_guard<decltype(m_txpool_notifier_mutex)> lg(m_txpool_notifier_mutex);
5464 m_txpool_notifier = notify;
5465 }
5466
5467 void Blockchain::add_block_notify(BlockNotifyCallback&& notify)
5468 {
5469 if (notify)
5470 {
5471 CRITICAL_REGION_LOCAL(m_blockchain_lock);
5472 m_block_notifiers.push_back(std::move(notify));
5473 }
5474 }
5475
5476 void Blockchain::add_miner_notify(MinerNotifyCallback&& notify)
5477 {
5478 if (notify)
5479 {
5480 CRITICAL_REGION_LOCAL(m_blockchain_lock);
5481 m_miner_notifiers.push_back(std::move(notify));
5482 }
5483 }
5484
5485 void Blockchain::notify_txpool_event(std::vector<txpool_event>&& event) const
5486 {
5487 std::lock_guard<decltype(m_txpool_notifier_mutex)> lg(m_txpool_notifier_mutex);
5488 if (m_txpool_notifier)
5489 {
5490 try
5491 {
5492 m_txpool_notifier(std::move(event));
5493 }
5494 catch (const std::exception &e)
5495 {
5496 MDEBUG("During Blockchain::notify_txpool_event(), ignored exception: " << e.what());
5497 }
5498 }
5499 }
5500
5501 void Blockchain::safesyncmode(const bool onoff)
5502 {
5503 /* all of this is no-op'd if the user set a specific
5504 * --db-sync-mode at startup.
5505 */
5506 if (m_db_default_sync)
5507 {
5508 m_db->safesyncmode(onoff);
5509 m_db_sync_mode = onoff ? db_nosync : db_async;
5510 }
5511 }
5512
5513 HardFork::State Blockchain::get_hard_fork_state() const
5514 {
5515 return m_hardfork->get_state();
5516 }
5517
5518 bool Blockchain::get_hard_fork_voting_info(uint8_t version, uint32_t &window, uint32_t &votes, uint32_t &threshold, uint64_t &earliest_height, uint8_t &voting) const
5519 {
5520 return m_hardfork->get_voting_info(version, window, votes, threshold, earliest_height, voting);
5521 }
5522
5523 uint64_t Blockchain::get_difficulty_target() const
5524 {
5525 return get_current_hard_fork_version() < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2;
5526 }
5527
5528 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> Blockchain:: get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const
5529 {
5530 return m_db->get_output_histogram(amounts, unlocked, recent_cutoff, min_count);
5531 }
5532
5533 std::vector<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> Blockchain::get_alternative_chains() const
5534 {
5535 std::vector<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> chains;
5536
5537 blocks_ext_by_hash alt_blocks;
5538 alt_blocks.reserve(m_db->get_alt_block_count());
5539 m_db->for_all_alt_blocks([&alt_blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const cryptonote::blobdata_ref *blob) {
5540 if (!blob)
5541 {
5542 MERROR("No blob, but blobs were requested");
5543 return false;
5544 }
5545 cryptonote::block bl;
5546 block_extended_info bei;
5547 if (cryptonote::parse_and_validate_block_from_blob(*blob, bei.bl))
5548 {
5549 bei.height = data.height;
5550 bei.block_cumulative_weight = data.cumulative_weight;
5551 bei.cumulative_difficulty = data.cumulative_difficulty_high;
5552 bei.cumulative_difficulty = (bei.cumulative_difficulty << 64) + data.cumulative_difficulty_low;
5553 bei.already_generated_coins = data.already_generated_coins;
5554 alt_blocks.insert(std::make_pair(cryptonote::get_block_hash(bei.bl), std::move(bei)));
5555 }
5556 else
5557 MERROR("Failed to parse block from blob");
5558 return true;
5559 }, true);
5560
5561 for (const auto &i: alt_blocks)
5562 {
5563 const crypto::hash top = cryptonote::get_block_hash(i.second.bl);
5564 bool found = false;
5565 for (const auto &j: alt_blocks)
5566 {
5567 if (j.second.bl.prev_id == top)
5568 {
5569 found = true;
5570 break;
5571 }
5572 }
5573 if (!found)
5574 {
5575 std::vector<crypto::hash> chain;
5576 auto h = i.second.bl.prev_id;
5577 chain.push_back(top);
5578 blocks_ext_by_hash::const_iterator prev;
5579 while ((prev = alt_blocks.find(h)) != alt_blocks.end())
5580 {
5581 chain.push_back(h);
5582 h = prev->second.bl.prev_id;
5583 }
5584 chains.push_back(std::make_pair(i.second, chain));
5585 }
5586 }
5587 return chains;
5588 }
5589
5590 void Blockchain::cancel()
5591 {
5592 m_cancel = true;
5593 }
5594
5595 #if defined(PER_BLOCK_CHECKPOINT)
5596 static const char expected_block_hashes_hash[] = "3aed3b6b896e8c1f97802b65f84966526d1ac8d75f417e5ce666f31a5928ac3f";
5597 void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get_checkpoints)
5598 {
5599 if (get_checkpoints == nullptr || !m_fast_sync)
5600 {
5601 return;
5602 }
5603 const epee::span<const unsigned char> &checkpoints = get_checkpoints(m_nettype);
5604 if (!checkpoints.empty())
5605 {
5606 MINFO("Loading precomputed blocks (" << checkpoints.size() << " bytes)");
5607 if (m_nettype == MAINNET)
5608 {
5609 // first check hash
5610 crypto::hash hash;
5611 if (!tools::sha256sum(checkpoints.data(), checkpoints.size(), hash))
5612 {
5613 MERROR("Failed to hash precomputed blocks data");
5614 return;
5615 }
5616 MINFO("precomputed blocks hash: " << hash << ", expected " << expected_block_hashes_hash);
5617 cryptonote::blobdata expected_hash_data;
5618 if (!epee::string_tools::parse_hexstr_to_binbuff(std::string(expected_block_hashes_hash), expected_hash_data) || expected_hash_data.size() != sizeof(crypto::hash))
5619 {
5620 MERROR("Failed to parse expected block hashes hash");
5621 return;
5622 }
5623 const crypto::hash expected_hash = *reinterpret_cast<const crypto::hash*>(expected_hash_data.data());
5624 if (hash != expected_hash)
5625 {
5626 MERROR("Block hash data does not match expected hash");
5627 return;
5628 }
5629 }
5630
5631 if (checkpoints.size() > 4)
5632 {
5633 const unsigned char *p = checkpoints.data();
5634 const uint32_t nblocks = *p | ((*(p+1))<<8) | ((*(p+2))<<16) | ((*(p+3))<<24);
5635 if (nblocks > (std::numeric_limits<uint32_t>::max() - 4) / sizeof(hash))
5636 {
5637 MERROR("Block hash data is too large");
5638 return;
5639 }
5640 const size_t size_needed = 4 + nblocks * (sizeof(crypto::hash) * 2);
5641 if(checkpoints.size() != size_needed)
5642 {
5643 MERROR("Failed to load hashes - unexpected data size");
5644 return;
5645 }
5646 else if(nblocks > 0 && nblocks > (m_db->height() + HASH_OF_HASHES_STEP - 1) / HASH_OF_HASHES_STEP)
5647 {
5648 p += sizeof(uint32_t);
5649 m_blocks_hash_of_hashes.reserve(nblocks);
5650 for (uint32_t i = 0; i < nblocks; i++)
5651 {
5652 crypto::hash hash_hashes, hash_weights;
5653 memcpy(hash_hashes.data, p, sizeof(hash_hashes.data));
5654 p += sizeof(hash_hashes.data);
5655 memcpy(hash_weights.data, p, sizeof(hash_weights.data));
5656 p += sizeof(hash_weights.data);
5657 m_blocks_hash_of_hashes.push_back(std::make_pair(hash_hashes, hash_weights));
5658 }
5659 m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, std::make_pair(crypto::null_hash, 0));
5660 MINFO(nblocks << " block hashes loaded");
5661
5662 // FIXME: clear tx_pool because the process might have been
5663 // terminated and caused it to store txs kept by blocks.
5664 // The core will not call check_tx_inputs(..) for these
5665 // transactions in this case. Consequently, the sanity check
5666 // for tx hashes will fail in handle_block_to_main_chain(..)
5667 CRITICAL_REGION_LOCAL(m_tx_pool);
5668
5669 std::vector<transaction> txs;
5670 m_tx_pool.get_transactions(txs, true);
5671
5672 size_t tx_weight;
5673 uint64_t fee;
5674 bool relayed, do_not_relay, double_spend_seen, pruned;
5675 transaction pool_tx;
5676 blobdata txblob;
5677 for(const transaction &tx : txs)
5678 {
5679 crypto::hash tx_hash = get_transaction_hash(tx);
5680 m_tx_pool.take_tx(tx_hash, pool_tx, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen, pruned);
5681 }
5682 }
5683 }
5684 }
5685 }
5686 #endif
5687
5688 bool Blockchain::is_within_compiled_block_hash_area(uint64_t height) const
5689 {
5690 #if defined(PER_BLOCK_CHECKPOINT)
5691 return height < m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP;
5692 #else
5693 return false;
5694 #endif
5695 }
5696
5697 void Blockchain::lock()
5698 {
5699 m_blockchain_lock.lock();
5700 }
5701
5702 void Blockchain::unlock()
5703 {
5704 m_blockchain_lock.unlock();
5705 }
5706
5707 bool Blockchain::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const
5708 {
5709 return m_db->for_all_key_images(f);
5710 }
5711
5712 bool Blockchain::for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const block&)> f) const
5713 {
5714 return m_db->for_blocks_range(h1, h2, f);
5715 }
5716
5717 bool Blockchain::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const
5718 {
5719 return m_db->for_all_transactions(f, pruned);
5720 }
5721
5722 bool Blockchain::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)> f) const
5723 {
5724 return m_db->for_all_outputs(f);
5725 }
5726
5727 bool Blockchain::for_all_outputs(uint64_t amount, std::function<bool(uint64_t height)> f) const
5728 {
5729 return m_db->for_all_outputs(amount, f);
5730 }
5731
5732 void Blockchain::invalidate_block_template_cache()
5733 {
5734 MDEBUG("Invalidating block template cache");
5735 m_btc_valid = false;
5736 }
5737
5738 void Blockchain::cache_block_template(const block &b, const cryptonote::account_public_address &address, const blobdata &nonce, const difficulty_type &diff, uint64_t height, uint64_t expected_reward, uint64_t seed_height, const crypto::hash &seed_hash, uint64_t pool_cookie)
5739 {
5740 MDEBUG("Setting block template cache");
5741 m_btc = b;
5742 m_btc_address = address;
5743 m_btc_nonce = nonce;
5744 m_btc_difficulty = diff;
5745 m_btc_height = height;
5746 m_btc_expected_reward = expected_reward;
5747 m_btc_seed_hash = seed_hash;
5748 m_btc_seed_height = seed_height;
5749 m_btc_pool_cookie = pool_cookie;
5750 m_btc_valid = true;
5751 }
5752
5753 void Blockchain::send_miner_notifications(uint64_t height, const crypto::hash &seed_hash, const crypto::hash &prev_id, uint64_t already_generated_coins)
5754 {
5755 if (m_miner_notifiers.empty())
5756 return;
5757
5758 const uint8_t major_version = m_hardfork->get_ideal_version(height);
5759 const difficulty_type diff = get_difficulty_for_next_block();
5760 const uint64_t median_weight = m_current_block_cumul_weight_median;
5761
5762 std::vector<tx_block_template_backlog_entry> tx_backlog;
5763 m_tx_pool.get_block_template_backlog(tx_backlog);
5764
5765 for (const auto& notifier : m_miner_notifiers)
5766 {
5767 notifier(major_version, height, prev_id, seed_hash, diff, median_weight, already_generated_coins, tx_backlog);
5768 }
5769 }
5770
5771 namespace cryptonote {
5772 template bool Blockchain::get_transactions(const std::vector<crypto::hash>&, std::vector<transaction>&, std::vector<crypto::hash>&, bool) const;
5773 template bool Blockchain::get_split_transactions_blobs(const std::vector<crypto::hash>&, std::vector<std::tuple<crypto::hash, cryptonote::blobdata, crypto::hash, cryptonote::blobdata>>&, std::vector<crypto::hash>&) const;
5774 }