Debian Codegraph @

monero/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 *
449 * @return true
450 */
451 bool get_short_chain_history(std::list<crypto::hash>& ids) const;
452
453 /**
454 * @brief get recent block hashes for a foreign chain
455 *
456 * Find the split point between us and foreign blockchain and return
457 * (by reference) the most recent common block hash along with up to
458 * BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes.
459 *
460 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
461 * @param hashes the hashes to be returned, return-by-reference
462 * @param weights the block weights to be returned, return-by-reference
463 * @param start_height the start height, return-by-reference
464 * @param current_height the current blockchain height, return-by-reference
465 * @param clip_pruned whether to constrain results to unpruned data
466 *
467 * @return true if a block found in common, else false
468 */
469 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;
470
471 /**
472 * @brief get recent block hashes for a foreign chain
473 *
474 * Find the split point between us and foreign blockchain and return
475 * (by reference) the most recent common block hash along with up to
476 * BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes.
477 *
478 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
479 * @param clip_pruned clip pruned blocks if true, include them otherwise
480 * @param resp return-by-reference the split height and subsequent blocks' hashes
481 *
482 * @return true if a block found in common, else false
483 */
484 bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, bool clip_pruned, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const;
485
486 /**
487 * @brief find the most recent common point between ours and a foreign chain
488 *
489 * This function takes a list of block hashes from another node
490 * on the network to find where the split point is between us and them.
491 * This is used to see what to send another node that needs to sync.
492 *
493 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
494 * @param starter_offset return-by-reference the most recent common block's height
495 *
496 * @return true if a block found in common, else false
497 */
498 bool find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const;
499
500 /**
501 * @brief get recent blocks for a foreign chain
502 *
503 * This function gets recent blocks relative to a foreign chain, starting either at
504 * a requested height or whatever height is the most recent ours and the foreign
505 * chain have in common.
506 *
507 * @param req_start_block if non-zero, specifies a start point (otherwise find most recent commonality)
508 * @param qblock_ids the foreign chain's "short history" (see get_short_chain_history)
509 * @param blocks return-by-reference the blocks and their transactions
510 * @param total_height return-by-reference our current blockchain height
511 * @param start_height return-by-reference the height of the first block returned
512 * @param pruned whether to return full or pruned tx blobs
513 * @param max_block_count the max number of blocks to get
514 * @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)
515 *
516 * @return true if a block found in common or req_start_block specified, else false
517 */
518 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;
519
520 /**
521 * @brief retrieves a set of blocks and their transactions, and possibly other transactions
522 *
523 * the request object encapsulates a list of block hashes and a (possibly empty) list of
524 * transaction hashes. for each block hash, the block is fetched along with all of that
525 * block's transactions. Any transactions requested separately are fetched afterwards.
526 *
527 * @param arg the request
528 * @param rsp return-by-reference the response to fill in
529 *
530 * @return true unless any blocks or transactions are missing
531 */
532 bool handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp);
533
534 /**
535 * @brief get number of outputs of an amount past the minimum spendable age
536 *
537 * @param amount the output amount
538 *
539 * @return the number of mature outputs
540 */
541 uint64_t get_num_mature_outputs(uint64_t amount) const;
542
543 /**
544 * @brief get the public key for an output
545 *
546 * @param amount the output amount
547 * @param global_index the output amount-global index
548 *
549 * @return the public key
550 */
551 crypto::public_key get_output_key(uint64_t amount, uint64_t global_index) const;
552
553 /**
554 * @brief gets specific outputs to mix with
555 *
556 * This function takes an RPC request for outputs to mix with
557 * and creates an RPC response with the resultant output indices.
558 *
559 * Outputs to mix with are specified in the request.
560 *
561 * @param req the outputs to return
562 * @param res return-by-reference the resultant output indices and keys
563 *
564 * @return true
565 */
566 bool get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const;
567
568 /**
569 * @brief gets an output's key and unlocked state
570 *
571 * @param amount in - the output amount
572 * @param index in - the output global amount index
573 * @param mask out - the output's RingCT mask
574 * @param key out - the output's key
575 * @param unlocked out - the output's unlocked state
576 */
577 void get_output_key_mask_unlocked(const uint64_t& amount, const uint64_t& index, crypto::public_key& key, rct::key& mask, bool& unlocked) const;
578
579 /**
580 * @brief gets per block distribution of outputs of a given amount
581 *
582 * @param amount the amount to get a ditribution for
583 * @param from_height the height before which we do not care about the data
584 * @param to_height the height after which we do not care about the data
585 * @param return-by-reference start_height the height of the first rct output
586 * @param return-by-reference distribution the start offset of the first rct output in this block (same as previous if none)
587 * @param return-by-reference base how many outputs of that amount are before the stated distribution
588 */
589 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;
590
591 /**
592 * @brief gets the global indices for outputs from a given transaction
593 *
594 * This function gets the global indices for all outputs belonging
595 * to a specific transaction.
596 *
597 * @param tx_id the hash of the transaction to fetch indices for
598 * @param indexs return-by-reference the global indices for the transaction's outputs
599 * @param n_txes how many txes in a row to get results for
600 *
601 * @return false if the transaction does not exist, or if no indices are found, otherwise true
602 */
603 bool get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const;
604 bool get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector<std::vector<uint64_t>>& indexs) const;
605
606 /**
607 * @brief stores the blockchain
608 *
609 * If Blockchain is handling storing of the blockchain (rather than BlockchainDB),
610 * this initiates a blockchain save.
611 *
612 * @return true unless saving the blockchain fails
613 */
614 bool store_blockchain();
615
616 /**
617 * @brief expands v2 transaction data from blockchain
618 *
619 * RingCT transactions do not transmit some of their data if it
620 * can be reconstituted by the receiver. This function expands
621 * that implicit data.
622 */
623 static bool expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys);
624
625 /**
626 * @brief validates a transaction's inputs
627 *
628 * validates a transaction's inputs as correctly used and not previously
629 * spent. also returns the hash and height of the most recent block
630 * which contains an output that was used as an input to the transaction.
631 * The transaction's rct signatures, if any, are expanded.
632 *
633 * @param tx the transaction to validate
634 * @param pmax_used_block_height return-by-reference block height of most recent input
635 * @param max_used_block_id return-by-reference block hash of most recent input
636 * @param tvc returned information about tx verification
637 * @param kept_by_block whether or not the transaction is from a previously-verified block
638 *
639 * @return false if any input is invalid, otherwise true
640 */
641 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;
642
643 /**
644 * @brief get fee quantization mask
645 *
646 * The dynamic fee may be quantized, to mask out the last decimal places
647 *
648 * @return the fee quantized mask
649 */
650 static uint64_t get_fee_quantization_mask()
651 {
652 return tools::PowerOf<10, CRYPTONOTE_DISPLAY_DECIMAL_POINT - PER_KB_FEE_QUANTIZATION_DECIMALS>::Value;
653 }
654
655 /**
656 * @brief get dynamic per kB or byte fee for a given block weight
657 *
658 * The dynamic fee is based on the block weight in a past window, and
659 * the current block reward. It is expressed by kB before v8, and
660 * per byte from v8.
661 *
662 * @param block_reward the current block reward
663 * @param median_block_weight the median block weight in the past window
664 * @param version hard fork version for rules and constants to use
665 *
666 * @return the fee
667 */
668 static uint64_t get_dynamic_base_fee(uint64_t block_reward, size_t median_block_weight, uint8_t version);
669
670 /**
671 * @brief get dynamic per kB or byte fee estimate for the next few blocks
672 *
673 * The dynamic fee is based on the block weight in a past window, and
674 * the current block reward. It is expressed by kB before v8, and
675 * per byte from v8.
676 * This function calculates an estimate for a dynamic fee which will be
677 * valid for the next grace_blocks
678 *
679 * @param grace_blocks number of blocks we want the fee to be valid for
680 *
681 * @return the fee estimate
682 */
683 uint64_t get_dynamic_base_fee_estimate(uint64_t grace_blocks) const;
684 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;
685
686 /**
687 * @brief get four levels of dynamic per byte fee estimate for the next few blocks
688 *
689 * The dynamic fee is based on the block weight in a past window, and
690 * the current block reward. It is expressed per byte, and is based on
691 * https://github.com/ArticMine/Monero-Documents/blob/master/MoneroScaling2021-02.pdf
692 * This function calculates an estimate for a dynamic fee which will be
693 * valid for the next grace_blocks
694 *
695 * @param grace_blocks number of blocks we want the fee to be valid for
696 *
697 * @return the fee estimates (4 of them)
698 */
699 void get_dynamic_base_fee_estimate_2021_scaling(uint64_t grace_blocks, std::vector<uint64_t> &fees) const;
700
701 /**
702 * @brief validate a transaction's fee
703 *
704 * This function validates the fee is enough for the transaction.
705 * This is based on the weight of the transaction, and, after a
706 * height threshold, on the average weight of transaction in a past window
707 *
708 * @param tx_weight the transaction weight
709 * @param fee the fee
710 *
711 * @return true if the fee is enough, false otherwise
712 */
713 bool check_fee(size_t tx_weight, uint64_t fee) const;
714
715 /**
716 * @brief check that a transaction's outputs conform to current standards
717 *
718 * This function checks, for example at the time of this writing, that
719 * each output is of the form a * 10^b (phrased differently, that if
720 * written out would have only one non-zero digit in base 10).
721 *
722 * @param tx the transaction to check the outputs of
723 * @param tvc returned info about tx verification
724 * @param hf_version hard fork version
725 *
726 * @return false if any outputs do not conform, otherwise true
727 */
728 static bool check_tx_outputs(const transaction& tx,
729 tx_verification_context &tvc,
730 std::uint8_t hf_version);
731
732 /**
733 * @brief gets the block weight limit based on recent blocks
734 *
735 * @return the limit
736 */
737 uint64_t get_current_cumulative_block_weight_limit() const;
738
739 /**
740 * @brief gets the long term block weight for a new block
741 *
742 * @return the long term block weight
743 */
744 uint64_t get_next_long_term_block_weight(uint64_t block_weight) const;
745
746 /**
747 * @brief gets the block weight median based on recent blocks (same window as for the limit)
748 *
749 * @return the median
750 */
751 uint64_t get_current_cumulative_block_weight_median() const;
752
753 /**
754 * @brief gets the difficulty of the block with a given height
755 *
756 * @param i the height
757 *
758 * @return the difficulty
759 */
760 difficulty_type block_difficulty(uint64_t i) const;
761
762 /**
763 * @brief gets blocks based on a list of block hashes
764 *
765 * @tparam t_ids_container a standard-iterable container
766 * @tparam t_blocks_container a standard-iterable container
767 * @tparam t_missed_container a standard-iterable container
768 * @param block_ids a container of block hashes for which to get the corresponding blocks
769 * @param blocks return-by-reference a container to store result blocks in
770 * @param missed_bs return-by-reference a container to store missed blocks in
771 *
772 * @return false if an unexpected exception occurs, else true
773 */
774 template<class t_ids_container, class t_blocks_container, class t_missed_container>
775 bool get_blocks(const t_ids_container& block_ids, t_blocks_container& blocks, t_missed_container& missed_bs) const;
776
777 /**
778 * @brief gets transactions based on a list of transaction hashes
779 *
780 * @tparam t_ids_container a standard-iterable container
781 * @tparam t_tx_container a standard-iterable container
782 * @tparam t_missed_container a standard-iterable container
783 * @param txs_ids a container of hashes for which to get the corresponding transactions
784 * @param txs return-by-reference a container to store result transactions in
785 * @param missed_txs return-by-reference a container to store missed transactions in
786 * @param pruned whether to return full or pruned blobs
787 *
788 * @return false if an unexpected exception occurs, else true
789 */
790 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;
791 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;
792 template<class t_ids_container, class t_tx_container, class t_missed_container>
793 bool get_split_transactions_blobs(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs) const;
794 template<class t_ids_container, class t_tx_container, class t_missed_container>
795 bool get_transactions(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs, bool pruned = false) const;
796
797 //debug functions
798
799 /**
800 * @brief check the blockchain against a set of checkpoints
801 *
802 * If a block fails a checkpoint and enforce is enabled, the blockchain
803 * will be rolled back to two blocks prior to that block. If enforce
804 * is disabled, as is currently the default case with DNS-based checkpoints,
805 * an error will be printed to the user but no other action will be taken.
806 *
807 * @param points the checkpoints to check against
808 * @param enforce whether or not to take action on failure
809 */
810 void check_against_checkpoints(const checkpoints& points, bool enforce);
811
812 /**
813 * @brief configure whether or not to enforce DNS-based checkpoints
814 *
815 * @param enforce the new enforcement setting
816 */
817 void set_enforce_dns_checkpoints(bool enforce);
818
819 /**
820 * @brief loads new checkpoints from a file and optionally from DNS
821 *
822 * @param file_path the path of the file to look for and load checkpoints from
823 * @param check_dns whether or not to check for new DNS-based checkpoints
824 *
825 * @return false if any enforced checkpoint type fails to load, otherwise true
826 */
827 bool update_checkpoints(const std::string& file_path, bool check_dns);
828
829
830 // user options, must be called before calling init()
831
832 /**
833 * @brief sets various performance options
834 *
835 * @param maxthreads max number of threads when preparing blocks for addition
836 * @param sync_on_blocks whether to sync based on blocks or bytes
837 * @param sync_threshold number of blocks/bytes to cache before syncing to database
838 * @param sync_mode the ::blockchain_db_sync_mode to use
839 * @param fast_sync sync using built-in block hashes as trusted
840 */
841 void set_user_options(uint64_t maxthreads, bool sync_on_blocks, uint64_t sync_threshold,
842 blockchain_db_sync_mode sync_mode, bool fast_sync);
843
844 /**
845 * @brief sets a txpool notify object to call for every new tx used to add a new block
846 *
847 * @param notify the notify object to call at every new tx used to add a new block
848 */
849 void set_txpool_notify(TxpoolNotifyCallback&& notify);
850
851 /**
852 * @brief sets a block notify object to call for every new block
853 *
854 * @param notify the notify object to call at every new block
855 */
856 void add_block_notify(BlockNotifyCallback&& notify);
857
858 /**
859 * @brief sets a miner notify object to call for every new block
860 *
861 * @param notify the notify object to call at every new block
862 */
863 void add_miner_notify(MinerNotifyCallback&& notify);
864
865 /**
866 * @brief sets a reorg notify object to call for every reorg
867 *
868 * @param notify the notify object to call at every reorg
869 */
870 void set_reorg_notify(const std::shared_ptr<tools::Notify> &notify) { m_reorg_notify = notify; }
871
872 /**
873 * @brief Notify this Blockchain's txpool notifier about a txpool event
874 */
875 void notify_txpool_event(std::vector<txpool_event>&& event) const;
876
877 /**
878 * @brief Put DB in safe sync mode
879 */
880 void safesyncmode(const bool onoff);
881
882 /**
883 * @brief set whether or not to show/print time statistics
884 *
885 * @param stats the new time stats setting
886 */
887 void set_show_time_stats(bool stats) { m_show_time_stats = stats; }
888
889 /**
890 * @brief gets the hardfork voting state object
891 *
892 * @return the HardFork object
893 */
894 HardFork::State get_hard_fork_state() const;
895
896 /**
897 * @brief gets the current hardfork version in use/voted for
898 *
899 * @return the version
900 */
901 uint8_t get_current_hard_fork_version() const { return m_hardfork->get_current_version(); }
902
903 /**
904 * @brief returns the newest hardfork version known to the blockchain
905 *
906 * @return the version
907 */
908 uint8_t get_ideal_hard_fork_version() const { return m_hardfork->get_ideal_version(); }
909
910 /**
911 * @brief returns the next hardfork version
912 *
913 * @return the version
914 */
915 uint8_t get_next_hard_fork_version() const { return m_hardfork->get_next_version(); }
916
917 /**
918 * @brief returns the newest hardfork version voted to be enabled
919 * as of a certain height
920 *
921 * @param height the height for which to check version info
922 *
923 * @return the version
924 */
925 uint8_t get_ideal_hard_fork_version(uint64_t height) const { return m_hardfork->get_ideal_version(height); }
926
927 /**
928 * @brief returns the actual hardfork version for a given block height
929 *
930 * @param height the height for which to check version info
931 *
932 * @return the version
933 */
934 uint8_t get_hard_fork_version(uint64_t height) const { return m_hardfork->get(height); }
935
936 /**
937 * @brief returns the earliest block a given version may activate
938 *
939 * @return the height
940 */
941 uint64_t get_earliest_ideal_height_for_version(uint8_t version) const { return m_hardfork->get_earliest_ideal_height_for_version(version); }
942
943 /**
944 * @brief get information about hardfork voting for a version
945 *
946 * @param version the version in question
947 * @param window the size of the voting window
948 * @param votes the number of votes to enable <version>
949 * @param threshold the number of votes required to enable <version>
950 * @param earliest_height the earliest height at which <version> is allowed
951 * @param voting which version this node is voting for/using
952 *
953 * @return whether the version queried is enabled
954 */
955 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;
956
957 /**
958 * @brief get difficulty target based on chain and hardfork version
959 *
960 * @return difficulty target
961 */
962 uint64_t get_difficulty_target() const;
963
964 /**
965 * @brief remove transactions from the transaction pool (if present)
966 *
967 * @param txids a list of hashes of transactions to be removed
968 *
969 * @return false if any removals fail, otherwise true
970 */
971 bool flush_txes_from_pool(const std::vector<crypto::hash> &txids);
972
973 /**
974 * @brief return a histogram of outputs on the blockchain
975 *
976 * @param amounts optional set of amounts to lookup
977 * @param unlocked whether to restrict instances to unlocked ones
978 * @param recent_cutoff timestamp to consider outputs as recent
979 * @param min_count return only amounts with at least that many instances
980 *
981 * @return a set of amount/instances
982 */
983 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;
984
985 /**
986 * @brief perform a check on all key images in the blockchain
987 *
988 * @param std::function the check to perform, pass/fail
989 *
990 * @return false if any key image fails the check, otherwise true
991 */
992 bool for_all_key_images(std::function<bool(const crypto::key_image&)>) const;
993
994 /**
995 * @brief perform a check on all blocks in the blockchain in the given range
996 *
997 * @param h1 the start height
998 * @param h2 the end height
999 * @param std::function the check to perform, pass/fail
1000 *
1001 * @return false if any block fails the check, otherwise true
1002 */
1003 bool for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const block&)>) const;
1004
1005 /**
1006 * @brief perform a check on all transactions in the blockchain
1007 *
1008 * @param std::function the check to perform, pass/fail
1009 * @param bool pruned whether to return pruned txes only
1010 *
1011 * @return false if any transaction fails the check, otherwise true
1012 */
1013 bool for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)>, bool pruned) const;
1014
1015 /**
1016 * @brief perform a check on all outputs in the blockchain
1017 *
1018 * @param std::function the check to perform, pass/fail
1019 *
1020 * @return false if any output fails the check, otherwise true
1021 */
1022 bool for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)>) const;
1023
1024 /**
1025 * @brief perform a check on all outputs of a given amount in the blockchain
1026 *
1027 * @param amount the amount to iterate through
1028 * @param std::function the check to perform, pass/fail
1029 *
1030 * @return false if any output fails the check, otherwise true
1031 */
1032 bool for_all_outputs(uint64_t amount, std::function<bool(uint64_t height)>) const;
1033
1034 /**
1035 * @brief get a reference to the BlockchainDB in use by Blockchain
1036 *
1037 * @return a reference to the BlockchainDB instance
1038 */
1039 const BlockchainDB& get_db() const
1040 {
1041 return *m_db;
1042 }
1043
1044 /**
1045 * @brief get a reference to the BlockchainDB in use by Blockchain
1046 *
1047 * @return a reference to the BlockchainDB instance
1048 */
1049 BlockchainDB& get_db()
1050 {
1051 return *m_db;
1052 }
1053
1054 /**
1055 * @brief get a number of outputs of a specific amount
1056 *
1057 * @param amount the amount
1058 * @param offsets the indices (indexed to the amount) of the outputs
1059 * @param outputs return-by-reference the outputs collected
1060 */
1061 void output_scan_worker(const uint64_t amount,const std::vector<uint64_t> &offsets,
1062 std::vector<output_data_t> &outputs) const;
1063
1064 /**
1065 * @brief computes the "short" and "long" hashes for a set of blocks
1066 *
1067 * @param height the height of the first block
1068 * @param blocks the blocks to be hashed
1069 * @param map return-by-reference the hashes for each block
1070 */
1071 void block_longhash_worker(uint64_t height, const epee::span<const block> &blocks,
1072 std::unordered_map<crypto::hash, crypto::hash> &map) const;
1073
1074 /**
1075 * @brief returns a set of known alternate chains
1076 *
1077 * @return a vector of chains
1078 */
1079 std::vector<std::pair<block_extended_info,std::vector<crypto::hash>>> get_alternative_chains() const;
1080
1081 void add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata &blob, const txpool_tx_meta_t &meta);
1082 void update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta);
1083 void remove_txpool_tx(const crypto::hash &txid);
1084 uint64_t get_txpool_tx_count(bool include_sensitive = false) const;
1085 bool get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const;
1086 bool get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const;
1087 cryptonote::blobdata get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const;
1088 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;
1089 bool txpool_tx_matches_category(const crypto::hash& tx_hash, relay_category category);
1090
1091 bool is_within_compiled_block_hash_area() const { return is_within_compiled_block_hash_area(m_db->height()); }
1092 uint64_t prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights);
1093 uint32_t get_blockchain_pruning_seed() const { return m_db->get_blockchain_pruning_seed(); }
1094 bool prune_blockchain(uint32_t pruning_seed = 0);
1095 bool update_blockchain_pruning();
1096 bool check_blockchain_pruning();
1097
1098 void lock();
1099 void unlock();
1100
1101 void cancel();
1102
1103 /**
1104 * @brief returns the timestamps of the last N blocks
1105 */
1106 std::vector<time_t> get_last_block_timestamps(unsigned int blocks) const;
1107
1108 /**
1109 * @brief removes blocks from the top of the blockchain
1110 *
1111 * @param nblocks number of blocks to be removed
1112 */
1113 void pop_blocks(uint64_t nblocks);
1114
1115 /**
1116 * @brief checks whether a given block height is included in the precompiled block hash area
1117 *
1118 * @param height the height to check for
1119 */
1120 bool is_within_compiled_block_hash_area(uint64_t height) const;
1121
1122 /**
1123 * @brief checks whether we have known weights for the given block heights
1124 *
1125 * @param height the start height to check for
1126 * @param nblocks how many blocks to check from that height
1127 */
1128 bool has_block_weights(uint64_t height, uint64_t nblocks) const;
1129
1130 /**
1131 * @brief flush the invalid blocks set
1132 */
1133 void flush_invalid_blocks();
1134
1135 /**
1136 * @brief get the "adjusted time"
1137 *
1138 * Computes the median timestamp of the previous 60 blocks, projects it
1139 * onto the current block to get an 'adjusted median time' which approximates
1140 * what the current block's timestamp should be. Also projects the previous
1141 * block's timestamp to estimate the current block's timestamp.
1142 *
1143 * Returns the minimum of the two projections, or the current local time on
1144 * the machine if less than 60 blocks are available.
1145 *
1146 * @return current time approximated from chain data
1147 */
1148 uint64_t get_adjusted_time(uint64_t height) const;
1149
1150 #ifndef IN_UNIT_TESTS
1151 private:
1152 #endif
1153
1154 // TODO: evaluate whether or not each of these typedefs are left over from blockchain_storage
1155 typedef std::unordered_set<crypto::key_image> key_images_container;
1156
1157 typedef std::vector<block_extended_info> blocks_container;
1158
1159 typedef std::unordered_map<crypto::hash, block_extended_info> blocks_ext_by_hash;
1160
1161
1162 BlockchainDB* m_db;
1163
1164 tx_memory_pool& m_tx_pool;
1165
1166 mutable epee::critical_section m_blockchain_lock; // TODO: add here reader/writer lock
1167
1168 // main chain
1169 size_t m_current_block_cumul_weight_limit;
1170 size_t m_current_block_cumul_weight_median;
1171
1172 // metadata containers
1173 std::unordered_map<crypto::hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>> m_scan_table;
1174 std::unordered_map<crypto::hash, crypto::hash> m_blocks_longhash_table;
1175
1176 // Keccak hashes for each block and for fast pow checking
1177 std::vector<std::pair<crypto::hash, crypto::hash>> m_blocks_hash_of_hashes;
1178 std::vector<std::pair<crypto::hash, uint64_t>> m_blocks_hash_check;
1179
1180 blockchain_db_sync_mode m_db_sync_mode;
1181 bool m_fast_sync;
1182 bool m_show_time_stats;
1183 bool m_db_default_sync;
1184 bool m_db_sync_on_blocks;
1185 uint64_t m_db_sync_threshold;
1186 uint64_t m_max_prepare_blocks_threads;
1187 uint64_t m_fake_pow_calc_time;
1188 uint64_t m_fake_scan_time;
1189 uint64_t m_sync_counter;
1190 uint64_t m_bytes_to_sync;
1191 std::vector<uint64_t> m_timestamps;
1192 std::vector<difficulty_type> m_difficulties;
1193 uint64_t m_timestamps_and_difficulties_height;
1194 bool m_reset_timestamps_and_difficulties_height;
1195 uint64_t m_long_term_block_weights_window;
1196 uint64_t m_long_term_effective_median_block_weight;
1197 mutable crypto::hash m_long_term_block_weights_cache_tip_hash;
1198 mutable epee::misc_utils::rolling_median_t<uint64_t> m_long_term_block_weights_cache_rolling_median;
1199
1200 epee::critical_section m_difficulty_lock;
1201 crypto::hash m_difficulty_for_next_block_top_hash;
1202 difficulty_type m_difficulty_for_next_block;
1203
1204 boost::asio::io_context m_async_service;
1205 boost::thread_group m_async_pool;
1206 std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> m_async_work_idle;
1207
1208 // some invalid blocks
1209 blocks_ext_by_hash m_invalid_blocks; // crypto::hash -> block_extended_info
1210
1211
1212 checkpoints m_checkpoints;
1213 bool m_enforce_dns_checkpoints;
1214
1215 HardFork *m_hardfork;
1216
1217 network_type m_nettype;
1218 bool m_offline;
1219 difficulty_type m_fixed_difficulty;
1220
1221 std::atomic<bool> m_cancel;
1222
1223 // block template cache
1224 block m_btc;
1225 account_public_address m_btc_address;
1226 blobdata m_btc_nonce;
1227 difficulty_type m_btc_difficulty;
1228 uint64_t m_btc_height;
1229 uint64_t m_btc_pool_cookie;
1230 uint64_t m_btc_expected_reward;
1231 crypto::hash m_btc_seed_hash;
1232 uint64_t m_btc_seed_height;
1233 bool m_btc_valid;
1234
1235
1236 bool m_batch_success;
1237
1238 TxpoolNotifyCallback m_txpool_notifier;
1239 mutable std::mutex m_txpool_notifier_mutex;
1240
1241 /* `boost::function` is used because the implementation never allocates if
1242 the callable object has a single `std::shared_ptr` or `std::weap_ptr`
1243 internally. Whereas, the libstdc++ `std::function` will allocate. */
1244
1245 std::vector<BlockNotifyCallback> m_block_notifiers;
1246 std::vector<MinerNotifyCallback> m_miner_notifiers;
1247 std::shared_ptr<tools::Notify> m_reorg_notify;
1248
1249 // for prepare_handle_incoming_blocks
1250 uint64_t m_prepare_height;
1251 uint64_t m_prepare_nblocks;
1252 std::vector<block> *m_prepare_blocks;
1253
1254 // cache for verifying transaction RCT non semantics
1255 mutable rct_ver_cache_t m_rct_ver_cache;
1256
1257 /**
1258 * @brief collects the keys for all outputs being "spent" as an input
1259 *
1260 * This function makes sure that each "input" in an input (mixins) exists
1261 * and collects the public key for each from the transaction it was included in
1262 * via the visitor passed to it.
1263 *
1264 * If pmax_related_block_height is not NULL, its value is set to the height
1265 * of the most recent block which contains an output used in the input set
1266 *
1267 * @tparam visitor_t a class encapsulating tx is unlocked and collect tx key
1268 * @param tx_in_to_key a transaction input instance
1269 * @param vis an instance of the visitor to use
1270 * @param tx_prefix_hash the hash of the associated transaction_prefix
1271 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1272 * @param tx_version version of the tx, if > 1 we also get commitments
1273 *
1274 * @return false if any keys are not found or any inputs are not unlocked, otherwise true
1275 */
1276 template<class visitor_t>
1277 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;
1278
1279 /**
1280 * @brief collect output public keys of a transaction input set
1281 *
1282 * This function locates all outputs associated with a given input set (mixins)
1283 * and validates that they exist and are usable
1284 * (unlocked, unspent is checked elsewhere).
1285 *
1286 * If pmax_related_block_height is not NULL, its value is set to the height
1287 * of the most recent block which contains an output used in the input set
1288 *
1289 * @param tx_version the transaction version
1290 * @param txin the transaction input
1291 * @param tx_prefix_hash the transaction prefix hash, for caching organization
1292 * @param sig the input signature
1293 * @param output_keys return-by-reference the public keys of the outputs in the input set
1294 * @param rct_signatures the ringCT signatures, which are only valid if tx version > 1
1295 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1296 * @param hf_version the consensus rules version to use
1297 *
1298 * @return false if any output is not yet unlocked, or is missing, otherwise true
1299 */
1300 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;
1301
1302 /**
1303 * @brief validate a transaction's inputs and their keys
1304 *
1305 * This function validates transaction inputs and their keys. Previously
1306 * it also performed double spend checking, but that has been moved to its
1307 * own function.
1308 * The transaction's rct signatures, if any, are expanded.
1309 *
1310 * If pmax_related_block_height is not NULL, its value is set to the height
1311 * of the most recent block which contains an output used in any input set
1312 *
1313 * Currently this function calls ring signature validation for each
1314 * transaction.
1315 *
1316 * @param tx the transaction to validate
1317 * @param tvc returned information about tx verification
1318 * @param pmax_related_block_height return-by-pointer the height of the most recent block in the input set
1319 *
1320 * @return false if any validation step fails, otherwise true
1321 */
1322 bool check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height = NULL) const;
1323
1324 /**
1325 * @brief performs a blockchain reorganization according to the longest chain rule
1326 *
1327 * This function aggregates all the actions necessary to switch to a
1328 * newly-longer chain. If any step in the reorganization process fails,
1329 * the blockchain is reverted to its previous state.
1330 *
1331 * @param alt_chain the chain to switch to
1332 * @param discard_disconnected_chain whether or not to keep the old chain as an alternate
1333 *
1334 * @return false if the reorganization fails, otherwise true
1335 */
1336 bool switch_to_alternative_blockchain(std::list<block_extended_info>& alt_chain, bool discard_disconnected_chain);
1337
1338 /**
1339 * @brief removes the most recent block from the blockchain
1340 *
1341 * @return the block removed
1342 */
1343 block pop_block_from_blockchain();
1344
1345 /**
1346 * @brief validate and add a new block to the end of the blockchain
1347 *
1348 * This function is merely a convenience wrapper around the other
1349 * of the same name. This one passes the block's hash to the other
1350 * as well as the block and verification context.
1351 *
1352 * @param bl the block to be added
1353 * @param bvc metadata concerning the block's validity
1354 *
1355 * @return true if the block was added successfully, otherwise false
1356 */
1357 bool handle_block_to_main_chain(const block& bl, block_verification_context& bvc);
1358
1359 /**
1360 * @brief validate and add a new block to the end of the blockchain
1361 *
1362 * When a block is given to Blockchain to be added to the blockchain, it
1363 * is passed here if it is determined to belong at the end of the current
1364 * chain.
1365 *
1366 * @param bl the block to be added
1367 * @param id the hash of the block
1368 * @param bvc metadata concerning the block's validity
1369 * @param extra_block_txs txs belonging to this block that may not be in the mempool
1370 *
1371 * @return true if the block was added successfully, otherwise false
1372 */
1373 bool handle_block_to_main_chain(const block& bl, const crypto::hash& id,
1374 block_verification_context& bvc, pool_supplement& extra_block_txs);
1375
1376 /**
1377 * @brief validate and add a new block to an alternate blockchain
1378 *
1379 * If a block to be added does not belong to the main chain, but there
1380 * is an alternate chain to which it should be added, that is handled
1381 * here.
1382 *
1383 * @param b the block to be added
1384 * @param id the hash of the block
1385 * @param bvc metadata concerning the block's validity
1386 * @param extra_block_txs txs belonging to this block that may not be in the mempool
1387 *
1388 * @return true if the block was added successfully, otherwise false
1389 */
1390 bool handle_alternative_block(const block& b, const crypto::hash& id,
1391 block_verification_context& bvc, pool_supplement& extra_block_txs);
1392
1393 /**
1394 * @brief builds a list of blocks connecting a block to the main chain
1395 *
1396 * @param prev_id the block hash of the tip of the alt chain
1397 * @param alt_chain the chain to be added to
1398 * @param timestamps returns the timestamps of previous blocks
1399 * @param bvc the block verification context for error return
1400 *
1401 * @return true on success, false otherwise
1402 */
1403 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;
1404
1405 /**
1406 * @brief gets the difficulty requirement for a new block on an alternate chain
1407 *
1408 * @param alt_chain the chain to be added to
1409 * @param bei the block being added (and metadata, see ::block_extended_info)
1410 *
1411 * @return the difficulty requirement
1412 */
1413 difficulty_type get_next_difficulty_for_alternative_chain(const std::list<block_extended_info>& alt_chain, block_extended_info& bei) const;
1414
1415 /**
1416 * @brief sanity checks a miner transaction before validating an entire block
1417 *
1418 * This function merely checks basic things like the structure of the miner
1419 * transaction, the unlock time, and that the amount doesn't overflow.
1420 *
1421 * @param b the block containing the miner transaction
1422 * @param height the height at which the block will be added
1423 * @param hf_version the consensus rules to apply
1424 *
1425 * @return false if anything is found wrong with the miner transaction, otherwise true
1426 */
1427 bool prevalidate_miner_transaction(const block& b, uint64_t height, uint8_t hf_version);
1428
1429 /**
1430 * @brief validates a miner (coinbase) transaction
1431 *
1432 * This function makes sure that the miner calculated his reward correctly
1433 * and that his miner transaction totals reward + fee.
1434 *
1435 * @param b the block containing the miner transaction to be validated
1436 * @param cumulative_block_weight the block's weight
1437 * @param fee the total fees collected in the block
1438 * @param base_reward return-by-reference the new block's generated coins
1439 * @param already_generated_coins the amount of currency generated prior to this block
1440 * @param partial_block_reward return-by-reference true if miner accepted only partial reward
1441 * @param version hard fork version for that transaction
1442 *
1443 * @return false if anything is found wrong with the miner transaction, otherwise true
1444 */
1445 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);
1446
1447 /**
1448 * @brief reverts the blockchain to its previous state following a failed switch
1449 *
1450 * If Blockchain fails to switch to an alternate chain when it means
1451 * to do so, this function reverts the blockchain to how it was before
1452 * the attempted switch.
1453 *
1454 * @param original_chain the chain to switch back to
1455 * @param rollback_height the height to revert to before appending the original chain
1456 *
1457 * @return false if something goes wrong with reverting (very bad), otherwise true
1458 */
1459 bool rollback_blockchain_switching(std::list<block>& original_chain, uint64_t rollback_height);
1460
1461 /**
1462 * @brief gets recent block weights for median calculation
1463 *
1464 * get the block weights of the last <count> blocks, and return by reference <weights>.
1465 *
1466 * @param weights return-by-reference the list of weights
1467 * @param count the number of blocks to get weights for
1468 */
1469 void get_last_n_blocks_weights(std::vector<uint64_t>& weights, size_t count) const;
1470
1471 /**
1472 * @brief gets block long term weight median
1473 *
1474 * get the block long term weight median of <count> blocks starting at <start_height>
1475 *
1476 * @param start_height the block height of the first block to query
1477 * @param count the number of blocks to get weights for
1478 *
1479 * @return the long term median block weight
1480 */
1481 uint64_t get_long_term_block_weight_median(uint64_t start_height, size_t count) const;
1482
1483 /**
1484 * @brief checks if a transaction is unlocked (its outputs spendable)
1485 *
1486 * This function checks to see if a transaction is unlocked.
1487 * unlock_time is either a block index or a unix time.
1488 *
1489 * @param unlock_time the unlock parameter (height or time)
1490 * @param hf_version the consensus rules version to use
1491 *
1492 * @return true if spendable, otherwise false
1493 */
1494 bool is_tx_spendtime_unlocked(uint64_t unlock_time, uint8_t hf_version) const;
1495
1496 /**
1497 * @brief stores an invalid block in a separate container
1498 *
1499 * Storing invalid blocks allows quick dismissal of the same block
1500 * if it is seen again.
1501 *
1502 * @param bl the invalid block
1503 * @param h the block's hash
1504 *
1505 * @return false if the block cannot be stored for some reason, otherwise true
1506 */
1507 bool add_block_as_invalid(const block& bl, const crypto::hash& h);
1508
1509 /**
1510 * @brief stores an invalid block in a separate container
1511 *
1512 * Storing invalid blocks allows quick dismissal of the same block
1513 * if it is seen again.
1514 *
1515 * @param bei the invalid block (see ::block_extended_info)
1516 * @param h the block's hash
1517 *
1518 * @return false if the block cannot be stored for some reason, otherwise true
1519 */
1520 bool add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h);
1521
1522 /**
1523 * @brief checks a block's timestamp
1524 *
1525 * This function grabs the timestamps from the most recent <n> blocks,
1526 * where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many
1527 * blocks in the blockchain, the timestap is assumed to be valid. If there
1528 * are, this function returns:
1529 * true if the block's timestamp is not less than the timestamp of the
1530 * median of the selected blocks
1531 * false otherwise
1532 *
1533 * @param b the block to be checked
1534 * @param median_ts return-by-reference the median of timestamps
1535 *
1536 * @return true if the block's timestamp is valid, otherwise false
1537 */
1538 bool check_block_timestamp(const block& b, uint64_t& median_ts) const;
1539 bool check_block_timestamp(const block& b) const { uint64_t median_ts; return check_block_timestamp(b, median_ts); }
1540
1541 /**
1542 * @brief checks a block's timestamp
1543 *
1544 * If the block is not more recent than the median of the recent
1545 * timestamps passed here, it is considered invalid.
1546 *
1547 * @param timestamps a list of the most recent timestamps to check against
1548 * @param b the block to be checked
1549 *
1550 * @return true if the block's timestamp is valid, otherwise false
1551 */
1552 bool check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b, uint64_t& median_ts) const;
1553 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); }
1554
1555 /**
1556 * @brief finish an alternate chain's timestamp window from the main chain
1557 *
1558 * for an alternate chain, get the timestamps from the main chain to complete
1559 * the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW.
1560 *
1561 * @param start_height the alternate chain's attachment height to the main chain
1562 * @param timestamps return-by-value the timestamps set to be populated
1563 *
1564 * @return true unless start_height is greater than the current blockchain height
1565 */
1566 bool complete_timestamps_vector(uint64_t start_height, std::vector<uint64_t>& timestamps) const;
1567
1568 /**
1569 * @brief calculate the block weight limit for the next block to be added
1570 *
1571 * @param long_term_effective_median_block_weight optionally return that value
1572 *
1573 * @return true
1574 */
1575 bool update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight = NULL);
1576
1577 /**
1578 * @brief make sure a transaction isn't attempting a double-spend
1579 *
1580 * @param tx the transaction to check
1581 * @param keys_this_block a cumulative list of spent keys for the current block
1582 *
1583 * @return false if a double spend was detected, otherwise true
1584 */
1585 bool check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const;
1586
1587 /**
1588 * @brief validates a transaction input's ring signature
1589 *
1590 * @param tx_prefix_hash the transaction prefix' hash
1591 * @param key_image the key image generated from the true input
1592 * @param pubkeys the public keys for each input in the ring signature
1593 * @param sig the signature generated for each input in the ring signature
1594 * @param result false if the ring signature is invalid, otherwise true
1595 */
1596 void check_ring_signature(const crypto::hash &tx_prefix_hash, const crypto::key_image &key_image,
1597 const std::vector<rct::ctkey> &pubkeys, const std::vector<crypto::signature> &sig, uint64_t &result) const;
1598
1599 /**
1600 * @brief loads block hashes from compiled-in data set
1601 *
1602 * A (possibly empty) set of block hashes can be compiled into the
1603 * monero daemon binary. This function loads those hashes into
1604 * a useful state.
1605 *
1606 * @param get_checkpoints if set, will be called to get checkpoints data
1607 */
1608 void load_compiled_in_block_hashes(const GetCheckpointsCallback& get_checkpoints);
1609
1610 /**
1611 * @brief invalidates any cached block template
1612 */
1613 void invalidate_block_template_cache();
1614
1615 /**
1616 * @brief stores a new cached block template
1617 *
1618 * At some point, may be used to push an update to miners
1619 */
1620 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);
1621
1622 /**
1623 * @brief sends new block notifications to ZMQ `miner_data` subscribers
1624 *
1625 * @param height current blockchain height
1626 * @param seed_hash seed hash to use for mining
1627 * @param prev_id hash of new blockchain tip
1628 * @param already_generated_coins total coins mined by the network so far
1629 */
1630 void send_miner_notifications(uint64_t height, const crypto::hash &seed_hash, const crypto::hash &prev_id, uint64_t already_generated_coins);
1631 };
1632 } // namespace cryptonote