Debian Codegraph @

src/cryptonote_core/blockchain.h

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 #pragma once
32 #include <boost/asio/executor_work_guard.hpp>
33 #include <boost/asio/io_context.hpp>
34 #include <boost/function/function_fwd.hpp>
35 #if BOOST_VERSION >= 107400
36 #include <boost/serialization/library_version_type.hpp>
37 #endif
38 #include <boost/serialization/serialization.hpp>
39 #include <boost/serialization/version.hpp>
40 #include <boost/serialization/list.hpp>
41 #include <boost/multi_index_container.hpp>
42 #include <boost/multi_index/global_fun.hpp>
43 #include <boost/multi_index/hashed_index.hpp>
44 #include <boost/multi_index/member.hpp>
45 #include <atomic>
46 #include <functional>
47 #include <unordered_map>
48 #include <unordered_set>
49
50 #include "span.h"
51 #include "syncobj.h"
52 #include "string_tools.h"
53 #include "rolling_median.h"
54 #include "cryptonote_basic/cryptonote_basic.h"
55 #include "common/powerof.h"
56 #include "common/util.h"
57 #include "cryptonote_protocol/cryptonote_protocol_defs.h"
58 #include "rpc/core_rpc_server_commands_defs.h"
59 #include "cryptonote_basic/difficulty.h"
60 #include "cryptonote_tx_utils.h"
61 #include "tx_verification_utils.h"
62 #include "cryptonote_basic/verification_context.h"
63 #include "crypto/hash.h"
64 #include "checkpoints/checkpoints.h"
65 #include "cryptonote_basic/hardfork.h"
66 #include "blockchain_db/blockchain_db.h"
67
68 namespace tools { class Notify; }
69
70 namespace cryptonote
71 {
72 class tx_memory_pool;
73 struct test_options;
74
75 /** Declares ways in which the BlockchainDB backend should be told to sync
76 *
77 */
78 enum blockchain_db_sync_mode
79 {
80 db_defaultsync, //!< user didn't specify, use db_async
81 db_sync, //!< handle syncing calls instead of the backing db, synchronously
82 db_async, //!< handle syncing calls instead of the backing db, asynchronously
83 db_nosync //!< Leave syncing up to the backing db (safest, but slowest because of disk I/O)
84 };
85
86 /**
87 * @brief Callback routine that returns checkpoints data for specific network type
88 *
89 * @param network network type
90 *
91 * @return checkpoints data, empty span if there ain't any checkpoints for specific network type
92 */
93 typedef std::function<const epee::span<const unsigned char>(cryptonote::network_type network)> GetCheckpointsCallback;
94
95 typedef boost::function<void(std::vector<txpool_event>)> TxpoolNotifyCallback;
96 typedef boost::function<void(uint64_t /* height */, epee::span<const block> /* blocks */)> BlockNotifyCallback;
97 typedef boost::function<void(uint8_t /* major_version */, uint64_t /* height */, const crypto::hash& /* prev_id */, const crypto::hash& /* seed_hash */, difficulty_type /* diff */, uint64_t /* median_weight */, uint64_t /* already_generated_coins */, const std::vector<tx_block_template_backlog_entry>& /* tx_backlog */)> MinerNotifyCallback;
98
99 /************************************************************************/
100 /* */
101 /************************************************************************/
102 class Blockchain
103 {
104 public:
105 /**
106 * @brief container for passing a block and metadata about it on the blockchain
107 */
108 struct block_extended_info
109 {
110 block bl; //!< the block
111 uint64_t height; //!< the height of the block in the blockchain
112 uint64_t block_cumulative_weight; //!< the weight of the block
113 difficulty_type cumulative_difficulty; //!< the accumulated difficulty after that block
114 uint64_t already_generated_coins; //!< the total coins minted after that block
115 };
116
117 /**
118 * @brief Blockchain constructor
119 *
120 * @param tx_pool a reference to the transaction pool to be kept by the Blockchain
121 */
122 Blockchain(tx_memory_pool& tx_pool);
123
124 /**
125 * @brief Blockchain destructor
126 */
127 ~Blockchain();
128
129 /**
130 * @brief Initialize the Blockchain state
131 *
132 * @param db a pointer to the backing store to use for the blockchain
133 * @param nettype network type
134 * @param offline true if running offline, else false
135 * @param test_options test parameters
136 * @param fixed_difficulty fixed difficulty for testing purposes; 0 means disabled
137 * @param get_checkpoints if set, will be called to get checkpoints data
138 *
139 * @return true on success, false if any initialization steps fail
140 */
141 bool init(BlockchainDB* db, const network_type nettype = MAINNET, bool offline = false, const cryptonote::test_options *test_options = NULL, difficulty_type fixed_difficulty = 0, const GetCheckpointsCallback& get_checkpoints = nullptr);
142
143 /**
144 * @brief Initialize the Blockchain state
145 *
146 * @param db a pointer to the backing store to use for the blockchain
147 * @param hf a structure containing hardfork information
148 * @param nettype network type
149 * @param offline true if running offline, else false
150 *
151 * @return true on success, false if any initialization steps fail
152 */
153 bool init(BlockchainDB* db, HardFork*& hf, const network_type nettype = MAINNET, bool offline = false);
154
155 /**
156 * @brief Uninitializes the blockchain state
157 *
158 * Saves to disk any state that needs to be maintained
159 *
160 * @return true on success, false if any uninitialization steps fail
161 */
162 bool deinit();
163
164 /**
165 * @brief get a set of blockchain checkpoint hashes
166 *
167 * @return set of blockchain checkpoint hashes
168 */
169 const checkpoints& get_checkpoints() const { return m_checkpoints; }
170
171 /**
172 * @brief assign a set of blockchain checkpoint hashes
173 *
174 * @param chk_pts the set of checkpoints to assign
175 */
176 void set_checkpoints(checkpoints&& chk_pts) { m_checkpoints = chk_pts; }
177
178 /**
179 * @brief get blocks and transactions from blocks based on start height and count
180 *
181 * @param start_offset the height on the blockchain to start at
182 * @param count the number of blocks to get, if there are as many after start_offset
183 * @param blocks return-by-reference container to put result blocks in
184 * @param txs return-by-reference container to put result transactions in
185 *
186 * @return false if start_offset > blockchain height, else true
187 */
188 bool get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks, std::vector<cryptonote::blobdata>& txs) const;
189
190 /**
191 * @brief get blocks from blocks based on start height and count
192 *
193 * @param start_offset the height on the blockchain to start at
194 * @param count the number of blocks to get, if there are as many after start_offset
195 * @param blocks return-by-reference container to put result blocks in
196 *
197 * @return false if start_offset > blockchain height, else true
198 */
199 bool get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks) const;
200
201 /**
202 * @brief compiles a list of all blocks stored as alternative chains
203 *
204 * @param blocks return-by-reference container to put result blocks in
205 *
206 * @return true
207 */
208 bool get_alternative_blocks(std::vector<block>& blocks) const;
209
210 /**
211 * @brief returns the number of alternative blocks stored
212 *
213 * @return the number of alternative blocks stored
214 */
215 size_t get_alternative_blocks_count() const;
216
217 /**
218 * @brief gets a block's hash given a height
219 *
220 * @param height the height of the block
221 *
222 * @return the hash of the block at the requested height, or a zeroed hash if there is no such block
223 */
224 crypto::hash get_block_id_by_height(uint64_t height) const;
225
226 /**
227 * @brief gets a block's hash given a height
228 *
229 * Used only by prepare_handle_incoming_blocks. Will look in the list of incoming blocks
230 * if the height is contained there.
231 *
232 * @param height the height of the block
233 *
234 * @return the hash of the block at the requested height, or a zeroed hash if there is no such block
235 */
236 crypto::hash get_pending_block_id_by_height(uint64_t height) const;
237
238 /**
239 * @brief gets the block with a given hash
240 *
241 * @param h the hash to look for
242 * @param blk return-by-reference variable to put result block in
243 * @param orphan if non-NULL, will be set to true if not in the main chain, false otherwise
244 *
245 * @return true if the block was found, else false
246 */
247 bool get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan = NULL) const;
248
249 /**
250 * @brief performs some preprocessing on a group of incoming blocks to speed up verification
251 *
252 * @param blocks_entry a list of incoming blocks
253 * @param blocks the parsed blocks
254 *
255 * @return false on erroneous blocks, else true
256 */
257 bool prepare_handle_incoming_blocks(const std::vector<block_complete_entry> &blocks_entry, std::vector<block> &blocks);
258
259 /**
260 * @brief prepare the blockchain for handling an incoming block, without performing preprocessing
261 *
262 * @param block_byte_estimate an estimate of the byte size of the block & its transactions
263 *
264 * This function should *always* be followed up by a call to cleanup_handle_incoming_blocks()
265 * later in the same thread.
266 */
267 void prepare_handle_incoming_block_no_preprocess(const size_t block_byte_estimate);
268
269 /**
270 * @brief incoming blocks post-processing, cleanup, and disk sync
271 *
272 * @param force_sync if true, and Blockchain is handling syncing to disk, always sync
273 *
274 * @return true
275 */
276 bool cleanup_handle_incoming_blocks(bool force_sync = false);
277
278 /**
279 * @brief search the blockchain for a transaction by hash
280 *
281 * @param id the hash to search for
282 *
283 * @return true if the tx exists, else false
284 */
285 bool have_tx(const crypto::hash &id) const;
286
287 /**
288 * @brief check if any key image in a transaction has already been spent
289 *
290 * @param tx the transaction to check
291 *
292 * @return true if any key image is already spent in the blockchain, else false
293 */
294 bool have_tx_keyimges_as_spent(const transaction &tx) const;
295
296 /**
297 * @brief check if a key image is already spent on the blockchain
298 *
299 * Whenever a transaction output is used as an input for another transaction
300 * (a true input, not just one of a mixing set), a key image is generated
301 * and stored in the transaction in order to prevent double spending. If
302 * this key image is seen again, the transaction using it is rejected.
303 *
304 * @param key_im the key image to search for
305 *
306 * @return true if the key image is already spent in the blockchain, else false
307 */
308 bool have_tx_keyimg_as_spent(const crypto::key_image &key_im) const;
309
310 /**
311 * @brief get the current height of the blockchain
312 *
313 * @return the height
314 */
315 uint64_t get_current_blockchain_height() const;
316
317 /**
318 * @brief get the hash of the most recent block on the blockchain
319 *
320 * @return the hash
321 */
322 crypto::hash get_tail_id() const;
323
324 /**
325 * @brief get the height and hash of the most recent block on the blockchain
326 *
327 * @param height return-by-reference variable to store the height in
328 *
329 * @return the hash
330 */
331 crypto::hash get_tail_id(uint64_t& height) const;
332
333 /**
334 * @brief returns the difficulty target the next block to be added must meet
335 *
336 * @return the target
337 */
338 difficulty_type get_difficulty_for_next_block();
339
340 /**
341 * @brief check currently stored difficulties against difficulty checkpoints
342 *
343 * @return {flag, height} flag: true if all difficulty checkpoints pass, height: the last checkpoint height before the difficulty drift bug starts
344 */
345 std::pair<bool, uint64_t> check_difficulty_checkpoints() const;
346
347 /**
348 * @brief recalculate difficulties for blocks after the last difficulty checkpoints to circumvent the annoying 'difficulty drift' bug
349 *
350 * @param start_height: if omitted, starts recalculation from the last difficulty checkpoint
351 *
352 * @return number of blocks whose difficulties got corrected
353 */
354 size_t recalculate_difficulties(boost::optional<uint64_t> start_height = boost::none);
355
356 /**
357 * @brief adds a block to the blockchain
358 *
359 * Adds a new block to the blockchain. If the block's parent is not the
360 * current top of the blockchain, the block may be added to an alternate
361 * chain. If the block does not belong, is already in the blockchain
362 * or an alternate chain, or is invalid, return false.
363 *
364 * @param bl_ the block to be added
365 * @param bvc metadata about the block addition's success/failure
366 * @param extra_block_txs txs belonging to this block that may not be in the mempool
367 *
368 * @return true on successful addition to the blockchain, else false
369 */
370 bool add_new_block(const block& bl_, block_verification_context& bvc);
371
372 bool add_new_block(const block& bl_, block_verification_context& bvc,
373 pool_supplement& extra_block_txs);
374
375 /**
376 * @brief clears the blockchain and starts a new one
377 *
378 * @param b the first block in the new chain (the genesis block)
379 *
380 * @return true on success, else false
381 */
382 bool reset_and_set_genesis_block(const block& b);
383
384 /**
385 * @brief creates a new block to mine against
386 *
387 * @param b return-by-reference block to be filled in
388 * @param from_block optional block hash to start mining from (main chain tip if NULL)
389 * @param miner_address address new coins for the block will go to
390 * @param di return-by-reference tells the miner what the difficulty target is
391 * @param height return-by-reference tells the miner what height it's mining against
392 * @param expected_reward return-by-reference the total reward awarded to the miner finding this block, including transaction fees
393 * @param ex_nonce extra data to be added to the miner transaction's extra
394 *
395 * @return true if block template filled in successfully, else false
396 */
397 bool create_block_template(block& b, const account_public_address& miner_address, difficulty_type& di, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash);
398 bool create_block_template(block& b, const crypto::hash *from_block, const account_public_address& miner_address, difficulty_type& di, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash);
399
400 /**
401 * @brief gets data required to create a block template and start mining on it
402 *
403 * @param major_version current hardfork version
404 * @param height current blockchain height
405 * @param prev_id hash of the top block
406 * @param seed_hash seed hash used for RandomX initialization
407 * @param difficulty current mining difficulty
408 * @param median_weight current median block weight
409 * @param already_generated_coins current emission
410 * @param tx_backlog transactions in mempool ready to be mined
411 *
412 * @return true if block template filled in successfully, else false
413 */
414 bool 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);
415
416 /**
417 * @brief checks if a block is known about with a given hash
418 *
419 * This function checks the main chain, alternate chains, and invalid blocks
420 * for a block with the given hash
421 *
422 * @param id the hash to search for
423 * @param where the type of block, if non NULL
424 *
425 * @return true if the block is known, else false
426 */
427 bool have_block_unlocked(const crypto::hash& id, int *where = NULL) const;
428 bool have_block(const crypto::hash& id, int *where = NULL) const;
429
430 /**
431 * @brief gets the total number of transactions on the main chain
432 *
433 * @return the number of transactions on the main chain
434 */
435 size_t get_total_transactions() const;
436
437 /**
438 * @brief gets the hashes for a subset of the blockchain
439 *
440 * puts into list <ids> a list of hashes representing certain blocks
441 * from the blockchain in reverse chronological order
442 *
443 * the blocks chosen, at the time of this writing, are:
444 * the most recent 11
445 * powers of 2 less recent from there, so 13, 17, 25, etc...
446 *
447 * @param ids return-by-reference list to put the resulting hashes in
448 * @param current_height the current blockchain height, return-by-reference
449 *
450 * @return true
451 */
452 bool get_short_chain_history(std::list<crypto::hash>& ids, uint64_t& current_height) const;
453
454 /**
455 * @brief get recent block hashes for a foreign chain
456 *
457 * Find the split point between us and foreign blockchain and return
458 * (by reference) the most recent common block hash along with up to
459 * BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes.
460 *
461 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
462 * @param hashes the hashes to be returned, return-by-reference
463 * @param weights the block weights to be returned, return-by-reference
464 * @param start_height the start height, return-by-reference
465 * @param current_height the current blockchain height, return-by-reference
466 * @param clip_pruned whether to constrain results to unpruned data
467 *
468 * @return true if a block found in common, else false
469 */
470 bool 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;
471
472 /**
473 * @brief get recent block hashes for a foreign chain
474 *
475 * Find the split point between us and foreign blockchain and return
476 * (by reference) the most recent common block hash along with up to
477 * BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes.
478 *
479 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
480 * @param clip_pruned clip pruned blocks if true, include them otherwise
481 * @param resp return-by-reference the split height and subsequent blocks' hashes
482 *
483 * @return true if a block found in common, else false
484 */
485 bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, bool clip_pruned, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const;
486
487 /**
488 * @brief find the most recent common point between ours and a foreign chain
489 *
490 * This function takes a list of block hashes from another node
491 * on the network to find where the split point is between us and them.
492 * This is used to see what to send another node that needs to sync.
493 *
494 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
495 * @param starter_offset return-by-reference the most recent common block's height
496 *
497 * @return true if a block found in common, else false
498 */
499 bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const;
500
501 /**
502 * @brief get recent blocks for a foreign chain
503 *
504 * This function gets recent blocks relative to a foreign chain, starting either at
505 * a requested height or whatever height is the most recent ours and the foreign
506 * chain have in common.
507 *
508 * @param req_start_block if non-zero, specifies a start point (otherwise find most recent commonality)
509 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
510 * @param blocks return-by-reference the blocks and their transactions
511 * @param total_height return-by-reference our current blockchain height
512 * @param start_height return-by-reference the height of the first block returned
513 * @param pruned whether to return full or pruned tx blobs
514 * @param max_block_count the max number of blocks to get
515 * @param max_tx_count the max number of txes to get (it can get overshot by the last block's number of txes minus 1)
516 *
517 * @return true if a block found in common or req_start_block specified, else false
518 */
519 bool 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;
520
521 /**
522 * @brief retrieves a set of blocks and their transactions, and possibly other transactions
523 *
524 * the request object encapsulates a list of block hashes and a (possibly empty) list of
525 * transaction hashes. for each block hash, the block is fetched along with all of that
526 * block's transactions. Any transactions requested separately are fetched afterwards.
527 *
528 * @param arg the request
529 * @param rsp return-by-reference the response to fill in
530 *
531 * @return true unless any blocks or transactions are missing
532 */
533 bool handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp);
534
535 /**
536 * @brief get number of outputs of an amount past the minimum spendable age
537 *
538 * @param amount the output amount
539 *
540 * @return the number of mature outputs
541 */
542 uint64_t get_num_mature_outputs(uint64_t amount) const;
543
544 /**
545 * @brief get the public key for an output
546 *
547 * @param amount the output amount
548 * @param global_index the output amount-global index
549 *
550 * @return the public key
551 */
552 crypto::public_key get_output_key(uint64_t amount, uint64_t global_index) const;
553
554 /**
555 * @brief gets specific outputs to mix with
556 *
557 * This function takes an RPC request for outputs to mix with
558 * and creates an RPC response with the resultant output indices.
559 *
560 * Outputs to mix with are specified in the request.
561 *
562 * @param req the outputs to return
563 * @param res return-by-reference the resultant output indices and keys
564 *
565 * @return true
566 */
567 bool get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const;
568
569 /**
570 * @brief gets an output's key and unlocked state
571 *
572 * @param amount in - the output amount
573 * @param index in - the output global amount index
574 * @param mask out - the output's RingCT mask
575 * @param key out - the output's key
576 * @param unlocked out - the output's unlocked state
577 */
578 void get_output_key_mask_unlocked(const uint64_t& amount, const uint64_t& index, crypto::public_key& key, rct::key& mask, bool& unlocked) const;
579
580 /**
581 * @brief gets per block distribution of outputs of a given amount
582 *
583 * @param amount the amount to get a ditribution for
584 * @param from_height the height before which we do not care about the data
585 * @param to_height the height after which we do not care about the data
586 * @param return-by-reference start_height the height of the first rct output
587 * @param return-by-reference distribution the start offset of the first rct output in this block (same as previous if none)
588 * @param return-by-reference base how many outputs of that amount are before the stated distribution
589 */
590 bool 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;
591
592 /**
593 * @brief gets the global indices for outputs from a given transaction
594 *
595 * This function gets the global indices for all outputs belonging
596 * to a specific transaction.
597 *
598 * @param tx_id the hash of the transaction to fetch indices for
599 * @param indexs return-by-reference the global indices for the transaction's outputs
600 * @param n_txes how many txes in a row to get results for
601 *
602 * @return false if the transaction does not exist, or if no indices are found, otherwise true
603 */
604 bool get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const;
605 bool get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector<std::vector<uint64_t>>& indexs) const;
606
607 /**
608 * @brief stores the blockchain
609 *
610 * If Blockchain is handling storing of the blockchain (rather than BlockchainDB),
611 * this initiates a blockchain save.
612 *
613 * @return true unless saving the blockchain fails
614 */
615 bool store_blockchain();
616
617 /**
618 * @brief expands v2 transaction data from blockchain
619 *
620 * RingCT transactions do not transmit some of their data if it
621 * can be reconstituted by the receiver. This function expands
622 * that implicit data.
623 */
624 static bool expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys);
625
626 /**
627 * @brief validates a transaction's inputs
628 *
629 * validates a transaction's inputs as correctly used and not previously
630 * spent. also returns the hash and height of the most recent block
631 * which contains an output that was used as an input to the transaction.
632 * The transaction's rct signatures, if any, are expanded.
633 *
634 * @param tx the transaction to validate
635 * @param pmax_used_block_height return-by-reference block height of most recent input
636 * @param max_used_block_id return-by-reference block hash of most recent input
637 * @param tvc returned information about tx verification
638 * @param kept_by_block whether or not the transaction is from a previously-verified block
639 *
640 * @return false if any input is invalid, otherwise true
641 */
642 bool check_tx_inputs(transaction& tx, uint64_t& pmax_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block = false) const;
643
644 /**
645 * @brief get fee quantization mask
646 *
647 * The dynamic fee may be quantized, to mask out the last decimal places
648 *
649 * @return the fee quantized mask
650 */
651 static uint64_t get_fee_quantization_mask()
652 {
653 return tools::PowerOf<10, CRYPTONOTE_DISPLAY_DECIMAL_POINT - PER_KB_FEE_QUANTIZATION_DECIMALS>::Value;
654 }
655
656 /**
657 * @brief get dynamic per kB or byte fee for a given block weight
658 *
659 * The dynamic fee is based on the block weight in a past window, and
660 * the current block reward. It is expressed by kB before v8, and
661 * per byte from v8.
662 *
663 * @param block_reward the current block reward
664 * @param median_block_weight the median block weight in the past window
665 * @param version hard fork version for rules and constants to use
666 *
667 * @return the fee
668 */
669 static uint64_t get_dynamic_base_fee(uint64_t block_reward, size_t median_block_weight, uint8_t version);
670
671 /**
672 * @brief get dynamic per kB or byte fee estimate for the next few blocks
673 *
674 * The dynamic fee is based on the block weight in a past window, and
675 * the current block reward. It is expressed by kB before v8, and
676 * per byte from v8.
677 * This function calculates an estimate for a dynamic fee which will be
678 * valid for the next grace_blocks
679 *
680 * @param grace_blocks number of blocks we want the fee to be valid for
681 *
682 * @return the fee estimate
683 */
684 uint64_t get_dynamic_base_fee_estimate(uint64_t grace_blocks) const;
685 void 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;
686
687 /**
688 * @brief get four levels of dynamic per byte fee estimate for the next few blocks
689 *
690 * The dynamic fee is based on the block weight in a past window, and
691 * the current block reward. It is expressed per byte, and is based on
692 * https://github.com/ArticMine/Monero-Documents/blob/master/MoneroScaling2021-02.pdf
693 * This function calculates an estimate for a dynamic fee which will be
694 * valid for the next grace_blocks
695 *
696 * @param grace_blocks number of blocks we want the fee to be valid for
697 *
698 * @return the fee estimates (4 of them)
699 */
700 void get_dynamic_base_fee_estimate_2021_scaling(uint64_t grace_blocks, std::vector<uint64_t> &fees) const;
701
702 /**
703 * @brief validate a transaction's fee
704 *
705 * This function validates the fee is enough for the transaction.
706 * This is based on the weight of the transaction, and, after a
707 * height threshold, on the average weight of transaction in a past window
708 *
709 * @param tx_weight the transaction weight
710 * @param fee the fee
711 *
712 * @return true if the fee is enough, false otherwise
713 */
714 bool check_fee(size_t tx_weight, uint64_t fee) const;
715
716 /**
717 * @brief check that a transaction's outputs conform to current standards
718 *
719 * This function checks, for example at the time of this writing, that
720 * each output is of the form a * 10^b (phrased differently, that if
721 * written out would have only one non-zero digit in base 10).
722 *
723 * @param tx the transaction to check the outputs of
724 * @param tvc returned info about tx verification
725 * @param hf_version hard fork version
726 *
727 * @return false if any outputs do not conform, otherwise true
728 */
729 static bool check_tx_outputs(const transaction& tx,
730 tx_verification_context &tvc,
731 std::uint8_t hf_version);
732
733 /**
734 * @brief gets the block weight limit based on recent blocks
735 *
736 * @return the limit
737 */
738 uint64_t get_current_cumulative_block_weight_limit() const;
739
740 /**
741 * @brief gets the long term block weight for a new block
742 *
743 * @return the long term block weight
744 */
745 uint64_t get_next_long_term_block_weight(uint64_t block_weight) const;
746
747 /**
748 * @brief gets the block weight median based on recent blocks (same window as for the limit)
749 *
750 * @return the median
751 */
752 uint64_t get_current_cumulative_block_weight_median() const;
753
754 /**
755 * @brief gets the difficulty of the block with a given height
756 *
757 * @param i the height
758 *
759 * @return the difficulty
760 */
761 difficulty_type block_difficulty(uint64_t i) const;
762
763 /**
764 * @brief gets blocks based on a list of block hashes
765 *
766 * @tparam t_ids_container a standard-iterable container
767 * @tparam t_blocks_container a standard-iterable container
768 * @tparam t_missed_container a standard-iterable container
769 * @param block_ids a container of block hashes for which to get the corresponding blocks
770 * @param blocks return-by-reference a container to store result blocks in
771 * @param missed_bs return-by-reference a container to store missed blocks in
772 *
773 * @return false if an unexpected exception occurs, else true
774 */
775 template<class t_ids_container, class t_blocks_container, class t_missed_container>
776 bool get_blocks(const t_ids_container& block_ids, t_blocks_container& blocks, t_missed_container& missed_bs) const;
777
778 /**
779 * @brief gets transactions based on a list of transaction hashes
780 *
781 * @tparam t_ids_container a standard-iterable container
782 * @tparam t_tx_container a standard-iterable container
783 * @tparam t_missed_container a standard-iterable container
784 * @param txs_ids a container of hashes for which to get the corresponding transactions
785 * @param txs return-by-reference a container to store result transactions in
786 * @param missed_txs return-by-reference a container to store missed transactions in
787 * @param pruned whether to return full or pruned blobs
788 *
789 * @return false if an unexpected exception occurs, else true
790 */
791 bool get_transactions_blobs(const std::vector<crypto::hash>& txs_ids, std::vector<cryptonote::blobdata>& txs, std::vector<crypto::hash>& missed_txs, bool pruned = false) const;
792 bool get_transactions_blobs(const std::vector<crypto::hash>& txs_ids, std::vector<tx_blob_entry>& txs, std::vector<crypto::hash>& missed_txs, bool pruned = false) const;
793 template<class t_ids_container, class t_tx_container, class t_missed_container>
794 bool get_split_transactions_blobs(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs) const;
795 template<class t_ids_container, class t_tx_container, class t_missed_container>
796 bool get_transactions(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs, bool pruned = false) const;
797
798 //debug functions
799
800 /**
801 * @brief check the blockchain against a set of checkpoints
802 *
803 * If a block fails a checkpoint and enforce is enabled, the blockchain
804 * will be rolled back to two blocks prior to that block. If enforce
805 * is disabled, as is currently the default case with DNS-based checkpoints,
806 * an error will be printed to the user but no other action will be taken.
807 *
808 * @param points the checkpoints to check against
809 * @param enforce whether or not to take action on failure
810 */
811 void check_against_checkpoints(const checkpoints& points, bool enforce);
812
813 /**
814 * @brief configure whether or not to enforce DNS-based checkpoints
815 *
816 * @param enforce the new enforcement setting
817 */
818 void set_enforce_dns_checkpoints(bool enforce);
819
820 /**
821 * @brief loads new checkpoints from a file and optionally from DNS
822 *
823 * @param file_path the path of the file to look for and load checkpoints from
824 * @param check_dns whether or not to check for new DNS-based checkpoints
825 *
826 * @return false if any enforced checkpoint type fails to load, otherwise true
827 */
828 bool update_checkpoints(const std::string& file_path, bool check_dns);
829
830
831 // user options, must be called before calling init()
832
833 /**
834 * @brief sets various performance options
835 *
836 * @param maxthreads max number of threads when preparing blocks for addition
837 * @param sync_on_blocks whether to sync based on blocks or bytes
838 * @param sync_threshold number of blocks/bytes to cache before syncing to database
839 * @param sync_mode the ::blockchain_db_sync_mode to use
840 * @param fast_sync sync using built-in block hashes as trusted
841 */
842 void set_user_options(uint64_t maxthreads, bool sync_on_blocks, uint64_t sync_threshold,
843 blockchain_db_sync_mode sync_mode, bool fast_sync);
844
845 /**
846 * @brief sets a txpool notify object to call for every new tx used to add a new block
847 *
848 * @param notify the notify object to call at every new tx used to add a new block
849 */
850 void set_txpool_notify(TxpoolNotifyCallback&& notify);
851
852 /**
853 * @brief sets a block notify object to call for every new block
854 *
855 * @param notify the notify object to call at every new block
856 */
857 void add_block_notify(BlockNotifyCallback&& notify);
858
859 /**
860 * @brief sets a miner notify object to call for every new block
861 *
862 * @param notify the notify object to call at every new block
863 */
864 void add_miner_notify(MinerNotifyCallback&& notify);
865
866 /**
867 * @brief sets a reorg notify object to call for every reorg
868 *
869 * @param notify the notify object to call at every reorg
870 */
871 void set_reorg_notify(const std::shared_ptr<tools::Notify> &notify) { m_reorg_notify = notify; }
872
873 /**
874 * @brief Notify this Blockchain's txpool notifier about a txpool event
875 */
876 void notify_txpool_event(std::vector<txpool_event>&& event) const;
877
878 /**
879 * @brief Put DB in safe sync mode
880 */
881 void safesyncmode(const bool onoff);
882
883 /**
884 * @brief set whether or not to show/print time statistics
885 *
886 * @param stats the new time stats setting
887 */
888 void set_show_time_stats(bool stats) { m_show_time_stats = stats; }
889
890 /**
891 * @brief gets the hardfork voting state object
892 *
893 * @return the HardFork object
894 */
895 HardFork::State get_hard_fork_state() const;
896
897 /**
898 * @brief gets the current hardfork version in use/voted for
899 *
900 * @return the version
901 */
902 uint8_t get_current_hard_fork_version() const { return m_hardfork->get_current_version(); }
903
904 /**
905 * @brief returns the newest hardfork version known to the blockchain
906 *
907 * @return the version
908 */
909 uint8_t get_ideal_hard_fork_version() const { return m_hardfork->get_ideal_version(); }
910
911 /**
912 * @brief returns the next hardfork version
913 *
914 * @return the version
915 */
916 uint8_t get_next_hard_fork_version() const { return m_hardfork->get_next_version(); }
917
918 /**
919 * @brief returns the newest hardfork version voted to be enabled
920 * as of a certain height
921 *
922 * @param height the height for which to check version info
923 *
924 * @return the version
925 */
926 uint8_t get_ideal_hard_fork_version(uint64_t height) const { return m_hardfork->get_ideal_version(height); }
927
928 /**
929 * @brief returns the actual hardfork version for a given block height
930 *
931 * @param height the height for which to check version info
932 *
933 * @return the version
934 */
935 uint8_t get_hard_fork_version(uint64_t height) const { return m_hardfork->get(height); }
936
937 /**
938 * @brief returns the earliest block a given version may activate
939 *
940 * @return the height
941 */
942 uint64_t get_earliest_ideal_height_for_version(uint8_t version) const { return m_hardfork->get_earliest_ideal_height_for_version(version); }
943
944 /**
945 * @brief returns info for all known hard forks
946 *
947 * @return the hardforks
948 */
949 const std::vector<hardfork_t>& get_hardforks() const { return m_hardfork->get_hardforks(); }
950
951 /**
952 * @brief get information about hardfork voting for a version
953 *
954 * @param version the version in question
955 * @param window the size of the voting window
956 * @param votes the number of votes to enable <version>
957 * @param threshold the number of votes required to enable <version>
958 * @param earliest_height the earliest height at which <version> is allowed
959 * @param voting which version this node is voting for/using
960 *
961 * @return whether the version queried is enabled
962 */
963 bool 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;
964
965 /**
966 * @brief get difficulty target based on chain and hardfork version
967 *
968 * @return difficulty target
969 */
970 uint64_t get_difficulty_target() const;
971
972 /**
973 * @brief remove transactions from the transaction pool (if present)
974 *
975 * @param txids a list of hashes of transactions to be removed
976 *
977 * @return false if any removals fail, otherwise true
978 */
979 bool flush_txes_from_pool(const std::vector<crypto::hash> &txids);
980
981 /**
982 * @brief return a histogram of outputs on the blockchain
983 *
984 * @param amounts optional set of amounts to lookup
985 * @param unlocked whether to restrict instances to unlocked ones
986 * @param recent_cutoff timestamp to consider outputs as recent
987 * @param min_count return only amounts with at least that many instances
988 *
989 * @return a set of amount/instances
990 */
991 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count = 0) const;
992
993 /**
994 * @brief perform a check on all key images in the blockchain
995 *
996 * @param std::function the check to perform, pass/fail
997 *
998 * @return false if any key image fails the check, otherwise true
999 */
1000 bool for_all_key_images(std::function<bool(const crypto::key_image&)>) const;
1001
1002 /**
1003 * @brief perform a check on all blocks in the blockchain in the given range
1004 *
1005 * @param h1 the start height
1006 * @param h2 the end height
1007 * @param std::function the check to perform, pass/fail
1008 *
1009 * @return false if any block fails the check, otherwise true
1010 */
1011 bool for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const block&)>) const;
1012
1013 /**
1014 * @brief perform a check on all transactions in the blockchain
1015 *
1016 * @param std::function the check to perform, pass/fail
1017 * @param bool pruned whether to return pruned txes only
1018 *
1019 * @return false if any transaction fails the check, otherwise true
1020 */
1021 bool for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)>, bool pruned) const;
1022
1023 /**
1024 * @brief perform a check on all outputs in the blockchain
1025 *
1026 * @param std::function the check to perform, pass/fail
1027 *
1028 * @return false if any output fails the check, otherwise true
1029 */
1030 bool for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)>) const;
1031
1032 /**
1033 * @brief perform a check on all outputs of a given amount in the blockchain
1034 *
1035 * @param amount the amount to iterate through
1036 * @param std::function the check to perform, pass/fail
1037 *
1038 * @return false if any output fails the check, otherwise true
1039 */
1040 bool for_all_outputs(uint64_t amount, std::function<bool(uint64_t height)>) const;
1041
1042 /**
1043 * @brief get a reference to the BlockchainDB in use by Blockchain
1044 *
1045 * @return a reference to the BlockchainDB instance
1046 */
1047 const BlockchainDB& get_db() const
1048 {
1049 return *m_db;
1050 }
1051
1052 /**
1053 * @brief get a reference to the BlockchainDB in use by Blockchain
1054 *
1055 * @return a reference to the BlockchainDB instance
1056 */
1057 BlockchainDB& get_db()
1058 {
1059 return *m_db;
1060 }
1061
1062 /**
1063 * @brief get a number of outputs of a specific amount
1064 *
1065 * @param amount the amount
1066 * @param offsets the indices (indexed to the amount) of the outputs
1067 * @param outputs return-by-reference the outputs collected
1068 */
1069 void output_scan_worker(const uint64_t amount,const std::vector<uint64_t> &offsets,
1070 std::vector<output_data_t> &outputs) const;
1071
1072 /**
1073 * @brief computes the "short" and "long" hashes for a set of blocks
1074 *
1075 * @param height the height of the first block
1076 * @param blocks the blocks to be hashed
1077 * @param map return-by-reference the hashes for each block
1078 */
1079 void block_longhash_worker(uint64_t height, const epee::span<const block> &blocks,
1080 std::unordered_map<crypto::hash, crypto::hash> &map) const;
1081
1082 /**
1083 * @brief returns a set of known alternate chains
1084 *
1085 * @return a vector of chains
1086 */
1087 std::vector<std::pair<block_extended_info,std::vector<crypto::hash>>> get_alternative_chains() const;
1088
1089 void add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata &blob, const txpool_tx_meta_t &meta);
1090 void update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta);
1091 void remove_txpool_tx(const crypto::hash &txid);
1092 uint64_t get_txpool_tx_count(bool include_sensitive = false) const;
1093 bool get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const;
1094 bool get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const;
1095 cryptonote::blobdata get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const;
1096 bool for_all_txpool_txes(std::function<bool(const crypto::hash&, const txpool_tx_meta_t&, const cryptonote::blobdata_ref*)>, bool include_blob = false, relay_category tx_category = relay_category::broadcasted) const;
1097 bool txpool_tx_matches_category(const crypto::hash& tx_hash, relay_category category);
1098
1099 bool is_within_compiled_block_hash_area() const { return is_within_compiled_block_hash_area(m_db->height()); }
1100 uint64_t prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights);
1101 uint32_t get_blockchain_pruning_seed() const { return m_db->get_blockchain_pruning_seed(); }
1102 bool prune_blockchain(uint32_t pruning_seed = 0);
1103 bool update_blockchain_pruning();
1104 bool check_blockchain_pruning();
1105
1106 void lock();
1107 void unlock();
1108
1109 void cancel();
1110
1111 /**
1112 * @brief returns the timestamps of the last N blocks
1113 */
1114 std::vector<time_t> get_last_block_timestamps(unsigned int blocks) const;
1115
1116 /**
1117 * @brief removes blocks from the top of the blockchain
1118 *
1119 * @param nblocks number of blocks to be removed
1120 */
1121 void pop_blocks(uint64_t nblocks);
1122
1123 /**
1124 * @brief checks whether a given block height is included in the precompiled block hash area
1125 *
1126 * @param height the height to check for
1127 */
1128 bool is_within_compiled_block_hash_area(uint64_t height) const;
1129
1130 /**
1131 * @brief checks whether we have known weights for the given block heights
1132 *
1133 * @param height the start height to check for
1134 * @param nblocks how many blocks to check from that height
1135 */
1136 bool has_block_weights(uint64_t height, uint64_t nblocks) const;
1137
1138 /**
1139 * @brief flush the invalid blocks set
1140 */
1141 void flush_invalid_blocks();
1142
1143 /**
1144 * @brief get the "adjusted time"
1145 *
1146 * Computes the median timestamp of the previous 60 blocks, projects it
1147 * onto the current block to get an 'adjusted median time' which approximates
1148 * what the current block's timestamp should be. Also projects the previous
1149 * block's timestamp to estimate the current block's timestamp.
1150 *
1151 * Returns the minimum of the two projections, or the current local time on
1152 * the machine if less than 60 blocks are available.
1153 *
1154 * @return current time approximated from chain data
1155 */
1156 uint64_t get_adjusted_time(uint64_t height) const;
1157
1158 #ifndef IN_UNIT_TESTS
1159 private:
1160 #endif
1161
1162 // TODO: evaluate whether or not each of these typedefs are left over from blockchain_storage
1163 typedef std::unordered_set<crypto::key_image> key_images_container;
1164
1165 typedef std::vector<block_extended_info> blocks_container;
1166
1167 typedef std::unordered_map<crypto::hash, block_extended_info> blocks_ext_by_hash;
1168
1169
1170 BlockchainDB* m_db;
1171
1172 tx_memory_pool& m_tx_pool;
1173
1174 mutable epee::critical_section m_blockchain_lock; // TODO: add here reader/writer lock
1175
1176 // main chain
1177 size_t m_current_block_cumul_weight_limit;
1178 size_t m_current_block_cumul_weight_median;
1179
1180 // metadata containers
1181 std::unordered_map<crypto::hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>> m_scan_table;
1182 std::unordered_map<crypto::hash, crypto::hash> m_blocks_longhash_table;
1183
1184 // Keccak hashes for each block and for fast pow checking
1185 std::vector<std::pair<crypto::hash, crypto::hash>> m_blocks_hash_of_hashes;
1186 std::vector<std::pair<crypto::hash, uint64_t>> m_blocks_hash_check;
1187
1188 blockchain_db_sync_mode m_db_sync_mode;
1189 bool m_fast_sync;
1190 bool m_show_time_stats;
1191 bool m_db_default_sync;
1192 bool m_db_sync_on_blocks;
1193 uint64_t m_db_sync_threshold;
1194 uint64_t m_max_prepare_blocks_threads;
1195 uint64_t m_fake_pow_calc_time;
1196 uint64_t m_fake_scan_time;
1197 uint64_t m_sync_counter;
1198 uint64_t m_bytes_to_sync;
1199 std::vector<uint64_t> m_timestamps;
1200 std::vector<difficulty_type> m_difficulties;
1201 uint64_t m_timestamps_and_difficulties_height;
1202 bool m_reset_timestamps_and_difficulties_height;
1203 uint64_t m_long_term_block_weights_window;
1204 uint64_t m_long_term_effective_median_block_weight;
1205 mutable crypto::hash m_long_term_block_weights_cache_tip_hash;
1206 mutable epee::misc_utils::rolling_median_t<uint64_t> m_long_term_block_weights_cache_rolling_median;
1207
1208 epee::critical_section m_difficulty_lock;
1209 crypto::hash m_difficulty_for_next_block_top_hash;
1210 difficulty_type m_difficulty_for_next_block;
1211
1212 boost::asio::io_context m_async_service;
1213 boost::thread_group m_async_pool;
1214 std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> m_async_work_idle;
1215
1216 // some invalid blocks
1217 blocks_ext_by_hash m_invalid_blocks; // crypto::hash -> block_extended_info
1218
1219
1220 checkpoints m_checkpoints;
1221 bool m_enforce_dns_checkpoints;
1222
1223 HardFork *m_hardfork;
1224
1225 network_type m_nettype;
1226 bool m_offline;
1227 difficulty_type m_fixed_difficulty;
1228
1229 std::atomic<bool> m_cancel;
1230
1231 // block template cache
1232 block m_btc;
1233 account_public_address m_btc_address;
1234 blobdata m_btc_nonce;
1235 difficulty_type m_btc_difficulty;
1236 uint64_t m_btc_height;
1237 uint64_t m_btc_pool_cookie;
1238 uint64_t m_btc_expected_reward;
1239 crypto::hash m_btc_seed_hash;
1240 uint64_t m_btc_seed_height;
1241 bool m_btc_valid;
1242
1243
1244 bool m_batch_success;
1245
1246 TxpoolNotifyCallback m_txpool_notifier;
1247 mutable std::mutex m_txpool_notifier_mutex;
1248
1249 /* `boost::function` is used because the implementation never allocates if
1250 the callable object has a single `std::shared_ptr` or `std::weap_ptr`
1251 internally. Whereas, the libstdc++ `std::function` will allocate. */
1252
1253 std::vector<BlockNotifyCallback> m_block_notifiers;
1254 std::vector<MinerNotifyCallback> m_miner_notifiers;
1255 std::shared_ptr<tools::Notify> m_reorg_notify;
1256
1257 // for prepare_handle_incoming_blocks
1258 uint64_t m_prepare_height;
1259 uint64_t m_prepare_nblocks;
1260 std::vector<block> *m_prepare_blocks;
1261
1262 // cache for verifying transaction RCT non semantics
1263 mutable rct_ver_cache_t m_rct_ver_cache;
1264
1265 /**
1266 * @brief collects the keys for all outputs being "spent" as an input
1267 *
1268 * This function makes sure that each "input" in an input (mixins) exists
1269 * and collects the public key for each from the transaction it was included in
1270 * via the visitor passed to it.
1271 *
1272 * If pmax_related_block_height is not NULL, its value is set to the height
1273 * of the most recent block which contains an output used in the input set
1274 *
1275 * @tparam visitor_t a class encapsulating tx is unlocked and collect tx key
1276 * @param tx_in_to_key a transaction input instance
1277 * @param vis an instance of the visitor to use
1278 * @param tx_prefix_hash the hash of the associated transaction_prefix
1279 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1280 * @param tx_version version of the tx, if > 1 we also get commitments
1281 *
1282 * @return false if any keys are not found or any inputs are not unlocked, otherwise true
1283 */
1284 template<class visitor_t>
1285 inline bool 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 = NULL) const;
1286
1287 /**
1288 * @brief collect output public keys of a transaction input set
1289 *
1290 * This function locates all outputs associated with a given input set (mixins)
1291 * and validates that they exist and are usable
1292 * (unlocked, unspent is checked elsewhere).
1293 *
1294 * If pmax_related_block_height is not NULL, its value is set to the height
1295 * of the most recent block which contains an output used in the input set
1296 *
1297 * @param tx_version the transaction version
1298 * @param txin the transaction input
1299 * @param tx_prefix_hash the transaction prefix hash, for caching organization
1300 * @param sig the input signature
1301 * @param output_keys return-by-reference the public keys of the outputs in the input set
1302 * @param rct_signatures the ringCT signatures, which are only valid if tx version > 1
1303 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1304 * @param hf_version the consensus rules version to use
1305 *
1306 * @return false if any output is not yet unlocked, or is missing, otherwise true
1307 */
1308 bool 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;
1309
1310 /**
1311 * @brief validate a transaction's inputs and their keys
1312 *
1313 * This function validates transaction inputs and their keys. Previously
1314 * it also performed double spend checking, but that has been moved to its
1315 * own function.
1316 * The transaction's rct signatures, if any, are expanded.
1317 *
1318 * If pmax_related_block_height is not NULL, its value is set to the height
1319 * of the most recent block which contains an output used in any input set
1320 *
1321 * Currently this function calls ring signature validation for each
1322 * transaction.
1323 *
1324 * @param tx the transaction to validate
1325 * @param tvc returned information about tx verification
1326 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1327 *
1328 * @return false if any validation step fails, otherwise true
1329 */
1330 bool check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height = NULL) const;
1331
1332 /**
1333 * @brief performs a blockchain reorganization according to the longest chain rule
1334 *
1335 * This function aggregates all the actions necessary to switch to a
1336 * newly-longer chain. If any step in the reorganization process fails,
1337 * the blockchain is reverted to its previous state.
1338 *
1339 * @param alt_chain the chain to switch to
1340 * @param discard_disconnected_chain whether or not to keep the old chain as an alternate
1341 *
1342 * @return false if the reorganization fails, otherwise true
1343 */
1344 bool switch_to_alternative_blockchain(std::list<block_extended_info>& alt_chain, bool discard_disconnected_chain);
1345
1346 /**
1347 * @brief removes the most recent block from the blockchain
1348 *
1349 * @return the block removed
1350 */
1351 block pop_block_from_blockchain();
1352
1353 /**
1354 * @brief validate and add a new block to the end of the blockchain
1355 *
1356 * This function is merely a convenience wrapper around the other
1357 * of the same name. This one passes the block's hash to the other
1358 * as well as the block and verification context.
1359 *
1360 * @param bl the block to be added
1361 * @param bvc metadata concerning the block's validity
1362 *
1363 * @return true if the block was added successfully, otherwise false
1364 */
1365 bool handle_block_to_main_chain(const block& bl, block_verification_context& bvc);
1366
1367 /**
1368 * @brief validate and add a new block to the end of the blockchain
1369 *
1370 * When a block is given to Blockchain to be added to the blockchain, it
1371 * is passed here if it is determined to belong at the end of the current
1372 * chain.
1373 *
1374 * @param bl the block to be added
1375 * @param id the hash of the block
1376 * @param bvc metadata concerning the block's validity
1377 * @param extra_block_txs txs belonging to this block that may not be in the mempool
1378 *
1379 * @return true if the block was added successfully, otherwise false
1380 */
1381 bool handle_block_to_main_chain(const block& bl, const crypto::hash& id,
1382 block_verification_context& bvc, pool_supplement& extra_block_txs);
1383
1384 /**
1385 * @brief validate and add a new block to an alternate blockchain
1386 *
1387 * If a block to be added does not belong to the main chain, but there
1388 * is an alternate chain to which it should be added, that is handled
1389 * here.
1390 *
1391 * @param b the block to be added
1392 * @param id the hash of the block
1393 * @param bvc metadata concerning the block's validity
1394 * @param extra_block_txs txs belonging to this block that may not be in the mempool
1395 *
1396 * @return true if the block was added successfully, otherwise false
1397 */
1398 bool handle_alternative_block(const block& b, const crypto::hash& id,
1399 block_verification_context& bvc, pool_supplement& extra_block_txs);
1400
1401 /**
1402 * @brief builds a list of blocks connecting a block to the main chain
1403 *
1404 * @param prev_id the block hash of the tip of the alt chain
1405 * @param alt_chain the chain to be added to
1406 * @param timestamps returns the timestamps of previous blocks
1407 * @param bvc the block verification context for error return
1408 *
1409 * @return true on success, false otherwise
1410 */
1411 bool 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;
1412
1413 /**
1414 * @brief gets the difficulty requirement for a new block on an alternate chain
1415 *
1416 * @param alt_chain the chain to be added to
1417 * @param bei the block being added (and metadata, see ::block_extended_info)
1418 *
1419 * @return the difficulty requirement
1420 */
1421 difficulty_type get_next_difficulty_for_alternative_chain(const std::list<block_extended_info>& alt_chain, block_extended_info& bei) const;
1422
1423 /**
1424 * @brief sanity checks a miner transaction before validating an entire block
1425 *
1426 * This function merely checks basic things like the structure of the miner
1427 * transaction, the unlock time, and that the amount doesn't overflow.
1428 *
1429 * @param b the block containing the miner transaction
1430 * @param height the height at which the block will be added
1431 * @param hf_version the consensus rules to apply
1432 *
1433 * @return false if anything is found wrong with the miner transaction, otherwise true
1434 */
1435 bool prevalidate_miner_transaction(const block& b, uint64_t height, uint8_t hf_version);
1436
1437 /**
1438 * @brief validates a miner (coinbase) transaction
1439 *
1440 * This function makes sure that the miner calculated his reward correctly
1441 * and that his miner transaction totals reward + fee.
1442 *
1443 * @param b the block containing the miner transaction to be validated
1444 * @param cumulative_block_weight the block's weight
1445 * @param fee the total fees collected in the block
1446 * @param base_reward return-by-reference the new block's generated coins
1447 * @param already_generated_coins the amount of currency generated prior to this block
1448 * @param partial_block_reward return-by-reference true if miner accepted only partial reward
1449 * @param version hard fork version for that transaction
1450 *
1451 * @return false if anything is found wrong with the miner transaction, otherwise true
1452 */
1453 bool 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);
1454
1455 /**
1456 * @brief reverts the blockchain to its previous state following a failed switch
1457 *
1458 * If Blockchain fails to switch to an alternate chain when it means
1459 * to do so, this function reverts the blockchain to how it was before
1460 * the attempted switch.
1461 *
1462 * @param original_chain the chain to switch back to
1463 * @param rollback_height the height to revert to before appending the original chain
1464 *
1465 * @return false if something goes wrong with reverting (very bad), otherwise true
1466 */
1467 bool rollback_blockchain_switching(std::list<block>& original_chain, uint64_t rollback_height);
1468
1469 /**
1470 * @brief gets recent block weights for median calculation
1471 *
1472 * get the block weights of the last <count> blocks, and return by reference <weights>.
1473 *
1474 * @param weights return-by-reference the list of weights
1475 * @param count the number of blocks to get weights for
1476 */
1477 void get_last_n_blocks_weights(std::vector<uint64_t>& weights, size_t count) const;
1478
1479 /**
1480 * @brief gets block long term weight median
1481 *
1482 * get the block long term weight median of <count> blocks starting at <start_height>
1483 *
1484 * @param start_height the block height of the first block to query
1485 * @param count the number of blocks to get weights for
1486 *
1487 * @return the long term median block weight
1488 */
1489 uint64_t get_long_term_block_weight_median(uint64_t start_height, size_t count) const;
1490
1491 /**
1492 * @brief checks if a transaction is unlocked (its outputs spendable)
1493 *
1494 * This function checks to see if a transaction is unlocked.
1495 * unlock_time is either a block index or a unix time.
1496 *
1497 * @param unlock_time the unlock parameter (height or time)
1498 * @param hf_version the consensus rules version to use
1499 *
1500 * @return true if spendable, otherwise false
1501 */
1502 bool is_tx_spendtime_unlocked(uint64_t unlock_time, uint8_t hf_version) const;
1503
1504 /**
1505 * @brief stores an invalid block in a separate container
1506 *
1507 * Storing invalid blocks allows quick dismissal of the same block
1508 * if it is seen again.
1509 *
1510 * @param bl the invalid block
1511 * @param h the block's hash
1512 *
1513 * @return false if the block cannot be stored for some reason, otherwise true
1514 */
1515 bool add_block_as_invalid(const block& bl, const crypto::hash& h);
1516
1517 /**
1518 * @brief stores an invalid block in a separate container
1519 *
1520 * Storing invalid blocks allows quick dismissal of the same block
1521 * if it is seen again.
1522 *
1523 * @param bei the invalid block (see ::block_extended_info)
1524 * @param h the block's hash
1525 *
1526 * @return false if the block cannot be stored for some reason, otherwise true
1527 */
1528 bool add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h);
1529
1530 /**
1531 * @brief checks a block's timestamp
1532 *
1533 * This function grabs the timestamps from the most recent <n> blocks,
1534 * where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many
1535 * blocks in the blockchain, the timestap is assumed to be valid. If there
1536 * are, this function returns:
1537 * true if the block's timestamp is not less than the timestamp of the
1538 * median of the selected blocks
1539 * false otherwise
1540 *
1541 * @param b the block to be checked
1542 * @param median_ts return-by-reference the median of timestamps
1543 *
1544 * @return true if the block's timestamp is valid, otherwise false
1545 */
1546 bool check_block_timestamp(const block& b, uint64_t& median_ts) const;
1547 bool check_block_timestamp(const block& b) const { uint64_t median_ts; return check_block_timestamp(b, median_ts); }
1548
1549 /**
1550 * @brief checks a block's timestamp
1551 *
1552 * If the block is not more recent than the median of the recent
1553 * timestamps passed here, it is considered invalid.
1554 *
1555 * @param timestamps a list of the most recent timestamps to check against
1556 * @param b the block to be checked
1557 *
1558 * @return true if the block's timestamp is valid, otherwise false
1559 */
1560 bool check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b, uint64_t& median_ts) const;
1561 bool check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b) const { uint64_t median_ts; return check_block_timestamp(timestamps, b, median_ts); }
1562
1563 /**
1564 * @brief finish an alternate chain's timestamp window from the main chain
1565 *
1566 * for an alternate chain, get the timestamps from the main chain to complete
1567 * the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW.
1568 *
1569 * @param start_height the alternate chain's attachment height to the main chain
1570 * @param timestamps return-by-value the timestamps set to be populated
1571 *
1572 * @return true unless start_height is greater than the current blockchain height
1573 */
1574 bool complete_timestamps_vector(uint64_t start_height, std::vector<uint64_t>& timestamps) const;
1575
1576 /**
1577 * @brief calculate the block weight limit for the next block to be added
1578 *
1579 * @param long_term_effective_median_block_weight optionally return that value
1580 *
1581 * @return true
1582 */
1583 bool update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight = NULL);
1584
1585 /**
1586 * @brief make sure a transaction isn't attempting a double-spend
1587 *
1588 * @param tx the transaction to check
1589 * @param keys_this_block a cumulative list of spent keys for the current block
1590 *
1591 * @return false if a double spend was detected, otherwise true
1592 */
1593 bool check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const;
1594
1595 /**
1596 * @brief validates a transaction input's ring signature
1597 *
1598 * @param tx_prefix_hash the transaction prefix' hash
1599 * @param key_image the key image generated from the true input
1600 * @param pubkeys the public keys for each input in the ring signature
1601 * @param sig the signature generated for each input in the ring signature
1602 * @param result false if the ring signature is invalid, otherwise true
1603 */
1604 void check_ring_signature(const crypto::hash &tx_prefix_hash, const crypto::key_image &key_image,
1605 const std::vector<rct::ctkey> &pubkeys, const std::vector<crypto::signature> &sig, uint64_t &result) const;
1606
1607 /**
1608 * @brief loads block hashes from compiled-in data set
1609 *
1610 * A (possibly empty) set of block hashes can be compiled into the
1611 * monero daemon binary. This function loads those hashes into
1612 * a useful state.
1613 *
1614 * @param get_checkpoints if set, will be called to get checkpoints data
1615 */
1616 void load_compiled_in_block_hashes(const GetCheckpointsCallback& get_checkpoints);
1617
1618 /**
1619 * @brief invalidates any cached block template
1620 */
1621 void invalidate_block_template_cache();
1622
1623 /**
1624 * @brief stores a new cached block template
1625 *
1626 * At some point, may be used to push an update to miners
1627 */
1628 void 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);
1629
1630 /**
1631 * @brief sends new block notifications to ZMQ `miner_data` subscribers
1632 *
1633 * @param height current blockchain height
1634 * @param seed_hash seed hash to use for mining
1635 * @param prev_id hash of new blockchain tip
1636 * @param already_generated_coins total coins mined by the network so far
1637 */
1638 void send_miner_notifications(uint64_t height, const crypto::hash &seed_hash, const crypto::hash &prev_id, uint64_t already_generated_coins);
1639 };
1640 } // namespace cryptonote