oxen-core/src/blockchain_db/blockchain_db.cpp

449 lines
16 KiB
C++
Raw Permalink Normal View History

// Copyright (c) 2014-2019, The Monero Project
2018-04-10 06:49:20 +02:00
// Copyright (c) 2018, The Loki Project
2023-04-13 15:50:13 +02:00
//
// All rights reserved.
2023-04-13 15:50:13 +02:00
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
2023-04-13 15:50:13 +02:00
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
2023-04-13 15:50:13 +02:00
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
2023-04-13 15:50:13 +02:00
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
2023-04-13 15:50:13 +02:00
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2023-04-13 15:50:13 +02:00
#include "blockchain_db.h"
#include <chrono>
#include "checkpoints/checkpoints.h"
#include "common/hex.h"
#include "common/string_util.h"
2023-04-13 15:50:13 +02:00
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_basic/hardfork.h"
#include "cryptonote_core/service_node_rules.h"
#include "epee/string_tools.h"
#include "lmdb/db_lmdb.h"
2023-04-13 15:50:13 +02:00
#include "ringct/rctOps.h"
2023-04-13 15:50:13 +02:00
namespace cryptonote {
2023-04-13 15:50:13 +02:00
static auto logcat = log::Cat("blockchain.db");
const command_line::arg_descriptor<std::string> arg_db_sync_mode = {
2023-04-13 15:50:13 +02:00
"db-sync-mode",
"Specify sync option, using format "
"[safe|fast|fastest]:[sync|async]:[<nblocks_per_sync>[blocks]|<nbytes_per_sync>[bytes]].",
"fast:async:250000000bytes"};
const command_line::arg_descriptor<bool> arg_db_salvage = {
"db-salvage", "Try to salvage a blockchain database if it seems corrupted", false};
BlockchainDB* new_db() {
return new BlockchainLMDB();
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::init_options(boost::program_options::options_description& desc) {
command_line::add_arg(desc, arg_db_sync_mode);
command_line::add_arg(desc, arg_db_salvage);
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::pop_block() {
block blk;
std::vector<transaction> txs;
pop_block(blk, txs);
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::add_transaction(
const crypto::hash& blk_hash,
const std::pair<transaction, std::string>& txp,
const crypto::hash* tx_hash_ptr,
const crypto::hash* tx_prunable_hash_ptr) {
const transaction& tx = txp.first;
bool miner_tx = false;
crypto::hash tx_hash, tx_prunable_hash;
if (!tx_hash_ptr) {
// should only need to compute hash for miner transactions
tx_hash = get_transaction_hash(tx);
log::trace(logcat, "null tx_hash_ptr - needed to compute: {}", tx_hash);
} else {
tx_hash = *tx_hash_ptr;
}
2023-04-13 15:50:13 +02:00
bool has_blacklisted_outputs = false;
if (tx.version >= cryptonote::txversion::v2_ringct) {
if (!tx_prunable_hash_ptr)
tx_prunable_hash = get_transaction_prunable_hash(tx, &txp.second);
else
tx_prunable_hash = *tx_prunable_hash_ptr;
crypto::secret_key secret_tx_key;
cryptonote::account_public_address address;
if (get_tx_secret_key_from_tx_extra(tx.extra, secret_tx_key) &&
get_service_node_contributor_from_tx_extra(tx.extra, address))
has_blacklisted_outputs = true;
}
2023-04-13 15:50:13 +02:00
for (const txin_v& tx_input : tx.vin) {
if (std::holds_alternative<txin_to_key>(tx_input)) {
add_spent_key(var::get<txin_to_key>(tx_input).k_image);
} else if (std::holds_alternative<txin_gen>(tx_input)) {
/* nothing to do here */
miner_tx = true;
} else {
log::info(
logcat,
"Unsupported input type, removing key images and aborting transaction "
"addition");
for (const txin_v& tx_input : tx.vin) {
if (std::holds_alternative<txin_to_key>(tx_input)) {
remove_spent_key(var::get<txin_to_key>(tx_input).k_image);
}
}
return;
}
}
2023-04-13 15:50:13 +02:00
uint64_t tx_id = add_transaction_data(blk_hash, txp, tx_hash, tx_prunable_hash);
2023-04-13 15:50:13 +02:00
std::vector<uint64_t> amount_output_indices(tx.vout.size());
2023-04-13 15:50:13 +02:00
// iterate tx.vout using indices instead of C++11 foreach syntax because
// we need the index
for (uint64_t i = 0; i < tx.vout.size(); ++i) {
uint64_t unlock_time = 0;
if (tx.version >= cryptonote::txversion::v3_per_output_unlock_times) {
unlock_time = tx.output_unlock_times[i];
} else {
unlock_time = tx.unlock_time;
}
2023-04-13 15:50:13 +02:00
// miner v2 txes have their coinbase output in one single out to save space,
// and we store them as rct outputs with an identity mask
if (miner_tx && tx.version >= cryptonote::txversion::v2_ringct) {
cryptonote::tx_out vout = tx.vout[i];
const rct::key commitment = rct::zeroCommit(vout.amount);
vout.amount = 0;
amount_output_indices[i] = add_output(tx_hash, vout, i, unlock_time, &commitment);
} else {
amount_output_indices[i] = add_output(
tx_hash,
tx.vout[i],
i,
unlock_time,
tx.version >= cryptonote::txversion::v2_ringct
? &tx.rct_signatures.outPk[i].mask
: NULL);
}
}
Infinite Staking Part 2 (#406) * Cleanup and undoing some protocol breakages * Simplify expiration of nodes * Request unlock schedules entire node for expiration * Fix off by one in expiring nodes * Undo expiring code for pre v10 nodes * Fix RPC returning register as unlock height and not checking 0 * Rename key image unlock height const * Undo testnet hardfork debug changes * Remove is_type for get_type, fix missing var rename * Move serialisable data into public namespace * Serialise tx types properly * Fix typo in no service node known msg * Code review * Fix == to >= on serialising tx type * Code review 2 * Fix tests and key image unlock * Add command to print locked key images * Update ui to display lock stakes, query in print cmd blacklist * Modify print stakes to be less slow * Remove autostaking code * Refactor staking into sweep functions It appears staking was derived off stake_main written separately at implementation at the beginning. This merges them back into a common code path, after removing autostake there's only some minor differences. It also makes sure that any changes to sweeping upstream are going to be considered in the staking process which we want. * Display unlock height for stakes * Begin creating output blacklist * Make blacklist output a migration step * Implement get_output_blacklist for lmdb * In wallet output selection ignore blacklisted outputs * Apply blacklisted outputs to output selection * Fix broken tests, switch key image unlock * Fix broken unit_tests * Begin change to limit locked key images to 4 globally * Revamp prepare registration for new min contribution rules * Fix up old back case in prepare registration * Remove debug code * Cleanup debug code and some unecessary changes * Fix migration step on mainnet db * Fix blacklist outputs for pre-existing DB's * Remove irrelevant note * Tweak scanning addresses for locked stakes Since we only now allow contributions from the primary address we can skip checking all subaddress + lookahead to speed up wallet scanning * Define macro for SCNu64 for Mingw * Fix failure on empty DB * Add missing error msg, remove contributor from stake * Improve staking messages * Flush prompt to always display * Return the msg from stake failure and fix stake parsing error * Tweak fork rules for smaller bulletproofs * Tweak pooled nodes minimum amounts * Fix crash on exit, there's no need to store on destructor Since all information about service nodes is derived from the blockchain and we store state every time we receive a block, storing in the destructor is redundant as there is no new information to store. * Make prompt be consistent with CLI * Check max number of key images from per user to node * Implement error message on get_output_blacklist failure * Remove resolved TODO's/comments * Handle infinite staking in print_sn * Atoi->strtol, fix prepare_registration, virtual override, stale msgs
2019-02-14 02:12:57 +01:00
2023-04-13 15:50:13 +02:00
if (has_blacklisted_outputs)
add_output_blacklist(amount_output_indices);
Infinite Staking Part 2 (#406) * Cleanup and undoing some protocol breakages * Simplify expiration of nodes * Request unlock schedules entire node for expiration * Fix off by one in expiring nodes * Undo expiring code for pre v10 nodes * Fix RPC returning register as unlock height and not checking 0 * Rename key image unlock height const * Undo testnet hardfork debug changes * Remove is_type for get_type, fix missing var rename * Move serialisable data into public namespace * Serialise tx types properly * Fix typo in no service node known msg * Code review * Fix == to >= on serialising tx type * Code review 2 * Fix tests and key image unlock * Add command to print locked key images * Update ui to display lock stakes, query in print cmd blacklist * Modify print stakes to be less slow * Remove autostaking code * Refactor staking into sweep functions It appears staking was derived off stake_main written separately at implementation at the beginning. This merges them back into a common code path, after removing autostake there's only some minor differences. It also makes sure that any changes to sweeping upstream are going to be considered in the staking process which we want. * Display unlock height for stakes * Begin creating output blacklist * Make blacklist output a migration step * Implement get_output_blacklist for lmdb * In wallet output selection ignore blacklisted outputs * Apply blacklisted outputs to output selection * Fix broken tests, switch key image unlock * Fix broken unit_tests * Begin change to limit locked key images to 4 globally * Revamp prepare registration for new min contribution rules * Fix up old back case in prepare registration * Remove debug code * Cleanup debug code and some unecessary changes * Fix migration step on mainnet db * Fix blacklist outputs for pre-existing DB's * Remove irrelevant note * Tweak scanning addresses for locked stakes Since we only now allow contributions from the primary address we can skip checking all subaddress + lookahead to speed up wallet scanning * Define macro for SCNu64 for Mingw * Fix failure on empty DB * Add missing error msg, remove contributor from stake * Improve staking messages * Flush prompt to always display * Return the msg from stake failure and fix stake parsing error * Tweak fork rules for smaller bulletproofs * Tweak pooled nodes minimum amounts * Fix crash on exit, there's no need to store on destructor Since all information about service nodes is derived from the blockchain and we store state every time we receive a block, storing in the destructor is redundant as there is no new information to store. * Make prompt be consistent with CLI * Check max number of key images from per user to node * Implement error message on get_output_blacklist failure * Remove resolved TODO's/comments * Handle infinite staking in print_sn * Atoi->strtol, fix prepare_registration, virtual override, stale msgs
2019-02-14 02:12:57 +01:00
2023-04-13 15:50:13 +02:00
add_tx_amount_output_indices(tx_id, amount_output_indices);
}
2023-04-13 15:50:13 +02:00
uint64_t BlockchainDB::add_block(
const std::pair<block, std::string>& blck,
size_t block_weight,
uint64_t long_term_block_weight,
const difficulty_type& cumulative_difficulty,
const uint64_t& coins_generated,
const std::vector<std::pair<transaction, std::string>>& txs) {
const block& blk = blck.first;
// sanity
if (blk.tx_hashes.size() != txs.size())
throw std::runtime_error("Inconsistent tx/hashes sizes");
auto started = std::chrono::steady_clock::now();
crypto::hash blk_hash = get_block_hash(blk);
time_blk_hash += std::chrono::steady_clock::now() - started;
uint64_t prev_height = height();
// call out to add the transactions
started = std::chrono::steady_clock::now();
uint64_t num_rct_outs = 0;
add_transaction(blk_hash, std::make_pair(blk.miner_tx, tx_to_blob(blk.miner_tx)));
if (blk.miner_tx.version >= cryptonote::txversion::v2_ringct)
num_rct_outs += blk.miner_tx.vout.size();
int tx_i = 0;
crypto::hash tx_hash{};
for (const std::pair<transaction, std::string>& tx : txs) {
tx_hash = blk.tx_hashes[tx_i];
add_transaction(blk_hash, tx, &tx_hash);
for (const auto& vout : tx.first.vout) {
if (vout.amount == 0)
++num_rct_outs;
}
++tx_i;
}
2023-04-13 15:50:13 +02:00
time_add_transaction += std::chrono::steady_clock::now() - started;
// call out to subclass implementation to add the block & metadata
started = std::chrono::steady_clock::now();
add_block(
blk,
block_weight,
long_term_block_weight,
cumulative_difficulty,
coins_generated,
num_rct_outs,
blk_hash);
time_add_block1 += std::chrono::steady_clock::now() - started;
++num_calls;
return prev_height;
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::pop_block(block& blk, std::vector<transaction>& txs) {
blk = get_top_block();
2023-04-13 15:50:13 +02:00
remove_block();
2023-04-13 15:50:13 +02:00
for (auto it = blk.tx_hashes.rbegin(); it != blk.tx_hashes.rend(); ++it) {
auto& h = *it;
cryptonote::transaction tx;
if (!get_tx(h, tx) && !get_pruned_tx(h, tx))
throw DB_ERROR("Failed to get pruned or unpruned transaction from the db");
txs.push_back(std::move(tx));
remove_transaction(h);
}
remove_transaction(get_transaction_hash(blk.miner_tx));
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::remove_transaction(const crypto::hash& tx_hash) {
transaction tx = get_pruned_tx(tx_hash);
2023-04-13 15:50:13 +02:00
for (const txin_v& tx_input : tx.vin) {
if (std::holds_alternative<txin_to_key>(tx_input)) {
remove_spent_key(var::get<txin_to_key>(tx_input).k_image);
}
}
2023-04-13 15:50:13 +02:00
// need tx as tx.vout has the tx outputs, and the output amounts are needed
remove_transaction_data(tx_hash, tx);
}
2023-04-13 15:50:13 +02:00
block_header BlockchainDB::get_block_header(const crypto::hash& h) const {
block_header b = get_block_header_from_height(get_block_height(h));
return b;
}
2023-04-13 15:50:13 +02:00
block BlockchainDB::get_block(const crypto::hash& h) const {
block b = get_block_from_height(get_block_height(h));
return b;
}
2023-04-13 15:50:13 +02:00
bool BlockchainDB::get_tx(const crypto::hash& h, cryptonote::transaction& tx) const {
std::string bd;
if (!get_tx_blob(h, bd))
return false;
if (!parse_and_validate_tx_from_blob(bd, tx))
throw DB_ERROR("Failed to parse transaction from blob retrieved from the db");
2023-04-13 15:50:13 +02:00
return true;
}
2023-04-13 15:50:13 +02:00
bool BlockchainDB::get_pruned_tx(const crypto::hash& h, cryptonote::transaction& tx) const {
std::string bd;
if (!get_pruned_tx_blob(h, bd))
return false;
if (!parse_and_validate_tx_base_from_blob(bd, tx)) {
throw DB_ERROR("Failed to parse transaction base from blob retrieved from the db");
}
return true;
}
2023-04-13 15:50:13 +02:00
transaction BlockchainDB::get_tx(const crypto::hash& h) const {
transaction tx;
if (!get_tx(h, tx))
throw TX_DNE("tx with hash " + tools::type_to_hex(h) + " not found in db");
return tx;
}
2023-04-13 15:50:13 +02:00
uint64_t BlockchainDB::get_output_unlock_time(
const uint64_t amount, const uint64_t amount_index) const {
output_data_t odata = get_output_key(amount, amount_index);
return odata.unlock_time;
}
2023-04-13 15:50:13 +02:00
transaction BlockchainDB::get_pruned_tx(const crypto::hash& h) const {
transaction tx;
if (!get_pruned_tx(h, tx))
throw TX_DNE("pruned tx with hash " + tools::type_to_hex(h) + " not found in db");
return tx;
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::reset_stats() {
num_calls = 0;
time_blk_hash = 0ns;
time_tx_exists = 0ns;
time_add_block1 = 0ns;
time_add_transaction = 0ns;
time_commit1 = 0ns;
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::show_stats() {
log::info(
logcat,
"\n*********************************\n \
num_calls: {}\n \
time_blk_hash: {}\n \
time_tx_exists: {}\n \
time_add_block1: {}\n \
time_add_transaction: {}\n \
time_commit1: {}\n \
*********************************\n",
2023-04-13 15:50:13 +02:00
num_calls,
tools::friendly_duration(time_blk_hash),
tools::friendly_duration(time_tx_exists),
tools::friendly_duration(time_add_block1),
tools::friendly_duration(time_add_transaction),
tools::friendly_duration(time_commit1));
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::fixup(cryptonote::network_type) {
if (is_read_only()) {
log::info(logcat, "Database is opened read only - skipping fixup check");
return;
}
2023-04-13 15:50:13 +02:00
set_batch_transactions(true);
}
2023-04-13 15:50:13 +02:00
bool BlockchainDB::get_immutable_checkpoint(
checkpoint_t* immutable_checkpoint, uint64_t block_height) const {
size_t constexpr NUM_CHECKPOINTS = service_nodes::CHECKPOINT_NUM_CHECKPOINTS_FOR_CHAIN_FINALITY;
static_assert(
NUM_CHECKPOINTS == 2,
"Expect checkpoint finality to be 2, otherwise the immutable logic needs to check for "
"any hardcoded "
"checkpoints inbetween");
2023-04-13 15:50:13 +02:00
std::vector<checkpoint_t> checkpoints = get_checkpoints_range(block_height, 0, NUM_CHECKPOINTS);
if (checkpoints.empty())
return false;
checkpoint_t* checkpoint_ptr = nullptr;
if (checkpoints[0].type != checkpoint_type::service_node) // checkpoint[0] is the first closest
// checkpoint that is <= my height
{
checkpoint_ptr = &checkpoints[0]; // Must be hard-coded then, always immutable
} else if (checkpoints.size() == NUM_CHECKPOINTS) {
// NOTE: The first checkpoint is a service node checkpoint. Go back
// 1 checkpoint, which will either be another service node checkpoint or
// a predefined one.
checkpoint_ptr = &checkpoints[1];
} else {
return false; // NOTE: Only one service node checkpoint recorded, we can override this
// checkpoint.
}
if (immutable_checkpoint)
*immutable_checkpoint = std::move(*checkpoint_ptr);
return true;
}
2023-04-13 15:50:13 +02:00
uint64_t BlockchainDB::get_tx_block_height(const crypto::hash& h) const {
auto result = get_tx_block_heights({{h}}).front();
if (result == std::numeric_limits<uint64_t>::max()) {
std::string err = "tx_data_t with hash " + tools::type_to_hex(h) + " not found in db";
log::info(logcat, "{}", err);
throw TX_DNE(std::move(err));
}
return result;
}
2023-04-13 15:50:13 +02:00
bool BlockchainDB::get_alt_block_header(
const crypto::hash& blkid,
alt_block_data_t* data,
cryptonote::block_header* header,
std::string* checkpoint) const {
std::string blob;
if (!get_alt_block(blkid, data, &blob, checkpoint)) {
throw BLOCK_DNE("Alt-block with hash " + tools::type_to_hex(blkid) + " not found in db");
return false;
}
2023-04-13 15:50:13 +02:00
try {
serialization::binary_string_unarchiver ba{blob};
serialization::value(ba, *header);
} catch (std::exception& e) {
return false;
}
2023-04-13 15:50:13 +02:00
return true;
}
2023-04-13 15:50:13 +02:00
void BlockchainDB::fill_timestamps_and_difficulties_for_pow(
cryptonote::network_type nettype,
std::vector<uint64_t>& timestamps,
std::vector<uint64_t>& difficulties,
uint64_t chain_height,
uint64_t timestamps_difficulty_height) const {
constexpr uint64_t MIN_CHAIN_HEIGHT = 2;
if (chain_height < MIN_CHAIN_HEIGHT)
return;
uint64_t const top_block_height = chain_height - 1;
bool const before_hf16 = !is_hard_fork_at_least(nettype, hf::hf16_pulse, chain_height);
uint64_t const block_count = old::DIFFICULTY_BLOCKS_COUNT(before_hf16);
timestamps.reserve(block_count);
difficulties.reserve(block_count);
if (timestamps_difficulty_height == 0 || (chain_height - timestamps_difficulty_height) != 1 ||
timestamps.size() > block_count || difficulties.size() > block_count) {
// Cache invalidated.
timestamps.clear();
difficulties.clear();
// Fill missing timestamps/difficulties, up to one before the latest (latest is added
// below).
uint64_t start_height = chain_height - std::min<size_t>(chain_height, block_count);
start_height = std::max<uint64_t>(start_height, 1);
for (uint64_t block_height = start_height;
block_height < (chain_height - 1) /*skip latest block*/;
block_height++) {
timestamps.push_back(get_block_timestamp(block_height));
difficulties.push_back(get_block_cumulative_difficulty(block_height));
}
}
// Add latest timestamp/difficulty
add_timestamp_and_difficulty(
nettype,
chain_height,
timestamps,
difficulties,
get_block_timestamp(top_block_height),
get_block_cumulative_difficulty(top_block_height));
}
} // namespace cryptonote