Debian Codegraph @

monero/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) 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 = 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 v4, forbid invalid pubkeys
3013 if (hf_version >= 4) {
3014 for (const auto &o: tx.vout) {
3015 crypto::public_key output_public_key;
3016 if (!get_output_public_key(o, output_public_key)) {
3017 tvc.m_invalid_output = true;
3018 return false;
3019 }
3020 if (!crypto::check_key(output_public_key)) {
3021 tvc.m_invalid_output = true;
3022 return false;
3023 }
3024 }
3025 }
3026
3027 // from v8, allow bulletproofs
3028 if (hf_version < 8) {
3029 if (tx.version >= 2) {
3030 const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type);
3031 if (bulletproof || !tx.rct_signatures.p.bulletproofs.empty())
3032 {
3033 MERROR_VER("Bulletproofs are not allowed before v8");
3034 tvc.m_invalid_output = true;
3035 return false;
3036 }
3037 }
3038 }
3039
3040 // from v9, forbid borromean range proofs
3041 if (hf_version > 8) {
3042 if (tx.version >= 2) {
3043 const bool borromean = rct::is_rct_borromean(tx.rct_signatures.type);
3044 if (borromean)
3045 {
3046 MERROR_VER("Borromean range proofs are not allowed after v8");
3047 tvc.m_invalid_output = true;
3048 return false;
3049 }
3050 }
3051 }
3052
3053 // from v10, allow bulletproofs v2
3054 if (hf_version < HF_VERSION_SMALLER_BP) {
3055 if (tx.version >= 2) {
3056 if (tx.rct_signatures.type == rct::RCTTypeBulletproof2)
3057 {
3058 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeBulletproof2 << " is not allowed before v" << HF_VERSION_SMALLER_BP);
3059 tvc.m_invalid_output = true;
3060 return false;
3061 }
3062 }
3063 }
3064
3065 // from v11, allow only bulletproofs v2
3066 if (hf_version > HF_VERSION_SMALLER_BP) {
3067 if (tx.version >= 2) {
3068 if (tx.rct_signatures.type == rct::RCTTypeBulletproof)
3069 {
3070 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeBulletproof << " is not allowed from v" << (HF_VERSION_SMALLER_BP + 1));
3071 tvc.m_invalid_output = true;
3072 return false;
3073 }
3074 }
3075 }
3076
3077 // from v13, allow CLSAGs
3078 if (hf_version < HF_VERSION_CLSAG) {
3079 if (tx.version >= 2) {
3080 if (tx.rct_signatures.type == rct::RCTTypeCLSAG)
3081 {
3082 MERROR_VER("Ringct type " << (unsigned)rct::RCTTypeCLSAG << " is not allowed before v" << HF_VERSION_CLSAG);
3083 tvc.m_invalid_output = true;
3084 return false;
3085 }
3086 }
3087 }
3088
3089 // from v14, allow only CLSAGs
3090 if (hf_version > HF_VERSION_CLSAG) {
3091 if (tx.version >= 2) {
3092 if (tx.rct_signatures.type <= rct::RCTTypeBulletproof2)
3093 {
3094 // two MLSAG txes went in due to a bug with txes that went into the txpool before the fork, grandfather them in
3095 static const char * grandfathered[2] = { "c5151944f0583097ba0c88cd0f43e7fabb3881278aa2f73b3b0a007c5d34e910", "6f2f117cde6fbcf8d4a6ef8974fcac744726574ac38cf25d3322c996b21edd4c" };
3096 crypto::hash h0, h1;
3097 epee::string_tools::hex_to_pod(grandfathered[0], h0);
3098 epee::string_tools::hex_to_pod(grandfathered[1], h1);
3099 if (cryptonote::get_transaction_hash(tx) == h0 || cryptonote::get_transaction_hash(tx) == h1)
3100 {
3101 MDEBUG("Grandfathering cryptonote::get_transaction_hash(tx) in");
3102 }
3103 else
3104 {
3105 MERROR_VER("Ringct type " << (unsigned)tx.rct_signatures.type << " is not allowed from v" << (HF_VERSION_CLSAG + 1));
3106 tvc.m_invalid_output = true;
3107 return false;
3108 }
3109 }
3110 }
3111 }
3112
3113 // from v15, allow bulletproofs plus
3114 if (hf_version < HF_VERSION_BULLETPROOF_PLUS) {
3115 if (tx.version >= 2) {
3116 const bool bulletproof_plus = rct::is_rct_bulletproof_plus(tx.rct_signatures.type);
3117 if (bulletproof_plus || !tx.rct_signatures.p.bulletproofs_plus.empty())
3118 {
3119 MERROR_VER("Bulletproofs plus are not allowed before v" << std::to_string(HF_VERSION_BULLETPROOF_PLUS));
3120 tvc.m_invalid_output = true;
3121 return false;
3122 }
3123 }
3124 }
3125
3126 // from v16, forbid bulletproofs
3127 if (hf_version > HF_VERSION_BULLETPROOF_PLUS) {
3128 if (tx.version >= 2) {
3129 const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type);
3130 if (bulletproof)
3131 {
3132 MERROR_VER("Bulletproof range proofs are not allowed after v" + std::to_string(HF_VERSION_BULLETPROOF_PLUS));
3133 tvc.m_invalid_output = true;
3134 return false;
3135 }
3136 }
3137 }
3138
3139 // from v15, require view tags on outputs
3140 if (!check_output_types(tx, hf_version))
3141 {
3142 tvc.m_invalid_output = true;
3143 return false;
3144 }
3145
3146 return true;
3147 }
3148 //------------------------------------------------------------------
3149 bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const
3150 {
3151 LOG_PRINT_L3("Blockchain::" << __func__);
3152 for (const txin_v& in: tx.vin)
3153 {
3154 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true);
3155 if(have_tx_keyimg_as_spent(in_to_key.k_image))
3156 return true;
3157 }
3158 return false;
3159 }
3160 bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys)
3161 {
3162 PERF_TIMER(expand_transaction_2);
3163 CHECK_AND_ASSERT_MES(tx.version == 2, false, "Transaction version is not 2");
3164
3165 rct::rctSig &rv = tx.rct_signatures;
3166
3167 // message - hash of the transaction prefix
3168 rv.message = rct::hash2rct(tx_prefix_hash);
3169
3170 // mixRing - full and simple store it in opposite ways
3171 if (rv.type == rct::RCTTypeFull)
3172 {
3173 CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys");
3174 rv.mixRing.resize(pubkeys[0].size());
3175 for (size_t m = 0; m < pubkeys[0].size(); ++m)
3176 rv.mixRing[m].clear();
3177 for (size_t n = 0; n < pubkeys.size(); ++n)
3178 {
3179 CHECK_AND_ASSERT_MES(pubkeys[n].size() <= pubkeys[0].size(), false, "More inputs that first ring");
3180 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3181 {
3182 rv.mixRing[m].push_back(pubkeys[n][m]);
3183 }
3184 }
3185 }
3186 else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof || rv.type == rct::RCTTypeBulletproof2 || rv.type == rct::RCTTypeCLSAG || rv.type == rct::RCTTypeBulletproofPlus)
3187 {
3188 CHECK_AND_ASSERT_MES(!pubkeys.empty() && !pubkeys[0].empty(), false, "empty pubkeys");
3189 rv.mixRing.resize(pubkeys.size());
3190 for (size_t n = 0; n < pubkeys.size(); ++n)
3191 {
3192 rv.mixRing[n].clear();
3193 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3194 {
3195 rv.mixRing[n].push_back(pubkeys[n][m]);
3196 }
3197 }
3198 }
3199 else
3200 {
3201 CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type));
3202 }
3203
3204 // II
3205 if (rv.type == rct::RCTTypeFull)
3206 {
3207 if (!tx.pruned)
3208 {
3209 rv.p.MGs.resize(1);
3210 rv.p.MGs[0].II.resize(tx.vin.size());
3211 for (size_t n = 0; n < tx.vin.size(); ++n)
3212 rv.p.MGs[0].II[n] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3213 }
3214 }
3215 else if (rv.type == rct::RCTTypeSimple || rv.type == rct::RCTTypeBulletproof || rv.type == rct::RCTTypeBulletproof2)
3216 {
3217 if (!tx.pruned)
3218 {
3219 CHECK_AND_ASSERT_MES(rv.p.MGs.size() == tx.vin.size(), false, "Bad MGs size");
3220 for (size_t n = 0; n < tx.vin.size(); ++n)
3221 {
3222 rv.p.MGs[n].II.resize(1);
3223 rv.p.MGs[n].II[0] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3224 }
3225 }
3226 }
3227 else if (rv.type == rct::RCTTypeCLSAG || rv.type == rct::RCTTypeBulletproofPlus)
3228 {
3229 if (!tx.pruned)
3230 {
3231 CHECK_AND_ASSERT_MES(rv.p.CLSAGs.size() == tx.vin.size(), false, "Bad CLSAGs size");
3232 for (size_t n = 0; n < tx.vin.size(); ++n)
3233 {
3234 rv.p.CLSAGs[n].I = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image);
3235 }
3236 }
3237 }
3238 else
3239 {
3240 CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type));
3241 }
3242
3243 // outPk was already done by handle_incoming_tx
3244
3245 return true;
3246 }
3247 //------------------------------------------------------------------
3248 // This function validates transaction inputs and their keys.
3249 // FIXME: consider moving functionality specific to one input into
3250 // check_tx_input() rather than here, and use this function simply
3251 // to iterate the inputs as necessary (splitting the task
3252 // using threads, etc.)
3253 bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height) const
3254 {
3255 PERF_TIMER(check_tx_inputs);
3256 LOG_PRINT_L3("Blockchain::" << __func__);
3257 size_t sig_index = 0;
3258 if(pmax_used_block_height)
3259 *pmax_used_block_height = 0;
3260
3261 crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx);
3262
3263 const uint8_t hf_version = m_hardfork->get_current_version();
3264
3265 if (hf_version >= HF_VERSION_MIN_2_OUTPUTS)
3266 {
3267 if (tx.version >= 2)
3268 {
3269 if (tx.vout.size() < 2)
3270 {
3271 MERROR_VER("Tx " << get_transaction_hash(tx) << " has fewer than two outputs");
3272 tvc.m_too_few_outputs = true;
3273 return false;
3274 }
3275 }
3276 }
3277
3278 // from hard fork 2, we require mixin at least 2 unless one output cannot mix with 2 others
3279 // if one output cannot mix with 2 others, we accept at most 1 output that can mix
3280 if (hf_version >= 2)
3281 {
3282 size_t n_unmixable = 0, n_mixable = 0;
3283 size_t min_actual_mixin = std::numeric_limits<size_t>::max();
3284 size_t max_actual_mixin = 0;
3285 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;
3286 for (const auto& txin : tx.vin)
3287 {
3288 // non txin_to_key inputs will be rejected below
3289 if (txin.type() == typeid(txin_to_key))
3290 {
3291 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3292 if (in_to_key.amount == 0)
3293 {
3294 // always consider rct inputs mixable. Even if there's not enough rct
3295 // inputs on the chain to mix with, this is going to be the case for
3296 // just a few blocks right after the fork at most
3297 ++n_mixable;
3298 }
3299 else
3300 {
3301 uint64_t n_outputs = m_db->get_num_outputs(in_to_key.amount);
3302 MDEBUG("output size " << print_money(in_to_key.amount) << ": " << n_outputs << " available");
3303 // n_outputs includes the output we're considering
3304 if (n_outputs <= min_mixin)
3305 ++n_unmixable;
3306 else
3307 ++n_mixable;
3308 }
3309 size_t ring_mixin = in_to_key.key_offsets.size() - 1;
3310 if (ring_mixin < min_actual_mixin)
3311 min_actual_mixin = ring_mixin;
3312 if (ring_mixin > max_actual_mixin)
3313 max_actual_mixin = ring_mixin;
3314 }
3315 }
3316 MDEBUG("Mixin: " << min_actual_mixin << "-" << max_actual_mixin);
3317
3318 if (hf_version >= HF_VERSION_SAME_MIXIN)
3319 {
3320 if (min_actual_mixin != max_actual_mixin)
3321 {
3322 MERROR_VER("Tx " << get_transaction_hash(tx) << " has varying ring size (" << (min_actual_mixin + 1) << "-" << (max_actual_mixin + 1) << "), it should be constant");
3323 tvc.m_low_mixin = true;
3324 return false;
3325 }
3326 }
3327
3328 // The only circumstance where ring sizes less than expected are
3329 // allowed is when spending unmixable non-RCT outputs in the chain.
3330 // Caveat: at HF_VERSION_MIN_MIXIN_15, temporarily allow ring sizes
3331 // of 11 to allow a grace period in the transition to larger ring size.
3332 if (min_actual_mixin < min_mixin && !(hf_version == HF_VERSION_MIN_MIXIN_15 && min_actual_mixin == 10))
3333 {
3334 if (n_unmixable == 0)
3335 {
3336 MERROR_VER("Tx " << get_transaction_hash(tx) << " has too low ring size (" << (min_actual_mixin + 1) << "), and no unmixable inputs");
3337 tvc.m_low_mixin = true;
3338 return false;
3339 }
3340 if (n_mixable > 1)
3341 {
3342 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");
3343 tvc.m_low_mixin = true;
3344 return false;
3345 }
3346 } else if ((hf_version > HF_VERSION_MIN_MIXIN_15 && min_actual_mixin > 15)
3347 || (hf_version == HF_VERSION_MIN_MIXIN_15 && min_actual_mixin != 15 && min_actual_mixin != 10) // grace period to allow either 15 or 10
3348 || (hf_version < HF_VERSION_MIN_MIXIN_15 && hf_version >= HF_VERSION_MIN_MIXIN_10+2 && min_actual_mixin > 10)
3349 || ((hf_version == HF_VERSION_MIN_MIXIN_10 || hf_version == HF_VERSION_MIN_MIXIN_10+1) && min_actual_mixin != 10)
3350 )
3351 {
3352 MERROR_VER("Tx " << get_transaction_hash(tx) << " has invalid ring size (" << (min_actual_mixin + 1) << "), it should be " << (min_mixin + 1));
3353 tvc.m_low_mixin = true;
3354 return false;
3355 }
3356
3357 // min/max tx version based on HF, and we accept v1 txes if having a non mixable
3358 const size_t max_tx_version = (hf_version <= 3) ? 1 : 2;
3359 if (tx.version > max_tx_version)
3360 {
3361 MERROR_VER("transaction version " << (unsigned)tx.version << " is higher than max accepted version " << max_tx_version);
3362 tvc.m_verifivation_failed = true;
3363 return false;
3364 }
3365 const size_t min_tx_version = (n_unmixable > 0 ? 1 : (hf_version >= HF_VERSION_ENFORCE_RCT) ? 2 : 1);
3366 if (tx.version < min_tx_version)
3367 {
3368 MERROR_VER("transaction version " << (unsigned)tx.version << " is lower than min accepted version " << min_tx_version);
3369 tvc.m_verifivation_failed = true;
3370 return false;
3371 }
3372 }
3373
3374 // from v7, sorted ins
3375 if (hf_version >= 7) {
3376 const crypto::key_image *last_key_image = NULL;
3377 for (size_t n = 0; n < tx.vin.size(); ++n)
3378 {
3379 const txin_v &txin = tx.vin[n];
3380 if (txin.type() == typeid(txin_to_key))
3381 {
3382 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3383 if (last_key_image && memcmp(&in_to_key.k_image, last_key_image, sizeof(*last_key_image)) >= 0)
3384 {
3385 MERROR_VER("transaction has unsorted inputs");
3386 tvc.m_verifivation_failed = true;
3387 return false;
3388 }
3389 last_key_image = &in_to_key.k_image;
3390 }
3391 }
3392 }
3393
3394 std::vector<std::vector<rct::ctkey>> pubkeys(tx.vin.size());
3395 std::vector < uint64_t > results;
3396 results.resize(tx.vin.size(), 0);
3397
3398 tools::threadpool& tpool = tools::threadpool::getInstanceForCompute();
3399 tools::threadpool::waiter waiter(tpool);
3400 int threads = tpool.get_max_concurrency();
3401
3402 uint64_t max_used_block_height = 0;
3403 if (!pmax_used_block_height)
3404 pmax_used_block_height = &max_used_block_height;
3405 for (const auto& txin : tx.vin)
3406 {
3407 // make sure output being spent is of type txin_to_key, rather than
3408 // e.g. txin_gen, which is only used for miner transactions
3409 CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at Blockchain::check_tx_inputs");
3410 const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
3411
3412 // make sure tx output has key offset(s) (is signed to be used)
3413 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));
3414
3415 if(have_tx_keyimg_as_spent(in_to_key.k_image))
3416 {
3417 MERROR_VER("Key image already spent in blockchain: " << epee::string_tools::pod_to_hex(in_to_key.k_image));
3418 tvc.m_double_spend = true;
3419 return false;
3420 }
3421
3422 if (tx.version == 1)
3423 {
3424 // basically, make sure number of inputs == number of signatures
3425 CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index);
3426 }
3427
3428 // make sure that output being spent matches up correctly with the
3429 // signature spending it.
3430 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))
3431 {
3432 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);
3433 if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain()
3434 {
3435 MERROR_VER(" *pmax_used_block_height: " << *pmax_used_block_height);
3436 }
3437
3438 return false;
3439 }
3440
3441 if (tx.version == 1)
3442 {
3443 if (threads > 1)
3444 {
3445 // ND: Speedup
3446 // 1. Thread ring signature verification if possible.
3447 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);
3448 }
3449 else
3450 {
3451 check_ring_signature(tx_prefix_hash, in_to_key.k_image, pubkeys[sig_index], tx.signatures[sig_index], results[sig_index]);
3452 if (!results[sig_index])
3453 {
3454 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);
3455
3456 if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain()
3457 {
3458 MERROR_VER("*pmax_used_block_height: " << *pmax_used_block_height);
3459 }
3460
3461 return false;
3462 }
3463 }
3464 }
3465
3466 sig_index++;
3467 }
3468 if (tx.version == 1 && threads > 1)
3469 if (!waiter.wait())
3470 return false;
3471
3472 // enforce min output age
3473 if (hf_version >= HF_VERSION_ENFORCE_MIN_AGE)
3474 {
3475 CHECK_AND_ASSERT_MES(*pmax_used_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= m_db->height(),
3476 false, "Transaction spends at least one output which is too young");
3477 }
3478
3479 // Warn that new RCT types are present, and thus the cache is not being used effectively
3480 static constexpr const std::uint8_t RCT_CACHE_TYPE = rct::RCTTypeBulletproofPlus;
3481 if (tx.rct_signatures.type > RCT_CACHE_TYPE)
3482 {
3483 MWARNING("RCT cache is not caching new verification results. Please update RCT_CACHE_TYPE!");
3484 }
3485
3486 if (tx.version == 1)
3487 {
3488 if (threads > 1)
3489 {
3490 // save results to table, passed or otherwise
3491 bool failed = false;
3492 for (size_t i = 0; i < tx.vin.size(); i++)
3493 {
3494 if(!failed && !results[i])
3495 failed = true;
3496 }
3497
3498 if (failed)
3499 {
3500 MERROR_VER("Failed to check ring signatures!");
3501 return false;
3502 }
3503 }
3504 }
3505 else
3506 {
3507 // from version 2, check ringct signatures
3508 // obviously, the original and simple rct APIs use a mixRing that's indexes
3509 // in opposite orders, because it'd be too simple otherwise...
3510 const rct::rctSig &rv = tx.rct_signatures;
3511 switch (rv.type)
3512 {
3513 case rct::RCTTypeNull: {
3514 // we only accept no signatures for coinbase txes
3515 MERROR_VER("Null rct signature on non-coinbase tx");
3516 return false;
3517 }
3518 case rct::RCTTypeSimple:
3519 case rct::RCTTypeBulletproof:
3520 case rct::RCTTypeBulletproof2:
3521 case rct::RCTTypeCLSAG:
3522 case rct::RCTTypeBulletproofPlus:
3523 {
3524 if (!ver_rct_non_semantics_simple_cached(tx, pubkeys, m_rct_ver_cache, RCT_CACHE_TYPE))
3525 {
3526 MERROR_VER("Failed to check ringct signatures!");
3527 return false;
3528 }
3529 break;
3530 }
3531 case rct::RCTTypeFull:
3532 {
3533 if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys))
3534 {
3535 MERROR_VER("Failed to expand rct signatures!");
3536 return false;
3537 }
3538
3539 // check all this, either reconstructed (so should really pass), or not
3540 {
3541 bool size_matches = true;
3542 for (size_t i = 0; i < pubkeys.size(); ++i)
3543 size_matches &= pubkeys[i].size() == rv.mixRing.size();
3544 for (size_t i = 0; i < rv.mixRing.size(); ++i)
3545 size_matches &= pubkeys.size() == rv.mixRing[i].size();
3546 if (!size_matches)
3547 {
3548 MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size");
3549 return false;
3550 }
3551
3552 for (size_t n = 0; n < pubkeys.size(); ++n)
3553 {
3554 for (size_t m = 0; m < pubkeys[n].size(); ++m)
3555 {
3556 if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest))
3557 {
3558 MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m);
3559 return false;
3560 }
3561 if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask))
3562 {
3563 MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m);
3564 return false;
3565 }
3566 }
3567 }
3568 }
3569
3570 if (rv.p.MGs.size() != 1)
3571 {
3572 MERROR_VER("Failed to check ringct signatures: Bad MGs size");
3573 return false;
3574 }
3575 if (rv.p.MGs.empty() || rv.p.MGs[0].II.size() != tx.vin.size())
3576 {
3577 MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes");
3578 return false;
3579 }
3580 for (size_t n = 0; n < tx.vin.size(); ++n)
3581 {
3582 if (memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32))
3583 {
3584 MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes");
3585 return false;
3586 }
3587 }
3588
3589 if (!rct::verRct(rv, false))
3590 {
3591 MERROR_VER("Failed to check ringct signatures!");
3592 return false;
3593 }
3594 break;
3595 }
3596 default:
3597 MERROR_VER("Unsupported rct type: " << rv.type);
3598 return false;
3599 }
3600
3601 // for bulletproofs, check they're only multi-output after v8
3602 if (rct::is_rct_bulletproof(rv.type))
3603 {
3604 if (hf_version < 8)
3605 {
3606 for (const rct::Bulletproof &proof: rv.p.bulletproofs)
3607 {
3608 if (proof.V.size() > 1)
3609 {
3610 MERROR_VER("Multi output bulletproofs are invalid before v8");
3611 return false;
3612 }
3613 }
3614 }
3615 }
3616 }
3617 return true;
3618 }
3619
3620 //------------------------------------------------------------------
3621 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
3622 {
3623 std::vector<const crypto::public_key *> p_output_keys;
3624 p_output_keys.reserve(pubkeys.size());
3625 for (auto &key : pubkeys)
3626 {
3627 // rct::key and crypto::public_key have the same structure, avoid object ctor/memcpy
3628 p_output_keys.push_back(&(const crypto::public_key&)key.dest);
3629 }
3630
3631 result = crypto::check_ring_signature(tx_prefix_hash, key_image, p_output_keys, sig.data()) ? 1 : 0;
3632 }
3633
3634 //------------------------------------------------------------------
3635 uint64_t Blockchain::get_dynamic_base_fee(uint64_t block_reward, size_t median_block_weight, uint8_t version)
3636 {
3637 const uint64_t min_block_weight = get_min_block_weight(version);
3638 if (median_block_weight < min_block_weight)
3639 median_block_weight = min_block_weight;
3640 uint64_t hi, lo;
3641
3642 if (version >= HF_VERSION_PER_BYTE_FEE)
3643 {
3644 lo = mul128(block_reward, DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT, &hi);
3645 div128_64(hi, lo, median_block_weight, &hi, &lo, NULL, NULL);
3646 if (version >= HF_VERSION_2021_SCALING)
3647 {
3648 // min_fee_per_byte = round_up( 0.95 * block_reward * ref_weight / (fee_median^2) )
3649 // note: since hardfork HF_VERSION_2021_SCALING, fee_median (a.k.a. median_block_weight) equals effective long term median
3650 div128_64(hi, lo, median_block_weight, &hi, &lo, NULL, NULL);
3651 assert(hi == 0);
3652 lo -= lo / 20;
3653 return lo == 0 ? 1 : lo;
3654 }
3655 else
3656 {
3657 // min_fee_per_byte = 0.2 * block_reward * ref_weight / (min_penalty_free_zone * fee_median)
3658 div128_64(hi, lo, min_block_weight, &hi, &lo, NULL, NULL);
3659 assert(hi == 0);
3660 lo /= 5;
3661 return lo;
3662 }
3663 }
3664
3665 const uint64_t fee_base = version >= 5 ? DYNAMIC_FEE_PER_KB_BASE_FEE_V5 : DYNAMIC_FEE_PER_KB_BASE_FEE;
3666
3667 uint64_t unscaled_fee_base = (fee_base * min_block_weight / median_block_weight);
3668 lo = mul128(unscaled_fee_base, block_reward, &hi);
3669 div128_64(hi, lo, DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD, &hi, &lo, NULL, NULL);
3670 assert(hi == 0);
3671
3672 // quantize fee up to 8 decimals
3673 uint64_t mask = get_fee_quantization_mask();
3674 uint64_t qlo = (lo + mask - 1) / mask * mask;
3675 MDEBUG("lo " << print_money(lo) << ", qlo " << print_money(qlo) << ", mask " << mask);
3676
3677 return qlo;
3678 }
3679
3680 //------------------------------------------------------------------
3681 bool Blockchain::check_fee(size_t tx_weight, uint64_t fee) const
3682 {
3683 const uint8_t version = get_current_hard_fork_version();
3684
3685 uint64_t median = 0;
3686 uint64_t already_generated_coins = 0;
3687 uint64_t base_reward = 0;
3688 if (version >= HF_VERSION_DYNAMIC_FEE)
3689 {
3690 median = m_current_block_cumul_weight_limit / 2;
3691 const uint64_t blockchain_height = m_db->height();
3692 already_generated_coins = blockchain_height ? m_db->get_block_already_generated_coins(blockchain_height - 1) : 0;
3693 if (!get_block_reward(median, 1, already_generated_coins, base_reward, version))
3694 return false;
3695 }
3696
3697 uint64_t needed_fee;
3698 if (version >= HF_VERSION_PER_BYTE_FEE)
3699 {
3700 const bool use_long_term_median_in_fee = version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT;
3701 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);
3702 MDEBUG("Using " << print_money(fee_per_byte) << "/byte fee");
3703 needed_fee = tx_weight * fee_per_byte;
3704 // quantize fee up to 8 decimals
3705 const uint64_t mask = get_fee_quantization_mask();
3706 needed_fee = (needed_fee + mask - 1) / mask * mask;
3707 }
3708 else
3709 {
3710 uint64_t fee_per_kb;
3711 if (version < HF_VERSION_DYNAMIC_FEE)
3712 {
3713 fee_per_kb = FEE_PER_KB;
3714 }
3715 else
3716 {
3717 fee_per_kb = get_dynamic_base_fee(base_reward, median, version);
3718 }
3719 MDEBUG("Using " << print_money(fee_per_kb) << "/kB fee");
3720
3721 needed_fee = tx_weight / 1024;
3722 needed_fee += (tx_weight % 1024) ? 1 : 0;
3723 needed_fee *= fee_per_kb;
3724 }
3725
3726 if (fee < needed_fee - needed_fee / 50) // keep a little 2% buffer on acceptance - no integer overflow
3727 {
3728 MERROR_VER("transaction fee is not enough: " << print_money(fee) << ", minimum fee: " << print_money(needed_fee));
3729 return false;
3730 }
3731 return true;
3732 }
3733
3734 //------------------------------------------------------------------
3735 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
3736 {
3737 // variable names and calculations as per https://github.com/ArticMine/Monero-Documents/blob/master/MoneroScaling2021-02.pdf
3738 // from (earlier than) this fork, the base fee is per byte
3739 const uint64_t Mfw = std::min(Mnw, Mlw);
3740
3741 // 3 kB divided by something ? It's going to be either 0 or *very* quantized, so fold it into integer steps below
3742 //const uint64_t Brlw = DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / Mfw;
3743
3744 // constant.... equal to 0, unless floating point, so fold it into integer steps below
3745 //const uint64_t Br = DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5
3746
3747 //const uint64_t Fl = base_reward * Brlw / Mfw; fold Brlw from above
3748 const uint64_t Fl = base_reward * /*Brlw*/ DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (Mfw * Mfw);
3749
3750 // fold Fl into this for better precision (and to match the test cases in the PDF)
3751 // const uint64_t Fn = 4 * Fl;
3752 const uint64_t Fn = 4 * base_reward * /*Brlw*/ DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (Mfw * Mfw);
3753
3754 // const uint64_t Fm = 16 * base_reward * Br / Mfw; fold Br from above
3755 const uint64_t Fm = 16 * base_reward * DYNAMIC_FEE_REFERENCE_TRANSACTION_WEIGHT / (CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5 * Mfw);
3756
3757 // const uint64_t Fp = 2 * base_reward / Mnw;
3758
3759 // fold Br from above, move 4Fm in the max to decrease quantization effect
3760 //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));
3761 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));
3762
3763 fees.resize(4);
3764 fees[0] = cryptonote::round_money_up(Fl, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3765 fees[1] = cryptonote::round_money_up(Fn, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3766 fees[2] = cryptonote::round_money_up(Fm, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3767 fees[3] = cryptonote::round_money_up(Fh, CRYPTONOTE_SCALING_2021_FEE_ROUNDING_PLACES);
3768 }
3769
3770 void Blockchain::get_dynamic_base_fee_estimate_2021_scaling(uint64_t grace_blocks, std::vector<uint64_t> &fees) const
3771 {
3772 const uint8_t version = get_current_hard_fork_version();
3773 const uint64_t db_height = m_db->height();
3774
3775 CHECK_AND_ASSERT_THROW_MES(grace_blocks <= CRYPTONOTE_REWARD_BLOCKS_WINDOW, "Grace blocks invalid In 2021 fee scaling estimate.");
3776
3777 // we want Mlw = median of max((min(Mbw, 1.7 * Ml), Zm), Ml / 1.7)
3778 // Mbw: block weight for the last 99990 blocks, 0 for the next 10
3779 // Ml: penalty free zone (dynamic), aka long_term_median, aka median of max((min(Mb, 1.7 * Ml), Zm), Ml / 1.7)
3780 // Zm: 300000 (minimum penalty free zone)
3781 //
3782 // So we copy the current rolling median state, add 10 (grace_blocks) zeroes to it, and get back Mlw
3783
3784 epee::misc_utils::rolling_median_t<uint64_t> rm = m_long_term_block_weights_cache_rolling_median;
3785 for (size_t i = 0; i < grace_blocks; ++i)
3786 rm.insert(0);
3787 const uint64_t Mlw_penalty_free_zone_for_wallet = std::max<uint64_t>(rm.median(), CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5);
3788
3789 // Msw: median over [100 - grace blocks] past + [grace blocks] future blocks
3790 std::vector<uint64_t> weights;
3791 get_last_n_blocks_weights(weights, 100 - grace_blocks);
3792 weights.reserve(100);
3793 for (size_t i = 0; i < grace_blocks; ++i)
3794 weights.push_back(0);
3795 const uint64_t Msw_effective_short_term_median = std::max(epee::misc_utils::median(weights), Mlw_penalty_free_zone_for_wallet);
3796
3797 const uint64_t Mnw = std::min(Msw_effective_short_term_median, 50 * Mlw_penalty_free_zone_for_wallet);
3798
3799 uint64_t already_generated_coins = db_height ? m_db->get_block_already_generated_coins(db_height - 1) : 0;
3800 uint64_t base_reward;
3801 if (!get_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, version))
3802 {
3803 MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound");
3804 base_reward = BLOCK_REWARD_OVERESTIMATE;
3805 }
3806
3807 get_dynamic_base_fee_estimate_2021_scaling(grace_blocks, base_reward, Mnw, Mlw_penalty_free_zone_for_wallet, fees);
3808 }
3809
3810 //------------------------------------------------------------------
3811 uint64_t Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_blocks) const
3812 {
3813 const uint8_t version = get_current_hard_fork_version();
3814 const uint64_t db_height = m_db->height();
3815
3816 if (version < HF_VERSION_DYNAMIC_FEE)
3817 return FEE_PER_KB;
3818
3819 if (grace_blocks >= CRYPTONOTE_REWARD_BLOCKS_WINDOW)
3820 grace_blocks = CRYPTONOTE_REWARD_BLOCKS_WINDOW - 1;
3821
3822 if (version >= HF_VERSION_2021_SCALING)
3823 {
3824 std::vector<uint64_t> fees;
3825 get_dynamic_base_fee_estimate_2021_scaling(grace_blocks, fees);
3826 return fees[0];
3827 }
3828
3829 const uint64_t min_block_weight = get_min_block_weight(version);
3830 std::vector<uint64_t> weights;
3831 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW - grace_blocks);
3832 weights.reserve(grace_blocks);
3833 for (size_t i = 0; i < grace_blocks; ++i)
3834 weights.push_back(min_block_weight);
3835
3836 uint64_t median = epee::misc_utils::median(weights);
3837 if(median <= min_block_weight)
3838 median = min_block_weight;
3839
3840 uint64_t already_generated_coins = db_height ? m_db->get_block_already_generated_coins(db_height - 1) : 0;
3841 uint64_t base_reward;
3842 if (!get_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, version))
3843 {
3844 MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound");
3845 base_reward = BLOCK_REWARD_OVERESTIMATE;
3846 }
3847
3848 const bool use_long_term_median_in_fee = version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT;
3849 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;
3850 const uint64_t fee = get_dynamic_base_fee(base_reward, use_median_value, version);
3851 const bool per_byte = version < HF_VERSION_PER_BYTE_FEE;
3852 MDEBUG("Estimating " << grace_blocks << "-block fee at " << print_money(fee) << "/" << (per_byte ? "byte" : "kB"));
3853 return fee;
3854 }
3855
3856 //------------------------------------------------------------------
3857 // This function checks to see if a tx is unlocked. unlock_time is either
3858 // a block index or a unix time.
3859 bool Blockchain::is_tx_spendtime_unlocked(uint64_t unlock_time, uint8_t hf_version) const
3860 {
3861 LOG_PRINT_L3("Blockchain::" << __func__);
3862 if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
3863 {
3864 // ND: Instead of calling get_current_blockchain_height(), call m_db->height()
3865 // directly as get_current_blockchain_height() locks the recursive mutex.
3866 if(m_db->height()-1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time)
3867 return true;
3868 else
3869 return false;
3870 }
3871 else
3872 {
3873 //interpret as time
3874 const uint64_t current_time = hf_version >= HF_VERSION_DETERMINISTIC_UNLOCK_TIME ? get_adjusted_time(m_db->height()) : static_cast<uint64_t>(time(NULL));
3875 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)
3876 return true;
3877 else
3878 return false;
3879 }
3880 return false;
3881 }
3882 //------------------------------------------------------------------
3883 // This function locates all outputs associated with a given input (mixins)
3884 // and validates that they exist and are usable. It also checks the ring
3885 // signature for each input.
3886 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
3887 {
3888 LOG_PRINT_L3("Blockchain::" << __func__);
3889
3890 // ND:
3891 // 1. Disable locking and make method private.
3892 //CRITICAL_REGION_LOCAL(m_blockchain_lock);
3893
3894 struct outputs_visitor
3895 {
3896 std::vector<rct::ctkey >& m_output_keys;
3897 const Blockchain& m_bch;
3898 const uint8_t hf_version;
3899 outputs_visitor(std::vector<rct::ctkey>& output_keys, const Blockchain& bch, uint8_t hf_version) :
3900 m_output_keys(output_keys), m_bch(bch), hf_version(hf_version)
3901 {
3902 }
3903 bool handle_output(uint64_t unlock_time, const crypto::public_key &pubkey, const rct::key &commitment)
3904 {
3905 //check tx unlock time
3906 if (!m_bch.is_tx_spendtime_unlocked(unlock_time, hf_version))
3907 {
3908 MERROR_VER("One of outputs for one of inputs has wrong tx.unlock_time = " << unlock_time);
3909 return false;
3910 }
3911
3912 // The original code includes a check for the output corresponding to this input
3913 // to be a txout_to_key. This is removed, as the database does not store this info.
3914 // Only txout_to_key (and since HF_VERSION_VIEW_TAGS, txout_to_tagged_key)
3915 // outputs are stored in the DB in the first place, done in Blockchain*::add_output.
3916 // Additional type checks on outputs were also added via cryptonote::check_output_types
3917 // and cryptonote::get_output_public_key (see Blockchain::check_tx_outputs).
3918
3919 m_output_keys.push_back(rct::ctkey({rct::pk2rct(pubkey), commitment}));
3920 return true;
3921 }
3922 };
3923
3924 output_keys.clear();
3925
3926 // collect output keys
3927 outputs_visitor vi(output_keys, *this, hf_version);
3928 if (!scan_outputkeys_for_indexes(tx_version, txin, vi, tx_prefix_hash, pmax_related_block_height))
3929 {
3930 MERROR_VER("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size());
3931 return false;
3932 }
3933
3934 if(txin.key_offsets.size() != output_keys.size())
3935 {
3936 MERROR_VER("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size());
3937 return false;
3938 }
3939 if (tx_version == 1) {
3940 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());
3941 }
3942 // rct_signatures will be expanded after this
3943 return true;
3944 }
3945 //------------------------------------------------------------------
3946 // only works on the main chain
3947 uint64_t Blockchain::get_adjusted_time(uint64_t height) const
3948 {
3949 LOG_PRINT_L3("Blockchain::" << __func__);
3950
3951 // if not enough blocks, no proper median yet, return current time
3952 if(height < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
3953 {
3954 return static_cast<uint64_t>(time(NULL));
3955 }
3956 std::vector<uint64_t> timestamps;
3957
3958 // need most recent 60 blocks, get index of first of those
3959 size_t offset = height - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW;
3960 timestamps.reserve(height - offset);
3961 for(;offset < height; ++offset)
3962 {
3963 timestamps.push_back(m_db->get_block_timestamp(offset));
3964 }
3965 uint64_t median_ts = epee::misc_utils::median(timestamps);
3966
3967 // project the median to match approximately when the block being validated will appear
3968 // the median is calculated from a chunk of past blocks, so we use +1 to offset onto the current block
3969 median_ts += (BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW + 1) * DIFFICULTY_TARGET_V2 / 2;
3970
3971 // project the current block's time based on the previous block's time
3972 // we don't use the current block's time directly to mitigate timestamp manipulation
3973 uint64_t adjusted_current_block_ts = timestamps.back() + DIFFICULTY_TARGET_V2;
3974
3975 // return minimum of ~current block time and adjusted median time
3976 // we do this since it's better to report a time in the past than a time in the future
3977 return (adjusted_current_block_ts < median_ts ? adjusted_current_block_ts : median_ts);
3978 }
3979 //------------------------------------------------------------------
3980 //TODO: revisit, has changed a bit on upstream
3981 bool Blockchain::check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b, uint64_t& median_ts) const
3982 {
3983 LOG_PRINT_L3("Blockchain::" << __func__);
3984 median_ts = epee::misc_utils::median(timestamps);
3985
3986 if(b.timestamp < median_ts)
3987 {
3988 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);
3989 return false;
3990 }
3991
3992 return true;
3993 }
3994 //------------------------------------------------------------------
3995 // This function grabs the timestamps from the most recent <n> blocks,
3996 // where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many
3997 // blocks in the blockchain, the timestap is assumed to be valid. If there
3998 // are, this function returns:
3999 // true if the block's timestamp is not less than the timestamp of the
4000 // median of the selected blocks
4001 // false otherwise
4002 bool Blockchain::check_block_timestamp(const block& b, uint64_t& median_ts) const
4003 {
4004 LOG_PRINT_L3("Blockchain::" << __func__);
4005 if(b.timestamp > (uint64_t)time(NULL) + CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT)
4006 {
4007 MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than local time + 2 hours");
4008 return false;
4009 }
4010
4011 const auto h = m_db->height();
4012
4013 // if not enough blocks, no proper median yet, return true
4014 if(h < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
4015 {
4016 return true;
4017 }
4018
4019 std::vector<uint64_t> timestamps;
4020
4021 // need most recent 60 blocks, get index of first of those
4022 size_t offset = h - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW;
4023 timestamps.reserve(h - offset);
4024 for(;offset < h; ++offset)
4025 {
4026 timestamps.push_back(m_db->get_block_timestamp(offset));
4027 }
4028
4029 return check_block_timestamp(timestamps, b, median_ts);
4030 }
4031 //------------------------------------------------------------------
4032 bool Blockchain::flush_txes_from_pool(const std::vector<crypto::hash> &txids)
4033 {
4034 CRITICAL_REGION_LOCAL(m_tx_pool);
4035
4036 bool res = true;
4037 for (const auto &txid: txids)
4038 {
4039 cryptonote::transaction tx;
4040 cryptonote::blobdata txblob;
4041 size_t tx_weight;
4042 uint64_t fee;
4043 bool relayed, do_not_relay, double_spend_seen, pruned;
4044 MINFO("Removing txid " << txid << " from the pool");
4045 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))
4046 {
4047 MERROR("Failed to remove txid " << txid << " from the pool");
4048 res = false;
4049 }
4050 }
4051 return res;
4052 }
4053 //------------------------------------------------------------------
4054 // Needs to validate the block and acquire each transaction from the
4055 // transaction mem_pool, then pass the block and transactions to
4056 // m_db->add_block()
4057 bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id,
4058 block_verification_context& bvc, pool_supplement& extra_block_txs)
4059 {
4060 LOG_PRINT_L3("Blockchain::" << __func__);
4061
4062 TIME_MEASURE_START(block_processing_time);
4063 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4064 TIME_MEASURE_START(t1);
4065
4066 static bool seen_future_version = false;
4067
4068 db_rtxn_guard rtxn_guard(m_db);
4069 uint64_t blockchain_height;
4070 const crypto::hash top_hash = get_tail_id(blockchain_height);
4071 ++blockchain_height; // block height to chain height
4072 if(bl.prev_id != top_hash)
4073 {
4074 MERROR_VER("Block with id: " << id << std::endl << "has wrong prev_id: " << bl.prev_id << std::endl << "expected: " << top_hash);
4075 bvc.m_verifivation_failed = true;
4076 leave:
4077 return false;
4078 }
4079
4080 // warn users if they're running an old version
4081 if (!seen_future_version && bl.major_version > m_hardfork->get_ideal_version())
4082 {
4083 seen_future_version = true;
4084 const el::Level level = el::Level::Warning;
4085 MCLOG_RED(level, "global", "**********************************************************************");
4086 MCLOG_RED(level, "global", "A block was seen on the network with a version higher than the last");
4087 MCLOG_RED(level, "global", "known one. This may be an old version of the daemon, and a software");
4088 MCLOG_RED(level, "global", "update may be required to sync further. Try running: update check");
4089 MCLOG_RED(level, "global", "**********************************************************************");
4090 }
4091
4092 // this is a cheap test
4093 const uint8_t hf_version = get_current_hard_fork_version();
4094 if (!m_hardfork->check(bl))
4095 {
4096 MERROR_VER("Block with id: " << id << std::endl << "has old version: " << (unsigned)bl.major_version << std::endl << "current: " << (unsigned)hf_version);
4097 bvc.m_verifivation_failed = true;
4098 goto leave;
4099 }
4100
4101 TIME_MEASURE_FINISH(t1);
4102 TIME_MEASURE_START(t2);
4103
4104 // make sure block timestamp is not less than the median timestamp
4105 // of a set number of the most recent blocks.
4106 if(!check_block_timestamp(bl))
4107 {
4108 MERROR_VER("Block with id: " << id << std::endl << "has invalid timestamp: " << bl.timestamp);
4109 bvc.m_verifivation_failed = true;
4110 goto leave;
4111 }
4112
4113 TIME_MEASURE_FINISH(t2);
4114 //check proof of work
4115 TIME_MEASURE_START(target_calculating_time);
4116
4117 // get the target difficulty for the block.
4118 // the calculation can overflow, among other failure cases,
4119 // so we need to check the return type.
4120 // FIXME: get_difficulty_for_next_block can also assert, look into
4121 // changing this to throwing exceptions instead so we can clean up.
4122 difficulty_type current_diffic = get_difficulty_for_next_block();
4123 CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!");
4124
4125 TIME_MEASURE_FINISH(target_calculating_time);
4126
4127 TIME_MEASURE_START(longhash_calculating_time);
4128
4129 crypto::hash proof_of_work;
4130 memset(proof_of_work.data, 0xff, sizeof(proof_of_work.data));
4131
4132 // Formerly the code below contained an if loop with the following condition
4133 // !m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height())
4134 // however, this caused the daemon to not bother checking PoW for blocks
4135 // before checkpoints, which is very dangerous behaviour. We moved the PoW
4136 // validation out of the next chunk of code to make sure that we correctly
4137 // check PoW now.
4138 // FIXME: height parameter is not used...should it be used or should it not
4139 // be a parameter?
4140 // validate proof_of_work versus difficulty target
4141 bool precomputed = false;
4142 bool fast_check = false;
4143 #if defined(PER_BLOCK_CHECKPOINT)
4144 if (blockchain_height < m_blocks_hash_check.size())
4145 {
4146 const auto &expected_hash = m_blocks_hash_check[blockchain_height].first;
4147 if (expected_hash != crypto::null_hash)
4148 {
4149 if (memcmp(&id, &expected_hash, sizeof(hash)) != 0)
4150 {
4151 MERROR_VER("Block with id is INVALID: " << id << ", expected " << expected_hash);
4152 bvc.m_verifivation_failed = true;
4153 goto leave;
4154 }
4155 fast_check = true;
4156 }
4157 else
4158 {
4159 MCINFO("verify", "No pre-validated hash at height " << blockchain_height << ", verifying fully");
4160 }
4161 }
4162 #endif
4163 if (!fast_check)
4164 {
4165 auto it = m_blocks_longhash_table.find(id);
4166 if (it != m_blocks_longhash_table.end())
4167 {
4168 precomputed = true;
4169 proof_of_work = it->second;
4170 }
4171 else
4172 proof_of_work = get_block_longhash(this, bl, blockchain_height, 0);
4173
4174 // validate proof_of_work versus difficulty target
4175 if(!check_hash(proof_of_work, current_diffic))
4176 {
4177 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);
4178 bvc.m_verifivation_failed = true;
4179 bvc.m_bad_pow = true;
4180 goto leave;
4181 }
4182 }
4183
4184 // If we're at a checkpoint, ensure that our hardcoded checkpoint hash
4185 // is correct.
4186 if(m_checkpoints.is_in_checkpoint_zone(blockchain_height))
4187 {
4188 if(!m_checkpoints.check_block(blockchain_height, id))
4189 {
4190 LOG_ERROR("CHECKPOINT VALIDATION FAILED");
4191 bvc.m_verifivation_failed = true;
4192 goto leave;
4193 }
4194 }
4195
4196 TIME_MEASURE_FINISH(longhash_calculating_time);
4197 if (precomputed)
4198 longhash_calculating_time += m_fake_pow_calc_time;
4199
4200 TIME_MEASURE_START(t3);
4201
4202 // sanity check basic miner tx properties;
4203 if(!prevalidate_miner_transaction(bl, blockchain_height, hf_version))
4204 {
4205 MERROR_VER("Block with id: " << id << " failed to pass prevalidation");
4206 bvc.m_verifivation_failed = true;
4207 goto leave;
4208 }
4209
4210 // verify all non-input consensus rules for txs inside the pool supplement (if not inside checkpoint zone)
4211 #if defined(PER_BLOCK_CHECKPOINT)
4212 if (!fast_check)
4213 #endif
4214 {
4215 tx_verification_context tvc{};
4216 // If fail non-input consensus rule checking...
4217 if (!ver_non_input_consensus(extra_block_txs, tvc, hf_version))
4218 {
4219 MERROR_VER("Pool supplement provided for block with id: " << id << " failed to pass validation");
4220 bvc.m_verifivation_failed = true;
4221 goto leave;
4222 }
4223 }
4224
4225 size_t coinbase_weight = get_transaction_weight(bl.miner_tx);
4226 size_t cumulative_block_weight = coinbase_weight;
4227
4228 std::vector<std::pair<transaction, blobdata>> txs;
4229 // txid weight mempool?
4230 std::vector<std::tuple<crypto::hash, size_t, bool>> txs_meta;
4231
4232 // This will be the data sent to the ZMQ pool listeners for txs which skipped the mempool
4233 std::vector<txpool_event> txpool_events;
4234
4235 // this lambda returns relevant txs back to the mempool
4236 auto return_txs_to_pool = [this, &txs, &txs_meta, &hf_version]()
4237 {
4238 if (txs_meta.size() != txs.size())
4239 {
4240 MERROR("BUG: txs_meta and txs not matching size!!!");
4241 return;
4242 }
4243
4244 for (size_t i = 0; i < txs.size(); ++i)
4245 {
4246 // if this transaction wasn't ever in the pool, don't return it back to the pool
4247 const bool found_in_pool = std::get<2>(txs_meta[i]);
4248 if (!found_in_pool)
4249 continue;
4250
4251 transaction &tx = txs[i].first;
4252 const crypto::hash &txid = std::get<0>(txs_meta[i]);
4253 const blobdata &tx_blob = txs[i].second;
4254 const size_t tx_weight = std::get<1>(txs_meta[i]);
4255
4256 // We assume that if they were in a block, the transactions are already known to the network
4257 // as a whole. However, if we had mined that block, that might not be always true. Unlikely
4258 // though, and always relaying these again might cause a spike of traffic as many nodes
4259 // re-relay all the transactions in a popped block when a reorg happens. You might notice that
4260 // we also set the "nic_verified_hf_version" paramater. Since we know we took this transaction
4261 // from the mempool earlier in this function call, when the mempool has the same current fork
4262 // version, we can return it without re-verifying the consensus rules on it.
4263 cryptonote::tx_verification_context tvc{};
4264 if (!m_tx_pool.add_tx(tx, txid, tx_blob, tx_weight, tvc, relay_method::block, true,
4265 hf_version, hf_version))
4266 MERROR("Failed to return taken transaction with hash: " << txid << " to tx_pool");
4267 }
4268 };
4269
4270 key_images_container keys;
4271
4272 uint64_t fee_summary = 0;
4273 uint64_t t_checktx = 0;
4274 uint64_t t_exists = 0;
4275 uint64_t t_pool = 0;
4276 uint64_t t_dblspnd = 0;
4277 uint64_t n_pruned = 0;
4278 TIME_MEASURE_FINISH(t3);
4279
4280 // XXX old code adds miner tx here
4281
4282 // Iterate over the block's transaction hashes, grabbing each
4283 // from the tx_pool (or from extra_block_txs) and validating them. Each is then added
4284 // to txs. Keys spent in each are added to <keys> by the double spend check.
4285 txs.reserve(bl.tx_hashes.size());
4286 txs_meta.reserve(bl.tx_hashes.size());
4287 txpool_events.reserve(bl.tx_hashes.size());
4288 for (const crypto::hash& tx_id : bl.tx_hashes)
4289 {
4290 TIME_MEASURE_START(aa);
4291
4292 // XXX old code does not check whether tx exists
4293 if (m_db->tx_exists(tx_id))
4294 {
4295 MERROR("Block with id: " << id << " attempting to add transaction already in blockchain with id: " << tx_id);
4296 bvc.m_verifivation_failed = true;
4297 return_txs_to_pool();
4298 return false;
4299 }
4300
4301 TIME_MEASURE_FINISH(aa);
4302 t_exists += aa;
4303 TIME_MEASURE_START(bb);
4304
4305 // get transaction with hash <tx_id> from m_tx_pool or extra_block_txs
4306 // tx info we want:
4307 // * tx as `cryptonote::transaction`
4308 // * blob
4309 // * weight
4310 // * fee
4311 // * is pruned?
4312 txs.emplace_back();
4313 transaction &tx = txs.back().first;
4314 blobdata &txblob = txs.back().second;
4315 size_t tx_weight{};
4316 uint64_t fee{};
4317 bool pruned{};
4318
4319 /*
4320 * Try pulling transaction data from the mempool proper first. If that fails, then try pulling
4321 * from the block supplement. We add txs pulled from the block to the txpool events for future
4322 * notifications, since if the tx skipped the mempool, then listeners have not yet received a
4323 * notification for this tx.
4324 */
4325 bool _unused1, _unused2, _unused3;
4326 const bool found_tx_in_pool{
4327 m_tx_pool.take_tx(tx_id, tx, txblob, tx_weight, fee,
4328 _unused1, _unused2, _unused3, pruned, /*suppress_missing_msgs=*/true)
4329 };
4330 bool find_tx_failure{!found_tx_in_pool};
4331 if (!found_tx_in_pool) // if not in mempool:
4332 {
4333 const auto extra_txs_it{extra_block_txs.txs_by_txid.find(tx_id)};
4334 if (extra_txs_it != extra_block_txs.txs_by_txid.end()) // if in block supplement:
4335 {
4336 tx = std::move(extra_txs_it->second.first);
4337 txblob = std::move(extra_txs_it->second.second);
4338 tx_weight = tx.pruned ? get_pruned_transaction_weight(tx) : get_transaction_weight(tx, txblob.size());
4339 fee = get_tx_fee(tx);
4340 pruned = tx.pruned;
4341 extra_block_txs.txs_by_txid.erase(extra_txs_it);
4342 txpool_events.emplace_back(txpool_event{tx, tx_id, txblob.size(), tx_weight, true});
4343 find_tx_failure = false;
4344 }
4345 }
4346
4347 // @TODO: We should move this section (checking if the daemon has all txs from the block) to
4348 // right after the PoW check. Since it's now expected the node will sometimes not have all txs
4349 // in its pool at this point nor the txs included as fluffy txs (and will need to re-request
4350 // missing fluffy txs), then the node will sometimes waste cycles doing verification for some
4351 // txs twice.
4352 if (find_tx_failure) // did not find txid in mempool or provided extra block txs
4353 {
4354 const bool fully_supplemented_block = extra_block_txs.txs_by_txid.size() >= bl.tx_hashes.size();
4355 if (fully_supplemented_block)
4356 MERROR_VER("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id);
4357 else
4358 LOG_PRINT_L2("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id);
4359 txs.pop_back(); // We push to the back preemptively. On fail, we need txs & txs_meta to match size
4360 bvc.m_verifivation_failed = true;
4361 bvc.m_missing_txs = true;
4362 return_txs_to_pool();
4363 return false;
4364 }
4365 if (pruned)
4366 ++n_pruned;
4367
4368 TIME_MEASURE_FINISH(bb);
4369 t_pool += bb;
4370 // add the transaction to the temp list of transactions, so we can either
4371 // store the list of transactions all at once or return the ones we've
4372 // taken from the tx_pool back to it if the block fails verification.
4373 txs_meta.emplace_back(tx_id, tx_weight, found_tx_in_pool);
4374 TIME_MEASURE_START(dd);
4375
4376 // FIXME: the storage should not be responsible for validation.
4377 // If it does any, it is merely a sanity check.
4378 // Validation is the purview of the Blockchain class
4379 // - TW
4380 //
4381 // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly.
4382 // if (!check_for_double_spend(tx, keys))
4383 // {
4384 // LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id);
4385 // bvc.m_verifivation_failed = true;
4386 // break;
4387 // }
4388
4389 TIME_MEASURE_FINISH(dd);
4390 t_dblspnd += dd;
4391 TIME_MEASURE_START(cc);
4392
4393 #if defined(PER_BLOCK_CHECKPOINT)
4394 if (!fast_check)
4395 #endif
4396 {
4397 // validate that transaction inputs and the keys spending them are correct.
4398 tx_verification_context tvc;
4399 if(!check_tx_inputs(tx, tvc))
4400 {
4401 MERROR_VER("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs.");
4402
4403 //TODO: why is this done? make sure that keeping invalid blocks makes sense.
4404 add_block_as_invalid(bl, id);
4405 MERROR_VER("Block with id " << id << " added as invalid because of wrong inputs in transactions");
4406 bvc.m_verifivation_failed = true;
4407 return_txs_to_pool();
4408 return false;
4409 }
4410 }
4411
4412 TIME_MEASURE_FINISH(cc);
4413 t_checktx += cc;
4414 fee_summary += fee;
4415 cumulative_block_weight += tx_weight;
4416 }
4417
4418 // if we were syncing pruned blocks
4419 if (n_pruned > 0)
4420 {
4421 if (blockchain_height >= m_blocks_hash_check.size() || m_blocks_hash_check[blockchain_height].second == 0)
4422 {
4423 MERROR("Block at " << blockchain_height << " is pruned, but we do not have a weight for it");
4424 goto leave;
4425 }
4426 cumulative_block_weight = m_blocks_hash_check[blockchain_height].second;
4427 }
4428
4429 TIME_MEASURE_START(vmt);
4430 uint64_t base_reward = 0;
4431 uint64_t already_generated_coins = blockchain_height ? m_db->get_block_already_generated_coins(blockchain_height - 1) : 0;
4432 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()))
4433 {
4434 MERROR_VER("Block with id: " << id << " has incorrect miner transaction");
4435 bvc.m_verifivation_failed = true;
4436 return_txs_to_pool();
4437 return false;
4438 }
4439
4440 TIME_MEASURE_FINISH(vmt);
4441 size_t block_weight;
4442 difficulty_type cumulative_difficulty;
4443
4444 // populate various metadata about the block to be stored alongside it.
4445 block_weight = cumulative_block_weight;
4446 cumulative_difficulty = current_diffic;
4447 // In the "tail" state when the minimum subsidy (implemented in get_block_reward) is in effect, the number of
4448 // coins will eventually exceed MONEY_SUPPLY and overflow a uint64. To prevent overflow, cap already_generated_coins
4449 // at MONEY_SUPPLY. already_generated_coins is only used to compute the block subsidy and MONEY_SUPPLY yields a
4450 // subsidy of 0 under the base formula and therefore the minimum subsidy >0 in the tail state.
4451 already_generated_coins = base_reward < (MONEY_SUPPLY-already_generated_coins) ? already_generated_coins + base_reward : MONEY_SUPPLY;
4452 if(blockchain_height)
4453 cumulative_difficulty += m_db->get_block_cumulative_difficulty(blockchain_height - 1);
4454
4455 TIME_MEASURE_FINISH(block_processing_time);
4456 if(precomputed)
4457 block_processing_time += m_fake_pow_calc_time;
4458
4459 rtxn_guard.stop();
4460 TIME_MEASURE_START(addblock);
4461 uint64_t new_height = 0;
4462 if (!bvc.m_verifivation_failed)
4463 {
4464 try
4465 {
4466 uint64_t long_term_block_weight = get_next_long_term_block_weight(block_weight);
4467 cryptonote::blobdata bd = cryptonote::block_to_blob(bl);
4468 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);
4469 }
4470 catch (const KEY_IMAGE_EXISTS& e)
4471 {
4472 LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what());
4473 m_batch_success = false;
4474 bvc.m_verifivation_failed = true;
4475 return_txs_to_pool();
4476 return false;
4477 }
4478 catch (const std::exception& e)
4479 {
4480 //TODO: figure out the best way to deal with this failure
4481 LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what());
4482 m_batch_success = false;
4483 bvc.m_verifivation_failed = true;
4484 return_txs_to_pool();
4485 return false;
4486 }
4487 }
4488 else
4489 {
4490 LOG_ERROR("Blocks that failed verification should not reach here");
4491 }
4492
4493 TIME_MEASURE_FINISH(addblock);
4494
4495 // do this after updating the hard fork state since the weight limit may change due to fork
4496 if (!update_next_cumulative_weight_limit())
4497 {
4498 MERROR("Failed to update next cumulative weight limit");
4499 pop_block_from_blockchain();
4500 return false;
4501 }
4502
4503 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");
4504 if(m_show_time_stats)
4505 {
4506 MINFO("Height: " << new_height << " coinbase weight: " << coinbase_weight << " cumm: "
4507 << cumulative_block_weight << " p/t: " << block_processing_time << " ("
4508 << target_calculating_time << "/" << longhash_calculating_time << "/"
4509 << t1 << "/" << t2 << "/" << t3 << "/" << t_exists << "/" << t_pool
4510 << "/" << t_checktx << "/" << t_dblspnd << "/" << vmt << "/" << addblock << ")ms");
4511 }
4512
4513 bvc.m_added_to_main_chain = true;
4514 ++m_sync_counter;
4515
4516 // appears to be a NOP *and* is called elsewhere. wat?
4517 m_tx_pool.on_blockchain_inc(new_height, id);
4518 get_difficulty_for_next_block(); // just to cache it
4519 invalidate_block_template_cache();
4520
4521 const uint8_t new_hf_version = get_current_hard_fork_version();
4522 if (new_hf_version != hf_version)
4523 {
4524 // the genesis block is added before everything's setup, and the txpool is empty
4525 // when we start from scratch, so we skip this
4526 const bool is_genesis_block = new_height == 1;
4527 if (!is_genesis_block)
4528 {
4529 MGINFO("Validating txpool for v" << (unsigned)new_hf_version);
4530 m_tx_pool.validate(new_hf_version);
4531 }
4532 }
4533
4534 const crypto::hash seedhash = get_block_id_by_height(crypto::rx_seedheight(new_height));
4535 send_miner_notifications(new_height, seedhash, id, already_generated_coins);
4536
4537 // Make sure that txpool notifications happen BEFORE block notifications
4538 notify_txpool_event(std::move(txpool_events));
4539
4540 for (const auto& notifier: m_block_notifiers)
4541 notifier(new_height - 1, {std::addressof(bl), 1});
4542
4543 if (m_hardfork->get_current_version() >= RX_BLOCK_VERSION)
4544 rx_set_main_seedhash(seedhash.data, tools::get_max_concurrency());
4545
4546 return true;
4547 }
4548 //------------------------------------------------------------------
4549 bool Blockchain::prune_blockchain(uint32_t pruning_seed)
4550 {
4551 m_tx_pool.lock();
4552 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4553 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4554
4555 return m_db->prune_blockchain(pruning_seed);
4556 }
4557 //------------------------------------------------------------------
4558 bool Blockchain::update_blockchain_pruning()
4559 {
4560 m_tx_pool.lock();
4561 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4562 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4563
4564 return m_db->update_pruning();
4565 }
4566 //------------------------------------------------------------------
4567 bool Blockchain::check_blockchain_pruning()
4568 {
4569 m_tx_pool.lock();
4570 epee::misc_utils::auto_scope_leave_caller unlocker = epee::misc_utils::create_scope_leave_handler([&](){m_tx_pool.unlock();});
4571 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4572
4573 return m_db->check_pruning();
4574 }
4575 //------------------------------------------------------------------
4576 // 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
4577 uint64_t Blockchain::get_next_long_term_block_weight(uint64_t block_weight) const
4578 {
4579 PERF_TIMER(get_next_long_term_block_weight);
4580
4581 const uint64_t db_height = m_db->height();
4582 const uint64_t nblocks = std::min<uint64_t>(m_long_term_block_weights_window, db_height);
4583
4584 const uint8_t hf_version = get_current_hard_fork_version();
4585 if (hf_version < HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
4586 return block_weight;
4587
4588 uint64_t long_term_median = get_long_term_block_weight_median(db_height - nblocks, nblocks);
4589 uint64_t long_term_effective_median_block_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, long_term_median);
4590
4591 uint64_t short_term_constraint;
4592 if (hf_version >= HF_VERSION_2021_SCALING)
4593 {
4594 // long_term_block_weight = block_weight bounded to range [long-term-median/1.7, long-term-median*1.7]
4595 block_weight = std::max<uint64_t>(block_weight, long_term_effective_median_block_weight * 10 / 17);
4596 short_term_constraint = long_term_effective_median_block_weight + long_term_effective_median_block_weight * 7 / 10;
4597 }
4598 else
4599 {
4600 // long_term_block_weight = block_weight bounded to range [0, long-term-median*1.4]
4601 short_term_constraint = long_term_effective_median_block_weight + long_term_effective_median_block_weight * 2 / 5;
4602 }
4603 uint64_t long_term_block_weight = std::min<uint64_t>(block_weight, short_term_constraint);
4604
4605 return long_term_block_weight;
4606 }
4607 //------------------------------------------------------------------
4608 bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight)
4609 {
4610 PERF_TIMER(update_next_cumulative_weight_limit);
4611
4612 LOG_PRINT_L3("Blockchain::" << __func__);
4613
4614 // when we reach this, the last hf version is not yet written to the db
4615 const uint64_t db_height = m_db->height();
4616 const uint8_t hf_version = get_current_hard_fork_version();
4617 uint64_t full_reward_zone = get_min_block_weight(hf_version);
4618
4619 if (hf_version < HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
4620 {
4621 std::vector<uint64_t> weights;
4622 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
4623 m_current_block_cumul_weight_median = epee::misc_utils::median(weights);
4624 }
4625 else
4626 {
4627 const uint64_t nblocks = std::min<uint64_t>(m_long_term_block_weights_window, db_height);
4628 const uint64_t long_term_median = get_long_term_block_weight_median(db_height - nblocks, nblocks);
4629
4630 m_long_term_effective_median_block_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, long_term_median);
4631
4632 std::vector<uint64_t> weights;
4633 get_last_n_blocks_weights(weights, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
4634
4635 uint64_t short_term_median = epee::misc_utils::median(weights);
4636 uint64_t effective_median_block_weight;
4637 if (hf_version >= HF_VERSION_2021_SCALING)
4638 {
4639 // effective median = short_term_median bounded to range [long_term_median, 50*long_term_median], but it can't be smaller than the
4640 // minimum penalty free zone (a.k.a. 'full reward zone')
4641 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);
4642 }
4643 else
4644 {
4645 // effective median = short_term_median bounded to range [0, 50*long_term_median], but it can't be smaller than the
4646 // minimum penalty free zone (a.k.a. 'full reward zone')
4647 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);
4648 }
4649
4650 m_current_block_cumul_weight_median = effective_median_block_weight;
4651 }
4652
4653 if (m_current_block_cumul_weight_median <= full_reward_zone)
4654 m_current_block_cumul_weight_median = full_reward_zone;
4655
4656 m_current_block_cumul_weight_limit = m_current_block_cumul_weight_median * 2;
4657
4658 if (long_term_effective_median_block_weight)
4659 *long_term_effective_median_block_weight = m_long_term_effective_median_block_weight;
4660
4661 if (!m_db->is_read_only())
4662 m_db->add_max_block_size(m_current_block_cumul_weight_limit);
4663
4664 return true;
4665 }
4666 //------------------------------------------------------------------
4667 bool Blockchain::add_new_block(const block& bl_, block_verification_context& bvc)
4668 {
4669 pool_supplement ps{};
4670 return add_new_block(bl_, bvc, ps);
4671 }
4672 //------------------------------------------------------------------
4673 bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc,
4674 pool_supplement& extra_block_txs)
4675 {
4676 try
4677 {
4678
4679 LOG_PRINT_L3("Blockchain::" << __func__);
4680 crypto::hash id = get_block_hash(bl);
4681 CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process
4682 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
4683 db_rtxn_guard rtxn_guard(m_db);
4684 if(have_block(id))
4685 {
4686 LOG_PRINT_L3("block with id = " << id << " already exists");
4687 bvc.m_already_exists = true;
4688 return false;
4689 }
4690
4691 //check that block refers to chain tail
4692 if(!(bl.prev_id == get_tail_id()))
4693 {
4694 //chain switching or wrong block
4695 bvc.m_added_to_main_chain = false;
4696 rtxn_guard.stop();
4697 return handle_alternative_block(bl, id, bvc, extra_block_txs);
4698 //never relay alternative blocks
4699 }
4700
4701 rtxn_guard.stop();
4702 return handle_block_to_main_chain(bl, id, bvc, extra_block_txs);
4703
4704 }
4705 catch (const std::exception &e)
4706 {
4707 LOG_ERROR("Exception at [add_new_block], what=" << e.what());
4708 bvc.m_verifivation_failed = true;
4709 return false;
4710 }
4711 }
4712 //------------------------------------------------------------------
4713 //TODO: Refactor, consider returning a failure height and letting
4714 // caller decide course of action.
4715 void Blockchain::check_against_checkpoints(const checkpoints& points, bool enforce)
4716 {
4717 const auto& pts = points.get_points();
4718 bool stop_batch;
4719
4720 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4721 stop_batch = m_db->batch_start();
4722 const uint64_t blockchain_height = m_db->height();
4723 for (const auto& pt : pts)
4724 {
4725 // if the checkpoint is for a block we don't have yet, move on
4726 if (pt.first >= blockchain_height)
4727 {
4728 continue;
4729 }
4730
4731 if (!points.check_block(pt.first, m_db->get_block_hash_from_height(pt.first)))
4732 {
4733 // if asked to enforce checkpoints, roll back to a couple of blocks before the checkpoint
4734 if (enforce)
4735 {
4736 LOG_ERROR("Local blockchain failed to pass a checkpoint, rolling back!");
4737 std::list<block> empty;
4738 rollback_blockchain_switching(empty, pt.first - 2);
4739 }
4740 else
4741 {
4742 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");
4743 }
4744 }
4745 }
4746 if (stop_batch)
4747 m_db->batch_stop();
4748 }
4749 //------------------------------------------------------------------
4750 // returns false if any of the checkpoints loading returns false.
4751 // That should happen only if a checkpoint is added that conflicts
4752 // with an existing checkpoint.
4753 bool Blockchain::update_checkpoints(const std::string& file_path, bool check_dns)
4754 {
4755 if (!m_checkpoints.load_checkpoints_from_json(file_path))
4756 {
4757 return false;
4758 }
4759
4760 // if we're checking both dns and json, load checkpoints from dns.
4761 // if we're not hard-enforcing dns checkpoints, handle accordingly
4762 if (m_enforce_dns_checkpoints && check_dns && !m_offline)
4763 {
4764 if (!m_checkpoints.load_checkpoints_from_dns())
4765 {
4766 return false;
4767 }
4768 }
4769 else if (check_dns && !m_offline)
4770 {
4771 checkpoints dns_points;
4772 dns_points.load_checkpoints_from_dns();
4773 if (m_checkpoints.check_for_conflicts(dns_points))
4774 {
4775 check_against_checkpoints(dns_points, false);
4776 }
4777 else
4778 {
4779 MERROR("One or more checkpoints fetched from DNS conflicted with existing checkpoints!");
4780 }
4781 }
4782
4783 check_against_checkpoints(m_checkpoints, true);
4784
4785 return true;
4786 }
4787 //------------------------------------------------------------------
4788 void Blockchain::set_enforce_dns_checkpoints(bool enforce_checkpoints)
4789 {
4790 m_enforce_dns_checkpoints = enforce_checkpoints;
4791 }
4792
4793 //------------------------------------------------------------------
4794 void Blockchain::block_longhash_worker(uint64_t height, const epee::span<const block> &blocks, std::unordered_map<crypto::hash, crypto::hash> &map) const
4795 {
4796 TIME_MEASURE_START(t);
4797 slow_hash_allocate_state();
4798
4799 for (const auto & block : blocks)
4800 {
4801 if (m_cancel)
4802 break;
4803 crypto::hash id = get_block_hash(block);
4804 crypto::hash pow = get_block_longhash(this, block, height++, 0);
4805 map.emplace(id, pow);
4806 }
4807
4808 slow_hash_free_state();
4809 TIME_MEASURE_FINISH(t);
4810 }
4811
4812 //------------------------------------------------------------------
4813 bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync)
4814 {
4815 bool success = false;
4816
4817 MTRACE("Blockchain::" << __func__);
4818 CRITICAL_REGION_BEGIN(m_blockchain_lock);
4819 TIME_MEASURE_START(t1);
4820
4821 try
4822 {
4823 if (m_batch_success)
4824 {
4825 m_db->batch_stop();
4826 if (m_reset_timestamps_and_difficulties_height)
4827 {
4828 m_timestamps_and_difficulties_height = 0;
4829 m_reset_timestamps_and_difficulties_height = false;
4830 }
4831 }
4832 else
4833 m_db->batch_abort();
4834 success = true;
4835 }
4836 catch (const std::exception &e)
4837 {
4838 MERROR("Exception in cleanup_handle_incoming_blocks: " << e.what());
4839 }
4840
4841 if (success && m_sync_counter > 0)
4842 {
4843 if (force_sync)
4844 {
4845 if(m_db_sync_mode != db_nosync)
4846 store_blockchain();
4847 m_sync_counter = 0;
4848 }
4849 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)))
4850 {
4851 MDEBUG("Sync threshold met, syncing");
4852 if(m_db_sync_mode == db_async)
4853 {
4854 m_sync_counter = 0;
4855 m_bytes_to_sync = 0;
4856 boost::asio::dispatch(m_async_service, boost::bind(&Blockchain::store_blockchain, this));
4857 }
4858 else if(m_db_sync_mode == db_sync)
4859 {
4860 store_blockchain();
4861 }
4862 else // db_nosync
4863 {
4864 // DO NOTHING, not required to call sync.
4865 }
4866 }
4867 }
4868
4869 TIME_MEASURE_FINISH(t1);
4870 m_blocks_longhash_table.clear();
4871 m_scan_table.clear();
4872
4873 // when we're well clear of the precomputed hashes, free the memory
4874 if (!m_blocks_hash_check.empty() && m_db->height() > m_blocks_hash_check.size() + 4096)
4875 {
4876 MINFO("Dumping block hashes, we're now 4k past " << m_blocks_hash_check.size());
4877 m_blocks_hash_check.clear();
4878 m_blocks_hash_check.shrink_to_fit();
4879 }
4880
4881 CRITICAL_REGION_END();
4882 m_tx_pool.unlock();
4883
4884 update_blockchain_pruning();
4885
4886 return success;
4887 }
4888
4889 //------------------------------------------------------------------
4890 void Blockchain::output_scan_worker(const uint64_t amount, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs) const
4891 {
4892 try
4893 {
4894 m_db->get_output_key(epee::span<const uint64_t>(&amount, 1), offsets, outputs, true);
4895 }
4896 catch (const std::exception& e)
4897 {
4898 MERROR_VER("EXCEPTION: " << e.what());
4899 }
4900 catch (...)
4901 {
4902
4903 }
4904 }
4905
4906 uint64_t Blockchain::prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights)
4907 {
4908 // new: . . . . . X X X X X . . . . . .
4909 // pre: A A A A B B B B C C C C D D D D
4910
4911 CHECK_AND_ASSERT_MES(weights.empty() || weights.size() == hashes.size(), 0, "Unexpected weights size");
4912
4913 CRITICAL_REGION_LOCAL(m_blockchain_lock);
4914
4915 // easy case: height >= hashes
4916 if (height >= m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP)
4917 return hashes.size();
4918
4919 // if we're getting old blocks, we might have jettisoned the hashes already
4920 if (m_blocks_hash_check.empty())
4921 return hashes.size();
4922
4923 // find hashes encompassing those block
4924 size_t first_index = height / HASH_OF_HASHES_STEP;
4925 size_t last_index = (height + hashes.size() - 1) / HASH_OF_HASHES_STEP;
4926 MDEBUG("Blocks " << height << " - " << (height + hashes.size() - 1) << " start at " << first_index << " and end at " << last_index);
4927
4928 // case of not enough to calculate even a single hash
4929 if (first_index == last_index && hashes.size() < HASH_OF_HASHES_STEP && (height + hashes.size()) % HASH_OF_HASHES_STEP)
4930 return hashes.size();
4931
4932 // build hashes vector to hash hashes together
4933 std::vector<crypto::hash> data_hashes;
4934 std::vector<uint64_t> data_weights;
4935 data_hashes.reserve(hashes.size() + HASH_OF_HASHES_STEP - 1); // may be a bit too much
4936 if (!weights.empty())
4937 data_weights.reserve(data_hashes.size());
4938
4939 // we expect height to be either equal or a bit below db height
4940 bool disconnected = (height > m_db->height());
4941 size_t pop;
4942 if (disconnected && height % HASH_OF_HASHES_STEP)
4943 {
4944 ++first_index;
4945 pop = HASH_OF_HASHES_STEP - height % HASH_OF_HASHES_STEP;
4946 }
4947 else
4948 {
4949 // we might need some already in the chain for the first part of the first hash
4950 for (uint64_t h = first_index * HASH_OF_HASHES_STEP; h < height; ++h)
4951 {
4952 data_hashes.push_back(m_db->get_block_hash_from_height(h));
4953 if (!weights.empty())
4954 data_weights.push_back(m_db->get_block_weight(h));
4955 }
4956 pop = 0;
4957 }
4958
4959 // push the data to check
4960 for (size_t i = 0; i < hashes.size(); ++i)
4961 {
4962 if (pop)
4963 --pop;
4964 else
4965 {
4966 data_hashes.push_back(hashes[i]);
4967 if (!weights.empty())
4968 data_weights.push_back(weights[i]);
4969 }
4970 }
4971
4972 // hash and check
4973 uint64_t usable = first_index * HASH_OF_HASHES_STEP - height; // may start negative, but unsigned under/overflow is not UB
4974 for (size_t n = first_index; n <= last_index; ++n)
4975 {
4976 if (n < m_blocks_hash_of_hashes.size())
4977 {
4978 // if the last index isn't fully filled, we can't tell if valid
4979 if (data_hashes.size() < (n - first_index) * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP)
4980 break;
4981
4982 crypto::hash hash;
4983 cn_fast_hash(data_hashes.data() + (n - first_index) * HASH_OF_HASHES_STEP, HASH_OF_HASHES_STEP * sizeof(crypto::hash), hash);
4984 bool valid = hash == m_blocks_hash_of_hashes[n].first;
4985 if (valid && !weights.empty())
4986 {
4987 cn_fast_hash(data_weights.data() + (n - first_index) * HASH_OF_HASHES_STEP, HASH_OF_HASHES_STEP * sizeof(uint64_t), hash);
4988 valid &= hash == m_blocks_hash_of_hashes[n].second;
4989 }
4990
4991 // add to the known hashes array
4992 if (!valid)
4993 {
4994 MDEBUG("invalid hash for blocks " << n * HASH_OF_HASHES_STEP << " - " << (n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP - 1));
4995 break;
4996 }
4997
4998 size_t end = n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP;
4999 for (size_t i = n * HASH_OF_HASHES_STEP; i < end; ++i)
5000 {
5001 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],
5002 0, "Consistency failure in m_blocks_hash_check construction");
5003 m_blocks_hash_check[i].first = data_hashes[i - first_index * HASH_OF_HASHES_STEP];
5004 if (!weights.empty())
5005 {
5006 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],
5007 0, "Consistency failure in m_blocks_hash_check construction");
5008 m_blocks_hash_check[i].second = data_weights[i - first_index * HASH_OF_HASHES_STEP];
5009 }
5010 }
5011 usable += HASH_OF_HASHES_STEP;
5012 }
5013 else
5014 {
5015 // if after the end of the precomputed blocks, accept anything
5016 usable += HASH_OF_HASHES_STEP;
5017 if (usable > hashes.size())
5018 usable = hashes.size();
5019 }
5020 }
5021 MDEBUG("usable: " << usable << " / " << hashes.size());
5022 CHECK_AND_ASSERT_MES(usable < std::numeric_limits<uint64_t>::max() / 2, 0, "usable is negative");
5023 return usable;
5024 }
5025
5026 bool Blockchain::has_block_weights(uint64_t height, uint64_t nblocks) const
5027 {
5028 CHECK_AND_ASSERT_MES(nblocks > 0, false, "nblocks is 0");
5029 uint64_t last_block_height = height + nblocks - 1;
5030 if (last_block_height >= m_blocks_hash_check.size())
5031 return false;
5032 for (uint64_t h = height; h <= last_block_height; ++h)
5033 if (m_blocks_hash_check[h].second == 0)
5034 return false;
5035 return true;
5036 }
5037
5038 //------------------------------------------------------------------
5039 // ND: Speedups:
5040 // 1. Thread long_hash computations if possible (m_max_prepare_blocks_threads = nthreads, default = 4)
5041 // 2. Group all amounts (from txs) and related absolute offsets and form a table of tx_prefix_hash
5042 // vs [k_image, output_keys] (m_scan_table). This is faster because it takes advantage of bulk queries
5043 // and is threaded if possible. The table (m_scan_table) will be used later when querying output
5044 // keys.
5045 bool Blockchain::prepare_handle_incoming_blocks(const std::vector<block_complete_entry> &blocks_entry, std::vector<block> &blocks)
5046 {
5047 MTRACE("Blockchain::" << __func__);
5048 TIME_MEASURE_START(prepare);
5049 bool stop_batch;
5050 uint64_t bytes = 0;
5051 size_t total_txs = 0;
5052 blocks.clear();
5053
5054 // Order of locking must be:
5055 // m_incoming_tx_lock (optional)
5056 // m_tx_pool lock
5057 // blockchain lock
5058 //
5059 // Something which takes the blockchain lock may never take the txpool lock
5060 // if it has not provably taken the txpool lock earlier
5061 //
5062 // The txpool lock is now taken in prepare_handle_incoming_blocks
5063 // and released in cleanup_handle_incoming_blocks. This avoids issues
5064 // when something uses the pool, which now uses the blockchain and
5065 // needs a batch, since a batch could otherwise be active while the
5066 // txpool and blockchain locks were not held
5067
5068 m_tx_pool.lock();
5069 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
5070
5071 if(blocks_entry.size() == 0)
5072 return false;
5073
5074 for (const auto &entry : blocks_entry)
5075 {
5076 bytes += entry.block.size();
5077 for (const auto &tx_blob : entry.txs)
5078 {
5079 bytes += tx_blob.blob.size();
5080 }
5081 total_txs += entry.txs.size();
5082 }
5083 m_bytes_to_sync += bytes;
5084 while (!(stop_batch = m_db->batch_start(blocks_entry.size(), bytes))) {
5085 m_blockchain_lock.unlock();
5086 m_tx_pool.unlock();
5087 epee::misc_utils::sleep_no_w(1000);
5088 m_tx_pool.lock();
5089 m_blockchain_lock.lock();
5090 }
5091 m_batch_success = true;
5092
5093 const uint64_t height = m_db->height();
5094 if ((height + blocks_entry.size()) < m_blocks_hash_check.size())
5095 return true;
5096
5097 bool blocks_exist = false;
5098 tools::threadpool& tpool = tools::threadpool::getInstanceForCompute();
5099 unsigned threads = tpool.get_max_concurrency();
5100 blocks.resize(blocks_entry.size());
5101
5102 if (1)
5103 {
5104 // limit threads, default limit = 4
5105 if(threads > m_max_prepare_blocks_threads)
5106 threads = m_max_prepare_blocks_threads;
5107
5108 unsigned int batches = blocks_entry.size() / threads;
5109 unsigned int extra = blocks_entry.size() % threads;
5110 MDEBUG("block_batches: " << batches);
5111 std::vector<std::unordered_map<crypto::hash, crypto::hash>> maps(threads);
5112 auto it = blocks_entry.begin();
5113 unsigned blockidx = 0;
5114
5115 const crypto::hash tophash = m_db->top_block_hash();
5116 for (unsigned i = 0; i < threads; i++)
5117 {
5118 for (unsigned int j = 0; j < batches; j++, ++blockidx)
5119 {
5120 block &block = blocks[blockidx];
5121 crypto::hash block_hash;
5122
5123 if (!parse_and_validate_block_from_blob(it->block, block, block_hash))
5124 return false;
5125
5126 // check first block and skip all blocks if its not chained properly
5127 if (blockidx == 0)
5128 {
5129 if (block.prev_id != tophash)
5130 {
5131 MDEBUG("Skipping prepare blocks. New blocks don't belong to chain.");
5132 blocks.clear();
5133 return true;
5134 }
5135 }
5136 if (have_block(block_hash))
5137 blocks_exist = true;
5138
5139 std::advance(it, 1);
5140 }
5141 }
5142
5143 for (unsigned i = 0; i < extra && !blocks_exist; i++, blockidx++)
5144 {
5145 block &block = blocks[blockidx];
5146 crypto::hash block_hash;
5147
5148 if (!parse_and_validate_block_from_blob(it->block, block, block_hash))
5149 return false;
5150
5151 if (have_block(block_hash))
5152 blocks_exist = true;
5153
5154 std::advance(it, 1);
5155 }
5156
5157 if (!blocks_exist)
5158 {
5159 m_blocks_longhash_table.clear();
5160 uint64_t thread_height = height;
5161 tools::threadpool::waiter waiter(tpool);
5162 m_prepare_height = height;
5163 m_prepare_nblocks = blocks_entry.size();
5164 m_prepare_blocks = &blocks;
5165 for (unsigned int i = 0; i < threads; i++)
5166 {
5167 unsigned nblocks = batches;
5168 if (i < extra)
5169 ++nblocks;
5170 if (nblocks == 0)
5171 break;
5172 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);
5173 thread_height += nblocks;
5174 }
5175
5176 if (!waiter.wait())
5177 return false;
5178 m_prepare_height = 0;
5179
5180 if (m_cancel)
5181 return false;
5182
5183 for (const auto & map : maps)
5184 {
5185 m_blocks_longhash_table.insert(map.begin(), map.end());
5186 }
5187 }
5188 }
5189
5190 if (m_cancel)
5191 return false;
5192
5193 if (blocks_exist)
5194 {
5195 MDEBUG("Skipping remainder of prepare blocks. Blocks exist.");
5196 return true;
5197 }
5198
5199 m_fake_scan_time = 0;
5200 m_fake_pow_calc_time = 0;
5201
5202 m_scan_table.clear();
5203
5204 TIME_MEASURE_FINISH(prepare);
5205 m_fake_pow_calc_time = prepare / blocks_entry.size();
5206
5207 if (blocks_entry.size() > 1 && threads > 1 && m_show_time_stats)
5208 MDEBUG("Prepare blocks took: " << prepare << " ms");
5209
5210 TIME_MEASURE_START(scantable);
5211
5212 // [input] stores all unique amounts found
5213 std::vector < uint64_t > amounts;
5214 // [input] stores all absolute_offsets for each amount
5215 std::map<uint64_t, std::vector<uint64_t>> offset_map;
5216 // [output] stores all output_data_t for each absolute_offset
5217 std::map<uint64_t, std::vector<output_data_t>> tx_map;
5218 std::vector<std::pair<cryptonote::transaction, crypto::hash>> txes(total_txs);
5219
5220 #define SCAN_TABLE_QUIT(m) \
5221 do { \
5222 MERROR_VER(m) ;\
5223 m_scan_table.clear(); \
5224 return false; \
5225 } while(0); \
5226
5227 // generate sorted tables for all amounts and absolute offsets
5228 size_t tx_index = 0, block_index = 0;
5229 for (const auto &entry : blocks_entry)
5230 {
5231 if (m_cancel)
5232 return false;
5233
5234 for (const auto &tx_blob : entry.txs)
5235 {
5236 if (tx_index >= txes.size())
5237 SCAN_TABLE_QUIT("tx_index is out of sync");
5238 transaction &tx = txes[tx_index].first;
5239 crypto::hash &tx_prefix_hash = txes[tx_index].second;
5240 ++tx_index;
5241
5242 if (!parse_and_validate_tx_base_from_blob(tx_blob.blob, tx))
5243 SCAN_TABLE_QUIT("Could not parse tx from incoming blocks.");
5244 cryptonote::get_transaction_prefix_hash(tx, tx_prefix_hash);
5245
5246 auto its = m_scan_table.find(tx_prefix_hash);
5247 if (its != m_scan_table.end())
5248 SCAN_TABLE_QUIT("Duplicate tx found from incoming blocks.");
5249
5250 m_scan_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>());
5251 its = m_scan_table.find(tx_prefix_hash);
5252 assert(its != m_scan_table.end());
5253
5254 // get all amounts from tx.vin(s)
5255 for (const auto &txin : tx.vin)
5256 {
5257 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5258
5259 // check for duplicate
5260 auto it = its->second.find(in_to_key.k_image);
5261 if (it != its->second.end())
5262 SCAN_TABLE_QUIT("Duplicate key_image found from incoming blocks.");
5263
5264 amounts.push_back(in_to_key.amount);
5265 }
5266
5267 // sort and remove duplicate amounts from amounts list
5268 std::sort(amounts.begin(), amounts.end());
5269 auto last = std::unique(amounts.begin(), amounts.end());
5270 amounts.erase(last, amounts.end());
5271
5272 // add amount to the offset_map and tx_map
5273 for (const uint64_t &amount : amounts)
5274 {
5275 if (offset_map.find(amount) == offset_map.end())
5276 offset_map.emplace(amount, std::vector<uint64_t>());
5277
5278 if (tx_map.find(amount) == tx_map.end())
5279 tx_map.emplace(amount, std::vector<output_data_t>());
5280 }
5281
5282 // add new absolute_offsets to offset_map
5283 for (const auto &txin : tx.vin)
5284 {
5285 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5286 // no need to check for duplicate here.
5287 auto absolute_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets);
5288 for (const auto & offset : absolute_offsets)
5289 offset_map[in_to_key.amount].push_back(offset);
5290
5291 }
5292 }
5293 ++block_index;
5294 }
5295
5296 // sort and remove duplicate absolute_offsets in offset_map
5297 for (auto &offsets : offset_map)
5298 {
5299 std::sort(offsets.second.begin(), offsets.second.end());
5300 auto last = std::unique(offsets.second.begin(), offsets.second.end());
5301 offsets.second.erase(last, offsets.second.end());
5302 }
5303
5304 // gather all the output keys
5305 threads = tpool.get_max_concurrency();
5306 if (!m_db->can_thread_bulk_indices())
5307 threads = 1;
5308
5309 if (threads > 1 && amounts.size() > 1)
5310 {
5311 tools::threadpool::waiter waiter(tpool);
5312
5313 for (size_t i = 0; i < amounts.size(); i++)
5314 {
5315 uint64_t amount = amounts[i];
5316 tpool.submit(&waiter, boost::bind(&Blockchain::output_scan_worker, this, amount, std::cref(offset_map[amount]), std::ref(tx_map[amount])), true);
5317 }
5318 if (!waiter.wait())
5319 return false;
5320 }
5321 else
5322 {
5323 for (size_t i = 0; i < amounts.size(); i++)
5324 {
5325 uint64_t amount = amounts[i];
5326 output_scan_worker(amount, offset_map[amount], tx_map[amount]);
5327 }
5328 }
5329
5330 // now generate a table for each tx_prefix and k_image hashes
5331 tx_index = 0;
5332 for (const auto &entry : blocks_entry)
5333 {
5334 if (m_cancel)
5335 return false;
5336
5337 for (size_t i = 0; i < entry.txs.size(); ++i)
5338 {
5339 if (tx_index >= txes.size())
5340 SCAN_TABLE_QUIT("tx_index is out of sync");
5341 const transaction &tx = txes[tx_index].first;
5342 const crypto::hash &tx_prefix_hash = txes[tx_index].second;
5343 ++tx_index;
5344
5345 auto its = m_scan_table.find(tx_prefix_hash);
5346 if (its == m_scan_table.end())
5347 SCAN_TABLE_QUIT("Tx not found on scan table from incoming blocks.");
5348
5349 for (const auto &txin : tx.vin)
5350 {
5351 const txin_to_key &in_to_key = boost::get < txin_to_key > (txin);
5352 auto needed_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets);
5353
5354 std::vector<output_data_t> outputs;
5355 for (const uint64_t & offset_needed : needed_offsets)
5356 {
5357 size_t pos = 0;
5358 bool found = false;
5359
5360 for (const uint64_t &offset_found : offset_map[in_to_key.amount])
5361 {
5362 if (offset_needed == offset_found)
5363 {
5364 found = true;
5365 break;
5366 }
5367
5368 ++pos;
5369 }
5370
5371 if (found && pos < tx_map[in_to_key.amount].size())
5372 outputs.push_back(tx_map[in_to_key.amount].at(pos));
5373 else
5374 break;
5375 }
5376
5377 its->second.emplace(in_to_key.k_image, outputs);
5378 }
5379 }
5380 }
5381
5382 TIME_MEASURE_FINISH(scantable);
5383 if (total_txs > 0)
5384 {
5385 m_fake_scan_time = scantable / total_txs;
5386 if(m_show_time_stats)
5387 MDEBUG("Prepare scantable took: " << scantable << " ms");
5388 }
5389
5390 return true;
5391 }
5392
5393 void Blockchain::prepare_handle_incoming_block_no_preprocess(const size_t block_byte_estimate)
5394 {
5395 // acquire locks
5396 m_tx_pool.lock();
5397 CRITICAL_REGION_LOCAL1(m_blockchain_lock);
5398
5399 // increment sync byte counter to trigger sync against database backing store
5400 // later in cleanup_handle_incoming_blocks()
5401 m_bytes_to_sync += block_byte_estimate;
5402
5403 // spin until we start a batch
5404 while (!m_db->batch_start(1, block_byte_estimate)) {
5405 m_blockchain_lock.unlock();
5406 m_tx_pool.unlock();
5407 epee::misc_utils::sleep_no_w(1000);
5408 m_tx_pool.lock();
5409 m_blockchain_lock.lock();
5410 }
5411 m_batch_success = true;
5412 }
5413
5414 void Blockchain::add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata &blob, const txpool_tx_meta_t &meta)
5415 {
5416 m_db->add_txpool_tx(txid, blob, meta);
5417 }
5418
5419 void Blockchain::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta)
5420 {
5421 m_db->update_txpool_tx(txid, meta);
5422 }
5423
5424 void Blockchain::remove_txpool_tx(const crypto::hash &txid)
5425 {
5426 m_db->remove_txpool_tx(txid);
5427 }
5428
5429 uint64_t Blockchain::get_txpool_tx_count(bool include_sensitive) const
5430 {
5431 return m_db->get_txpool_tx_count(include_sensitive ? relay_category::all : relay_category::broadcasted);
5432 }
5433
5434 bool Blockchain::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const
5435 {
5436 return m_db->get_txpool_tx_meta(txid, meta);
5437 }
5438
5439 bool Blockchain::get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const
5440 {
5441 return m_db->get_txpool_tx_blob(txid, bd, tx_category);
5442 }
5443
5444 cryptonote::blobdata Blockchain::get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const
5445 {
5446 return m_db->get_txpool_tx_blob(txid, tx_category);
5447 }
5448
5449 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
5450 {
5451 return m_db->for_all_txpool_txes(f, include_blob, tx_category);
5452 }
5453
5454 bool Blockchain::txpool_tx_matches_category(const crypto::hash& tx_hash, relay_category category)
5455 {
5456 return m_db->txpool_tx_matches_category(tx_hash, category);
5457 }
5458
5459 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)
5460 {
5461 if (sync_mode == db_defaultsync)
5462 {
5463 m_db_default_sync = true;
5464 sync_mode = db_async;
5465 }
5466 m_db_sync_mode = sync_mode;
5467 m_fast_sync = fast_sync;
5468 m_db_sync_on_blocks = sync_on_blocks;
5469 m_db_sync_threshold = sync_threshold;
5470 m_max_prepare_blocks_threads = maxthreads;
5471 }
5472
5473 void Blockchain::set_txpool_notify(TxpoolNotifyCallback&& notify)
5474 {
5475 std::lock_guard<decltype(m_txpool_notifier_mutex)> lg(m_txpool_notifier_mutex);
5476 m_txpool_notifier = notify;
5477 }
5478
5479 void Blockchain::add_block_notify(BlockNotifyCallback&& notify)
5480 {
5481 if (notify)
5482 {
5483 CRITICAL_REGION_LOCAL(m_blockchain_lock);
5484 m_block_notifiers.push_back(std::move(notify));
5485 }
5486 }
5487
5488 void Blockchain::add_miner_notify(MinerNotifyCallback&& notify)
5489 {
5490 if (notify)
5491 {
5492 CRITICAL_REGION_LOCAL(m_blockchain_lock);
5493 m_miner_notifiers.push_back(std::move(notify));
5494 }
5495 }
5496
5497 void Blockchain::notify_txpool_event(std::vector<txpool_event>&& event) const
5498 {
5499 std::lock_guard<decltype(m_txpool_notifier_mutex)> lg(m_txpool_notifier_mutex);
5500 if (m_txpool_notifier)
5501 {
5502 try
5503 {
5504 m_txpool_notifier(std::move(event));
5505 }
5506 catch (const std::exception &e)
5507 {
5508 MDEBUG("During Blockchain::notify_txpool_event(), ignored exception: " << e.what());
5509 }
5510 }
5511 }
5512
5513 void Blockchain::safesyncmode(const bool onoff)
5514 {
5515 /* all of this is no-op'd if the user set a specific
5516 * --db-sync-mode at startup.
5517 */
5518 if (m_db_default_sync)
5519 {
5520 m_db->safesyncmode(onoff);
5521 m_db_sync_mode = onoff ? db_nosync : db_async;
5522 }
5523 }
5524
5525 HardFork::State Blockchain::get_hard_fork_state() const
5526 {
5527 return m_hardfork->get_state();
5528 }
5529
5530 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
5531 {
5532 return m_hardfork->get_voting_info(version, window, votes, threshold, earliest_height, voting);
5533 }
5534
5535 uint64_t Blockchain::get_difficulty_target() const
5536 {
5537 return get_current_hard_fork_version() < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2;
5538 }
5539
5540 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
5541 {
5542 return m_db->get_output_histogram(amounts, unlocked, recent_cutoff, min_count);
5543 }
5544
5545 std::vector<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> Blockchain::get_alternative_chains() const
5546 {
5547 std::vector<std::pair<Blockchain::block_extended_info,std::vector<crypto::hash>>> chains;
5548
5549 blocks_ext_by_hash alt_blocks;
5550 alt_blocks.reserve(m_db->get_alt_block_count());
5551 m_db->for_all_alt_blocks([&alt_blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const cryptonote::blobdata_ref *blob) {
5552 if (!blob)
5553 {
5554 MERROR("No blob, but blobs were requested");
5555 return false;
5556 }
5557 cryptonote::block bl;
5558 block_extended_info bei;
5559 if (cryptonote::parse_and_validate_block_from_blob(*blob, bei.bl))
5560 {
5561 bei.height = data.height;
5562 bei.block_cumulative_weight = data.cumulative_weight;
5563 bei.cumulative_difficulty = data.cumulative_difficulty_high;
5564 bei.cumulative_difficulty = (bei.cumulative_difficulty << 64) + data.cumulative_difficulty_low;
5565 bei.already_generated_coins = data.already_generated_coins;
5566 alt_blocks.insert(std::make_pair(cryptonote::get_block_hash(bei.bl), std::move(bei)));
5567 }
5568 else
5569 MERROR("Failed to parse block from blob");
5570 return true;
5571 }, true);
5572
5573 for (const auto &i: alt_blocks)
5574 {
5575 const crypto::hash top = cryptonote::get_block_hash(i.second.bl);
5576 bool found = false;
5577 for (const auto &j: alt_blocks)
5578 {
5579 if (j.second.bl.prev_id == top)
5580 {
5581 found = true;
5582 break;
5583 }
5584 }
5585 if (!found)
5586 {
5587 std::vector<crypto::hash> chain;
5588 auto h = i.second.bl.prev_id;
5589 chain.push_back(top);
5590 blocks_ext_by_hash::const_iterator prev;
5591 while ((prev = alt_blocks.find(h)) != alt_blocks.end())
5592 {
5593 chain.push_back(h);
5594 h = prev->second.bl.prev_id;
5595 }
5596 chains.push_back(std::make_pair(i.second, chain));
5597 }
5598 }
5599 return chains;
5600 }
5601
5602 void Blockchain::cancel()
5603 {
5604 m_cancel = true;
5605 }
5606
5607 #if defined(PER_BLOCK_CHECKPOINT)
5608 static const char expected_block_hashes_hash[] = "e3087cc643a8cb9e2f0a1e54e87f67f087a72e41701b469f5dfed39fd484ca4a";
5609 void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get_checkpoints)
5610 {
5611 if (get_checkpoints == nullptr || !m_fast_sync)
5612 {
5613 return;
5614 }
5615 const epee::span<const unsigned char> &checkpoints = get_checkpoints(m_nettype);
5616 if (!checkpoints.empty())
5617 {
5618 MINFO("Loading precomputed blocks (" << checkpoints.size() << " bytes)");
5619 if (m_nettype == MAINNET)
5620 {
5621 // first check hash
5622 crypto::hash hash;
5623 if (!tools::sha256sum(checkpoints.data(), checkpoints.size(), hash))
5624 {
5625 MERROR("Failed to hash precomputed blocks data");
5626 return;
5627 }
5628 MINFO("precomputed blocks hash: " << hash << ", expected " << expected_block_hashes_hash);
5629 cryptonote::blobdata expected_hash_data;
5630 if (!epee::string_tools::parse_hexstr_to_binbuff(std::string(expected_block_hashes_hash), expected_hash_data) || expected_hash_data.size() != sizeof(crypto::hash))
5631 {
5632 MERROR("Failed to parse expected block hashes hash");
5633 return;
5634 }
5635 const crypto::hash expected_hash = *reinterpret_cast<const crypto::hash*>(expected_hash_data.data());
5636 if (hash != expected_hash)
5637 {
5638 MERROR("Block hash data does not match expected hash");
5639 return;
5640 }
5641 }
5642
5643 if (checkpoints.size() > 4)
5644 {
5645 const unsigned char *p = checkpoints.data();
5646 const uint32_t nblocks = *p | ((*(p+1))<<8) | ((*(p+2))<<16) | ((*(p+3))<<24);
5647 if (nblocks > (std::numeric_limits<uint32_t>::max() - 4) / sizeof(hash))
5648 {
5649 MERROR("Block hash data is too large");
5650 return;
5651 }
5652 const size_t size_needed = 4 + nblocks * (sizeof(crypto::hash) * 2);
5653 if(checkpoints.size() != size_needed)
5654 {
5655 MERROR("Failed to load hashes - unexpected data size");
5656 return;
5657 }
5658 else if(nblocks > 0 && nblocks > (m_db->height() + HASH_OF_HASHES_STEP - 1) / HASH_OF_HASHES_STEP)
5659 {
5660 p += sizeof(uint32_t);
5661 m_blocks_hash_of_hashes.reserve(nblocks);
5662 for (uint32_t i = 0; i < nblocks; i++)
5663 {
5664 crypto::hash hash_hashes, hash_weights;
5665 memcpy(hash_hashes.data, p, sizeof(hash_hashes.data));
5666 p += sizeof(hash_hashes.data);
5667 memcpy(hash_weights.data, p, sizeof(hash_weights.data));
5668 p += sizeof(hash_weights.data);
5669 m_blocks_hash_of_hashes.push_back(std::make_pair(hash_hashes, hash_weights));
5670 }
5671 m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, std::make_pair(crypto::null_hash, 0));
5672 MINFO(nblocks << " block hashes loaded");
5673
5674 // FIXME: clear tx_pool because the process might have been
5675 // terminated and caused it to store txs kept by blocks.
5676 // The core will not call check_tx_inputs(..) for these
5677 // transactions in this case. Consequently, the sanity check
5678 // for tx hashes will fail in handle_block_to_main_chain(..)
5679 CRITICAL_REGION_LOCAL(m_tx_pool);
5680
5681 std::vector<transaction> txs;
5682 m_tx_pool.get_transactions(txs, true);
5683
5684 size_t tx_weight;
5685 uint64_t fee;
5686 bool relayed, do_not_relay, double_spend_seen, pruned;
5687 transaction pool_tx;
5688 blobdata txblob;
5689 for(const transaction &tx : txs)
5690 {
5691 crypto::hash tx_hash = get_transaction_hash(tx);
5692 m_tx_pool.take_tx(tx_hash, pool_tx, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen, pruned);
5693 }
5694 }
5695 }
5696 }
5697 }
5698 #endif
5699
5700 bool Blockchain::is_within_compiled_block_hash_area(uint64_t height) const
5701 {
5702 #if defined(PER_BLOCK_CHECKPOINT)
5703 return height < m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP;
5704 #else
5705 return false;
5706 #endif
5707 }
5708
5709 void Blockchain::lock()
5710 {
5711 m_blockchain_lock.lock();
5712 }
5713
5714 void Blockchain::unlock()
5715 {
5716 m_blockchain_lock.unlock();
5717 }
5718
5719 bool Blockchain::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const
5720 {
5721 return m_db->for_all_key_images(f);
5722 }
5723
5724 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
5725 {
5726 return m_db->for_blocks_range(h1, h2, f);
5727 }
5728
5729 bool Blockchain::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const
5730 {
5731 return m_db->for_all_transactions(f, pruned);
5732 }
5733
5734 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
5735 {
5736 return m_db->for_all_outputs(f);
5737 }
5738
5739 bool Blockchain::for_all_outputs(uint64_t amount, std::function<bool(uint64_t height)> f) const
5740 {
5741 return m_db->for_all_outputs(amount, f);
5742 }
5743
5744 void Blockchain::invalidate_block_template_cache()
5745 {
5746 MDEBUG("Invalidating block template cache");
5747 m_btc_valid = false;
5748 }
5749
5750 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)
5751 {
5752 MDEBUG("Setting block template cache");
5753 m_btc = b;
5754 m_btc_address = address;
5755 m_btc_nonce = nonce;
5756 m_btc_difficulty = diff;
5757 m_btc_height = height;
5758 m_btc_expected_reward = expected_reward;
5759 m_btc_seed_hash = seed_hash;
5760 m_btc_seed_height = seed_height;
5761 m_btc_pool_cookie = pool_cookie;
5762 m_btc_valid = true;
5763 }
5764
5765 void Blockchain::send_miner_notifications(uint64_t height, const crypto::hash &seed_hash, const crypto::hash &prev_id, uint64_t already_generated_coins)
5766 {
5767 if (m_miner_notifiers.empty())
5768 return;
5769
5770 const uint8_t major_version = m_hardfork->get_ideal_version(height);
5771 const difficulty_type diff = get_difficulty_for_next_block();
5772 const uint64_t median_weight = m_current_block_cumul_weight_median;
5773
5774 std::vector<tx_block_template_backlog_entry> tx_backlog;
5775 m_tx_pool.get_block_template_backlog(tx_backlog);
5776
5777 for (const auto& notifier : m_miner_notifiers)
5778 {
5779 notifier(major_version, height, prev_id, seed_hash, diff, median_weight, already_generated_coins, tx_backlog);
5780 }
5781 }
5782
5783 namespace cryptonote {
5784 template bool Blockchain::get_transactions(const std::vector<crypto::hash>&, std::vector<transaction>&, std::vector<crypto::hash>&, bool) const;
5785 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;
5786 }