From d7992b59407d9492dcbd539b0033367b8e213875 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Tue, 13 Sep 2022 16:57:56 +1000 Subject: [PATCH 01/32] Logging Refactor This replaces the current epee logging system with our oxen::log library. It replaces the easylogging library with spdlog, removes the macros and replaces with functions and standardises how we call the logs. --- .gitmodules | 12 +- CMakeLists.txt | 2 - contrib/epee/include/epee/console_handler.h | 7 - contrib/epee/include/epee/misc_log_ex.h | 122 +- .../include/epee/net/abstract_tcp_server2.inl | 156 +- contrib/epee/include/epee/net/buffer.h | 4 - .../include/epee/net/levin_protocol_handler.h | 7 - .../epee/net/levin_protocol_handler_async.h | 52 +- .../epee/include/epee/net/net_utils_base.h | 31 +- .../serialization/keyvalue_serialization.h | 8 +- .../keyvalue_serialization_overloads.h | 2 +- .../epee/storages/levin_abstract_invoke2.h | 19 - .../epee/storages/portable_storage_base.h | 1 + .../storages/portable_storage_from_json.h | 6 - .../epee/storages/portable_storage_to_bin.h | 1 + .../portable_storage_val_converters.h | 1 - contrib/epee/src/CMakeLists.txt | 2 - contrib/epee/src/connection_basic.cpp | 15 +- contrib/epee/src/mlocker.cpp | 17 +- contrib/epee/src/mlog.cpp | 494 -- contrib/epee/src/network_throttle-detail.cpp | 28 +- contrib/epee/src/parserse_base_utils.cpp | 4 - contrib/epee/src/portable_storage.cpp | 3 - contrib/epee/src/wipeable_string.cpp | 1 + contrib/format.sh | 2 +- external/CMakeLists.txt | 3 +- external/easylogging++/CMakeLists.txt | 61 - external/easylogging++/ea_config.h | 17 - external/easylogging++/easylogging++.cc | 3319 ------------ external/easylogging++/easylogging++.h | 4653 ----------------- external/fmt | 1 - external/oxen-logging | 1 + external/oxen-mq | 2 +- src/CMakeLists.txt | 1 + src/blockchain_db/CMakeLists.txt | 1 + src/blockchain_db/blockchain_db.cpp | 32 +- src/blockchain_db/lmdb/db_lmdb.cpp | 532 +- src/blockchain_db/locked_txn.h | 4 +- src/blockchain_db/sqlite/db_sqlite.cpp | 82 +- src/blockchain_db/sqlite/db_sqlite.h | 1 - src/blockchain_utilities/CMakeLists.txt | 1 + .../blockchain_ancestry.cpp | 99 +- .../blockchain_blackball.cpp | 115 +- src/blockchain_utilities/blockchain_depth.cpp | 75 +- .../blockchain_export.cpp | 45 +- .../blockchain_import.cpp | 118 +- src/blockchain_utilities/blockchain_prune.cpp | 49 +- .../blockchain_prune_known_spent_data.cpp | 47 +- src/blockchain_utilities/blockchain_stats.cpp | 42 +- src/blockchain_utilities/blockchain_usage.cpp | 50 +- src/blockchain_utilities/blocksdat_file.cpp | 24 +- src/blockchain_utilities/bootstrap_file.cpp | 73 +- src/checkpoints/CMakeLists.txt | 1 + src/checkpoints/checkpoints.cpp | 25 +- src/checkpoints/checkpoints.h | 1 - src/common/CMakeLists.txt | 3 +- src/common/apply_permutation.h | 16 +- src/common/boost_serialization_helper.h | 3 +- src/common/command_line.h | 15 +- src/common/expect.cpp | 6 +- src/common/file.cpp | 35 +- src/common/i18n.cpp | 4 +- src/common/json_util.h | 4 +- src/common/notify.cpp | 6 +- src/common/perf_timer.cpp | 141 - src/common/perf_timer.h | 84 - src/common/scoped_message_writer.cpp | 17 +- src/common/scoped_message_writer.h | 23 +- src/common/signal_handler.h | 2 +- src/common/spawn.cpp | 26 +- src/common/threadpool.cpp | 5 +- src/common/util.cpp | 16 +- src/crypto/CMakeLists.txt | 1 + src/crypto/fmt.h | 69 + src/crypto/rx-slow-hash.c | 5 - src/cryptonote_basic/CMakeLists.txt | 1 + src/cryptonote_basic/account.cpp | 10 +- src/cryptonote_basic/connection_context.h | 9 + src/cryptonote_basic/cryptonote_basic.h | 19 +- .../cryptonote_basic_impl.cpp | 18 +- .../cryptonote_format_utils.cpp | 105 +- .../cryptonote_format_utils.h | 5 +- src/cryptonote_basic/miner.cpp | 44 +- src/cryptonote_core/CMakeLists.txt | 1 + src/cryptonote_core/blockchain.cpp | 789 +-- src/cryptonote_core/cryptonote_core.cpp | 255 +- src/cryptonote_core/cryptonote_tx_utils.cpp | 75 +- src/cryptonote_core/oxen_name_system.cpp | 70 +- src/cryptonote_core/oxen_name_system.h | 18 +- src/cryptonote_core/pulse.cpp | 125 +- src/cryptonote_core/service_node_list.cpp | 426 +- .../service_node_quorum_cop.cpp | 94 +- src/cryptonote_core/service_node_quorum_cop.h | 26 +- src/cryptonote_core/service_node_rules.cpp | 18 +- src/cryptonote_core/service_node_swarm.cpp | 33 +- src/cryptonote_core/service_node_voting.cpp | 85 +- src/cryptonote_core/service_node_voting.h | 27 +- src/cryptonote_core/tx_blink.cpp | 2 +- src/cryptonote_core/tx_pool.cpp | 166 +- src/cryptonote_core/tx_sanity_check.cpp | 15 +- src/cryptonote_core/uptime_proof.cpp | 8 +- src/cryptonote_protocol/CMakeLists.txt | 2 +- src/cryptonote_protocol/block_queue.cpp | 35 +- .../cryptonote_protocol_handler.h | 17 +- .../cryptonote_protocol_handler.inl | 608 +-- src/cryptonote_protocol/levin_notify.cpp | 11 +- src/cryptonote_protocol/quorumnet.cpp | 164 +- src/daemon/CMakeLists.txt | 1 + src/daemon/command_line_args.h | 4 +- src/daemon/command_parser_executor.cpp | 13 +- src/daemon/daemon.cpp | 68 +- src/daemon/daemon.h | 1 - src/daemon/main.cpp | 30 +- src/daemon/rpc_command_executor.cpp | 13 - src/daemonizer/posix_daemonizer.inl | 2 +- src/debug_utilities/CMakeLists.txt | 2 + src/debug_utilities/cn_deserialize.cpp | 19 +- src/debug_utilities/object_sizes.cpp | 6 +- src/device/CMakeLists.txt | 1 + src/device/device.cpp | 6 +- src/device/device_ledger.cpp | 56 +- src/device/io_hid.cpp | 23 +- src/device/io_ledger_tcp.cpp | 10 +- src/device/log.cpp | 10 +- src/device_trezor/device_trezor.cpp | 33 +- src/device_trezor/device_trezor_base.cpp | 57 +- src/device_trezor/trezor/transport.cpp | 46 +- src/gen_multisig/CMakeLists.txt | 1 + src/gen_multisig/gen_multisig.cpp | 8 +- src/logging/CMakeLists.txt | 5 + src/logging/dev_sink.h | 84 + src/logging/oxen_logger.cpp | 173 + src/logging/oxen_logger.h | 28 + src/mnemonics/CMakeLists.txt | 2 +- src/mnemonics/chinese_simplified.h | 3424 ++++++------ src/mnemonics/dutch.h | 3378 ++++++------ src/mnemonics/electrum-words.cpp | 28 +- src/mnemonics/english.h | 3378 ++++++------ src/mnemonics/english_old.h | 3382 ++++++------ src/mnemonics/esperanto.h | 3396 ++++++------ src/mnemonics/german.h | 3382 ++++++------ src/mnemonics/italian.h | 3382 ++++++------ src/mnemonics/japanese.h | 3422 ++++++------ src/mnemonics/language_base.h | 573 +- src/mnemonics/lojban.h | 3392 ++++++------ src/mnemonics/portuguese.h | 3424 ++++++------ src/mnemonics/russian.h | 3382 ++++++------ src/mnemonics/singleton.h | 124 +- src/mnemonics/spanish.h | 3424 ++++++------ src/multisig/CMakeLists.txt | 1 + src/multisig/multisig.cpp | 6 +- src/net/CMakeLists.txt | 1 + src/net/epee_network_address_hack.cpp | 5 +- src/p2p/CMakeLists.txt | 1 + src/p2p/net_node.cpp | 26 +- src/p2p/net_node.h | 6 +- src/p2p/net_node.inl | 279 +- src/p2p/net_peerlist.cpp | 3 +- src/ringct/CMakeLists.txt | 2 + src/ringct/bulletproofs.cc | 89 +- src/ringct/fmt.h | 39 + src/ringct/multiexp.cc | 68 +- src/ringct/rctOps.cpp | 6 +- src/ringct/rctSigs.cpp | 69 +- src/ringct/rctTypes.cpp | 7 +- src/ringct/rctTypes.h | 2 - src/rpc/CMakeLists.txt | 4 + src/rpc/common/CMakeLists.txt | 1 + src/rpc/core_rpc_server.cpp | 158 +- src/rpc/core_rpc_server_commands_defs.h | 1 - src/rpc/http_client.cpp | 17 +- src/rpc/http_client.h | 1 + src/rpc/http_server.cpp | 57 +- src/rpc/lmq_server.cpp | 34 +- src/simplewallet/CMakeLists.txt | 1 + src/simplewallet/simplewallet.cpp | 234 +- src/simplewallet/simplewallet.h | 7 +- src/sqlitedb/CMakeLists.txt | 1 + src/sqlitedb/database.cpp | 19 +- src/sqlitedb/database.hpp | 5 +- src/wallet/CMakeLists.txt | 2 + src/wallet/api/CMakeLists.txt | 1 - src/wallet/api/address_book.cpp | 4 +- src/wallet/api/pending_transaction.cpp | 6 +- src/wallet/api/stake_unlock_result.cpp | 2 +- src/wallet/api/subaddress.cpp | 4 +- src/wallet/api/subaddress_account.cpp | 2 +- src/wallet/api/transaction_history.cpp | 2 +- src/wallet/api/unsigned_transaction.cpp | 4 +- src/wallet/api/utils.cpp | 2 +- src/wallet/api/wallet.cpp | 140 +- src/wallet/api/wallet_manager.cpp | 9 +- src/wallet/message_store.cpp | 19 +- src/wallet/message_store.h | 4 +- src/wallet/message_transporter.cpp | 10 +- src/wallet/node_rpc_proxy.cpp | 4 +- src/wallet/node_rpc_proxy.h | 4 +- src/wallet/ringdb.cpp | 24 +- src/wallet/wallet2.cpp | 861 ++- src/wallet/wallet2.h | 10 +- src/wallet/wallet_args.cpp | 49 +- src/wallet/wallet_args.h | 2 +- src/wallet/wallet_errors.h | 7 +- src/wallet/wallet_rpc_server.cpp | 109 +- src/wallet/wallet_rpc_server.h | 5 +- src/wallet/wallet_rpc_server_commands_defs.h | 5 +- src/wallet3/transaction_scanner.cpp | 6 +- tests/CMakeLists.txt | 1 - tests/block_weight/CMakeLists.txt | 1 + tests/core_proxy/CMakeLists.txt | 1 + tests/core_proxy/core_proxy.cpp | 31 +- tests/core_tests/CMakeLists.txt | 1 + tests/core_tests/block_validation.cpp | 4 +- tests/core_tests/bulletproofs.cpp | 8 +- tests/core_tests/chaingen.cpp | 7 +- tests/core_tests/chaingen.h | 122 +- tests/core_tests/chaingen_main.cpp | 29 +- tests/core_tests/multisig.cpp | 66 +- tests/core_tests/oxen_tests.cpp | 10 +- tests/core_tests/rct.cpp | 2 +- tests/core_tests/ring_signature_1.cpp | 7 +- tests/core_tests/wallet_tools.cpp | 14 +- tests/difficulty/CMakeLists.txt | 1 - .../transactions_flow_test.cpp | 32 +- tests/fuzz/CMakeLists.txt | 10 + tests/fuzz/fuzzer.cpp | 1 + tests/hash/CMakeLists.txt | 1 + tests/libwallet_api_tests/main.cpp | 11 +- tests/net_load_tests/CMakeLists.txt | 2 + tests/net_load_tests/clt.cpp | 57 +- tests/net_load_tests/net_load_tests.h | 9 +- tests/net_load_tests/srv.cpp | 23 +- tests/performance_tests/CMakeLists.txt | 1 + tests/performance_tests/main.cpp | 2 +- tests/performance_tests/performance_tests.h | 43 +- tests/performance_tests/timings.cc | 8 +- tests/performance_tests/timings.h | 4 +- tests/trezor/daemon.cpp | 26 +- tests/trezor/trezor_tests.cpp | 74 +- tests/unit_tests/CMakeLists.txt | 1 + tests/unit_tests/blockchain_db.cpp | 3 +- tests/unit_tests/logging.cpp | 87 +- tests/unit_tests/main.cpp | 13 +- tests/unit_tests/memwipe.cpp | 4 +- tests/unit_tests/multiexp.cpp | 1 + tests/unit_tests/multisig.cpp | 2 +- tests/unit_tests/output_selection.cpp | 8 +- tests/unit_tests/service_nodes_swarm.cpp | 2 +- tests/unit_tests/subaddress.cpp | 2 +- 249 files changed, 25249 insertions(+), 34357 deletions(-) delete mode 100644 contrib/epee/src/mlog.cpp delete mode 100644 external/easylogging++/CMakeLists.txt delete mode 100644 external/easylogging++/ea_config.h delete mode 100644 external/easylogging++/easylogging++.cc delete mode 100644 external/easylogging++/easylogging++.h delete mode 160000 external/fmt create mode 160000 external/oxen-logging delete mode 100644 src/common/perf_timer.cpp delete mode 100644 src/common/perf_timer.h create mode 100644 src/crypto/fmt.h create mode 100644 src/logging/CMakeLists.txt create mode 100644 src/logging/dev_sink.h create mode 100644 src/logging/oxen_logger.cpp create mode 100644 src/logging/oxen_logger.h create mode 100644 src/ringct/fmt.h diff --git a/.gitmodules b/.gitmodules index 43c0514d2..0051186c5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,9 +7,6 @@ [submodule "external/randomx"] path = external/randomx url = https://github.com/oxen-io/loki-randomXL -[submodule "external/loki-mq"] - path = external/oxen-mq - url = https://github.com/oxen-io/loki-mq.git [submodule "external/googletest"] path = external/googletest url = https://github.com/google/googletest.git @@ -25,9 +22,6 @@ [submodule "external/ghc-filesystem"] path = external/ghc-filesystem url = https://github.com/gulrak/filesystem.git -[submodule "external/fmt"] - path = external/fmt - url = https://github.com/fmtlib/fmt.git [submodule "external/Catch2"] path = external/Catch2 url = https://github.com/catchorg/Catch2 @@ -43,3 +37,9 @@ [submodule "external/oxen-encoding"] path = external/oxen-encoding url = https://github.com/oxen-io/oxen-encoding.git +[submodule "external/oxen-logging"] + path = external/oxen-logging + url = https://github.com/oxen-io/oxen-logging +[submodule "external/oxen-mq"] + path = external/oxen-mq + url = https://github.com/oxen-io/oxen-mq.git diff --git a/CMakeLists.txt b/CMakeLists.txt index f68c48895..01afd1238 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -299,7 +299,6 @@ if(NOT MANUAL_SUBMODULES) endif() check_submodule(external/uWebSockets uSockets) check_submodule(external/ghc-filesystem) - check_submodule(external/SQLiteCpp) endif() endif() @@ -491,7 +490,6 @@ if(NOT BUILD_STATIC_DEPS) endif() add_subdirectory(external) -target_compile_definitions(easylogging PRIVATE AUTO_INITIALIZE_EASYLOGGINGPP) if(USE_DEVICE_TREZOR) include(CheckTrezor) diff --git a/contrib/epee/include/epee/console_handler.h b/contrib/epee/include/epee/console_handler.h index c878dd5a5..9cfd43401 100644 --- a/contrib/epee/include/epee/console_handler.h +++ b/contrib/epee/include/epee/console_handler.h @@ -338,11 +338,9 @@ eof: color_prompt += "\001\033[0m\002"; m_stdin_reader.get_readline_buffer().set_prompt(color_prompt); #else - epee::set_console_color(epee::console_color_yellow, true); std::cout << prompt; if (' ' != prompt.back()) std::cout << ' '; - epee::reset_console_color(); std::cout.flush(); #endif } @@ -370,26 +368,22 @@ eof: break; if (m_stdin_reader.eos()) { - MGINFO("EOF on stdin, exiting"); std::cout << std::endl; break; } if (m_cancel) { - MDEBUG("Input cancelled"); cmd_handler(std::nullopt); m_cancel = false; continue; } if (!get_line_ret) { - MERROR("Failed to read line."); } string_tools::trim(command); - LOG_PRINT_L2("Read command: " << command); if (command.empty()) { continue; @@ -405,7 +399,6 @@ eof: } catch (const std::exception &ex) { - LOG_ERROR("Exception at [console_handler], what=" << ex.what()); } } if (exit_handler) diff --git a/contrib/epee/include/epee/misc_log_ex.h b/contrib/epee/include/epee/misc_log_ex.h index 467297946..6f8439b1d 100644 --- a/contrib/epee/include/epee/misc_log_ex.h +++ b/contrib/epee/include/epee/misc_log_ex.h @@ -31,84 +31,12 @@ #ifdef __cplusplus #include - -#include "easylogging++.h" +#include +#include #undef OXEN_DEFAULT_LOG_CATEGORY #define OXEN_DEFAULT_LOG_CATEGORY "default" -#define MAX_LOG_FILE_SIZE 104850000 // 100 MB - 7600 bytes -#define MAX_LOG_FILES 50 - -#define CLOG_ENABLED(level, cat) ELPP->vRegistry()->allowed(el::Level::level, cat) -#define LOG_ENABLED(level) CLOG_ENABLED(level, OXEN_DEFAULT_LOG_CATEGORY) - -#define MCLOG_TYPE(level, cat, type, x) do { \ - if (ELPP->vRegistry()->allowed(level, cat)) { \ - el::base::Writer(level, __FILE__, __LINE__, ELPP_FUNC, type).construct(cat) << x; \ - } \ - } while (0) - -#define MCLOG(level, cat, x) MCLOG_TYPE(level, cat, el::base::DispatchAction::NormalLog, x) -#define MCLOG_FILE(level, cat, x) MCLOG_TYPE(level, cat, el::base::DispatchAction::FileOnlyLog, x) - -#define MCFATAL(cat,x) MCLOG(el::Level::Fatal,cat, x) -#define MCERROR(cat,x) MCLOG(el::Level::Error,cat, x) -#define MCWARNING(cat,x) MCLOG(el::Level::Warning,cat, x) -#define MCINFO(cat,x) MCLOG(el::Level::Info,cat, x) -#define MCDEBUG(cat,x) MCLOG(el::Level::Debug,cat, x) -#define MCTRACE(cat,x) MCLOG(el::Level::Trace,cat, x) - -#define MCLOG_COLOR(level,cat,color,x) MCLOG(level,cat,"\033[1;" color "m" << x << "\033[0m") -#define MCLOG_RED(level,cat,x) MCLOG_COLOR(level,cat,"31",x) -#define MCLOG_GREEN(level,cat,x) MCLOG_COLOR(level,cat,"32",x) -#define MCLOG_YELLOW(level,cat,x) MCLOG_COLOR(level,cat,"33",x) -#define MCLOG_BLUE(level,cat,x) MCLOG_COLOR(level,cat,"34",x) -#define MCLOG_MAGENTA(level,cat,x) MCLOG_COLOR(level,cat,"35",x) -#define MCLOG_CYAN(level,cat,x) MCLOG_COLOR(level,cat,"36",x) - -#define MLOG_RED(level,x) MCLOG_RED(level,OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG_GREEN(level,x) MCLOG_GREEN(level,OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG_YELLOW(level,x) MCLOG_YELLOW(level,OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG_BLUE(level,x) MCLOG_BLUE(level,OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG_MAGENTA(level,x) MCLOG_MAGENTA(level,OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG_CYAN(level,x) MCLOG_CYAN(level,OXEN_DEFAULT_LOG_CATEGORY,x) - -#define MFATAL(x) MCFATAL(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MERROR(x) MCERROR(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MWARNING(x) MCWARNING(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MINFO(x) MCINFO(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MDEBUG(x) MCDEBUG(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MTRACE(x) MCTRACE(OXEN_DEFAULT_LOG_CATEGORY,x) -#define MLOG(level,x) MCLOG(level,OXEN_DEFAULT_LOG_CATEGORY,x) - -#define MGINFO(x) MCINFO("global",x) -#define MGINFO_RED(x) MCLOG_RED(el::Level::Info, "global",x) -#define MGINFO_GREEN(x) MCLOG_GREEN(el::Level::Info, "global",x) -#define MGINFO_YELLOW(x) MCLOG_YELLOW(el::Level::Info, "global",x) -#define MGINFO_BLUE(x) MCLOG_BLUE(el::Level::Info, "global",x) -#define MGINFO_MAGENTA(x) MCLOG_MAGENTA(el::Level::Info, "global",x) -#define MGINFO_CYAN(x) MCLOG_CYAN(el::Level::Info, "global",x) - -#define IFLOG(level, cat, type, init, x) \ - do { \ - if (ELPP->vRegistry()->allowed(level, cat)) { \ - init; \ - el::base::Writer(level, __FILE__, __LINE__, ELPP_FUNC, type).construct(cat) << x; \ - } \ - } while(0) -#define MIDEBUG(init, x) IFLOG(el::Level::Debug, OXEN_DEFAULT_LOG_CATEGORY, el::base::DispatchAction::NormalLog, init, x) - - -#define LOG_ERROR(x) MERROR(x) -#define LOG_PRINT_L0(x) MWARNING(x) -#define LOG_PRINT_L1(x) MINFO(x) -#define LOG_PRINT_L2(x) MDEBUG(x) -#define LOG_PRINT_L3(x) MTRACE(x) -#define LOG_PRINT_L4(x) MTRACE(x) - -#define MLOG_SET_THREAD_NAME(x) el::Helpers::setThreadName(x) - #ifndef LOCAL_ASSERT #include #if (defined _MSC_VER) @@ -119,13 +47,6 @@ #endif -std::string mlog_get_default_log_path(const char *default_filename); -void mlog_configure(const std::string &filename_base, bool console, const std::size_t max_log_file_size = MAX_LOG_FILE_SIZE, const std::size_t max_log_files = MAX_LOG_FILES); -void mlog_set_categories(const char *categories); -std::string mlog_get_categories(); -void mlog_set_log_level(int level); -void mlog_set_log(const char *log); - namespace epee { namespace debug @@ -146,12 +67,10 @@ namespace debug catch(const std::exception& ex) \ { \ (void)(ex); \ - LOG_ERROR("Exception at [" << location << "], what=" << ex.what()); \ return return_val; \ }\ catch(...)\ {\ - LOG_ERROR("Exception at [" << location << "], generic exception \"...\"");\ return return_val; \ } @@ -161,39 +80,15 @@ namespace debug #define CATCH_ENTRY_L3(lacation, return_val) CATCH_ENTRY(lacation, return_val) #define CATCH_ENTRY_L4(lacation, return_val) CATCH_ENTRY(lacation, return_val) - -#define ASSERT_MES_AND_THROW(message) {LOG_ERROR(message); std::stringstream ss; ss << message; throw std::runtime_error(ss.str());} +#define ASSERT_MES_AND_THROW(message) {std::stringstream ss; ss << message; throw std::runtime_error(ss.str());} #define CHECK_AND_ASSERT_THROW_MES(expr, message) do {if(!(expr)) ASSERT_MES_AND_THROW(message);} while(0) - #ifndef CHECK_AND_ASSERT #define CHECK_AND_ASSERT(expr, fail_ret_val) do{if(!(expr)){LOCAL_ASSERT(expr); return fail_ret_val;};}while(0) #endif #ifndef CHECK_AND_ASSERT_MES -#define CHECK_AND_ASSERT_MES(expr, fail_ret_val, message) do{if(!(expr)) {LOG_ERROR(message); return fail_ret_val;};}while(0) -#endif - -#ifndef CHECK_AND_NO_ASSERT_MES_L -#define CHECK_AND_NO_ASSERT_MES_L(expr, fail_ret_val, l, message) do{if(!(expr)) {LOG_PRINT_L##l(message); /*LOCAL_ASSERT(expr);*/ return fail_ret_val;};}while(0) -#endif - -#ifndef CHECK_AND_NO_ASSERT_MES -#define CHECK_AND_NO_ASSERT_MES(expr, fail_ret_val, message) CHECK_AND_NO_ASSERT_MES_L(expr, fail_ret_val, 0, message) -#endif - -#ifndef CHECK_AND_NO_ASSERT_MES_L1 -#define CHECK_AND_NO_ASSERT_MES_L1(expr, fail_ret_val, message) CHECK_AND_NO_ASSERT_MES_L(expr, fail_ret_val, 1, message) -#endif - - -#ifndef CHECK_AND_ASSERT_MES_NO_RET -#define CHECK_AND_ASSERT_MES_NO_RET(expr, message) do{if(!(expr)) {LOG_ERROR(message); return;};}while(0) -#endif - - -#ifndef CHECK_AND_ASSERT_MES2 -#define CHECK_AND_ASSERT_MES2(expr, message) do{if(!(expr)) {LOG_ERROR(message); };}while(0) +#define CHECK_AND_ASSERT_MES(expr, fail_ret_val, message) do{if(!(expr)) {return fail_ret_val;};}while(0) #endif enum console_colors @@ -209,9 +104,6 @@ enum console_colors }; bool is_stdout_a_tty(); -void set_console_color(int color, bool bright); -void reset_console_color(); - } extern "C" @@ -225,12 +117,6 @@ extern "C" #define ATTRIBUTE_PRINTF #endif -bool merror(const char *category, const char *format, ...) ATTRIBUTE_PRINTF; -bool mwarning(const char *category, const char *format, ...) ATTRIBUTE_PRINTF; -bool minfo(const char *category, const char *format, ...) ATTRIBUTE_PRINTF; -bool mdebug(const char *category, const char *format, ...) ATTRIBUTE_PRINTF; -bool mtrace(const char *category, const char *format, ...) ATTRIBUTE_PRINTF; - #ifdef __cplusplus } diff --git a/contrib/epee/include/epee/net/abstract_tcp_server2.inl b/contrib/epee/include/epee/net/abstract_tcp_server2.inl index 1314155a2..d68e3d667 100644 --- a/contrib/epee/include/epee/net/abstract_tcp_server2.inl +++ b/contrib/epee/include/epee/net/abstract_tcp_server2.inl @@ -51,9 +51,6 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net" - #define AGGRESSIVE_TIMEOUT_THRESHOLD 120 // sockets #define NEW_CONNECTION_TIMEOUT_LOCAL 1200000 // 2 minutes #define NEW_CONNECTION_TIMEOUT_REMOTE 10000 // 10 seconds @@ -103,7 +100,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) m_local(false), m_ready_to_close(false) { - MDEBUG("test, connection constructor set m_connection_type="< @@ -141,9 +135,10 @@ PRAGMA_WARNING_DISABLE_VS(4355) boost::system::error_code ec; auto remote_ep = socket().remote_endpoint(ec); - CHECK_AND_NO_ASSERT_MES(!ec, false, "Failed to get remote endpoint: " << ec.message() << ':' << ec.value()); - CHECK_AND_NO_ASSERT_MES(remote_ep.address().is_v4() || remote_ep.address().is_v6(), false, "only IPv4 and IPv6 supported here"); - + if (ec) + throw std::runtime_error(std::string("Failed to get remote endpoint: ") + ec.message() + ":" + std::to_string(ec.value())); + if (!remote_ep.address().is_v4() && !remote_ep.address().is_v6()) + throw std::runtime_error("Only IPv4 and IPv6 are supported here"); if (remote_ep.address().is_v4()) { const unsigned long ip_ = boost::asio::detail::socket_ops::host_to_network_long(remote_ep.address().to_v4().to_ulong()); @@ -176,17 +171,8 @@ PRAGMA_WARNING_DISABLE_VS(4355) context = t_connection_context{}; context.set_details(random_uuid, std::move(real_remote), is_income); - boost::system::error_code ec; - auto local_ep = socket().local_endpoint(ec); - CHECK_AND_NO_ASSERT_MES(!ec, false, "Failed to get local endpoint: " << ec.message() << ':' << ec.value()); - - MTRACE("[sock " << socket_.native_handle() << "] new connection from " << print_connection_context_short(context) << - " to " << local_ep.address().to_string() << ':' << local_ep.port() << - ", total sockets objects " << get_state().sock_count); - if(static_cast(get_state()).pfilter && !static_cast(get_state()).pfilter->is_remote_host_allowed(context.m_remote_address)) { - MDEBUG("[sock " << socket().native_handle() << "] host denied " << context.m_remote_address.host_str() << ", shutdowning connection"); close(); return false; } @@ -211,7 +197,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) boost::asio::detail::socket_option::integer< IPPROTO_IP, IP_TOS > optionTos( tos ); socket().set_option( optionTos ); - //MDEBUG("Set ToS flag to " << tos); #endif boost::asio::ip::tcp::no_delay noDelayOption(false); @@ -226,7 +211,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) bool connection::request_callback() { TRY_ENTRY(); - MDEBUG("[" << print_connection_context_short(context) << "] request_callback"); // Use safe_shared_from_this, because of this is public method and it can be called on the object being deleted auto self = safe_shared_from_this(); if(!self) @@ -252,9 +236,7 @@ PRAGMA_WARNING_DISABLE_VS(4355) auto self = safe_shared_from_this(); if(!self) return false; - //MTRACE("[sock " << socket().native_handle() << "] add_ref, m_peer_number=" << mI->m_peer_number); std::lock_guard lock{self->m_self_refs_lock}; - //MTRACE("[sock " << socket().native_handle() << "] add_ref 2, m_peer_number=" << mI->m_peer_number); if(m_was_shutdown) return false; ++m_reference_count; @@ -268,7 +250,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) { TRY_ENTRY(); std::shared_ptr > back_connection_copy; - LOG_TRACE_CC(context, "[sock " << socket().native_handle() << "] release"); std::lock_guard lock{m_self_refs_lock}; CHECK_AND_ASSERT_MES(m_reference_count, false, "[sock " << socket().native_handle() << "] m_reference_count already at 0 at connection::release() call"); // is this the last reference? @@ -284,7 +265,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) void connection::call_back_starter() { TRY_ENTRY(); - MDEBUG("[" << print_connection_context_short(context) << "] fired_callback"); m_protocol_handler.handle_qued_callback(); CATCH_ENTRY_L0("connection::call_back_starter()", void()); } @@ -306,9 +286,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) address = endpoint.address().to_string(); port = boost::lexical_cast(endpoint.port()); } - MDEBUG(" connection type " << to_string( m_connection_type ) << " " - << socket().local_endpoint().address().to_string() << ":" << socket().local_endpoint().port() - << " <--> " << context.m_remote_address.str() << " (via " << address << ":" << port << ")"); } //--------------------------------------------------------------------------------- template @@ -316,7 +293,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) std::size_t bytes_transferred) { TRY_ENTRY(); - //MINFO("[sock " << socket().native_handle() << "] Async read calledback."); if (!e) { @@ -354,7 +330,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) } while(delay > 0); } // any form of sleeping - //MINFO("[sock " << socket().native_handle() << "] RECV " << bytes_transferred); logger_handle_net_read(bytes_transferred); context.m_last_recv = std::chrono::steady_clock::now(); context.m_recv_cnt += bytes_transferred; @@ -362,7 +337,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) bool recv_res = m_protocol_handler.handle_recv(buffer_.data(), bytes_transferred); if(!recv_res) { - //MINFO("[sock " << socket().native_handle() << "] protocol_want_close"); //some error in protocol, protocol handler ask to close connection m_want_close_connection = true; bool do_shutdown = false; @@ -381,19 +355,15 @@ PRAGMA_WARNING_DISABLE_VS(4355) boost::bind(&connection::handle_read, connection::shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); - //MINFO("[sock " << socket().native_handle() << "]Async read requested."); } }else { - MTRACE("[sock " << socket().native_handle() << "] Some not success at read: " << e.message() << ':' << e.value()); if(e.value() != 2) { - MTRACE("[sock " << socket().native_handle() << "] Some problems at read: " << e.message() << ':' << e.value()); shutdown(); } else { - MTRACE("[sock " << socket().native_handle() << "] peer closed connection"); bool do_shutdown = false; { std::lock_guard lock{m_send_que_lock}; @@ -461,21 +431,14 @@ PRAGMA_WARNING_DISABLE_VS(4355) { // LOCK: chunking std::lock_guard send_guard{m_chunking_lock}; - MDEBUG("do_send() will SPLIT into small chunks, from packet="<{250, 299}(rng); - MDEBUG("Sleeping because QUEUE is FULL, in " << __FUNCTION__ << " for " << ms << " ms before packet_size="< retry_limit) { - MWARNING("send que size is more than ABSTRACT_SERVER_SEND_QUE_MAX_COUNT(" << ABSTRACT_SERVER_SEND_QUE_MAX_COUNT << "), shutting down connection"); shutdown(); return false; } @@ -559,22 +513,18 @@ PRAGMA_WARNING_DISABLE_VS(4355) if(m_send_que.size() > 1) { // active operation should be in progress, nothing to do, just wait last operation callback auto size_now = m_send_que.back().size(); - MDEBUG("do_send_chunk() NOW just queues: packet="<::handle_write, self, _1, _2) ) ); - //MTRACE("(chunk): " << size_now); - //logger_handle_net_write(size_now); - //MINFO("[sock " << socket().native_handle() << "] Async send requested " << m_send_que.front().size()); } //do_send_handler_stop( ptr , cb ); // empty function @@ -629,10 +576,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) std::lock_guard lock{hosts_mutex}; static std::map hosts; unsigned int &val = hosts[host]; - if (delta > 0) - MTRACE("New connection from host " << host << ": " << val); - else if (delta < 0) - MTRACE("Closed connection from host " << host << ": " << val); CHECK_AND_ASSERT_THROW_MES(delta >= 0 || val >= (unsigned)-delta, "Count would go negative"); CHECK_AND_ASSERT_THROW_MES(delta <= 0 || val <= std::numeric_limits::max() - (unsigned)delta, "Count would wrap"); val += delta; @@ -644,19 +587,15 @@ PRAGMA_WARNING_DISABLE_VS(4355) { if (ms < 0s) { - MWARNING("Ignoring negative timeout " << ms.count()); return; } - MTRACE((add ? "Adding" : "Setting") << " " << ms.count() << "ms expiry"); auto self = safe_shared_from_this(); if(!self) { - MERROR("Resetting timer on a dead object"); return; } if (m_was_shutdown) { - MERROR("Setting timer on a shut down object"); return; } if (add) @@ -670,7 +609,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) { if(ec == boost::asio::error::operation_aborted) return; - MDEBUG(context << "connection timeout, closing"); self->close(); }); } @@ -703,7 +641,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) auto self = safe_shared_from_this(); if(!self) return false; - //MINFO("[sock " << socket().native_handle() << "] Que Shutdown called."); m_timer.cancel(); size_t send_que_size = 0; { @@ -739,11 +676,9 @@ PRAGMA_WARNING_DISABLE_VS(4355) void connection::handle_write(const boost::system::error_code& e, size_t cb) { TRY_ENTRY(); - LOG_TRACE_CC(context, "[sock " << socket().native_handle() << "] Async send calledback " << cb); if (e) { - MDEBUG("[sock " << socket().native_handle() << "] Some problems at write: " << e.message() << ':' << e.value()); shutdown(); return; } @@ -758,7 +693,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) std::unique_lock lock{m_send_que_lock}; if(m_send_que.empty()) { - MERROR("[sock " << socket().native_handle() << "] m_send_que.size() == 0 at handle_write!"); return; } @@ -774,7 +708,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) //have more data to send reset_timer(get_default_timeout(), false); auto size_now = m_send_que.front().size(); - MDEBUG("handle_write() NOW SENDS: packet="<::handle_write, connection::shared_from_this(), _1, _2) ) ); - //MTRACE("(normal)" << size_now); } lock.unlock(); @@ -800,10 +732,8 @@ PRAGMA_WARNING_DISABLE_VS(4355) void connection::setRpcStation() { m_connection_type = e_connection_type_RPC; - MDEBUG("set m_connection_type = RPC "); } - template bool connection::speed_limit_is_enabled() const { return m_connection_type != e_connection_type_RPC ; @@ -893,7 +823,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) acceptor_.listen(); boost::asio::ip::tcp::endpoint binded_endpoint = acceptor_.local_endpoint(); m_port = binded_endpoint.port(); - MDEBUG("start accept (IPv4)"); new_connection_.reset(new connection(io_service_, m_state, m_connection_type)); acceptor_.async_accept(new_connection_->socket(), boost::bind(&boosted_tcp_server::handle_accept_ipv4, this, @@ -906,7 +835,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) if (ipv4_failed != "") { - MERROR("Failed to bind IPv4: " << ipv4_failed); if (require_ipv4) { throw std::runtime_error("Failed to bind IPv4 (set to required)"); @@ -930,7 +858,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) acceptor_ipv6.listen(); boost::asio::ip::tcp::endpoint binded_endpoint = acceptor_ipv6.local_endpoint(); m_port_ipv6 = binded_endpoint.port(); - MDEBUG("start accept (IPv6)"); new_connection_ipv6.reset(new connection(io_service_, m_state, m_connection_type)); acceptor_ipv6.async_accept(new_connection_ipv6->socket(), boost::bind(&boosted_tcp_server::handle_accept_ipv6, this, @@ -944,7 +871,6 @@ PRAGMA_WARNING_DISABLE_VS(4355) if (use_ipv6 && ipv6_failed != "") { - MERROR("Failed to bind IPv6: " << ipv6_failed); if (ipv4_failed != "") { throw std::runtime_error("Failed to bind IPv4 and IPv6"); @@ -955,12 +881,12 @@ PRAGMA_WARNING_DISABLE_VS(4355) } catch (const std::exception &e) { - MFATAL("Error starting server: " << e.what()); + throw std::runtime_error(std::string("Error starting server: {}") + e.what()); return false; } catch (...) { - MFATAL("Error starting server"); + throw std::runtime_error("Error starting server"); return false; } } @@ -975,12 +901,10 @@ DISABLE_GCC_WARNING(maybe-uninitialized) uint32_t p_ipv6 = 0; if (port.size() && !string_tools::get_xtype_from_string(p, port)) { - MERROR("Failed to convert port no = " << port); return false; } if (port_ipv6.size() && !string_tools::get_xtype_from_string(p_ipv6, port_ipv6)) { - MERROR("Failed to convert port no = " << port_ipv6); return false; } return this->init_server(p, address, p_ipv6, address_ipv6, use_ipv6, require_ipv4); @@ -991,11 +915,6 @@ POP_WARNINGS bool boosted_tcp_server::worker_thread() { TRY_ENTRY(); - uint32_t local_thr_index = m_thread_index++; - std::string thread_name = std::string("[") + m_thread_name_prefix; - thread_name += std::to_string(local_thr_index) + "]"; - MLOG_SET_THREAD_NAME(thread_name); - // MDEBUG("Thread name: " << m_thread_name_prefix); while(!m_stop_signal_sent) { try @@ -1003,16 +922,10 @@ POP_WARNINGS io_service_.run(); return true; } - catch(const std::exception& ex) - { - MERROR("Exception at server worker thread, what=" << ex.what()); - } catch(...) { - MERROR("Exception at server worker thread, unknown execption"); } } - //MINFO("Worker thread finished"); return true; CATCH_ENTRY_L0("boosted_tcp_server::worker_thread", false); } @@ -1024,7 +937,6 @@ POP_WARNINGS auto it = server_type_map.find(m_thread_name_prefix); if (it==server_type_map.end()) throw std::runtime_error("Unknown prefix/server type:" + std::string(prefix_name)); auto connection_type = it->second; // the value of type - MINFO("Set server type to: " << connection_type << " from name: " << m_thread_name_prefix << ", prefix_name = " << prefix_name); } //--------------------------------------------------------------------------------- template @@ -1040,7 +952,6 @@ POP_WARNINGS TRY_ENTRY(); m_threads_count = threads_count; m_main_thread_id = std::this_thread::get_id(); - MLOG_SET_THREAD_NAME("[SRV_MAIN]"); while(!m_stop_signal_sent) { @@ -1050,36 +961,28 @@ POP_WARNINGS for (std::size_t i = 0; i < threads_count; ++i) { m_threads.emplace_back([this] { worker_thread(); }); - MDEBUG("Run server thread name: " << m_thread_name_prefix); } } // Wait for all threads in the pool to exit. if (wait) { - MDEBUG("JOINING all threads"); for (auto& th: m_threads) th.join(); - MDEBUG("JOINING all threads - almost"); m_threads.clear(); - MDEBUG("JOINING all threads - DONE"); } else { - MDEBUG("Reiniting OK."); return true; } if(wait && !m_stop_signal_sent) { //some problems with the listening socket ?.. - MDEBUG("Net service stopped without stop request, restarting..."); if(!this->init_server(m_port, m_address, m_port_ipv6, m_address_ipv6, m_use_ipv6, m_require_ipv4)) { - MDEBUG("Reiniting service failed, exit."); return false; - }else - { - MDEBUG("Reiniting OK."); + //}else + //{ } } } @@ -1145,8 +1048,6 @@ POP_WARNINGS template void boosted_tcp_server::handle_accept(const boost::system::error_code& e, bool ipv6) { - MDEBUG("handle_accept"); - boost::asio::ip::tcp::acceptor* current_acceptor = &acceptor_; connection_ptr* current_new_connection = &new_connection_; auto accept_function_pointer = &boosted_tcp_server::handle_accept_ipv4; @@ -1162,7 +1063,6 @@ POP_WARNINGS if (!e) { if (m_connection_type == e_connection_type_RPC) { - MDEBUG("New server for RPC connections"); (*current_new_connection)->setRpcStation(); // hopefully this is not needed actually } connection_ptr conn(std::move((*current_new_connection))); @@ -1187,19 +1087,13 @@ POP_WARNINGS conn->save_dbg_log(); return; } - else - { - MERROR("Error in boosted_tcp_server::handle_accept: " << e); - } } catch (const std::exception &e) { - MERROR("Exception in boosted_tcp_server::handle_accept: " << e.what()); } // error path, if e or exception assert(m_state != nullptr); // always set in constructor - MERROR("Some problems at accept: " << e.message() << ", connections_count = " << m_state->sock_count); std::this_thread::sleep_for(100ms); (*current_new_connection).reset(new connection(io_service_, m_state, m_connection_type)); current_acceptor->async_accept((*current_new_connection)->socket(), @@ -1220,10 +1114,6 @@ POP_WARNINGS return true; } } - else - { - MWARNING(out << " was not added, socket/io_service mismatch"); - } return false; } //--------------------------------------------------------------------------------- @@ -1240,7 +1130,6 @@ POP_WARNINGS sock_.bind(local_endpoint, ec); if (ec) { - MERROR("Error binding to " << bind_ip << ": " << ec.message()); if (sock_.is_open()) sock_.close(); return CONNECT_FAILURE; @@ -1284,7 +1173,6 @@ POP_WARNINGS { //timeout sock_.close(); - MTRACE("Failed to connect to " << adr << ":" << port << ", because of timeout (" << conn_timeout << ")"); return CONNECT_FAILURE; } } @@ -1292,14 +1180,11 @@ POP_WARNINGS if (ec || !sock_.is_open()) { - MTRACE("Some problems at connect, message: " << ec.message()); if (sock_.is_open()) sock_.close(); return CONNECT_FAILURE; } - MTRACE("Connected success to " << adr << ':' << port); - return CONNECT_SUCCESS; CATCH_ENTRY_L0("boosted_tcp_server::try_connect", CONNECT_FAILURE); @@ -1313,7 +1198,6 @@ POP_WARNINGS connection_ptr new_connection_l(new connection(io_service_, m_state, m_connection_type) ); connections_mutex.lock(); connections_.insert(new_connection_l); - MDEBUG("connections_ size now " << connections_.size()); connections_mutex.unlock(); auto scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ std::lock_guard lock{connections_mutex}; connections_.erase(new_connection_l); }); boost::asio::ip::tcp::socket& sock_ = new_connection_l->socket(); @@ -1350,13 +1234,11 @@ POP_WARNINGS { if (!m_use_ipv6) { - MERROR("Failed to resolve " << adr); return false; } else { try_ipv6 = true; - MINFO("Resolving address as IPv4 failed, trying IPv6"); } } else @@ -1372,7 +1254,6 @@ POP_WARNINGS if(iterator == end) { - MERROR("Failed to resolve " << adr); return false; } else @@ -1390,9 +1271,6 @@ POP_WARNINGS } - MDEBUG("Trying to connect to " << adr << ":" << port << ", bind_ip = " << bind_ip_to_use); - - //boost::asio::ip::tcp::endpoint remote_endpoint(boost::asio::ip::address::from_string(addr.c_str()), port); boost::asio::ip::tcp::endpoint remote_endpoint(*iterator); auto try_connect_result = try_connect(new_connection_l, adr, port, sock_, remote_endpoint, bind_ip_to_use, conn_timeout); @@ -1412,7 +1290,6 @@ POP_WARNINGS else { assert(m_state != nullptr); // always set in constructor - MERROR("[sock " << new_connection_l->socket().native_handle() << "] Failed to start connection, connections_count = " << m_state->sock_count); } new_connection_l->save_dbg_log(); @@ -1429,7 +1306,6 @@ POP_WARNINGS connection_ptr new_connection_l(new connection(io_service_, m_state, m_connection_type) ); connections_mutex.lock(); connections_.insert(new_connection_l); - MDEBUG("connections_ size now " << connections_.size()); connections_mutex.unlock(); auto scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ std::lock_guard lock{connections_mutex}; connections_.erase(new_connection_l); }); boost::asio::ip::tcp::socket& sock_ = new_connection_l->socket(); @@ -1465,13 +1341,8 @@ POP_WARNINGS { if (!try_ipv6) { - MERROR("Failed to resolve " << adr); return false; } - else - { - MINFO("Resolving address as IPv4 failed, trying IPv6"); - } } if (try_ipv6) @@ -1482,7 +1353,6 @@ POP_WARNINGS if(iterator == end) { - MERROR("Failed to resolve " << adr); return false; } } @@ -1498,7 +1368,6 @@ POP_WARNINGS sock_.bind(local_endpoint, ec); if (ec) { - MERROR("Error binding to " << bind_ip << ": " << ec.message()); if (sock_.is_open()) sock_.close(); return false; @@ -1512,7 +1381,6 @@ POP_WARNINGS { if(error != boost::asio::error::operation_aborted) { - MTRACE("Failed to connect to " << adr << ':' << port << ", because of timeout (" << conn_timeout << ")"); new_connection_l->socket().close(); } }); @@ -1520,8 +1388,6 @@ POP_WARNINGS sock_.async_connect(remote_endpoint, [=](const boost::system::error_code& ec_) { t_connection_context conn_context{}; - boost::system::error_code ignored_ec; - boost::asio::ip::tcp::socket::endpoint_type lep = new_connection_l->socket().local_endpoint(ignored_ec); if(!ec_) {//success if(!sh_deadline->cancel()) @@ -1529,9 +1395,6 @@ POP_WARNINGS cb(conn_context, boost::asio::error::operation_aborted);//this mean that deadline timer already queued callback with cancel operation, rare situation }else { - MTRACE("[sock " << new_connection_l->socket().native_handle() << "] Connected success to " << adr << ':' << port << - " from " << lep.address().to_string() << ':' << lep.port()); - // start adds the connection to the config object's list, so we don't need to have it locally anymore connections_mutex.lock(); connections_.erase(new_connection_l); @@ -1544,14 +1407,11 @@ POP_WARNINGS } else { - MTRACE("[sock " << new_connection_l->socket().native_handle() << "] Failed to start connection to " << adr << ':' << port); cb(conn_context, boost::asio::error::fault); } } }else { - MTRACE("[sock " << new_connection_l->socket().native_handle() << "] Failed to connect to " << adr << ':' << port << - " from " << lep.address().to_string() << ':' << lep.port() << ": " << ec_.message() << ':' << ec_.value()); cb(conn_context, ec_); } }); diff --git a/contrib/epee/include/epee/net/buffer.h b/contrib/epee/include/epee/net/buffer.h index 0ae10960e..41d68e740 100644 --- a/contrib/epee/include/epee/net/buffer.h +++ b/contrib/epee/include/epee/net/buffer.h @@ -32,10 +32,6 @@ #include "../misc_log_ex.h" #include "../span.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net.buffer" - -//#define NET_BUFFER_LOG(x) MDEBUG(x) #define NET_BUFFER_LOG(x) ((void)0) namespace epee diff --git a/contrib/epee/include/epee/net/levin_protocol_handler.h b/contrib/epee/include/epee/net/levin_protocol_handler.h index 3cce0eca7..cf5df7c76 100644 --- a/contrib/epee/include/epee/net/levin_protocol_handler.h +++ b/contrib/epee/include/epee/net/levin_protocol_handler.h @@ -33,9 +33,6 @@ #include "levin_base.h" #include "../int-util.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net" - namespace epee { namespace levin @@ -91,7 +88,6 @@ namespace levin { if(!m_config.m_pcommands_handler) { - LOG_ERROR_CC(m_conn_context, "Command handler not set!"); return false; } m_cach_in_buffer.append((const char*)ptr, cb); @@ -106,7 +102,6 @@ namespace levin { if(m_cach_in_buffer.size() >= sizeof(uint64_t) && *((uint64_t*)m_cach_in_buffer.data()) != SWAP64LE(LEVIN_SIGNATURE)) { - LOG_ERROR_CC(m_conn_context, "Signature mismatch on accepted connection"); return false; } is_continue = false; @@ -126,7 +121,6 @@ namespace levin #endif if(LEVIN_SIGNATURE != phead.m_signature) { - LOG_ERROR_CC(m_conn_context, "Signature mismatch on accepted connection"); return false; } m_current_head = phead; @@ -169,7 +163,6 @@ namespace levin m_state = conn_state_reading_head; break; default: - LOG_ERROR_CC(m_conn_context, "Undefined state in levin_server_impl::connection_handler, m_state=" << m_state); return false; } } diff --git a/contrib/epee/include/epee/net/levin_protocol_handler_async.h b/contrib/epee/include/epee/net/levin_protocol_handler_async.h index bd684b886..313c9e4c9 100644 --- a/contrib/epee/include/epee/net/levin_protocol_handler_async.h +++ b/contrib/epee/include/epee/net/levin_protocol_handler_async.h @@ -32,6 +32,7 @@ #include #include +#include #include "levin_base.h" #include "buffer.h" @@ -41,9 +42,6 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net" - #ifndef MIN_BYTES_WANTED #define MIN_BYTES_WANTED 512 #endif @@ -135,11 +133,6 @@ class async_protocol_handler if(!m_pservice_endpoint->do_send(shared_sv{std::move(data)})) return false; - MDEBUG(m_connection_context << "LEVIN_PACKET_SENT. [len=" << head.m_cb - << ", flags" << head.m_flags - << ", r?=" << head.m_have_to_return_data - <<", cmd = " << head.m_command - << ", ver=" << head.m_protocol_version); return true; } @@ -194,13 +187,11 @@ public: { if(m_con.start_outer_call()) { - MDEBUG(con.get_context_ref() << "anvoke_handler, timeout: " << timeout.count()); m_timer.expires_from_now(std::chrono::milliseconds(timeout)); m_timer.async_wait([&con, command, cb, timeout](const boost::system::error_code& ec) { if(ec == boost::asio::error::operation_aborted) return; - MINFO(con.get_context_ref() << "Timeout on invoke operation happened, command: " << command << " timeout: " << timeout.count()); epee::span fake; cb(LEVIN_ERROR_CONNECTION_TIMEDOUT, fake, con.get_context_ref()); con.close(); @@ -263,7 +254,6 @@ public: { if(ec == boost::asio::error::operation_aborted) return; - MINFO(con.get_context_ref() << "Timeout on invoke operation happened, command: " << command << " timeout: " << timeout.count()); epee::span fake; cb(LEVIN_ERROR_CONNECTION_TIMEDOUT, fake, con.get_context_ref()); con.close(); @@ -282,7 +272,6 @@ public: std::lock_guard lock{m_invoke_response_handlers_lock}; if (m_protocol_released) { - MERROR("Adding response handler to a released object"); return false; } std::shared_ptr handler(std::make_shared>(cb, timeout, con, command)); @@ -325,20 +314,14 @@ public: { std::this_thread::sleep_for(100ms); } - CHECK_AND_ASSERT_MES_NO_RET(0 == m_wait_count, "Failed to wait for operation completion. m_wait_count = " << m_wait_count); - - MTRACE(m_connection_context << "~async_protocol_handler()"); - } catch (...) { /* ignore */ } } bool start_outer_call() { - MTRACE(m_connection_context << "[levin_protocol] -->> start_outer_call"); if(!m_pservice_endpoint->add_ref()) { - MERROR(m_connection_context << "[levin_protocol] -->> start_outer_call failed"); return false; } m_wait_count++; @@ -346,7 +329,6 @@ public: } bool finish_outer_call() { - MTRACE(m_connection_context << "[levin_protocol] <<-- finish_outer_call"); m_wait_count--; m_pservice_endpoint->release(); return true; @@ -403,7 +385,6 @@ public: if(!m_config.m_pcommands_handler) { - MERROR(m_connection_context << "Commands handler not set!"); return false; } @@ -414,9 +395,6 @@ public: // flipped to subtraction; prevent overflow since m_max_packet_size is variable and public if(cb > m_config.m_max_packet_size - m_cache_in_buffer.size() - m_fragment_buffer.size()) { - MWARNING(m_connection_context << "Maximum packet size exceed!, m_max_packet_size = " << m_config.m_max_packet_size - << ", packet received " << m_cache_in_buffer.size() + cb - << ", connection will be closed."); return false; } @@ -439,7 +417,6 @@ public: //async call scenario std::shared_ptr response_handler = m_invoke_response_handlers.front(); response_handler->reset_timer(); - MDEBUG(m_connection_context << "LEVIN_PACKET partial msg received. len=" << cb); } } break; @@ -467,7 +444,6 @@ public: if (m_fragment_buffer.size() < sizeof(bucket_head2)) { - MERROR(m_connection_context << "Fragmented data too small for levin header"); return false; } @@ -479,12 +455,6 @@ public: bool is_response = (m_oponent_protocol_ver == LEVIN_PROTOCOL_VER_1 && m_current_head.m_flags&LEVIN_PACKET_RESPONSE); - MDEBUG(m_connection_context << "LEVIN_PACKET_RECEIVED. [len=" << m_current_head.m_cb - << ", flags" << m_current_head.m_flags - << ", r?=" << m_current_head.m_have_to_return_data - <<", cmd = " << m_current_head.m_command - << ", v=" << m_current_head.m_protocol_version); - if(is_response) {//response to some invoke @@ -507,7 +477,6 @@ public: //use sync call scenario if(m_wait_count == 0 && m_close_called == 0) { - MERROR(m_connection_context << "no active invoke when response came, wtf?"); return false; }else { @@ -533,12 +502,6 @@ public: if(!m_pservice_endpoint->do_send(shared_sv{std::move(return_buff)})) return false; - - MDEBUG(m_connection_context << "LEVIN_PACKET_SENT. [len=" << head.m_cb - << ", flags" << head.m_flags - << ", r?=" << head.m_have_to_return_data - <<", cmd = " << head.m_command - << ", ver=" << head.m_protocol_version); } else m_config.m_pcommands_handler->notify(m_current_head.m_command, buff_to_invoke, m_connection_context); @@ -557,7 +520,6 @@ public: { if(m_cache_in_buffer.size() >= sizeof(uint64_t) && *((uint64_t*)m_cache_in_buffer.span(8).data()) != SWAP64LE(LEVIN_SIGNATURE)) { - MWARNING(m_connection_context << "Signature mismatch, connection will be closed"); return false; } is_continue = false; @@ -577,7 +539,6 @@ public: #endif if(LEVIN_SIGNATURE != phead.m_signature) { - LOG_ERROR_CC(m_connection_context, "Signature mismatch, connection will be closed"); return false; } m_current_head = phead; @@ -587,15 +548,11 @@ public: m_oponent_protocol_ver = m_current_head.m_protocol_version; if(m_current_head.m_cb > m_config.m_max_packet_size) { - LOG_ERROR_CC(m_connection_context, "Maximum packet size exceed!, m_max_packet_size = " << m_config.m_max_packet_size - << ", packet header received " << m_current_head.m_cb - << ", connection will be closed."); return false; } } break; default: - LOG_ERROR_CC(m_connection_context, "Undefined state in levin_server_impl::connection_handler, m_state=" << m_state); return false; } } @@ -645,7 +602,6 @@ public: if(!send_message(command, in_buff, LEVIN_PACKET_REQUEST, true)) { - LOG_ERROR_CC(m_connection_context, "Failed to do_send"); err_code = LEVIN_ERROR_CONNECTION; break; } @@ -686,7 +642,6 @@ public: if (!send_message(command, in_buff, LEVIN_PACKET_REQUEST, true)) { - LOG_ERROR_CC(m_connection_context, "Failed to send request"); return LEVIN_ERROR_CONNECTION; } @@ -702,7 +657,6 @@ public: } if (std::chrono::steady_clock::now() > start + m_config.m_invoke_timeout) { - MWARNING(m_connection_context << "invoke timeout (" << m_config.m_invoke_timeout.count() << "), closing connection "); close(); return LEVIN_ERROR_CONNECTION_TIMEDOUT; } @@ -735,7 +689,6 @@ public: if (!send_message(command, in_buff, LEVIN_PACKET_REQUEST, false)) { - LOG_ERROR_CC(m_connection_context, "Failed to send notify message"); return -1; } @@ -759,11 +712,9 @@ public: const std::size_t length = message.view.size(); if (!m_pservice_endpoint->do_send(std::move(message))) { - LOG_ERROR_CC(m_connection_context, "Failed to send message, dropping it"); return -1; } - MDEBUG(m_connection_context << "LEVIN_PACKET_SENT. [len=" << (length - sizeof(bucket_head2)) << ", r?=0]"); return 1; } //------------------------------------------------------------------------------------------ @@ -809,7 +760,6 @@ void async_protocol_handler_config::delete_connections(siz } catch (const std::out_of_range &e) { - MWARNING("Connection not found in m_connects, continuing"); } --count; } diff --git a/contrib/epee/include/epee/net/net_utils_base.h b/contrib/epee/include/epee/net/net_utils_base.h index 07985a859..b7a38c78d 100644 --- a/contrib/epee/include/epee/net/net_utils_base.h +++ b/contrib/epee/include/epee/net/net_utils_base.h @@ -437,36 +437,15 @@ namespace net_utils //some helpers - - std::string print_connection_context(const connection_context_base& ctx); std::string print_connection_context_short(const connection_context_base& ctx); -inline MAKE_LOGGABLE(connection_context_base, ct, os) -{ - os << "[" << epee::net_utils::print_connection_context_short(ct) << "] "; - return os; -} + inline std::ostream& operator<<(std::ostream& os, const connection_context_base& ct) + { + os << "[" << epee::net_utils::print_connection_context_short(ct) << "] "; + return os; + } -#define LOG_ERROR_CC(ct, message) MERROR(ct << message) -#define LOG_WARNING_CC(ct, message) MWARNING(ct << message) -#define LOG_INFO_CC(ct, message) MINFO(ct << message) -#define LOG_DEBUG_CC(ct, message) MDEBUG(ct << message) -#define LOG_TRACE_CC(ct, message) MTRACE(ct << message) -#define LOG_CC(level, ct, message) MLOG(level, ct << message) - -#define LOG_PRINT_CC_L0(ct, message) LOG_PRINT_L0(ct << message) -#define LOG_PRINT_CC_L1(ct, message) LOG_PRINT_L1(ct << message) -#define LOG_PRINT_CC_L2(ct, message) LOG_PRINT_L2(ct << message) -#define LOG_PRINT_CC_L3(ct, message) LOG_PRINT_L3(ct << message) -#define LOG_PRINT_CC_L4(ct, message) LOG_PRINT_L4(ct << message) - -#define LOG_PRINT_CCONTEXT_L0(message) LOG_PRINT_CC_L0(context, message) -#define LOG_PRINT_CCONTEXT_L1(message) LOG_PRINT_CC_L1(context, message) -#define LOG_PRINT_CCONTEXT_L2(message) LOG_PRINT_CC_L2(context, message) -#define LOG_PRINT_CCONTEXT_L3(message) LOG_PRINT_CC_L3(context, message) -#define LOG_ERROR_CCONTEXT(message) LOG_ERROR_CC(context, message) - #define CHECK_AND_ASSERT_MES_CC(condition, return_val, err_message) CHECK_AND_ASSERT_MES(condition, return_val, "[" << epee::net_utils::print_connection_context_short(context) << "]" << err_message) } diff --git a/contrib/epee/include/epee/serialization/keyvalue_serialization.h b/contrib/epee/include/epee/serialization/keyvalue_serialization.h index 726d9c5ec..aa66599a8 100644 --- a/contrib/epee/include/epee/serialization/keyvalue_serialization.h +++ b/contrib/epee/include/epee/serialization/keyvalue_serialization.h @@ -29,10 +29,6 @@ #include "../misc_log_ex.h" #include "keyvalue_serialization_overloads.h" #include "../storages/portable_storage.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "serialization" - namespace epee { /************************************************************************/ @@ -66,8 +62,7 @@ public: \ bool Class::load(epee::serialization::portable_storage& st, epee::serialization::section* parent_section) \ { \ try { return _load(st, parent_section); } \ - catch (const std::exception& err) { LOG_ERROR("Deserialization exception: " << err.what()); } \ - catch (...) { LOG_ERROR("Unknown deserialization exception"); } \ + catch (...) {} \ return false; \ } \ template \ @@ -98,7 +93,6 @@ public: \ catch(const std::exception& err) \ { \ (void)(err); \ - LOG_ERROR("Exception on deserializing: " << err.what());\ return false; \ }\ }\ diff --git a/contrib/epee/include/epee/serialization/keyvalue_serialization_overloads.h b/contrib/epee/include/epee/serialization/keyvalue_serialization_overloads.h index be5efd04c..8395ee3bd 100644 --- a/contrib/epee/include/epee/serialization/keyvalue_serialization_overloads.h +++ b/contrib/epee/include/epee/serialization/keyvalue_serialization_overloads.h @@ -34,6 +34,7 @@ #include #include #include +#include #include "../span.h" #include "../storages/portable_storage_base.h" @@ -152,7 +153,6 @@ namespace epee return true; } catch (const std::out_of_range&) { // ignore silently } catch (const std::exception& e) { - LOG_ERROR("Failed to deserialize stl container: " << e.what()); } return false; } diff --git a/contrib/epee/include/epee/storages/levin_abstract_invoke2.h b/contrib/epee/include/epee/storages/levin_abstract_invoke2.h index 0206ef5fd..db9819ba8 100644 --- a/contrib/epee/include/epee/storages/levin_abstract_invoke2.h +++ b/contrib/epee/include/epee/storages/levin_abstract_invoke2.h @@ -30,9 +30,6 @@ #include "../span.h" #include "../net/levin_base.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net" - namespace epee { namespace net_utils @@ -51,13 +48,11 @@ namespace epee int res = transport.invoke(command, buff_to_send, buff_to_recv); if( res <=0 ) { - MERROR("Failed to invoke command " << command << " return code " << res); return false; } serialization::portable_storage stg_ret; if(!stg_ret.load_from_binary(buff_to_recv)) { - LOG_ERROR("Failed to load_from_binary on command " << command); return false; } return result_struct.load(stg_ret); @@ -77,7 +72,6 @@ namespace epee int res = transport.notify(command, buff_to_send); if(res <=0 ) { - LOG_ERROR("Failed to notify command " << command << " return code " << res); return false; } return true; @@ -95,13 +89,11 @@ namespace epee int res = transport.invoke(command, buff_to_send, buff_to_recv, conn_id); if( res <=0 ) { - LOG_PRINT_L1("Failed to invoke command " << command << " return code " << res); return false; } typename serialization::portable_storage stg_ret; if(!stg_ret.load_from_binary(buff_to_recv)) { - LOG_ERROR("Failed to load_from_binary on command " << command); return false; } return result_struct.load(stg_ret); @@ -119,20 +111,17 @@ namespace epee t_result result_struct{}; if( code <=0 ) { - LOG_PRINT_L1("Failed to invoke command " << command << " return code " << code); cb(code, std::move(result_struct), context); return false; } serialization::portable_storage stg_ret; if(!stg_ret.load_from_binary(buff)) { - LOG_ERROR("Failed to load_from_binary on command " << command); cb(LEVIN_ERROR_FORMAT, std::move(result_struct), context); return false; } if (!result_struct.load(stg_ret)) { - LOG_ERROR("Failed to load result struct on command " << command); cb(LEVIN_ERROR_FORMAT, std::move(result_struct), context); return false; } @@ -141,7 +130,6 @@ namespace epee }, inv_timeout); if( res <=0 ) { - LOG_PRINT_L1("Failed to invoke command " << command << " return code " << res); return false; } return true; @@ -159,7 +147,6 @@ namespace epee int res = transport.notify(command, epee::strspan(buff_to_send), conn_id); if(res <=0 ) { - MERROR("Failed to notify command " << command << " return code " << res); return false; } return true; @@ -172,7 +159,6 @@ namespace epee serialization::portable_storage strg; if(!strg.load_from_binary(in_buff)) { - LOG_ERROR("Failed to load_from_binary in command " << command); return -1; } t_in_type in_struct{}; @@ -180,7 +166,6 @@ namespace epee if (!in_struct.load(strg)) { - LOG_ERROR("Failed to load in_struct in command " << command); return -1; } int res = cb(command, in_struct, out_struct, context); @@ -189,7 +174,6 @@ namespace epee if(!strg_out.store_to_binary(buff_out)) { - LOG_ERROR("Failed to store_to_binary in command" << command); return -1; } @@ -202,13 +186,11 @@ namespace epee serialization::portable_storage strg; if(!strg.load_from_binary(in_buff)) { - LOG_ERROR("Failed to load_from_binary in notify " << command); return -1; } t_in_type in_struct{}; if (!in_struct.load(strg)) { - LOG_ERROR("Failed to load in_struct in notify " << command); return -1; } return cb(command, in_struct, context); @@ -294,7 +276,6 @@ namespace epee #define END_INVOKE_MAP2() \ - LOG_ERROR("Unknown command:" << command); \ return LEVIN_ERROR_CONNECTION_HANDLER_NOT_DEFINED; \ } } diff --git a/contrib/epee/include/epee/storages/portable_storage_base.h b/contrib/epee/include/epee/storages/portable_storage_base.h index deb0aae50..9124595f2 100644 --- a/contrib/epee/include/epee/storages/portable_storage_base.h +++ b/contrib/epee/include/epee/storages/portable_storage_base.h @@ -33,6 +33,7 @@ #include #include #include +#include #include "../misc_log_ex.h" #include "../int-util.h" diff --git a/contrib/epee/include/epee/storages/portable_storage_from_json.h b/contrib/epee/include/epee/storages/portable_storage_from_json.h index 34a967a67..b81ba4ebb 100644 --- a/contrib/epee/include/epee/storages/portable_storage_from_json.h +++ b/contrib/epee/include/epee/storages/portable_storage_from_json.h @@ -398,14 +398,8 @@ namespace epee run_handler(nullptr, it, buff_json.end(), stg, 0); return true; } - catch(const std::exception& ex) - { - MERROR("Failed to parse json, what: " << ex.what()); - return false; - } catch(...) { - MERROR("Failed to parse json"); return false; } } diff --git a/contrib/epee/include/epee/storages/portable_storage_to_bin.h b/contrib/epee/include/epee/storages/portable_storage_to_bin.h index aeca11f3b..8b5de9911 100644 --- a/contrib/epee/include/epee/storages/portable_storage_to_bin.h +++ b/contrib/epee/include/epee/storages/portable_storage_to_bin.h @@ -32,6 +32,7 @@ #include "portable_storage_base.h" #include #include +#include namespace epee { diff --git a/contrib/epee/include/epee/storages/portable_storage_val_converters.h b/contrib/epee/include/epee/storages/portable_storage_val_converters.h index ff18df7b9..e6f09c130 100644 --- a/contrib/epee/include/epee/storages/portable_storage_val_converters.h +++ b/contrib/epee/include/epee/storages/portable_storage_val_converters.h @@ -92,7 +92,6 @@ POP_WARNINGS void operator()(const std::string& from, uint64_t& to) { - MTRACE("Converting std::string to uint64_t. Source: " << from); const auto* strend = from.data() + from.size(); if (auto [p, ec] = std::from_chars(from.data(), strend, to); ec == std::errc{} && p == strend) return; // Good: successfully consumed the whole string. diff --git a/contrib/epee/src/CMakeLists.txt b/contrib/epee/src/CMakeLists.txt index 3ea86391e..ccec9fac2 100644 --- a/contrib/epee/src/CMakeLists.txt +++ b/contrib/epee/src/CMakeLists.txt @@ -32,7 +32,6 @@ add_library(epee levin_base.cpp memwipe.c mlocker.cpp - mlog.cpp net_utils_base.cpp network_throttle.cpp network_throttle-detail.cpp @@ -63,7 +62,6 @@ endif() target_link_libraries(epee PUBLIC - easylogging oxenmq::oxenmq oxenc::oxenc PRIVATE diff --git a/contrib/epee/src/connection_basic.cpp b/contrib/epee/src/connection_basic.cpp index c7afcc92c..162d87bee 100644 --- a/contrib/epee/src/connection_basic.cpp +++ b/contrib/epee/src/connection_basic.cpp @@ -137,8 +137,6 @@ connection_basic::connection_basic(boost::asio::ip::tcp::socket&& sock, std::sha std::string remote_addr_str = "?"; try { boost::system::error_code e; remote_addr_str = socket_.remote_endpoint(e).address().to_string(); } catch(...){} ; - - MDEBUG("Spawned connection #"<m_peer_number<<" to " << remote_addr_str << " currently we have sockets count:" << m_state->sock_count); } connection_basic::connection_basic(boost::asio::io_service &io_service, std::shared_ptr state) @@ -159,8 +157,6 @@ connection_basic::connection_basic(boost::asio::io_service &io_service, std::sha std::string remote_addr_str = "?"; try { boost::system::error_code e; remote_addr_str = socket().remote_endpoint(e).address().to_string(); } catch(...){} ; - - MDEBUG("Spawned connection #"<m_peer_number<<" to " << remote_addr_str << " currently we have sockets count:" << m_state->sock_count); } connection_basic::~connection_basic() noexcept(false) { @@ -168,7 +164,6 @@ connection_basic::~connection_basic() noexcept(false) { std::string remote_addr_str = "?"; try { boost::system::error_code e; remote_addr_str = socket().remote_endpoint(e).address().to_string(); } catch(...){} ; - MDEBUG("Destructing connection #"<m_peer_number << " to " << remote_addr_str); } void connection_basic::set_rate_up_limit(uint64_t limit) { @@ -221,7 +216,6 @@ void connection_basic::sleep_before_packet(size_t packet_size, int phase, int q do { // rate limiting if (m_was_shutdown) { - MDEBUG("m_was_shutdown - so abort sleep"); return; } @@ -232,8 +226,7 @@ void connection_basic::sleep_before_packet(size_t packet_size, int phase, int q delay *= 0.50; if (delay > 0) { - long int ms = (long int)(delay * 1000); - MTRACE("Sleeping in " << __FUNCTION__ << " for " << ms << " ms before packet_size="< 0); @@ -247,13 +240,11 @@ void connection_basic::sleep_before_packet(size_t packet_size, int phase, int q } void connection_basic::do_send_handler_write(const void* ptr , size_t cb ) { - // No sleeping here; sleeping is done once and for all in connection::handle_write - MTRACE("handler_write (direct) - before ASIO write, for packet="<::handle_write } void connection_basic::do_send_handler_write_from_queue( const boost::system::error_code& e, size_t cb, int q_len ) { - // No sleeping here; sleeping is done once and for all in connection::handle_write - MTRACE("handler_write (after write, from queue="<::handle_write } void connection_basic::logger_handle_net_read(size_t size) { // network data read diff --git a/contrib/epee/src/mlocker.cpp b/contrib/epee/src/mlocker.cpp index 16533ca28..b7477ec99 100644 --- a/contrib/epee/src/mlocker.cpp +++ b/contrib/epee/src/mlocker.cpp @@ -45,9 +45,6 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "mlocker" - // did an mlock operation previously fail? we only // want to log an error once and be done with it static std::atomic previously_failed{ false }; @@ -58,7 +55,6 @@ static size_t query_page_size() long ret = sysconf(_SC_PAGESIZE); if (ret <= 0) { - MERROR("Failed to determine page size"); return 0; } return ret; @@ -72,8 +68,6 @@ static void do_lock(void *ptr, size_t len) { #if defined HAVE_MLOCK int ret = mlock(ptr, len); - if (ret < 0 && !previously_failed.exchange(true)) - MERROR("Error locking page at " << ptr << ": " << strerror(errno) << ", subsequent mlock errors will be silenced"); #else #warning Missing do_lock implementation #endif @@ -83,11 +77,6 @@ static void do_unlock(void *ptr, size_t len) { #if defined HAVE_MLOCK int ret = munlock(ptr, len); - // check whether we previously failed, but don't set it, this is just - // to pacify the errors of mlock()ing failed, in which case unlocking - // is also not going to work of course - if (ret < 0 && !previously_failed.load()) - MERROR("Error unlocking page at " << ptr << ": " << strerror(errno)); #else #warning Missing implementation of page size detection #endif @@ -214,11 +203,7 @@ namespace epee { #if defined(HAVE_MLOCK) std::map::iterator i = map().find(page); - if (i == map().end()) - { - MERROR("Attempt to unlock unlocked page at " << (void*)(page * page_size)); - } - else + if (i != map().end()) { if (!--i->second) { diff --git a/contrib/epee/src/mlog.cpp b/contrib/epee/src/mlog.cpp deleted file mode 100644 index 29e8988ae..000000000 --- a/contrib/epee/src/mlog.cpp +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of the Andrey N. Sabelnikov nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// 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 OWNER 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. -// - - -#ifndef _MLOG_H_ -#define _MLOG_H_ - -#include -#include -#ifdef _WIN32 -#include -#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING -#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 -#endif -#endif - -#include -#include -#include -#include "epee/string_tools.h" -#include "epee/misc_log_ex.h" - -#ifndef USE_GHC_FILESYSTEM -#include -namespace fs { using namespace std::filesystem; } -#else -#include -namespace fs = ghc::filesystem; -#endif - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "logging" - -#define MLOG_BASE_FORMAT "%datetime{%Y-%M-%d %H:%m:%s.%g}\t%thread\t%level\t%logger\t%loc\t%msg" - -#define MLOG_LOG(x) CINFO(el::base::Writer,el::base::DispatchAction::FileOnlyLog,OXEN_DEFAULT_LOG_CATEGORY) << x - -using namespace epee; - -std::string mlog_get_default_log_path(const char *default_filename) -{ - std::string process_name = epee::string_tools::get_current_module_name(); - std::string default_log_folder = epee::string_tools::get_current_module_folder(); - std::string default_log_file = process_name; - std::string::size_type a = default_log_file.rfind('.'); - if ( a != std::string::npos ) - default_log_file.erase( a, default_log_file.size()); - if ( ! default_log_file.empty() ) - default_log_file += ".log"; - else - default_log_file = default_filename; - - return (fs::u8path(default_log_folder) / fs::u8path(default_log_file)).u8string(); -} - -static void mlog_set_common_prefix() -{ - static const char * const expected_filename = "contrib/epee/src/mlog.cpp"; - const char *path = __FILE__, *expected_ptr = strstr(path, expected_filename); - if (!expected_ptr) - return; - el::Loggers::setFilenameCommonPrefix(std::string(path, expected_ptr - path)); -} - -static const char *get_default_categories(int level) -{ - const char *categories = ""; - switch (level) - { - case 0: - categories = "*:WARNING,net:FATAL,net.http:FATAL,net.p2p:FATAL,net.cn:FATAL,global:INFO,verify:FATAL,serialization:FATAL,logging:INFO,msgwriter:INFO"; - break; - case 1: - categories = "*:INFO,global:INFO,stacktrace:INFO,logging:INFO,msgwriter:INFO,perf.*:DEBUG"; - break; - case 2: - categories = "*:DEBUG"; - break; - case 3: - categories = "*:TRACE"; - break; - case 4: - categories = "*:TRACE"; - break; - default: - break; - } - return categories; -} - -#ifdef WIN32 -bool EnableVTMode() -{ - // Set output mode to handle virtual terminal sequences - HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); - if (hOut == INVALID_HANDLE_VALUE) - { - return false; - } - - DWORD dwMode = 0; - if (!GetConsoleMode(hOut, &dwMode)) - { - return false; - } - - dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; - if (!SetConsoleMode(hOut, dwMode)) - { - return false; - } - return true; -} -#endif - -void mlog_configure(const std::string &filename_base, bool console, const std::size_t max_log_file_size, const std::size_t max_log_files) -{ - el::Configurations c; - c.setGlobally(el::ConfigurationType::Filename, filename_base); - c.setGlobally(el::ConfigurationType::ToFile, "true"); - const char *log_format = getenv("OXEN_LOG_FORMAT"); - if (!log_format) - log_format = MLOG_BASE_FORMAT; - c.setGlobally(el::ConfigurationType::Format, log_format); - c.setGlobally(el::ConfigurationType::ToStandardOutput, console ? "true" : "false"); - c.setGlobally(el::ConfigurationType::MaxLogFileSize, std::to_string(max_log_file_size)); - el::Loggers::setDefaultConfigurations(c, true); - - el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); - el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); - el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog); - el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); - el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck); - el::Helpers::installPreRollOutCallback([filename_base, max_log_files](const char *name, size_t){ - std::string rname = filename_base + "-" + date::format("%Y-%m-%d-%H-%M-%S", std::chrono::system_clock::now()); - int ret = rename(name, rname.c_str()); - if (ret < 0) - { - // can't log a failure, but don't do the file removal below - return; - } - if (max_log_files != 0) - { - std::vector found_files; - const auto filename_base_path = fs::u8path(filename_base); - const auto parent_path = filename_base_path.has_parent_path() ? filename_base_path.parent_path() : fs::path("."); - for (const auto& p : fs::directory_iterator{parent_path}) - { - const std::string filename = p.path().u8string(); - if (filename.size() >= filename_base.size() && std::memcmp(filename.data(), filename_base.data(), filename_base.size()) == 0) - found_files.push_back(p.path()); - } - - if (found_files.size() >= max_log_files) - { - std::sort(found_files.begin(), found_files.end(), [](auto& a, auto& b) { - std::error_code ec; - return fs::last_write_time(a, ec) < fs::last_write_time(b, ec); - }); - for (size_t i = 0; i <= found_files.size() - max_log_files; ++i) - { - std::error_code ec; - if (!fs::remove(found_files[i], ec)) - MERROR("Failed to remove " << found_files[i] << ": " << ec.message()); - } - } - } - }); - mlog_set_common_prefix(); - const char *loki_log = getenv("OXEN_LOGS"); - if (!loki_log) - { - loki_log = get_default_categories(0); - } - mlog_set_log(loki_log); -#ifdef WIN32 - EnableVTMode(); -#endif -} - -void mlog_set_categories(const char *categories) -{ - std::string new_categories; - if (*categories) - { - if (*categories == '+') - { - ++categories; - new_categories = mlog_get_categories(); - if (*categories) - { - if (!new_categories.empty()) - new_categories += ","; - new_categories += categories; - } - } - else if (*categories == '-') - { - ++categories; - new_categories = mlog_get_categories(); - std::vector single_categories; - boost::split(single_categories, categories, boost::is_any_of(","), boost::token_compress_on); - for (const std::string &s: single_categories) - { - size_t pos = new_categories.find(s); - if (pos != std::string::npos) - new_categories = new_categories.erase(pos, s.size()); - } - } - else - { - new_categories = categories; - } - } - el::Loggers::setCategories(new_categories.c_str(), true); - MLOG_LOG("New log categories: " << el::Loggers::getCategories()); -} - -std::string mlog_get_categories() -{ - return el::Loggers::getCategories(); -} - -// maps epee style log level to new logging system -void mlog_set_log_level(int level) -{ - const char *categories = get_default_categories(level); - mlog_set_categories(categories); -} - -void mlog_set_log(const char *log) -{ - long level; - char *ptr = NULL; - - if (!*log) - { - mlog_set_categories(log); - return; - } - level = strtol(log, &ptr, 10); - if (ptr && *ptr) - { - // we can have a default level, eg, 2,foo:ERROR - if (*ptr == ',') { - std::string new_categories = std::string(get_default_categories(level)) + ptr; - mlog_set_categories(new_categories.c_str()); - } - else { - mlog_set_categories(log); - } - } - else if (level >= 0 && level <= 4) - { - mlog_set_log_level(level); - } - else - { - MERROR("Invalid numerical log level: " << log); - } -} - -namespace epee -{ - -bool is_stdout_a_tty() -{ - static std::atomic initialized(false); - static std::atomic is_a_tty(false); - - if (!initialized.load(std::memory_order_acquire)) - { -#if defined(WIN32) - is_a_tty.store(0 != _isatty(_fileno(stdout)), std::memory_order_relaxed); -#else - is_a_tty.store(0 != isatty(fileno(stdout)), std::memory_order_relaxed); -#endif - initialized.store(true, std::memory_order_release); - } - - return is_a_tty.load(std::memory_order_relaxed); -} - -void set_console_color(int color, bool bright) -{ - if (!is_stdout_a_tty()) - return; - - switch(color) - { - case console_color_default: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE| (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;37m"; - else - std::cout << "\033[0m"; -#endif - } - break; - case console_color_white: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;37m"; - else - std::cout << "\033[0;37m"; -#endif - } - break; - case console_color_red: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;31m"; - else - std::cout << "\033[0;31m"; -#endif - } - break; - case console_color_green: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;32m"; - else - std::cout << "\033[0;32m"; -#endif - } - break; - - case console_color_blue: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_INTENSITY);//(bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;34m"; - else - std::cout << "\033[0;34m"; -#endif - } - break; - - case console_color_cyan: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;36m"; - else - std::cout << "\033[0;36m"; -#endif - } - break; - - case console_color_magenta: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;35m"; - else - std::cout << "\033[0;35m"; -#endif - } - break; - - case console_color_yellow: - { -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0)); -#else - if(bright) - std::cout << "\033[1;33m"; - else - std::cout << "\033[0;33m"; -#endif - } - break; - - } -} - -void reset_console_color() { - if (!is_stdout_a_tty()) - return; - -#ifdef WIN32 - HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); -#else - std::cout << "\033[0m"; - std::cout.flush(); -#endif -} - -} - -static bool mlog(el::Level level, const char *category, const char *format, va_list ap) noexcept -{ - int size = 0; - char *p = NULL; - va_list apc; - bool ret = true; - - /* Determine required size */ - va_copy(apc, ap); - size = vsnprintf(p, size, format, apc); - va_end(apc); - if (size < 0) - return false; - - size++; /* For '\0' */ - p = (char*)malloc(size); - if (p == NULL) - return false; - - size = vsnprintf(p, size, format, ap); - if (size < 0) - { - free(p); - return false; - } - - try - { - /* TODO(loki): when pulling upstream epee changes change this to: - MCLOG(level, category, el::Color::Default, p); - */ - MCLOG(level, category, p); - } - catch(...) - { - ret = false; - } - free(p); - - return ret; -} - -#define DEFLOG(fun,lev) \ - bool m##fun(const char *category, const char *fmt, ...) { va_list ap; va_start(ap, fmt); bool ret = mlog(el::Level::lev, category, fmt, ap); va_end(ap); return ret; } - -DEFLOG(error, Error) -DEFLOG(warning, Warning) -DEFLOG(info, Info) -DEFLOG(debug, Debug) -DEFLOG(trace, Trace) - -#undef DEFLOG - -#endif //_MLOG_H_ diff --git a/contrib/epee/src/network_throttle-detail.cpp b/contrib/epee/src/network_throttle-detail.cpp index 37a8c68f5..3a5089bee 100644 --- a/contrib/epee/src/network_throttle-detail.cpp +++ b/contrib/epee/src/network_throttle-detail.cpp @@ -133,8 +133,7 @@ void network_throttle::set_name(const std::string &name) void network_throttle::set_target_speed( network_speed_kbps target ) { - m_target_speed = target * 1024; - MINFO("Setting LIMIT: " << target << " kbps"); + m_target_speed = target * 1024; } network_speed_kbps network_throttle::get_target_speed() @@ -155,7 +154,6 @@ void network_throttle::tick() // TODO optimize when moving few slots at once while ( (!m_any_packet_yet) || (last_sample_time_slot < current_sample_time_slot)) { - MTRACE("Moving counter buffer by 1 second " << last_sample_time_slot << " < " << current_sample_time_slot << " (last time " << m_last_sample_time<<")"); // rotate buffer m_history.push_front(packet_info()); if (! m_any_packet_yet) @@ -185,13 +183,6 @@ void network_throttle::_handle_trafic_exact(size_t packet_size, size_t orginal_s std::ostringstream oss; oss << "["; for (auto sample: m_history) oss << sample.m_size << " "; oss << "]" << std::ends; std::string history_str = oss.str(); - - MTRACE("Throttle " << m_name << ": packet of ~"<(time) << " " << static_cast(size/1024) << "\n"; file.close(); } @@ -269,28 +258,13 @@ void network_throttle::calculate_times(size_t packet_size, calculate_times_struc if (cts.delay>=0) cts.delay = 0; // no traffic in history so we will not wait } - double Wgood=-1; { // how much data we recommend now to download - Wgood = the_window_size + 1; cts.recomendetDataSize = M*cts.window - E; } if (dbg) { std::ostringstream oss; oss << "["; for (auto sample: m_history) oss << sample.m_size << " "; oss << "]" << std::ends; std::string history_str = oss.str(); - MTRACE((cts.delay > 0 ? "SLEEP" : "") - << "dbg " << m_name << ": " - << "speed is A=" << std::setw(8) < #include @@ -99,7 +96,6 @@ void match_string2(const char*& star_end_string, const char* buf_end, std::strin break; default: val.push_back(*it); - LOG_PRINT_L0("Unknown escape sequence :\"\\" << *it << "\""); } escape_mode = false; }else if(*it == '"') diff --git a/contrib/epee/src/portable_storage.cpp b/contrib/epee/src/portable_storage.cpp index 12b40aa70..7338f5be2 100644 --- a/contrib/epee/src/portable_storage.cpp +++ b/contrib/epee/src/portable_storage.cpp @@ -119,7 +119,6 @@ namespace epee { m_root.m_entries.clear(); if(source.size() < sizeof(storage_block_header)) { - LOG_ERROR("portable_storage: wrong binary format, packet size = " << source.size() << " less than expected sizeof(storage_block_header)=" << sizeof(storage_block_header)); return false; } storage_block_header* pbuff = (storage_block_header*)source.data(); @@ -127,12 +126,10 @@ namespace epee { pbuff->m_signature_b != PORTABLE_STORAGE_SIGNATUREB ) { - LOG_ERROR("portable_storage: wrong binary format - signature mismatch"); return false; } if(pbuff->m_ver != PORTABLE_STORAGE_FORMAT_VER) { - LOG_ERROR("portable_storage: wrong binary format - unknown format ver = " << pbuff->m_ver); return false; } TRY_ENTRY(); diff --git a/contrib/epee/src/wipeable_string.cpp b/contrib/epee/src/wipeable_string.cpp index 7034db8a7..da7ce9bd3 100644 --- a/contrib/epee/src/wipeable_string.cpp +++ b/contrib/epee/src/wipeable_string.cpp @@ -37,6 +37,7 @@ #include "epee/memwipe.h" #include "epee/misc_log_ex.h" #include "epee/wipeable_string.h" +#include static constexpr const char hex[] = u8"0123456789abcdef"; diff --git a/contrib/format.sh b/contrib/format.sh index 4ff2f83d1..88c7037f9 100755 --- a/contrib/format.sh +++ b/contrib/format.sh @@ -2,7 +2,7 @@ CLANG_FORMAT_DESIRED_VERSION=11 -TARGET_DIRS=(src/wallet3 src/sqlitedb) +TARGET_DIRS=(src/wallet3 src/sqlitedb src/logging) binary=$(which clang-format-$CLANG_FORMAT_DESIRED_VERSION 2>/dev/null) if [ $? -ne 0 ]; then diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 9bd761bfd..03740a801 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -61,16 +61,15 @@ endmacro() system_or_submodule(OXENC oxenc liboxenc>=1.0.3 oxen-encoding) system_or_submodule(OXENMQ oxenmq liboxenmq>=1.2.12 oxen-mq) -system_or_submodule(FMT fmt fmt>=8.0.0 fmt) add_subdirectory(db_drivers) -add_subdirectory(easylogging++ easyloggingpp) add_subdirectory(randomx EXCLUDE_FROM_ALL) add_subdirectory(date EXCLUDE_FROM_ALL) set(JSON_BuildTests OFF CACHE INTERNAL "") set(JSON_MultipleHeaders ON CACHE BOOL "") # Allows multi-header nlohmann use add_subdirectory(nlohmann-json EXCLUDE_FROM_ALL) +add_subdirectory(oxen-logging) # uSockets doesn't really have a proper build system (just a very simple Makefile) so build it # ourselves. diff --git a/external/easylogging++/CMakeLists.txt b/external/easylogging++/CMakeLists.txt deleted file mode 100644 index 8583dbe32..000000000 --- a/external/easylogging++/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2014-2018, The Monero Project -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, are -# permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 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. -# -# 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. -# -# 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. - -cmake_minimum_required(VERSION 3.5) - -project(easylogging CXX) - -add_library(easylogging - easylogging++.cc) - -set_property(TARGET easylogging PROPERTY POSITION_INDEPENDENT_CODE ON) -set_property(TARGET easylogging PROPERTY CXX_STANDARD 11) -set_property(TARGET easylogging PROPERTY CXX_STANDARD_REQUIRED ON) - -find_package(Threads) -find_package(Backtrace) - -target_include_directories(easylogging PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") - -target_link_libraries(easylogging - PRIVATE - Threads::Threads - ${Backtrace_LIBRARIES}) - -# GUI/libwallet install target -if (BUILD_GUI_DEPS) - if(IOS) - set(lib_folder lib-${ARCH}) - target_compile_options(easylogging PUBLIC -fno-stack-check) - else() - set(lib_folder lib) - endif() - install(TARGETS easylogging - ARCHIVE DESTINATION ${lib_folder} - LIBRARY DESTINATION ${lib_folder}) -endif() diff --git a/external/easylogging++/ea_config.h b/external/easylogging++/ea_config.h deleted file mode 100644 index 91a671575..000000000 --- a/external/easylogging++/ea_config.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#define ELPP_THREAD_SAFE -#define ELPP_DEFAULT_LOG_FILE "" -#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING -#define ELPP_NO_CHECK_MACROS -#define ELPP_WINSOCK2 -#define ELPP_NO_DEBUG_MACROS -#define ELPP_UTC_DATETIME - -#ifdef EASYLOGGING_CC -#if !(!defined __GLIBC__ || !defined __GNUC__ || defined __MINGW32__ || defined __MINGW64__ || defined __ANDROID__) -#define ELPP_FEATURE_CRASH_LOG -#endif -#endif diff --git a/external/easylogging++/easylogging++.cc b/external/easylogging++/easylogging++.cc deleted file mode 100644 index 8c3a6641c..000000000 --- a/external/easylogging++/easylogging++.cc +++ /dev/null @@ -1,3319 +0,0 @@ -// -// Bismillah ar-Rahmaan ar-Raheem -// -// Easylogging++ v9.96.7 -// Cross-platform logging library for C++ applications -// -// Copyright (c) 2012-2018 Zuhd Web Services -// Copyright (c) 2012-2018 @abumusamq -// -// This library is released under the MIT Licence. -// https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE -// -// https://zuhd.org -// http://muflihun.com -// - -#define EASYLOGGING_CC -#include "easylogging++.h" - -#include - -#if defined(AUTO_INITIALIZE_EASYLOGGINGPP) -INITIALIZE_EASYLOGGINGPP -#endif - -namespace el { - -// el::base -namespace base { -// el::base::consts -namespace consts { - -// Level log values - These are values that are replaced in place of %level format specifier -// Extra spaces after format specifiers are only for readability purposes in log files -static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO"); -static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG"); -static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING"); -static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR"); -static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL"); -static const base::type::char_t* kVerboseLevelLogValue = - ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level -static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE"); -static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I"); -static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D"); -static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W"); -static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E"); -static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F"); -static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V"); -static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T"); -// Format specifiers - These are used to define log format -static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app"); -static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger"); -static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread"); -static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level"); -static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort"); -static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime"); -static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file"); -static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase"); -static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line"); -static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc"); -static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func"); -static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user"); -static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host"); -static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg"); -static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel"); -static const char* kDateTimeFormatSpecifierForFilename = "%datetime"; -// Date/time -static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; -static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; -static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August", - "September", "October", "November", "December" - }; -static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; -static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g"; -static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m"; -static const int kYearBase = 1900; -static const char* kAm = "AM"; -static const char* kPm = "PM"; -// Miscellaneous constants - -static const char* kNullPointer = "nullptr"; -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED -static const base::type::VerboseLevel kMaxVerboseLevel = 9; -static const char* kUnknownUser = "user"; -static const char* kUnknownHost = "unknown-host"; - - -//---------------- DEFAULT LOG FILE ----------------------- - -#if defined(ELPP_NO_DEFAULT_LOG_FILE) -# if ELPP_OS_UNIX -static const char* kDefaultLogFile = "/dev/null"; -# elif ELPP_OS_WINDOWS -static const char* kDefaultLogFile = "nul"; -# endif // ELPP_OS_UNIX -#elif defined(ELPP_DEFAULT_LOG_FILE) -static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE; -#else -static const char* kDefaultLogFile = "myeasylog.log"; -#endif // defined(ELPP_NO_DEFAULT_LOG_FILE) - - -#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -static const char* kDefaultLogFileParam = "--default-log-file"; -#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) -static const char* kLoggingFlagsParam = "--logging-flags"; -#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) -static const char* kValidLoggerIdSymbols = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._"; -static const char* kConfigurationComment = "##"; -static const char* kConfigurationLevel = "*"; -static const char* kConfigurationLoggerId = "--"; -} -// el::base::utils -namespace utils { - -/// @brief Aborts application due with user-defined status -static void abort(int status, const std::string& reason) { - // Both status and reason params are there for debugging with tools like gdb etc - ELPP_UNUSED(status); - ELPP_UNUSED(reason); -#if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) - // Ignore msvc critical error dialog - break instead (on debug mode) - _asm int 3 -#else -#ifdef NDEBUG - ::_exit(1); -#else - ::abort(); -#endif -#endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) -} - -} // namespace utils -} // namespace base - -// el - -// LevelHelper - -const char* LevelHelper::convertToString(Level level) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (level == Level::Global) return "GLOBAL"; - if (level == Level::Debug) return "DEBUG"; - if (level == Level::Info) return "INFO"; - if (level == Level::Warning) return "WARNING"; - if (level == Level::Error) return "ERROR"; - if (level == Level::Fatal) return "FATAL"; - if (level == Level::Verbose) return "VERBOSE"; - if (level == Level::Trace) return "TRACE"; - return "UNKNOWN"; -} - -struct StringToLevelItem { - const char* levelString; - Level level; -}; - -static struct StringToLevelItem stringToLevelMap[] = { - { "global", Level::Global }, - { "debug", Level::Debug }, - { "info", Level::Info }, - { "warning", Level::Warning }, - { "error", Level::Error }, - { "fatal", Level::Fatal }, - { "verbose", Level::Verbose }, - { "trace", Level::Trace } -}; - -Level LevelHelper::convertFromString(const char* levelStr) { - for (auto& item : stringToLevelMap) { - if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) { - return item.level; - } - } - return Level::Unknown; -} - -Level LevelHelper::convertFromStringPrefix(const char* levelStr) { - if ((strncmp(levelStr, "GLOBAL", 6) == 0) || (strncmp(levelStr, "global", 6) == 0)) - return Level::Global; - if ((strncmp(levelStr, "DEBUG", 5) == 0) || (strncmp(levelStr, "debug", 5) == 0)) - return Level::Debug; - if ((strncmp(levelStr, "INFO", 4) == 0) || (strncmp(levelStr, "info", 4) == 0)) - return Level::Info; - if ((strncmp(levelStr, "WARNING", 7) == 0) || (strncmp(levelStr, "warning", 7) == 0)) - return Level::Warning; - if ((strncmp(levelStr, "ERROR", 5) == 0) || (strncmp(levelStr, "error", 5) == 0)) - return Level::Error; - if ((strncmp(levelStr, "FATAL", 5) == 0) || (strncmp(levelStr, "fatal", 5) == 0)) - return Level::Fatal; - if ((strncmp(levelStr, "VERBOSE", 7) == 0) || (strncmp(levelStr, "verbose", 7) == 0)) - return Level::Verbose; - if ((strncmp(levelStr, "TRACE", 5) == 0) || (strncmp(levelStr, "trace", 5) == 0)) - return Level::Trace; - return Level::Unknown; -} - -void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function& fn) { - base::type::EnumType lIndexMax = LevelHelper::kMaxValid; - do { - if (fn()) { - break; - } - *startIndex = static_cast(*startIndex << 1); - } while (*startIndex <= lIndexMax); -} - -// ConfigurationTypeHelper - -const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (configurationType == ConfigurationType::Enabled) return "ENABLED"; - if (configurationType == ConfigurationType::Filename) return "FILENAME"; - if (configurationType == ConfigurationType::Format) return "FORMAT"; - if (configurationType == ConfigurationType::ToFile) return "TO_FILE"; - if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT"; - if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION"; - if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING"; - if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE"; - if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD"; - return "UNKNOWN"; -} - -struct ConfigurationStringToTypeItem { - const char* configString; - ConfigurationType configType; -}; - -static struct ConfigurationStringToTypeItem configStringToTypeMap[] = { - { "enabled", ConfigurationType::Enabled }, - { "to_file", ConfigurationType::ToFile }, - { "to_standard_output", ConfigurationType::ToStandardOutput }, - { "format", ConfigurationType::Format }, - { "filename", ConfigurationType::Filename }, - { "subsecond_precision", ConfigurationType::SubsecondPrecision }, - { "milliseconds_width", ConfigurationType::MillisecondsWidth }, - { "performance_tracking", ConfigurationType::PerformanceTracking }, - { "max_log_file_size", ConfigurationType::MaxLogFileSize }, - { "log_flush_threshold", ConfigurationType::LogFlushThreshold }, -}; - -ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) { - for (auto& item : configStringToTypeMap) { - if (base::utils::Str::cStringCaseEq(configStr, item.configString)) { - return item.configType; - } - } - return ConfigurationType::Unknown; -} - -void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function& fn) { - base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid; - do { - if (fn()) { - break; - } - *startIndex = static_cast(*startIndex << 1); - } while (*startIndex <= cIndexMax); -} - -// Configuration - -Configuration::Configuration(const Configuration& c) : - m_level(c.m_level), - m_configurationType(c.m_configurationType), - m_value(c.m_value) { -} - -Configuration& Configuration::operator=(const Configuration& c) { - if (&c != this) { - m_level = c.m_level; - m_configurationType = c.m_configurationType; - m_value = c.m_value; - } - return *this; -} - -/// @brief Full constructor used to sets value of configuration -Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) : - m_level(level), - m_configurationType(configurationType), - m_value(value) { -} - -void Configuration::log(el::base::type::ostream_t& os) const { - os << LevelHelper::convertToString(m_level) - << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType) - << ELPP_LITERAL(" = ") << m_value.c_str(); -} - -/// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. -Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) : - m_level(level), - m_configurationType(configurationType) { -} - -bool Configuration::Predicate::operator()(const Configuration* conf) const { - return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType)); -} - -// Configurations - -Configurations::Configurations(void) : - m_configurationFile(std::string()), - m_isFromFile(false) { -} - -Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining, - Configurations* base) : - m_configurationFile(configurationFile), - m_isFromFile(false) { - parseFromFile(configurationFile, base); - if (useDefaultsForRemaining) { - setRemainingToDefault(); - } -} - -bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) { - // We initial assertion with true because if we have assertion diabled, we want to pass this - // check and if assertion is enabled we will have values re-assigned any way. - bool assertionPassed = true; - ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true, - "Configuration file [" << configurationFile << "] does not exist!"); - if (!assertionPassed) { - return false; - } - bool success = Parser::parseFromFile(configurationFile, this, base); - m_isFromFile = success; - return success; -} - -bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) { - bool success = Parser::parseFromText(configurationsString, this, base); - if (success) { - m_isFromFile = false; - } - return success; -} - -void Configurations::setFromBase(Configurations* base) { - if (base == nullptr || base == this) { - return; - } - base::threading::ScopedLock scopedLock(base->lock()); - for (Configuration*& conf : base->list()) { - set(conf); - } -} - -bool Configurations::hasConfiguration(ConfigurationType configurationType) { - base::type::EnumType lIndex = LevelHelper::kMinValid; - bool result = false; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) { - result = true; - } - return result; - }); - return result; -} - -bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) { - base::threading::ScopedLock scopedLock(lock()); -#if ELPP_COMPILER_INTEL - // We cant specify template types here, Intel C++ throws compilation error - // "error: type name is not allowed" - return RegistryWithPred::get(level, configurationType) != nullptr; -#else - return RegistryWithPred::get(level, configurationType) != nullptr; -#endif // ELPP_COMPILER_INTEL -} - -void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) { - base::threading::ScopedLock scopedLock(lock()); - unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex - if (level == Level::Global) { - unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either - } -} - -void Configurations::set(Configuration* conf) { - if (conf == nullptr) { - return; - } - set(conf->level(), conf->configurationType(), conf->value()); -} - -void Configurations::setToDefault(void) { - setGlobally(ConfigurationType::Enabled, std::string("true"), true); - setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true); -#if defined(ELPP_NO_LOG_TO_FILE) - setGlobally(ConfigurationType::ToFile, std::string("false"), true); -#else - setGlobally(ConfigurationType::ToFile, std::string("true"), true); -#endif // defined(ELPP_NO_LOG_TO_FILE) - setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true); - setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true); - setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true); - setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true); - setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true); - - setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true); - set(Level::Debug, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); - // INFO and WARNING are set to default by Level::Global - set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); - set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); -} - -void Configurations::setRemainingToDefault(void) { - base::threading::ScopedLock scopedLock(lock()); -#if defined(ELPP_NO_LOG_TO_FILE) - unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false")); -#else - unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true")); -#endif // defined(ELPP_NO_LOG_TO_FILE) - unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile)); - unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0")); - unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); - // INFO and WARNING are set to default by Level::Global - unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); - unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); - unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format, - std::string("%datetime %level [%logger] [%func] [%loc] %msg")); -} - -bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender, - Configurations* base) { - sender->setFromBase(base); - std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in); - ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing."); - bool parsedSuccessfully = false; - std::string line = std::string(); - Level currLevel = Level::Unknown; - std::string currConfigStr = std::string(); - std::string currLevelStr = std::string(); - while (fileStream_.good()) { - std::getline(fileStream_, line); - parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); - ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); - } - return parsedSuccessfully; -} - -bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender, - Configurations* base) { - sender->setFromBase(base); - bool parsedSuccessfully = false; - std::stringstream ss(configurationsString); - std::string line = std::string(); - Level currLevel = Level::Unknown; - std::string currConfigStr = std::string(); - std::string currLevelStr = std::string(); - while (std::getline(ss, line)) { - parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); - ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); - } - return parsedSuccessfully; -} - -void Configurations::Parser::ignoreComments(std::string* line) { - std::size_t foundAt = 0; - std::size_t quotesStart = line->find("\""); - std::size_t quotesEnd = std::string::npos; - if (quotesStart != std::string::npos) { - quotesEnd = line->find("\"", quotesStart + 1); - while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') { - // Do not erase slash yet - we will erase it in parseLine(..) while loop - quotesEnd = line->find("\"", quotesEnd + 2); - } - } - if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) { - if (foundAt < quotesEnd) { - foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1); - } - *line = line->substr(0, foundAt); - } -} - -bool Configurations::Parser::isLevel(const std::string& line) { - return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel)); -} - -bool Configurations::Parser::isComment(const std::string& line) { - return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment)); -} - -bool Configurations::Parser::isConfig(const std::string& line) { - std::size_t assignment = line.find('='); - return line != "" && - ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) && - (assignment != std::string::npos) && - (line.size() > assignment); -} - -bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, - Level* currLevel, - Configurations* conf) { - ConfigurationType currConfig = ConfigurationType::Unknown; - std::string currValue = std::string(); - *line = base::utils::Str::trim(*line); - if (isComment(*line)) return true; - ignoreComments(line); - *line = base::utils::Str::trim(*line); - if (line->empty()) { - // Comment ignored - return true; - } - if (isLevel(*line)) { - if (line->size() <= 2) { - return true; - } - *currLevelStr = line->substr(1, line->size() - 2); - *currLevelStr = base::utils::Str::toUpper(*currLevelStr); - *currLevelStr = base::utils::Str::trim(*currLevelStr); - *currLevel = LevelHelper::convertFromString(currLevelStr->c_str()); - return true; - } - if (isConfig(*line)) { - std::size_t assignment = line->find('='); - *currConfigStr = line->substr(0, assignment); - *currConfigStr = base::utils::Str::toUpper(*currConfigStr); - *currConfigStr = base::utils::Str::trim(*currConfigStr); - currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str()); - currValue = line->substr(assignment + 1); - currValue = base::utils::Str::trim(currValue); - std::size_t quotesStart = currValue.find("\"", 0); - std::size_t quotesEnd = std::string::npos; - if (quotesStart != std::string::npos) { - quotesEnd = currValue.find("\"", quotesStart + 1); - while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') { - currValue = currValue.erase(quotesEnd - 1, 1); - quotesEnd = currValue.find("\"", quotesEnd + 2); - } - } - if (quotesStart != std::string::npos && quotesEnd != std::string::npos) { - // Quote provided - check and strip if valid - ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in [" - << currConfigStr << "]"); - ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]"); - if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) { - // Explicit check in case if assertion is disabled - currValue = currValue.substr(quotesStart + 1, quotesEnd - 1); - } - } - } - ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]"); - ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]"); - if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) { - return false; // unrecognizable level or config - } - conf->set(*currLevel, currConfig, currValue); - return true; -} - -void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) { - Configuration* conf = RegistryWithPred::get(level, configurationType); - if (conf == nullptr) { - unsafeSet(level, configurationType, value); - } -} - -void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) { - Configuration* conf = RegistryWithPred::get(level, configurationType); - if (conf == nullptr) { - registerNew(new Configuration(level, configurationType, value)); - } else { - conf->setValue(value); - } - if (level == Level::Global) { - unsafeSetGlobally(configurationType, value, false); - } -} - -void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value, - bool includeGlobalLevel) { - if (includeGlobalLevel) { - set(Level::Global, configurationType, value); - } - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - set(LevelHelper::castFromInt(lIndex), configurationType, value); - return false; // Do not break lambda function yet as we need to set all levels regardless - }); -} - -void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, - bool includeGlobalLevel) { - if (includeGlobalLevel) { - unsafeSet(Level::Global, configurationType, value); - } - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value); - return false; // Do not break lambda function yet as we need to set all levels regardless - }); -} - -// LogBuilder - -void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) { - if (!m_termSupportsColor) return; - const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m"); - if (level == Level::Error || level == Level::Fatal) - *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor; - else if (level == Level::Warning) - *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor; - else if (level == Level::Debug) - *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor; - else if (level == Level::Info) - *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor; - else if (level == Level::Trace) - *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor; -} - -// Logger - -Logger::Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) : - m_id(id), - m_typedConfigurations(nullptr), - m_parentApplicationName(std::string()), - m_isConfigured(false), - m_logStreamsReference(logStreamsReference) { - initUnflushedCount(); -} - -Logger::Logger(const std::string& id, const Configurations& configurations, - base::LogStreamsReferenceMap* logStreamsReference) : - m_id(id), - m_typedConfigurations(nullptr), - m_parentApplicationName(std::string()), - m_isConfigured(false), - m_logStreamsReference(logStreamsReference) { - initUnflushedCount(); - configure(configurations); -} - -Logger::Logger(const Logger& logger) { - base::utils::safeDelete(m_typedConfigurations); - m_id = logger.m_id; - m_typedConfigurations = logger.m_typedConfigurations; - m_parentApplicationName = logger.m_parentApplicationName; - m_isConfigured = logger.m_isConfigured; - m_configurations = logger.m_configurations; - m_unflushedCount = logger.m_unflushedCount; - m_logStreamsReference = logger.m_logStreamsReference; -} - -Logger& Logger::operator=(const Logger& logger) { - if (&logger != this) { - base::utils::safeDelete(m_typedConfigurations); - m_id = logger.m_id; - m_typedConfigurations = logger.m_typedConfigurations; - m_parentApplicationName = logger.m_parentApplicationName; - m_isConfigured = logger.m_isConfigured; - m_configurations = logger.m_configurations; - m_unflushedCount = logger.m_unflushedCount; - m_logStreamsReference = logger.m_logStreamsReference; - } - return *this; -} - -void Logger::configure(const Configurations& configurations) { - m_isConfigured = false; // we set it to false in case if we fail - initUnflushedCount(); - if (m_typedConfigurations != nullptr) { - Configurations* c = const_cast(m_typedConfigurations->configurations()); - if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) { - flush(); - } - } - base::threading::ScopedLock scopedLock(lock()); - if (m_configurations != configurations) { - m_configurations.setFromBase(const_cast(&configurations)); - } - base::utils::safeDelete(m_typedConfigurations); - m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference); - resolveLoggerFormatSpec(); - m_isConfigured = true; -} - -void Logger::reconfigure(void) { - ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]"); - configure(m_configurations); -} - -bool Logger::isValidId(const std::string& id) { - for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) { - if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) { - return false; - } - } - return true; -} - -void Logger::flush(void) { - ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels"); - base::threading::ScopedLock scopedLock(lock()); - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - flush(LevelHelper::castFromInt(lIndex), nullptr); - return false; - }); -} - -void Logger::flush(Level level, base::type::fstream_t* fs) { - if (fs == nullptr && m_typedConfigurations->toFile(level)) { - fs = m_typedConfigurations->fileStream(level); - } - if (fs != nullptr) { - fs->flush(); - std::unordered_map::iterator iter = m_unflushedCount.find(level); - if (iter != m_unflushedCount.end()) { - iter->second = 0; - } - Helpers::validateFileRolling(this, level); - } -} - -void Logger::initUnflushedCount(void) { - m_unflushedCount.clear(); - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0)); - return false; - }); -} - -void Logger::resolveLoggerFormatSpec(void) const { - base::type::EnumType lIndex = LevelHelper::kMinValid; - LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { - base::LogFormat* logFormat = - const_cast(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex))); - base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id); - return false; - }); -} - -// el::base -namespace base { - -// el::base::utils -namespace utils { - -// File - -base::type::fstream_t* File::newFileStream(const std::string& filename) { - base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), - base::type::fstream_t::out -#if !defined(ELPP_FRESH_LOG_FILE) - | base::type::fstream_t::app -#endif - ); -#if defined(ELPP_UNICODE) - std::locale elppUnicodeLocale(""); -# if ELPP_OS_WINDOWS - std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16); - elppUnicodeLocale = elppUnicodeLocaleWindows; -# endif // ELPP_OS_WINDOWS - fs->imbue(elppUnicodeLocale); -#endif // defined(ELPP_UNICODE) - if (fs->is_open()) { - fs->flush(); - } else { - base::utils::safeDelete(fs); - ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true); - } - return fs; -} - -std::size_t File::getSizeOfFile(base::type::fstream_t* fs) { - if (fs == nullptr) { - return 0; - } - // Since the file stream is appended to or truncated, the current - // offset is the file size. - std::size_t size = static_cast(fs->tellg()); - return size; -} - -bool File::pathExists(const char* path, bool considerFile) { - if (path == nullptr) { - return false; - } -#if ELPP_OS_UNIX - ELPP_UNUSED(considerFile); - struct stat st; - return (stat(path, &st) == 0); -#elif ELPP_OS_WINDOWS - DWORD fileType = GetFileAttributesA(path); - if (fileType == INVALID_FILE_ATTRIBUTES) { - return false; - } - return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true); -#endif // ELPP_OS_UNIX -} - -bool File::createPath(const std::string& path) { - if (path.empty()) { - return false; - } - if (base::utils::File::pathExists(path.c_str())) { - return true; - } - int status = -1; - - char* currPath = const_cast(path.c_str()); - std::string builtPath = std::string(); -#if ELPP_OS_UNIX - if (path[0] == '/') { - builtPath = "/"; - } - currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0); -#elif ELPP_OS_WINDOWS - // Use secure functions API - char* nextTok_ = nullptr; - currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_); - ELPP_UNUSED(nextTok_); -#endif // ELPP_OS_UNIX - while (currPath != nullptr) { - builtPath.append(currPath); - builtPath.append(base::consts::kFilePathSeperator); -#if ELPP_OS_UNIX - status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS); - currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0); -#elif ELPP_OS_WINDOWS - status = _mkdir(builtPath.c_str()); - currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_); -#endif // ELPP_OS_UNIX - } - if (status == -1) { - ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true); - return false; - } - return true; -} - -std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) { - if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) { - return fullPath; - } - std::size_t lastSlashAt = fullPath.find_last_of(separator); - if (lastSlashAt == 0) { - return std::string(separator); - } - return fullPath.substr(0, lastSlashAt + 1); -} - -void File::buildStrippedFilename(const char* filename, char buff[], const std::string &commonPrefix, std::size_t limit) { - if (!commonPrefix.empty()) { - if (!strncmp(filename, commonPrefix.c_str(), commonPrefix.size())) - filename += commonPrefix.size(); - } - std::size_t sizeOfFilename = strlen(filename); - if (sizeOfFilename >= limit) { - filename += (sizeOfFilename - limit); - if (filename[0] != '.' && filename[1] != '.') { // prepend if not already - filename += 3; // 3 = '..' - STRCAT(buff, "..", limit); - } - } - STRCAT(buff, filename, limit); -} - -void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) { - const char *filename = fullPath.c_str(); - std::size_t lastSlashAt = fullPath.find_last_of(separator); - filename += lastSlashAt ? lastSlashAt+1 : 0; - std::size_t sizeOfFilename = strlen(filename); - if (sizeOfFilename >= limit) { - filename += (sizeOfFilename - limit); - if (filename[0] != '.' && filename[1] != '.') { // prepend if not already - filename += 3; // 3 = '..' - STRCAT(buff, "..", limit); - } - } - STRCAT(buff, filename, limit); -} - -// Str - -bool Str::wildCardMatch(const char* str, const char* pattern) { - while (*pattern) { - switch (*pattern) { - case '?': - if (!*str) - return false; - ++str; - ++pattern; - break; - case '*': - if (wildCardMatch(str, pattern + 1)) - return true; - if (*str && wildCardMatch(str + 1, pattern)) - return true; - return false; - default: - if (*str++ != *pattern++) - return false; - break; - } - } - return !*str && !*pattern; -} - -std::string& Str::ltrim(std::string& str) { - str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) { - return !std::isspace(c); - } )); - return str; -} - -std::string& Str::rtrim(std::string& str) { - str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) { - return !std::isspace(c); - }).base(), str.end()); - return str; -} - -std::string& Str::trim(std::string& str) { - return ltrim(rtrim(str)); -} - -bool Str::startsWith(const std::string& str, const std::string& start) { - return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0); -} - -bool Str::endsWith(const std::string& str, const std::string& end) { - return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0); -} - -std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) { - std::replace(str.begin(), str.end(), replaceWhat, replaceWith); - return str; -} - -std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat, - const std::string& replaceWith) { - if (replaceWhat == replaceWith) - return str; - std::size_t foundAt = std::string::npos; - while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) { - str.replace(foundAt, replaceWhat.length(), replaceWith); - } - return str; -} - -void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const base::type::string_t& replaceWith) { - std::size_t foundAt = base::type::string_t::npos; - while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) { - if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) { - str.erase(foundAt - 1, 1); - ++foundAt; - } else { - str.replace(foundAt, replaceWhat.length(), replaceWith); - return; - } - } -} -#if defined(ELPP_UNICODE) -void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const std::string& replaceWith) { - replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end())); -} -#endif // defined(ELPP_UNICODE) - -std::string& Str::toUpper(std::string& str) { - std::transform(str.begin(), str.end(), str.begin(), - [](char c) { - return static_cast(::toupper(c)); - }); - return str; -} - -bool Str::cStringEq(const char* s1, const char* s2) { - if (s1 == nullptr && s2 == nullptr) return true; - if (s1 == nullptr || s2 == nullptr) return false; - return strcmp(s1, s2) == 0; -} - -bool Str::cStringCaseEq(const char* s1, const char* s2) { - if (s1 == nullptr && s2 == nullptr) return true; - if (s1 == nullptr || s2 == nullptr) return false; - - // With thanks to cygwin for this code - int d = 0; - - while (true) { - const int c1 = toupper(*s1++); - const int c2 = toupper(*s2++); - - if (((d = c1 - c2) != 0) || (c2 == '\0')) { - break; - } - } - - return d == 0; -} - -bool Str::contains(const char* str, char c) { - for (; *str; ++str) { - if (*str == c) - return true; - } - return false; -} - -char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) { - char localBuff[10] = ""; - char* p = localBuff + sizeof(localBuff) - 2; - if (n > 0) { - for (; n > 0 && p > localBuff && len > 0; n /= 10, --len) - *--p = static_cast(n % 10 + '0'); - } else { - *--p = '0'; - --len; - } - if (zeroPadded) - while (p > localBuff && len-- > 0) *--p = static_cast('0'); - return addToBuff(p, buf, bufLim); -} - -char* Str::addToBuff(const char* str, char* buf, const char* bufLim) { - while ((buf < bufLim) && ((*buf = *str++) != '\0')) - ++buf; - return buf; -} - -char* Str::clearBuff(char buff[], std::size_t lim) { - STRCPY(buff, "", lim); - ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro - return buff; -} - -/// @brief Converst wchar* to char* -/// NOTE: Need to free return value after use! -char* Str::wcharPtrToCharPtr(const wchar_t* line) { - std::size_t len_ = wcslen(line) + 1; - char* buff_ = static_cast(malloc(len_ + 1)); -# if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) - std::wcstombs(buff_, line, len_); -# elif ELPP_OS_WINDOWS - std::size_t convCount_ = 0; - mbstate_t mbState_; - ::memset(static_cast(&mbState_), 0, sizeof(mbState_)); - wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_); -# endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) - return buff_; -} - -// OS - -#if ELPP_OS_WINDOWS -/// @brief Gets environment variables for Windows based OS. -/// We are not using getenv(const char*) because of CRT deprecation -/// @param varname Variable name to get environment variable value for -/// @return If variable exist the value of it otherwise nullptr -const char* OS::getWindowsEnvironmentVariable(const char* varname) { - const DWORD bufferLen = 50; - static char buffer[bufferLen]; - if (GetEnvironmentVariableA(varname, buffer, bufferLen)) { - return buffer; - } - return nullptr; -} -#endif // ELPP_OS_WINDOWS -#if ELPP_OS_ANDROID -std::string OS::getProperty(const char* prop) { - char propVal[PROP_VALUE_MAX + 1]; - int ret = __system_property_get(prop, propVal); - return ret == 0 ? std::string() : std::string(propVal); -} - -std::string OS::getDeviceName(void) { - std::stringstream ss; - std::string manufacturer = getProperty("ro.product.manufacturer"); - std::string model = getProperty("ro.product.model"); - if (manufacturer.empty() || model.empty()) { - return std::string(); - } - ss << manufacturer << "-" << model; - return ss.str(); -} -#endif // ELPP_OS_ANDROID - -const std::string OS::getBashOutput(const char* command) { -#if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) - if (command == nullptr) { - return std::string(); - } - FILE* proc = nullptr; - if ((proc = popen(command, "r")) == nullptr) { - ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true); - return std::string(); - } - char hBuff[4096]; - if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) { - pclose(proc); - const std::size_t buffLen = strlen(hBuff); - if (buffLen > 0 && hBuff[buffLen - 1] == '\n') { - hBuff[buffLen- 1] = '\0'; - } - return std::string(hBuff); - } else { - pclose(proc); - } - return std::string(); -#else - ELPP_UNUSED(command); - return std::string(); -#endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) -} - -std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal, - const char* alternativeBashCommand) { -#if ELPP_OS_UNIX - const char* val = getenv(variableName); -#elif ELPP_OS_WINDOWS - const char* val = getWindowsEnvironmentVariable(variableName); -#endif // ELPP_OS_UNIX - if ((val == nullptr) || ((strcmp(val, "") == 0))) { -#if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) - // Try harder on unix-based systems - std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand); - if (valBash.empty()) { - return std::string(defaultVal); - } else { - return valBash; - } -#elif ELPP_OS_WINDOWS || ELPP_OS_UNIX - ELPP_UNUSED(alternativeBashCommand); - return std::string(defaultVal); -#endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) - } - return std::string(val); -} - -std::string OS::currentUser(void) { -#if ELPP_OS_UNIX && !ELPP_OS_ANDROID - return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami"); -#elif ELPP_OS_WINDOWS - return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser); -#elif ELPP_OS_ANDROID - ELPP_UNUSED(base::consts::kUnknownUser); - return std::string("android"); -#else - return std::string(); -#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID -} - -std::string OS::currentHost(void) { -#if ELPP_OS_UNIX && !ELPP_OS_ANDROID - return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname"); -#elif ELPP_OS_WINDOWS - return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost); -#elif ELPP_OS_ANDROID - ELPP_UNUSED(base::consts::kUnknownHost); - return getDeviceName(); -#else - return std::string(); -#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID -} - -bool OS::termSupportsColor(void) { - std::string term = getEnvironmentVariable("TERM", ""); - return term == "xterm" || term == "xterm-color" || term == "xterm-256color" - || term == "screen" || term == "linux" || term == "cygwin" - || term == "tmux" || term == "tmux-256color" - || term == "screen-256color" || term == "screen.xterm-256color"; -} - -// DateTime - -void DateTime::gettimeofday(struct timeval* tv) { -#if ELPP_OS_WINDOWS - if (tv != nullptr) { -# if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) - const unsigned __int64 delta_ = 11644473600000000Ui64; -# else - const unsigned __int64 delta_ = 11644473600000000ULL; -# endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) - const double secOffSet = 0.000001; - const unsigned long usecOffSet = 1000000; - FILETIME fileTime; - GetSystemTimeAsFileTime(&fileTime); - unsigned __int64 present = 0; - present |= fileTime.dwHighDateTime; - present = present << 32; - present |= fileTime.dwLowDateTime; - present /= 10; // mic-sec - // Subtract the difference - present -= delta_; - tv->tv_sec = static_cast(present * secOffSet); - tv->tv_usec = static_cast(present % usecOffSet); - } -#else - ::gettimeofday(tv, nullptr); -#endif // ELPP_OS_WINDOWS -} - -std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) { - struct timeval currTime; - gettimeofday(&currTime); - return timevalToString(currTime, format, ssPrec); -} - -std::string DateTime::timevalToString(struct timeval tval, const char* format, - const el::base::SubsecondPrecision* ssPrec) { - struct ::tm timeInfo; - buildTimeInfo(&tval, &timeInfo); - const int kBuffSize = 30; - char buff_[kBuffSize] = ""; - parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast(tval.tv_usec / ssPrec->m_offset), - ssPrec); - return std::string(buff_); -} - -base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) { - base::type::EnumType start = static_cast(timestampUnit); - const base::type::char_t* unit = base::consts::kTimeFormats[start].unit; - for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) { - if (time <= base::consts::kTimeFormats[i].value) { - break; - } - if (base::consts::kTimeFormats[i].value == 1000.0f && time / 1000.0f < 1.9f) { - break; - } - time /= static_cast(base::consts::kTimeFormats[i].value); - unit = base::consts::kTimeFormats[i + 1].unit; - } - base::type::stringstream_t ss; - ss << time << " " << unit; - return ss.str(); -} - -unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, - base::TimestampUnit timestampUnit) { - if (timestampUnit == base::TimestampUnit::Microsecond) { - return static_cast(static_cast(1000000 * endTime.tv_sec + endTime.tv_usec) - - static_cast(1000000 * startTime.tv_sec + startTime.tv_usec)); - } - // milliseconds - auto conv = [](const struct timeval& tim) { - return static_cast((tim.tv_sec * 1000) + (tim.tv_usec / 1000)); - }; - return static_cast(conv(endTime) - conv(startTime)); -} - -struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) { -#if ELPP_OS_UNIX - time_t rawTime = currTime->tv_sec; - ::elpptime_r(&rawTime, timeInfo); - return timeInfo; -#else -# if ELPP_COMPILER_MSVC - ELPP_UNUSED(currTime); - time_t t; -# if defined(_USE_32BIT_TIME_T) - _time32(&t); -# else - _time64(&t); -# endif - elpptime_s(timeInfo, &t); - return timeInfo; -# else - // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method - time_t rawTime = currTime->tv_sec; - struct tm* tmInf = elpptime(&rawTime); - *timeInfo = *tmInf; - return timeInfo; -# endif // ELPP_COMPILER_MSVC -#endif // ELPP_OS_UNIX -} - -char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, - std::size_t msec, const base::SubsecondPrecision* ssPrec) { - const char* bufLim = buf + bufSz; - for (; *format; ++format) { - if (*format == base::consts::kFormatSpecifierChar) { - switch (*++format) { - case base::consts::kFormatSpecifierChar: // Escape - break; - case '\0': // End - --format; - break; - case 'd': // Day - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim); - continue; - case 'a': // Day of week (short) - buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim); - continue; - case 'A': // Day of week (long) - buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim); - continue; - case 'M': // month - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim); - continue; - case 'b': // month (short) - buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim); - continue; - case 'B': // month (long) - buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim); - continue; - case 'y': // year (two digits) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim); - continue; - case 'Y': // year (four digits) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim); - continue; - case 'h': // hour (12-hour) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim); - continue; - case 'H': // hour (24-hour) - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim); - continue; - case 'm': // minute - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim); - continue; - case 's': // second - buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim); - continue; - case 'z': // subsecond part - case 'g': - buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->m_width, buf, bufLim); - continue; - case 'F': // AM/PM - buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim); - continue; - default: - continue; - } - } - if (buf == bufLim) break; - *buf++ = *format; - } - return buf; -} - -// CommandLineArgs - -void CommandLineArgs::setArgs(int argc, char** argv) { - m_params.clear(); - m_paramsWithValue.clear(); - if (argc == 0 || argv == nullptr) { - return; - } - m_argc = argc; - m_argv = argv; - for (int i = 1; i < m_argc; ++i) { - const char* v = (strstr(m_argv[i], "=")); - if (v != nullptr && strlen(v) > 0) { - std::string key = std::string(m_argv[i]); - key = key.substr(0, key.find_first_of('=')); - if (hasParamWithValue(key.c_str())) { - ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value [" - << getParamValue(key.c_str()) << "]"); - } else { - m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1))); - } - } - if (v == nullptr) { - if (hasParam(m_argv[i])) { - ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists"); - } else { - m_params.push_back(std::string(m_argv[i])); - } - } - } -} - -bool CommandLineArgs::hasParamWithValue(const char* paramKey) const { - return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end(); -} - -const char* CommandLineArgs::getParamValue(const char* paramKey) const { - std::unordered_map::const_iterator iter = m_paramsWithValue.find(std::string(paramKey)); - return iter != m_paramsWithValue.end() ? iter->second.c_str() : ""; -} - -bool CommandLineArgs::hasParam(const char* paramKey) const { - return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end(); -} - -bool CommandLineArgs::empty(void) const { - return m_params.empty() && m_paramsWithValue.empty(); -} - -std::size_t CommandLineArgs::size(void) const { - return m_params.size() + m_paramsWithValue.size(); -} - -base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) { - for (int i = 1; i < c.m_argc; ++i) { - os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]"); - if (i < c.m_argc - 1) { - os << ELPP_LITERAL(" "); - } - } - return os; -} - -} // namespace utils - -// el::base::threading -namespace threading { - -#if ELPP_THREADING_ENABLED -# if ELPP_USE_STD_THREADING -# if ELPP_ASYNC_LOGGING -static void msleep(int ms) { - // Only when async logging enabled - this is because async is strict on compiler -# if defined(ELPP_NO_SLEEP_FOR) - usleep(ms * 1000); -# else - std::this_thread::sleep_for(std::chrono::milliseconds(ms)); -# endif // defined(ELPP_NO_SLEEP_FOR) -} -# endif // ELPP_ASYNC_LOGGING -# endif // !ELPP_USE_STD_THREADING -#endif // ELPP_THREADING_ENABLED - -} // namespace threading - -// el::base - -// SubsecondPrecision - -void SubsecondPrecision::init(int width) { - if (width < 1 || width > 6) { - width = base::consts::kDefaultSubsecondPrecision; - } - m_width = width; - switch (m_width) { - case 3: - m_offset = 1000; - break; - case 4: - m_offset = 100; - break; - case 5: - m_offset = 10; - break; - case 6: - m_offset = 1; - break; - default: - m_offset = 1000; - break; - } -} - -// LogFormat - -LogFormat::LogFormat(void) : - m_level(Level::Unknown), - m_userFormat(base::type::string_t()), - m_format(base::type::string_t()), - m_dateTimeFormat(std::string()), - m_flags(0x0), - m_currentUser(base::utils::OS::currentUser()), - m_currentHost(base::utils::OS::currentHost()) { -} - -LogFormat::LogFormat(Level level, const base::type::string_t& format) - : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()), - m_currentHost(base::utils::OS::currentHost()) { - parseFromFormat(m_userFormat); -} - -LogFormat::LogFormat(const LogFormat& logFormat): - m_level(logFormat.m_level), - m_userFormat(logFormat.m_userFormat), - m_format(logFormat.m_format), - m_dateTimeFormat(logFormat.m_dateTimeFormat), - m_flags(logFormat.m_flags), - m_currentUser(logFormat.m_currentUser), - m_currentHost(logFormat.m_currentHost) { -} - -LogFormat::LogFormat(LogFormat&& logFormat) { - m_level = std::move(logFormat.m_level); - m_userFormat = std::move(logFormat.m_userFormat); - m_format = std::move(logFormat.m_format); - m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat); - m_flags = std::move(logFormat.m_flags); - m_currentUser = std::move(logFormat.m_currentUser); - m_currentHost = std::move(logFormat.m_currentHost); -} - -LogFormat& LogFormat::operator=(const LogFormat& logFormat) { - if (&logFormat != this) { - m_level = logFormat.m_level; - m_userFormat = logFormat.m_userFormat; - m_dateTimeFormat = logFormat.m_dateTimeFormat; - m_flags = logFormat.m_flags; - m_currentUser = logFormat.m_currentUser; - m_currentHost = logFormat.m_currentHost; - } - return *this; -} - -bool LogFormat::operator==(const LogFormat& other) { - return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format && - m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags; -} - -/// @brief Updates format to be used while logging. -/// @param userFormat User provided format -void LogFormat::parseFromFormat(const base::type::string_t& userFormat) { - // We make copy because we will be changing the format - // i.e, removing user provided date format from original format - // and then storing it. - base::type::string_t formatCopy = userFormat; - m_flags = 0x0; - auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) { - std::size_t foundAt = base::type::string_t::npos; - while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) { - if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) { - if (hasFlag(flag)) { - // If we already have flag we remove the escape chars so that '%%' is turned to '%' - // even after specifier resolution - this is because we only replaceFirst specifier - formatCopy.erase(foundAt - 1, 1); - ++foundAt; - } - } else { - if (!hasFlag(flag)) addFlag(flag); - } - } - }; - conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName); - conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level); - conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort); - conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId); - conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId); - conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File); - conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase); - conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line); - conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location); - conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function); - conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User); - conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host); - conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage); - conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel); - // For date/time we need to extract user's date format first - std::size_t dateIndex = std::string::npos; - if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) { - while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) { - dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1); - } - if (dateIndex != std::string::npos) { - addFlag(base::FormatFlags::DateTime); - updateDateFormat(dateIndex, formatCopy); - } - } - m_format = formatCopy; - updateFormatSpec(); -} - -void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) { - if (hasFlag(base::FormatFlags::DateTime)) { - index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier); - } - const base::type::char_t* ptr = currFormat.c_str() + index; - if ((currFormat.size() > index) && (ptr[0] == '{')) { - // User has provided format for date/time - ++ptr; - int count = 1; // Start by 1 in order to remove starting brace - std::stringstream ss; - for (; *ptr; ++ptr, ++count) { - if (*ptr == '}') { - ++count; // In order to remove ending brace - break; - } - ss << static_cast(*ptr); - } - currFormat.erase(index, count); - m_dateTimeFormat = ss.str(); - } else { - // No format provided, use default - if (hasFlag(base::FormatFlags::DateTime)) { - m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat); - } - } -} - -void LogFormat::updateFormatSpec(void) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (m_level == Level::Debug) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kDebugLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kDebugLevelShortLogValue); - } else if (m_level == Level::Info) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kInfoLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kInfoLevelShortLogValue); - } else if (m_level == Level::Warning) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kWarningLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kWarningLevelShortLogValue); - } else if (m_level == Level::Error) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kErrorLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kErrorLevelShortLogValue); - } else if (m_level == Level::Fatal) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kFatalLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kFatalLevelShortLogValue); - } else if (m_level == Level::Verbose) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kVerboseLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kVerboseLevelShortLogValue); - } else if (m_level == Level::Trace) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, - base::consts::kTraceLevelLogValue); - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, - base::consts::kTraceLevelShortLogValue); - } - if (hasFlag(base::FormatFlags::User)) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier, - m_currentUser); - } - if (hasFlag(base::FormatFlags::Host)) { - base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier, - m_currentHost); - } - // Ignore Level::Global and Level::Unknown -} - -// TypedConfigurations - -TypedConfigurations::TypedConfigurations(Configurations* configurations, - base::LogStreamsReferenceMap* logStreamsReference) { - m_configurations = configurations; - m_logStreamsReference = logStreamsReference; - build(m_configurations); -} - -TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) { - this->m_configurations = other.m_configurations; - this->m_logStreamsReference = other.m_logStreamsReference; - build(m_configurations); -} - -bool TypedConfigurations::enabled(Level level) { - return getConfigByVal(level, &m_enabledMap, "enabled"); -} - -bool TypedConfigurations::toFile(Level level) { - return getConfigByVal(level, &m_toFileMap, "toFile"); -} - -const std::string& TypedConfigurations::filename(Level level) { - return getConfigByRef(level, &m_filenameMap, "filename"); -} - -bool TypedConfigurations::toStandardOutput(Level level) { - return getConfigByVal(level, &m_toStandardOutputMap, "toStandardOutput"); -} - -const base::LogFormat& TypedConfigurations::logFormat(Level level) { - return getConfigByRef(level, &m_logFormatMap, "logFormat"); -} - -const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) { - return getConfigByRef(level, &m_subsecondPrecisionMap, "subsecondPrecision"); -} - -const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) { - return getConfigByRef(level, &m_subsecondPrecisionMap, "millisecondsWidth"); -} - -bool TypedConfigurations::performanceTracking(Level level) { - return getConfigByVal(level, &m_performanceTrackingMap, "performanceTracking"); -} - -base::type::fstream_t* TypedConfigurations::fileStream(Level level) { - return getConfigByRef(level, &m_fileStreamMap, "fileStream").get(); -} - -std::size_t TypedConfigurations::maxLogFileSize(Level level) { - return getConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); -} - -std::size_t TypedConfigurations::logFlushThreshold(Level level) { - return getConfigByVal(level, &m_logFlushThresholdMap, "logFlushThreshold"); -} - -void TypedConfigurations::build(Configurations* configurations) { - base::threading::ScopedLock scopedLock(lock()); - auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming - base::utils::Str::trim(boolStr); - return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1"); - }; - setValue(Level::Global, base::FileStreamPtr(NULL), &m_fileStreamMap); - std::vector withFileSizeLimit; - for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { - Configuration* conf = *it; - // We cannot use switch on strong enums because Intel C++ dont support them yet - if (conf->configurationType() == ConfigurationType::Enabled) { - setValue(conf->level(), getBool(conf->value()), &m_enabledMap); - } else if (conf->configurationType() == ConfigurationType::ToFile) { - setValue(conf->level(), getBool(conf->value()), &m_toFileMap); - } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) { - setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap); - } else if (conf->configurationType() == ConfigurationType::Filename) { - // We do not yet configure filename but we will configure in another - // loop. This is because if file cannot be created, we will force ToFile - // to be false. Because configuring logger is not necessarily performance - // sensative operation, we can live with another loop; (by the way this loop - // is not very heavy either) - } else if (conf->configurationType() == ConfigurationType::Format) { - setValue(conf->level(), base::LogFormat(conf->level(), - base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap); - } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) { - setValue(Level::Global, - base::SubsecondPrecision(static_cast(getULong(conf->value()))), &m_subsecondPrecisionMap); - } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) { - setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap); - } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) { - auto v = getULong(conf->value()); - setValue(conf->level(), static_cast(v), &m_maxLogFileSizeMap); - if (v != 0) { - withFileSizeLimit.push_back(conf); - } - } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) { - setValue(conf->level(), static_cast(getULong(conf->value())), &m_logFlushThresholdMap); - } - } - // As mentioned earlier, we will now set filename configuration in separate loop to deal with non-existent files - for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { - Configuration* conf = *it; - if (conf->configurationType() == ConfigurationType::Filename) { - insertFile(conf->level(), conf->value()); - } - } - for (std::vector::iterator conf = withFileSizeLimit.begin(); - conf != withFileSizeLimit.end(); ++conf) { - // This is not unsafe as mutex is locked in currect scope - unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback); - } -} - -unsigned long TypedConfigurations::getULong(std::string confVal) { - bool valid = true; - base::utils::Str::trim(confVal); - valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(), - [](char c) { - return !base::utils::Str::isDigit(c); - }) == confVal.end(); - if (!valid) { - valid = false; - ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]"); - return 0; - } - return atol(confVal.c_str()); -} - -std::string TypedConfigurations::resolveFilename(const std::string& filename) { - std::string resultingFilename = filename; - std::size_t dateIndex = std::string::npos; - std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename); - if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) { - while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) { - dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1); - } - if (dateIndex != std::string::npos) { - const char* ptr = resultingFilename.c_str() + dateIndex; - // Goto end of specifier - ptr += dateTimeFormatSpecifierStr.size(); - std::string fmt; - if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) { - // User has provided format for date/time - ++ptr; - int count = 1; // Start by 1 in order to remove starting brace - std::stringstream ss; - for (; *ptr; ++ptr, ++count) { - if (*ptr == '}') { - ++count; // In order to remove ending brace - break; - } - ss << *ptr; - } - resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count); - fmt = ss.str(); - } else { - fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename); - } - base::SubsecondPrecision ssPrec(3); - std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec); - base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename - base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now); - } - } - return resultingFilename; -} - -void TypedConfigurations::insertFile(Level level, const std::string& fullFilename) { - if (fullFilename.empty()) - return; - std::string resolvedFilename = resolveFilename(fullFilename); - if (resolvedFilename.empty()) { - std::cerr << "Could not load empty file for logging, please re-check your configurations for level [" - << LevelHelper::convertToString(level) << "]"; - } - std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator); - if (filePath.size() < resolvedFilename.size()) { - base::utils::File::createPath(filePath); - } - auto create = [&](Level level) { - base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename); - base::type::fstream_t* fs = nullptr; - if (filestreamIter == m_logStreamsReference->end()) { - // We need a completely new stream, nothing to share with - fs = base::utils::File::newFileStream(resolvedFilename); - m_filenameMap.insert(std::make_pair(level, resolvedFilename)); - m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs))); - m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level)))); - } else { - // Woops! we have an existing one, share it! - m_filenameMap.insert(std::make_pair(level, filestreamIter->first)); - m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second))); - fs = filestreamIter->second.get(); - } - if (fs == nullptr) { - // We display bad file error from newFileStream() - ELPP_INTERNAL_ERROR("Setting [TO_FILE] of [" - << LevelHelper::convertToString(level) << "] to FALSE", false); - setValue(level, false, &m_toFileMap); - } - }; - // If we dont have file conf for any level, create it for Level::Global first - // otherwise create for specified level - create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level); -} - -bool TypedConfigurations::unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) { - base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get(); - if (fs == nullptr) { - return true; - } - std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); - std::size_t currFileSize = base::utils::File::getSizeOfFile(fs); - if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) { - std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename"); - ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level [" - << LevelHelper::convertToString(level) << "]"); - fs->close(); - preRollOutCallback(fname.c_str(), currFileSize); - fs->open(fname, std::fstream::out | std::fstream::trunc); - return true; - } - return false; -} - -// RegisteredHitCounters - -bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - counter->validateHitCounts(n); - bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0); - return result; -} - -/// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one -/// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned -bool RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - // Do not use validateHitCounts here since we do not want to reset counter here - // Note the >= instead of > because we are incrementing - // after this check - if (counter->hitCounts() >= n) - return true; - counter->increment(); - return false; -} - -/// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one -/// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned -bool RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - base::threading::ScopedLock scopedLock(lock()); - base::HitCounter* counter = get(filename, lineNumber); - if (counter == nullptr) { - registerNew(counter = new base::HitCounter(filename, lineNumber)); - } - counter->increment(); - // Do not use validateHitCounts here since we do not want to reset counter here - if (counter->hitCounts() <= n) - return true; - return false; -} - -// RegisteredLoggers - -RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) : - m_defaultLogBuilder(defaultLogBuilder) { - m_defaultConfigurations.setToDefault(); -} - -Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) { - base::threading::ScopedLock scopedLock(lock()); - Logger* logger_ = base::utils::Registry::get(id); - if (logger_ == nullptr && forceCreation) { - bool validId = Logger::isValidId(id); - if (!validId) { - ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger."); - return nullptr; - } - logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference); - logger_->m_logBuilder = m_defaultLogBuilder; - registerNew(id, logger_); - LoggerRegistrationCallback* callback = nullptr; - for (const std::pair& h - : m_loggerRegistrationCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(logger_); - } - } - } - return logger_; -} - -bool RegisteredLoggers::remove(const std::string& id) { - if (id == base::consts::kDefaultLoggerId) { - return false; - } - // get has internal lock - Logger* logger = base::utils::Registry::get(id); - if (logger != nullptr) { - // unregister has internal lock - unregister(logger); - } - return true; -} - -void RegisteredLoggers::unsafeFlushAll(void) { - ELPP_INTERNAL_INFO(1, "Flushing all log files"); - for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin(); - it != m_logStreamsReference.end(); ++it) { - if (it->second.get() == nullptr) continue; - it->second->flush(); - } -} - -// VRegistry - -VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags), m_lowest_priority(INT_MAX) { -} - -/// @brief Sets verbose level. Accepted range is 0-9 -void VRegistry::setLevel(base::type::VerboseLevel level) { - base::threading::ScopedLock scopedLock(lock()); - if (level > 9) - m_level = base::consts::kMaxVerboseLevel; - else - m_level = level; -} - -void VRegistry::setModules(const char* modules) { - base::threading::ScopedLock scopedLock(lock()); - auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) { - if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) { - std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev))); - ss.str(std::string("")); - ss << chr; - } - if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) { - std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx))); - ss.str(std::string("")); - ss << chr; - } - ss << sfx; - }; - auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) { - if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) { - addSuffix(ss, ".h", nullptr); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".c", ".h"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cpp", ".c"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cc", ".cpp"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".cxx", ".cc"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".-inl.h", ".cxx"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hxx", ".-inl.h"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hpp", ".hxx"); - m_modules.insert(std::make_pair(ss.str(), level)); - addSuffix(ss, ".hh", ".hpp"); - } - m_modules.insert(std::make_pair(ss.str(), level)); - }; - bool isMod = true; - bool isLevel = false; - std::stringstream ss; - int level = -1; - for (; *modules; ++modules) { - switch (*modules) { - case '=': - isLevel = true; - isMod = false; - break; - case ',': - isLevel = false; - isMod = true; - if (!ss.str().empty() && level != -1) { - insert(ss, static_cast(level)); - ss.str(std::string("")); - level = -1; - } - break; - default: - if (isMod) { - ss << *modules; - } else if (isLevel) { - if (isdigit(*modules)) { - level = static_cast(*modules) - 48; - } - } - break; - } - } - if (!ss.str().empty() && level != -1) { - insert(ss, static_cast(level)); - } -} - -// Log levels are sorted in a weird way... -static int priority(Level level) { - if (level == Level::Fatal) return 0; - if (level == Level::Error) return 1; - if (level == Level::Warning) return 2; - if (level == Level::Info) return 3; - if (level == Level::Debug) return 4; - if (level == Level::Verbose) return 5; - if (level == Level::Trace) return 6; - return 7; -} - -void VRegistry::setCategories(const char* categories, bool clear) { - base::threading::ScopedLock scopedLock(lock()); - auto insert = [&](std::stringstream& ss, Level level) { - m_categories.push_back(std::make_pair(ss.str(), level)); - m_cached_allowed_categories.clear(); - int pri = priority(level); - if (pri > m_lowest_priority) - m_lowest_priority = pri; - }; - - if (clear) { - m_lowest_priority = 0; - m_categories.clear(); - m_cached_allowed_categories.clear(); - m_categoriesString.clear(); - } - if (!categories) - return; - if (!m_categoriesString.empty()) - m_categoriesString += ","; - m_categoriesString += categories; - - size_t n_fields = m_categories.size() + 1; - for (const char *ptr = categories; *ptr; ++ptr) - if (*ptr == ',') - ++n_fields; - m_categories.reserve(n_fields); - - bool isCat = true; - bool isLevel = false; - std::stringstream ss; - Level level = Level::Unknown; - for (; *categories; ++categories) { - switch (*categories) { - case ':': - isLevel = true; - isCat = false; - break; - case ',': - isLevel = false; - isCat = true; - if (!ss.str().empty() && level != Level::Unknown) { - insert(ss, level); - ss.str(std::string("")); - level = Level::Unknown; - } - break; - default: - if (isCat) { - ss << *categories; - } else if (isLevel) { - level = LevelHelper::convertFromStringPrefix(categories); - if (level != Level::Unknown) - categories += strlen(LevelHelper::convertToString(level)) - 1; - } - break; - } - } - if (!ss.str().empty() && level != Level::Unknown) { - insert(ss, level); - } -} - -std::string VRegistry::getCategories() { - base::threading::ScopedLock scopedLock(lock()); - return m_categoriesString; -} - -bool VRegistry::allowed(Level level, const std::string &category) { - const int pri = priority(level); - if (pri > m_lowest_priority) - return false; - base::threading::ScopedLock scopedLock(lock()); - const std::map::const_iterator it = m_cached_allowed_categories.find(category); - if (it != m_cached_allowed_categories.end()) - return pri <= it->second; - if (m_categories.empty()) { - return false; - } else { - std::vector>::const_reverse_iterator it = m_categories.rbegin(); - for (; it != m_categories.rend(); ++it) { - if (base::utils::Str::wildCardMatch(category.c_str(), it->first.c_str())) { - const int p = priority(it->second); - m_cached_allowed_categories.insert(std::make_pair(category, p)); - return pri <= p; - } - } - m_cached_allowed_categories.insert(std::make_pair(category, -1)); - return false; - } -} - -bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) { - base::threading::ScopedLock scopedLock(lock()); - if (m_modules.empty() || file == nullptr) { - return vlevel <= m_level; - } else { - char baseFilename[base::consts::kSourceFilenameMaxLength] = ""; - base::utils::File::buildBaseFilename(file, baseFilename); - std::unordered_map::iterator it = m_modules.begin(); - for (; it != m_modules.end(); ++it) { - if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) { - return vlevel <= it->second; - } - } - if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) { - return true; - } - return false; - } -} - -void VRegistry::setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) { - if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") || - commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) { - setLevel(base::consts::kMaxVerboseLevel); - } else if (commandLineArgs->hasParamWithValue("--v")) { - setLevel(static_cast(atoi(commandLineArgs->getParamValue("--v")))); - } else if (commandLineArgs->hasParamWithValue("--V")) { - setLevel(static_cast(atoi(commandLineArgs->getParamValue("--V")))); - } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) { - setModules(commandLineArgs->getParamValue("-vmodule")); - } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) { - setModules(commandLineArgs->getParamValue("-VMODULE")); - } -} - -#if !defined(ELPP_DEFAULT_LOGGING_FLAGS) -# define ELPP_DEFAULT_LOGGING_FLAGS 0x0 -#endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS) -// Storage -el::base::type::StoragePointer &el::base::Storage::getELPP() -{ - if (!el::base::elStorage) - el::base::elStorage = new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder())); - return el::base::elStorage; -} -static struct EnsureELPP { EnsureELPP() { el::base::Storage::getELPP(); } } ensureELPP; -#if ELPP_ASYNC_LOGGING -Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) : -#else -Storage::Storage(const LogBuilderPtr& defaultLogBuilder) : -#endif // ELPP_ASYNC_LOGGING - m_registeredHitCounters(new base::RegisteredHitCounters()), - m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)), - m_flags(ELPP_DEFAULT_LOGGING_FLAGS), - m_vRegistry(new base::VRegistry(0, &m_flags)), - -#if ELPP_ASYNC_LOGGING - m_asyncLogQueue(new base::AsyncLogQueue()), - m_asyncDispatchWorker(asyncDispatchWorker), -#endif // ELPP_ASYNC_LOGGING - - m_preRollOutCallback(base::defaultPreRollOutCallback) { - // Register default logger - m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId)); - // We register default logger anyway (worse case it's not going to register) just in case - m_registeredLoggers->get("default"); - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - // Register performance logger and reconfigure format - Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId)); - m_registeredLoggers->get("performance"); - performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg")); - performanceLogger->reconfigure(); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -#if defined(ELPP_SYSLOG) - // Register syslog logger and reconfigure format - Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId)); - sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg")); - sysLogLogger->reconfigure(); -#endif // defined(ELPP_SYSLOG) - addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified); - addFlag(LoggingFlag::CreateLoggerAutomatically); -#if ELPP_ASYNC_LOGGING - installLogDispatchCallback(std::string("AsyncLogDispatchCallback")); -#else - installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); -#endif // ELPP_ASYNC_LOGGING -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - installPerformanceTrackingCallback - (std::string("DefaultPerformanceTrackingCallback")); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized"); -#if ELPP_ASYNC_LOGGING - m_asyncDispatchWorker->start(); -#endif // ELPP_ASYNC_LOGGING -} - -Storage::~Storage(void) { - ELPP_INTERNAL_INFO(4, "Destroying storage"); -#if ELPP_ASYNC_LOGGING - ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous"); - uninstallLogDispatchCallback(std::string("AsyncLogDispatchCallback")); - installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); - ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker"); - base::utils::safeDelete(m_asyncDispatchWorker); - ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue"); - base::utils::safeDelete(m_asyncLogQueue); -#endif // ELPP_ASYNC_LOGGING - ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters"); - base::utils::safeDelete(m_registeredHitCounters); - ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers"); - base::utils::safeDelete(m_registeredLoggers); - ELPP_INTERNAL_INFO(5, "Destroying vRegistry"); - base::utils::safeDelete(m_vRegistry); -} - -bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) { - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(), - formatSpecifier) != m_customFormatSpecifiers.end(); -} - -void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { - if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) { - return; - } - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - m_customFormatSpecifiers.push_back(customFormatSpecifier); -} - -bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) { - base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); - std::vector::iterator it = std::find(m_customFormatSpecifiers.begin(), - m_customFormatSpecifiers.end(), formatSpecifier); - if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) { - m_customFormatSpecifiers.erase(it); - return true; - } - return false; -} - -void Storage::setApplicationArguments(int argc, char** argv) { - m_commandLineArgs.setArgs(argc, argv); - m_vRegistry->setFromArgs(commandLineArgs()); - // default log file -#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) - if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) { - Configurations c; - c.setGlobally(ConfigurationType::Filename, - std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam))); - registeredLoggers()->setDefaultConfigurations(c); - for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin(); - it != registeredLoggers()->end(); ++it) { - it->second->configure(c); - } - } -#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) -#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) - if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) { - int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam)); - if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) { - m_flags = userInput; - } else { - base::utils::addFlag(userInput, &m_flags); - } - } -#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) -} - -} // namespace base - -// LogDispatchCallback -void LogDispatchCallback::handle(const LogDispatchData* data) { -#if defined(ELPP_THREAD_SAFE) - base::threading::ScopedLock scopedLock(m_fileLocksMapLock); - std::string filename = data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level()); - auto lock = m_fileLocks.find(filename); - if (lock == m_fileLocks.end()) { - m_fileLocks.emplace(std::make_pair(filename, std::unique_ptr(new base::threading::Mutex))); - } -#endif -} - -base::threading::Mutex& LogDispatchCallback::fileHandle(const LogDispatchData* data) { - auto it = m_fileLocks.find(data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level())); - return *(it->second.get()); -} - -namespace base { -// DefaultLogDispatchCallback - -const char* convertToChar(Level level) { - // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. - if (level == Level::Global) return "G"; - if (level == Level::Debug) return "D"; - if (level == Level::Info) return "I"; - if (level == Level::Warning) return "W"; - if (level == Level::Error) return "E"; - if (level == Level::Fatal) return "F"; - if (level == Level::Verbose) return "V"; - if (level == Level::Trace) return "T"; - return "?"; -} - -void DefaultLogDispatchCallback::handle(const LogDispatchData* data) { -#if defined(ELPP_THREAD_SAFE) -#if 0 - LogDispatchCallback::handle(data); - base::threading::ScopedLock scopedLock(fileHandle(data)); -#endif -#endif - m_data = data; - base::TypedConfigurations* tc = m_data->logMessage()->logger()->typedConfigurations(); - const base::LogFormat* logFormat = &tc->logFormat(m_data->logMessage()->level()); - dispatch(base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), &tc->subsecondPrecision(m_data->logMessage()->level())) - + "\t" + convertToChar(m_data->logMessage()->level()) + " " + m_data->logMessage()->message() + "\n", - m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(), - m_data->dispatchAction() == base::DispatchAction::NormalLog || m_data->dispatchAction() == base::DispatchAction::FileOnlyLog)); -} - -void DefaultLogDispatchCallback::dispatch(base::type::string_t&& rawLine, base::type::string_t&& logLine) { - if (m_data->dispatchAction() == base::DispatchAction::NormalLog || m_data->dispatchAction() == base::DispatchAction::FileOnlyLog) { - if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) { - base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream( - m_data->logMessage()->level()); - if (fs != nullptr) { - fs->write(logLine.c_str(), logLine.size()); - if (fs->fail()) { - ELPP_INTERNAL_ERROR("Unable to write log to file [" - << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n" - << "Few possible reasons (could be something else):\n" << " * Permission denied\n" - << " * Disk full\n" << " * Disk is not writable", true); - } else { - if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) - || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) { - m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs); - } - } - } else { - ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] " - << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " - << m_data->logMessage()->logger()->id() << "]", false); - } - } - if (m_data->dispatchAction() != base::DispatchAction::FileOnlyLog) { - if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) { - if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) - m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&rawLine, m_data->logMessage()->level()); - ELPP_COUT << ELPP_COUT_LINE(rawLine); - } - } - } -#if defined(ELPP_SYSLOG) - else if (m_data->dispatchAction() == base::DispatchAction::SysLog) { - // Determine syslog priority - int sysLogPriority = 0; - if (m_data->logMessage()->level() == Level::Fatal) - sysLogPriority = LOG_EMERG; - else if (m_data->logMessage()->level() == Level::Error) - sysLogPriority = LOG_ERR; - else if (m_data->logMessage()->level() == Level::Warning) - sysLogPriority = LOG_WARNING; - else if (m_data->logMessage()->level() == Level::Info) - sysLogPriority = LOG_INFO; - else if (m_data->logMessage()->level() == Level::Debug) - sysLogPriority = LOG_DEBUG; - else - sysLogPriority = LOG_NOTICE; -# if defined(ELPP_UNICODE) - char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); - syslog(sysLogPriority, "%s", line); - free(line); -# else - syslog(sysLogPriority, "%s", logLine.c_str()); -# endif - } -#endif // defined(ELPP_SYSLOG) -} - -#if ELPP_ASYNC_LOGGING - -// AsyncLogDispatchCallback - -void AsyncLogDispatchCallback::handle(const LogDispatchData* data) { - base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(), - data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog); - if ((data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog) - && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) { - if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) - data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level()); - ELPP_COUT << ELPP_COUT_LINE(logLine); - } - // Save resources and only queue if we want to write to file otherwise just ignore handler - if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) { - ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine)); - } -} - -// AsyncDispatchWorker -AsyncDispatchWorker::AsyncDispatchWorker() { - setContinueRunning(false); -} - -AsyncDispatchWorker::~AsyncDispatchWorker() { - setContinueRunning(false); - ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue"); - clean(); - ELPP_INTERNAL_INFO(6, "Log queue cleaned"); -} - -bool AsyncDispatchWorker::clean(void) { - std::mutex m; - std::unique_lock lk(m); - cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); }); - emptyQueue(); - lk.unlock(); - cv.notify_one(); - return ELPP->asyncLogQueue()->empty(); -} - -void AsyncDispatchWorker::emptyQueue(void) { - while (!ELPP->asyncLogQueue()->empty()) { - AsyncLogItem data = ELPP->asyncLogQueue()->next(); - handle(&data); - base::threading::msleep(100); - } -} - -void AsyncDispatchWorker::start(void) { - base::threading::msleep(5000); // 5s (why?) - setContinueRunning(true); - std::thread t1(&AsyncDispatchWorker::run, this); - t1.join(); -} - -void AsyncDispatchWorker::handle(AsyncLogItem* logItem) { - LogDispatchData* data = logItem->data(); - LogMessage* logMessage = logItem->logMessage(); - Logger* logger = logMessage->logger(); - base::TypedConfigurations* conf = logger->typedConfigurations(); - base::type::string_t logLine = logItem->logLine(); - if (data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog) { - if (conf->toFile(logMessage->level())) { - base::type::fstream_t* fs = conf->fileStream(logMessage->level()); - if (fs != nullptr) { - fs->write(logLine.c_str(), logLine.size()); - if (fs->fail()) { - ELPP_INTERNAL_ERROR("Unable to write log to file [" - << conf->filename(logMessage->level()) << "].\n" - << "Few possible reasons (could be something else):\n" << " * Permission denied\n" - << " * Disk full\n" << " * Disk is not writable", true); - } else { - if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) { - logger->flush(logMessage->level(), fs); - } - } - } else { - ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] " - << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false); - } - } - } -# if defined(ELPP_SYSLOG) - else if (data->dispatchAction() == base::DispatchAction::SysLog) { - // Determine syslog priority - int sysLogPriority = 0; - if (logMessage->level() == Level::Fatal) - sysLogPriority = LOG_EMERG; - else if (logMessage->level() == Level::Error) - sysLogPriority = LOG_ERR; - else if (logMessage->level() == Level::Warning) - sysLogPriority = LOG_WARNING; - else if (logMessage->level() == Level::Info) - sysLogPriority = LOG_INFO; - else if (logMessage->level() == Level::Debug) - sysLogPriority = LOG_DEBUG; - else - sysLogPriority = LOG_NOTICE; -# if defined(ELPP_UNICODE) - char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); - syslog(sysLogPriority, "%s", line); - free(line); -# else - syslog(sysLogPriority, "%s", logLine.c_str()); -# endif - } -# endif // defined(ELPP_SYSLOG) -} - -void AsyncDispatchWorker::run(void) { - while (continueRunning()) { - emptyQueue(); - base::threading::msleep(10); // 10ms - } -} -#endif // ELPP_ASYNC_LOGGING - -// DefaultLogBuilder - -base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const { - base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations(); - const base::LogFormat* logFormat = &tc->logFormat(logMessage->level()); - base::type::string_t logLine = logFormat->format(); - char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = ""; - const char* bufLim = buff + sizeof(buff); - if (logFormat->hasFlag(base::FormatFlags::AppName)) { - // App name - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier, - logMessage->logger()->parentApplicationName()); - } - if (logFormat->hasFlag(base::FormatFlags::ThreadId)) { - // Thread ID - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier, - ELPP->getThreadName(base::threading::getCurrentThreadId())); - } - if (logFormat->hasFlag(base::FormatFlags::DateTime)) { - // DateTime - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier, - base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), - &tc->subsecondPrecision(logMessage->level()))); - } - if (logFormat->hasFlag(base::FormatFlags::Function)) { - // Function - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func()); - } - if (logFormat->hasFlag(base::FormatFlags::File)) { - // File - base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); - base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff, ELPP->vRegistry()->getFilenameCommonPrefix()); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::FileBase)) { - // FileBase - base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); - base::utils::File::buildBaseFilename(logMessage->file(), buff); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::Line)) { - // Line - char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength); - buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::Location)) { - // Location - char* buf = base::utils::Str::clearBuff(buff, - base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength); - base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff, ELPP->vRegistry()->getFilenameCommonPrefix()); - buf = base::utils::Str::addToBuff(buff, buf, bufLim); - buf = base::utils::Str::addToBuff(":", buf, bufLim); - buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, - false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff)); - } - if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) { - // Verbose level - char* buf = base::utils::Str::clearBuff(buff, 1); - buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false); - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff)); - } - if (logFormat->hasFlag(base::FormatFlags::LogMessage)) { - // Log message - base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message()); - } -#if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) - el::base::threading::ScopedLock lock_(ELPP->customFormatSpecifiersLock()); - ELPP_UNUSED(lock_); - for (std::vector::const_iterator it = ELPP->customFormatSpecifiers()->begin(); - it != ELPP->customFormatSpecifiers()->end(); ++it) { - std::string fs(it->formatSpecifier()); - base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end()); - base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage)); - } -#endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) - if (appendNewLine) logLine += ELPP_LITERAL("\n"); - return logLine; -} - -// LogDispatcher - -void LogDispatcher::dispatch(void) { - if (m_proceed && m_dispatchAction == base::DispatchAction::None) { - m_proceed = false; - } - if (!m_proceed) { - return; - } -#ifndef ELPP_NO_GLOBAL_LOCK - // see https://github.com/muflihun/easyloggingpp/issues/580 - // global lock is turned off by default unless - // ELPP_NO_GLOBAL_LOCK is defined - base::threading::ScopedLock scopedLock(ELPP->lock()); -#endif - base::TypedConfigurations* tc = m_logMessage->logger()->m_typedConfigurations; - if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) { - tc->validateFileRolling(m_logMessage->level(), ELPP->preRollOutCallback()); - } - LogDispatchCallback* callback = nullptr; - LogDispatchData data; - for (const std::pair& h - : ELPP->m_logDispatchCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - data.setLogMessage(m_logMessage); - data.setDispatchAction(m_dispatchAction); - callback->handle(&data); - } - } -} - -// MessageBuilder - -void MessageBuilder::initialize(Logger* logger) { - m_logger = logger; - m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ? - ELPP_LITERAL("\n ") : ELPP_LITERAL(", "); -} - -MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) { - if (msg == nullptr) { - m_logger->stream() << base::consts::kNullPointer; - return *this; - } -# if defined(ELPP_UNICODE) - m_logger->stream() << msg; -# else - char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg); - m_logger->stream() << buff_; - free(buff_); -# endif - if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { - m_logger->stream() << " "; - } - return *this; -} - -// Writer - -Writer& Writer::construct(Logger* logger, bool needLock) { - m_logger = logger; - initializeLogger(logger->id(), false, needLock); - m_messageBuilder.initialize(m_logger); - return *this; -} - -Writer& Writer::construct(int count, const char* loggerIds, ...) { - if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { - va_list loggersList; - va_start(loggersList, loggerIds); - const char* id = loggerIds; - m_loggerIds.reserve(count); - for (int i = 0; i < count; ++i) { - m_loggerIds.push_back(std::string(id)); - id = va_arg(loggersList, const char*); - } - va_end(loggersList); - initializeLogger(m_loggerIds.at(0)); - } else { - initializeLogger(std::string(loggerIds)); - } - m_messageBuilder.initialize(m_logger); - return *this; -} - -Writer& Writer::construct(const char *loggerId) { - initializeLogger(ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically))); - m_messageBuilder.initialize(m_logger); - return *this; -} - -void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) { - if (lookup) { - m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically)); - } - if (m_logger == nullptr) { - { - if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) { - // Somehow default logger has been unregistered. Not good! Register again - ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId)); - } - } - Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) - << "Logger [" << loggerId << "] is not registered yet!"; - m_proceed = false; - } else { - if (needLock) { - m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because - // m_proceed can be changed by lines below - } - if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) { - m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) : - ELPP->vRegistry()->allowed(m_level, loggerId); - } else { - m_proceed = m_logger->enabled(m_level); - } - } -} - -void Writer::initializeLogger(Logger *logger, bool needLock) { - m_logger = logger; - if (m_logger == nullptr) { - m_proceed = false; - } else { - if (needLock) { - m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because - // m_proceed can be changed by lines below - } - m_proceed = true; - } -} - -void Writer::processDispatch() { -#if ELPP_LOGGING_ENABLED - if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { - bool firstDispatched = false; - base::type::string_t logMessage; - std::size_t i = 0; - do { - if (m_proceed) { - if (firstDispatched) { - m_logger->stream() << logMessage; - } else { - firstDispatched = true; - if (m_loggerIds.size() > 1) { - logMessage = m_logger->stream().str(); - } - } - triggerDispatch(); - } else if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - if (i + 1 < m_loggerIds.size()) { - initializeLogger(m_loggerIds.at(i + 1)); - } - } while (++i < m_loggerIds.size()); - } else { - if (m_proceed) { - triggerDispatch(); - } else if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - } -#else - if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } -#endif // ELPP_LOGGING_ENABLED -} - -void Writer::triggerDispatch(void) { - if (m_proceed) { - if (m_msg == nullptr) { - LogMessage msg(m_level, m_file, m_line, m_func, m_verboseLevel, - m_logger); - base::LogDispatcher(m_proceed, &msg, m_dispatchAction).dispatch(); - } else { - base::LogDispatcher(m_proceed, m_msg, m_dispatchAction).dispatch(); - } - } - if (m_logger != nullptr) { - m_logger->stream().str(ELPP_LITERAL("")); - m_logger->releaseLock(); - } - if (m_proceed && m_level == Level::Fatal - && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) { - base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) - << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]"; - std::stringstream reasonStream; - reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]" - << " If you wish to disable 'abort on fatal log' please use " - << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)"; - base::utils::abort(1, reasonStream.str()); - } - m_proceed = false; -} - -// PErrorWriter - -PErrorWriter::~PErrorWriter(void) { - if (m_proceed) { -#if ELPP_COMPILER_MSVC - char buff[256]; - strerror_s(buff, 256, errno); - m_logger->stream() << ": " << buff << " [" << errno << "]"; -#else - m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]"; -#endif - } -} - -// PerformanceTracker - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -PerformanceTracker::PerformanceTracker(const std::string& blockName, - base::TimestampUnit timestampUnit, - const std::string& loggerId, - bool scopedLog, Level level) : - m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog), - m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - // We store it locally so that if user happen to change configuration by the end of scope - // or before calling checkpoint, we still depend on state of configuraton at time of construction - el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false); - m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level); - if (m_enabled) { - base::utils::DateTime::gettimeofday(&m_startTime); - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED -} - -PerformanceTracker::~PerformanceTracker(void) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - if (m_enabled) { - base::threading::ScopedLock scopedLock(lock()); - if (m_scopedLog) { - base::utils::DateTime::gettimeofday(&m_endTime); - base::type::string_t formattedTime = getFormattedTimeTaken(); - PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete); - data.init(this); - data.m_formattedTimeTaken = formattedTime; - PerformanceTrackingCallback* callback = nullptr; - for (const std::pair& h - : ELPP->m_performanceTrackingCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(&data); - } - } - } - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) -} - -void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line, - const char* func) { -#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - if (m_enabled) { - base::threading::ScopedLock scopedLock(lock()); - base::utils::DateTime::gettimeofday(&m_endTime); - base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL(""); - PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint); - data.init(this); - data.m_checkpointId = id; - data.m_file = file; - data.m_line = line; - data.m_func = func; - data.m_formattedTimeTaken = formattedTime; - PerformanceTrackingCallback* callback = nullptr; - for (const std::pair& h - : ELPP->m_performanceTrackingCallbacks) { - callback = h.second.get(); - if (callback != nullptr && callback->enabled()) { - callback->handle(&data); - } - } - base::utils::DateTime::gettimeofday(&m_lastCheckpointTime); - m_hasChecked = true; - m_lastCheckpointId = id; - } -#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED - ELPP_UNUSED(id); - ELPP_UNUSED(file); - ELPP_UNUSED(line); - ELPP_UNUSED(func); -} - -const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const { - if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) { - base::type::stringstream_t ss; - ss << base::utils::DateTime::getTimeDifference(m_endTime, - startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast - (m_timestampUnit)].unit; - return ss.str(); - } - return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime, - startTime, m_timestampUnit), m_timestampUnit); -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - -namespace debug { -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -// StackTrace - -StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, - const std::string& hex, - const std::string& addr) : - m_index(index), - m_location(loc), - m_demangled(demang), - m_hex(hex), - m_addr(addr) { -} - -std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) { - ss << "[" << si.m_index << "] " << si.m_location << (si.m_hex.empty() ? "" : "+") << si.m_hex << " " << si.m_addr << - (si.m_demangled.empty() ? "" : ":") << si.m_demangled; - return ss; -} - -std::ostream& operator<<(std::ostream& os, const StackTrace& st) { - std::vector::const_iterator it = st.m_stack.begin(); - while (it != st.m_stack.end()) { - os << " " << *it++ << "\n"; - } - return os; -} - -void StackTrace::generateNew(void) { -#if ELPP_STACKTRACE - m_stack.clear(); - void* stack[kMaxStack]; - unsigned int size = backtrace(stack, kMaxStack); - char** strings = backtrace_symbols(stack, size); - if (size > kStackStart) { // Skip StackTrace c'tor and generateNew - for (std::size_t i = kStackStart; i < size; ++i) { - std::string mangName; - std::string location; - std::string hex; - std::string addr; - - // entry: 2 crash.cpp.bin 0x0000000101552be5 _ZN2el4base5debug10StackTraceC1Ev + 21 - const std::string line(strings[i]); - auto p = line.find("_"); - if (p != std::string::npos) { - mangName = line.substr(p); - mangName = mangName.substr(0, mangName.find(" +")); - } - p = line.find("0x"); - if (p != std::string::npos) { - addr = line.substr(p); - addr = addr.substr(0, addr.find("_")); - } - // Perform demangling if parsed properly - if (!mangName.empty()) { - int status = 0; - char* demangName = abi::__cxa_demangle(mangName.data(), 0, 0, &status); - // if demangling is successful, output the demangled function name - if (status == 0) { - // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) - StackTraceEntry entry(i - 1, location, demangName, hex, addr); - m_stack.push_back(entry); - } else { - // Not successful - we will use mangled name - StackTraceEntry entry(i - 1, location, mangName, hex, addr); - m_stack.push_back(entry); - } - free(demangName); - } else { - StackTraceEntry entry(i - 1, line); - m_stack.push_back(entry); - } - } - } - free(strings); -#else - ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler"); -#endif // ELPP_STACKTRACE -} - -// Static helper functions - -static std::string crashReason(int sig) { - std::stringstream ss; - bool foundReason = false; - for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) { - if (base::consts::kCrashSignals[i].numb == sig) { - ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal"; - if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) { - ss << std::endl << - " " << base::consts::kCrashSignals[i].brief << std::endl << - " " << base::consts::kCrashSignals[i].detail; - } - foundReason = true; - } - } - if (!foundReason) { - ss << "Application has crashed due to unknown signal [" << sig << "]"; - } - return ss.str(); -} -/// @brief Logs reason of crash from sig -static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { - if (sig == SIGINT && ELPP->hasFlag(el::LoggingFlag::IgnoreSigInt)) { - return; - } - std::stringstream ss; - ss << "CRASH HANDLED; "; - ss << crashReason(sig); -#if ELPP_STACKTRACE - if (stackTraceIfAvailable) { - ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace(); - } -#else - ELPP_UNUSED(stackTraceIfAvailable); -#endif // ELPP_STACKTRACE - ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str(); -} - -static inline void crashAbort(int sig) { - base::utils::abort(sig, std::string()); -} - -/// @brief Default application crash handler -/// -/// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program. -static inline void defaultCrashHandler(int sig) { - base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId); - base::debug::crashAbort(sig); -} - -// CrashHandler - -CrashHandler::CrashHandler(bool useDefault) { - if (useDefault) { - setHandler(defaultCrashHandler); - } -} - -void CrashHandler::setHandler(const Handler& cHandler) { - m_handler = cHandler; -#if defined(ELPP_HANDLE_SIGABRT) - int i = 0; // SIGABRT is at base::consts::kCrashSignals[0] -#else - int i = 1; -#endif // defined(ELPP_HANDLE_SIGABRT) - for (; i < base::consts::kCrashSignalsCount; ++i) { - m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler); - } -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -} // namespace debug -} // namespace base - -// el - -// Helpers - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) { - std::stringstream ss; - ss << base::debug::crashReason(sig).c_str(); - ss << " - [Called el::Helpers::crashAbort(" << sig << ")]"; - if (sourceFile != nullptr && strlen(sourceFile) > 0) { - ss << " - Source: " << sourceFile; - if (line > 0) - ss << ":" << line; - else - ss << " (line number not specified)"; - } - base::utils::abort(sig, ss.str()); -} - -void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { - el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger); -} - -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - -// Loggers - -Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) { - return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable); -} - -void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) { - ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr); -} - -bool Loggers::unregisterLogger(const std::string& identity) { - return ELPP->registeredLoggers()->remove(identity); -} - -bool Loggers::hasLogger(const std::string& identity) { - return ELPP->registeredLoggers()->has(identity); -} - -Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) { - if (!logger) return nullptr; - logger->configure(configurations); - return logger; -} - -Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) { - return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations); -} - -Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType, - const std::string& value) { - Logger* logger = Loggers::getLogger(identity); - if (logger == nullptr) { - return nullptr; - } - logger->configurations()->set(Level::Global, configurationType, value); - logger->reconfigure(); - return logger; -} - -void Loggers::reconfigureAllLoggers(const Configurations& configurations) { - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); - it != ELPP->registeredLoggers()->end(); ++it) { - Loggers::reconfigureLogger(it->second, configurations); - } -} - -void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType, - const std::string& value) { - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); - it != ELPP->registeredLoggers()->end(); ++it) { - Logger* logger = it->second; - logger->configurations()->set(level, configurationType, value); - logger->reconfigure(); - } -} - -void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) { - ELPP->registeredLoggers()->setDefaultConfigurations(configurations); - if (reconfigureExistingLoggers) { - Loggers::reconfigureAllLoggers(configurations); - } -} - -const Configurations* Loggers::defaultConfigurations(void) { - return ELPP->registeredLoggers()->defaultConfigurations(); -} - -const base::LogStreamsReferenceMap* Loggers::logStreamsReference(void) { - return ELPP->registeredLoggers()->logStreamsReference(); -} - -base::TypedConfigurations Loggers::defaultTypedConfigurations(void) { - return base::TypedConfigurations( - ELPP->registeredLoggers()->defaultConfigurations(), - ELPP->registeredLoggers()->logStreamsReference()); -} - -std::vector* Loggers::populateAllLoggerIds(std::vector* targetList) { - targetList->clear(); - for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin(); - it != ELPP->registeredLoggers()->list().end(); ++it) { - targetList->push_back(it->first); - } - return targetList; -} - -void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) { - std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in); - ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath - << "] for parsing."); - std::string line = std::string(); - std::stringstream ss; - Logger* logger = nullptr; - auto configure = [&](void) { - ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str() - << "\n--------------"); - Configurations c; - c.parseFromText(ss.str()); - logger->configure(c); - }; - while (gcfStream.good()) { - std::getline(gcfStream, line); - ELPP_INTERNAL_INFO(1, "Parsing line: " << line); - base::utils::Str::trim(line); - if (Configurations::Parser::isComment(line)) continue; - Configurations::Parser::ignoreComments(&line); - base::utils::Str::trim(line); - if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) { - if (!ss.str().empty() && logger != nullptr) { - configure(); - } - ss.str(std::string("")); - line = line.substr(2); - base::utils::Str::trim(line); - if (line.size() > 1) { - ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'"); - logger = getLogger(line); - } - } else { - ss << line << "\n"; - } - } - if (!ss.str().empty() && logger != nullptr) { - configure(); - } -} - -bool Loggers::configureFromArg(const char* argKey) { -#if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) - ELPP_UNUSED(argKey); -#else - if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) { - return false; - } - configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey)); -#endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) - return true; -} - -void Loggers::flushAll(void) { - ELPP->registeredLoggers()->flushAll(); -} - -void Loggers::setVerboseLevel(base::type::VerboseLevel level) { - ELPP->vRegistry()->setLevel(level); -} - -base::type::VerboseLevel Loggers::verboseLevel(void) { - return ELPP->vRegistry()->level(); -} - -void Loggers::setVModules(const char* modules) { - if (ELPP->vRegistry()->vModulesEnabled()) { - ELPP->vRegistry()->setModules(modules); - } -} - -void Loggers::clearVModules(void) { - ELPP->vRegistry()->clearModules(); -} - -void Loggers::setCategories(const char* categories, bool clear) { - ELPP->vRegistry()->setCategories(categories, clear); -} - -std::string Loggers::getCategories() { - return ELPP->vRegistry()->getCategories(); -} - -void Loggers::clearCategories(void) { - ELPP->vRegistry()->clearCategories(); -} - -void Loggers::setFilenameCommonPrefix(const std::string &prefix) { - ELPP->vRegistry()->setFilenameCommonPrefix(prefix); -} - -const std::string &Loggers::getFilenameCommonPrefix() { - return ELPP->vRegistry()->getFilenameCommonPrefix(); -} - -// VersionInfo - -const std::string VersionInfo::version(void) { - return std::string("9.96.7"); -} -/// @brief Release date of current version -const std::string VersionInfo::releaseDate(void) { - return std::string("24-11-2018 0728hrs"); -} - -} // namespace el diff --git a/external/easylogging++/easylogging++.h b/external/easylogging++/easylogging++.h deleted file mode 100644 index 05b53c717..000000000 --- a/external/easylogging++/easylogging++.h +++ /dev/null @@ -1,4653 +0,0 @@ -// -// Bismillah ar-Rahmaan ar-Raheem -// -// Easylogging++ v9.96.7 -// Single-header only, cross-platform logging library for C++ applications -// -// Copyright (c) 2012-2018 Zuhd Web Services -// Copyright (c) 2012-2018 @abumusamq -// -// This library is released under the MIT Licence. -// https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE -// -// https://zuhd.org -// http://muflihun.com -// - -#ifndef EASYLOGGINGPP_H -#define EASYLOGGINGPP_H -#include "ea_config.h" -// Compilers and C++0x/C++11 Evaluation -#if __cplusplus >= 201103L -# define ELPP_CXX11 1 -#endif // __cplusplus >= 201103L -#if (defined(__GNUC__)) -# define ELPP_COMPILER_GCC 1 -#else -# define ELPP_COMPILER_GCC 0 -#endif -#if ELPP_COMPILER_GCC -# define ELPP_GCC_VERSION (__GNUC__ * 10000 \ -+ __GNUC_MINOR__ * 100 \ -+ __GNUC_PATCHLEVEL__) -# if defined(__GXX_EXPERIMENTAL_CXX0X__) -# define ELPP_CXX0X 1 -# endif -#endif -// Visual C++ -#if defined(_MSC_VER) -# define ELPP_COMPILER_MSVC 1 -#else -# define ELPP_COMPILER_MSVC 0 -#endif -#define ELPP_CRT_DBG_WARNINGS ELPP_COMPILER_MSVC -#if ELPP_COMPILER_MSVC -# if (_MSC_VER == 1600) -# define ELPP_CXX0X 1 -# elif(_MSC_VER >= 1700) -# define ELPP_CXX11 1 -# endif -#endif -// Clang++ -#if (defined(__clang__) && (__clang__ == 1)) -# define ELPP_COMPILER_CLANG 1 -#else -# define ELPP_COMPILER_CLANG 0 -#endif -#if ELPP_COMPILER_CLANG -# if __has_include() -# include // Make __GLIBCXX__ defined when using libstdc++ -# if !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426 -# define ELPP_CLANG_SUPPORTS_THREAD -# endif // !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426 -# endif // __has_include() -#endif -#if (defined(__MINGW32__) || defined(__MINGW64__)) -# define ELPP_MINGW 1 -#else -# define ELPP_MINGW 0 -#endif -#if (defined(__CYGWIN__) && (__CYGWIN__ == 1)) -# define ELPP_CYGWIN 1 -#else -# define ELPP_CYGWIN 0 -#endif -#if (defined(__INTEL_COMPILER)) -# define ELPP_COMPILER_INTEL 1 -#else -# define ELPP_COMPILER_INTEL 0 -#endif -// Operating System Evaluation -// Windows -#if (defined(_WIN32) || defined(_WIN64)) -# define ELPP_OS_WINDOWS 1 -#else -# define ELPP_OS_WINDOWS 0 -#endif -// Linux -#if (defined(__linux) || defined(__linux__)) -# define ELPP_OS_LINUX 1 -#else -# define ELPP_OS_LINUX 0 -#endif -#if (defined(__APPLE__)) -# define ELPP_OS_MAC 1 -#else -# define ELPP_OS_MAC 0 -#endif -#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) -# define ELPP_OS_FREEBSD 1 -#else -# define ELPP_OS_FREEBSD 0 -#endif -#if (defined(__OpenBSD__)) -# define ELPP_OS_OPENBSD 1 -#else -# define ELPP_OS_OPENBSD 0 -#endif -#if (defined(__NetBSD__)) -# define ELPP_OS_NETBSD 1 -#else -# define ELPP_OS_NETBSD 0 -#endif -#if (defined(__sun)) -# define ELPP_OS_SOLARIS 1 -#else -# define ELPP_OS_SOLARIS 0 -#endif -#if (defined(_AIX)) -# define ELPP_OS_AIX 1 -#else -# define ELPP_OS_AIX 0 -#endif -#if (defined(__NetBSD__)) -# define ELPP_OS_NETBSD 1 -#else -# define ELPP_OS_NETBSD 0 -#endif -#if defined(__EMSCRIPTEN__) -# define ELPP_OS_EMSCRIPTEN 1 -#else -# define ELPP_OS_EMSCRIPTEN 0 -#endif -#if (defined(__DragonFly__)) -# define ELPP_OS_DRAGONFLY 1 -#else -# define ELPP_OS_DRAGONFLY 0 -#endif -// Unix -#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS || ELPP_OS_AIX || ELPP_OS_EMSCRIPTEN || ELPP_OS_DRAGONFLY || ELPP_OS_OPENBSD) && (!ELPP_OS_WINDOWS)) -# define ELPP_OS_UNIX 1 -#else -# define ELPP_OS_UNIX 0 -#endif -#if (defined(__ANDROID__)) -# define ELPP_OS_ANDROID 1 -#else -# define ELPP_OS_ANDROID 0 -#endif -// Evaluating Cygwin as *nix OS -#if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN -# undef ELPP_OS_UNIX -# undef ELPP_OS_LINUX -# define ELPP_OS_UNIX 1 -# define ELPP_OS_LINUX 1 -#endif // !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN -#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO) -# define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR) -# define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_ENDL) -# define ELPP_INTERNAL_DEBUGGING_ENDL std::endl -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -#if !defined(ELPP_INTERNAL_DEBUGGING_MSG) -# define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg -#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) -// Internal Assertions and errors -#if !defined(ELPP_DISABLE_ASSERT) -# if (defined(ELPP_DEBUG_ASSERT_FAILURE)) -# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ -std::stringstream internalInfoStream; internalInfoStream << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ -<< "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \ -<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; base::utils::abort(1, \ -"ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE"); } -# else -# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ -std::stringstream internalInfoStream; internalInfoStream << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR\ -<< "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " \ -<< __LINE__ << ") [" #expr << "] WITH MESSAGE \"" << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" \ -<< ELPP_INTERNAL_DEBUGGING_ENDL; } -# endif // (defined(ELPP_DEBUG_ASSERT_FAILURE)) -#else -# define ELPP_ASSERT(x, y) -#endif //(!defined(ELPP_DISABLE_ASSERT) -#if ELPP_COMPILER_MSVC -# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ -{ char buff[256]; strerror_s(buff, 256, errno); \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]";} (void)0 -#else -# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; (void)0 -#endif // ELPP_COMPILER_MSVC -#if defined(ELPP_DEBUG_ERRORS) -# if !defined(ELPP_INTERNAL_ERROR) -# define ELPP_INTERNAL_ERROR(msg, pe) { \ -std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ -<< "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \ -<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << ELPP_INTERNAL_DEBUGGING_ENDL; \ -if (pe) { ELPP_INTERNAL_DEBUGGING_OUT_ERROR << " "; ELPP_INTERNAL_DEBUGGING_WRITE_PERROR; }} (void)0 -# endif -#else -# undef ELPP_INTERNAL_INFO -# define ELPP_INTERNAL_ERROR(msg, pe) -#endif // defined(ELPP_DEBUG_ERRORS) -#if (defined(ELPP_DEBUG_INFO)) -# if !(defined(ELPP_INTERNAL_INFO_LEVEL)) -# define ELPP_INTERNAL_INFO_LEVEL 9 -# endif // !(defined(ELPP_INTERNAL_INFO_LEVEL)) -# if !defined(ELPP_INTERNAL_INFO) -# define ELPP_INTERNAL_INFO(lvl, msg) { if (lvl <= ELPP_INTERNAL_INFO_LEVEL) { \ -std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ -ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \ -<< ELPP_INTERNAL_DEBUGGING_ENDL; }} -# endif -#else -# undef ELPP_INTERNAL_INFO -# define ELPP_INTERNAL_INFO(lvl, msg) -#endif // (defined(ELPP_DEBUG_INFO)) -#if (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG)) -# if (ELPP_COMPILER_GCC && !ELPP_MINGW && !ELPP_OS_OPENBSD && !ELPP_OS_NETBSD && !ELPP_OS_ANDROID && !ELPP_OS_EMSCRIPTEN) -# define ELPP_STACKTRACE 1 -# else -# define ELPP_STACKTRACE 0 -# ifdef EASYLOGGING_CC -# if ELPP_COMPILER_MSVC -# pragma message("Stack trace not available for this compiler") -# else -# warning "Stack trace not available for this compiler"; -# endif // ELPP_COMPILER_MSVC -# endif -# endif // ELPP_COMPILER_GCC -#else -# define ELPP_STACKTRACE 0 -#endif // (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG)) -// Miscellaneous macros -#define ELPP_UNUSED(x) (void)x -#if ELPP_OS_UNIX -// Log file permissions for unix-based systems -# define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH -#endif // ELPP_OS_UNIX -#if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC -# if defined(ELPP_EXPORT_SYMBOLS) -# define ELPP_EXPORT __declspec(dllexport) -# else -# define ELPP_EXPORT __declspec(dllimport) -# endif // defined(ELPP_EXPORT_SYMBOLS) -#else -# define ELPP_EXPORT -#endif // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC -// Some special functions that are VC++ specific -#undef STRTOK -#undef STRERROR -#undef STRCAT -#undef STRCPY -#if ELPP_CRT_DBG_WARNINGS -# define STRTOK(a, b, c) strtok_s(a, b, c) -# define STRERROR(a, b, c) strerror_s(a, b, c) -# define STRCAT(a, b, len) strcat_s(a, len, b) -# define STRCPY(a, b, len) strcpy_s(a, len, b) -#else -# define STRTOK(a, b, c) strtok(a, b) -# define STRERROR(a, b, c) strerror(c) -# define STRCAT(a, b, len) strcat(a, b) -# define STRCPY(a, b, len) strcpy(a, b) -#endif -// Compiler specific support evaluations -#if (ELPP_MINGW && !defined(ELPP_FORCE_USE_STD_THREAD)) -# define ELPP_USE_STD_THREADING 0 -#else -# if ((ELPP_COMPILER_CLANG && defined(ELPP_CLANG_SUPPORTS_THREAD)) || \ - (!ELPP_COMPILER_CLANG && defined(ELPP_CXX11)) || \ - defined(ELPP_FORCE_USE_STD_THREAD)) -# define ELPP_USE_STD_THREADING 1 -# else -# define ELPP_USE_STD_THREADING 0 -# endif -#endif -#undef ELPP_FINAL -#if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) -# define ELPP_FINAL -#else -# define ELPP_FINAL final -#endif // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) -#if defined(ELPP_EXPERIMENTAL_ASYNC) -# define ELPP_ASYNC_LOGGING 1 -#else -# define ELPP_ASYNC_LOGGING 0 -#endif // defined(ELPP_EXPERIMENTAL_ASYNC) -#if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING -# define ELPP_THREADING_ENABLED 1 -#else -# define ELPP_THREADING_ENABLED 0 -#endif // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING -// Function macro ELPP_FUNC -#undef ELPP_FUNC -#if ELPP_COMPILER_MSVC // Visual C++ -# define ELPP_FUNC __FUNCSIG__ -#elif ELPP_COMPILER_GCC // GCC -# define ELPP_FUNC __PRETTY_FUNCTION__ -#elif ELPP_COMPILER_INTEL // Intel C++ -# define ELPP_FUNC __PRETTY_FUNCTION__ -#elif ELPP_COMPILER_CLANG // Clang++ -# define ELPP_FUNC __PRETTY_FUNCTION__ -#else -# if defined(__func__) -# define ELPP_FUNC __func__ -# else -# define ELPP_FUNC "" -# endif // defined(__func__) -#endif // defined(_MSC_VER) -#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED -// Keep following line commented until features are fixed -#define ELPP_VARIADIC_TEMPLATES_SUPPORTED \ -(ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800)) -// Logging Enable/Disable macros -#ifdef ELPP_DISABLE_LOGS -# define ELPP_LOGGING_ENABLED 0 -#else -# define ELPP_LOGGING_ENABLED 1 -#endif -#if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_DEBUG_LOG 1 -#else -# define ELPP_DEBUG_LOG 0 -#endif // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_INFO_LOG 1 -#else -# define ELPP_INFO_LOG 0 -#endif // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_WARNING_LOG 1 -#else -# define ELPP_WARNING_LOG 0 -#endif // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_ERROR_LOG 1 -#else -# define ELPP_ERROR_LOG 0 -#endif // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_FATAL_LOG 1 -#else -# define ELPP_FATAL_LOG 0 -#endif // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_TRACE_LOG 1 -#else -# define ELPP_TRACE_LOG 0 -#endif // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) -# define ELPP_VERBOSE_LOG 1 -#else -# define ELPP_VERBOSE_LOG 0 -#endif // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) -#if (!(ELPP_CXX0X || ELPP_CXX11)) -# error "C++0x (or higher) support not detected! (Is `-std=c++11' missing?)" -#endif // (!(ELPP_CXX0X || ELPP_CXX11)) -// Headers -#if defined(ELPP_SYSLOG) -# include -#endif // defined(ELPP_SYSLOG) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(ELPP_UNICODE) -# include -# if ELPP_OS_WINDOWS -# include -# endif // ELPP_OS_WINDOWS -#endif // defined(ELPP_UNICODE) -#if ELPP_STACKTRACE -# include -# include -#endif // ELPP_STACKTRACE -#if ELPP_OS_ANDROID -# include -#endif // ELPP_OS_ANDROID -#if ELPP_OS_UNIX -# include -# include -#elif ELPP_OS_WINDOWS -# include -# include -# if defined(WIN32_LEAN_AND_MEAN) -# if defined(ELPP_WINSOCK2) -# include -# else -# include -# endif // defined(ELPP_WINSOCK2) -# endif // defined(WIN32_LEAN_AND_MEAN) -#endif // ELPP_OS_UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if ELPP_THREADING_ENABLED -# if ELPP_USE_STD_THREADING -# include -# include -# else -# if ELPP_OS_UNIX -# include -# endif // ELPP_OS_UNIX -# endif // ELPP_USE_STD_THREADING -#endif // ELPP_THREADING_ENABLED -#if ELPP_ASYNC_LOGGING -# if defined(ELPP_NO_SLEEP_FOR) -# include -# endif // defined(ELPP_NO_SLEEP_FOR) -# include -# include -# include -#endif // ELPP_ASYNC_LOGGING -#if defined(ELPP_STL_LOGGING) -// For logging STL based templates -# include -# include -# include -# include -# include -# include -# if defined(ELPP_LOG_STD_ARRAY) -# include -# endif // defined(ELPP_LOG_STD_ARRAY) -# if defined(ELPP_LOG_UNORDERED_SET) -# include -# endif // defined(ELPP_UNORDERED_SET) -#endif // defined(ELPP_STL_LOGGING) -#if defined(ELPP_QT_LOGGING) -// For logging Qt based classes & templates -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // defined(ELPP_QT_LOGGING) -#if defined(ELPP_BOOST_LOGGING) -// For logging boost based classes & templates -# include -# include -# include -# include -# include -# include -# include -# include -#endif // defined(ELPP_BOOST_LOGGING) -#if defined(ELPP_WXWIDGETS_LOGGING) -// For logging wxWidgets based classes & templates -# include -#endif // defined(ELPP_WXWIDGETS_LOGGING) -#if defined(ELPP_UTC_DATETIME) -# define elpptime_r gmtime_r -# define elpptime_s gmtime_s -# define elpptime gmtime -#else -# define elpptime_r localtime_r -# define elpptime_s localtime_s -# define elpptime localtime -#endif // defined(ELPP_UTC_DATETIME) -// Forward declarations -namespace el { -class Logger; -class LogMessage; -class PerformanceTrackingData; -class Loggers; -class Helpers; -template class Callback; -class LogDispatchCallback; -class PerformanceTrackingCallback; -class LoggerRegistrationCallback; -class LogDispatchData; -namespace base { -class Storage; -class RegisteredLoggers; -class PerformanceTracker; -class MessageBuilder; -class Writer; -class PErrorWriter; -class LogDispatcher; -class DefaultLogBuilder; -class DefaultLogDispatchCallback; -#if ELPP_ASYNC_LOGGING -class AsyncLogDispatchCallback; -class AsyncDispatchWorker; -#endif // ELPP_ASYNC_LOGGING -class DefaultPerformanceTrackingCallback; -} // namespace base -} // namespace el -/// @brief Easylogging++ entry namespace -namespace el { -/// @brief Namespace containing base/internal functionality used by Easylogging++ -namespace base { -/// @brief Data types used by Easylogging++ -namespace type { -#undef ELPP_LITERAL -#undef ELPP_STRLEN -#undef ELPP_COUT -#if defined(ELPP_UNICODE) -# define ELPP_LITERAL(txt) L##txt -# define ELPP_STRLEN wcslen -# if defined ELPP_CUSTOM_COUT -# define ELPP_COUT ELPP_CUSTOM_COUT -# else -# define ELPP_COUT std::wcout -# endif // defined ELPP_CUSTOM_COUT -typedef wchar_t char_t; -typedef std::wstring string_t; -typedef std::wstringstream stringstream_t; -typedef std::wfstream fstream_t; -typedef std::wostream ostream_t; -#else -# define ELPP_LITERAL(txt) txt -# define ELPP_STRLEN strlen -# if defined ELPP_CUSTOM_COUT -# define ELPP_COUT ELPP_CUSTOM_COUT -# else -# define ELPP_COUT std::cout -# endif // defined ELPP_CUSTOM_COUT -typedef char char_t; -typedef std::string string_t; -typedef std::stringstream stringstream_t; -typedef std::fstream fstream_t; -typedef std::ostream ostream_t; -#endif // defined(ELPP_UNICODE) -#if defined(ELPP_CUSTOM_COUT_LINE) -# define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine) -#else -# define ELPP_COUT_LINE(logLine) logLine << std::flush -#endif // defined(ELPP_CUSTOM_COUT_LINE) -typedef unsigned int EnumType; -typedef unsigned short VerboseLevel; -typedef unsigned long int LineNumber; -typedef base::Storage *StoragePointer; -typedef std::shared_ptr LogDispatchCallbackPtr; -typedef std::shared_ptr PerformanceTrackingCallbackPtr; -typedef std::shared_ptr LoggerRegistrationCallbackPtr; -typedef std::unique_ptr PerformanceTrackerPtr; -} // namespace type -/// @brief Internal helper class that prevent copy constructor for class -/// -/// @detail When using this class simply inherit it privately -class NoCopy { - protected: - NoCopy(void) {} - private: - NoCopy(const NoCopy&); - NoCopy& operator=(const NoCopy&); -}; -/// @brief Internal helper class that makes all default constructors private. -/// -/// @detail This prevents initializing class making it static unless an explicit constructor is declared. -/// When using this class simply inherit it privately -class StaticClass { - private: - StaticClass(void); - StaticClass(const StaticClass&); - StaticClass& operator=(const StaticClass&); -}; -} // namespace base -/// @brief Represents enumeration for severity level used to determine level of logging -/// -/// @detail With Easylogging++, developers may disable or enable any level regardless of -/// what the severity is. Or they can choose to log using hierarchical logging flag -enum class Level : base::type::EnumType { - /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels - Global = 1, - /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs. - Trace = 2, - /// @brief Informational events most useful for developers to debug application - Debug = 4, - /// @brief Severe error information that will presumably abort application - Fatal = 8, - /// @brief Information representing errors in application but application will keep running - Error = 16, - /// @brief Useful when application has potentially harmful situtaions - Warning = 32, - /// @brief Information that can be highly useful and vary with verbose logging level. - Verbose = 64, - /// @brief Mainly useful to represent current progress of application - Info = 128, - /// @brief Represents unknown level - Unknown = 1010 -}; -} // namespace el -namespace std { -template<> struct hash { - public: - std::size_t operator()(const el::Level& l) const { - return hash {}(static_cast(l)); - } -}; -} -namespace el { -/// @brief Static class that contains helper functions for el::Level -class LevelHelper : base::StaticClass { - public: - /// @brief Represents minimum valid level. Useful when iterating through enum. - static const base::type::EnumType kMinValid = static_cast(Level::Trace); - /// @brief Represents maximum valid level. This is used internally and you should not need it. - static const base::type::EnumType kMaxValid = static_cast(Level::Info); - /// @brief Casts level to int, useful for iterating through enum. - static base::type::EnumType castToInt(Level level) { - return static_cast(level); - } - /// @brief Casts int(ushort) to level, useful for iterating through enum. - static Level castFromInt(base::type::EnumType l) { - return static_cast(l); - } - /// @brief Converts level to associated const char* - /// @return Upper case string based level. - static const char* convertToString(Level level); - /// @brief Converts from prefix of levelStr to Level - /// @param levelStr Upper case string based level. - /// Lower case is also valid but providing upper case is recommended. - static Level convertFromStringPrefix(const char* levelStr); - /// @brief Converts from levelStr to Level - /// @param levelStr Upper case string based level. - /// Lower case is also valid but providing upper case is recommended. - static Level convertFromString(const char* levelStr); - /// @brief Applies specified function to each level starting from startIndex - /// @param startIndex initial value to start the iteration from. This is passed as pointer and - /// is left-shifted so this can be used inside function (fn) to represent current level. - /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through levels. - static void forEachLevel(base::type::EnumType* startIndex, const std::function& fn); -}; -/// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect -/// of logging -enum class ConfigurationType : base::type::EnumType { - /// @brief Determines whether or not corresponding level and logger of logging is enabled - /// You may disable all logs by using el::Level::Global - Enabled = 1, - /// @brief Whether or not to write corresponding log to log file - ToFile = 2, - /// @brief Whether or not to write corresponding level and logger log to standard output. - /// By standard output meaning termnal, command prompt etc - ToStandardOutput = 4, - /// @brief Determines format of logging corresponding level and logger. - Format = 8, - /// @brief Determines log file (full path) to write logs to for correponding level and logger - Filename = 16, - /// @brief Specifies precision of the subsecond part. It should be within range (1-6). - SubsecondPrecision = 32, - /// @brief Alias of SubsecondPrecision (for backward compatibility) - MillisecondsWidth = SubsecondPrecision, - /// @brief Determines whether or not performance tracking is enabled. - /// - /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger - PerformanceTracking = 64, - /// @brief Specifies log file max size. - /// - /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will - /// be truncated and re-initiated. - MaxLogFileSize = 128, - /// @brief Specifies number of log entries to hold until we flush pending log data - LogFlushThreshold = 256, - /// @brief Represents unknown configuration - Unknown = 1010 -}; -/// @brief Static class that contains helper functions for el::ConfigurationType -class ConfigurationTypeHelper : base::StaticClass { - public: - /// @brief Represents minimum valid configuration type. Useful when iterating through enum. - static const base::type::EnumType kMinValid = static_cast(ConfigurationType::Enabled); - /// @brief Represents maximum valid configuration type. This is used internally and you should not need it. - static const base::type::EnumType kMaxValid = static_cast(ConfigurationType::MaxLogFileSize); - /// @brief Casts configuration type to int, useful for iterating through enum. - static base::type::EnumType castToInt(ConfigurationType configurationType) { - return static_cast(configurationType); - } - /// @brief Casts int(ushort) to configurationt type, useful for iterating through enum. - static ConfigurationType castFromInt(base::type::EnumType c) { - return static_cast(c); - } - /// @brief Converts configuration type to associated const char* - /// @returns Upper case string based configuration type. - static const char* convertToString(ConfigurationType configurationType); - /// @brief Converts from configStr to ConfigurationType - /// @param configStr Upper case string based configuration type. - /// Lower case is also valid but providing upper case is recommended. - static ConfigurationType convertFromString(const char* configStr); - /// @brief Applies specified function to each configuration type starting from startIndex - /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted - /// so this can be used inside function (fn) to represent current configuration type. - /// @param fn function to apply with each configuration type. - /// This bool represent whether or not to stop iterating through configurations. - static inline void forEachConfigType(base::type::EnumType* startIndex, const std::function& fn); -}; -/// @brief Flags used while writing logs. This flags are set by user -enum class LoggingFlag : base::type::EnumType { - /// @brief Makes sure we have new line for each container log entry - NewLineForContainer = 1, - /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose - /// logging is allowed via that module. - AllowVerboseIfModuleNotSpecified = 2, - /// @brief When handling crashes by default, detailed crash reason will be logged as well - LogDetailedCrashReason = 4, - /// @brief Allows to disable application abortion when logged using FATAL level - DisableApplicationAbortOnFatalLog = 8, - /// @brief Flushes log with every log-entry (performance sensative) - Disabled by default - ImmediateFlush = 16, - /// @brief Enables strict file rolling - StrictLogFileSizeCheck = 32, - /// @brief Make terminal output colorful for supported terminals - ColoredTerminalOutput = 64, - /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network") - MultiLoggerSupport = 128, - /// @brief Disables comparing performance tracker's checkpoints - DisablePerformanceTrackingCheckpointComparison = 256, - /// @brief Disable VModules - DisableVModules = 512, - /// @brief Disable VModules extensions - DisableVModulesExtensions = 1024, - /// @brief Enables hierarchical logging - HierarchicalLogging = 2048, - /// @brief Creates logger automatically when not available - CreateLoggerAutomatically = 4096, - /// @brief Adds spaces b/w logs that separated by left-shift operator - AutoSpacing = 8192, - /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only) - FixedTimeFormat = 16384, - // @brief Ignore SIGINT or crash - IgnoreSigInt = 32768, -}; -namespace base { -/// @brief Namespace containing constants used internally. -namespace consts { -static const char kFormatSpecifierCharValue = 'v'; -static const char kFormatSpecifierChar = '%'; -static const unsigned int kMaxLogPerCounter = 100000; -static const unsigned int kMaxLogPerContainer = 100; -static const unsigned int kDefaultSubsecondPrecision = 3; - -#ifdef ELPP_DEFAULT_LOGGER -static const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER; -#else -static const char* kDefaultLoggerId = "default"; -#endif - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -#ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER -static const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER; -#else -static const char* kPerformanceLoggerId = "performance"; -#endif // ELPP_DEFAULT_PERFORMANCE_LOGGER -#endif - -#if defined(ELPP_SYSLOG) -static const char* kSysLogLoggerId = "syslog"; -#endif // defined(ELPP_SYSLOG) - -#if ELPP_OS_WINDOWS -static const char* kFilePathSeperator = "\\"; -#else -static const char* kFilePathSeperator = "/"; -#endif // ELPP_OS_WINDOWS - -static const std::size_t kSourceFilenameMaxLength = 100; -static const std::size_t kSourceLineMaxLength = 10; -static const Level kPerformanceTrackerDefaultLevel = Level::Info; -const struct { - double value; - const base::type::char_t* unit; -} kTimeFormats[] = { - { 1000.0f, ELPP_LITERAL("us") }, - { 1000.0f, ELPP_LITERAL("ms") }, - { 60.0f, ELPP_LITERAL("seconds") }, - { 60.0f, ELPP_LITERAL("minutes") }, - { 24.0f, ELPP_LITERAL("hours") }, - { 7.0f, ELPP_LITERAL("days") } -}; -static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]); -const struct { - int numb; - const char* name; - const char* brief; - const char* detail; -} kCrashSignals[] = { - // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..) - { - SIGABRT, "SIGABRT", "Abnormal termination", - "Program was abnormally terminated." - }, - { - SIGFPE, "SIGFPE", "Erroneous arithmetic operation", - "Arithemetic operation issue such as division by zero or operation resulting in overflow." - }, - { - SIGILL, "SIGILL", "Illegal instruction", - "Generally due to a corruption in the code or to an attempt to execute data." - }, - { - SIGSEGV, "SIGSEGV", "Invalid access to memory", - "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory." - }, - { - SIGINT, "SIGINT", "Interactive attention signal", - "Interruption generated (generally) by user or operating system." - }, -}; -static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]); -} // namespace consts -} // namespace base -typedef std::function PreRollOutCallback; -namespace base { -static inline void defaultPreRollOutCallback(const char*, std::size_t) {} -/// @brief Enum to represent timestamp unit -enum class TimestampUnit : base::type::EnumType { - Microsecond = 0, Millisecond = 1, Second = 2, Minute = 3, Hour = 4, Day = 5 -}; -/// @brief Format flags used to determine specifiers that are active for performance improvements. -enum class FormatFlags : base::type::EnumType { - DateTime = 1 << 1, - LoggerId = 1 << 2, - File = 1 << 3, - Line = 1 << 4, - Location = 1 << 5, - Function = 1 << 6, - User = 1 << 7, - Host = 1 << 8, - LogMessage = 1 << 9, - VerboseLevel = 1 << 10, - AppName = 1 << 11, - ThreadId = 1 << 12, - Level = 1 << 13, - FileBase = 1 << 14, - LevelShort = 1 << 15 -}; -/// @brief A subsecond precision class containing actual width and offset of the subsecond part -class SubsecondPrecision { - public: - SubsecondPrecision(void) { - init(base::consts::kDefaultSubsecondPrecision); - } - explicit SubsecondPrecision(int width) { - init(width); - } - bool operator==(const SubsecondPrecision& ssPrec) { - return m_width == ssPrec.m_width && m_offset == ssPrec.m_offset; - } - int m_width; - unsigned int m_offset; - private: - void init(int width); -}; -/// @brief Type alias of SubsecondPrecision -typedef SubsecondPrecision MillisecondsWidth; -/// @brief Namespace containing utility functions/static classes used internally -namespace utils { -/// @brief Deletes memory safely and points to null -template -static -typename std::enable_if::value, void>::type -safeDelete(T*& pointer) { - if (pointer == nullptr) - return; - delete pointer; - pointer = nullptr; -} -/// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise operation -/// Use these function as
flag = bitwise::Or(MyEnum::val1, flag);
-namespace bitwise { -template -static inline base::type::EnumType And(Enum e, base::type::EnumType flag) { - return static_cast(flag) & static_cast(e); -} -template -static inline base::type::EnumType Not(Enum e, base::type::EnumType flag) { - return static_cast(flag) & ~(static_cast(e)); -} -template -static inline base::type::EnumType Or(Enum e, base::type::EnumType flag) { - return static_cast(flag) | static_cast(e); -} -} // namespace bitwise -template -static inline void addFlag(Enum e, base::type::EnumType* flag) { - *flag = base::utils::bitwise::Or(e, *flag); -} -template -static inline void removeFlag(Enum e, base::type::EnumType* flag) { - *flag = base::utils::bitwise::Not(e, *flag); -} -template -static inline bool hasFlag(Enum e, base::type::EnumType flag) { - return base::utils::bitwise::And(e, flag) > 0x0; -} -} // namespace utils -namespace threading { -#if ELPP_THREADING_ENABLED -# if !ELPP_USE_STD_THREADING -namespace internal { -/// @brief A mutex wrapper for compiler that dont yet support std::recursive_mutex -class Mutex : base::NoCopy { - public: - Mutex(void) { -# if ELPP_OS_UNIX - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&m_underlyingMutex, &attr); - pthread_mutexattr_destroy(&attr); -# elif ELPP_OS_WINDOWS - InitializeCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - virtual ~Mutex(void) { -# if ELPP_OS_UNIX - pthread_mutex_destroy(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - DeleteCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline void lock(void) { -# if ELPP_OS_UNIX - pthread_mutex_lock(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - EnterCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline bool try_lock(void) { -# if ELPP_OS_UNIX - return (pthread_mutex_trylock(&m_underlyingMutex) == 0); -# elif ELPP_OS_WINDOWS - return TryEnterCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - inline void unlock(void) { -# if ELPP_OS_UNIX - pthread_mutex_unlock(&m_underlyingMutex); -# elif ELPP_OS_WINDOWS - LeaveCriticalSection(&m_underlyingMutex); -# endif // ELPP_OS_UNIX - } - - private: -# if ELPP_OS_UNIX - pthread_mutex_t m_underlyingMutex; -# elif ELPP_OS_WINDOWS - CRITICAL_SECTION m_underlyingMutex; -# endif // ELPP_OS_UNIX -}; -/// @brief Scoped lock for compiler that dont yet support std::lock_guard -template -class ScopedLock : base::NoCopy { - public: - explicit ScopedLock(M& mutex) { - m_mutex = &mutex; - m_mutex->lock(); - } - - virtual ~ScopedLock(void) { - m_mutex->unlock(); - } - private: - M* m_mutex; - ScopedLock(void); -}; -} // namespace internal -typedef base::threading::internal::Mutex Mutex; -typedef base::threading::internal::ScopedLock ScopedLock; -# else -typedef std::recursive_mutex Mutex; -typedef std::lock_guard ScopedLock; -# endif // !ELPP_USE_STD_THREADING -#else -namespace internal { -/// @brief Mutex wrapper used when multi-threading is disabled. -class NoMutex : base::NoCopy { - public: - NoMutex(void) {} - inline void lock(void) {} - inline bool try_lock(void) { - return true; - } - inline void unlock(void) {} -}; -/// @brief Lock guard wrapper used when multi-threading is disabled. -template -class NoScopedLock : base::NoCopy { - public: - explicit NoScopedLock(Mutex&) { - } - virtual ~NoScopedLock(void) { - } - private: - NoScopedLock(void); -}; -} // namespace internal -typedef base::threading::internal::NoMutex Mutex; -typedef base::threading::internal::NoScopedLock ScopedLock; -#endif // ELPP_THREADING_ENABLED -/// @brief Base of thread safe class, this class is inheritable-only -class ThreadSafe { - public: - virtual inline void acquireLock(void) ELPP_FINAL { m_mutex.lock(); } - virtual inline void releaseLock(void) ELPP_FINAL { m_mutex.unlock(); } - virtual inline base::threading::Mutex& lock(void) ELPP_FINAL { return m_mutex; } - protected: - ThreadSafe(void) {} - virtual ~ThreadSafe(void) {} - private: - base::threading::Mutex m_mutex; -}; - -#if ELPP_THREADING_ENABLED -# if !ELPP_USE_STD_THREADING -/// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned. -static std::string getCurrentThreadId(void) { - std::stringstream ss; -# if (ELPP_OS_WINDOWS) - ss << GetCurrentThreadId(); -# endif // (ELPP_OS_WINDOWS) - return ss.str(); -} -# else -/// @brief Gets ID of currently running threading using std::this_thread::get_id() -static std::string getCurrentThreadId(void) { - std::stringstream ss; - char prev_fill = ss.fill(' '); - auto prev_flags = ss.flags(std::ios::hex); - //ss.setf(std::ios::hex); - auto prev_width = ss.width(16); - ss << std::this_thread::get_id(); - ss.fill(prev_fill); - ss.flags(prev_flags); - ss.width(prev_width); - return ss.str(); -} -# endif // !ELPP_USE_STD_THREADING -#else -static inline std::string getCurrentThreadId(void) { - return std::string(); -} -#endif // ELPP_THREADING_ENABLED -} // namespace threading -namespace utils { -class File : base::StaticClass { - public: - /// @brief Creates new out file stream for specified filename. - /// @return Pointer to newly created fstream or nullptr - static base::type::fstream_t* newFileStream(const std::string& filename); - - /// @brief Gets size of file provided in stream - static std::size_t getSizeOfFile(base::type::fstream_t* fs); - - /// @brief Determines whether or not provided path exist in current file system - static bool pathExists(const char* path, bool considerFile = false); - - /// @brief Creates specified path on file system - /// @param path Path to create. - static bool createPath(const std::string& path); - /// @brief Extracts path of filename with leading slash - static std::string extractPathFromFilename(const std::string& fullPath, - const char* seperator = base::consts::kFilePathSeperator); - /// @brief builds stripped filename and puts it in buff - static void buildStrippedFilename(const char* filename, char buff[], const std::string &commonPrefix = NULL, - std::size_t limit = base::consts::kSourceFilenameMaxLength); - /// @brief builds base filename and puts it in buff - static void buildBaseFilename(const std::string& fullPath, char buff[], - std::size_t limit = base::consts::kSourceFilenameMaxLength, - const char* seperator = base::consts::kFilePathSeperator); -}; -/// @brief String utilities helper class used internally. You should not use it. -class Str : base::StaticClass { - public: - /// @brief Checks if character is digit. Dont use libc implementation of it to prevent locale issues. - static inline bool isDigit(char c) { - return c >= '0' && c <= '9'; - } - - /// @brief Matches wildcards, '*' and '?' only supported. - static bool wildCardMatch(const char* str, const char* pattern); - - static std::string& ltrim(std::string& str); - static std::string& rtrim(std::string& str); - static std::string& trim(std::string& str); - - /// @brief Determines whether or not str starts with specified string - /// @param str String to check - /// @param start String to check against - /// @return Returns true if starts with specified string, false otherwise - static bool startsWith(const std::string& str, const std::string& start); - - /// @brief Determines whether or not str ends with specified string - /// @param str String to check - /// @param end String to check against - /// @return Returns true if ends with specified string, false otherwise - static bool endsWith(const std::string& str, const std::string& end); - - /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance. - /// @param [in,out] str String to replace from - /// @param replaceWhat Character to replace - /// @param replaceWith Character to replace with - /// @return Modified version of str - static std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith); - - /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place - /// @param str String to replace from - /// @param replaceWhat Character to replace - /// @param replaceWith Character to replace with - /// @return Modified (original) str - static std::string& replaceAll(std::string& str, const std::string& replaceWhat, - const std::string& replaceWith); - - static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const base::type::string_t& replaceWith); -#if defined(ELPP_UNICODE) - static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, - const std::string& replaceWith); -#endif // defined(ELPP_UNICODE) - /// @brief Converts string to uppercase - /// @param str String to convert - /// @return Uppercase string - static std::string& toUpper(std::string& str); - - /// @brief Compares cstring equality - uses strcmp - static bool cStringEq(const char* s1, const char* s2); - - /// @brief Compares cstring equality (case-insensitive) - uses toupper(char) - /// Dont use strcasecmp because of CRT (VC++) - static bool cStringCaseEq(const char* s1, const char* s2); - - /// @brief Returns true if c exist in str - static bool contains(const char* str, char c); - - static char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true); - static char* addToBuff(const char* str, char* buf, const char* bufLim); - static char* clearBuff(char buff[], std::size_t lim); - - /// @brief Converst wchar* to char* - /// NOTE: Need to free return value after use! - static char* wcharPtrToCharPtr(const wchar_t* line); -}; -/// @brief Operating System helper static class used internally. You should not use it. -class OS : base::StaticClass { - public: -#if ELPP_OS_WINDOWS - /// @brief Gets environment variables for Windows based OS. - /// We are not using getenv(const char*) because of CRT deprecation - /// @param varname Variable name to get environment variable value for - /// @return If variable exist the value of it otherwise nullptr - static const char* getWindowsEnvironmentVariable(const char* varname); -#endif // ELPP_OS_WINDOWS -#if ELPP_OS_ANDROID - /// @brief Reads android property value - static std::string getProperty(const char* prop); - - /// @brief Reads android device name - static std::string getDeviceName(void); -#endif // ELPP_OS_ANDROID - - /// @brief Runs command on terminal and returns the output. - /// - /// @detail This is applicable only on unix based systems, for all other OS, an empty string is returned. - /// @param command Bash command - /// @return Result of bash output or empty string if no result found. - static const std::string getBashOutput(const char* command); - - /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++) - /// @param variableName Environment variable name - /// @param defaultVal If no environment variable or value found the value to return by default - /// @param alternativeBashCommand If environment variable not found what would be alternative bash command - /// in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami' - static std::string getEnvironmentVariable(const char* variableName, const char* defaultVal, - const char* alternativeBashCommand = nullptr); - /// @brief Gets current username. - static std::string currentUser(void); - - /// @brief Gets current host name or computer name. - /// - /// @detail For android systems this is device name with its manufacturer and model seperated by hyphen - static std::string currentHost(void); - /// @brief Whether or not terminal supports colors - static bool termSupportsColor(void); -}; -/// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str -class DateTime : base::StaticClass { - public: - /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current microsecond. - /// - /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a seperate implementation is provided - /// @param [in,out] tv Pointer that gets updated - static void gettimeofday(struct timeval* tv); - - /// @brief Gets current date and time with a subsecond part. - /// @param format User provided date/time format - /// @param ssPrec A pointer to base::SubsecondPrecision from configuration (non-null) - /// @returns string based date time in specified format. - static std::string getDateTime(const char* format, const base::SubsecondPrecision* ssPrec); - - /// @brief Converts timeval (struct from ctime) to string using specified format and subsecond precision - static std::string timevalToString(struct timeval tval, const char* format, - const el::base::SubsecondPrecision* ssPrec); - - /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc - static base::type::string_t formatTime(unsigned long long time, base::TimestampUnit timestampUnit); - - /// @brief Gets time difference in milli/micro second depending on timestampUnit - static unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, - base::TimestampUnit timestampUnit); - - - static struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo); - private: - static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, - std::size_t msec, const base::SubsecondPrecision* ssPrec); -}; -/// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..) -class CommandLineArgs { - public: - CommandLineArgs(void) { - setArgs(0, static_cast(nullptr)); - } - CommandLineArgs(int argc, const char** argv) { - setArgs(argc, argv); - } - CommandLineArgs(int argc, char** argv) { - setArgs(argc, argv); - } - virtual ~CommandLineArgs(void) {} - /// @brief Sets arguments and parses them - inline void setArgs(int argc, const char** argv) { - setArgs(argc, const_cast(argv)); - } - /// @brief Sets arguments and parses them - void setArgs(int argc, char** argv); - /// @brief Returns true if arguments contain paramKey with a value (seperated by '=') - bool hasParamWithValue(const char* paramKey) const; - /// @brief Returns value of arguments - /// @see hasParamWithValue(const char*) - const char* getParamValue(const char* paramKey) const; - /// @brief Return true if arguments has a param (not having a value) i,e without '=' - bool hasParam(const char* paramKey) const; - /// @brief Returns true if no params available. This exclude argv[0] - bool empty(void) const; - /// @brief Returns total number of arguments. This exclude argv[0] - std::size_t size(void) const; - friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c); - - private: - int m_argc; - char** m_argv; - std::unordered_map m_paramsWithValue; - std::vector m_params; -}; -/// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type. -/// -/// @detail Most of the functions are virtual final methods but anything implementing this abstract class should implement -/// unregisterAll() and deepCopy(const AbstractRegistry&) and write registerNew() method according to container -/// and few more methods; get() to find element, unregister() to unregister single entry. -/// Please note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation. -template -class AbstractRegistry : public base::threading::ThreadSafe { - public: - typedef typename Container::iterator iterator; - typedef typename Container::const_iterator const_iterator; - - /// @brief Default constructor - AbstractRegistry(void) {} - - /// @brief Move constructor that is useful for base classes - AbstractRegistry(AbstractRegistry&& sr) { - if (this == &sr) { - return; - } - unregisterAll(); - m_list = std::move(sr.m_list); - } - - bool operator==(const AbstractRegistry& other) { - if (size() != other.size()) { - return false; - } - for (std::size_t i = 0; i < m_list.size(); ++i) { - if (m_list.at(i) != other.m_list.at(i)) { - return false; - } - } - return true; - } - - bool operator!=(const AbstractRegistry& other) { - if (size() != other.size()) { - return true; - } - for (std::size_t i = 0; i < m_list.size(); ++i) { - if (m_list.at(i) != other.m_list.at(i)) { - return true; - } - } - return false; - } - - /// @brief Assignment move operator - AbstractRegistry& operator=(AbstractRegistry&& sr) { - if (this == &sr) { - return *this; - } - unregisterAll(); - m_list = std::move(sr.m_list); - return *this; - } - - virtual ~AbstractRegistry(void) { - } - - /// @return Iterator pointer from start of repository - virtual inline iterator begin(void) ELPP_FINAL { - return m_list.begin(); - } - - /// @return Iterator pointer from end of repository - virtual inline iterator end(void) ELPP_FINAL { - return m_list.end(); - } - - - /// @return Constant iterator pointer from start of repository - virtual inline const_iterator cbegin(void) const ELPP_FINAL { - return m_list.cbegin(); - } - - /// @return End of repository - virtual inline const_iterator cend(void) const ELPP_FINAL { - return m_list.cend(); - } - - /// @return Whether or not repository is empty - virtual inline bool empty(void) const ELPP_FINAL { - return m_list.empty(); - } - - /// @return Size of repository - virtual inline std::size_t size(void) const ELPP_FINAL { - return m_list.size(); - } - - /// @brief Returns underlying container by reference - virtual inline Container& list(void) ELPP_FINAL { - return m_list; - } - - /// @brief Returns underlying container by constant reference. - virtual inline const Container& list(void) const ELPP_FINAL { - return m_list; - } - - /// @brief Unregisters all the pointers from current repository. - virtual void unregisterAll(void) = 0; - - protected: - virtual void deepCopy(const AbstractRegistry&) = 0; - void reinitDeepCopy(const AbstractRegistry& sr) { - unregisterAll(); - deepCopy(sr); - } - - private: - Container m_list; -}; - -/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version) -/// -/// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these functions) -/// of AbstractRegistry. Any implementation of this class should be -/// explicitly (by using lock functions) -template -class Registry : public AbstractRegistry> { - public: - typedef typename Registry::iterator iterator; - typedef typename Registry::const_iterator const_iterator; - - Registry(void) {} - - /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. - Registry(const Registry& sr) : AbstractRegistry>() { - if (this == &sr) { - return; - } - this->reinitDeepCopy(sr); - } - - /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element - /// @see unregisterAll() - /// @see deepCopy(const AbstractRegistry&) - Registry& operator=(const Registry& sr) { - if (this == &sr) { - return *this; - } - this->reinitDeepCopy(sr); - return *this; - } - - virtual ~Registry(void) { - unregisterAll(); - } - - protected: - virtual void unregisterAll(void) ELPP_FINAL { - if (!this->empty()) { - for (auto&& curr : this->list()) { - base::utils::safeDelete(curr.second); - } - this->list().clear(); - } - } - -/// @brief Registers new registry to repository. - virtual void registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL { - unregister(uniqKey); - this->list().insert(std::make_pair(uniqKey, ptr)); - } - -/// @brief Unregisters single entry mapped to specified unique key - void unregister(const T_Key& uniqKey) { - T_Ptr* existing = get(uniqKey); - if (existing != nullptr) { - this->list().erase(uniqKey); - base::utils::safeDelete(existing); - } - } - -/// @brief Gets pointer from repository. If none found, nullptr is returned. - T_Ptr* get(const T_Key& uniqKey) { - iterator it = this->list().find(uniqKey); - return it == this->list().end() - ? nullptr - : it->second; - } - - private: - virtual void deepCopy(const AbstractRegistry>& sr) ELPP_FINAL { - for (const_iterator it = sr.cbegin(); it != sr.cend(); ++it) { - registerNew(it->first, new T_Ptr(*it->second)); - } - } -}; - -/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version) -/// -/// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry. Any implementation of this class -/// should be made thread-safe explicitly -template -class RegistryWithPred : public AbstractRegistry> { - public: - typedef typename RegistryWithPred::iterator iterator; - typedef typename RegistryWithPred::const_iterator const_iterator; - - RegistryWithPred(void) { - } - - virtual ~RegistryWithPred(void) { - unregisterAll(); - } - - /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. - RegistryWithPred(const RegistryWithPred& sr) : AbstractRegistry>() { - if (this == &sr) { - return; - } - this->reinitDeepCopy(sr); - } - - /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element - /// @see unregisterAll() - /// @see deepCopy(const AbstractRegistry&) - RegistryWithPred& operator=(const RegistryWithPred& sr) { - if (this == &sr) { - return *this; - } - this->reinitDeepCopy(sr); - return *this; - } - - friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const RegistryWithPred& sr) { - for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { - os << ELPP_LITERAL(" ") << **it << ELPP_LITERAL("\n"); - } - return os; - } - - protected: - virtual void unregisterAll(void) ELPP_FINAL { - if (!this->empty()) { - for (auto&& curr : this->list()) { - base::utils::safeDelete(curr); - } - this->list().clear(); - } - } - - virtual void unregister(T_Ptr*& ptr) ELPP_FINAL { - if (ptr) { - iterator iter = this->begin(); - for (; iter != this->end(); ++iter) { - if (ptr == *iter) { - break; - } - } - if (iter != this->end() && *iter != nullptr) { - this->list().erase(iter); - base::utils::safeDelete(*iter); - } - } - } - - virtual inline void registerNew(T_Ptr* ptr) ELPP_FINAL { - this->list().push_back(ptr); - } - -/// @brief Gets pointer from repository with speicifed arguments. Arguments are passed to predicate -/// in order to validate pointer. - template - T_Ptr* get(const T& arg1, const T2 arg2) { - iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2)); - if (iter != this->list().end() && *iter != nullptr) { - return *iter; - } - return nullptr; - } - - private: - virtual void deepCopy(const AbstractRegistry>& sr) { - for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { - registerNew(new T_Ptr(**it)); - } - } -}; -class Utils { - public: - template - static bool installCallback(const std::string& id, std::unordered_map* mapT) { - if (mapT->find(id) == mapT->end()) { - mapT->insert(std::make_pair(id, TPtr(new T()))); - return true; - } - return false; - } - - template - static void uninstallCallback(const std::string& id, std::unordered_map* mapT) { - if (mapT->find(id) != mapT->end()) { - mapT->erase(id); - } - } - - template - static T* callback(const std::string& id, std::unordered_map* mapT) { - typename std::unordered_map::iterator iter = mapT->find(id); - if (iter != mapT->end()) { - return static_cast(iter->second.get()); - } - return nullptr; - } -}; -} // namespace utils -} // namespace base -/// @brief Base of Easylogging++ friendly class -/// -/// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const` -class Loggable { - public: - virtual ~Loggable(void) {} - virtual void log(el::base::type::ostream_t&) const = 0; - private: - friend inline el::base::type::ostream_t& operator<<(el::base::type::ostream_t& os, const Loggable& loggable) { - loggable.log(os); - return os; - } -}; -namespace base { -/// @brief Represents log format containing flags and date format. This is used internally to start initial log -class LogFormat : public Loggable { - public: - LogFormat(void); - LogFormat(Level level, const base::type::string_t& format); - LogFormat(const LogFormat& logFormat); - LogFormat(LogFormat&& logFormat); - LogFormat& operator=(const LogFormat& logFormat); - virtual ~LogFormat(void) {} - bool operator==(const LogFormat& other); - - /// @brief Updates format to be used while logging. - /// @param userFormat User provided format - void parseFromFormat(const base::type::string_t& userFormat); - - inline Level level(void) const { - return m_level; - } - - inline const base::type::string_t& userFormat(void) const { - return m_userFormat; - } - - inline const base::type::string_t& format(void) const { - return m_format; - } - - inline const std::string& dateTimeFormat(void) const { - return m_dateTimeFormat; - } - - inline base::type::EnumType flags(void) const { - return m_flags; - } - - inline bool hasFlag(base::FormatFlags flag) const { - return base::utils::hasFlag(flag, m_flags); - } - - virtual void log(el::base::type::ostream_t& os) const { - os << m_format; - } - - protected: - /// @brief Updates date time format if available in currFormat. - /// @param index Index where %datetime, %date or %time was found - /// @param [in,out] currFormat current format that is being used to format - virtual void updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL; - - /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format and m_level - virtual void updateFormatSpec(void) ELPP_FINAL; - - inline void addFlag(base::FormatFlags flag) { - base::utils::addFlag(flag, &m_flags); - } - - private: - Level m_level; - base::type::string_t m_userFormat; - base::type::string_t m_format; - std::string m_dateTimeFormat; - base::type::EnumType m_flags; - std::string m_currentUser; - std::string m_currentHost; - friend class el::Logger; // To resolve loggerId format specifier easily -}; -} // namespace base -/// @brief Resolving function for format specifier -typedef std::function FormatSpecifierValueResolver; -/// @brief User-provided custom format specifier -/// @see el::Helpers::installCustomFormatSpecifier -/// @see FormatSpecifierValueResolver -class CustomFormatSpecifier { - public: - CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver) : - m_formatSpecifier(formatSpecifier), m_resolver(resolver) {} - inline const char* formatSpecifier(void) const { - return m_formatSpecifier; - } - inline const FormatSpecifierValueResolver& resolver(void) const { - return m_resolver; - } - inline bool operator==(const char* formatSpecifier) { - return strcmp(m_formatSpecifier, formatSpecifier) == 0; - } - - private: - const char* m_formatSpecifier; - FormatSpecifierValueResolver m_resolver; -}; -/// @brief Represents single configuration that has representing level, configuration type and a string based value. -/// -/// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside quotes -/// and will be parsed later. -/// -/// Consider some examples below: -/// * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true"); -/// * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048"); -/// * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log"); -class Configuration : public Loggable { - public: - Configuration(const Configuration& c); - Configuration& operator=(const Configuration& c); - - virtual ~Configuration(void) { - } - - /// @brief Full constructor used to sets value of configuration - Configuration(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Gets level of current configuration - inline Level level(void) const { - return m_level; - } - - /// @brief Gets configuration type of current configuration - inline ConfigurationType configurationType(void) const { - return m_configurationType; - } - - /// @brief Gets string based configuration value - inline const std::string& value(void) const { - return m_value; - } - - /// @brief Set string based configuration value - /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any integral values - /// use them in quotes. They will be parsed when configuring - inline void setValue(const std::string& value) { - m_value = value; - } - - virtual void log(el::base::type::ostream_t& os) const; - - /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. - class Predicate { - public: - Predicate(Level level, ConfigurationType configurationType); - - bool operator()(const Configuration* conf) const; - - private: - Level m_level; - ConfigurationType m_configurationType; - }; - - private: - Level m_level; - ConfigurationType m_configurationType; - std::string m_value; -}; - -/// @brief Thread-safe Configuration repository -/// -/// @detail This repository represents configurations for all the levels and configuration type mapped to a value. -class Configurations : public base::utils::RegistryWithPred { - public: - /// @brief Default constructor with empty repository - Configurations(void); - - /// @brief Constructor used to set configurations using configuration file. - /// @param configurationFile Full path to configuration file - /// @param useDefaultsForRemaining Lets you set the remaining configurations to default. - /// @param base If provided, this configuration will be based off existing repository that this argument is pointing to. - /// @see parseFromFile(const std::string&, Configurations* base) - /// @see setRemainingToDefault() - Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true, - Configurations* base = nullptr); - - virtual ~Configurations(void) { - } - - /// @brief Parses configuration from file. - /// @param configurationFile Full path to configuration file - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration file. - /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you - /// do not proceed without successful parse. - bool parseFromFile(const std::string& configurationFile, Configurations* base = nullptr); - - /// @brief Parse configurations from configuration string. - /// - /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary - /// new line characters are provided. - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration text. - /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you - /// do not proceed without successful parse. - bool parseFromText(const std::string& configurationsString, Configurations* base = nullptr); - - /// @brief Sets configuration based-off an existing configurations. - /// @param base Pointer to existing configurations. - void setFromBase(Configurations* base); - - /// @brief Determines whether or not specified configuration type exists in the repository. - /// - /// @detail Returns as soon as first level is found. - /// @param configurationType Type of configuration to check existence for. - bool hasConfiguration(ConfigurationType configurationType); - - /// @brief Determines whether or not specified configuration type exists for specified level - /// @param level Level to check - /// @param configurationType Type of configuration to check existence for. - bool hasConfiguration(Level level, ConfigurationType configurationType); - - /// @brief Sets value of configuration for specified level. - /// - /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types - /// ConfigurationType::SubsecondPrecision and ConfigurationType::PerformanceTracking will be ignored if not set for - /// Level::Global because these configurations are not dependant on level. - /// @param level Level to set configuration for (el::Level). - /// @param configurationType Type of configuration (el::ConfigurationType) - /// @param value A string based value. Regardless of what the data type of configuration is, it will always be string - /// from users' point of view. This is then parsed later to be used internally. - /// @see Configuration::setValue(const std::string& value) - /// @see el::Level - /// @see el::ConfigurationType - void set(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Sets single configuration based on other single configuration. - /// @see set(Level level, ConfigurationType configurationType, const std::string& value) - void set(Configuration* conf); - - inline Configuration* get(Level level, ConfigurationType configurationType) { - base::threading::ScopedLock scopedLock(lock()); - return RegistryWithPred::get(level, configurationType); - } - - /// @brief Sets configuration for all levels. - /// @param configurationType Type of configuration - /// @param value String based value - /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) - inline void setGlobally(ConfigurationType configurationType, const std::string& value) { - setGlobally(configurationType, value, false); - } - - /// @brief Clears repository so that all the configurations are unset - inline void clear(void) { - base::threading::ScopedLock scopedLock(lock()); - unregisterAll(); - } - - /// @brief Gets configuration file used in parsing this configurations. - /// - /// @detail If this repository was set manually or by text this returns empty string. - inline const std::string& configurationFile(void) const { - return m_configurationFile; - } - - /// @brief Sets configurations to "factory based" configurations. - void setToDefault(void); - - /// @brief Lets you set the remaining configurations to default. - /// - /// @detail By remaining, it means that the level/type a configuration does not exist for. - /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file that sets - /// configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set to default i.e, - /// true. If you dont do this explicitly (either by calling this function or by using second param in Constructor - /// and try to access a value, an error is thrown - void setRemainingToDefault(void); - - /// @brief Parser used internally to parse configurations from file or text. - /// - /// @detail This class makes use of base::utils::Str. - /// You should not need this unless you are working on some tool for Easylogging++ - class Parser : base::StaticClass { - public: - /// @brief Parses configuration from file. - /// @param configurationFile Full path to configuration file - /// @param sender Sender configurations pointer. Usually 'this' is used from calling class - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration file. - /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you - /// do not proceed without successful parse. - static bool parseFromFile(const std::string& configurationFile, Configurations* sender, - Configurations* base = nullptr); - - /// @brief Parse configurations from configuration string. - /// - /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary - /// new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you - /// do not proceed without successful parse (This is recommended) - /// @param configurationsString the configuration in plain text format - /// @param sender Sender configurations pointer. Usually 'this' is used from calling class - /// @param base Configurations to base new configuration repository off. This value is used when you want to use - /// existing Configurations to base all the values and then set rest of configuration via configuration text. - /// @return True if successfully parsed, false otherwise. - static bool parseFromText(const std::string& configurationsString, Configurations* sender, - Configurations* base = nullptr); - - private: - friend class el::Loggers; - static void ignoreComments(std::string* line); - static bool isLevel(const std::string& line); - static bool isComment(const std::string& line); - static inline bool isConfig(const std::string& line); - static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel, - Configurations* conf); - }; - - private: - std::string m_configurationFile; - bool m_isFromFile; - friend class el::Loggers; - - /// @brief Unsafely sets configuration if does not already exist - void unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Thread unsafe set - void unsafeSet(Level level, ConfigurationType configurationType, const std::string& value); - - /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true - /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) - void setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel); - - /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true - /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) - void unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel); -}; - -namespace base { -typedef std::shared_ptr FileStreamPtr; -typedef std::unordered_map LogStreamsReferenceMap; -/// @brief Configurations with data types. -/// -/// @detail el::Configurations have string based values. This is whats used internally in order to read correct configurations. -/// This is to perform faster while writing logs using correct configurations. -/// -/// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class) -class TypedConfigurations : public base::threading::ThreadSafe { - public: - /// @brief Constructor to initialize (construct) the object off el::Configurations - /// @param configurations Configurations pointer/reference to base this typed configurations off. - /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference() - TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference); - - TypedConfigurations(const TypedConfigurations& other); - - virtual ~TypedConfigurations(void) { - } - - const Configurations* configurations(void) const { - return m_configurations; - } - - bool enabled(Level level); - bool toFile(Level level); - const std::string& filename(Level level); - bool toStandardOutput(Level level); - const base::LogFormat& logFormat(Level level); - const base::SubsecondPrecision& subsecondPrecision(Level level = Level::Global); - const base::MillisecondsWidth& millisecondsWidth(Level level = Level::Global); - bool performanceTracking(Level level = Level::Global); - base::type::fstream_t* fileStream(Level level); - std::size_t maxLogFileSize(Level level); - std::size_t logFlushThreshold(Level level); - - private: - Configurations* m_configurations; - std::unordered_map m_enabledMap; - std::unordered_map m_toFileMap; - std::unordered_map m_filenameMap; - std::unordered_map m_toStandardOutputMap; - std::unordered_map m_logFormatMap; - std::unordered_map m_subsecondPrecisionMap; - std::unordered_map m_performanceTrackingMap; - std::unordered_map m_fileStreamMap; - std::unordered_map m_maxLogFileSizeMap; - std::unordered_map m_logFlushThresholdMap; - base::LogStreamsReferenceMap* m_logStreamsReference; - - friend class el::Helpers; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::DefaultLogDispatchCallback; - friend class el::base::LogDispatcher; - - template - inline Conf_T getConfigByVal(Level level, const std::unordered_map* confMap, const char* confName) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeGetConfigByVal(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope - } - - template - inline Conf_T& getConfigByRef(Level level, std::unordered_map* confMap, const char* confName) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeGetConfigByRef(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope - } - - template - Conf_T unsafeGetConfigByVal(Level level, const std::unordered_map* confMap, const char* confName) { - ELPP_UNUSED(confName); - typename std::unordered_map::const_iterator it = confMap->find(level); - if (it == confMap->end()) { - try { - return confMap->at(Level::Global); - } catch (...) { - ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" - << LevelHelper::convertToString(level) << "]" - << std::endl << "Please ensure you have properly configured logger.", false); - return Conf_T(); - } - } - return it->second; - } - - template - Conf_T& unsafeGetConfigByRef(Level level, std::unordered_map* confMap, const char* confName) { - ELPP_UNUSED(confName); - typename std::unordered_map::iterator it = confMap->find(level); - if (it == confMap->end()) { - try { - return confMap->at(Level::Global); - } catch (...) { - ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" - << LevelHelper::convertToString(level) << "]" - << std::endl << "Please ensure you have properly configured logger.", false); - } - } - return it->second; - } - - template - void setValue(Level level, const Conf_T& value, std::unordered_map* confMap, - bool includeGlobalLevel = true) { - // If map is empty and we are allowed to add into generic level (Level::Global), do it! - if (confMap->empty() && includeGlobalLevel) { - confMap->insert(std::make_pair(Level::Global, value)); - return; - } - // If same value exist in generic level already, dont add it to explicit level - typename std::unordered_map::iterator it = confMap->find(Level::Global); - if (it != confMap->end() && it->second == value) { - return; - } - // Now make sure we dont double up values if we really need to add it to explicit level - it = confMap->find(level); - if (it == confMap->end()) { - // Value not found for level, add new - confMap->insert(std::make_pair(level, value)); - } else { - // Value found, just update value - confMap->at(level) = value; - } - } - - void build(Configurations* configurations); - unsigned long getULong(std::string confVal); - std::string resolveFilename(const std::string& filename); - void insertFile(Level level, const std::string& fullFilename); - bool unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback); - - inline bool validateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) { - base::threading::ScopedLock scopedLock(lock()); - return unsafeValidateFileRolling(level, preRollOutCallback); - } -}; -/// @brief Class that keeps record of current line hit for occasional logging -class HitCounter { - public: - HitCounter(void) : - m_filename(""), - m_lineNumber(0), - m_hitCounts(0) { - } - - HitCounter(const char* filename, base::type::LineNumber lineNumber) : - m_filename(filename), - m_lineNumber(lineNumber), - m_hitCounts(0) { - } - - HitCounter(const HitCounter& hitCounter) : - m_filename(hitCounter.m_filename), - m_lineNumber(hitCounter.m_lineNumber), - m_hitCounts(hitCounter.m_hitCounts) { - } - - HitCounter& operator=(const HitCounter& hitCounter) { - if (&hitCounter != this) { - m_filename = hitCounter.m_filename; - m_lineNumber = hitCounter.m_lineNumber; - m_hitCounts = hitCounter.m_hitCounts; - } - return *this; - } - - virtual ~HitCounter(void) { - } - - /// @brief Resets location of current hit counter - inline void resetLocation(const char* filename, base::type::LineNumber lineNumber) { - m_filename = filename; - m_lineNumber = lineNumber; - } - - /// @brief Validates hit counts and resets it if necessary - inline void validateHitCounts(std::size_t n) { - if (m_hitCounts >= base::consts::kMaxLogPerCounter) { - m_hitCounts = (n >= 1 ? base::consts::kMaxLogPerCounter % n : 0); - } - ++m_hitCounts; - } - - inline const char* filename(void) const { - return m_filename; - } - - inline base::type::LineNumber lineNumber(void) const { - return m_lineNumber; - } - - inline std::size_t hitCounts(void) const { - return m_hitCounts; - } - - inline void increment(void) { - ++m_hitCounts; - } - - class Predicate { - public: - Predicate(const char* filename, base::type::LineNumber lineNumber) - : m_filename(filename), - m_lineNumber(lineNumber) { - } - inline bool operator()(const HitCounter* counter) { - return ((counter != nullptr) && - (strcmp(counter->m_filename, m_filename) == 0) && - (counter->m_lineNumber == m_lineNumber)); - } - - private: - const char* m_filename; - base::type::LineNumber m_lineNumber; - }; - - private: - const char* m_filename; - base::type::LineNumber m_lineNumber; - std::size_t m_hitCounts; -}; -/// @brief Repository for hit counters used across the application -class RegisteredHitCounters : public base::utils::RegistryWithPred { - public: - /// @brief Validates counter for every N, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one - /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned - bool validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n); - - /// @brief Gets hit counter registered at specified position - inline const base::HitCounter* getCounter(const char* filename, base::type::LineNumber lineNumber) { - base::threading::ScopedLock scopedLock(lock()); - return get(filename, lineNumber); - } -}; -/// @brief Action to be taken for dispatching -enum class DispatchAction : base::type::EnumType { - None = 1, NormalLog = 2, SysLog = 4, FileOnlyLog = 8, -}; -} // namespace base -template -class Callback : protected base::threading::ThreadSafe { - public: - Callback(void) : m_enabled(true) {} - inline bool enabled(void) const { - return m_enabled; - } - inline void setEnabled(bool enabled) { - base::threading::ScopedLock scopedLock(lock()); - m_enabled = enabled; - } - protected: - virtual void handle(const T* handlePtr) = 0; - private: - bool m_enabled; -}; -class LogDispatchData { - public: - LogDispatchData() : m_logMessage(nullptr), m_dispatchAction(base::DispatchAction::None) {} - inline const LogMessage* logMessage(void) const { - return m_logMessage; - } - inline base::DispatchAction dispatchAction(void) const { - return m_dispatchAction; - } - inline void setLogMessage(LogMessage* logMessage) { - m_logMessage = logMessage; - } - inline void setDispatchAction(base::DispatchAction dispatchAction) { - m_dispatchAction = dispatchAction; - } - private: - LogMessage* m_logMessage; - base::DispatchAction m_dispatchAction; - friend class base::LogDispatcher; - -}; -class LogDispatchCallback : public Callback { - protected: - virtual void handle(const LogDispatchData* data); - base::threading::Mutex& fileHandle(const LogDispatchData* data); - private: - friend class base::LogDispatcher; - std::unordered_map> m_fileLocks; - base::threading::Mutex m_fileLocksMapLock; -}; -class PerformanceTrackingCallback : public Callback { - private: - friend class base::PerformanceTracker; -}; -class LoggerRegistrationCallback : public Callback { - private: - friend class base::RegisteredLoggers; -}; -class LogBuilder : base::NoCopy { - public: - LogBuilder() : m_termSupportsColor(base::utils::OS::termSupportsColor()) {} - virtual ~LogBuilder(void) { - ELPP_INTERNAL_INFO(3, "Destroying log builder...") - } - virtual base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const = 0; - void convertToColoredOutput(base::type::string_t* logLine, Level level); - private: - bool m_termSupportsColor; - friend class el::base::DefaultLogDispatchCallback; -}; -typedef std::shared_ptr LogBuilderPtr; -/// @brief Represents a logger holding ID and configurations we need to write logs -/// -/// @detail This class does not write logs itself instead its used by writer to read configuations from. -class Logger : public base::threading::ThreadSafe, public Loggable { - public: - Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference); - Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMap* logStreamsReference); - Logger(const Logger& logger); - Logger& operator=(const Logger& logger); - - virtual ~Logger(void) { - base::utils::safeDelete(m_typedConfigurations); - } - - virtual inline void log(el::base::type::ostream_t& os) const { - os << m_id.c_str(); - } - - /// @brief Configures the logger using specified configurations. - void configure(const Configurations& configurations); - - /// @brief Reconfigures logger using existing configurations - void reconfigure(void); - - inline const std::string& id(void) const { - return m_id; - } - - inline const std::string& parentApplicationName(void) const { - return m_parentApplicationName; - } - - inline void setParentApplicationName(const std::string& parentApplicationName) { - m_parentApplicationName = parentApplicationName; - } - - inline Configurations* configurations(void) { - return &m_configurations; - } - - inline base::TypedConfigurations* typedConfigurations(void) { - return m_typedConfigurations; - } - - static bool isValidId(const std::string& id); - - /// @brief Flushes logger to sync all log files for all levels - void flush(void); - - void flush(Level level, base::type::fstream_t* fs); - - inline bool isFlushNeeded(Level level) { - return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level); - } - - inline LogBuilder* logBuilder(void) const { - return m_logBuilder.get(); - } - - inline void setLogBuilder(const LogBuilderPtr& logBuilder) { - m_logBuilder = logBuilder; - } - - inline bool enabled(Level level) const { - return m_typedConfigurations->enabled(level); - } - -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -# define LOGGER_LEVEL_WRITERS_SIGNATURES(FUNCTION_NAME)\ -template \ -inline void FUNCTION_NAME(const char*, const T&, const Args&...);\ -template \ -inline void FUNCTION_NAME(const T&); - - template - inline void verbose(int, const char*, const T&, const Args&...); - - template - inline void verbose(int, const T&); - - LOGGER_LEVEL_WRITERS_SIGNATURES(info) - LOGGER_LEVEL_WRITERS_SIGNATURES(debug) - LOGGER_LEVEL_WRITERS_SIGNATURES(warn) - LOGGER_LEVEL_WRITERS_SIGNATURES(error) - LOGGER_LEVEL_WRITERS_SIGNATURES(fatal) - LOGGER_LEVEL_WRITERS_SIGNATURES(trace) -# undef LOGGER_LEVEL_WRITERS_SIGNATURES -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED - private: - std::string m_id; - base::TypedConfigurations* m_typedConfigurations; - base::type::stringstream_t m_stream; - std::string m_parentApplicationName; - bool m_isConfigured; - Configurations m_configurations; - std::unordered_map m_unflushedCount; - base::LogStreamsReferenceMap* m_logStreamsReference; - LogBuilderPtr m_logBuilder; - - friend class el::LogMessage; - friend class el::Loggers; - friend class el::Helpers; - friend class el::base::RegisteredLoggers; - friend class el::base::DefaultLogDispatchCallback; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::PErrorWriter; - friend class el::base::Storage; - friend class el::base::PerformanceTracker; - friend class el::base::LogDispatcher; - - Logger(void); - -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED - template - void log_(Level, int, const char*, const T&, const Args&...); - - template - inline void log_(Level, int, const T&); - - template - void log(Level, const char*, const T&, const Args&...); - - template - inline void log(Level, const T&); -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED - - void initUnflushedCount(void); - - inline base::type::stringstream_t& stream(void) { - return m_stream; - } - - void resolveLoggerFormatSpec(void) const; -}; -namespace base { -/// @brief Loggers repository -class RegisteredLoggers : public base::utils::Registry { - public: - explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder); - - virtual ~RegisteredLoggers(void) { - unsafeFlushAll(); - } - - inline void setDefaultConfigurations(const Configurations& configurations) { - base::threading::ScopedLock scopedLock(lock()); - m_defaultConfigurations.setFromBase(const_cast(&configurations)); - } - - inline Configurations* defaultConfigurations(void) { - return &m_defaultConfigurations; - } - - Logger* get(const std::string& id, bool forceCreation = true); - - template - inline bool installLoggerRegistrationCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, - &m_loggerRegistrationCallbacks); - } - - template - inline void uninstallLoggerRegistrationCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, &m_loggerRegistrationCallbacks); - } - - template - inline T* loggerRegistrationCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_loggerRegistrationCallbacks); - } - - bool remove(const std::string& id); - - inline bool has(const std::string& id) { - return get(id, false) != nullptr; - } - - inline void unregister(Logger*& logger) { - base::threading::ScopedLock scopedLock(lock()); - base::utils::Registry::unregister(logger->id()); - } - - inline base::LogStreamsReferenceMap* logStreamsReference(void) { - return &m_logStreamsReference; - } - - inline void flushAll(void) { - base::threading::ScopedLock scopedLock(lock()); - unsafeFlushAll(); - } - - inline void setDefaultLogBuilder(LogBuilderPtr& logBuilderPtr) { - base::threading::ScopedLock scopedLock(lock()); - m_defaultLogBuilder = logBuilderPtr; - } - - private: - LogBuilderPtr m_defaultLogBuilder; - Configurations m_defaultConfigurations; - base::LogStreamsReferenceMap m_logStreamsReference; - std::unordered_map m_loggerRegistrationCallbacks; - friend class el::base::Storage; - - void unsafeFlushAll(void); -}; -/// @brief Represents registries for verbose logging -class VRegistry : base::NoCopy, public base::threading::ThreadSafe { - public: - explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags); - - /// @brief Sets verbose level. Accepted range is 0-9 - void setLevel(base::type::VerboseLevel level); - - inline base::type::VerboseLevel level(void) const { - return m_level; - } - - inline void clearCategories(void) { - base::threading::ScopedLock scopedLock(lock()); - m_categories.clear(); - m_cached_allowed_categories.clear(); - m_lowest_priority = INT_MAX; - } - - inline void clearModules(void) { - base::threading::ScopedLock scopedLock(lock()); - m_modules.clear(); - } - - void setCategories(const char* categories, bool clear = true); - - std::string getCategories(); - - void setModules(const char* modules); - - bool allowed(Level level, const std::string &category); - - bool allowed(base::type::VerboseLevel vlevel, const char* file); - - inline const std::unordered_map& modules(void) const { - return m_modules; - } - - void setFromArgs(const base::utils::CommandLineArgs* commandLineArgs); - - /// @brief Whether or not vModules enabled - inline bool vModulesEnabled(void) { - return !base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags); - } - - inline void setFilenameCommonPrefix(const std::string &prefix) { - m_filenameCommonPrefix = prefix; - } - - inline const std::string &getFilenameCommonPrefix() const { - return m_filenameCommonPrefix; - } - - private: - base::type::VerboseLevel m_level; - base::type::EnumType* m_pFlags; - std::unordered_map m_modules; - std::vector> m_categories; - std::map m_cached_allowed_categories; - std::string m_categoriesString; - std::string m_filenameCommonPrefix; - std::atomic m_lowest_priority; -}; -} // namespace base -class LogMessage { - public: - LogMessage(Level level, const std::string& file, base::type::LineNumber line, const std::string& func, - base::type::VerboseLevel verboseLevel, Logger* logger) : - m_level(level), m_file(file), m_line(line), m_func(func), - m_verboseLevel(verboseLevel), m_logger(logger), m_message(logger->stream().str()) { - } - inline Level level(void) const { - return m_level; - } - inline const std::string& file(void) const { - return m_file; - } - inline base::type::LineNumber line(void) const { - return m_line; - } - inline const std::string& func(void) const { - return m_func; - } - inline base::type::VerboseLevel verboseLevel(void) const { - return m_verboseLevel; - } - inline Logger* logger(void) const { - return m_logger; - } - inline const base::type::string_t& message(void) const { - return m_message; - } - private: - Level m_level; - std::string m_file; - base::type::LineNumber m_line; - std::string m_func; - base::type::VerboseLevel m_verboseLevel; - Logger* m_logger; - base::type::string_t m_message; -}; -namespace base { -#if ELPP_ASYNC_LOGGING -class AsyncLogItem { - public: - explicit AsyncLogItem(const LogMessage& logMessage, const LogDispatchData& data, const base::type::string_t& logLine) - : m_logMessage(logMessage), m_dispatchData(data), m_logLine(logLine) {} - virtual ~AsyncLogItem() {} - inline LogMessage* logMessage(void) { - return &m_logMessage; - } - inline LogDispatchData* data(void) { - return &m_dispatchData; - } - inline base::type::string_t logLine(void) { - return m_logLine; - } - private: - LogMessage m_logMessage; - LogDispatchData m_dispatchData; - base::type::string_t m_logLine; -}; -class AsyncLogQueue : public base::threading::ThreadSafe { - public: - virtual ~AsyncLogQueue() { - ELPP_INTERNAL_INFO(6, "~AsyncLogQueue"); - } - - inline AsyncLogItem next(void) { - base::threading::ScopedLock scopedLock(lock()); - AsyncLogItem result = m_queue.front(); - m_queue.pop(); - return result; - } - - inline void push(const AsyncLogItem& item) { - base::threading::ScopedLock scopedLock(lock()); - m_queue.push(item); - } - inline void pop(void) { - base::threading::ScopedLock scopedLock(lock()); - m_queue.pop(); - } - inline AsyncLogItem front(void) { - base::threading::ScopedLock scopedLock(lock()); - return m_queue.front(); - } - inline bool empty(void) { - base::threading::ScopedLock scopedLock(lock()); - return m_queue.empty(); - } - private: - std::queue m_queue; -}; -class IWorker { - public: - virtual ~IWorker() {} - virtual void start() = 0; -}; -#endif // ELPP_ASYNC_LOGGING -/// @brief Easylogging++ management storage -class Storage : base::NoCopy, public base::threading::ThreadSafe { - public: -#if ELPP_ASYNC_LOGGING - Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker); -#else - explicit Storage(const LogBuilderPtr& defaultLogBuilder); -#endif // ELPP_ASYNC_LOGGING - - virtual ~Storage(void); - - inline bool validateEveryNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t occasion) { - return hitCounters()->validateEveryN(filename, lineNumber, occasion); - } - - inline bool validateAfterNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - return hitCounters()->validateAfterN(filename, lineNumber, n); - } - - inline bool validateNTimesCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { - return hitCounters()->validateNTimes(filename, lineNumber, n); - } - - inline base::RegisteredHitCounters* hitCounters(void) const { - return m_registeredHitCounters; - } - - inline base::RegisteredLoggers* registeredLoggers(void) const { - return m_registeredLoggers; - } - - inline base::VRegistry* vRegistry(void) const { - return m_vRegistry; - } - -#if ELPP_ASYNC_LOGGING - inline base::AsyncLogQueue* asyncLogQueue(void) const { - return m_asyncLogQueue; - } -#endif // ELPP_ASYNC_LOGGING - - inline const base::utils::CommandLineArgs* commandLineArgs(void) const { - return &m_commandLineArgs; - } - - inline void addFlag(LoggingFlag flag) { - base::utils::addFlag(flag, &m_flags); - } - - inline void removeFlag(LoggingFlag flag) { - base::utils::removeFlag(flag, &m_flags); - } - - inline bool hasFlag(LoggingFlag flag) const { - return base::utils::hasFlag(flag, m_flags); - } - - inline base::type::EnumType flags(void) const { - return m_flags; - } - - inline void setFlags(base::type::EnumType flags) { - m_flags = flags; - } - - inline void setPreRollOutCallback(const PreRollOutCallback& callback) { - m_preRollOutCallback = callback; - } - - inline void unsetPreRollOutCallback(void) { - m_preRollOutCallback = base::defaultPreRollOutCallback; - } - - inline PreRollOutCallback& preRollOutCallback(void) { - return m_preRollOutCallback; - } - - bool hasCustomFormatSpecifier(const char* formatSpecifier); - void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier); - bool uninstallCustomFormatSpecifier(const char* formatSpecifier); - - const std::vector* customFormatSpecifiers(void) const { - return &m_customFormatSpecifiers; - } - - base::threading::Mutex& customFormatSpecifiersLock() { - return m_customFormatSpecifiersLock; - } - - inline void setLoggingLevel(Level level) { - m_loggingLevel = level; - } - - template - inline bool installLogDispatchCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, &m_logDispatchCallbacks); - } - - template - inline void uninstallLogDispatchCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, &m_logDispatchCallbacks); - } - template - inline T* logDispatchCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_logDispatchCallbacks); - } - -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - template - inline bool installPerformanceTrackingCallback(const std::string& id) { - return base::utils::Utils::installCallback(id, - &m_performanceTrackingCallbacks); - } - - template - inline void uninstallPerformanceTrackingCallback(const std::string& id) { - base::utils::Utils::uninstallCallback(id, - &m_performanceTrackingCallbacks); - } - - template - inline T* performanceTrackingCallback(const std::string& id) { - return base::utils::Utils::callback(id, &m_performanceTrackingCallbacks); - } -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - - /// @brief Sets thread name for current thread. Requires std::thread - inline void setThreadName(const std::string& name) { - if (name.empty()) return; - base::threading::ScopedLock scopedLock(m_threadNamesLock); - m_threadNames[base::threading::getCurrentThreadId()] = name; - } - - inline std::string getThreadName(const std::string& threadId) { - base::threading::ScopedLock scopedLock(m_threadNamesLock); - std::unordered_map::const_iterator it = m_threadNames.find(threadId); - if (it == m_threadNames.end()) { - return threadId; - } - return it->second; - } - - static el::base::type::StoragePointer &getELPP(); - - private: - base::RegisteredHitCounters* m_registeredHitCounters; - base::RegisteredLoggers* m_registeredLoggers; - base::type::EnumType m_flags; - base::VRegistry* m_vRegistry; -#if ELPP_ASYNC_LOGGING - base::AsyncLogQueue* m_asyncLogQueue; - base::IWorker* m_asyncDispatchWorker; -#endif // ELPP_ASYNC_LOGGING - base::utils::CommandLineArgs m_commandLineArgs; - PreRollOutCallback m_preRollOutCallback; - std::unordered_map m_logDispatchCallbacks; - std::unordered_map m_performanceTrackingCallbacks; - std::unordered_map m_threadNames; - std::vector m_customFormatSpecifiers; - base::threading::Mutex m_customFormatSpecifiersLock; - base::threading::Mutex m_threadNamesLock; - Level m_loggingLevel; - - friend class el::Helpers; - friend class el::base::DefaultLogDispatchCallback; - friend class el::LogBuilder; - friend class el::base::MessageBuilder; - friend class el::base::Writer; - friend class el::base::PerformanceTracker; - friend class el::base::LogDispatcher; - - void setApplicationArguments(int argc, char** argv); - - inline void setApplicationArguments(int argc, const char** argv) { - setApplicationArguments(argc, const_cast(argv)); - } -}; -extern ELPP_EXPORT base::type::StoragePointer elStorage; -#define ELPP el::base::Storage::getELPP() -class DefaultLogDispatchCallback : public LogDispatchCallback { - protected: - void handle(const LogDispatchData* data); - private: - const LogDispatchData* m_data; - void dispatch(base::type::string_t&& rawLine, base::type::string_t&& logLine); -}; -#if ELPP_ASYNC_LOGGING -class AsyncLogDispatchCallback : public LogDispatchCallback { - protected: - void handle(const LogDispatchData* data); -}; -class AsyncDispatchWorker : public base::IWorker, public base::threading::ThreadSafe { - public: - AsyncDispatchWorker(); - virtual ~AsyncDispatchWorker(); - - bool clean(void); - void emptyQueue(void); - virtual void start(void); - void handle(AsyncLogItem* logItem); - void run(void); - - void setContinueRunning(bool value) { - base::threading::ScopedLock scopedLock(m_continueRunningLock); - m_continueRunning = value; - } - - bool continueRunning(void) const { - return m_continueRunning; - } - private: - std::condition_variable cv; - bool m_continueRunning; - base::threading::Mutex m_continueRunningLock; -}; -#endif // ELPP_ASYNC_LOGGING -} // namespace base -namespace base { -class DefaultLogBuilder : public LogBuilder { - public: - base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const; -}; -/// @brief Dispatches log messages -class LogDispatcher : base::NoCopy { - public: - LogDispatcher(bool proceed, LogMessage* logMessage, base::DispatchAction dispatchAction) : - m_proceed(proceed), - m_logMessage(logMessage), - m_dispatchAction(std::move(dispatchAction)) { - } - - void dispatch(void); - - private: - bool m_proceed; - LogMessage* m_logMessage; - base::DispatchAction m_dispatchAction; -}; -#if defined(ELPP_STL_LOGGING) -/// @brief Workarounds to write some STL logs -/// -/// @detail There is workaround needed to loop through some stl containers. In order to do that, we need iterable containers -/// of same type and provide iterator interface and pass it on to writeIterator(). -/// Remember, this is passed by value in constructor so that we dont change original containers. -/// This operation is as expensive as Big-O(std::min(class_.size(), base::consts::kMaxLogPerContainer)) -namespace workarounds { -/// @brief Abstract IterableContainer template that provides interface for iterable classes of type T -template -class IterableContainer { - public: - typedef typename Container::iterator iterator; - typedef typename Container::const_iterator const_iterator; - IterableContainer(void) {} - virtual ~IterableContainer(void) {} - iterator begin(void) { - return getContainer().begin(); - } - iterator end(void) { - return getContainer().end(); - } - private: - virtual Container& getContainer(void) = 0; -}; -/// @brief Implements IterableContainer and provides iterable std::priority_queue class -template, typename Comparator = std::less> -class IterablePriorityQueue : public IterableContainer, - public std::priority_queue { - public: - IterablePriorityQueue(std::priority_queue queue_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { - this->push(queue_.top()); - queue_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -/// @brief Implements IterableContainer and provides iterable std::queue class -template> -class IterableQueue : public IterableContainer, public std::queue { - public: - IterableQueue(std::queue queue_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { - this->push(queue_.front()); - queue_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -/// @brief Implements IterableContainer and provides iterable std::stack class -template> -class IterableStack : public IterableContainer, public std::stack { - public: - IterableStack(std::stack stack_) { - std::size_t count_ = 0; - while (++count_ < base::consts::kMaxLogPerContainer && !stack_.empty()) { - this->push(stack_.top()); - stack_.pop(); - } - } - private: - inline Container& getContainer(void) { - return this->c; - } -}; -} // namespace workarounds -#endif // defined(ELPP_STL_LOGGING) -// Log message builder -class MessageBuilder { - public: - MessageBuilder(void) : m_logger(nullptr), m_containerLogSeperator(ELPP_LITERAL("")) {} - void initialize(Logger* logger); - -# define ELPP_SIMPLE_LOG(LOG_TYPE)\ -MessageBuilder& operator<<(LOG_TYPE msg) {\ -m_logger->stream() << msg;\ -if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {\ -m_logger->stream() << " ";\ -}\ -return *this;\ -} - - inline MessageBuilder& operator<<(const std::string& msg) { - return operator<<(msg.c_str()); - } - ELPP_SIMPLE_LOG(char) - ELPP_SIMPLE_LOG(bool) - ELPP_SIMPLE_LOG(signed short) - ELPP_SIMPLE_LOG(unsigned short) - ELPP_SIMPLE_LOG(signed int) - ELPP_SIMPLE_LOG(unsigned int) - ELPP_SIMPLE_LOG(signed long) - ELPP_SIMPLE_LOG(unsigned long) - ELPP_SIMPLE_LOG(float) - ELPP_SIMPLE_LOG(double) - ELPP_SIMPLE_LOG(char*) - ELPP_SIMPLE_LOG(const char*) - ELPP_SIMPLE_LOG(const void*) - ELPP_SIMPLE_LOG(long double) - inline MessageBuilder& operator<<(const std::wstring& msg) { - return operator<<(msg.c_str()); - } - MessageBuilder& operator<<(const wchar_t* msg); - // ostream manipulators - inline MessageBuilder& operator<<(std::ostream& (*OStreamMani)(std::ostream&)) { - m_logger->stream() << OStreamMani; - return *this; - } -#define ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} -#define ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(temp) \ -template \ -inline MessageBuilder& operator<<(const temp& template_inst) { \ -return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ -} - -#if defined(ELPP_STL_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::list) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::deque) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::set) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::multiset) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::map) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::multimap) - template - inline MessageBuilder& operator<<(const std::queue& queue_) { - base::workarounds::IterableQueue iterableQueue_ = - static_cast >(queue_); - return writeIterator(iterableQueue_.begin(), iterableQueue_.end(), iterableQueue_.size()); - } - template - inline MessageBuilder& operator<<(const std::stack& stack_) { - base::workarounds::IterableStack iterableStack_ = - static_cast >(stack_); - return writeIterator(iterableStack_.begin(), iterableStack_.end(), iterableStack_.size()); - } - template - inline MessageBuilder& operator<<(const std::priority_queue& priorityQueue_) { - base::workarounds::IterablePriorityQueue iterablePriorityQueue_ = - static_cast >(priorityQueue_); - return writeIterator(iterablePriorityQueue_.begin(), iterablePriorityQueue_.end(), iterablePriorityQueue_.size()); - } - template - MessageBuilder& operator<<(const std::pair& pair_) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(pair_.first)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(pair_.second)); - m_logger->stream() << ELPP_LITERAL(")"); - return *this; - } - template - MessageBuilder& operator<<(const std::bitset& bitset_) { - m_logger->stream() << ELPP_LITERAL("["); - operator << (bitset_.to_string()); - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } -# if defined(ELPP_LOG_STD_ARRAY) - template - inline MessageBuilder& operator<<(const std::array& array) { - return writeIterator(array.begin(), array.end(), array.size()); - } -# endif // defined(ELPP_LOG_STD_ARRAY) -# if defined(ELPP_LOG_UNORDERED_MAP) - ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_map) - ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_multimap) -# endif // defined(ELPP_LOG_UNORDERED_MAP) -# if defined(ELPP_LOG_UNORDERED_SET) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_set) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_multiset) -# endif // defined(ELPP_LOG_UNORDERED_SET) -#endif // defined(ELPP_STL_LOGGING) -#if defined(ELPP_QT_LOGGING) - inline MessageBuilder& operator<<(const QString& msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << msg.toStdWString(); -# else - m_logger->stream() << msg.toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(const QByteArray& msg) { - return operator << (QString(msg)); - } - inline MessageBuilder& operator<<(const QStringRef& msg) { - return operator<<(msg.toString()); - } - inline MessageBuilder& operator<<(qint64 msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << QString::number(msg).toStdWString(); -# else - m_logger->stream() << QString::number(msg).toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(quint64 msg) { -# if defined(ELPP_UNICODE) - m_logger->stream() << QString::number(msg).toStdWString(); -# else - m_logger->stream() << QString::number(msg).toStdString(); -# endif // defined(ELPP_UNICODE) - return *this; - } - inline MessageBuilder& operator<<(QChar msg) { - m_logger->stream() << msg.toLatin1(); - return *this; - } - inline MessageBuilder& operator<<(const QLatin1String& msg) { - m_logger->stream() << msg.latin1(); - return *this; - } - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QList) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QVector) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QQueue) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QSet) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QLinkedList) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QStack) - template - MessageBuilder& operator<<(const QPair& pair_) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(pair_.first)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(pair_.second)); - m_logger->stream() << ELPP_LITERAL(")"); - return *this; - } - template - MessageBuilder& operator<<(const QMap& map_) { - m_logger->stream() << ELPP_LITERAL("["); - QList keys = map_.keys(); - typename QList::const_iterator begin = keys.begin(); - typename QList::const_iterator end = keys.end(); - int max_ = static_cast(base::consts::kMaxLogPerContainer); // to prevent warning - for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(*begin)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(map_.value(*begin))); - m_logger->stream() << ELPP_LITERAL(")"); - m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL("")); - } - if (begin != end) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } - template - inline MessageBuilder& operator<<(const QMultiMap& map_) { - operator << (static_cast>(map_)); - return *this; - } - template - MessageBuilder& operator<<(const QHash& hash_) { - m_logger->stream() << ELPP_LITERAL("["); - QList keys = hash_.keys(); - typename QList::const_iterator begin = keys.begin(); - typename QList::const_iterator end = keys.end(); - int max_ = static_cast(base::consts::kMaxLogPerContainer); // prevent type warning - for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { - m_logger->stream() << ELPP_LITERAL("("); - operator << (static_cast(*begin)); - m_logger->stream() << ELPP_LITERAL(", "); - operator << (static_cast(hash_.value(*begin))); - m_logger->stream() << ELPP_LITERAL(")"); - m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL("")); - } - if (begin != end) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - return *this; - } - template - inline MessageBuilder& operator<<(const QMultiHash& multiHash_) { - operator << (static_cast>(multiHash_)); - return *this; - } -#endif // defined(ELPP_QT_LOGGING) -#if defined(ELPP_BOOST_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::stable_vector) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::list) - ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::deque) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::map) - ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::flat_map) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::set) - ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::flat_set) -#endif // defined(ELPP_BOOST_LOGGING) - - /// @brief Macro used internally that can be used externally to make containers easylogging++ friendly - /// - /// @detail This macro expands to write an ostream& operator<< for container. This container is expected to - /// have begin() and end() methods that return respective iterators - /// @param ContainerType Type of container e.g, MyList from WX_DECLARE_LIST(int, MyList); in wxwidgets - /// @param SizeMethod Method used to get size of container. - /// @param ElementInstance Instance of element to be fed out. Insance name is "elem". See WXELPP_ENABLED macro - /// for an example usage -#define MAKE_CONTAINERELPP_FRIENDLY(ContainerType, SizeMethod, ElementInstance) \ -el::base::type::ostream_t& operator<<(el::base::type::ostream_t& ss, const ContainerType& container) {\ -const el::base::type::char_t* sep = ELPP->hasFlag(el::LoggingFlag::NewLineForContainer) ? \ -ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");\ -ContainerType::const_iterator elem = container.begin();\ -ContainerType::const_iterator endElem = container.end();\ -std::size_t size_ = container.SizeMethod; \ -ss << ELPP_LITERAL("[");\ -for (std::size_t i = 0; elem != endElem && i < el::base::consts::kMaxLogPerContainer; ++i, ++elem) { \ -ss << ElementInstance;\ -ss << ((i < size_ - 1) ? sep : ELPP_LITERAL(""));\ -}\ -if (elem != endElem) {\ -ss << ELPP_LITERAL("...");\ -}\ -ss << ELPP_LITERAL("]");\ -return ss;\ -} -#if defined(ELPP_WXWIDGETS_LOGGING) - ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(wxVector) -# define ELPP_WX_PTR_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), *(*elem)) -# define ELPP_WX_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), (*elem)) -# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), \ -ELPP_LITERAL("(") << elem->first << ELPP_LITERAL(", ") << elem->second << ELPP_LITERAL(")") -#else -# define ELPP_WX_PTR_ENABLED(ContainerType) -# define ELPP_WX_ENABLED(ContainerType) -# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) -#endif // defined(ELPP_WXWIDGETS_LOGGING) - // Other classes - template - ELPP_SIMPLE_LOG(const Class&) -#undef ELPP_SIMPLE_LOG -#undef ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG -#undef ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG - private: - Logger* m_logger; - const base::type::char_t* m_containerLogSeperator; - - template - MessageBuilder& writeIterator(Iterator begin_, Iterator end_, std::size_t size_) { - m_logger->stream() << ELPP_LITERAL("["); - for (std::size_t i = 0; begin_ != end_ && i < base::consts::kMaxLogPerContainer; ++i, ++begin_) { - operator << (*begin_); - m_logger->stream() << ((i < size_ - 1) ? m_containerLogSeperator : ELPP_LITERAL("")); - } - if (begin_ != end_) { - m_logger->stream() << ELPP_LITERAL("..."); - } - m_logger->stream() << ELPP_LITERAL("]"); - if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { - m_logger->stream() << " "; - } - return *this; - } -}; -/// @brief Writes nothing - Used when certain log is disabled -class NullWriter : base::NoCopy { - public: - NullWriter(void) {} - - // Null manipulator - inline NullWriter& operator<<(std::ostream& (*)(std::ostream&)) { - return *this; - } - - template - inline NullWriter& operator<<(const T&) { - return *this; - } - - inline operator bool() { - return true; - } -}; -/// @brief Main entry point of each logging -class Writer : base::NoCopy { - public: - Writer(Level level, const char* file, base::type::LineNumber line, - const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, - base::type::VerboseLevel verboseLevel = 0) : - m_msg(nullptr), m_level(level), m_file(file), m_line(line), m_func(func), m_verboseLevel(verboseLevel), - m_logger(nullptr), m_proceed(false), m_dispatchAction(dispatchAction) { - } - - Writer(LogMessage* msg, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog) : - m_msg(msg), m_level(msg != nullptr ? msg->level() : Level::Unknown), - m_line(0), m_logger(nullptr), m_proceed(false), m_dispatchAction(dispatchAction) { - } - - virtual ~Writer(void) { - processDispatch(); - } - - template - inline typename std::enable_if::value, Writer&>::type - operator<<(T log) { -#if ELPP_LOGGING_ENABLED - if (m_proceed) { - m_messageBuilder << log; - } -#endif // ELPP_LOGGING_ENABLED - return *this; - } - - template - inline typename std::enable_if::value, Writer&>::type - operator<<(const T& log) { -#if ELPP_LOGGING_ENABLED - if (m_proceed) { - m_messageBuilder << log; - } -#endif // ELPP_LOGGING_ENABLED - return *this; - } - - inline Writer& operator<<(std::ostream& (*log)(std::ostream&)) { -#if ELPP_LOGGING_ENABLED - if (m_proceed) { - m_messageBuilder << log; - } -#endif // ELPP_LOGGING_ENABLED - return *this; - } - - inline operator bool() { - return true; - } - - Writer& construct(Logger* logger, bool needLock = true); - Writer& construct(int count, const char* loggerIds, ...); - Writer& construct(const char *loggerId); - protected: - LogMessage* m_msg; - Level m_level; - const char* m_file; - const base::type::LineNumber m_line; - const char* m_func; - base::type::VerboseLevel m_verboseLevel; - Logger* m_logger; - bool m_proceed; - base::MessageBuilder m_messageBuilder; - base::DispatchAction m_dispatchAction; - std::vector m_loggerIds; - friend class el::Helpers; - - void initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true); - void initializeLogger(Logger *logger, bool needLock = true); - void processDispatch(); - void triggerDispatch(void); -}; -class PErrorWriter : public base::Writer { - public: - PErrorWriter(Level level, const char* file, base::type::LineNumber line, - const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, - base::type::VerboseLevel verboseLevel = 0) : - base::Writer(level, file, line, func, dispatchAction, verboseLevel) { - } - - virtual ~PErrorWriter(void); -}; -} // namespace base -// Logging from Logger class. Why this is here? Because we have Storage and Writer class available -#if ELPP_VARIADIC_TEMPLATES_SUPPORTED -template -void Logger::log_(Level level, int vlevel, const char* s, const T& value, const Args&... args) { - base::MessageBuilder b; - b.initialize(this); - while (*s) { - if (*s == base::consts::kFormatSpecifierChar) { - if (*(s + 1) == base::consts::kFormatSpecifierChar) { - ++s; - } else { - if (*(s + 1) == base::consts::kFormatSpecifierCharValue) { - ++s; - b << value; - log_(level, vlevel, ++s, args...); - return; - } - } - } - b << *s++; - } - ELPP_INTERNAL_ERROR("Too many arguments provided. Unable to handle. Please provide more format specifiers", false); -} -template -void Logger::log_(Level level, int vlevel, const T& log) { - if (level == Level::Verbose) { - if (ELPP->vRegistry()->allowed(vlevel, __FILE__)) { - base::Writer(Level::Verbose, "FILE", 0, "FUNCTION", - base::DispatchAction::NormalLog, vlevel).construct(this, false) << log; - } else { - stream().str(ELPP_LITERAL("")); - releaseLock(); - } - } else { - base::Writer(level, "FILE", 0, "FUNCTION").construct(this, false) << log; - } -} -template -inline void Logger::log(Level level, const char* s, const T& value, const Args&... args) { - acquireLock(); // released in Writer! - log_(level, 0, s, value, args...); -} -template -inline void Logger::log(Level level, const T& log) { - acquireLock(); // released in Writer! - log_(level, 0, log); -} -# if ELPP_VERBOSE_LOG -template -inline void Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) { - acquireLock(); // released in Writer! - log_(el::Level::Verbose, vlevel, s, value, args...); -} -template -inline void Logger::verbose(int vlevel, const T& log) { - acquireLock(); // released in Writer! - log_(el::Level::Verbose, vlevel, log); -} -# else -template -inline void Logger::verbose(int, const char*, const T&, const Args&...) { - return; -} -template -inline void Logger::verbose(int, const T&) { - return; -} -# endif // ELPP_VERBOSE_LOG -# define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)\ -template \ -inline void Logger::FUNCTION_NAME(const char* s, const T& value, const Args&... args) {\ -log(LOG_LEVEL, s, value, args...);\ -}\ -template \ -inline void Logger::FUNCTION_NAME(const T& value) {\ -log(LOG_LEVEL, value);\ -} -# define LOGGER_LEVEL_WRITERS_DISABLED(FUNCTION_NAME, LOG_LEVEL)\ -template \ -inline void Logger::FUNCTION_NAME(const char*, const T&, const Args&...) {\ -return;\ -}\ -template \ -inline void Logger::FUNCTION_NAME(const T&) {\ -return;\ -} - -# if ELPP_INFO_LOG -LOGGER_LEVEL_WRITERS(info, Level::Info) -# else -LOGGER_LEVEL_WRITERS_DISABLED(info, Level::Info) -# endif // ELPP_INFO_LOG -# if ELPP_DEBUG_LOG -LOGGER_LEVEL_WRITERS(debug, Level::Debug) -# else -LOGGER_LEVEL_WRITERS_DISABLED(debug, Level::Debug) -# endif // ELPP_DEBUG_LOG -# if ELPP_WARNING_LOG -LOGGER_LEVEL_WRITERS(warn, Level::Warning) -# else -LOGGER_LEVEL_WRITERS_DISABLED(warn, Level::Warning) -# endif // ELPP_WARNING_LOG -# if ELPP_ERROR_LOG -LOGGER_LEVEL_WRITERS(error, Level::Error) -# else -LOGGER_LEVEL_WRITERS_DISABLED(error, Level::Error) -# endif // ELPP_ERROR_LOG -# if ELPP_FATAL_LOG -LOGGER_LEVEL_WRITERS(fatal, Level::Fatal) -# else -LOGGER_LEVEL_WRITERS_DISABLED(fatal, Level::Fatal) -# endif // ELPP_FATAL_LOG -# if ELPP_TRACE_LOG -LOGGER_LEVEL_WRITERS(trace, Level::Trace) -# else -LOGGER_LEVEL_WRITERS_DISABLED(trace, Level::Trace) -# endif // ELPP_TRACE_LOG -# undef LOGGER_LEVEL_WRITERS -# undef LOGGER_LEVEL_WRITERS_DISABLED -#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED -#if ELPP_COMPILER_MSVC -# define ELPP_VARIADIC_FUNC_MSVC(variadicFunction, variadicArgs) variadicFunction variadicArgs -# define ELPP_VARIADIC_FUNC_MSVC_RUN(variadicFunction, ...) ELPP_VARIADIC_FUNC_MSVC(variadicFunction, (__VA_ARGS__)) -# define el_getVALength(...) ELPP_VARIADIC_FUNC_MSVC_RUN(el_resolveVALength, 0, ## __VA_ARGS__,\ -10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -#else -# if ELPP_COMPILER_CLANG -# define el_getVALength(...) el_resolveVALength(0, __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -# else -# define el_getVALength(...) el_resolveVALength(0, ## __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) -# endif // ELPP_COMPILER_CLANG -#endif // ELPP_COMPILER_MSVC -#define el_resolveVALength(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N -#define ELPP_WRITE_LOG(writer, level, dispatchAction, ...) \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_IF(writer, condition, level, dispatchAction, ...) if (condition) \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_EVERY_N(writer, occasion, level, dispatchAction, ...) \ -ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_AFTER_N(writer, n, level, dispatchAction, ...) \ -ELPP->validateAfterNCounter(__FILE__, __LINE__, n) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#define ELPP_WRITE_LOG_N_TIMES(writer, n, level, dispatchAction, ...) \ -ELPP->validateNTimesCounter(__FILE__, __LINE__, n) && \ -writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -class PerformanceTrackingData { - public: - enum class DataType : base::type::EnumType { - Checkpoint = 1, Complete = 2 - }; - // Do not use constructor, will run into multiple definition error, use init(PerformanceTracker*) - explicit PerformanceTrackingData(DataType dataType) : m_performanceTracker(nullptr), - m_dataType(dataType), m_firstCheckpoint(false), m_file(""), m_line(0), m_func("") {} - inline const std::string* blockName(void) const; - inline const struct timeval* startTime(void) const; - inline const struct timeval* endTime(void) const; - inline const struct timeval* lastCheckpointTime(void) const; - inline const base::PerformanceTracker* performanceTracker(void) const { - return m_performanceTracker; - } - inline PerformanceTrackingData::DataType dataType(void) const { - return m_dataType; - } - inline bool firstCheckpoint(void) const { - return m_firstCheckpoint; - } - inline std::string checkpointId(void) const { - return m_checkpointId; - } - inline const char* file(void) const { - return m_file; - } - inline base::type::LineNumber line(void) const { - return m_line; - } - inline const char* func(void) const { - return m_func; - } - inline const base::type::string_t* formattedTimeTaken() const { - return &m_formattedTimeTaken; - } - inline const std::string& loggerId(void) const; - private: - base::PerformanceTracker* m_performanceTracker; - base::type::string_t m_formattedTimeTaken; - PerformanceTrackingData::DataType m_dataType; - bool m_firstCheckpoint; - std::string m_checkpointId; - const char* m_file; - base::type::LineNumber m_line; - const char* m_func; - inline void init(base::PerformanceTracker* performanceTracker, bool firstCheckpoint = false) { - m_performanceTracker = performanceTracker; - m_firstCheckpoint = firstCheckpoint; - } - - friend class el::base::PerformanceTracker; -}; -namespace base { -/// @brief Represents performanceTracker block of code that conditionally adds performance status to log -/// either when goes outside the scope of when checkpoint() is called -class PerformanceTracker : public base::threading::ThreadSafe, public Loggable { - public: - PerformanceTracker(const std::string& blockName, - base::TimestampUnit timestampUnit = base::TimestampUnit::Millisecond, - const std::string& loggerId = std::string(el::base::consts::kPerformanceLoggerId), - bool scopedLog = true, Level level = base::consts::kPerformanceTrackerDefaultLevel); - /// @brief Copy constructor - PerformanceTracker(const PerformanceTracker& t) : - m_blockName(t.m_blockName), m_timestampUnit(t.m_timestampUnit), m_loggerId(t.m_loggerId), m_scopedLog(t.m_scopedLog), - m_level(t.m_level), m_hasChecked(t.m_hasChecked), m_lastCheckpointId(t.m_lastCheckpointId), m_enabled(t.m_enabled), - m_startTime(t.m_startTime), m_endTime(t.m_endTime), m_lastCheckpointTime(t.m_lastCheckpointTime) { - } - virtual ~PerformanceTracker(void); - /// @brief A checkpoint for current performanceTracker block. - void checkpoint(const std::string& id = std::string(), const char* file = __FILE__, - base::type::LineNumber line = __LINE__, - const char* func = ""); - inline Level level(void) const { - return m_level; - } - private: - std::string m_blockName; - base::TimestampUnit m_timestampUnit; - std::string m_loggerId; - bool m_scopedLog; - Level m_level; - bool m_hasChecked; - std::string m_lastCheckpointId; - bool m_enabled; - struct timeval m_startTime, m_endTime, m_lastCheckpointTime; - - PerformanceTracker(void); - - friend class el::PerformanceTrackingData; - friend class base::DefaultPerformanceTrackingCallback; - - const inline base::type::string_t getFormattedTimeTaken() const { - return getFormattedTimeTaken(m_startTime); - } - - const base::type::string_t getFormattedTimeTaken(struct timeval startTime) const; - - virtual inline void log(el::base::type::ostream_t& os) const { - os << getFormattedTimeTaken(); - } -}; -class DefaultPerformanceTrackingCallback : public PerformanceTrackingCallback { - protected: - void handle(const PerformanceTrackingData* data) { - m_data = data; - base::type::stringstream_t ss; - if (m_data->dataType() == PerformanceTrackingData::DataType::Complete) { - ss << ELPP_LITERAL("Executed [") << m_data->blockName()->c_str() << ELPP_LITERAL("] in [") << - *m_data->formattedTimeTaken() << ELPP_LITERAL("]"); - } else { - ss << ELPP_LITERAL("Performance checkpoint"); - if (!m_data->checkpointId().empty()) { - ss << ELPP_LITERAL(" [") << m_data->checkpointId().c_str() << ELPP_LITERAL("]"); - } - ss << ELPP_LITERAL(" for block [") << m_data->blockName()->c_str() << ELPP_LITERAL("] : [") << - *m_data->performanceTracker(); - if (!ELPP->hasFlag(LoggingFlag::DisablePerformanceTrackingCheckpointComparison) - && m_data->performanceTracker()->m_hasChecked) { - ss << ELPP_LITERAL(" ([") << *m_data->formattedTimeTaken() << ELPP_LITERAL("] from "); - if (m_data->performanceTracker()->m_lastCheckpointId.empty()) { - ss << ELPP_LITERAL("last checkpoint"); - } else { - ss << ELPP_LITERAL("checkpoint '") << m_data->performanceTracker()->m_lastCheckpointId.c_str() << ELPP_LITERAL("'"); - } - ss << ELPP_LITERAL(")]"); - } else { - ss << ELPP_LITERAL("]"); - } - } - el::base::Writer(m_data->performanceTracker()->level(), m_data->file(), m_data->line(), m_data->func()).construct(1, - m_data->loggerId().c_str()) << ss.str(); - } - private: - const PerformanceTrackingData* m_data; -}; -} // namespace base -inline const std::string* PerformanceTrackingData::blockName() const { - return const_cast(&m_performanceTracker->m_blockName); -} -inline const struct timeval* PerformanceTrackingData::startTime() const { - return const_cast(&m_performanceTracker->m_startTime); -} -inline const struct timeval* PerformanceTrackingData::endTime() const { - return const_cast(&m_performanceTracker->m_endTime); -} -inline const struct timeval* PerformanceTrackingData::lastCheckpointTime() const { - return const_cast(&m_performanceTracker->m_lastCheckpointTime); -} -inline const std::string& PerformanceTrackingData::loggerId(void) const { - return m_performanceTracker->m_loggerId; -} -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) -namespace base { -/// @brief Contains some internal debugging tools like crash handler and stack tracer -namespace debug { -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -class StackTrace : base::NoCopy { - public: - static const unsigned int kMaxStack = 64; - static const unsigned int kStackStart = 2; // We want to skip c'tor and StackTrace::generateNew() - class StackTraceEntry { - public: - StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, const std::string& hex, - const std::string& addr); - StackTraceEntry(std::size_t index, const std::string& loc) : - m_index(index), - m_location(loc) { - } - std::size_t m_index; - std::string m_location; - std::string m_demangled; - std::string m_hex; - std::string m_addr; - friend std::ostream& operator<<(std::ostream& ss, const StackTraceEntry& si); - - private: - StackTraceEntry(void); - }; - - StackTrace(void) { - generateNew(); - } - - virtual ~StackTrace(void) { - } - - inline std::vector& getLatestStack(void) { - return m_stack; - } - - friend std::ostream& operator<<(std::ostream& os, const StackTrace& st); - - private: - std::vector m_stack; - - void generateNew(void); -}; -/// @brief Handles unexpected crashes -class CrashHandler : base::NoCopy { - public: - typedef void (*Handler)(int); - - explicit CrashHandler(bool useDefault); - explicit CrashHandler(const Handler& cHandler) { - setHandler(cHandler); - } - void setHandler(const Handler& cHandler); - - private: - Handler m_handler; -}; -#else -class CrashHandler { - public: - explicit CrashHandler(bool) {} -}; -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) -} // namespace debug -} // namespace base -extern base::debug::CrashHandler elCrashHandler; -#define MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance) \ -el::base::type::ostream_t& operator<<(el::base::type::ostream_t& OutputStreamInstance, const ClassType& ClassInstance) -/// @brief Initializes syslog with process ID, options and facility. calls closelog() on d'tor -class SysLogInitializer { - public: - SysLogInitializer(const char* processIdent, int options = 0, int facility = 0) { -#if defined(ELPP_SYSLOG) - openlog(processIdent, options, facility); -#else - ELPP_UNUSED(processIdent); - ELPP_UNUSED(options); - ELPP_UNUSED(facility); -#endif // defined(ELPP_SYSLOG) - } - virtual ~SysLogInitializer(void) { -#if defined(ELPP_SYSLOG) - closelog(); -#endif // defined(ELPP_SYSLOG) - } -}; -#define ELPP_INITIALIZE_SYSLOG(id, opt, fac) el::SysLogInitializer elSyslogInit(id, opt, fac) -/// @brief Static helpers for developers -class Helpers : base::StaticClass { - public: - /// @brief Shares logging repository (base::Storage) - static inline void setStorage(base::type::StoragePointer storage) { - ELPP = storage; - } - /// @return Main storage repository - static inline base::type::StoragePointer storage() { - return ELPP; - } - /// @brief Sets application arguments and figures out whats active for logging and whats not. - static inline void setArgs(int argc, char** argv) { - ELPP->setApplicationArguments(argc, argv); - } - /// @copydoc setArgs(int argc, char** argv) - static inline void setArgs(int argc, const char** argv) { - ELPP->setApplicationArguments(argc, const_cast(argv)); - } - /// @brief Sets thread name for current thread. Requires std::thread - static inline void setThreadName(const std::string& name) { - ELPP->setThreadName(name); - } - static inline std::string getThreadName() { - return ELPP->getThreadName(base::threading::getCurrentThreadId()); - } -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - /// @brief Overrides default crash handler and installs custom handler. - /// @param crashHandler A functor with no return type that takes single int argument. - /// Handler is a typedef with specification: void (*Handler)(int) - static inline void setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) { - el::elCrashHandler.setHandler(crashHandler); - } - /// @brief Abort due to crash with signal in parameter - /// @param sig Crash signal - static void crashAbort(int sig, const char* sourceFile = "", unsigned int long line = 0); - /// @brief Logs reason of crash as per sig - /// @param sig Crash signal - /// @param stackTraceIfAvailable Includes stack trace if available - /// @param level Logging level - /// @param logger Logger to use for logging - static void logCrashReason(int sig, bool stackTraceIfAvailable = false, - Level level = Level::Fatal, const char* logger = base::consts::kDefaultLoggerId); -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) - /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out - /// (can be useful for backing up) - static inline void installPreRollOutCallback(const PreRollOutCallback& callback) { - ELPP->setPreRollOutCallback(callback); - } - /// @brief Uninstalls pre rollout callback - static inline void uninstallPreRollOutCallback(void) { - ELPP->unsetPreRollOutCallback(); - } - /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched - template - static inline bool installLogDispatchCallback(const std::string& id) { - return ELPP->installLogDispatchCallback(id); - } - /// @brief Uninstalls log dispatch callback - template - static inline void uninstallLogDispatchCallback(const std::string& id) { - ELPP->uninstallLogDispatchCallback(id); - } - template - static inline T* logDispatchCallback(const std::string& id) { - return ELPP->logDispatchCallback(id); - } -#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - /// @brief Installs post performance tracking callback, this callback is triggered when performance tracking is finished - template - static inline bool installPerformanceTrackingCallback(const std::string& id) { - return ELPP->installPerformanceTrackingCallback(id); - } - /// @brief Uninstalls post performance tracking handler - template - static inline void uninstallPerformanceTrackingCallback(const std::string& id) { - ELPP->uninstallPerformanceTrackingCallback(id); - } - template - static inline T* performanceTrackingCallback(const std::string& id) { - return ELPP->performanceTrackingCallback(id); - } -#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) - /// @brief Converts template to std::string - useful for loggable classes to log containers within log(std::ostream&) const - template - static std::string convertTemplateToStdString(const T& templ) { - el::Logger* logger = - ELPP->registeredLoggers()->get(el::base::consts::kDefaultLoggerId); - if (logger == nullptr) { - return std::string(); - } - base::MessageBuilder b; - b.initialize(logger); - logger->acquireLock(); - b << templ; -#if defined(ELPP_UNICODE) - std::string s = std::string(logger->stream().str().begin(), logger->stream().str().end()); -#else - std::string s = logger->stream().str(); -#endif // defined(ELPP_UNICODE) - logger->stream().str(ELPP_LITERAL("")); - logger->releaseLock(); - return s; - } - /// @brief Returns command line arguments (pointer) provided to easylogging++ - static inline const el::base::utils::CommandLineArgs* commandLineArgs(void) { - return ELPP->commandLineArgs(); - } - /// @brief Reserve space for custom format specifiers for performance - /// @see std::vector::reserve - static inline void reserveCustomFormatSpecifiers(std::size_t size) { - ELPP->m_customFormatSpecifiers.reserve(size); - } - /// @brief Installs user defined format specifier and handler - static inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { - ELPP->installCustomFormatSpecifier(customFormatSpecifier); - } - /// @brief Uninstalls user defined format specifier and handler - static inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) { - return ELPP->uninstallCustomFormatSpecifier(formatSpecifier); - } - /// @brief Returns true if custom format specifier is installed - static inline bool hasCustomFormatSpecifier(const char* formatSpecifier) { - return ELPP->hasCustomFormatSpecifier(formatSpecifier); - } - static inline void validateFileRolling(Logger* logger, Level level) { - if (ELPP == nullptr || logger == nullptr) return; - logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback()); - } -}; -/// @brief Static helpers to deal with loggers and their configurations -class Loggers : base::StaticClass { - public: - /// @brief Gets existing or registers new logger - static Logger* getLogger(const std::string& identity, bool registerIfNotAvailable = true); - /// @brief Changes default log builder for future loggers - static void setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr); - /// @brief Installs logger registration callback, this callback is triggered when new logger is registered - template - static inline bool installLoggerRegistrationCallback(const std::string& id) { - return ELPP->registeredLoggers()->installLoggerRegistrationCallback(id); - } - /// @brief Uninstalls log dispatch callback - template - static inline void uninstallLoggerRegistrationCallback(const std::string& id) { - ELPP->registeredLoggers()->uninstallLoggerRegistrationCallback(id); - } - template - static inline T* loggerRegistrationCallback(const std::string& id) { - return ELPP->registeredLoggers()->loggerRegistrationCallback(id); - } - /// @brief Unregisters logger - use it only when you know what you are doing, you may unregister - /// loggers initialized / used by third-party libs. - static bool unregisterLogger(const std::string& identity); - /// @brief Whether or not logger with id is registered - static bool hasLogger(const std::string& identity); - /// @brief Reconfigures specified logger with new configurations - static Logger* reconfigureLogger(Logger* logger, const Configurations& configurations); - /// @brief Reconfigures logger with new configurations after looking it up using identity - static Logger* reconfigureLogger(const std::string& identity, const Configurations& configurations); - /// @brief Reconfigures logger's single configuration - static Logger* reconfigureLogger(const std::string& identity, ConfigurationType configurationType, - const std::string& value); - /// @brief Reconfigures all the existing loggers with new configurations - static void reconfigureAllLoggers(const Configurations& configurations); - /// @brief Reconfigures single configuration for all the loggers - static inline void reconfigureAllLoggers(ConfigurationType configurationType, const std::string& value) { - reconfigureAllLoggers(Level::Global, configurationType, value); - } - /// @brief Reconfigures single configuration for all the loggers for specified level - static void reconfigureAllLoggers(Level level, ConfigurationType configurationType, - const std::string& value); - /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing) loggers - static void setDefaultConfigurations(const Configurations& configurations, - bool reconfigureExistingLoggers = false); - /// @brief Returns current default - static const Configurations* defaultConfigurations(void); - /// @brief Returns log stream reference pointer if needed by user - static const base::LogStreamsReferenceMap* logStreamsReference(void); - /// @brief Default typed configuration based on existing defaultConf - static base::TypedConfigurations defaultTypedConfigurations(void); - /// @brief Populates all logger IDs in current repository. - /// @param [out] targetList List of fill up. - static std::vector* populateAllLoggerIds(std::vector* targetList); - /// @brief Sets configurations from global configuration file. - static void configureFromGlobal(const char* globalConfigurationFilePath); - /// @brief Configures loggers using command line arg. Ensure you have already set command line args, - /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger. - /// If true is returned that does not mean it has been configured successfully, it only means that it - /// has attempeted to configure logger using configuration file provided in argument - static bool configureFromArg(const char* argKey); - /// @brief Flushes all loggers for all levels - Be careful if you dont know how many loggers are registered - static void flushAll(void); - /// @brief Adds logging flag used internally. - static inline void addFlag(LoggingFlag flag) { - ELPP->addFlag(flag); - } - /// @brief Removes logging flag used internally. - static inline void removeFlag(LoggingFlag flag) { - ELPP->removeFlag(flag); - } - /// @brief Determines whether or not certain flag is active - static inline bool hasFlag(LoggingFlag flag) { - return ELPP->hasFlag(flag); - } - /// @brief Adds flag and removes it when scope goes out - class ScopedAddFlag { - public: - ScopedAddFlag(LoggingFlag flag) : m_flag(flag) { - Loggers::addFlag(m_flag); - } - ~ScopedAddFlag(void) { - Loggers::removeFlag(m_flag); - } - private: - LoggingFlag m_flag; - }; - /// @brief Removes flag and add it when scope goes out - class ScopedRemoveFlag { - public: - ScopedRemoveFlag(LoggingFlag flag) : m_flag(flag) { - Loggers::removeFlag(m_flag); - } - ~ScopedRemoveFlag(void) { - Loggers::addFlag(m_flag); - } - private: - LoggingFlag m_flag; - }; - /// @brief Sets hierarchy for logging. Needs to enable logging flag (HierarchicalLogging) - static void setLoggingLevel(Level level) { - ELPP->setLoggingLevel(level); - } - /// @brief Sets verbose level on the fly - static void setVerboseLevel(base::type::VerboseLevel level); - /// @brief Gets current verbose level - static base::type::VerboseLevel verboseLevel(void); - /// @brief Sets vmodules as specified (on the fly) - static void setVModules(const char* modules); - /// @brief Sets categories as specified (on the fly) - static void setCategories(const char* categories, bool clear = true); - /// @brief Gets current categories - static std::string getCategories(); - /// @brief Clears vmodules - static void clearVModules(void); - /// @brief Clears categories - static void clearCategories(void); - /// @brief Sets filename common prefix - static void setFilenameCommonPrefix(const std::string &prefix); - /// @brief Gets filename common prefix - static const std::string &getFilenameCommonPrefix(); -}; -class VersionInfo : base::StaticClass { - public: - /// @brief Current version number - static const std::string version(void); - - /// @brief Release date of current version - static const std::string releaseDate(void); -}; -} // namespace el -#undef VLOG_IS_ON -/// @brief Determines whether verbose logging is on for specified level current file. -#define VLOG_IS_ON(verboseLevel) (ELPP->vRegistry()->allowed(verboseLevel, __FILE__)) -#undef TIMED_BLOCK -#undef TIMED_SCOPE -#undef TIMED_SCOPE_IF -#undef TIMED_FUNC -#undef TIMED_FUNC_IF -#undef ELPP_MIN_UNIT -#if defined(ELPP_PERFORMANCE_MICROSECONDS) -# define ELPP_MIN_UNIT el::base::TimestampUnit::Microsecond -#else -# define ELPP_MIN_UNIT el::base::TimestampUnit::Millisecond -#endif // (defined(ELPP_PERFORMANCE_MICROSECONDS)) -/// @brief Performance tracked scope. Performance gets written when goes out of scope using -/// 'performance' logger. -/// -/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint(); -/// @see el::base::PerformanceTracker -/// @see el::base::PerformanceTracker::checkpoint -// Note: Do not surround this definition with null macro because of obj instance -#define TIMED_SCOPE_IF(obj, blockname, condition) el::base::type::PerformanceTrackerPtr obj( condition ? \ - new el::base::PerformanceTracker(blockname, ELPP_MIN_UNIT) : nullptr ) -#define TIMED_SCOPE(obj, blockname) TIMED_SCOPE_IF(obj, blockname, true) -#define TIMED_BLOCK(obj, blockName) for (struct { int i; el::base::type::PerformanceTrackerPtr timer; } obj = { 0, \ - el::base::type::PerformanceTrackerPtr(new el::base::PerformanceTracker(blockName, ELPP_MIN_UNIT)) }; obj.i < 1; ++obj.i) -/// @brief Performance tracked function. Performance gets written when goes out of scope using -/// 'performance' logger. -/// -/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint(); -/// @see el::base::PerformanceTracker -/// @see el::base::PerformanceTracker::checkpoint -#define TIMED_FUNC_IF(obj,condition) TIMED_SCOPE_IF(obj, ELPP_FUNC, condition) -#define TIMED_FUNC(obj) TIMED_SCOPE(obj, ELPP_FUNC) -#undef PERFORMANCE_CHECKPOINT -#undef PERFORMANCE_CHECKPOINT_WITH_ID -#define PERFORMANCE_CHECKPOINT(obj) obj->checkpoint(std::string(), __FILE__, __LINE__, ELPP_FUNC) -#define PERFORMANCE_CHECKPOINT_WITH_ID(obj, id) obj->checkpoint(id, __FILE__, __LINE__, ELPP_FUNC) -#undef ELPP_COUNTER -#undef ELPP_COUNTER_POS -/// @brief Gets hit counter for file/line -#define ELPP_COUNTER (ELPP->hitCounters()->getCounter(__FILE__, __LINE__)) -/// @brief Gets hit counter position for file/line, -1 if not registered yet -#define ELPP_COUNTER_POS (ELPP_COUNTER == nullptr ? -1 : ELPP_COUNTER->hitCounts()) -// Undef levels to support LOG(LEVEL) -#undef INFO -#undef WARNING -#undef DEBUG -#undef ERROR -#undef FATAL -#undef TRACE -#undef VERBOSE -// Undef existing -#undef CINFO -#undef CWARNING -#undef CDEBUG -#undef CFATAL -#undef CERROR -#undef CTRACE -#undef CVERBOSE -#undef CINFO_IF -#undef CWARNING_IF -#undef CDEBUG_IF -#undef CERROR_IF -#undef CFATAL_IF -#undef CTRACE_IF -#undef CVERBOSE_IF -#undef CINFO_EVERY_N -#undef CWARNING_EVERY_N -#undef CDEBUG_EVERY_N -#undef CERROR_EVERY_N -#undef CFATAL_EVERY_N -#undef CTRACE_EVERY_N -#undef CVERBOSE_EVERY_N -#undef CINFO_AFTER_N -#undef CWARNING_AFTER_N -#undef CDEBUG_AFTER_N -#undef CERROR_AFTER_N -#undef CFATAL_AFTER_N -#undef CTRACE_AFTER_N -#undef CVERBOSE_AFTER_N -#undef CINFO_N_TIMES -#undef CWARNING_N_TIMES -#undef CDEBUG_N_TIMES -#undef CERROR_N_TIMES -#undef CFATAL_N_TIMES -#undef CTRACE_N_TIMES -#undef CVERBOSE_N_TIMES -// Normal logs -#if ELPP_INFO_LOG -# define CINFO(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE(writer, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE(writer, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel)) writer(\ -el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#else -# define CVERBOSE(writer, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// Conditional logs -#if ELPP_INFO_LOG -# define CINFO_IF(writer, condition_, dispatchAction, ...) \ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_IF(writer, condition_, dispatchAction, ...)\ -ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel) && (condition_)) writer( \ -el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) -#else -# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// Occasional logs -#if ELPP_INFO_LOG -# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...)\ -ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// After N logs -#if ELPP_INFO_LOG -# define CINFO_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_AFTER_N(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateAfterNCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// N Times logs -#if ELPP_INFO_LOG -# define CINFO_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) -#else -# define CINFO_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_INFO_LOG -#if ELPP_WARNING_LOG -# define CWARNING_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) -#else -# define CWARNING_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_WARNING_LOG -#if ELPP_DEBUG_LOG -# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) -#else -# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_DEBUG_LOG -#if ELPP_ERROR_LOG -# define CERROR_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) -#else -# define CERROR_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_ERROR_LOG -#if ELPP_FATAL_LOG -# define CFATAL_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) -#else -# define CFATAL_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_FATAL_LOG -#if ELPP_TRACE_LOG -# define CTRACE_N_TIMES(writer, n, dispatchAction, ...)\ -ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) -#else -# define CTRACE_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_TRACE_LOG -#if ELPP_VERBOSE_LOG -# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...)\ -CVERBOSE_IF(writer, ELPP->validateNTimesCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) -#else -# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() -#endif // ELPP_VERBOSE_LOG -// -// Custom Loggers - Requires (level, dispatchAction, loggerId/s) -// -// undef existing -#undef CLOG -#undef CLOG_VERBOSE -#undef CVLOG -#undef CLOG_IF -#undef CLOG_VERBOSE_IF -#undef CVLOG_IF -#undef CLOG_EVERY_N -#undef CVLOG_EVERY_N -#undef CLOG_AFTER_N -#undef CVLOG_AFTER_N -#undef CLOG_N_TIMES -#undef CVLOG_N_TIMES -// Normal logs -#define CLOG(LEVEL, ...)\ -C##LEVEL(el::base::Writer, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG(vlevel, ...) CVERBOSE(el::base::Writer, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// Conditional logs -#define CLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_IF(condition, vlevel, ...)\ -CVERBOSE_IF(el::base::Writer, condition, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// Hit counts based logs -#define CLOG_EVERY_N(n, LEVEL, ...)\ -C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_EVERY_N(n, vlevel, ...)\ -CVERBOSE_EVERY_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CLOG_AFTER_N(n, LEVEL, ...)\ -C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_AFTER_N(n, vlevel, ...)\ -CVERBOSE_AFTER_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CLOG_N_TIMES(n, LEVEL, ...)\ -C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CVLOG_N_TIMES(n, vlevel, ...)\ -CVERBOSE_N_TIMES(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) -// -// Default Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros -// -// undef existing -#undef LOG -#undef VLOG -#undef LOG_IF -#undef VLOG_IF -#undef LOG_EVERY_N -#undef VLOG_EVERY_N -#undef LOG_AFTER_N -#undef VLOG_AFTER_N -#undef LOG_N_TIMES -#undef VLOG_N_TIMES -#undef ELPP_CURR_FILE_LOGGER_ID -#if defined(ELPP_DEFAULT_LOGGER) -# define ELPP_CURR_FILE_LOGGER_ID ELPP_DEFAULT_LOGGER -#else -# define ELPP_CURR_FILE_LOGGER_ID el::base::consts::kDefaultLoggerId -#endif -#undef ELPP_TRACE -#define ELPP_TRACE CLOG(TRACE, ELPP_CURR_FILE_LOGGER_ID) -// Normal logs -#define LOG(LEVEL) CLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG(vlevel) CVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Conditional logs -#define LOG_IF(condition, LEVEL) CLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_IF(condition, vlevel) CVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Hit counts based logs -#define LOG_EVERY_N(n, LEVEL) CLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_EVERY_N(n, vlevel) CVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define LOG_AFTER_N(n, LEVEL) CLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_AFTER_N(n, vlevel) CVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define LOG_N_TIMES(n, LEVEL) CLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define VLOG_N_TIMES(n, vlevel) CVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Generic PLOG() -#undef CPLOG -#undef CPLOG_IF -#undef PLOG -#undef PLOG_IF -#undef DCPLOG -#undef DCPLOG_IF -#undef DPLOG -#undef DPLOG_IF -#define CPLOG(LEVEL, ...)\ -C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define CPLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::PErrorWriter, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define DCPLOG(LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define DCPLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::PErrorWriter, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::NormalLog, __VA_ARGS__) -#define PLOG(LEVEL) CPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define PLOG_IF(condition, LEVEL) CPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DPLOG(LEVEL) DCPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DPLOG_IF(condition, LEVEL) DCPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -// Generic SYSLOG() -#undef CSYSLOG -#undef CSYSLOG_IF -#undef CSYSLOG_EVERY_N -#undef CSYSLOG_AFTER_N -#undef CSYSLOG_N_TIMES -#undef SYSLOG -#undef SYSLOG_IF -#undef SYSLOG_EVERY_N -#undef SYSLOG_AFTER_N -#undef SYSLOG_N_TIMES -#undef DCSYSLOG -#undef DCSYSLOG_IF -#undef DCSYSLOG_EVERY_N -#undef DCSYSLOG_AFTER_N -#undef DCSYSLOG_N_TIMES -#undef DSYSLOG -#undef DSYSLOG_IF -#undef DSYSLOG_EVERY_N -#undef DSYSLOG_AFTER_N -#undef DSYSLOG_N_TIMES -#if defined(ELPP_SYSLOG) -# define CSYSLOG(LEVEL, ...)\ -C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_EVERY_N(n, LEVEL, ...) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_AFTER_N(n, LEVEL, ...) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define CSYSLOG_N_TIMES(n, LEVEL, ...) C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define SYSLOG(LEVEL) CSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_IF(condition, LEVEL) CSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_EVERY_N(n, LEVEL) CSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_AFTER_N(n, LEVEL) CSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define SYSLOG_N_TIMES(n, LEVEL) CSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DCSYSLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_IF(condition, LEVEL, ...)\ -C##LEVEL##_IF(el::base::Writer, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_EVERY_N(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_AFTER_N(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DCSYSLOG_N_TIMES(n, LEVEL, ...)\ -if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) -# define DSYSLOG(LEVEL) DCSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_IF(condition, LEVEL) DCSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_EVERY_N(n, LEVEL) DCSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_AFTER_N(n, LEVEL) DCSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) -# define DSYSLOG_N_TIMES(n, LEVEL) DCSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) -#else -# define CSYSLOG(LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() -# define CSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() -# define SYSLOG(LEVEL) el::base::NullWriter() -# define SYSLOG_IF(condition, LEVEL) el::base::NullWriter() -# define SYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() -# define SYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() -# define SYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() -# define DCSYSLOG(LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() -# define DCSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() -# define DSYSLOG(LEVEL) el::base::NullWriter() -# define DSYSLOG_IF(condition, LEVEL) el::base::NullWriter() -# define DSYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() -# define DSYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() -# define DSYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() -#endif // defined(ELPP_SYSLOG) -// -// Custom Debug Only Loggers - Requires (level, loggerId/s) -// -// undef existing -#undef DCLOG -#undef DCVLOG -#undef DCLOG_IF -#undef DCVLOG_IF -#undef DCLOG_EVERY_N -#undef DCVLOG_EVERY_N -#undef DCLOG_AFTER_N -#undef DCVLOG_AFTER_N -#undef DCLOG_N_TIMES -#undef DCVLOG_N_TIMES -// Normal logs -#define DCLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG(LEVEL, __VA_ARGS__) -#define DCLOG_VERBOSE(vlevel, ...) if (ELPP_DEBUG_LOG) CLOG_VERBOSE(vlevel, __VA_ARGS__) -#define DCVLOG(vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG(vlevel, __VA_ARGS__) -// Conditional logs -#define DCLOG_IF(condition, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_IF(condition, LEVEL, __VA_ARGS__) -#define DCVLOG_IF(condition, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_IF(condition, vlevel, __VA_ARGS__) -// Hit counts based logs -#define DCLOG_EVERY_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_EVERY_N(n, LEVEL, __VA_ARGS__) -#define DCVLOG_EVERY_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_EVERY_N(n, vlevel, __VA_ARGS__) -#define DCLOG_AFTER_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_AFTER_N(n, LEVEL, __VA_ARGS__) -#define DCVLOG_AFTER_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_AFTER_N(n, vlevel, __VA_ARGS__) -#define DCLOG_N_TIMES(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_N_TIMES(n, LEVEL, __VA_ARGS__) -#define DCVLOG_N_TIMES(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_N_TIMES(n, vlevel, __VA_ARGS__) -// -// Default Debug Only Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros -// -#if !defined(ELPP_NO_DEBUG_MACROS) -// undef existing -#undef DLOG -#undef DVLOG -#undef DLOG_IF -#undef DVLOG_IF -#undef DLOG_EVERY_N -#undef DVLOG_EVERY_N -#undef DLOG_AFTER_N -#undef DVLOG_AFTER_N -#undef DLOG_N_TIMES -#undef DVLOG_N_TIMES -// Normal logs -#define DLOG(LEVEL) DCLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG(vlevel) DCVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Conditional logs -#define DLOG_IF(condition, LEVEL) DCLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_IF(condition, vlevel) DCVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) -// Hit counts based logs -#define DLOG_EVERY_N(n, LEVEL) DCLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_EVERY_N(n, vlevel) DCVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define DLOG_AFTER_N(n, LEVEL) DCLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_AFTER_N(n, vlevel) DCVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#define DLOG_N_TIMES(n, LEVEL) DCLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) -#define DVLOG_N_TIMES(n, vlevel) DCVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) -#endif // defined(ELPP_NO_DEBUG_MACROS) -#if !defined(ELPP_NO_CHECK_MACROS) -// Check macros -#undef CCHECK -#undef CPCHECK -#undef CCHECK_EQ -#undef CCHECK_NE -#undef CCHECK_LT -#undef CCHECK_GT -#undef CCHECK_LE -#undef CCHECK_GE -#undef CCHECK_BOUNDS -#undef CCHECK_NOTNULL -#undef CCHECK_STRCASEEQ -#undef CCHECK_STRCASENE -#undef CHECK -#undef PCHECK -#undef CHECK_EQ -#undef CHECK_NE -#undef CHECK_LT -#undef CHECK_GT -#undef CHECK_LE -#undef CHECK_GE -#undef CHECK_BOUNDS -#undef CHECK_NOTNULL -#undef CHECK_STRCASEEQ -#undef CHECK_STRCASENE -#define CCHECK(condition, ...) CLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " -#define CPCHECK(condition, ...) CPLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " -#define CHECK(condition) CCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define PCHECK(condition) CPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define CCHECK_EQ(a, b, ...) CCHECK(a == b, __VA_ARGS__) -#define CCHECK_NE(a, b, ...) CCHECK(a != b, __VA_ARGS__) -#define CCHECK_LT(a, b, ...) CCHECK(a < b, __VA_ARGS__) -#define CCHECK_GT(a, b, ...) CCHECK(a > b, __VA_ARGS__) -#define CCHECK_LE(a, b, ...) CCHECK(a <= b, __VA_ARGS__) -#define CCHECK_GE(a, b, ...) CCHECK(a >= b, __VA_ARGS__) -#define CCHECK_BOUNDS(val, min, max, ...) CCHECK(val >= min && val <= max, __VA_ARGS__) -#define CHECK_EQ(a, b) CCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_NE(a, b) CCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_LT(a, b) CCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_GT(a, b) CCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_LE(a, b) CCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_GE(a, b) CCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_BOUNDS(val, min, max) CCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) -#define CCHECK_NOTNULL(ptr, ...) CCHECK((ptr) != nullptr, __VA_ARGS__) -#define CCHECK_STREQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " == " << #str2 << "] " -#define CCHECK_STRNE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " != " << #str2 << "] " -#define CCHECK_STRCASEEQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " == " << #str2 << "] " -#define CCHECK_STRCASENE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ -<< "Check failed: [" << #str1 << " != " << #str2 << "] " -#define CHECK_NOTNULL(ptr) CCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STREQ(str1, str2) CCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRNE(str1, str2) CCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRCASEEQ(str1, str2) CCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define CHECK_STRCASENE(str1, str2) CCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#undef DCCHECK -#undef DCCHECK_EQ -#undef DCCHECK_NE -#undef DCCHECK_LT -#undef DCCHECK_GT -#undef DCCHECK_LE -#undef DCCHECK_GE -#undef DCCHECK_BOUNDS -#undef DCCHECK_NOTNULL -#undef DCCHECK_STRCASEEQ -#undef DCCHECK_STRCASENE -#undef DCPCHECK -#undef DCHECK -#undef DCHECK_EQ -#undef DCHECK_NE -#undef DCHECK_LT -#undef DCHECK_GT -#undef DCHECK_LE -#undef DCHECK_GE -#undef DCHECK_BOUNDS_ -#undef DCHECK_NOTNULL -#undef DCHECK_STRCASEEQ -#undef DCHECK_STRCASENE -#undef DPCHECK -#define DCCHECK(condition, ...) if (ELPP_DEBUG_LOG) CCHECK(condition, __VA_ARGS__) -#define DCCHECK_EQ(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_EQ(a, b, __VA_ARGS__) -#define DCCHECK_NE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_NE(a, b, __VA_ARGS__) -#define DCCHECK_LT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LT(a, b, __VA_ARGS__) -#define DCCHECK_GT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GT(a, b, __VA_ARGS__) -#define DCCHECK_LE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LE(a, b, __VA_ARGS__) -#define DCCHECK_GE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GE(a, b, __VA_ARGS__) -#define DCCHECK_BOUNDS(val, min, max, ...) if (ELPP_DEBUG_LOG) CCHECK_BOUNDS(val, min, max, __VA_ARGS__) -#define DCCHECK_NOTNULL(ptr, ...) if (ELPP_DEBUG_LOG) CCHECK_NOTNULL((ptr), __VA_ARGS__) -#define DCCHECK_STREQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STREQ(str1, str2, __VA_ARGS__) -#define DCCHECK_STRNE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRNE(str1, str2, __VA_ARGS__) -#define DCCHECK_STRCASEEQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASEEQ(str1, str2, __VA_ARGS__) -#define DCCHECK_STRCASENE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASENE(str1, str2, __VA_ARGS__) -#define DCPCHECK(condition, ...) if (ELPP_DEBUG_LOG) CPCHECK(condition, __VA_ARGS__) -#define DCHECK(condition) DCCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_EQ(a, b) DCCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_NE(a, b) DCCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_LT(a, b) DCCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_GT(a, b) DCCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_LE(a, b) DCCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_GE(a, b) DCCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_BOUNDS(val, min, max) DCCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_NOTNULL(ptr) DCCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STREQ(str1, str2) DCCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRNE(str1, str2) DCCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRCASEEQ(str1, str2) DCCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DCHECK_STRCASENE(str1, str2) DCCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) -#define DPCHECK(condition) DCPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) -#endif // defined(ELPP_NO_CHECK_MACROS) -#if defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) -# define ELPP_USE_DEF_CRASH_HANDLER false -#else -# define ELPP_USE_DEF_CRASH_HANDLER true -#endif // defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) -#define ELPP_CRASH_HANDLER_INIT -#define ELPP_INIT_EASYLOGGINGPP(val) \ -namespace el { \ -namespace base { \ -el::base::type::StoragePointer elStorage(val); \ -} \ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \ -} - -#if ELPP_ASYNC_LOGGING -# define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()),\ -new el::base::AsyncDispatchWorker())) -#else -# define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()))) -#endif // ELPP_ASYNC_LOGGING -#define INITIALIZE_NULL_EASYLOGGINGPP \ -namespace el {\ -namespace base {\ -el::base::type::StoragePointer elStorage;\ -}\ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ -} -#define SHARE_EASYLOGGINGPP(initializedStorage)\ -namespace el {\ -namespace base {\ -el::base::type::StoragePointer elStorage(initializedStorage);\ -}\ -el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ -} - -#if defined(ELPP_UNICODE) -# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv); std::locale::global(std::locale("")) -#else -# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv) -#endif // defined(ELPP_UNICODE) -#endif // EASYLOGGINGPP_H diff --git a/external/fmt b/external/fmt deleted file mode 160000 index d141cdbeb..000000000 --- a/external/fmt +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d141cdbeb0fb422a3fb7173b285fd38e0d1772dc diff --git a/external/oxen-logging b/external/oxen-logging new file mode 160000 index 000000000..98a8882c8 --- /dev/null +++ b/external/oxen-logging @@ -0,0 +1 @@ +Subproject commit 98a8882c81aa046fbadc0571fcea7bf92ed20154 diff --git a/external/oxen-mq b/external/oxen-mq index a93c16af0..0858dd278 160000 --- a/external/oxen-mq +++ b/external/oxen-mq @@ -1 +1 @@ -Subproject commit a93c16af04eba58fba2bf7f5726c4669c290bd46 +Subproject commit 0858dd278b91a899b69210088622ca6fa3bb0eed diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 74f23f65f..10286ae3e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -53,6 +53,7 @@ add_subdirectory(ringct) add_subdirectory(checkpoints) add_subdirectory(cryptonote_basic) add_subdirectory(cryptonote_core) +add_subdirectory(logging) add_subdirectory(lmdb) add_subdirectory(multisig) add_subdirectory(net) diff --git a/src/blockchain_db/CMakeLists.txt b/src/blockchain_db/CMakeLists.txt index d016d8b02..2c9a2820b 100644 --- a/src/blockchain_db/CMakeLists.txt +++ b/src/blockchain_db/CMakeLists.txt @@ -43,6 +43,7 @@ target_link_libraries(blockchain_db lmdb filesystem Boost::thread + logging extra) target_compile_definitions(blockchain_db PRIVATE diff --git a/src/blockchain_db/blockchain_db.cpp b/src/blockchain_db/blockchain_db.cpp index 91fa1a91d..152485e31 100644 --- a/src/blockchain_db/blockchain_db.cpp +++ b/src/blockchain_db/blockchain_db.cpp @@ -40,12 +40,11 @@ #include "lmdb/db_lmdb.h" #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "blockchain.db" - namespace cryptonote { + static auto logcat = oxen::log::Cat("blockchain.db"); + const command_line::arg_descriptor arg_db_sync_mode = { "db-sync-mode" , "Specify sync option, using format [safe|fast|fastest]:[sync|async]:[[blocks]|[bytes]]." @@ -85,7 +84,7 @@ void BlockchainDB::add_transaction(const crypto::hash& blk_hash, const std::pair { // should only need to compute hash for miner transactions tx_hash = get_transaction_hash(tx); - LOG_PRINT_L3("null tx_hash_ptr - needed to compute: " << tx_hash); + oxen::log::trace(logcat, "null tx_hash_ptr - needed to compute: {}", tx_hash); } else { @@ -119,7 +118,7 @@ void BlockchainDB::add_transaction(const crypto::hash& blk_hash, const std::pair } else { - LOG_PRINT_L1("Unsupported input type, removing key images and aborting transaction addition"); + oxen::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(tx_input)) @@ -330,22 +329,21 @@ void BlockchainDB::reset_stats() void BlockchainDB::show_stats() { - LOG_PRINT_L1("\n" - << "*********************************\n" - << "num_calls: " << num_calls << "\n" - << "time_blk_hash: " << tools::friendly_duration(time_blk_hash) << "\n" - << "time_tx_exists: " << tools::friendly_duration(time_tx_exists) << "\n" - << "time_add_block1: " << tools::friendly_duration(time_add_block1) << "\n" - << "time_add_transaction: " << tools::friendly_duration(time_add_transaction) << "\n" - << "time_commit1: " << tools::friendly_duration(time_commit1) << "\n" - << "*********************************\n" - ); + oxen::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", + 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)); } void BlockchainDB::fixup(cryptonote::network_type) { if (is_read_only()) { - LOG_PRINT_L1("Database is opened read only - skipping fixup check"); + oxen::log::info(logcat, "Database is opened read only - skipping fixup check"); return; } @@ -393,7 +391,7 @@ uint64_t BlockchainDB::get_tx_block_height(const crypto::hash &h) const if (result == std::numeric_limits::max()) { std::string err = "tx_data_t with hash " + tools::type_to_hex(h) + " not found in db"; - LOG_PRINT_L1(err); + oxen::log::info(logcat, "{}", err); throw TX_DNE(std::move(err)); } return result; diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index adfb782cf..3ce362ce3 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -35,6 +35,8 @@ #include #include #include +#include +#include #include "common/string_util.h" #include "cryptonote_basic/hardfork.h" @@ -46,16 +48,13 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "crypto/crypto.h" #include "ringct/rctOps.h" +#include "logging/oxen_logger.h" #include "checkpoints/checkpoints.h" #include "cryptonote_core/service_node_rules.h" #include "cryptonote_core/service_node_list.h" #include "cryptonote_core/uptime_proof.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "blockchain.db.lmdb" - - using namespace crypto; enum struct lmdb_version @@ -72,6 +71,8 @@ constexpr lmdb_version VERSION = tools::enum_top; namespace { + static auto logcat = oxen::log::Cat("blockchain.db.lmdb"); + // This MUST be identical to output_data_t, without the extra rct data at the end struct pre_rct_output_data_t { @@ -84,14 +85,14 @@ static_assert(sizeof(pre_rct_output_data_t) == sizeof(crypto::public_key) + 2*si template void throw0(const T &e) { - LOG_PRINT_L0(e.what()); + oxen::log::warning(logcat, e.what()); throw e; } template void throw1(const T &e) { - LOG_PRINT_L1(e.what()); + oxen::log::info(logcat, e.what()); throw e; } @@ -319,8 +320,7 @@ public: else if constexpr (sizeof...(More)) load_variant(); else { - MWARNING("Invalid stored type size in iterable_db: stored size (" << v.mv_size << - ") matched none of " << tools::type_name()); + oxen::log::warning(logcat, "Invalid stored type size in iterable_db: stored size ({}) matched none of {}", v.mv_size, tools::type_name()); var::get<0>(element.second) = nullptr; } } @@ -489,7 +489,7 @@ mdb_txn_safe::~mdb_txn_safe() { if (!m_check) return; - LOG_PRINT_L3("mdb_txn_safe: destructor"); + oxen::log::trace(logcat, "mdb_txn_safe: destructor"); if (m_tinfo != nullptr) { mdb_txn_reset(m_tinfo->m_ti_rtxn); @@ -498,7 +498,7 @@ mdb_txn_safe::~mdb_txn_safe() { if (m_batch_txn) // this is a batch txn and should have been handled before this point for safety { - LOG_PRINT_L0("WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()"); + oxen::log::warning(logcat, "WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()"); } else { @@ -508,7 +508,7 @@ mdb_txn_safe::~mdb_txn_safe() // // NOTE: not sure if this is ever reached for a non-batch write // transaction, but it's probably not ideal if it did. - LOG_PRINT_L3("mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()"); + oxen::log::trace(logcat, "mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()"); } mdb_txn_abort(m_txn); } @@ -538,7 +538,7 @@ void mdb_txn_safe::commit(std::string message) void mdb_txn_safe::abort() { - LOG_PRINT_L3("mdb_txn_safe: abort()"); + oxen::log::trace(logcat, "mdb_txn_safe: abort()"); if(m_txn != nullptr) { mdb_txn_abort(m_txn); @@ -546,7 +546,7 @@ void mdb_txn_safe::abort() } else { - LOG_PRINT_L0("WARNING: mdb_txn_safe: abort() called, but m_txn is NULL"); + oxen::log::warning(logcat, "WARNING: mdb_txn_safe: abort() called, but m_txn is NULL"); } } @@ -574,7 +574,7 @@ void lmdb_resized(MDB_env *env) { mdb_txn_safe::prevent_new_txns(); - MGINFO("LMDB map resize detected."); + oxen::log::info(logcat, "LMDB map resize detected."); MDB_envinfo mei; @@ -590,7 +590,7 @@ void lmdb_resized(MDB_env *env) mdb_env_info(env, &mei); uint64_t new_mapsize = mei.me_mapsize; - MGINFO("LMDB Mapsize increased." << " Old: " << old / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB"); + oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", old / (1024 * 1024), new_mapsize / (1024 * 1024)); mdb_txn_safe::allow_new_txns(); } @@ -623,7 +623,7 @@ void BlockchainLMDB::check_open() const void BlockchainLMDB::do_resize(uint64_t increase_size) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); std::lock_guard lock{*this}; const uint64_t add_size = 1LL << 30; @@ -633,15 +633,14 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) auto si = fs::space(m_folder); if(si.available < add_size) { - MERROR("!! WARNING: Insufficient free space to extend database !!: " << - (si.available >> 20L) << " MB available, " << (add_size >> 20L) << " MB needed"); + oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available, {} MB needed", (si.available >> 20L), (add_size >> 20L)); return; } } catch(...) { // print something but proceed. - MWARNING("Unable to query free disk space."); + oxen::log::warning(logcat, "Unable to query free disk space."); } MDB_envinfo mei; @@ -683,7 +682,7 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) if (result) throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str())); - MGINFO("LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB"); + oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); mdb_txn_safe::allow_new_txns(); } @@ -691,7 +690,7 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) // threshold_size is used for batch transactions bool BlockchainLMDB::need_resize(uint64_t threshold_size) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); #if defined(ENABLE_AUTO_RESIZE) MDB_envinfo mei; @@ -707,18 +706,18 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const // additional size needed. uint64_t size_used = mst.ms_psize * mei.me_last_pgno; - MDEBUG("DB map size: " << mei.me_mapsize); - MDEBUG("Space used: " << size_used); - MDEBUG("Space remaining: " << mei.me_mapsize - size_used); - MDEBUG("Size threshold: " << threshold_size); + oxen::log::debug(logcat, "DB map size: {}", mei.me_mapsize); + oxen::log::debug(logcat, "Space used: {}", size_used); + oxen::log::debug(logcat, "Space remaining: {}", mei.me_mapsize - size_used); + oxen::log::debug(logcat, "Size threshold: {}", threshold_size); float resize_percent = RESIZE_PERCENT; - MDEBUG("Percent used: " << 100.*size_used/mei.me_mapsize << " Percent threshold: " << 100.*resize_percent); + oxen::log::debug(logcat, "Percent used: {} Percent threshold: {}", 100.*size_used/mei.me_mapsize, 100.*resize_percent); if (threshold_size > 0) { if (mei.me_mapsize - size_used < threshold_size) { - MINFO("Threshold met (size-based)"); + oxen::log::info(logcat, "Threshold met (size-based)"); return true; } else @@ -727,7 +726,7 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const if ((double)size_used / mei.me_mapsize > resize_percent) { - MINFO("Threshold met (percent-based)"); + oxen::log::info(logcat, "Threshold met (percent-based)"); return true; } return false; @@ -738,15 +737,15 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint64_t batch_bytes) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); - MTRACE("[" << __func__ << "] " << "checking DB size"); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + oxen::log::trace(logcat, "[{}] checking DB size", __func__); const uint64_t min_increase_size = 512 * (1 << 20); uint64_t threshold_size = 0; uint64_t increase_size = 0; if (batch_num_blocks > 0) { threshold_size = get_estimated_batch_size(batch_num_blocks, batch_bytes); - MDEBUG("calculated batch size: " << threshold_size); + oxen::log::debug(logcat, "calculated batch size: {}", threshold_size); // The increased DB size could be a multiple of threshold_size, a fixed // size increase (> threshold_size), or other variations. @@ -755,7 +754,7 @@ void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint6 // minimum size increase is used to avoid frequent resizes when the batch // size is set to a very small numbers of blocks. increase_size = (threshold_size > min_increase_size) ? threshold_size : min_increase_size; - MDEBUG("increase size: " << increase_size); + oxen::log::debug(logcat, "increase size: {}", increase_size); } // if threshold_size is 0 (i.e. number of blocks for batch not passed in), it @@ -763,14 +762,14 @@ void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint6 // size-based check if (need_resize(threshold_size)) { - MGINFO("[batch] DB resize needed"); + oxen::log::info(logcat, "[batch] DB resize needed"); do_resize(increase_size); } } uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uint64_t batch_bytes) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t threshold_size = 0; // batch size estimate * batch safety factor = final size estimate @@ -793,7 +792,7 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin block_start = block_stop - num_prev_blocks + 1; uint32_t num_blocks_used = 0; uint64_t total_block_size = 0; - MDEBUG("[" << __func__ << "] " << "m_height: " << m_height << " block_start: " << block_start << " block_stop: " << block_stop); + oxen::log::debug(logcat, "[{}] m_height: {} block_start: {} block_stop: {}", __func__, m_height, block_start, block_stop); size_t avg_block_size = 0; if (batch_bytes) { @@ -802,12 +801,12 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin } if (m_height == 0) { - MDEBUG("No existing blocks to check for average block size"); + oxen::log::debug(logcat, "No existing blocks to check for average block size"); } else if (m_cum_count >= num_prev_blocks) { avg_block_size = m_cum_size / m_cum_count; - MDEBUG("average block size across recent " << m_cum_count << " blocks: " << avg_block_size); + oxen::log::debug(logcat, "average block size across recent {} blocks: {}", m_cum_count, avg_block_size); m_cum_size = 0; m_cum_count = 0; } @@ -829,12 +828,12 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin } if (my_rtxn) block_rtxn_stop(); avg_block_size = total_block_size / (num_blocks_used ? num_blocks_used : 1); - MDEBUG("average block size across recent " << num_blocks_used << " blocks: " << avg_block_size); + oxen::log::debug(logcat, "average block size across recent {} blocks: {}", num_blocks_used, avg_block_size); } estim: if (avg_block_size < min_block_size) avg_block_size = min_block_size; - MDEBUG("estimated average block size for batch: " << avg_block_size); + oxen::log::debug(logcat, "estimated average block size for batch: {}", avg_block_size); // bigger safety margin on smaller block sizes if (batch_fudge_factor < 5000.0) @@ -846,7 +845,7 @@ estim: void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated, uint64_t num_rct_outs, const crypto::hash& blk_hash) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -863,8 +862,8 @@ void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t l int result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &parent_key, MDB_GET_BOTH); if (result) { - LOG_PRINT_L3("m_height: " << m_height); - LOG_PRINT_L3("parent_key: " << blk.prev_id); + oxen::log::trace(logcat, "m_height: {}", m_height); + oxen::log::trace(logcat, "parent_key: {}", blk.prev_id); throw0(DB_ERROR(lmdb_error("Failed to get top block hash to check for new block's parent: ", result).c_str())); } blk_height *prev = (blk_height *)parent_key.mv_data; @@ -924,7 +923,7 @@ void BlockchainLMDB::remove_block() { int result; - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -959,7 +958,7 @@ void BlockchainLMDB::remove_block() uint64_t BlockchainLMDB::add_transaction_data(const crypto::hash& blk_hash, const std::pair& txp, const crypto::hash& tx_hash, const crypto::hash& tx_prunable_hash) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -1050,7 +1049,7 @@ void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const { int result; - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1107,7 +1106,7 @@ void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const result = mdb_cursor_get(m_cur_tx_outputs, &val_tx_id, NULL, MDB_SET); if (result == MDB_NOTFOUND) - LOG_PRINT_L1("tx has no outputs to remove: " << tx_hash); + oxen::log::info(logcat, "tx has no outputs to remove: {}", tx_hash); else if (result) throw1(DB_ERROR(lmdb_error("Failed to locate tx outputs for removal: ", result).c_str())); if (!result) @@ -1128,7 +1127,7 @@ uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash, const uint64_t unlock_time, const rct::key *commitment) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -1191,7 +1190,7 @@ uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash, void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, const std::vector& amount_output_indices) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(tx_outputs) @@ -1204,7 +1203,7 @@ void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, MDB_val v; v.mv_data = num_outputs ? (void *)amount_output_indices.data() : (void*)""; v.mv_size = sizeof(uint64_t) * num_outputs; - // LOG_PRINT_L1("tx_outputs[tx_hash] size: " << v.mv_size); + // oxen::log::info(logcat, "tx_outputs[tx_hash] size: {}", v.mv_size); result = mdb_cursor_put(m_cur_tx_outputs, &k_tx_id, &v, MDB_APPEND); if (result) @@ -1213,7 +1212,7 @@ void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& tx) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); std::vector> amount_output_indices_set = get_tx_amount_output_indices(tx_id, 1); const std::vector &amount_output_indices = amount_output_indices_set.front(); @@ -1221,7 +1220,7 @@ void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& if (amount_output_indices.empty()) { if (tx.vout.empty()) - LOG_PRINT_L2("tx has no outputs, so no output indices"); + oxen::log::debug(logcat, "tx has no outputs, so no output indices"); else throw0(DB_ERROR("tx has outputs, but no output indices found")); } @@ -1236,7 +1235,7 @@ void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_index) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(output_amounts); @@ -1274,13 +1273,13 @@ void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_in void BlockchainLMDB::prune_outputs(uint64_t amount) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(output_amounts); CURSOR(output_txs); - MINFO("Pruning outputs for amount " << amount); + oxen::log::info(logcat, "Pruning outputs for amount {}", amount); MDB_val v; MDB_val_set(k, amount); @@ -1293,14 +1292,14 @@ void BlockchainLMDB::prune_outputs(uint64_t amount) // gather output ids mdb_size_t num_elems; mdb_cursor_count(m_cur_output_amounts, &num_elems); - MINFO(num_elems << " outputs found"); + oxen::log::info(logcat, "{} outputs found", num_elems); std::vector output_ids; output_ids.reserve(num_elems); while (1) { const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data; output_ids.push_back(okp->output_id); - MDEBUG("output id " << okp->output_id); + oxen::log::debug(logcat, "output id {}", okp->output_id); result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_NEXT_DUP); if (result == MDB_NOTFOUND) break; @@ -1328,7 +1327,7 @@ void BlockchainLMDB::prune_outputs(uint64_t amount) void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1345,7 +1344,7 @@ void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image) void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1365,7 +1364,7 @@ void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image) BlockchainLMDB::~BlockchainLMDB() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); // batch transaction shouldn't be active at this point. If it is, consider it aborted. if (m_batch_active) @@ -1379,7 +1378,7 @@ BlockchainLMDB::~BlockchainLMDB() BlockchainLMDB::BlockchainLMDB(bool batch_transactions): BlockchainDB() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); // initialize folder to something "safe" just in case // someone accidentally misuses this class... m_folder = "thishsouldnotexistbecauseitisgibberish"; @@ -1399,7 +1398,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net int result; int mdb_flags = MDB_NORDAHEAD; - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (m_open) throw0(DB_OPEN_FAILURE("Attempted to open db, but it's already open")); @@ -1420,8 +1419,8 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net if (fs::exists(old_files / BLOCKCHAINDATA_FILENAME) || fs::exists(old_files / BLOCKCHAINDATA_LOCK_FILENAME)) { - LOG_PRINT_L0("Found existing LMDB files in " << old_files.u8string()); - LOG_PRINT_L0("Move " << BLOCKCHAINDATA_FILENAME << " and/or " << BLOCKCHAINDATA_LOCK_FILENAME << " to " << filename << ", or delete them, and then restart"); + oxen::log::warning(logcat, "Found existing LMDB files in {}", old_files.u8string()); + oxen::log::warning(logcat, "Move {} and/or {} to {}, or delete them, and then restart", BLOCKCHAINDATA_FILENAME, BLOCKCHAINDATA_LOCK_FILENAME, filename); throw DB_ERROR("Database could not be opened"); } @@ -1429,7 +1428,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net #ifdef __OpenBSD__ if ((mdb_flags & MDB_WRITEMAP) == 0) { - MCLOG_RED(el::Level::Info, "global", "Running on OpenBSD: forcing WRITEMAP"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Running on OpenBSD: forcing WRITEMAP")); mdb_flags |= MDB_WRITEMAP; } #endif @@ -1470,12 +1469,12 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net throw0(DB_ERROR(lmdb_error("Failed to set max memory map size: ", result).c_str())); mdb_env_info(m_env, &mei); cur_mapsize = (uint64_t)mei.me_mapsize; - LOG_PRINT_L1("LMDB memory map size: " << cur_mapsize); + oxen::log::info(logcat, "LMDB memory map size: {}", cur_mapsize); } if (need_resize()) { - LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now."); + oxen::log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); do_resize(); } @@ -1561,7 +1560,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net MDB_stat db_stats; if ((result = mdb_stat(txn, m_blocks, &db_stats))) throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); - LOG_PRINT_L2("Setting m_height to: " << db_stats.ms_entries); + oxen::log::debug(logcat, "Setting m_height to: {}", db_stats.ms_entries); uint64_t m_height = db_stats.ms_entries; MDB_val_str(k, "version"); @@ -1575,17 +1574,17 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net bool failed = false; if (db_version > static_cast(VERSION)) { - MWARNING("Existing lmdb database was made by a later version (" << db_version << "). We don't know how it will change yet."); - MFATAL("Existing lmdb database is incompatible with this version."); - MFATAL("Please delete the existing database and resync."); + oxen::log::warning(logcat, "Existing lmdb database was made by a later version ({}). We don't know how it will change yet.", db_version); + oxen::log::error(logcat, "Existing lmdb database is incompatible with this version."); + oxen::log::error(logcat, "Please delete the existing database and resync."); failed = true; } else if (db_version < static_cast(VERSION)) { if (mdb_flags & MDB_RDONLY) { - MFATAL("Existing lmdb database needs to be converted, which cannot be done on a read-only database."); - MFATAL("Please run oxend once to convert the database."); + oxen::log::error(logcat, "Existing lmdb database needs to be converted, which cannot be done on a read-only database."); + oxen::log::error(logcat, "Please run oxend once to convert the database."); failed = true; } else @@ -1619,7 +1618,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net txn.abort(); mdb_env_close(m_env); m_open = false; - MERROR("Failed to write version to database."); + oxen::log::error(logcat, "Failed to write version to database."); return; } } @@ -1633,10 +1632,10 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net void BlockchainLMDB::close() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (m_batch_active) { - LOG_PRINT_L3("close() first calling batch_abort() due to active batch transaction"); + oxen::log::trace(logcat, "close() first calling batch_abort() due to active batch transaction"); batch_abort(); } this->sync(); @@ -1649,7 +1648,7 @@ void BlockchainLMDB::close() void BlockchainLMDB::sync() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); if (is_read_only()) @@ -1665,13 +1664,13 @@ void BlockchainLMDB::sync() void BlockchainLMDB::safesyncmode(const bool onoff) { - MINFO("switching safe mode " << (onoff ? "on" : "off")); + oxen::log::info(logcat, "switching safe mode {}", (onoff ? "on" : "off")); mdb_env_set_flags(m_env, MDB_NOSYNC|MDB_MAPASYNC, !onoff); } void BlockchainLMDB::reset() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_safe txn; @@ -1727,7 +1726,7 @@ void BlockchainLMDB::reset() std::vector BlockchainLMDB::get_filenames() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); std::vector paths; paths.push_back(m_folder / BLOCKCHAINDATA_FILENAME); paths.push_back(m_folder / BLOCKCHAINDATA_LOCK_FILENAME); @@ -1743,7 +1742,7 @@ bool BlockchainLMDB::remove_data_file(const fs::path& folder) const } catch (const std::exception &e) { - MERROR("Failed to remove " << filename << ": " << e.what()); + oxen::log::error(logcat, "Failed to remove {}: {}", filename, e.what()); return false; } return true; @@ -1751,26 +1750,26 @@ bool BlockchainLMDB::remove_data_file(const fs::path& folder) const std::string BlockchainLMDB::get_db_name() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); return "lmdb"s; } void BlockchainLMDB::lock() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); m_synchronization_lock.lock(); } bool BlockchainLMDB::try_lock() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); return m_synchronization_lock.try_lock(); } void BlockchainLMDB::unlock() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); m_synchronization_lock.unlock(); } @@ -1824,7 +1823,7 @@ void BlockchainLMDB::unlock() void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const std::string &blob, const txpool_tx_meta_t &meta) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1850,7 +1849,7 @@ void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const std::string & void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1876,7 +1875,7 @@ void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_ uint64_t BlockchainLMDB::get_txpool_tx_count(bool include_unrelayed_txes) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); int result; @@ -1920,7 +1919,7 @@ uint64_t BlockchainLMDB::get_txpool_tx_count(bool include_unrelayed_txes) const bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -1935,7 +1934,7 @@ bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid) const void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1965,7 +1964,7 @@ void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid) bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -1985,7 +1984,7 @@ bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta bool BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, std::string &bd) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2016,7 +2015,7 @@ std::string BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid) const uint32_t BlockchainLMDB::get_blockchain_pruning_seed() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2050,7 +2049,7 @@ enum { prune_mode_prune, prune_mode_update, prune_mode_check }; bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); const uint32_t log_stripes = tools::get_pruning_log_stripes(pruning_seed); if (log_stripes && log_stripes != PRUNING_LOG_STRIPES) throw0(DB_ERROR("Pruning seed not in range")); @@ -2084,7 +2083,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode != prune_mode_prune) { txn.abort(); - MDEBUG("Pruning not enabled, nothing to do"); + oxen::log::debug(logcat, "Pruning not enabled, nothing to do"); return true; } if (pruning_seed == 0) @@ -2118,9 +2117,9 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) } if (mode == prune_mode_check) - MINFO("Checking blockchain pruning..."); + oxen::log::info(logcat, "Checking blockchain pruning..."); else - MINFO("Pruning blockchain..."); + oxen::log::info(logcat, "Pruning blockchain..."); MDB_cursor *c_txs_pruned, *c_txs_prunable, *c_txs_prunable_tip; result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned); @@ -2156,12 +2155,12 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) ++n_prunable_records; result = mdb_cursor_get(c_txs_prunable, &k, &v, MDB_SET); if (result == MDB_NOTFOUND) - MWARNING("Already pruned at height " << block_height << "/" << blockchain_height); + oxen::log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); else if (result) throw0(DB_ERROR(lmdb_error("Failed to find transaction prunable data: ", result).c_str())); else { - MDEBUG("Pruning at height " << block_height << "/" << blockchain_height); + oxen::log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); ++n_pruned_records; ++commit_counter; n_bytes += k.mv_size + v.mv_size; @@ -2176,7 +2175,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode != prune_mode_check && commit_counter >= 4096) { - MDEBUG("Committing txn at checkpoint..."); + oxen::log::debug(logcat, "Committing txn at checkpoint..."); txn.commit(); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -2226,8 +2225,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (result && result != MDB_NOTFOUND) throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str())); if (result == MDB_NOTFOUND) - MERROR("Transaction not found in prunable tip table for height " << block_height << "/" << blockchain_height << - ", seed " << epee::string_tools::to_string_hex(pruning_seed)); + oxen::log::error(logcat, "Transaction not found in prunable tip table for height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } else { @@ -2245,17 +2243,16 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode == prune_mode_check) { if (result != MDB_NOTFOUND) - MERROR("Prunable data found for pruned height " << block_height << "/" << blockchain_height << - ", seed " << epee::string_tools::to_string_hex(pruning_seed)); + oxen::log::error(logcat, "Prunable data found for pruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } else { ++n_prunable_records; if (result == MDB_NOTFOUND) - MWARNING("Already pruned at height " << block_height << "/" << blockchain_height); + oxen::log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); else { - MDEBUG("Pruning at height " << block_height << "/" << blockchain_height); + oxen::log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); ++n_pruned_records; n_bytes += kp.mv_size + v.mv_size; result = mdb_cursor_del(c_txs_prunable, 0); @@ -2274,14 +2271,13 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (result && result != MDB_NOTFOUND) throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str())); if (result == MDB_NOTFOUND) - MERROR("Prunable data not found for unpruned height " << block_height << "/" << blockchain_height << - ", seed " << epee::string_tools::to_string_hex(pruning_seed)); + oxen::log::error(logcat, "Prunable data not found for unpruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } } if (mode != prune_mode_check && commit_counter >= 4096) { - MDEBUG("Committing txn at checkpoint..."); + oxen::log::debug(logcat, "Committing txn at checkpoint..."); txn.commit(); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -2321,10 +2317,17 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) txn.commit(); - MINFO((mode == prune_mode_check ? "Checked" : "Pruned") << " blockchain in " << - tools::friendly_duration(std::chrono::steady_clock::now() - t) << ": " << (n_bytes/1024.0f/1024.0f) << " MB (" << db_bytes/1024.0f/1024.0f << " MB) pruned in " << - n_pruned_records << " records (" << pages0 - pages1 << "/" << pages0 << " " << db_stats.ms_psize << " byte pages), " << - n_prunable_records << "/" << n_total_records << " pruned records"); + oxen::log::info(logcat, "{} blockchain in {}: {} MB ({} MB) prunded in {} records ({}/{} {} byte pages), {}/{} pruned records", + (mode == prune_mode_check ? "Checked" : "Pruned"), + tools::friendly_duration(std::chrono::steady_clock::now() - t), + (n_bytes/1024.0f/1024.0f), + db_bytes/1024.0f/1024.0f, + n_pruned_records, + pages0 - pages1, + pages0, + db_stats.ms_psize, + n_prunable_records, + n_total_records); return true; } @@ -2345,7 +2348,7 @@ bool BlockchainLMDB::check_pruning() bool BlockchainLMDB::for_all_txpool_txes(std::function f, bool include_blob, bool include_unrelayed_txes) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2458,7 +2461,7 @@ static bool read_alt_block_data_from_mdb_val(MDB_val const v, alt_block_data_t * bool BlockchainLMDB::for_all_alt_blocks(std::function f, bool include_blob) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2500,7 +2503,7 @@ bool BlockchainLMDB::for_all_alt_blocks(std::function(height); return result; } std::string BlockchainLMDB::get_block_blob(const crypto::hash& h) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); return get_block_blob_from_height(get_block_height(h)); @@ -2594,7 +2597,7 @@ std::string BlockchainLMDB::get_block_blob(const crypto::hash& h) const uint64_t BlockchainLMDB::get_block_height(const crypto::hash& h) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2620,14 +2623,14 @@ block_header BlockchainLMDB::get_block_header_from_height(uint64_t height) const std::string BlockchainLMDB::get_block_blob_from_height(uint64_t height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); std::string result = get_and_convert_block_blob_from_height(height); return result; } uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2649,7 +2652,7 @@ uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const std::vector BlockchainLMDB::get_block_cumulative_rct_outputs(const std::vector &heights) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector res; int result; @@ -2710,7 +2713,7 @@ std::vector BlockchainLMDB::get_block_cumulative_rct_outputs(const std uint64_t BlockchainLMDB::get_top_block_timestamp() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -2725,7 +2728,7 @@ uint64_t BlockchainLMDB::get_top_block_timestamp() const size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2747,7 +2750,7 @@ size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const std::vector BlockchainLMDB::get_block_info_64bit_fields(uint64_t start_height, size_t count, uint64_t (*extract)(const mdb_block_info* bi_data)) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2799,7 +2802,7 @@ std::vector BlockchainLMDB::get_block_info_64bit_fields(uint64_t start uint64_t BlockchainLMDB::get_max_block_size() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2820,7 +2823,7 @@ uint64_t BlockchainLMDB::get_max_block_size() void BlockchainLMDB::add_max_block_size(uint64_t sz) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -2861,7 +2864,7 @@ std::vector BlockchainLMDB::get_long_term_block_weights(uint64_t start difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__ << " height: " << height); + oxen::log::trace(logcat, "BlockchainLMDB::{} height: {}", __func__, height); check_open(); TXN_PREFIX_RDONLY(); @@ -2883,7 +2886,7 @@ difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); difficulty_type diff1 = 0; @@ -2900,7 +2903,7 @@ difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) con uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2922,7 +2925,7 @@ uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& heigh uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2944,7 +2947,7 @@ uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) cons crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2966,7 +2969,7 @@ crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) std::vector BlockchainLMDB::get_blocks_range(const uint64_t& h1, const uint64_t& h2) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -2980,7 +2983,7 @@ std::vector BlockchainLMDB::get_blocks_range(const uint64_t& h1, const ui std::vector BlockchainLMDB::get_hashes_range(const uint64_t& h1, const uint64_t& h2) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -2994,7 +2997,7 @@ std::vector BlockchainLMDB::get_hashes_range(const uint64_t& h1, c crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); if (block_height) @@ -3009,7 +3012,7 @@ crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const block BlockchainLMDB::get_top_block() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -3024,7 +3027,7 @@ block BlockchainLMDB::get_top_block() const uint64_t BlockchainLMDB::height() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); int result; @@ -3038,7 +3041,7 @@ uint64_t BlockchainLMDB::height() const uint64_t BlockchainLMDB::num_outputs() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); int result; @@ -3060,7 +3063,7 @@ uint64_t BlockchainLMDB::num_outputs() const bool BlockchainLMDB::tx_exists(const crypto::hash& h) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3080,7 +3083,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h) const if (! tx_found) { - LOG_PRINT_L1("transaction with hash " << tools::type_to_hex(h) << " not found in db"); + oxen::log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); return false; } @@ -3089,7 +3092,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h) const bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3108,7 +3111,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const bool ret = false; if (get_result == MDB_NOTFOUND) { - LOG_PRINT_L1("transaction with hash " << tools::type_to_hex(h) << " not found in db"); + oxen::log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); } else if (get_result) throw0(DB_ERROR(lmdb_error("DB error attempting to fetch transaction from hash", get_result).c_str())); @@ -3120,7 +3123,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3140,7 +3143,7 @@ uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, std::string &bd) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3175,7 +3178,7 @@ bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, std::string &bd) const bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, std::string &bd) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3203,7 +3206,7 @@ bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, std::string &bd) bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t count, std::vector &bd) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); if (!count) @@ -3243,7 +3246,7 @@ bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t coun bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, std::string &bd) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3271,7 +3274,7 @@ bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, std::string &bd bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::hash &prunable_hash) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3299,7 +3302,7 @@ bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::h uint64_t BlockchainLMDB::get_tx_count() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3314,7 +3317,7 @@ uint64_t BlockchainLMDB::get_tx_count() const std::vector BlockchainLMDB::get_tx_list(const std::vector& hlist) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -3328,7 +3331,7 @@ std::vector BlockchainLMDB::get_tx_list(const std::vector BlockchainLMDB::get_tx_block_heights(const std::vector& hs) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector result; result.reserve(hs.size()); @@ -3352,7 +3355,7 @@ std::vector BlockchainLMDB::get_tx_block_heights(const std::vector offsets; std::vector indices; offsets.push_back(index); @@ -3442,7 +3445,7 @@ tx_out_index BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, con std::vector> BlockchainLMDB::get_tx_amount_output_indices(uint64_t tx_id, size_t n_txes) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); @@ -3459,7 +3462,7 @@ std::vector> BlockchainLMDB::get_tx_amount_output_indices( { int result = mdb_cursor_get(m_cur_tx_outputs, &k_tx_id, &v, op); if (result == MDB_NOTFOUND) - LOG_PRINT_L0("WARNING: Unexpected: tx has no amount indices stored in " + oxen::log::warning(logcat, "WARNING: Unexpected: tx has no amount indices stored in " "tx_outputs, but it should have an empty entry even if it's a tx without " "outputs"); else if (result) @@ -3484,7 +3487,7 @@ std::vector> BlockchainLMDB::get_tx_amount_output_indices( bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); bool ret; @@ -3500,7 +3503,7 @@ bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const bool BlockchainLMDB::for_all_key_images(std::function f) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3531,7 +3534,7 @@ bool BlockchainLMDB::for_all_key_images(std::function f) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3580,7 +3583,7 @@ bool BlockchainLMDB::for_blocks_range(const uint64_t& h1, const uint64_t& h2, st bool BlockchainLMDB::for_all_transactions(std::function f, bool pruned) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3642,7 +3645,7 @@ bool BlockchainLMDB::for_all_transactions(std::function f) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3675,7 +3678,7 @@ bool BlockchainLMDB::for_all_outputs(std::function &f) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3697,7 +3700,7 @@ bool BlockchainLMDB::for_all_outputs(uint64_t amount, const std::functionm_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } - LOG_PRINT_L3("batch transaction: begin"); + oxen::log::trace(logcat, "batch transaction: begin"); return true; } void BlockchainLMDB::batch_commit() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3769,11 +3772,11 @@ void BlockchainLMDB::batch_commit() check_open(); - LOG_PRINT_L3("batch transaction: committing..."); + oxen::log::trace(logcat, "batch transaction: committing..."); auto time1 = std::chrono::steady_clock::now(); m_write_txn->commit(); time_commit1 += std::chrono::steady_clock::now() - time1; - LOG_PRINT_L3("batch transaction: committed"); + oxen::log::trace(logcat, "batch transaction: committed"); m_write_txn = nullptr; delete m_write_batch_txn; @@ -3793,7 +3796,7 @@ void BlockchainLMDB::cleanup_batch() void BlockchainLMDB::batch_stop() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3803,7 +3806,7 @@ void BlockchainLMDB::batch_stop() if (m_writer != boost::this_thread::get_id()) throw1(DB_ERROR("batch transaction owned by other thread")); check_open(); - LOG_PRINT_L3("batch transaction: committing..."); + oxen::log::trace(logcat, "batch transaction: committing..."); auto time1 = std::chrono::steady_clock::now(); try { @@ -3816,12 +3819,12 @@ void BlockchainLMDB::batch_stop() cleanup_batch(); throw; } - LOG_PRINT_L3("batch transaction: end"); + oxen::log::trace(logcat, "batch transaction: end"); } void BlockchainLMDB::batch_abort() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3839,18 +3842,18 @@ void BlockchainLMDB::batch_abort() m_write_batch_txn = nullptr; m_batch_active = false; memset(&m_wcursors, 0, sizeof(m_wcursors)); - LOG_PRINT_L3("batch transaction: aborted"); + oxen::log::trace(logcat, "batch transaction: aborted"); } void BlockchainLMDB::set_batch_transactions(bool batch_transactions) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if ((batch_transactions) && (m_batch_transactions)) { - MINFO("batch transaction mode already enabled, but asked to enable batch mode"); + oxen::log::info(logcat, "batch transaction mode already enabled, but asked to enable batch mode"); } m_batch_transactions = batch_transactions; - MINFO("batch transactions " << (m_batch_transactions ? "enabled" : "disabled")); + oxen::log::info(logcat, "batch transactions {}", (m_batch_transactions ? "enabled" : "disabled")); } // return true if we started the txn, false if already started @@ -3887,13 +3890,13 @@ bool BlockchainLMDB::block_rtxn_start(MDB_txn **mtxn, mdb_txn_cursors **mcur) co *mcur = &tinfo->m_ti_rcursors; if (ret) - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); return ret; } void BlockchainLMDB::block_rtxn_stop() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); mdb_txn_reset(m_tinfo->m_ti_rtxn); memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } @@ -3907,7 +3910,7 @@ bool BlockchainLMDB::block_rtxn_start() const void BlockchainLMDB::block_wtxn_start() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); // Distinguish the exceptions here from exceptions that would be thrown while // using the txn and committing it. // @@ -3940,7 +3943,7 @@ void BlockchainLMDB::block_wtxn_start() void BlockchainLMDB::block_wtxn_stop() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (!m_write_txn) throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn when no such txn exists in ")+__FUNCTION__).c_str())); if (m_writer != boost::this_thread::get_id()) @@ -3961,7 +3964,7 @@ void BlockchainLMDB::block_wtxn_stop() void BlockchainLMDB::block_wtxn_abort() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); if (!m_write_txn) throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn when no such txn exists in ")+__FUNCTION__).c_str())); if (m_writer != boost::this_thread::get_id()) @@ -3977,7 +3980,7 @@ void BlockchainLMDB::block_wtxn_abort() void BlockchainLMDB::block_rtxn_abort() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); mdb_txn_reset(m_tinfo->m_ti_rtxn); memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } @@ -3985,7 +3988,7 @@ void BlockchainLMDB::block_rtxn_abort() const uint64_t BlockchainLMDB::add_block(const std::pair& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated, const std::vector>& txs) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -3994,7 +3997,7 @@ uint64_t BlockchainLMDB::add_block(const std::pair& blk, siz // for batch mode, DB resize check is done at start of batch transaction if (! m_batch_active && need_resize()) { - LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now."); + oxen::log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); do_resize(); } } @@ -4031,7 +4034,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check result.len = sizeof(header) + bytes_for_signatures; if (result.len > sizeof(result.data)) { - LOG_PRINT_L0("Unexpected pre-calculated maximum number of bytes: " << sizeof(result.data) << ", is insufficient to store signatures requiring: " << result.len << " bytes"); + oxen::log::warning(logcat, "Unexpected pre-calculated maximum number of bytes: {}, is insufficient to store signatures requiring: {} bytes", sizeof(result.data), result.len); assert(result.len <= sizeof(result.data)); return false; } @@ -4048,7 +4051,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check char const *end = result.data + sizeof(result.data); if (buffer_ptr > end) { - LOG_PRINT_L0("Unexpected memcpy bounds overflow on update_block_checkpoint"); + oxen::log::warning(logcat, "Unexpected memcpy bounds overflow on update_block_checkpoint"); assert(buffer_ptr <= end); return false; } @@ -4059,7 +4062,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check void BlockchainLMDB::update_block_checkpoint(checkpoint_t const &checkpoint) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); checkpoint_mdb_buffer buffer = {}; convert_checkpoint_into_buffer(checkpoint, buffer); @@ -4079,7 +4082,7 @@ void BlockchainLMDB::update_block_checkpoint(checkpoint_t const &checkpoint) void BlockchainLMDB::remove_block_checkpoint(uint64_t height) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4140,14 +4143,14 @@ bool BlockchainLMDB::get_block_checkpoint_internal(uint64_t height, checkpoint_t bool BlockchainLMDB::get_block_checkpoint(uint64_t height, checkpoint_t &checkpoint) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); bool result = get_block_checkpoint_internal(height, checkpoint, MDB_SET_KEY); return result; } bool BlockchainLMDB::get_top_checkpoint(checkpoint_t &checkpoint) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); bool result = get_block_checkpoint_internal(0, checkpoint, MDB_LAST); return result; } @@ -4241,7 +4244,7 @@ std::vector BlockchainLMDB::get_checkpoints_range(uint64_t start, void BlockchainLMDB::pop_block(block& blk, std::vector& txs) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); block_wtxn_start(); @@ -4261,7 +4264,7 @@ void BlockchainLMDB::pop_block(block& blk, std::vector& txs) void BlockchainLMDB::get_output_tx_and_index_from_global(const std::vector &global_indices, std::vector &tx_out_indices) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); tx_out_indices.clear(); tx_out_indices.reserve(global_indices.size()); @@ -4289,7 +4292,7 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c if (amounts.size() != 1 && amounts.size() != offsets.size()) throw0(DB_ERROR("Invalid sizes of amounts and offets")); - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); auto db3 = std::chrono::steady_clock::now(); check_open(); outputs.clear(); @@ -4310,7 +4313,7 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c { if (allow_partial) { - MDEBUG("Partial result: " << outputs.size() << "/" << offsets.size()); + oxen::log::debug(logcat, "Partial result: {}/{}", outputs.size(), offsets.size()); break; } throw1(OUTPUT_DNE((std::string("Attempting to get output pubkey by global index (amount ") + std::to_string(amount) + ", index " + std::to_string(offsets[i]) + ", count " + std::to_string(get_num_outputs(amount)) + "), but key does not exist (current height " + std::to_string(height()) + ")").c_str())); @@ -4332,13 +4335,12 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c data.commitment = rct::zeroCommit(amount); } } - - LOG_PRINT_L3("db3: " << tools::friendly_duration(std::chrono::steady_clock::now() - db3)); + oxen::log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); } void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std::vector &offsets, std::vector &indices) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); indices.clear(); @@ -4368,12 +4370,12 @@ void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std:: { get_output_tx_and_index_from_global(tx_indices, indices); } - LOG_PRINT_L3("db3: " << tools::friendly_duration(std::chrono::steady_clock::now() - db3)); + oxen::log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); } std::map> BlockchainLMDB::get_output_histogram(const std::vector &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4464,7 +4466,7 @@ std::map> BlockchainLMDB::get bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, std::vector &distribution, uint64_t &base) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4509,7 +4511,7 @@ bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_heig void BlockchainLMDB::get_output_blacklist(std::vector &blacklist) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4552,7 +4554,7 @@ void BlockchainLMDB::add_output_blacklist(std::vector const &blacklist if (blacklist.size() == 0) return; - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4569,7 +4571,7 @@ void BlockchainLMDB::add_output_blacklist(std::vector const &blacklist void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string &block, std::string const *checkpoint) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4612,7 +4614,7 @@ void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote:: bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t *data, std::string *block, std::string *checkpoint) const { - LOG_PRINT_L3("BlockchainLMDB:: " << __func__); + oxen::log::trace(logcat, "BlockchainLMDB:: {}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4633,7 +4635,7 @@ bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t * void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4651,7 +4653,7 @@ void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid) uint64_t BlockchainLMDB::get_alt_block_count() { - LOG_PRINT_L3("BlockchainLMDB:: " << __func__); + oxen::log::trace(logcat, "BlockchainLMDB:: {}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4671,7 +4673,7 @@ uint64_t BlockchainLMDB::get_alt_block_count() void BlockchainLMDB::drop_alt_blocks() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX(0); @@ -4703,7 +4705,7 @@ uint64_t BlockchainLMDB::get_database_size() const void BlockchainLMDB::fixup(cryptonote::network_type nettype) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); // Always call parent as well BlockchainDB::fixup(nettype); @@ -4773,8 +4775,8 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) curr_cumulative_diff = next_block.bi_diff; curr_timestamp = next_block.bi_timestamp; - if (old_cumulative_diff != next_block.bi_diff) LOG_PRINT_L0("Height: " << curr_height << " curr difficulty: " << old_cumulative_diff << ", new difficulty: " << next_block.bi_diff); - else LOG_PRINT_L2("Height: " << curr_height << " difficulty unchanged (" << old_cumulative_diff << ")"); + if (old_cumulative_diff != next_block.bi_diff) oxen::log::warning(logcat, "Height: {} curr difficulty: {}, new difficulty: {}", curr_height, old_cumulative_diff, next_block.bi_diff); + else oxen::log::debug(logcat, "Height: {} difficulty unchanged ({})", curr_height, old_cumulative_diff); // NOTE: Store to DB MDB_val_set(val, next_block); @@ -4784,7 +4786,7 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) catch (DB_ERROR const &e) { block_wtxn_abort(); - LOG_PRINT_L0("Something went wrong recalculating difficulty for block " << curr_height << e.what()); + oxen::log::warning(logcat, "Something went wrong recalculating difficulty for block {}{}", curr_height, e.what()); return; } } @@ -4793,7 +4795,7 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) } catch (DB_ERROR const &e) { - LOG_PRINT_L0("Something went wrong in the pre-amble of recalculating difficulty for block: " << e.what()); + oxen::log::warning(logcat, "Something went wrong in the pre-amble of recalculating difficulty for block: {}", e.what()); return; } } @@ -4820,8 +4822,6 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) ptr = (char *)k.mv_data; \ ptr[sizeof(name)-2]++; } while(0) -#define LOGIF(y) if (ELPP->vRegistry()->allowed(y, "global")) - static int write_db_version(MDB_env *env, MDB_dbi &dest, uint32_t version) { MDB_val v = {}; @@ -4840,15 +4840,15 @@ static int write_db_version(MDB_env *env, MDB_dbi &dest, uint32_t version) void BlockchainLMDB::migrate_0_1() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i, z, m_height; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - MGINFO_YELLOW("Migrating blockchain from DB version 0 to 1 - this may take a while:"); - MINFO("updating blocks, hf_versions, outputs, txs, and spent_keys tables..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 0 to 1 - this may take a while:")); + oxen::log::info(logcat, "updating blocks, hf_versions, outputs, txs, and spent_keys tables..."); do { result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -4859,10 +4859,10 @@ void BlockchainLMDB::migrate_0_1() if ((result = mdb_stat(txn, m_blocks, &db_stats))) throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); m_height = db_stats.ms_entries; - MINFO("Total number of blocks: " << m_height); - MINFO("block migration will update block_heights, block_info, and hf_versions..."); + oxen::log::info(logcat, "Total number of blocks: {}", m_height); + oxen::log::info(logcat, "block migration will update block_heights, block_info, and hf_versions..."); - MINFO("migrating block_heights:"); + oxen::log::info(logcat, "migrating block_heights:"); MDB_dbi o_heights; unsigned int flags; @@ -4872,7 +4872,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if ((flags & (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) == (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) { txn.abort(); - LOG_PRINT_L1(" block_heights already migrated"); + oxen::log::info(logcat, " block_heights already migrated"); break; } @@ -4897,7 +4897,7 @@ void BlockchainLMDB::migrate_0_1() while(1) { if (!(i % 2000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << z << " \r" << std::flush; } txn.commit(); @@ -4963,7 +4963,7 @@ void BlockchainLMDB::migrate_0_1() * new table is DUPFIXED, k(zeroval), v{height, values...}. */ do { - LOG_PRINT_L1("migrating block info:"); + oxen::log::info(logcat, "migrating block info:"); MDB_dbi coins; result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -4972,7 +4972,7 @@ void BlockchainLMDB::migrate_0_1() result = mdb_dbi_open(txn, "block_coins", 0, &coins); if (result == MDB_NOTFOUND) { txn.abort(); - LOG_PRINT_L1(" block_info already migrated"); + oxen::log::info(logcat, " block_info already migrated"); break; } MDB_dbi diffs, hashes, sizes, timestamps; @@ -4990,7 +4990,7 @@ void BlockchainLMDB::migrate_0_1() MDB_val k, v; if (!(i % 2000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << z << " \r" << std::flush; } txn.commit(); @@ -5094,7 +5094,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - LOG_PRINT_L1("migrating hf_versions:"); + oxen::log::info(logcat, "migrating hf_versions:"); MDB_dbi o_hfv; unsigned int flags; @@ -5107,7 +5107,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if (flags & MDB_INTEGERKEY) { txn.abort(); - LOG_PRINT_L1(" hf_versions already migrated"); + oxen::log::info(logcat, " hf_versions already migrated"); break; } @@ -5124,7 +5124,7 @@ void BlockchainLMDB::migrate_0_1() while(1) { if (!(i % 2000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << z << " \r" << std::flush; } txn.commit(); @@ -5177,7 +5177,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - LOG_PRINT_L1("deleting old indices:"); + oxen::log::info(logcat, "deleting old indices:"); /* Delete all other tables, we're just going to recreate them */ MDB_dbi dbi; @@ -5188,13 +5188,13 @@ void BlockchainLMDB::migrate_0_1() result = mdb_dbi_open(txn, "tx_unlocks", 0, &dbi); if (result == MDB_NOTFOUND) { txn.abort(); - LOG_PRINT_L1(" old indices already deleted"); + oxen::log::info(logcat, " old indices already deleted"); break; } txn.abort(); #define DELETE_DB(x) do { \ - LOG_PRINT_L1(" " x ":"); \ + oxen::log::info(logcat, " " x ":"); \ result = mdb_txn_begin(m_env, NULL, 0, txn); \ if (result) \ throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str())); \ @@ -5230,7 +5230,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - LOG_PRINT_L1("migrating txs and outputs:"); + oxen::log::info(logcat, "migrating txs and outputs:"); unsigned int flags; result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -5242,7 +5242,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if (flags & MDB_INTEGERKEY) { txn.abort(); - LOG_PRINT_L1(" txs already migrated"); + oxen::log::info(logcat, " txs already migrated"); break; } @@ -5270,7 +5270,7 @@ void BlockchainLMDB::migrate_0_1() while(1) { if (!(i % 1000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << z << " \r" << std::flush; } MDB_val_set(pk, "txblk"); @@ -5374,15 +5374,15 @@ void BlockchainLMDB::migrate_0_1() void BlockchainLMDB::migrate_1_2() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i, z; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - MGINFO_YELLOW("Migrating blockchain from DB version 1 to 2 - this may take a while:"); - MINFO("updating txs_pruned and txs_prunable tables..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 1 to 2 - this may take a while:")); + oxen::log::info(logcat, "updating txs_pruned and txs_prunable tables..."); do { result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -5406,11 +5406,11 @@ void BlockchainLMDB::migrate_1_2() if (db_stats_txs_pruned.ms_entries == db_stats_txs.ms_entries) { txn.commit(); - MINFO("txs already migrated"); + oxen::log::info(logcat, "txs already migrated"); break; } - MINFO("updating txs tables:"); + oxen::log::info(logcat, "updating txs tables:"); MDB_cursor *c_old, *c_cur0, *c_cur1, *c_cur2; i = 0; @@ -5421,7 +5421,7 @@ void BlockchainLMDB::migrate_1_2() result = mdb_stat(txn, m_txs, &db_stats_txs); if (result) throw0(DB_ERROR(lmdb_error("Failed to query m_txs: ", result).c_str())); - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << (i + db_stats_txs.ms_entries) << " \r" << std::flush; } txn.commit(); @@ -5509,17 +5509,17 @@ void BlockchainLMDB::migrate_1_2() void BlockchainLMDB::migrate_2_3() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - MGINFO_YELLOW("Migrating blockchain from DB version 2 to 3 - this may take a while:"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 2 to 3 - this may take a while:")); do { - LOG_PRINT_L1("migrating block info:"); + oxen::log::info(logcat, "migrating block info:"); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -5530,12 +5530,12 @@ void BlockchainLMDB::migrate_2_3() throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); const uint64_t blockchain_height = db_stats.ms_entries; - MDEBUG("enumerating rct outputs..."); + oxen::log::debug(logcat, "enumerating rct outputs..."); std::vector distribution(blockchain_height, 0); bool r = for_all_outputs(0, [&](uint64_t height) { if (height >= blockchain_height) { - MERROR("Output found claiming height >= blockchain height"); + oxen::log::error(logcat, "Output found claiming height >= blockchain height"); return false; } distribution[height]++; @@ -5559,7 +5559,7 @@ void BlockchainLMDB::migrate_2_3() while(1) { if (!(i % 1000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << blockchain_height << " \r" << std::flush; } txn.commit(); @@ -5631,8 +5631,8 @@ void BlockchainLMDB::migrate_2_3() void BlockchainLMDB::migrate_3_4() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); - MGINFO_YELLOW("Migrating blockchain from DB version 3 to 4 - this may take a while:"); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 3 to 4 - this may take a while:")); // Migrate output blacklist { @@ -5685,7 +5685,7 @@ void BlockchainLMDB::migrate_3_4() if (++tx_count % 1000 == 0) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << tx_count << " / " << total_tx_count << " \r" << std::flush; } } @@ -5725,7 +5725,7 @@ void BlockchainLMDB::migrate_3_4() bool past_long_term_weight = false; do { - LOG_PRINT_L1("migrating block info:"); + oxen::log::info(logcat, "migrating block info:"); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -5757,7 +5757,7 @@ void BlockchainLMDB::migrate_3_4() while(1) { if (!(i % 1000)) { if (i) { - LOGIF(el::Level::Info) { + if (OXEN_LOG_ENABLED(info)) { std::cout << i << " / " << blockchain_height << " \r" << std::flush; } txn.commit(); @@ -5860,8 +5860,8 @@ void BlockchainLMDB::migrate_3_4() void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); - MGINFO_YELLOW("Migrating blockchain from DB version 4 to 5 - this may take a while:"); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 4 to 5 - this may take a while:")); mdb_txn_safe txn(false); { @@ -5933,8 +5933,8 @@ void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) void BlockchainLMDB::migrate_5_6() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); - MGINFO_YELLOW("Migrating blockchain from DB version 5 to 6 - this may take a while:"); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 5 to 6 - this may take a while:")); mdb_txn_safe txn(false); { @@ -6042,8 +6042,8 @@ void BlockchainLMDB::migrate_5_6() void BlockchainLMDB::migrate_6_7() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); - MGINFO_YELLOW("Migrating blockchain from DB version 6 to 7 - this may take a while:"); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 6 to 7 - this may take a while:")); std::vector checkpoints; checkpoints.reserve(1024); @@ -6133,7 +6133,7 @@ uint64_t constexpr SERVICE_NODE_BLOB_SHORT_TERM_KEY = 1; uint64_t constexpr SERVICE_NODE_BLOB_LONG_TERM_KEY = 2; void BlockchainLMDB::set_service_node_data(const std::string& data, bool long_term) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -6150,7 +6150,7 @@ void BlockchainLMDB::set_service_node_data(const std::string& data, bool long_te bool BlockchainLMDB::get_service_node_data(std::string& data, bool long_term) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6180,7 +6180,7 @@ bool BlockchainLMDB::get_service_node_data(std::string& data, bool long_term) co void BlockchainLMDB::clear_service_node_data() { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -6290,7 +6290,7 @@ static_assert(sizeof(service_node_proof_serialized) == 72, "service node seriali bool BlockchainLMDB::get_service_node_proof(const crypto::public_key &pubkey, service_nodes::proof_info &proof) const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6314,7 +6314,7 @@ bool BlockchainLMDB::get_service_node_proof(const crypto::public_key &pubkey, se void BlockchainLMDB::set_service_node_proof(const crypto::public_key &pubkey, const service_nodes::proof_info &proof) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); service_node_proof_serialized data{proof}; @@ -6331,7 +6331,7 @@ void BlockchainLMDB::set_service_node_proof(const crypto::public_key &pubkey, co std::unordered_map BlockchainLMDB::get_all_service_node_proofs() const { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6351,7 +6351,7 @@ std::unordered_map BlockchainLMDB bool BlockchainLMDB::remove_service_node_proof(const crypto::public_key& pubkey) { - LOG_PRINT_L3("BlockchainLMDB::" << __func__); + oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(service_node_proofs) diff --git a/src/blockchain_db/locked_txn.h b/src/blockchain_db/locked_txn.h index d1c4dd782..a2eb49c7d 100644 --- a/src/blockchain_db/locked_txn.h +++ b/src/blockchain_db/locked_txn.h @@ -46,8 +46,8 @@ namespace cryptonote LockedTXN(LockedTXN &&o) : m_db{o.m_db}, m_batch{o.m_batch} { o.m_batch = false; } LockedTXN &operator=(LockedTXN &&) = delete; - void commit() { try { if (m_batch) { m_db.batch_stop(); m_batch = false; } } catch (const std::exception &e) { MWARNING("LockedTXN::commit filtering exception: " << e.what()); } } - void abort() { try { if (m_batch) { m_db.batch_abort(); m_batch = false; } } catch (const std::exception &e) { MWARNING("LockedTXN::abort filtering exception: " << e.what()); } } + void commit() { try { if (m_batch) { m_db.batch_stop(); m_batch = false; } } catch (const std::exception &e) { oxen::log::warning(globallogcat, "LockedTXN::commit filtering exception: {}", e.what()); } } + void abort() { try { if (m_batch) { m_db.batch_abort(); m_batch = false; } } catch (const std::exception &e) { oxen::log::warning(globallogcat, "LockedTXN::abort filtering exception: {}", e.what()); } } ~LockedTXN() { this->abort(); } private: BlockchainDB &m_db; diff --git a/src/blockchain_db/sqlite/db_sqlite.cpp b/src/blockchain_db/sqlite/db_sqlite.cpp index ae15dc0f3..242309893 100644 --- a/src/blockchain_db/sqlite/db_sqlite.cpp +++ b/src/blockchain_db/sqlite/db_sqlite.cpp @@ -40,13 +40,12 @@ #include "common/string_util.h" #include "cryptonote_basic/hardfork.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "blockchain.db.sqlite" - namespace cryptonote { + + static auto logcat = oxen::log::Cat("blockchain.db.sqlite"); BlockchainSQLite::BlockchainSQLite(cryptonote::network_type nettype, fs::path db_path): db::Database(db_path, ""), m_nettype(nettype), filename {db_path.u8string()} { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); height = 0; if (!db.tableExists("batched_payments_accrued") || !db.tableExists("batched_payments_raw") || !db.tableExists("batch_db_info")) { @@ -59,7 +58,7 @@ namespace cryptonote { } void BlockchainSQLite::create_schema() { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto& netconf = cryptonote::get_config(m_nettype); @@ -118,7 +117,7 @@ namespace cryptonote { )", netconf.BATCHING_INTERVAL)); - MDEBUG("Database setup complete"); + oxen::log::debug(logcat, "Database setup complete"); } void BlockchainSQLite::upgrade_schema() { @@ -131,7 +130,7 @@ namespace cryptonote { } if (!have_offset) { - MINFO("Adding payout_offset to batching db"); + oxen::log::info(logcat, "Adding payout_offset to batching db"); auto& netconf = get_config(m_nettype); SQLite::Transaction transaction{ db, @@ -166,7 +165,7 @@ namespace cryptonote { if (count != 0) { constexpr auto error = "Batching db update to add offsets failed: not all addresses were converted"; - MFATAL(error); + oxen::log::error(logcat, error); throw std::runtime_error{error}; } @@ -175,7 +174,7 @@ namespace cryptonote { } void BlockchainSQLite::reset_database() { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); db.exec(R"( DROP TABLE IF EXISTS batched_payments_accrued; @@ -189,11 +188,11 @@ namespace cryptonote { create_schema(); - MDEBUG("Database reset complete"); + oxen::log::debug(logcat, "Database reset complete"); } void BlockchainSQLite::update_height(uint64_t new_height) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " Called with new height: " << new_height); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with new height: {}", __func__, new_height); height = new_height; prepared_exec( "UPDATE batch_db_info SET height = ?", @@ -201,12 +200,12 @@ namespace cryptonote { } void BlockchainSQLite::increment_height() { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " Called with height: " << height + 1); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height + 1); update_height(height + 1); } void BlockchainSQLite::decrement_height() { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " Called with height: " << height - 1); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height - 1); update_height(height - 1); } @@ -221,7 +220,7 @@ namespace cryptonote { bool BlockchainSQLite::add_sn_rewards(const std::vector& payments) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto insert_payment = prepared_st( "INSERT INTO batched_payments_accrued (address, payout_offset, amount) VALUES (?, ?, ?)" " ON CONFLICT (address) DO UPDATE SET amount = amount + excluded.amount"); @@ -232,8 +231,7 @@ namespace cryptonote { auto offset = static_cast(payment.address_info.address.modulus(netconf.BATCHING_INTERVAL)); auto amt = static_cast(payment.amount); const auto& address_str = get_address_str(payment.address_info.address); - MTRACE(fmt::format("Adding record for SN reward contributor {} to database with amount {}", - address_str, amt)); + oxen::log::trace(logcat, "Adding record for SN reward contributor {} to database with amount {}", address_str, amt); db::exec_query(insert_payment, address_str, offset, amt); insert_payment->reset(); } @@ -242,7 +240,7 @@ namespace cryptonote { } bool BlockchainSQLite::subtract_sn_rewards(const std::vector& payments) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto update_payment = prepared_st( "UPDATE batched_payments_accrued SET amount = (amount - ?) WHERE address = ?"); @@ -250,7 +248,7 @@ namespace cryptonote { const auto& address_str = get_address_str(payment.address_info.address); auto result = db::exec_query(update_payment, static_cast(payment.amount), address_str); if (!result) { - MERROR("tried to subtract payment from an address that doesn't exist: " << address_str); + oxen::log::error(logcat, "tried to subtract payment from an address that doesn't exist: {}", address_str); return false; } update_payment->reset(); @@ -260,7 +258,7 @@ namespace cryptonote { } std::vector BlockchainSQLite::get_sn_payments(uint64_t block_height) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); // <= here because we might have crap in the db that we don't clear until we actually add the HF // block later on. (This is a pretty slim edge case that happened on devnet and is probably @@ -289,7 +287,7 @@ namespace cryptonote { uint64_t BlockchainSQLite::get_accrued_earnings(const std::string& address) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto earnings = prepared_maybe_get( "SELECT amount FROM batched_payments_accrued WHERE address = ?", @@ -298,7 +296,7 @@ namespace cryptonote { } std::pair, std::vector> BlockchainSQLite::get_all_accrued_earnings() { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); std::pair, std::vector> result; auto& [addresses, amounts] = result; @@ -316,7 +314,7 @@ namespace cryptonote { } void BlockchainSQLite::calculate_rewards(hf hf_version, uint64_t distribution_amount, const service_nodes::service_node_info& sn_info, std::vector& payments) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); // Find out how much is due for the operator: fee_portions/PORTIONS * reward assert(sn_info.portions_for_operator <= old::STAKING_PORTIONS); @@ -423,7 +421,7 @@ namespace cryptonote { bool BlockchainSQLite::add_block(const cryptonote::block& block, const service_nodes::service_node_list::state_t& service_nodes_state) { auto block_height = get_block_height(block); - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " called on height: " << block_height); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); auto hf_version = block.major_version; if (hf_version < hf::hf19_reward_batching) { @@ -433,13 +431,13 @@ namespace cryptonote { auto fork_height = cryptonote::get_hard_fork_heights(m_nettype, hf::hf19_reward_batching); if (block_height == fork_height.first.value_or(0)) { - MDEBUG("Batching of Service Node Rewards Begins"); + oxen::log::debug(logcat, "Batching of Service Node Rewards Begins"); reset_database(); update_height(block_height - 1); } if (block_height != height + 1) { - MERROR(fmt::format("Block height ({}) out of sync with batching database ({})", block_height, height)); + oxen::log::error(logcat, "Block height ({}) out of sync with batching database ({})", block_height, height); return false; } @@ -472,7 +470,7 @@ namespace cryptonote { transaction.commit(); } catch (std::exception& e) { - MFATAL("Error adding reward payments: " << e.what()); + oxen::log::error(logcat, "Error adding reward payments: {}", e.what()); return false; } return true; @@ -482,13 +480,13 @@ namespace cryptonote { const service_nodes::service_node_list::state_t& service_nodes_state) { auto block_height = get_block_height(block); - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " called on height: " << block_height); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); if (height < block_height) { - MDEBUG("Block above batching DB height skipping pop"); + oxen::log::debug(logcat, "Block above batching DB height skipping pop"); return true; } if (block_height != height) { - MERROR("Block height out of sync with batching database"); + oxen::log::error(logcat, "Block height out of sync with batching database"); return false; } @@ -514,7 +512,7 @@ namespace cryptonote { decrement_height(); transaction.commit(); } catch (std::exception& e) { - MFATAL("Error subtracting reward payments: " << e.what()); + oxen::log::error(logcat, "Error subtracting reward payments: {}", e.what()); return false; } return true; @@ -524,10 +522,10 @@ namespace cryptonote { const std::vector>& miner_tx_vouts, const std::vector& calculated_payments_from_batching_db, uint64_t block_height) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); if (miner_tx_vouts.size() != calculated_payments_from_batching_db.size()) { - MERROR(fmt::format("Length of batch payments ({}) does not match block vouts ({})", calculated_payments_from_batching_db.size(), miner_tx_vouts.size())); + oxen::log::error(logcat, "Length of batch payments ({}) does not match block vouts ({})", calculated_payments_from_batching_db.size(), miner_tx_vouts.size()); return false; } @@ -546,23 +544,23 @@ namespace cryptonote { uint64_t amount = amt * BATCH_REWARD_FACTOR; const auto& from_db = calculated_payments_from_batching_db[vout_index]; if (amount != from_db.amount) { - MERROR(fmt::format("Batched payout amount incorrect. Should be {}, not {}", from_db.amount, amount)); + oxen::log::error(logcat, "Batched payout amount incorrect. Should be {}, not {}", from_db.amount, amount); return false; } crypto::public_key out_eph_public_key{}; if (!cryptonote::get_deterministic_output_key(from_db.address_info.address, deterministic_keypair, vout_index, out_eph_public_key)) { - MERROR("Failed to generate output one-time public key"); + oxen::log::error(logcat, "Failed to generate output one-time public key"); return false; } if (tools::view_guts(pubkey) != tools::view_guts(out_eph_public_key)) { - MERROR("Output ephemeral public key does not match"); + oxen::log::error(logcat, "Output ephemeral public key does not match"); return false; } total_oxen_payout_in_vouts += amount; finalised_payments.emplace_back(from_db.address_info, amount); } if (total_oxen_payout_in_vouts != total_oxen_payout_in_our_db) { - MERROR(fmt::format("Total batched payout amount incorrect. Should be {}, not {}", total_oxen_payout_in_our_db, total_oxen_payout_in_vouts)); + oxen::log::error(logcat, "Total batched payout amount incorrect. Should be {}, not {}", total_oxen_payout_in_our_db, total_oxen_payout_in_vouts); return false; } @@ -570,7 +568,7 @@ namespace cryptonote { } bool BlockchainSQLite::save_payments(uint64_t block_height, const std::vector& paid_amounts) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto select_sum = prepared_st( "SELECT amount from batched_payments_accrued WHERE address = ?"); @@ -588,8 +586,7 @@ namespace cryptonote { auto amount = static_cast(*maybe_amount) / BATCH_REWARD_FACTOR * BATCH_REWARD_FACTOR; if (amount != payment.amount) { - MERROR(fmt::format("Invalid amounts passed in to save payments for address {}: received {}, expected {} (truncated from {})", - address_str, payment.amount, amount, *maybe_amount)); + oxen::log::error(logcat, "Invalid amounts passed in to save payments for address {}: received {}, expected {} (truncated from {})", address_str, payment.amount, amount, *maybe_amount); return false; } @@ -598,8 +595,7 @@ namespace cryptonote { } else { // This shouldn't occur: we validate payout addresses much earlier in the block validation. - MERROR(fmt::format("Internal error: Invalid amounts passed in to save payments for address {}: that address has no accrued rewards", - address_str)); + oxen::log::error(logcat, "Internal error: Invalid amounts passed in to save payments for address {}: that address has no accrued rewards", address_str); return false; } @@ -609,7 +605,7 @@ namespace cryptonote { } std::vector BlockchainSQLite::get_block_payments(uint64_t block_height) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " Called with height: " << block_height); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); std::vector payments_at_height; auto paid = prepared_results( @@ -626,7 +622,7 @@ namespace cryptonote { } bool BlockchainSQLite::delete_block_payments(uint64_t block_height) { - LOG_PRINT_L3("BlockchainDB_SQLITE::" << __func__ << " Called with height: " << block_height); + oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); prepared_exec( "DELETE FROM batched_payments_paid WHERE height_paid >= ?", static_cast(block_height)); diff --git a/src/blockchain_db/sqlite/db_sqlite.h b/src/blockchain_db/sqlite/db_sqlite.h index 142ea75c3..08d3168ba 100644 --- a/src/blockchain_db/sqlite/db_sqlite.h +++ b/src/blockchain_db/sqlite/db_sqlite.h @@ -30,7 +30,6 @@ #include #include -#include "epee/misc_log_ex.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "cryptonote_core/cryptonote_tx_utils.h" #include "sqlitedb/database.hpp" diff --git a/src/blockchain_utilities/CMakeLists.txt b/src/blockchain_utilities/CMakeLists.txt index f5602822b..36c8c25cb 100644 --- a/src/blockchain_utilities/CMakeLists.txt +++ b/src/blockchain_utilities/CMakeLists.txt @@ -35,6 +35,7 @@ target_link_libraries(blockchain_tools_common_libs INTERFACE filesystem Boost::program_options SQLiteCpp + logging extra) diff --git a/src/blockchain_utilities/blockchain_ancestry.cpp b/src/blockchain_utilities/blockchain_ancestry.cpp index 2bcc22c3a..6d0df3702 100644 --- a/src/blockchain_utilities/blockchain_ancestry.cpp +++ b/src/blockchain_utilities/blockchain_ancestry.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include "common/unordered_containers_boost_serialization.h" #include "common/command_line.h" #include "common/varint.h" @@ -46,9 +47,9 @@ #include "blockchain_db/blockchain_db.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; using namespace cryptonote; @@ -102,7 +103,7 @@ struct tx_data_t vin.push_back(std::make_pair(txin->amount, cryptonote::relative_output_offsets_to_absolute(txin->key_offsets))); else { - LOG_PRINT_L0("Bad vin type in txid " << get_transaction_hash(tx)); + oxen::log::warning(logcat, "Bad vin type in txid {}", get_transaction_hash(tx)); throw std::runtime_error("Bad vin type"); } } @@ -116,7 +117,7 @@ struct tx_data_t } else { - LOG_PRINT_L0("Bad vout type in txid " << get_transaction_hash(tx)); + oxen::log::warning(logcat, "Bad vout type in txid {}", get_transaction_hash(tx)); throw std::runtime_error("Bad vout type"); } } @@ -215,7 +216,7 @@ static std::unordered_set get_ancestry(const std::unordered_map>::const_iterator i = ancestry.find(txid); if (i == ancestry.end()) { - //MERROR("txid ancestry not found: " << txid); + //oxen::log::error(logcat, "txid ancestry not found: {}", txid); //throw std::runtime_error("txid ancestry not found"); return std::unordered_set(); } @@ -234,7 +235,7 @@ static bool get_block_from_height(ancestry_state_t &state, BlockchainDB *db, uin std::string bd = db->get_block_blob_from_height(height); if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return false; } if (opt_cache_blocks) @@ -259,13 +260,13 @@ static bool get_transaction(ancestry_state_t &state, BlockchainDB *db, const cry std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - LOG_PRINT_L0("Failed to get txid " << txid << " from db"); + oxen::log::warning(logcat, "Failed to get txid {} from db", txid); return false; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - LOG_PRINT_L0("Bad tx: " << txid); + oxen::log::warning(logcat, "Bad tx: {}", txid); return false; } tx_data = ::tx_data_t(tx); @@ -304,7 +305,7 @@ static bool get_output_txid(ancestry_state_t &state, BlockchainDB *db, uint64_t } else { - LOG_PRINT_L0("Bad vout type in txid " << cryptonote::get_transaction_hash(b.miner_tx)); + oxen::log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); return false; } } @@ -334,8 +335,6 @@ int main(int argc, char* argv[]) epee::string_tools::set_module_name_and_folder(argv[0]); - uint32_t log_level = 0; - tools::on_startup(); auto opt_size = command_line::boost_option_sizes(); @@ -388,14 +387,17 @@ int main(int argc, char* argv[]) std::cout << desc_options << std::endl; return 1; } - - mlog_configure(mlog_get_default_log_path("oxen-blockchain-ancestry.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-ancestry.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); @@ -435,19 +437,19 @@ int main(int argc, char* argv[]) } } - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - LOG_PRINT_L0("database: LMDB"); + oxen::log::warning(logcat, "database: LMDB"); fs::path filename = fs::u8path(opt_data_dir) / db->get_db_name(); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -455,20 +457,20 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); std::vector start_txids; ancestry_state_t state; fs::path state_file_path = fs::u8path(opt_data_dir) / "ancestry-state.bin"; - LOG_PRINT_L0("Loading state data from " << state_file_path); + oxen::log::warning(logcat, "Loading state data from {}", state_file_path); fs::ifstream state_data_in; state_data_in.open(state_file_path, std::ios_base::binary | std::ios_base::in); if (!state_data_in.fail()) @@ -480,7 +482,7 @@ int main(int argc, char* argv[]) } catch (const std::exception &e) { - MERROR("Failed to load state data from " << state_file_path << ", restarting from scratch"); + oxen::log::error(logcat, "Failed to load state data from {}, restarting from scratch", state_file_path); state = ancestry_state_t(); } state_data_in.close(); @@ -494,7 +496,7 @@ int main(int argc, char* argv[]) const uint64_t db_height = db->height(); if (opt_refresh) { - MINFO("Starting from height " << state.height); + oxen::log::info(logcat, "Starting from height {}", state.height); state.block_cache.reserve(db_height); for (uint64_t h = state.height; h < db_height; ++h) { @@ -504,7 +506,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return 1; } if (opt_cache_blocks) @@ -535,13 +537,13 @@ int main(int argc, char* argv[]) std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - LOG_PRINT_L0("Failed to get txid " << txid << " from db"); + oxen::log::warning(logcat, "Failed to get txid {} from db", txid); return 1; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - LOG_PRINT_L0("Bad tx: " << txid); + oxen::log::warning(logcat, "Bad tx: {}", txid); return 1; } tx_data = ::tx_data_t(tx); @@ -566,7 +568,7 @@ int main(int argc, char* argv[]) crypto::hash output_txid; if (!get_output_txid(state, db, amount, offset, output_txid)) { - LOG_PRINT_L0("Output originating transaction not found"); + oxen::log::warning(logcat, "Output originating transaction not found"); return 1; } add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid)); @@ -575,19 +577,19 @@ int main(int argc, char* argv[]) } const size_t ancestry_size = get_ancestry(state.ancestry, txid).size(); block_ancestry_size += ancestry_size; - MINFO(txid << ": " << ancestry_size); + oxen::log::info(logcat, "{}: {}", txid, ancestry_size); } if (!txids.empty()) { std::string stats_msg; - MINFO("Height " << h << ": " << (block_ancestry_size / txids.size()) << " average over " << txids.size() << stats_msg); + oxen::log::info(logcat, "Height {}: {} average over {}{}", h, (block_ancestry_size / txids.size()), txids.size(), stats_msg); } state.height = h; if (stop_requested) break; } - LOG_PRINT_L0("Saving state data to " << state_file_path); + oxen::log::warning(logcat, "Saving state data to {}", state_file_path); std::ofstream state_data_out; state_data_out.open(state_file_path, std::ios_base::binary | std::ios_base::out | std::ios::trunc); if (!state_data_out.fail()) @@ -599,7 +601,7 @@ int main(int argc, char* argv[]) } catch (const std::exception &e) { - MERROR("Failed to save state data to " << state_file_path); + oxen::log::error(logcat, "Failed to save state data to {}", state_file_path); } state_data_out.close(); } @@ -608,8 +610,8 @@ int main(int argc, char* argv[]) { if (state.height < db_height) { - MWARNING("The state file is only built up to height " << state.height << ", but the blockchain reached height " << db_height); - MWARNING("You may want to run with --refresh if you want to get ancestry for newer data"); + oxen::log::warning(logcat, "The state file is only built up to height {}, but the blockchain reached height {}", state.height, db_height); + oxen::log::warning(logcat, "You may want to run with --refresh if you want to get ancestry for newer data"); } } @@ -622,7 +624,7 @@ int main(int argc, char* argv[]) crypto::hash txid; if (!get_output_txid(state, db, output_amount, output_offset, txid)) { - LOG_PRINT_L0("Output not found in db"); + oxen::log::warning(logcat, "Output not found in db"); return 1; } start_txids.push_back(txid); @@ -633,7 +635,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return 1; } for (const crypto::hash &txid: b.tx_hashes) @@ -642,13 +644,13 @@ int main(int argc, char* argv[]) if (start_txids.empty()) { - LOG_PRINT_L0("No transaction(s) to check"); + oxen::log::warning(logcat, "No transaction(s) to check"); return 1; } for (const crypto::hash &start_txid: start_txids) { - LOG_PRINT_L0("Checking ancestry for txid " << start_txid); + oxen::log::warning(logcat, "Checking ancestry for txid {}", start_txid); std::unordered_map ancestry; @@ -684,22 +686,22 @@ int main(int argc, char* argv[]) crypto::hash output_txid; if (!get_output_txid(state, db, amount, offset, output_txid)) { - LOG_PRINT_L0("Output originating transaction not found"); + oxen::log::warning(logcat, "Output originating transaction not found"); return 1; } add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid)); txids.push_back(output_txid); - MDEBUG("adding txid: " << output_txid); + oxen::log::debug(logcat, "adding txid: {}", output_txid); } } } } - MINFO("Ancestry for " << start_txid << ": " << get_deduplicated_ancestry(ancestry) << " / " << get_full_ancestry(ancestry)); + oxen::log::info(logcat, "Ancestry for {}: {} / {}", start_txid, get_deduplicated_ancestry(ancestry), get_full_ancestry(ancestry)); for (const auto &i: ancestry) { - MINFO(cryptonote::print_money(i.first.amount) << "/" << i.first.offset << ": " << i.second); + oxen::log::info(logcat, "{}/{}: {}", cryptonote::print_money(i.first.amount), i.first.offset, i.second); } } @@ -707,10 +709,7 @@ done: core_storage->deinit(); if (opt_show_cache_stats) - MINFO("cache: txes " << std::to_string(cached_txes*100./total_txes) - << "%, blocks " << std::to_string(cached_blocks*100./total_blocks) - << "%, outputs " << std::to_string(cached_outputs*100./total_outputs) - << "%"); + oxen::log::info(logcat, "cache: txes {}%, blocks {}%, outputs {}%", std::to_string(cached_txes*100./total_txes), std::to_string(cached_blocks*100./total_blocks), std::to_string(cached_outputs*100./total_outputs)); return 0; diff --git a/src/blockchain_utilities/blockchain_blackball.cpp b/src/blockchain_utilities/blockchain_blackball.cpp index 9c7922b9c..17fb6be2e 100644 --- a/src/blockchain_utilities/blockchain_blackball.cpp +++ b/src/blockchain_utilities/blockchain_blackball.cpp @@ -46,9 +46,9 @@ #include "wallet/ringdb.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; using namespace cryptonote; @@ -90,7 +90,7 @@ static bool parse_db_sync_mode(std::string db_sync_mode) auto options = tools::split_any(db_sync_mode, " :", true); for(const auto &option : options) - MDEBUG("option: " << option); + oxen::log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -206,14 +206,14 @@ static int resize_env(const char *db_path) auto si = fs::space(fs::u8path(db_path)); if(si.available < needed) { - MERROR("!! WARNING: Insufficient free space to extend database !!: " << (si.available / 1000000) << " MB available"); + oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); return ENOSPC; } } catch(...) { // print something but proceed. - MWARNING("Unable to query free disk space."); + oxen::log::warning(logcat, "Unable to query free disk space."); } mapsize += needed; @@ -227,11 +227,11 @@ static void init(fs::path cache_filename) bool tx_active = false; int dbr; - MINFO("Creating spent output cache in " << cache_filename); + oxen::log::info(logcat, "Creating spent output cache in {}", cache_filename); std::error_code ec; if (fs::create_directories(cache_filename, ec); ec) - MWARNING("Failed to create output cache directory " << cache_filename << ": " << ec.message()); + oxen::log::warning(logcat, "Failed to create output cache directory {}: {}", cache_filename, ec.message()); int flags = 0; if (db_flags & DBF_FAST) @@ -392,7 +392,7 @@ static bool for_all_transactions(const fs::path& filename, uint64_t& start_idx, std::string_view bd{static_cast(v.mv_data), v.mv_size}; serialization::parse_binary(bd, tx); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse transaction from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse transaction from blob: {}", e.what()); return false; } @@ -607,7 +607,7 @@ static std::vector canonicalize(const std::vector &v) } if (c.size() < v.size()) { - MINFO("Ring has duplicate member(s): " << tools::join(" ", v)); + oxen::log::info(logcat, "Ring has duplicate member(s): {}", tools::join(" ", v)); } return c; } @@ -955,7 +955,7 @@ static void open_db(const fs::path& filename, MDB_env** env, MDB_txn** txn, MDB_ { std::error_code ec; if (fs::create_directories(filename, ec); ec) - MWARNING("Failed to create lmdb path " << filename << ": " << ec.message()); + oxen::log::warning(logcat, "Failed to create lmdb path {}: {}", filename, ec.message()); int flags = MDB_RDONLY; if (db_flags & DBF_FAST) @@ -967,7 +967,7 @@ static void open_db(const fs::path& filename, MDB_env** env, MDB_txn** txn, MDB_ CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr))); dbr = mdb_env_set_maxdbs(*env, 1); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set max env dbs: " + std::string(mdb_strerror(dbr))); - MINFO("Opening oxen blockchain at " << filename); + oxen::log::info(logcat, "Opening oxen blockchain at {}", filename); dbr = mdb_env_open(*env, filename.string().c_str(), flags, 0664); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open rings database file '" + filename.u8string() + "': " + std::string(mdb_strerror(dbr))); @@ -1065,7 +1065,7 @@ static std::vector> load_outputs(const fs::path& f if (!f) { - MERROR("Failed to load outputs from " << filename << ": " << strerror(errno)); + oxen::log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); return {}; } while (1) @@ -1073,7 +1073,7 @@ static std::vector> load_outputs(const fs::path& f char s[256]; if (!fgets(s, sizeof(s), f)) { - MERROR("Error reading from " << filename << ": " << strerror(errno)); + oxen::log::error(logcat, "Error reading from {}: {}", filename, strerror(errno)); break; } if (feof(f)) @@ -1091,7 +1091,7 @@ static std::vector> load_outputs(const fs::path& f } if (amount == std::numeric_limits::max()) { - MERROR("Bad format in " << filename); + oxen::log::error(logcat, "Bad format in {}", filename); continue; } if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits::max() - offset) @@ -1105,7 +1105,7 @@ static std::vector> load_outputs(const fs::path& f } else { - MERROR("Bad format in " << filename); + oxen::log::error(logcat, "Bad format in {}", filename); continue; } } @@ -1124,7 +1124,7 @@ static bool export_spent_outputs(MDB_cursor* cur, const fs::path& filename) if (!f) { - MERROR("Failed to open " << filename << ": " << strerror(errno)); + oxen::log::error(logcat, "Failed to open {}: {}", filename, strerror(errno)); return false; } @@ -1141,7 +1141,7 @@ static bool export_spent_outputs(MDB_cursor* cur, const fs::path& filename) if (dbr) { fclose(f); - MERROR("Failed to enumerate spent outputs: " << mdb_strerror(dbr)); + oxen::log::error(logcat, "Failed to enumerate spent outputs: {}", mdb_strerror(dbr)); return false; } const uint64_t amount = *(const uint64_t*)k.mv_data; @@ -1178,9 +1178,6 @@ int main(int argc, char* argv[]) TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); - - uint32_t log_level = 0; - tools::on_startup(); auto opt_size = command_line::boost_option_sizes(); @@ -1243,13 +1240,17 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-mark-spent-outputs.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-mark-spent-outputs.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); fs::path output_file_path = fs::u8path(command_line::get_arg(vm, arg_blackball_db_dir)); bool opt_rct_only = command_line::get_arg(vm, arg_rct_only); @@ -1265,7 +1266,7 @@ int main(int argc, char* argv[]) std::string db_sync_mode = command_line::get_arg(vm, arg_db_sync_mode); if (!parse_db_sync_mode(db_sync_mode)) { - MERROR("Invalid db sync mode: " << db_sync_mode); + oxen::log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); return 1; } @@ -1274,7 +1275,7 @@ int main(int argc, char* argv[]) inputs.push_back(fs::u8path(in)); if (inputs.empty()) { - LOG_PRINT_L0("No inputs given"); + oxen::log::warning(logcat, "No inputs given"); return 1; } @@ -1288,7 +1289,7 @@ int main(int argc, char* argv[]) fs::path cache_dir = output_file_path / "spent-outputs-cache"; init(cache_dir); - LOG_PRINT_L0("Scanning for spent outputs..."); + oxen::log::warning(logcat, "Scanning for spent outputs..."); size_t done = 0; @@ -1317,7 +1318,7 @@ int main(int argc, char* argv[]) { if (!start_blackballed_outputs) { - MINFO("Spent outputs database is empty. Either you haven't run the analysis mode yet, or there is really no output marked as spent."); + oxen::log::info(logcat, "Spent outputs database is empty. Either you haven't run the analysis mode yet, or there is really no output marked as spent."); goto skip_secondary_passes; } MDB_txn *txn; @@ -1342,7 +1343,7 @@ int main(int argc, char* argv[]) { uint64_t window_front = (height / STAT_WINDOW - 1) * STAT_WINDOW; uint64_t window_back = window_front + STAT_WINDOW - 1; - LOG_PRINT_L0(window_front << "-" << window_back << ": " << (100.0f * outs_spent / outs_total) << "% ( " << outs_spent << " / " << outs_total << " )"); + oxen::log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); outs_total = outs_spent = 0; } } @@ -1359,11 +1360,11 @@ int main(int argc, char* argv[]) { uint64_t window_front = (height / STAT_WINDOW) * STAT_WINDOW; uint64_t window_back = height; - LOG_PRINT_L0(window_front << "-" << window_back << ": " << (100.0f * outs_spent / outs_total) << "% ( " << outs_spent << " / " << outs_total << " )"); + oxen::log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); } if (stop_requested) { - MINFO("Stopping scan..."); + oxen::log::info(logcat, "Stopping scan..."); return false; } return true; @@ -1376,7 +1377,7 @@ int main(int argc, char* argv[]) if (!extra_spent_outputs.empty()) { - MINFO("Adding " << extra_spent_outputs.size() << " extra spent outputs"); + oxen::log::info(logcat, "Adding {} extra spent outputs", extra_spent_outputs.size()); MDB_txn *txn; int dbr = mdb_txn_begin(env, NULL, 0, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); @@ -1411,9 +1412,9 @@ int main(int argc, char* argv[]) if (n > 0 && start_idx == 0) { start_idx = find_first_diverging_transaction(inputs[0], inputs[n]); - LOG_PRINT_L0("First diverging transaction at " << start_idx); + oxen::log::warning(logcat, "First diverging transaction at {}", start_idx); } - LOG_PRINT_L0("Reading blockchain from " << inputs[n] << " from " << start_idx); + oxen::log::warning(logcat, "Reading blockchain from {} from {}", inputs[n], start_idx); MDB_txn *txn; int dbr = mdb_txn_begin(env, NULL, 0, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); @@ -1450,7 +1451,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[0]); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in a 1-ring"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in a 1-ring", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1464,7 +1465,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[o]); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in " << new_ring.size() << " identical " << new_ring.size() << "-rings"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in {} identical {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1479,7 +1480,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, o); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to as many outputs of that amount being spent as exist so far"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to as many outputs of that amount being spent as exist so far", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1494,7 +1495,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[o]); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in " << new_ring.size() << " subsets of " << new_ring.size() << "-rings"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in {} subsets of {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1504,12 +1505,11 @@ int main(int argc, char* argv[]) } else if (n > 0 && get_relative_ring(txn, txin.k_image, relative_ring)) { - MDEBUG("Key image " << txin.k_image << " already seen: " - "rings " << tools::join(" ", relative_ring) << ", " << tools::join(" ", txin.key_offsets)); + oxen::log::debug(logcat, "Key image {} already seen: rings {}, {}", txin.k_image, tools::join(" ", relative_ring), tools::join(" ", txin.key_offsets)); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; if (relative_ring != txin.key_offsets) { - MDEBUG("Rings are different"); + oxen::log::debug(logcat, "Rings are different"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; const std::vector r0 = cryptonote::relative_output_offsets_to_absolute(relative_ring); const std::vector r1 = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets); @@ -1521,7 +1521,7 @@ int main(int argc, char* argv[]) } if (common.empty()) { - MERROR("Rings for the same key image are disjoint"); + oxen::log::error(logcat, "Rings for the same key image are disjoint"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } else if (common.size() == 1) @@ -1529,7 +1529,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, common[0]); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in rings with a single common element"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in rings with a single common element", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1538,7 +1538,7 @@ int main(int argc, char* argv[]) } else { - MDEBUG("The intersection has more than one element, it's still ok"); + oxen::log::debug(logcat, "The intersection has more than one element, it's still ok"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; for (const auto &out: r0) if (std::find(common.begin(), common.end(), out) != common.end()) @@ -1594,7 +1594,7 @@ int main(int argc, char* argv[]) if (stop_requested) { - MINFO("Stopping scan..."); + oxen::log::info(logcat, "Stopping scan..."); return false; } return true; @@ -1602,7 +1602,7 @@ int main(int argc, char* argv[]) mdb_cursor_close(cur); dbr = mdb_txn_commit(txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr))); - LOG_PRINT_L0("blockchain from " << inputs[n] << " processed till tx idx " << start_idx); + oxen::log::warning(logcat, "blockchain from {} processed till tx idx {}", inputs[n], start_idx); if (stop_requested) break; } @@ -1621,7 +1621,7 @@ int main(int argc, char* argv[]) while (!work_spent.empty()) { - LOG_PRINT_L0("Secondary pass on " << work_spent.size() << " spent outputs"); + oxen::log::warning(logcat, "Secondary pass on {} spent outputs", work_spent.size()); int dbr = resize_env(cache_dir.string().c_str()); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to resize LMDB database: " + std::string(mdb_strerror(dbr))); @@ -1659,8 +1659,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(od.amount, last_unknown); if (opt_verbose) { - MINFO("Marking output " << output.first << "/" << output.second << " as spent, due to being used in a " << - absolute.size() << "-ring where all other outputs are known to be spent"); + oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in a {}-ring where all other outputs are known to be spent", output.first, output.second, absolute.size()); } blackballs.push_back(output); if (add_spent_output(cur, output_data(od.amount, last_unknown))) @@ -1671,7 +1670,7 @@ int main(int argc, char* argv[]) if (stop_requested) { - MINFO("Stopping secondary passes. Secondary passes are not incremental, they will re-run fully."); + oxen::log::info(logcat, "Stopping secondary passes. Secondary passes are not incremental, they will re-run fully."); return 0; } } @@ -1687,15 +1686,15 @@ int main(int argc, char* argv[]) skip_secondary_passes: uint64_t diff = get_num_spent_outputs() - start_blackballed_outputs; - LOG_PRINT_L0(std::to_string(diff) << " new outputs marked as spent, " << get_num_spent_outputs() << " total outputs marked as spent"); + oxen::log::warning(logcat, "{} new outputs marked as spent, {} total outputs marked as spent", std::to_string(diff), get_num_spent_outputs()); MDB_txn *txn; dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); uint64_t pre_rct = 0, rct = 0; get_num_outputs(txn0, cur0, dbi0, pre_rct, rct); - MINFO("Total pre-rct outputs: " << pre_rct); - MINFO("Total rct outputs: " << rct); + oxen::log::info(logcat, "Total pre-rct outputs: {}", pre_rct); + oxen::log::info(logcat, "Total rct outputs: {}", rct); static const struct { const char *key; uint64_t base; } stat_keys[] = { { "pre-rct-ring-size-1", pre_rct }, { "rct-ring-size-1", rct }, { "pre-rct-duplicate-rings", pre_rct }, { "rct-duplicate-rings", rct }, @@ -1711,7 +1710,7 @@ skip_secondary_passes: if (!get_stat(txn, key.key, data)) data = 0; float percent = key.base ? 100.0f * data / key.base : 0.0f; - MINFO(key.key << ": " << data << " (" << percent << "%)"); + oxen::log::info(logcat, "{}: {} ({}%)", key.key, data, percent); } mdb_txn_abort(txn); @@ -1728,7 +1727,7 @@ skip_secondary_passes: mdb_txn_abort(txn); } - LOG_PRINT_L0("Blockchain spent output data exported OK"); + oxen::log::warning(logcat, "Blockchain spent output data exported OK"); close_db(env0, txn0, cur0, dbi0); close(); return 0; diff --git a/src/blockchain_utilities/blockchain_depth.cpp b/src/blockchain_utilities/blockchain_depth.cpp index c24c6929d..7510b154e 100644 --- a/src/blockchain_utilities/blockchain_depth.cpp +++ b/src/blockchain_utilities/blockchain_depth.cpp @@ -34,9 +34,9 @@ #include "blockchain_db/blockchain_db.h" #include "cryptonote_core/uptime_proof.h" #include "version.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; using namespace cryptonote; @@ -46,9 +46,6 @@ int main(int argc, char* argv[]) TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); - - uint32_t log_level = 0; - tools::on_startup(); auto opt_size = command_line::boost_option_sizes(); @@ -90,13 +87,17 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-depth.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-depth.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -120,19 +121,19 @@ int main(int argc, char* argv[]) } } - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - LOG_PRINT_L0("database: LMDB"); + oxen::log::warning(logcat, "database: LMDB"); const fs::path filename = fs::u8path(command_line::get_arg(vm, cryptonote::arg_data_dir)) / db->get_db_name(); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -140,13 +141,13 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); std::vector start_txids; if (!opt_txid_string.empty()) @@ -159,7 +160,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return 1; } for (const crypto::hash &txid: b.tx_hashes) @@ -170,7 +171,7 @@ int main(int argc, char* argv[]) if (start_txids.empty()) { - LOG_PRINT_L0("No transaction(s) to check"); + oxen::log::warning(logcat, "No transaction(s) to check"); return 1; } @@ -180,31 +181,31 @@ int main(int argc, char* argv[]) uint64_t depth = 0; bool coinbase = false; - LOG_PRINT_L0("Checking depth for txid " << start_txid); + oxen::log::warning(logcat, "Checking depth for txid {}", start_txid); std::vector txids(1, start_txid); while (!coinbase) { - LOG_PRINT_L0("Considering "<< txids.size() << " transaction(s) at depth " << depth); + oxen::log::warning(logcat, "Considering {} transaction(s) at depth {}", txids.size(), depth); std::vector new_txids; for (const crypto::hash &txid: txids) { std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - LOG_PRINT_L0("Failed to get txid " << txid << " from db"); + oxen::log::warning(logcat, "Failed to get txid {} from db", txid); return 1; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - LOG_PRINT_L0("Bad tx: " << txid); + oxen::log::warning(logcat, "Bad tx: {}", txid); return 1; } for (size_t ring = 0; ring < tx.vin.size(); ++ring) { if (std::holds_alternative(tx.vin[ring])) { - MDEBUG(txid << " is a coinbase transaction"); + oxen::log::debug(logcat, "{} is a coinbase transaction", txid); coinbase = true; goto done; } @@ -220,7 +221,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return 1; } // find the tx which created this output @@ -233,13 +234,13 @@ int main(int argc, char* argv[]) { found = true; new_txids.push_back(cryptonote::get_transaction_hash(b.miner_tx)); - MDEBUG("adding txid: " << cryptonote::get_transaction_hash(b.miner_tx)); + oxen::log::debug(logcat, "adding txid: {}", cryptonote::get_transaction_hash(b.miner_tx)); break; } } else { - LOG_PRINT_L0("Bad vout type in txid " << cryptonote::get_transaction_hash(b.miner_tx)); + oxen::log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); return 1; } } @@ -249,13 +250,13 @@ int main(int argc, char* argv[]) break; if (!db->get_pruned_tx_blob(block_txid, bd)) { - LOG_PRINT_L0("Failed to get txid " << block_txid << " from db"); + oxen::log::warning(logcat, "Failed to get txid {} from db", block_txid); return 1; } cryptonote::transaction tx2; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx2)) { - LOG_PRINT_L0("Bad tx: " << block_txid); + oxen::log::warning(logcat, "Bad tx: {}", block_txid); return 1; } for (size_t out = 0; out < tx2.vout.size(); ++out) @@ -266,27 +267,27 @@ int main(int argc, char* argv[]) { found = true; new_txids.push_back(block_txid); - MDEBUG("adding txid: " << block_txid); + oxen::log::debug(logcat, "adding txid: {}", block_txid); break; } } else { - LOG_PRINT_L0("Bad vout type in txid " << block_txid); + oxen::log::warning(logcat, "Bad vout type in txid {}", block_txid); return 1; } } } if (!found) { - LOG_PRINT_L0("Output originating transaction not found"); + oxen::log::warning(logcat, "Output originating transaction not found"); return 1; } } } else { - LOG_PRINT_L0("Bad vin type in txid " << txid); + oxen::log::warning(logcat, "Bad vin type in txid {}", txid); return 1; } } @@ -298,15 +299,15 @@ int main(int argc, char* argv[]) } } done: - LOG_PRINT_L0("Min depth for txid " << start_txid << ": " << depth); + oxen::log::warning(logcat, "Min depth for txid {}: {}", start_txid, depth); depths.push_back(depth); } uint64_t cumulative_depth = 0; for (uint64_t depth: depths) cumulative_depth += depth; - LOG_PRINT_L0("Average min depth for " << start_txids.size() << " transaction(s): " << cumulative_depth/(float)depths.size()); - LOG_PRINT_L0("Median min depth for " << start_txids.size() << " transaction(s): " << tools::median(std::move(depths))); + oxen::log::warning(logcat, "Average min depth for {} transaction(s): {}", start_txids.size(), cumulative_depth/(float)depths.size()); + oxen::log::warning(logcat, "Median min depth for {} transaction(s): {}", start_txids.size(), tools::median(std::move(depths))); core_storage->deinit(); return 0; diff --git a/src/blockchain_utilities/blockchain_export.cpp b/src/blockchain_utilities/blockchain_export.cpp index 21b6898ad..7e0a3e761 100644 --- a/src/blockchain_utilities/blockchain_export.cpp +++ b/src/blockchain_utilities/blockchain_export.cpp @@ -34,9 +34,9 @@ #include "blockchain_objects.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; @@ -45,13 +45,9 @@ int main(int argc, char* argv[]) TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); - - uint32_t log_level = 0; uint64_t block_stop = 0; bool blocks_dat = false; - tools::on_startup(); - auto opt_size = command_line::boost_option_sizes(); po::options_description desc_cmd_only("Command line options", opt_size.first, opt_size.second); @@ -92,14 +88,19 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-export.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); block_stop = command_line::get_arg(vm, arg_block_stop); - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-export.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -117,42 +118,42 @@ int main(int argc, char* argv[]) output_file_path = fs::u8path(command_line::get_arg(vm, arg_output_file)); else output_file_path = config_folder / "export" / BLOCKCHAIN_RAW; - LOG_PRINT_L0("Export output file: " << output_file_path.string()); + oxen::log::warning(logcat, "Export output file: {}", output_file_path.string()); - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - LOG_PRINT_L0("database: LMDB"); + oxen::log::warning(logcat, "database: LMDB"); auto filename = config_folder / db->get_db_name(); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { db->open(filename, core_storage->nettype(), DBF_RDONLY); } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr, nullptr, opt_testnet ? cryptonote::network_type::TESTNET : opt_devnet ? cryptonote::network_type::DEVNET : cryptonote::network_type::MAINNET); if (core_storage->get_blockchain_pruning_seed() && !opt_blocks_dat) { - LOG_PRINT_L0("Blockchain is pruned, cannot export"); + oxen::log::warning(logcat, "Blockchain is pruned, cannot export"); return 1; } CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); - LOG_PRINT_L0("Exporting blockchain raw data..."); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Exporting blockchain raw data..."); if (opt_blocks_dat) { @@ -165,7 +166,7 @@ int main(int argc, char* argv[]) r = bootstrap.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } CHECK_AND_ASSERT_MES(r, 1, "Failed to export blockchain raw data"); - LOG_PRINT_L0("Blockchain raw data exported OK"); + oxen::log::warning(logcat, "Blockchain raw data exported OK"); return 0; CATCH_ENTRY("Export error", 1); diff --git a/src/blockchain_utilities/blockchain_import.cpp b/src/blockchain_utilities/blockchain_import.cpp index cbe685c4a..37786f091 100644 --- a/src/blockchain_utilities/blockchain_import.cpp +++ b/src/blockchain_utilities/blockchain_import.cpp @@ -36,6 +36,7 @@ #include #include "cryptonote_protocol/quorumnet.h" #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "bootstrap_file.h" #include "bootstrap_serialization.h" #include "blocks/blocks.h" @@ -44,9 +45,10 @@ #include "cryptonote_core/uptime_proof.h" #include "cryptonote_core/cryptonote_core.h" #include "common/hex.h" +#include +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace { @@ -142,8 +144,7 @@ int check_flush(cryptonote::core &core, std::vector &block cryptonote::block block; if (!parse_and_validate_block_from_blob(b.block, block)) { - MERROR("Failed to parse block: " - << tools::type_to_hex(get_blob_hash(b.block))); + oxen::log::error(logcat, "Failed to parse block: {}", tools::type_to_hex(get_blob_hash(b.block))); core.cleanup_handle_incoming_blocks(); return 1; } @@ -155,12 +156,12 @@ int check_flush(cryptonote::core &core, std::vector &block std::vector pblocks; if (!core.prepare_handle_incoming_blocks(blocks, pblocks)) { - MERROR("Failed to prepare to add blocks"); + oxen::log::error(logcat, "Failed to prepare to add blocks"); return 1; } if (!pblocks.empty() && pblocks.size() != blocks.size()) { - MERROR("Unexpected parsed blocks size"); + oxen::log::error(logcat, "Unexpected parsed blocks size"); core.cleanup_handle_incoming_blocks(); return 1; } @@ -175,8 +176,7 @@ int check_flush(cryptonote::core &core, std::vector &block core.handle_incoming_tx(tx_blob, tvc, tx_pool_options::from_block()); if(tvc.m_verifivation_failed) { - MERROR("transaction verification failed, tx_id = " - << tools::type_to_hex(get_blob_hash(tx_blob))); + oxen::log::error(logcat, "transaction verification failed, tx_id = {}", tools::type_to_hex(get_blob_hash(tx_blob))); core.cleanup_handle_incoming_blocks(); return 1; } @@ -190,14 +190,13 @@ int check_flush(cryptonote::core &core, std::vector &block if(bvc.m_verifivation_failed) { - MERROR("Block verification failed, id = " - << tools::type_to_hex(get_blob_hash(block_entry.block))); + oxen::log::error(logcat, "Block verification failed, id = {}", tools::type_to_hex(get_blob_hash(block_entry.block))); core.cleanup_handle_incoming_blocks(); return 1; } if(bvc.m_marked_as_orphaned) { - MERROR("Block received at sync phase was marked as orphaned"); + oxen::log::error(logcat, "Block received at sync phase was marked as orphaned"); core.cleanup_handle_incoming_blocks(); return 1; } @@ -219,7 +218,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (std::error_code ec; !fs::exists(import_file_path, ec)) { - MFATAL("bootstrap file not found: " << import_file_path); + oxen::log::error(logcat, "bootstrap file not found: {}", import_file_path); return false; } @@ -232,7 +231,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u std::streampos pos; // BootstrapFile bootstrap(import_file_path); uint64_t total_source_blocks = bootstrap.count_blocks(import_file_path, pos, seek_height); - MINFO("bootstrap file last block number: " << total_source_blocks-1 << " (zero-based height) total blocks: " << total_source_blocks); + oxen::log::info(logcat, "bootstrap file last block number: {} (zero-based height) total blocks: {}", total_source_blocks-1, total_source_blocks); if (total_source_blocks-1 <= start_height) { @@ -245,7 +244,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (import_file.fail()) { - MFATAL("import_file.open() fail"); + oxen::log::error(logcat, "import_file.open() fail"); return false; } @@ -269,12 +268,11 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u // These are what we'll try to use, and they don't have to be a determination // from source and destination blockchains, but those are the defaults. - MINFO("start block: " << start_height << " stop block: " << - block_stop); + oxen::log::info(logcat, "start block: {} stop block: {}", start_height, block_stop); bool use_batch = opt_batch && !opt_verify; - MINFO("Reading blockchain from bootstrap file..."); + oxen::log::info(logcat, "Reading blockchain from bootstrap file..."); std::cout << "\n"; std::vector blocks; @@ -313,7 +311,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u // TODO: bootstrap.read_chunk(); if (! import_file) { std::cout << refresh_string; - MINFO("End of file reached"); + oxen::log::info(logcat, "End of file reached"); quit = 1; break; } @@ -324,19 +322,19 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of chunk size: "s + e.what()); } - MDEBUG("chunk_size: " << chunk_size); + oxen::log::debug(logcat, "chunk_size: {}", chunk_size); if (chunk_size > BUFFER_SIZE) { - MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE); + oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); throw std::runtime_error("Aborting: chunk size exceeds buffer size"); } if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD) { - MINFO("NOTE: chunk_size " << chunk_size << " > " << CHUNK_SIZE_WARNING_THRESHOLD); + oxen::log::info(logcat, "NOTE: chunk_size {} > {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD); } else if (chunk_size == 0) { - MFATAL("ERROR: chunk_size == 0"); + oxen::log::error(logcat, "ERROR: chunk_size == 0"); return 2; } import_file.read(buffer_block, chunk_size); @@ -344,26 +342,25 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (import_file.eof()) { std::cout << refresh_string; - MINFO("End of file reached - file was truncated"); + oxen::log::info(logcat, "End of file reached - file was truncated"); quit = 1; break; } else { - MFATAL("ERROR: unexpected end of file: bytes read before error: " - << import_file.gcount() << " of chunk_size " << chunk_size); + oxen::log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); return 2; } } bytes_read += chunk_size; - MDEBUG("Total bytes read: " << bytes_read); + oxen::log::debug(logcat, "Total bytes read: {}", bytes_read); if (h > block_stop) { std::cout << refresh_string << "block " << h-1 << " / " << block_stop << "\n" << std::endl; - MINFO("Specified block number reached - stopping. block: " << h-1 << " total blocks: " << h); + oxen::log::info(logcat, "Specified block number reached - stopping. block: {} total blocks: {}", h-1, h); quit = 1; break; } @@ -386,14 +383,14 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if ((h-1) % display_interval == 0) { std::cout << refresh_string; - MDEBUG("loading block number " << h-1); + oxen::log::debug(logcat, "loading block number {}", h-1); } else { - MDEBUG("loading block number " << h-1); + oxen::log::debug(logcat, "loading block number {}", h-1); } b = bp.block; - MDEBUG("block prev_id: " << b.prev_id << "\n"); + oxen::log::debug(logcat, "block prev_id: {}\n", b.prev_id); if ((h-1) % progress_interval == 0) { @@ -458,7 +455,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u catch (const std::exception& e) { std::cout << refresh_string; - MFATAL("Error adding block to blockchain: " << e.what()); + oxen::log::error(logcat, "Error adding block to blockchain: {}", e.what()); quit = 2; // make sure we don't commit partial block data break; } @@ -488,7 +485,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u catch (const std::exception& e) { std::cout << refresh_string; - MFATAL("exception while reading from file, height=" << h << ": " << e.what()); + oxen::log::error(logcat, "exception while reading from file, height={}: {}", h, e.what()); return 2; } } // while @@ -517,10 +514,10 @@ quitting: } core.get_blockchain_storage().get_db().show_stats(); - MINFO("Number of blocks imported: " << num_imported); + oxen::log::info(logcat, "Number of blocks imported: {}", num_imported); if (h > 0) // TODO: if there was an error, the last added block is probably at zero-based height h-2 - MINFO("Finished at block: " << h-1 << " total blocks: " << h); + oxen::log::info(logcat, "Finished at block: {} total blocks: {}", h-1, h); std::cout << "\n"; return 0; @@ -532,7 +529,6 @@ int main(int argc, char* argv[]) epee::string_tools::set_module_name_and_folder(argv[0]); - uint32_t log_level = 0; uint64_t num_blocks = 0; uint64_t block_stop = 0; std::string m_config_folder; @@ -638,14 +634,17 @@ int main(int argc, char* argv[]) return 1; } m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-import.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-import.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - MINFO("Starting..."); + oxen::logging::init(log_file_path, log_level); + oxen::log::info(logcat, "Starting..."); fs::path import_file_path; @@ -661,32 +660,31 @@ int main(int argc, char* argv[]) return 0; } - MINFO("database: LMDB"); - MINFO("verify: " << std::boolalpha << opt_verify << std::noboolalpha); + oxen::log::info(logcat, "database: LMDB"); + oxen::log::info(logcat, "verify: {}", opt_verify); if (opt_batch) { - MINFO("batch: " << std::boolalpha << opt_batch << std::noboolalpha - << " batch size: " << db_batch_size); + oxen::log::info(logcat, "batch: {} batch size: {}", opt_batch, db_batch_size); } else { - MINFO("batch: " << std::boolalpha << opt_batch << std::noboolalpha); + oxen::log::info(logcat, "batch: {}", opt_batch); } - MINFO("resume: " << std::boolalpha << opt_resume << std::noboolalpha); - MINFO("nettype: " << (opt_testnet ? "testnet" : opt_devnet ? "devnet" : "mainnet")); + oxen::log::info(logcat, "resume: {}", opt_resume); + oxen::log::info(logcat, "nettype: {}", (opt_testnet ? "testnet" : opt_devnet ? "devnet" : "mainnet")); - MINFO("bootstrap file path: " << import_file_path); - MINFO("database path: " << m_config_folder); + oxen::log::info(logcat, "bootstrap file path: {}", import_file_path); + oxen::log::info(logcat, "database path: {}", m_config_folder); if (!opt_verify) { - MCLOG_RED(el::Level::Warning, "global", "\n" - "Import is set to proceed WITHOUT VERIFICATION.\n" - "This is a DANGEROUS operation: if the file was tampered with in transit, or obtained from a malicious source,\n" - "you could end up with a compromised database. It is recommended to NOT use " << arg_noverify.name << ".\n" - "*****************************************************************************************\n" - "You have 90 seconds to press ^C or terminate this program before unverified import starts\n" - "*****************************************************************************************"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "\n\ + Import is set to proceed WITHOUT VERIFICATION.\n\ + This is a DANGEROUS operation: if the file was tampered with in transit, or obtained from a malicious source,\n\ + you could end up with a compromised database. It is recommended to NOT use {}.\n\ + *****************************************************************************************\n\ + You have 90 seconds to press ^C or terminate this program before unverified import starts\n\ + *****************************************************************************************", arg_noverify.name)); sleep(90); } @@ -714,9 +712,9 @@ int main(int argc, char* argv[]) if (!command_line::is_arg_defaulted(vm, arg_pop_blocks)) { num_blocks = command_line::get_arg(vm, arg_pop_blocks); - MINFO("height: " << core.get_blockchain_storage().get_current_blockchain_height()); + oxen::log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); pop_blocks(core, num_blocks); - MINFO("height: " << core.get_blockchain_storage().get_current_blockchain_height()); + oxen::log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); return 0; } diff --git a/src/blockchain_utilities/blockchain_prune.cpp b/src/blockchain_utilities/blockchain_prune.cpp index 151fafdc4..c880e8534 100644 --- a/src/blockchain_utilities/blockchain_prune.cpp +++ b/src/blockchain_utilities/blockchain_prune.cpp @@ -39,8 +39,7 @@ #include "blockchain_objects.h" #include "version.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); #define MDB_val_set(var, val) MDB_val var = {sizeof(val), (void *)&val} @@ -57,7 +56,7 @@ static std::error_code replace_file(const fs::path& replacement_name, const fs:: { std::error_code ec = fs::rename(replacement_name, replaced_name); if (ec) - MERROR("Error renaming " << replacement_name << " to " << replaced_name << ": " << ec.message()); + oxen::log::error(logcat, "Error renaming {} to {}: {}", replacement_name, replaced_name, ec.message()); return ec; } @@ -94,7 +93,7 @@ static void add_size(MDB_env *env, uint64_t bytes) auto si = fs::space(db_path); if(si.available < bytes) { - MERROR("!! WARNING: Insufficient free space to extend database !!: " << + oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: ", (si.available >> 20L) << " MB available, " << (bytes >> 20L) << " MB needed"); return; } @@ -102,7 +101,7 @@ static void add_size(MDB_env *env, uint64_t bytes) catch(...) { // print something but proceed. - MWARNING("Unable to query free disk space."); + oxen::log::warning(logcat, "Unable to query free disk space."); } MDB_envinfo mei; @@ -117,7 +116,7 @@ static void add_size(MDB_env *env, uint64_t bytes) if (result) throw std::runtime_error("Failed to set new mapsize to " + std::to_string(new_mapsize) + ": " + std::string(mdb_strerror(result))); - MGINFO("LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB"); + oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); } static void check_resize(MDB_env *env, size_t bytes) @@ -154,7 +153,7 @@ static void copy_table(MDB_env *env0, MDB_env *env1, const char *table, unsigned bool tx_active0 = false, tx_active1 = false; int dbr; - MINFO("Copying " << table); + oxen::log::info(logcat, "Copying {}", table); OXEN_DEFER { if (tx_active1) mdb_txn_abort(txn1); @@ -251,7 +250,7 @@ static void prune(MDB_env *env0, MDB_env *env1) bool tx_active0 = false, tx_active1 = false; int dbr; - MGINFO("Creating pruned txs_prunable"); + oxen::log::info(logcat, "Creating pruned txs_prunable"); OXEN_DEFER { if (tx_active1) mdb_txn_abort(txn1); @@ -336,7 +335,7 @@ static void prune(MDB_env *env0, MDB_env *env1) MDB_val_set(kk, ti->data.tx_id); if (block_height + PRUNING_TIP_BLOCKS >= blockchain_height) { - MDEBUG(block_height << "/" << blockchain_height << " is in tip"); + oxen::log::debug(logcat, "{}/{} is in tip", block_height, blockchain_height); MDB_val_set(vv, block_height); dbr = mdb_cursor_put(cur1_txs_prunable_tip, &kk, &vv, 0); if (dbr) throw std::runtime_error("Failed to write prunable tx tip data: " + std::string(mdb_strerror(dbr))); @@ -360,7 +359,7 @@ static void prune(MDB_env *env0, MDB_env *env1) } else { - MDEBUG("" << block_height << "/" << blockchain_height << " should be pruned, dropping"); + oxen::log::debug(logcat, "{}/{} should be pruned, dropping", block_height, blockchain_height); } } @@ -386,7 +385,7 @@ static bool parse_db_sync_mode(std::string db_sync_mode, uint64_t &db_flags) auto options = tools::split_any(db_sync_mode, " :", true); for(const auto &option : options) - MDEBUG("option: " << option); + oxen::log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -490,7 +489,7 @@ int main(int argc, char* argv[]) else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - MINFO("Starting..."); + oxen::log::info(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -504,7 +503,7 @@ int main(int argc, char* argv[]) uint64_t db_flags = 0; if (!parse_db_sync_mode(db_sync_mode, db_flags)) { - MERROR("Invalid db sync mode: " << db_sync_mode); + oxen::log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); return 1; } @@ -519,7 +518,7 @@ int main(int argc, char* argv[]) // Blockchain* core_storage = new Blockchain(NULL); // because unlike blockchain_storage constructor, which takes a pointer to // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object. - MINFO("Initializing source blockchain (BlockchainDB)"); + oxen::log::info(logcat, "Initializing source blockchain (BlockchainDB)"); std::array core_storage; fs::path paths[2]; bool already_pruned = false; @@ -531,7 +530,7 @@ int main(int argc, char* argv[]) BlockchainDB* db = new_db(); if (db == NULL) { - MERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } @@ -542,7 +541,7 @@ int main(int argc, char* argv[]) { if (!fs::is_directory(paths[1])) { - MERROR("LMDB needs a directory path, but a file was passed: " << paths[1].string()); + oxen::log::error(logcat, "LMDB needs a directory path, but a file was passed: {}", paths[1].string()); return 1; } } @@ -550,7 +549,7 @@ int main(int argc, char* argv[]) { if (!fs::create_directories(paths[1])) { - MERROR("Failed to create directory: " << paths[1].string()); + oxen::log::error(logcat, "Failed to create directory: {}", paths[1].string()); return 1; } } @@ -561,7 +560,7 @@ int main(int argc, char* argv[]) paths[0] = fs::u8path(data_dir) / db->get_db_name(); } - MINFO("Loading blockchain from folder " << paths[n] << " ..."); + oxen::log::info(logcat, "Loading blockchain from folder {} ...", paths[n]); try { @@ -569,19 +568,19 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - MERROR("Error opening database: " << e.what()); + oxen::log::error(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage[n]->init(db, nullptr /*ons_db*/, net_type); std::string source_dest = n == 0 ? "source" : "pruned"; CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize " << source_dest << " blockchain storage"); - MINFO(source_dest << " blockchain storage initialized OK"); + oxen::log::info(logcat, "{} blockchain storage initialized OK", source_dest); if (n == 0 && core_storage[0]->get_blockchain_pruning_seed()) { if (!opt_copy_pruned_database) { - MERROR("Blockchain is already pruned, use --" << arg_copy_pruned_database.name << " to copy it anyway"); + oxen::log::error(logcat, "Blockchain is already pruned, use --{} to copy it anyway", arg_copy_pruned_database.name); return 1; } already_pruned = true; @@ -592,7 +591,7 @@ int main(int argc, char* argv[]) core_storage[1]->deinit(); delete core_storage[1]; - MINFO("Pruning..."); + oxen::log::info(logcat, "Pruning..."); MDB_env *env0 = NULL, *env1 = NULL; open(env0, paths[0], db_flags, true); open(env1, paths[1], db_flags, false); @@ -624,16 +623,16 @@ int main(int argc, char* argv[]) close(env1); close(env0); - MINFO("Swapping databases, pre-pruning blockchain will be left in " << paths[0].string() + "-old and can be removed if desired"); + oxen::log::info(logcat, "Swapping databases, pre-pruning blockchain will be left in {}", paths[0].string() + "-old and can be removed if desired"); fs::path old = paths[0]; old += "-old"; if (replace_file(paths[0], old) || replace_file(paths[1], paths[0])) { - MERROR("Blockchain pruned OK, but renaming failed"); + oxen::log::error(logcat, "Blockchain pruned OK, but renaming failed"); return 1; } - MINFO("Blockchain pruned OK"); + oxen::log::info(logcat, "Blockchain pruned OK"); return 0; CATCH_ENTRY("Pruning error", 1); diff --git a/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp b/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp index 43017f20f..71574af48 100644 --- a/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp +++ b/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp @@ -37,8 +37,7 @@ #include "blockchain_db/blockchain_db.h" #include "version.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; using namespace cryptonote; @@ -57,7 +56,7 @@ static std::map load_outputs(const fs::path& filename) if (!f) { - MERROR("Failed to load outputs from " << filename << ": " << strerror(errno)); + oxen::log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); return {}; } while (1) @@ -80,7 +79,7 @@ static std::map load_outputs(const fs::path& filename) } if (amount == std::numeric_limits::max()) { - MERROR("Bad format in " << filename); + oxen::log::error(logcat, "Bad format in {}", filename); continue; } if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits::max() - offset) @@ -93,7 +92,7 @@ static std::map load_outputs(const fs::path& filename) } else { - MERROR("Bad format in " << filename); + oxen::log::error(logcat, "Bad format in {}", filename); continue; } } @@ -156,7 +155,7 @@ int main(int argc, char* argv[]) else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - LOG_PRINT_L0("Starting..."); + oxen::log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -166,18 +165,18 @@ int main(int argc, char* argv[]) const auto input = fs::u8path(command_line::get_arg(vm, arg_input)); - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } const fs::path filename = fs::u8path(command_line::get_arg(vm, cryptonote::arg_data_dir)) / db->get_db_name(); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -185,20 +184,20 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); std::map known_spent_outputs; if (input.empty()) { std::map> outputs; - LOG_PRINT_L0("Scanning for known spent data..."); + oxen::log::warning(logcat, "Scanning for known spent data..."); db->for_all_transactions([&](const crypto::hash &txid, const cryptonote::transaction &tx){ const bool miner_tx = tx.vin.size() == 1 && std::holds_alternative(tx.vin[0]); for (const auto &in: tx.vin) @@ -227,11 +226,11 @@ int main(int argc, char* argv[]) } else { - LOG_PRINT_L0("Loading known spent data..."); + oxen::log::warning(logcat, "Loading known spent data..."); known_spent_outputs = load_outputs(input); } - LOG_PRINT_L0("Pruning known spent data..."); + oxen::log::warning(logcat, "Pruning known spent data..."); bool stop_requested = false; tools::signal_handler::install([&stop_requested](int type) { @@ -249,22 +248,22 @@ int main(int argc, char* argv[]) if (i->first == 0) { if (opt_verbose) - MINFO("Ignoring output value " << i->first << ", with " << num_outputs << " outputs"); + oxen::log::info(logcat, "Ignoring output value {}, with {} outputs", i->first, num_outputs); continue; } num_eligible_outputs += num_outputs; num_eligible_known_spent_outputs += i->second; if (opt_verbose) - MINFO(i->first << ": " << i->second << "/" << num_outputs); + oxen::log::info(logcat, "{}: {}/{}", i->first, i->second, num_outputs); if (num_outputs > i->second) continue; if (num_outputs && num_outputs < i->second) { - MERROR("More outputs are spent than known for amount " << i->first << ", not touching"); + oxen::log::error(logcat, "More outputs are spent than known for amount {}, not touching", i->first); continue; } if (opt_verbose) - MINFO("Pruning data for " << num_outputs << " outputs"); + oxen::log::info(logcat, "Pruning data for {} outputs", num_outputs); if (!opt_dry_run) db->prune_outputs(i->first); num_prunable_outputs += i->second; @@ -272,13 +271,13 @@ int main(int argc, char* argv[]) db->batch_stop(); - MINFO("Total outputs: " << num_total_outputs); - MINFO("Known spent outputs: " << num_known_spent_outputs); - MINFO("Eligible outputs: " << num_eligible_outputs); - MINFO("Eligible known spent outputs: " << num_eligible_known_spent_outputs); - MINFO("Prunable outputs: " << num_prunable_outputs); + oxen::log::info(logcat, "Total outputs: {}", num_total_outputs); + oxen::log::info(logcat, "Known spent outputs: {}", num_known_spent_outputs); + oxen::log::info(logcat, "Eligible outputs: {}", num_eligible_outputs); + oxen::log::info(logcat, "Eligible known spent outputs: {}", num_eligible_known_spent_outputs); + oxen::log::info(logcat, "Prunable outputs: {}", num_prunable_outputs); - LOG_PRINT_L0("Blockchain known spent data pruned OK"); + oxen::log::warning(logcat, "Blockchain known spent data pruned OK"); core_storage->deinit(); return 0; diff --git a/src/blockchain_utilities/blockchain_stats.cpp b/src/blockchain_utilities/blockchain_stats.cpp index be3393160..c3046b165 100644 --- a/src/blockchain_utilities/blockchain_stats.cpp +++ b/src/blockchain_utilities/blockchain_stats.cpp @@ -38,13 +38,12 @@ #include "version.h" #include "cryptonote_core/uptime_proof.h" #include - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +#include namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = oxen::log::Cat("bcutil"); static bool stop_requested = false; int main(int argc, char* argv[]) @@ -52,11 +51,8 @@ int main(int argc, char* argv[]) TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); - - uint32_t log_level = 0; uint64_t block_start = 0; uint64_t block_stop = 0; - tools::on_startup(); auto opt_size = command_line::boost_option_sizes(); @@ -104,13 +100,17 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-stats.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-stats.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); @@ -123,18 +123,18 @@ int main(int argc, char* argv[]) bool do_ringsize = command_line::get_arg(vm, arg_ringsize); bool do_hours = command_line::get_arg(vm, arg_hours); - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } const fs::path filename = fs::u8path(opt_data_dir) / db->get_db_name(); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -142,13 +142,13 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); tools::signal_handler::install([](int type) { stop_requested = true; @@ -157,7 +157,7 @@ int main(int argc, char* argv[]) const uint64_t db_height = db->height(); if (!block_stop) block_stop = db_height; - MINFO("Starting from height " << block_start << ", stopping at height " << block_stop); + oxen::log::info(logcat, "Starting from height {}, stopping at height {}", block_start, block_stop); /* * The default output can be plotted with GnuPlot using these commands: @@ -212,7 +212,7 @@ plot 'stats.csv' index "DATA" using (timecolumn(1,"%Y-%m-%d")):4 with lines, '' cryptonote::block blk; if (!cryptonote::parse_and_validate_block_from_blob(bd, blk)) { - LOG_PRINT_L0("Bad block from db"); + oxen::log::warning(logcat, "Bad block from db"); return 1; } auto ts = std::chrono::system_clock::from_time_t(blk.timestamp); @@ -272,7 +272,7 @@ skip: transaction tx; if (!parse_and_validate_tx_base_from_blob(bd, tx)) { - LOG_PRINT_L0("Bad txn from db"); + oxen::log::warning(logcat, "Bad txn from db"); return 1; } currsz += bd.size(); diff --git a/src/blockchain_utilities/blockchain_usage.cpp b/src/blockchain_utilities/blockchain_usage.cpp index dddf63762..ef8a480e6 100644 --- a/src/blockchain_utilities/blockchain_usage.cpp +++ b/src/blockchain_utilities/blockchain_usage.cpp @@ -34,13 +34,13 @@ #include "blockchain_db/blockchain_db.h" #include "cryptonote_core/uptime_proof.h" #include "version.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +#include namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = oxen::log::Cat("quorum_cop"); + struct output_data { uint64_t amount; @@ -78,11 +78,7 @@ int main(int argc, char* argv[]) TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); - - uint32_t log_level = 0; - tools::on_startup(); - auto opt_size = command_line::boost_option_sizes(); po::options_description desc_cmd_only("Command line options", opt_size.first, opt_size.second); @@ -122,13 +118,17 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure(mlog_get_default_log_path("oxen-blockchain-usage.log"), true); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - - LOG_PRINT_L0("Starting..."); + auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); + auto log_file_path = m_config_folder + "oxen-blockchain-usage.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -146,7 +146,7 @@ int main(int argc, char* argv[]) // Blockchain* core_storage = new Blockchain(NULL); // because unlike blockchain_storage constructor, which takes a pointer to // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object. - LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); + oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); const std::string input = command_line::get_arg(vm, arg_input); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; @@ -154,13 +154,13 @@ int main(int argc, char* argv[]) BlockchainDB *db = new_db(); if (db == NULL) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - LOG_PRINT_L0("database: LMDB"); + oxen::log::warning(logcat, "database: LMDB"); const fs::path filename = fs::u8path(input); - LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); + oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -168,22 +168,22 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - LOG_PRINT_L0("Error opening database: " << e.what()); + oxen::log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - LOG_PRINT_L0("Source blockchain storage initialized OK"); + oxen::log::warning(logcat, "Source blockchain storage initialized OK"); - LOG_PRINT_L0("Building usage patterns..."); + oxen::log::warning(logcat, "Building usage patterns..."); size_t done = 0; std::unordered_map> outputs; std::unordered_map indices; - LOG_PRINT_L0("Reading blockchain from " << input); + oxen::log::warning(logcat, "Reading blockchain from {}", input); core_storage->for_all_transactions([&](const crypto::hash &hash, const cryptonote::transaction &tx)->bool { const bool coinbase = tx.vin.size() == 1 && std::holds_alternative(tx.vin[0]); @@ -228,15 +228,15 @@ int main(int argc, char* argv[]) for (const auto &c: counts) { float percent = 100.f * c.second / total; - MINFO(std::to_string(c.second) << " outputs used " << c.first << " times (" << percent << "%)"); + oxen::log::info(logcat, "{} outputs used {} times ({}%)", std::to_string(c.second), c.first, percent); } } else { - MINFO("No outputs to process"); + oxen::log::info(logcat, "No outputs to process"); } - LOG_PRINT_L0("Blockchain usage exported OK"); + oxen::log::warning(logcat, "Blockchain usage exported OK"); return 0; CATCH_ENTRY("Export error", 1); diff --git a/src/blockchain_utilities/blocksdat_file.cpp b/src/blockchain_utilities/blocksdat_file.cpp index b2a495022..90c70fdd7 100644 --- a/src/blockchain_utilities/blocksdat_file.cpp +++ b/src/blockchain_utilities/blocksdat_file.cpp @@ -28,9 +28,7 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "blocksdat_file.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +#include namespace po = boost::program_options; @@ -38,6 +36,8 @@ using namespace cryptonote; namespace { + static auto logcat = oxen::log::Cat("bcutil"); + std::string refresh_string = "\r \r"; } @@ -52,7 +52,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) { if (!fs::is_directory(dir_path)) { - MFATAL("export directory path is a file: " << dir_path); + oxen::log::error(logcat, "export directory path is a file: {}", dir_path); return false; } } @@ -60,7 +60,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) { if (!fs::create_directory(dir_path)) { - MFATAL("Failed to create directory " << dir_path); + oxen::log::error(logcat, "Failed to create directory {}", dir_path); return false; } } @@ -68,7 +68,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) m_raw_data_file = new std::ofstream(); - MINFO("creating file"); + oxen::log::info(logcat, "creating file"); m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc); if (m_raw_data_file->fail()) @@ -133,21 +133,21 @@ bool BlocksdatFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem uint64_t block_start = 0; uint64_t block_stop = 0; - MINFO("source blockchain height: " << m_blockchain_storage->get_current_blockchain_height()-1); + oxen::log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height())) { - MINFO("Using requested block height: " << requested_block_stop); + oxen::log::info(logcat, "Using requested block height: {}", requested_block_stop); block_stop = requested_block_stop; } else { block_stop = m_blockchain_storage->get_current_blockchain_height() - 1; - MINFO("Using block height of source blockchain: " << block_stop); + oxen::log::info(logcat, "Using block height of source blockchain: {}", block_stop); } - MINFO("Storing blocks raw data..."); + oxen::log::info(logcat, "Storing blocks raw data..."); if (!BlocksdatFile::open_writer(output_file, block_stop)) { - MFATAL("failed to open raw file for write"); + oxen::log::error(logcat, "failed to open raw file for write"); return false; } for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height) @@ -167,7 +167,7 @@ bool BlocksdatFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem std::cout << refresh_string; std::cout << "block " << m_cur_height-1 << "/" << block_stop << "\n"; - MINFO("Number of blocks exported: " << num_blocks_written); + oxen::log::info(logcat, "Number of blocks exported: {}", num_blocks_written); return BlocksdatFile::close(); } diff --git a/src/blockchain_utilities/bootstrap_file.cpp b/src/blockchain_utilities/bootstrap_file.cpp index 524b58c10..0c45bfc91 100644 --- a/src/blockchain_utilities/bootstrap_file.cpp +++ b/src/blockchain_utilities/bootstrap_file.cpp @@ -29,11 +29,11 @@ #include "bootstrap_serialization.h" #include "serialization/binary_utils.h" // dump_binary(), parse_binary() +#include #include "bootstrap_file.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bcutil" +static auto logcat = oxen::log::Cat("bcutil"); namespace po = boost::program_options; @@ -60,7 +60,7 @@ bool BootstrapFile::open_writer(const fs::path& file_path) { if (!fs::is_directory(dir_path)) { - MFATAL("export directory path is a file: " << dir_path); + oxen::log::error(logcat, "export directory path is a file: {}", dir_path); return false; } } @@ -68,7 +68,7 @@ bool BootstrapFile::open_writer(const fs::path& file_path) { if (!fs::create_directory(dir_path)) { - MFATAL("Failed to create directory " << dir_path); + oxen::log::error(logcat, "Failed to create directory {}", dir_path); return false; } } @@ -81,14 +81,14 @@ bool BootstrapFile::open_writer(const fs::path& file_path) if (! fs::exists(file_path)) { - MDEBUG("creating file"); + oxen::log::debug(logcat, "creating file"); do_initialize_file = true; num_blocks = 0; } else { num_blocks = count_blocks(file_path.string()); - MDEBUG("appending to existing file with height: " << num_blocks-1 << " total blocks: " << num_blocks); + oxen::log::debug(logcat, "appending to existing file with height: {} total blocks: {}", num_blocks-1, num_blocks); } m_height = num_blocks; @@ -139,7 +139,7 @@ bool BootstrapFile::initialize_file() uint32_t bd_size = 0; std::string bd = t_serializable_object_to_blob(bfi); - MDEBUG("bootstrap::file_info size: " << bd.size()); + oxen::log::debug(logcat, "bootstrap::file_info size: {}", bd.size()); bd_size = bd.size(); try { @@ -151,7 +151,7 @@ bool BootstrapFile::initialize_file() output_stream_header << bd; bd = t_serializable_object_to_blob(bbi); - MDEBUG("bootstrap::blocks_info size: " << bd.size()); + oxen::log::debug(logcat, "bootstrap::blocks_info size: {}", bd.size()); bd_size = bd.size(); try { @@ -175,10 +175,10 @@ void BootstrapFile::flush_chunk() m_output_stream->flush(); uint32_t chunk_size = m_buffer.size(); - // MTRACE("chunk_size " << chunk_size); + // oxen::log::trace(logcat, "chunk_size {}", chunk_size); if (chunk_size > BUFFER_SIZE) { - MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE); + oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); } std::string blob; @@ -200,14 +200,14 @@ void BootstrapFile::flush_chunk() long num_chars_written = pos_after - pos_before; if (static_cast(num_chars_written) != chunk_size) { - MFATAL("Error writing chunk: height: " << m_cur_height << " chunk_size: " << chunk_size << " num chars written: " << num_chars_written); + oxen::log::error(logcat, "Error writing chunk: height: {} chunk_size: {} num chars written: {}", m_cur_height, chunk_size, num_chars_written); throw std::runtime_error("Error writing chunk"); } m_buffer.clear(); delete m_output_stream; m_output_stream = new boost::iostreams::stream>(m_buffer); - MDEBUG("flushed chunk: chunk_size: " << chunk_size); + oxen::log::debug(logcat, "flushed chunk: chunk_size: {}", chunk_size); } void BootstrapFile::write_block(block& block) @@ -271,10 +271,10 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem m_blockchain_storage = _blockchain_storage; m_tx_pool = _tx_pool; uint64_t progress_interval = 100; - MINFO("Storing blocks raw data..."); + oxen::log::info(logcat, "Storing blocks raw data..."); if (!BootstrapFile::open_writer(output_file)) { - MFATAL("failed to open raw file for write"); + oxen::log::error(logcat, "failed to open raw file for write"); return false; } block b; @@ -284,16 +284,16 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem // height. uint64_t block_start = m_height; uint64_t block_stop = 0; - MINFO("source blockchain height: " << m_blockchain_storage->get_current_blockchain_height()-1); + oxen::log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height())) { - MINFO("Using requested block height: " << requested_block_stop); + oxen::log::info(logcat, "Using requested block height: {}", requested_block_stop); block_stop = requested_block_stop; } else { block_stop = m_blockchain_storage->get_current_blockchain_height() - 1; - MINFO("Using block height of source blockchain: " << block_stop); + oxen::log::info(logcat, "Using block height of source blockchain: {}", block_stop); } for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height) { @@ -319,9 +319,9 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem std::cout << refresh_string; std::cout << "block " << m_cur_height-1 << "/" << block_stop << "\n"; - MINFO("Number of blocks exported: " << num_blocks_written); + oxen::log::info(logcat, "Number of blocks exported: {}", num_blocks_written); if (num_blocks_written > 0) - MINFO("Largest chunk: " << m_max_chunk << " bytes"); + oxen::log::info(logcat, "Largest chunk: {} bytes", m_max_chunk); return BootstrapFile::close(); } @@ -345,11 +345,11 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) if (file_magic != blockchain_raw_magic) { - MFATAL("bootstrap file not recognized"); + oxen::log::error(logcat, "bootstrap file not recognized"); throw std::runtime_error("Aborting"); } else - MINFO("bootstrap file recognized"); + oxen::log::info(logcat, "bootstrap file recognized"); uint32_t buflen_file_info; @@ -362,7 +362,7 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of buflen_file_info: "s + e.what()); } - MINFO("bootstrap::file_info size: " << buflen_file_info); + oxen::log::info(logcat, "bootstrap::file_info size: {}", buflen_file_info); if (buflen_file_info > sizeof(buf1)) throw std::runtime_error("Error: bootstrap::file_info size exceeds buffer size"); @@ -376,9 +376,9 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of bootstrap::file_info: "s + e.what()); } - MINFO("bootstrap file v" << unsigned(bfi.major_version) << "." << unsigned(bfi.minor_version)); - MINFO("bootstrap magic size: " << sizeof(file_magic)); - MINFO("bootstrap header size: " << bfi.header_size); + oxen::log::info(logcat, "bootstrap file v{}.{}", unsigned(bfi.major_version), unsigned(bfi.minor_version)); + oxen::log::info(logcat, "bootstrap magic size: {}", sizeof(file_magic)); + oxen::log::info(logcat, "bootstrap header size: {}", bfi.header_size); uint64_t full_header_size = sizeof(file_magic) + bfi.header_size; import_file.seekg(full_header_size); @@ -398,7 +398,7 @@ uint64_t BootstrapFile::count_bytes(fs::ifstream& import_file, uint64_t blocks, import_file.read(buf1, sizeof(chunk_size)); if (!import_file) { std::cout << refresh_string; - MDEBUG("End of file reached"); + oxen::log::debug(logcat, "End of file reached"); quit = true; break; } @@ -409,32 +409,29 @@ uint64_t BootstrapFile::count_bytes(fs::ifstream& import_file, uint64_t blocks, } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of chunk_size: "s + e.what()); } - MDEBUG("chunk_size: " << chunk_size); + oxen::log::debug(logcat, "chunk_size: {}", chunk_size); if (chunk_size > BUFFER_SIZE) { std::cout << refresh_string; - MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE - << " height: " << h-1 << ", offset " << bytes_read); + oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {} height: {}, offset {}", chunk_size, BUFFER_SIZE, h-1, bytes_read); throw std::runtime_error("Aborting: chunk size exceeds buffer size"); } if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD) { std::cout << refresh_string; - MDEBUG("NOTE: chunk_size " << chunk_size << " > " << CHUNK_SIZE_WARNING_THRESHOLD << " << height: " - << h-1 << ", offset " << bytes_read); + oxen::log::debug(logcat, "NOTE: chunk_size {} > {} height: {}, offset {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD, h-1, bytes_read); } else if (chunk_size <= 0) { std::cout << refresh_string; - MDEBUG("ERROR: chunk_size " << chunk_size << " <= 0" << " height: " << h-1 << ", offset " << bytes_read); + oxen::log::debug(logcat, "ERROR: chunk_size {} <= 0 height: {}, offset {}", chunk_size, h-1, bytes_read); throw std::runtime_error("Aborting"); } // skip to next expected block size value import_file.seekg(chunk_size, std::ios_base::cur); if (! import_file) { std::cout << refresh_string; - MFATAL("ERROR: unexpected end of file: bytes read before error: " - << import_file.gcount() << " of chunk_size " << chunk_size); + oxen::log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); throw std::runtime_error("Aborting"); } bytes_read += chunk_size; @@ -459,7 +456,7 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre { if (std::error_code ec; !fs::exists(import_file_path, ec)) { - MFATAL("bootstrap file not found: " << import_file_path); + oxen::log::error(logcat, "bootstrap file not found: {}", import_file_path); throw std::runtime_error("Aborting"); } fs::ifstream import_file{import_file_path, std::ios::binary}; @@ -468,14 +465,14 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre uint64_t h = 0; if (import_file.fail()) { - MFATAL("import_file.open() fail"); + oxen::log::error(logcat, "import_file.open() fail"); throw std::runtime_error("Aborting"); } uint64_t full_header_size; // 4 byte magic + length of header structures full_header_size = seek_to_first_chunk(import_file); - MINFO("Scanning blockchain from bootstrap file..."); + oxen::log::info(logcat, "Scanning blockchain from bootstrap file..."); bool quit = false; uint64_t bytes_read = 0, blocks; int progress_interval = 10; @@ -495,7 +492,7 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre std::flush; // std::cout << refresh_string; - MDEBUG("Number bytes scanned: " << bytes_read); + oxen::log::debug(logcat, "Number bytes scanned: {}", bytes_read); } import_file.close(); diff --git a/src/checkpoints/CMakeLists.txt b/src/checkpoints/CMakeLists.txt index e9e9d072b..c301ad748 100644 --- a/src/checkpoints/CMakeLists.txt +++ b/src/checkpoints/CMakeLists.txt @@ -38,4 +38,5 @@ target_link_libraries(checkpoints Boost::program_options Boost::serialization filesystem + logging extra) diff --git a/src/checkpoints/checkpoints.cpp b/src/checkpoints/checkpoints.cpp index 605d96eac..861b99f94 100644 --- a/src/checkpoints/checkpoints.cpp +++ b/src/checkpoints/checkpoints.cpp @@ -42,17 +42,20 @@ #include "common/oxen.h" #include "common/file.h" #include "common/hex.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "checkpoints" +#include namespace cryptonote { + + static auto logcat = oxen::log::Cat("checkpoints"); + bool checkpoint_t::check(crypto::hash const &hash) const { bool result = block_hash == hash; - if (result) MINFO ("CHECKPOINT PASSED FOR HEIGHT " << height << " " << block_hash); - else MWARNING("CHECKPOINT FAILED FOR HEIGHT " << height << ". EXPECTED HASH " << block_hash << "GIVEN HASH: " << hash); + if (result) + oxen::log::info(logcat, "CHECKPOINT PASSED FOR HEIGHT {} {}", height, block_hash); + else + oxen::log::warning(logcat, "CHECKPOINT FAILED FOR HEIGHT {}. EXPECTED HASH {}GIVEN HASH: {}", height, block_hash, hash); return result; }; @@ -93,7 +96,7 @@ namespace cryptonote { if (std::error_code ec; !fs::exists(json_hashfile_fullpath, ec)) { - LOG_PRINT_L1("Blockchain checkpoints file not found"); + oxen::log::info(logcat, "Blockchain checkpoints file not found"); return true; } @@ -102,7 +105,7 @@ namespace cryptonote !tools::slurp_file(json_hashfile_fullpath, contents) || !epee::serialization::load_t_from_json(hashes, contents)) { - MERROR("Error loading checkpoints from " << json_hashfile_fullpath); + oxen::log::error(logcat, "Error loading checkpoints from {}", json_hashfile_fullpath); return false; } @@ -119,7 +122,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Get block checkpoint from DB failed at height: " << height << ", what = " << e.what()); + oxen::log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", height, e.what()); return false; } } @@ -158,7 +161,7 @@ namespace cryptonote } catch (const std::exception& e) { - MERROR("Failed to add checkpoint with hash: " << checkpoint.block_hash << " at height: " << checkpoint.height << ", what = " << e.what()); + oxen::log::error(logcat, "Failed to add checkpoint with hash: {} at height: {}, what = {}", checkpoint.block_hash, checkpoint.height, e.what()); result = false; } @@ -199,7 +202,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Pruning block checkpoint on block added failed non-trivially at height: " << m_last_cull_height << ", what = " << e.what()); + oxen::log::error(logcat, "Pruning block checkpoint on block added failed non-trivially at height: {}, what = {}", m_last_cull_height, e.what()); } } @@ -226,7 +229,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Remove block checkpoint on detach failed non-trivially at height: " << delete_height << ", what = " << e.what()); + oxen::log::error(logcat, "Remove block checkpoint on detach failed non-trivially at height: {}, what = {}", delete_height, e.what()); } } } diff --git a/src/checkpoints/checkpoints.h b/src/checkpoints/checkpoints.h index 85d7b0658..1c983029f 100644 --- a/src/checkpoints/checkpoints.h +++ b/src/checkpoints/checkpoints.h @@ -31,7 +31,6 @@ #pragma once #include -#include "epee/misc_log_ex.h" #include "crypto/hash.h" #include "cryptonote_config.h" #include "cryptonote_core/service_node_voting.h" diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 697a7a00f..21ccfa6d4 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -39,7 +39,6 @@ add_library(common oxen.cpp notify.cpp password.cpp - perf_timer.cpp pruning.cpp random.cpp rules.cpp @@ -67,7 +66,7 @@ target_link_libraries(common filesystem fmt::fmt date::date - fmt::fmt PRIVATE sodium + logging extra) diff --git a/src/common/apply_permutation.h b/src/common/apply_permutation.h index a6058286e..c48559b73 100644 --- a/src/common/apply_permutation.h +++ b/src/common/apply_permutation.h @@ -34,7 +34,7 @@ #include #include -#include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" namespace tools { @@ -44,7 +44,12 @@ void apply_permutation(std::vector permutation, const F &swap) { //sanity check for (size_t n = 0; n < permutation.size(); ++n) - CHECK_AND_ASSERT_THROW_MES(std::find(permutation.begin(), permutation.end(), n) != permutation.end(), "Bad permutation"); + if (std::find(permutation.begin(), permutation.end(), n) == permutation.end()) + { + oxen::log::error(globallogcat, "Bad permutation"); + throw std::runtime_error("Bad permutation"); + return; + } for (size_t i = 0; i < permutation.size(); ++i) { @@ -63,7 +68,12 @@ void apply_permutation(std::vector permutation, const F &swap) template void apply_permutation(const std::vector &permutation, std::vector &v) { - CHECK_AND_ASSERT_THROW_MES(permutation.size() == v.size(), "Mismatched vector sizes"); + if (permutation.size() != v.size()) + { + oxen::log::error(globallogcat, "Mismatched vector sizes"); + throw std::runtime_error("Mismatched vector sizes"); + return; + } apply_permutation(permutation, [&v](size_t i0, size_t i1){ std::swap(v[i0], v[i1]); }); } diff --git a/src/common/boost_serialization_helper.h b/src/common/boost_serialization_helper.h index caa017164..4f22bd46d 100644 --- a/src/common/boost_serialization_helper.h +++ b/src/common/boost_serialization_helper.h @@ -30,11 +30,12 @@ #pragma once -#include "epee/misc_log_ex.h" #include #include #include +#include "epee/misc_log_ex.h" #include "fs.h" +#include namespace tools diff --git a/src/common/command_line.h b/src/common/command_line.h index b22940002..234ebf167 100644 --- a/src/common/command_line.h +++ b/src/common/command_line.h @@ -34,16 +34,20 @@ #include #include #include +#include #include #include #include -#include "epee/misc_log_ex.h" #include "common/string_util.h" #include "common/i18n.h" +#include "logging/oxen_logger.h" namespace command_line { + + static auto logcat = oxen::log::Cat("global"); + inline const char* tr(const char* str) { return i18n_translate(str, "command_line"); } /// @return True if `str` is (case-insensitively) y, yes, a potentially translated yes, or any of @@ -216,7 +220,8 @@ namespace command_line { if (0 != description.find_nothrow(arg.name, false)) { - CHECK_AND_ASSERT_MES(!unique, void(), "Argument already exists: " << arg.name); + if (!unique) + oxen::log::error(logcat, "Argument already exists: {}", arg.name); return; } @@ -228,7 +233,8 @@ namespace command_line { if (0 != description.find_nothrow(arg.name, false)) { - CHECK_AND_ASSERT_MES(!unique, void(), "Argument already exists: " << arg.name); + if (!unique) + oxen::log::error(logcat, "Argument already exists: {}", arg.name); return; } @@ -240,7 +246,8 @@ namespace command_line { if (0 != description.find_nothrow(arg.name, false)) { - CHECK_AND_ASSERT_MES(!unique, void(), "Argument already exists: " << arg.name); + if (!unique) + oxen::log::error(logcat, "Argument already exists: {}", arg.name); return; } diff --git a/src/common/expect.cpp b/src/common/expect.cpp index c86e23e95..6bb7d2a02 100644 --- a/src/common/expect.cpp +++ b/src/common/expect.cpp @@ -26,8 +26,8 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "expect.h" +#include "common/fs.h" -#include #include namespace detail @@ -48,9 +48,7 @@ namespace detail error_msg.append("thrown at "); // remove path, get just filename + extension - char buff[256] = {0}; - el::base::utils::File::buildBaseFilename(file, buff, sizeof(buff) - 1); - error_msg.append(buff); + error_msg.append(fs::path(file).filename().c_str()); error_msg.push_back(':'); error_msg.append(std::to_string(line)); diff --git a/src/common/file.cpp b/src/common/file.cpp index f3f4b1074..240255eb5 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -30,9 +30,11 @@ // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers // #include "file.h" -#include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" +#include #include #include +#include #ifdef WIN32 #include "epee/string_tools.h" @@ -59,11 +61,10 @@ #include "cryptonote_config.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "util" - namespace tools { + static auto logcat = oxen::log::Cat("util"); + #ifndef _WIN32 static int flock_exnb(int fd) { @@ -77,7 +78,7 @@ namespace tools { fl.l_len = 0; ret = fcntl(fd, F_SETLK, &fl); if (ret < 0) - MERROR("Error locking fd " << fd << ": " << errno << " (" << strerror(errno) << ")"); + oxen::log::error(logcat, "Error locking fd {}: {} ({})", fd, errno, strerror(errno)); return ret; } #endif @@ -207,14 +208,14 @@ namespace tools { memset(&ov, 0, sizeof(ov)); if (!LockFileEx(m_fd, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ov)) { - MERROR("Failed to lock " << filename << ": " << std::error_code(GetLastError(), std::system_category())); + oxen::log::error(logcat, "Failed to lock {}: {}", filename, std::error_code(GetLastError(), std::system_category())); CloseHandle(m_fd); m_fd = INVALID_HANDLE_VALUE; } } else { - MERROR("Failed to open " << filename << ": " << std::error_code(GetLastError(), std::system_category())); + oxen::log::error(logcat, "Failed to open {}: {}", filename, std::error_code(GetLastError(), std::system_category())); } #else m_fd = open(filename.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666); @@ -222,14 +223,14 @@ namespace tools { { if (flock_exnb(m_fd) == -1) { - MERROR("Failed to lock " << filename << ": " << std::strerror(errno)); + oxen::log::error(logcat, "Failed to lock {}: {}", filename, std::strerror(errno)); close(m_fd); m_fd = -1; } } else { - MERROR("Failed to open " << filename << ": " << std::strerror(errno)); + oxen::log::error(logcat, "Failed to open {}: {}", filename, std::strerror(errno)); } #endif } @@ -264,7 +265,7 @@ namespace tools { return fs::path{psz_path}; } - LOG_ERROR("SHGetSpecialFolderPathW() failed, could not obtain requested path."); + oxen::log::error(logcat, "SHGetSpecialFolderPathW() failed, could not obtain requested path."); return ""; } #endif @@ -302,17 +303,11 @@ namespace tools { bool slurp_file(const fs::path& filename, std::string& contents) { - fs::ifstream in; - in.exceptions(std::ifstream::failbit | std::ifstream::badbit); + try { - in.open(filename, std::ios::binary | std::ios::in | std::ios::ate); - contents.clear(); - contents.resize(in.tellg()); - in.seekg(0); - in.read(contents.data(), contents.size()); - auto bytes_read = in.gcount(); - if (static_cast(bytes_read) < contents.size()) - contents.resize(bytes_read); + fs::ifstream in(filename); + std::string content((std::istreambuf_iterator(in)), (std::istreambuf_iterator())); + contents = std::move(content); return true; } catch (...) { return false; diff --git a/src/common/i18n.cpp b/src/common/i18n.cpp index 4ed603f2b..036dbbe17 100644 --- a/src/common/i18n.cpp +++ b/src/common/i18n.cpp @@ -37,9 +37,9 @@ #include #include #include "file.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "i18n" +static auto logcat = oxen::log::Cat("i18n"); #define MAX_LANGUAGE_SIZE 16 diff --git a/src/common/json_util.h b/src/common/json_util.h index 96f4b90e6..424231ce6 100644 --- a/src/common/json_util.h +++ b/src/common/json_util.h @@ -41,13 +41,13 @@ } \ else \ { \ - LOG_ERROR("Field " << #name << " found in JSON, but not " << #jtype); \ + oxen::log::error(logcat, "Field {} found in JSON, but not {}", #name, #jtype); \ return false; \ } \ } \ else if (mandatory) \ { \ - LOG_ERROR("Field " << #name << " not found in JSON"); \ + oxen::log::error(logcat, "Field {} not found in JSON", #name); \ return false; \ } while(0) diff --git a/src/common/notify.cpp b/src/common/notify.cpp index c1e26f7dc..6d04e5933 100644 --- a/src/common/notify.cpp +++ b/src/common/notify.cpp @@ -28,15 +28,15 @@ #include "string_util.h" #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "spawn.h" #include "notify.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "notify" - namespace tools { + static auto logcat = oxen::log::Cat("notify"); + /* TODO: - Improve tokenization to handle paths containing whitespaces, quotes, etc. diff --git a/src/common/perf_timer.cpp b/src/common/perf_timer.cpp deleted file mode 100644 index 2cfa66184..000000000 --- a/src/common/perf_timer.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) 2016-2019, The Monero Project -// Copyright (c) 2018, The Loki Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -#include -#include -#include "perf_timer.h" - -using namespace std::literals; - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "perf" - -#define PERF_LOG_ALWAYS(level, cat, x) \ - el::base::Writer(level, __FILE__, __LINE__, ELPP_FUNC, el::base::DispatchAction::FileOnlyLog).construct(cat) << x - -namespace tools -{ - -el::Level performance_timer_log_level = el::Level::Info; - -static thread_local std::vector* performance_timers = nullptr; - -void set_performance_timer_log_level(el::Level level) -{ - if (level != el::Level::Debug && level != el::Level::Trace && level != el::Level::Info - && level != el::Level::Warning && level != el::Level::Error && level != el::Level::Fatal) - { - MERROR("Wrong log level: " << el::LevelHelper::convertToString(level) << ", using Info"); - level = el::Level::Info; - } - performance_timer_log_level = level; -} - -PerformanceTimer::PerformanceTimer(bool paused): started(true) -{ - if (!paused) - since = std::chrono::steady_clock::now(); -} - -LoggingPerformanceTimer::LoggingPerformanceTimer(const std::string &s, const std::string &cat, uint64_t unit, el::Level l): PerformanceTimer(), name(s), cat(cat), unit(unit), level(l) -{ - const bool log = ELPP->vRegistry()->allowed(level, cat.c_str()); - if (!performance_timers) - { - if (log) - PERF_LOG_ALWAYS(level, cat.c_str(), "PERF ----------"); - performance_timers = new std::vector(); - performance_timers->reserve(16); // how deep before realloc - } - else - { - LoggingPerformanceTimer* pt = performance_timers->back(); - if (!pt->started && pt->since) - { - if (log) - { - size_t size = 0; for (const auto *tmp: *performance_timers) if (tmp->since) ++size; - PERF_LOG_ALWAYS(pt->level, cat.c_str(), "PERF " << std::string((size-1) * 2, ' ') << " " << pt->name); - } - pt->started = true; - } - } - performance_timers->push_back(this); -} - -LoggingPerformanceTimer::~LoggingPerformanceTimer() -{ - pause(); - performance_timers->pop_back(); - const bool log = ELPP->vRegistry()->allowed(level, cat.c_str()); - if (log) - { - char s[12]; - snprintf(s, sizeof(s), "%8llu ", static_cast(elapsed.count() / (1000000000 / unit))); - size_t size = 0; for (const auto *tmp: *performance_timers) if (tmp->since || tmp==this) ++size; - PERF_LOG_ALWAYS(level, cat.c_str(), "PERF " << s << std::string(size * 2, ' ') << " " << name); - } - if (performance_timers->empty()) - { - delete performance_timers; - performance_timers = nullptr; - } -} - -void PerformanceTimer::pause() -{ - if (!since) - return; - auto now = std::chrono::steady_clock::now(); - elapsed += now - *since; - since.reset(); -} - -void PerformanceTimer::resume() -{ - if (!since) - since = std::chrono::steady_clock::now(); -} - -void PerformanceTimer::reset() -{ - elapsed = 0ns; - if (since) - since = std::chrono::steady_clock::now(); -} - -std::chrono::nanoseconds PerformanceTimer::value() const -{ - auto ret = elapsed; - if (since) - ret += std::chrono::steady_clock::now() - *since; - return ret; -} - -} // namespace tools diff --git a/src/common/perf_timer.h b/src/common/perf_timer.h deleted file mode 100644 index e2a055aac..000000000 --- a/src/common/perf_timer.h +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2016-2019, The Monero Project -// Copyright (c) 2018, The Loki Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -#pragma once - -#include -#include -#include -#include -#include "epee/misc_log_ex.h" - -namespace tools -{ - -extern el::Level performance_timer_log_level; - -class PerformanceTimer -{ -public: - PerformanceTimer(bool paused = false); - void pause(); - void resume(); - void reset(); - std::chrono::nanoseconds value() const; - std::chrono::duration seconds() const { return value(); } - -protected: - std::optional since; - std::chrono::nanoseconds elapsed; - bool started; -}; - -class LoggingPerformanceTimer: public PerformanceTimer -{ -public: - LoggingPerformanceTimer(const std::string &s, const std::string &cat, uint64_t unit, el::Level l = el::Level::Info); - ~LoggingPerformanceTimer(); - -private: - std::string name; - std::string cat; - uint64_t unit; - el::Level level; -}; - -void set_performance_timer_log_level(el::Level level); - -#define PERF_TIMER_UNIT(name, unit) tools::LoggingPerformanceTimer pt_##name(#name, "perf." OXEN_DEFAULT_LOG_CATEGORY, unit, tools::performance_timer_log_level) -#define PERF_TIMER_UNIT_L(name, unit, l) tools::LoggingPerformanceTimer pt_##name(#name, "perf." OXEN_DEFAULT_LOG_CATEGORY, unit, l) -#define PERF_TIMER(name) PERF_TIMER_UNIT(name, 1000000) -#define PERF_TIMER_L(name, l) PERF_TIMER_UNIT_L(name, 1000000, l) -#define PERF_TIMER_START_UNIT(name, unit) std::unique_ptr pt_##name(new tools::LoggingPerformanceTimer(#name, "perf." OXEN_DEFAULT_LOG_CATEGORY, unit, el::Level::Info)) -#define PERF_TIMER_START(name) PERF_TIMER_START_UNIT(name, 1000000) -#define PERF_TIMER_STOP(name) do { pt_##name.reset(NULL); } while(0) -#define PERF_TIMER_PAUSE(name) pt_##name->pause() -#define PERF_TIMER_RESUME(name) pt_##name->resume() - -} diff --git a/src/common/scoped_message_writer.cpp b/src/common/scoped_message_writer.cpp index 4ae86cb2c..4c5f8891c 100644 --- a/src/common/scoped_message_writer.cpp +++ b/src/common/scoped_message_writer.cpp @@ -1,23 +1,16 @@ #include "scoped_message_writer.h" +static auto logcat = oxen::log::Cat("msgwriter"); + tools::scoped_message_writer::~scoped_message_writer() { if (m_flush) { m_flush = false; - - MCLOG_FILE(m_log_level, "msgwriter", m_oss.str()); - if (epee::console_color_default == m_color) - { - std::cout << m_oss.str(); - } + if (fmt::terminal_color::white == m_color) + logcat->log(m_log_level, m_oss.str()); else - { - rdln::suspend_readline pause_readline; - set_console_color(m_color, m_bright); - std::cout << m_oss.str(); - epee::reset_console_color(); - } + logcat->log(m_log_level, fmt::format(fg(m_color),m_oss.str())); std::cout << std::endl; } } diff --git a/src/common/scoped_message_writer.h b/src/common/scoped_message_writer.h index 6b01799c4..c89c6f1a0 100644 --- a/src/common/scoped_message_writer.h +++ b/src/common/scoped_message_writer.h @@ -28,9 +28,11 @@ #pragma once -#include "epee/misc_log_ex.h" #include "epee/readline_suspend.h" +#include "epee/misc_log_ex.h" #include +#include "logging/oxen_logger.h" +#include namespace tools { @@ -43,19 +45,16 @@ class scoped_message_writer private: bool m_flush; std::ostringstream m_oss; - epee::console_colors m_color; - bool m_bright; - el::Level m_log_level; + fmt::terminal_color m_color; + oxen::log::Level m_log_level; public: scoped_message_writer( - epee::console_colors color = epee::console_color_default - , bool bright = false + fmt::terminal_color color = fmt::terminal_color::white , std::string prefix = {} - , el::Level log_level = el::Level::Info + , spdlog::level::level_enum log_level = spdlog::level::info ) : m_flush(true) , m_color(color) - , m_bright(bright) , m_log_level(log_level) { m_oss << prefix; @@ -86,17 +85,17 @@ public: inline scoped_message_writer success_msg_writer(bool color = true) { - return scoped_message_writer(color ? epee::console_color_green : epee::console_color_default, false, std::string(), el::Level::Info); + return scoped_message_writer(color ? fmt::terminal_color::green : fmt::terminal_color::white, std::string(), spdlog::level::info); } -inline scoped_message_writer msg_writer(epee::console_colors color = epee::console_color_default) +inline scoped_message_writer msg_writer(fmt::terminal_color color = fmt::terminal_color::white) { - return scoped_message_writer(color, false, std::string(), el::Level::Info); + return scoped_message_writer(color, std::string(), spdlog::level::info); } inline scoped_message_writer fail_msg_writer() { - return scoped_message_writer(epee::console_color_red, true, "Error: ", el::Level::Error); + return scoped_message_writer(fmt::terminal_color::red, "Error: ", spdlog::level::err); } } // namespace tools diff --git a/src/common/signal_handler.h b/src/common/signal_handler.h index 4fe7ebc92..5e4e5628d 100644 --- a/src/common/signal_handler.h +++ b/src/common/signal_handler.h @@ -47,7 +47,7 @@ namespace tools { } else { - MGINFO_RED("Got control signal " << type << ". Exiting without saving..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Got control signal {}. Exiting without saving...", type); return FALSE; } return TRUE; diff --git a/src/common/spawn.cpp b/src/common/spawn.cpp index 25a9bb5c7..f88b5b5e3 100644 --- a/src/common/spawn.cpp +++ b/src/common/spawn.cpp @@ -37,17 +37,17 @@ #endif #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "util.h" #include "spawn.h" #include "oxen.h" #include "string_util.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "spawn" - namespace tools { + static auto logcat = oxen::log::Cat("spawn"); + #ifndef _WIN32 static void closefrom(int fd) { @@ -83,7 +83,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w // wchar_t* but out input is utf-8). Shame on you for this garbage API, Windows. if (!CreateProcessA(filename.string().c_str(), commandLine, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)) { - MERROR("CreateProcess failed. Error code " << GetLastError()); + oxen::log::error(logcat, "CreateProcess failed. Error code {}", GetLastError()); return -1; } @@ -100,18 +100,18 @@ int spawn(const fs::path& filename, const std::vector& args, bool w DWORD result = WaitForSingleObject(pi.hProcess, INFINITE); if (result != WAIT_OBJECT_0) { - MERROR("WaitForSingleObject failed. Result " << result << ", error code " << GetLastError()); + oxen::log::error(logcat, "WaitForSingleObject failed. Result {}, error code {}", result, GetLastError()); return -1; } DWORD exitCode; if (!GetExitCodeProcess(pi.hProcess, &exitCode)) { - MERROR("GetExitCodeProcess failed. Error code " << GetLastError()); + oxen::log::error(logcat, "GetExitCodeProcess failed. Error code {}", GetLastError()); return -1; } - MINFO("Child exited with " << exitCode); + oxen::log::info(logcat, "Child exited with {}", exitCode); return static_cast(exitCode); #else std::vector argv(args.size() + 1); @@ -122,7 +122,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w pid_t pid = fork(); if (pid < 0) { - MERROR("Error forking: " << strerror(errno)); + oxen::log::error(logcat, "Error forking: {}", strerror(errno)); return -1; } @@ -133,7 +133,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w close(0); char *envp[] = {NULL}; execve(filename.c_str(), argv.data(), envp); - MERROR("Failed to execve: " << strerror(errno)); + oxen::log::error(logcat, "Failed to execve: {}", strerror(errno)); return -1; } @@ -151,22 +151,22 @@ int spawn(const fs::path& filename, const std::vector& args, bool w int wstatus = 0; pid_t w = waitpid(pid, &wstatus, WUNTRACED | WCONTINUED); if (w < 0) { - MERROR("Error waiting for child: " << strerror(errno)); + oxen::log::error(logcat, "Error waiting for child: {}", strerror(errno)); return -1; } if (WIFEXITED(wstatus)) { - MINFO("Child exited with " << WEXITSTATUS(wstatus)); + oxen::log::info(logcat, "Child exited with {}", WEXITSTATUS(wstatus)); return WEXITSTATUS(wstatus); } if (WIFSIGNALED(wstatus)) { - MINFO("Child killed by " << WEXITSTATUS(wstatus)); + oxen::log::info(logcat, "Child killed by {}", WEXITSTATUS(wstatus)); return WEXITSTATUS(wstatus); } } } - MERROR("Secret passage found"); + oxen::log::error(logcat, "Secret passage found"); return -1; #endif } diff --git a/src/common/threadpool.cpp b/src/common/threadpool.cpp index ed93ee239..035a8a184 100644 --- a/src/common/threadpool.cpp +++ b/src/common/threadpool.cpp @@ -26,6 +26,7 @@ // 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. #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "common/threadpool.h" #include "cryptonote_config.h" @@ -36,6 +37,8 @@ static thread_local bool is_leaf = false; namespace tools { + static auto logcat = oxen::log::Cat("global"); + threadpool::threadpool(unsigned int max_threads) : running(true), active(0) { create(max_threads); } @@ -112,7 +115,7 @@ threadpool::waiter::~waiter() { std::unique_lock lock{mt}; if (num) - MERROR("wait should have been called before waiter dtor - waiting now"); + oxen::log::error(logcat, "wait should have been called before waiter dtor - waiting now"); } catch (...) { /* ignore */ } try diff --git a/src/common/util.cpp b/src/common/util.cpp index a39d05252..5f593f76f 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -33,6 +33,7 @@ #include #include #include +#include #include @@ -42,6 +43,7 @@ #include "util.h" #include "epee/readline_buffer.h" #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "string_util.h" #include "i18n.h" @@ -51,11 +53,9 @@ #include #endif -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "util" - namespace tools { + static auto logcat = oxen::log::Cat("util"); bool disable_core_dumps() { @@ -65,7 +65,7 @@ namespace tools rlimit.rlim_cur = rlimit.rlim_max = 0; if (setrlimit(RLIMIT_CORE, &rlimit)) { - MWARNING("Failed to disable core dumps"); + oxen::log::warning(logcat, "Failed to disable core dumps"); return false; } #endif @@ -78,7 +78,7 @@ namespace tools struct rlimit rlim; if (getrlimit(RLIMIT_MEMLOCK, &rlim) < 0) { - MERROR("Failed to determine the lockable memory limit"); + oxen::log::error(logcat, "Failed to determine the lockable memory limit"); return -1; } return rlim.rlim_cur; @@ -89,12 +89,10 @@ namespace tools bool on_startup() { - mlog_configure("", true); - #ifdef __GLIBC__ const char *ver = ::gnu_get_libc_version(); if (!strcmp(ver, "2.25")) - MCLOG_RED(el::Level::Warning, "global", "Running with glibc " << ver << ", hangs may occur - change glibc version if possible"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Running with glibc {}, hangs may occur - change glibc version if possible", ver)); #endif return true; @@ -164,7 +162,7 @@ namespace tools } else { - return {}; + return std::nullopt; } } diff --git a/src/crypto/CMakeLists.txt b/src/crypto/CMakeLists.txt index 74eb628e6..215dcc390 100644 --- a/src/crypto/CMakeLists.txt +++ b/src/crypto/CMakeLists.txt @@ -66,6 +66,7 @@ target_link_libraries(cncrypto Boost::thread sodium PRIVATE + logging extra) if (CMAKE_CXX_COMPILER_ID MATCHES Clang OR CMAKE_CXX_COMPILER_ID STREQUAL GNU) diff --git a/src/crypto/fmt.h b/src/crypto/fmt.h new file mode 100644 index 000000000..5f9616e90 --- /dev/null +++ b/src/crypto/fmt.h @@ -0,0 +1,69 @@ +#pragma once + +#include +#include "crypto.h" +#include "hash.h" + +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::public_key v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::secret_key v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::key_derivation v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::key_image v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::signature v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::ed25519_public_key v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::x25519_public_key v, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(v)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::hash h, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(h)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(crypto::hash8 h, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(h)), ctx); + } +}; diff --git a/src/crypto/rx-slow-hash.c b/src/crypto/rx-slow-hash.c index 25bcf9e2a..fe4fc51d5 100644 --- a/src/crypto/rx-slow-hash.c +++ b/src/crypto/rx-slow-hash.c @@ -37,7 +37,6 @@ #include "randomx.h" #include "c_threads.h" #include "hash-ops.h" -#include "epee/misc_log_ex.h" #define RX_LOGCAT "randomx" @@ -223,7 +222,6 @@ void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const ch if (cache == NULL) { cache = randomx_alloc_cache(flags | RANDOMX_FLAG_LARGE_PAGES); if (cache == NULL) { - mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX cache"); cache = randomx_alloc_cache(flags); } if (cache == NULL) @@ -249,7 +247,6 @@ void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const ch if (rx_dataset == NULL) { rx_dataset = randomx_alloc_dataset(RANDOMX_FLAG_LARGE_PAGES); if (rx_dataset == NULL) { - mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX dataset"); rx_dataset = randomx_alloc_dataset(RANDOMX_FLAG_DEFAULT); } if (rx_dataset != NULL) @@ -262,14 +259,12 @@ void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const ch miners = 0; if (!rx_dataset_nomem) { rx_dataset_nomem = 1; - mwarning(RX_LOGCAT, "Couldn't allocate RandomX dataset for miner"); } } CTHR_MUTEX_UNLOCK(rx_dataset_mutex); } rx_vm = randomx_create_vm(flags | RANDOMX_FLAG_LARGE_PAGES, rx_sp->rs_cache, rx_dataset); if(rx_vm == NULL) { //large pages failed - mdebug(RX_LOGCAT, "Couldn't use largePages for RandomX VM"); rx_vm = randomx_create_vm(flags, rx_sp->rs_cache, rx_dataset); } if(rx_vm == NULL) {//fallback if everything fails diff --git a/src/cryptonote_basic/CMakeLists.txt b/src/cryptonote_basic/CMakeLists.txt index 15415edc0..86baa30b9 100644 --- a/src/cryptonote_basic/CMakeLists.txt +++ b/src/cryptonote_basic/CMakeLists.txt @@ -44,4 +44,5 @@ target_link_libraries(cryptonote_basic Boost::program_options Boost::serialization filesystem + logging extra) diff --git a/src/cryptonote_basic/account.cpp b/src/cryptonote_basic/account.cpp index 09076b342..d2fac1c9a 100644 --- a/src/cryptonote_basic/account.cpp +++ b/src/cryptonote_basic/account.cpp @@ -43,15 +43,13 @@ extern "C" #include "cryptonote_config.h" #include "common/meta.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "account" - using namespace std; DISABLE_VS_WARNINGS(4244 4345) namespace cryptonote { + static auto logcat = oxen::log::Cat("account"); //----------------------------------------------------------------- hw::device& account_keys::get_device() const { @@ -60,7 +58,7 @@ DISABLE_VS_WARNINGS(4244 4345) //----------------------------------------------------------------- void account_keys::set_device( hw::device &hwdev) { m_device = &hwdev; - MCDEBUG("device", "account_keys::set_device device type: " << tools::type_name(typeid(hwdev))); + oxen::log::debug(oxen::log::Cat("device"), "account_keys::set_device device type: {}", tools::type_name(typeid(hwdev))); } //----------------------------------------------------------------- static void derive_key(const crypto::chacha_key &base_key, crypto::chacha_key &key) @@ -143,7 +141,7 @@ DISABLE_VS_WARNINGS(4244 4345) try{ m_keys.get_device().disconnect(); } catch (const std::exception &e){ - MERROR("Device disconnect exception: " << e.what()); + oxen::log::error(logcat, "Device disconnect exception: {}", e.what()); } } //----------------------------------------------------------------- @@ -207,7 +205,7 @@ DISABLE_VS_WARNINGS(4244 4345) void account_base::create_from_device(hw::device &hwdev) { m_keys.set_device(hwdev); - MCDEBUG("device", "device type: " << tools::type_name(typeid(hwdev))); + oxen::log::debug(oxen::log::Cat("device"), "device type: {}", tools::type_name(typeid(hwdev))); CHECK_AND_ASSERT_THROW_MES(hwdev.init(), "Device init failed"); CHECK_AND_ASSERT_THROW_MES(hwdev.connect(), "Device connect failed"); try { diff --git a/src/cryptonote_basic/connection_context.h b/src/cryptonote_basic/connection_context.h index c08688daa..d60e83c30 100644 --- a/src/cryptonote_basic/connection_context.h +++ b/src/cryptonote_basic/connection_context.h @@ -35,6 +35,7 @@ #include "epee/net/net_utils_base.h" #include "epee/copyable_atomic.h" #include "crypto/hash.h" +#include "fmt/format.h" using namespace std::literals; @@ -92,3 +93,11 @@ namespace cryptonote } } + +template +struct fmt::formatter>> : fmt::formatter { + auto format(epee::net_utils::connection_context_base connection_context, format_context& ctx) { + return formatter::format( + fmt::format("[{}]", epee::net_utils::print_connection_context_short(connection_context)), ctx); + } +}; diff --git a/src/cryptonote_basic/cryptonote_basic.h b/src/cryptonote_basic/cryptonote_basic.h index 16dc09063..4bb3e6503 100644 --- a/src/cryptonote_basic/cryptonote_basic.h +++ b/src/cryptonote_basic/cryptonote_basic.h @@ -45,6 +45,8 @@ #include "ringct/rctTypes.h" #include "device/device.hpp" #include "txtypes.h" +#include "logging/oxen_logger.h" +#include namespace service_nodes { @@ -226,7 +228,7 @@ namespace cryptonote { if (out_index >= output_unlock_times.size()) { - LOG_ERROR("Tried to get unlock time of a v3 transaction with missing output unlock time"); + oxen::log::error(globallogcat, "Tried to get unlock time of a v3 transaction with missing output unlock time"); return unlock_time; } return output_unlock_times[out_index]; @@ -603,6 +605,21 @@ namespace cryptonote } } +template <> +struct fmt::formatter : fmt::formatter { + auto format(cryptonote::txtype t, format_context& ctx) { + return formatter::format( + fmt::format("{}", cryptonote::transaction::type_to_string(t)), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(cryptonote::txversion v, format_context& ctx) { + return formatter::format( + fmt::format("{}", cryptonote::transaction::version_to_string(v)), ctx); + } +}; + namespace std { template <> struct hash diff --git a/src/cryptonote_basic/cryptonote_basic_impl.cpp b/src/cryptonote_basic/cryptonote_basic_impl.cpp index fbe76885b..cd7fc3227 100644 --- a/src/cryptonote_basic/cryptonote_basic_impl.cpp +++ b/src/cryptonote_basic/cryptonote_basic_impl.cpp @@ -39,13 +39,13 @@ #include "crypto/hash.h" #include "epee/int-util.h" #include "common/oxen.h" +#include "logging/oxen_logger.h" #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "cn" - namespace cryptonote { + static auto logcat = oxen::log::Cat("cn"); + struct integrated_address { account_public_address adr; crypto::hash8 payment_id; @@ -133,7 +133,7 @@ namespace cryptonote { } if(current_block_weight > 2 * median_weight) { - MERROR("Block cumulative weight is too big: " << current_block_weight << ", expected less than " << 2 * median_weight); + oxen::log::error(logcat, "Block cumulative weight is too big: {}, expected less than {}", current_block_weight, 2 * median_weight); return false; } @@ -225,7 +225,7 @@ namespace cryptonote { uint64_t prefix{0}; if (!tools::base58::decode_addr(str, prefix, data)) { - LOG_PRINT_L2("Invalid address format"); + oxen::log::debug(logcat, "Invalid address format"); return false; } @@ -245,9 +245,7 @@ namespace cryptonote { info.has_payment_id = false; } else { - LOG_PRINT_L1("Wrong address prefix: " << prefix << ", expected " << address_prefix - << " or " << integrated_address_prefix - << " or " << subaddress_prefix); + oxen::log::info(logcat, "Wrong address prefix: {}, expected {} or {} or {}", prefix, address_prefix, integrated_address_prefix, subaddress_prefix); return false; } @@ -264,13 +262,13 @@ namespace cryptonote { serialization::parse_binary(data, info.address); } } catch (const std::exception& e) { - LOG_PRINT_L1("Account public address keys can't be parsed: "s + e.what()); + oxen::log::info(logcat, "Account public address keys can't be parsed: "s + e.what()); return false; } if (!crypto::check_key(info.address.m_spend_public_key) || !crypto::check_key(info.address.m_view_public_key)) { - LOG_PRINT_L1("Failed to validate address keys"); + oxen::log::info(logcat, "Failed to validate address keys"); return false; } diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index 05bf3ac2b..5bf22ac62 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -46,20 +46,21 @@ #include "cryptonote_config.h" #include "crypto/crypto.h" #include "crypto/hash.h" +#include "crypto/fmt.h" #include "ringct/rctSigs.h" #include "cryptonote_basic/verification_context.h" #include "cryptonote_core/service_node_voting.h" #include "cryptonote_core/oxen_name_system.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "cn" +#include using namespace crypto; -#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}} +#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {oxen::log::warning(logcat, message); throw std::runtime_error(message);}} namespace cryptonote { + static auto logcat = oxen::log::Cat("cn"); + static inline unsigned char *operator &(ec_point &point) { return &reinterpret_cast(point); } @@ -134,14 +135,14 @@ namespace cryptonote return true; if (rv.outPk.size() != tx.vout.size()) { - LOG_PRINT_L1("Failed to parse transaction from blob, bad outPk size in tx " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Failed to parse transaction from blob, bad outPk size in tx {}", get_transaction_hash(tx)); return false; } for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n) { if (!std::holds_alternative(tx.vout[n].target)) { - LOG_PRINT_L1("Unsupported output type in tx " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Unsupported output type in tx {}", get_transaction_hash(tx)); return false; } rv.outPk[n].dest = rct::pk2rct(var::get(tx.vout[n].target).key); @@ -154,18 +155,18 @@ namespace cryptonote { if (rv.p.bulletproofs.size() != 1) { - LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs size in tx " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs size in tx {}", get_transaction_hash(tx)); return false; } if (rv.p.bulletproofs[0].L.size() < 6) { - LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs L size in tx " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs L size in tx {}", get_transaction_hash(tx)); return false; } const size_t max_outputs = 1 << (rv.p.bulletproofs[0].L.size() - 6); if (max_outputs < tx.vout.size()) { - LOG_PRINT_L1("Failed to parse transaction from blob, bad bulletproofs max outputs in tx " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs max outputs in tx {}", get_transaction_hash(tx)); return false; } const size_t n_amounts = tx.vout.size(); @@ -196,7 +197,7 @@ namespace cryptonote try { serialization::serialize(ba, tx); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse and validate transaction from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse and validate transaction from blob: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data"); @@ -211,7 +212,7 @@ namespace cryptonote try { tx.serialize_base(ba); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse transaction base from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse transaction base from blob: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, "Failed to expand transaction data"); @@ -225,7 +226,7 @@ namespace cryptonote try { serialization::value(ba, tx); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse transaction prefix from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse transaction prefix from blob: {}", e.what()); return false; } return true; @@ -237,7 +238,7 @@ namespace cryptonote try { serialization::serialize(ba, tx); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse and validate transaction from blob + hash: " << e.what()); + oxen::log::error(logcat, "Failed to parse and validate transaction from blob + hash: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data"); @@ -269,7 +270,7 @@ namespace cryptonote bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); if (!r) { - MWARNING("key image helper: failed to generate_key_derivation(" << tx_public_key << ", " << ack.m_view_secret_key << ")"); + oxen::log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", tx_public_key, ack.m_view_secret_key); memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation)); } @@ -280,7 +281,7 @@ namespace cryptonote r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); if (!r) { - MWARNING("key image helper: failed to generate_key_derivation(" << additional_tx_public_keys[i] << ", " << ack.m_view_secret_key << ")"); + oxen::log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], ack.m_view_secret_key); } else { @@ -527,7 +528,7 @@ namespace cryptonote try { serialization::deserialize_all(ar, tx_extra_fields); } catch (const std::exception& e) { - MWARNING(__func__ << ": failed to deserialize extra field: " << e.what() << "; extra = " << oxenc::to_hex(tx_extra.begin(), tx_extra.end())); + oxen::log::warning(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); return false; } @@ -548,7 +549,7 @@ namespace cryptonote for (auto& f : tx_extra_fields) serialization::value(ar, f); } catch (const std::exception& e) { - LOG_PRINT_L1("failed to serialize tx extra field: " << e.what()); + oxen::log::info(logcat, "failed to serialize tx extra field: {}", e.what()); return false; } @@ -608,8 +609,11 @@ namespace cryptonote bool add_additional_tx_pub_keys_to_extra(std::vector& tx_extra, const std::vector& additional_pub_keys) { tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys }; - bool r = add_tx_extra_field_to_tx_extra(tx_extra, field); - CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to serialize tx extra additional tx pub keys"); + if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) + { + oxen::log::info(logcat, "failed to serialize tx extra additional tx pub keys"); + return false; + } return true; } //--------------------------------------------------------------- @@ -678,17 +682,24 @@ namespace cryptonote bool add_tx_key_image_proofs_to_tx_extra(std::vector& tx_extra, const tx_extra_tx_key_image_proofs& proofs) { tx_extra_field field = proofs; - bool result = add_tx_extra_field_to_tx_extra(tx_extra, field); - CHECK_AND_NO_ASSERT_MES_L1(result, false, "failed to serialize tx extra tx key image proof"); - return result; + if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) + { + oxen::log::info(logcat, "failed to serialize tx extra tx key image proof"); + return false; + } + + return true; } //--------------------------------------------------------------- bool add_tx_key_image_unlock_to_tx_extra(std::vector& tx_extra, const tx_extra_tx_key_image_unlock& unlock) { tx_extra_field field = unlock; - bool result = add_tx_extra_field_to_tx_extra(tx_extra, field); - CHECK_AND_NO_ASSERT_MES_L1(result, false, "failed to serialize tx extra tx key image unlock"); - return result; + if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) + { + oxen::log::info(logcat, "failed to serialize tx extra tx key image unlock"); + return false; + } + return true; } //--------------------------------------------------------------- bool get_service_node_contributor_from_tx_extra(const std::vector& tx_extra, cryptonote::account_public_address& address) @@ -718,8 +729,12 @@ namespace cryptonote txreg.hf_or_expiration = reg.hf; txreg.signature = reg.signature; - bool r = add_tx_extra_field_to_tx_extra(tx_extra, field); - CHECK_AND_NO_ASSERT_MES_L1(r, false, "failed to serialize tx extra registration tx"); + if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) + { + oxen::log::info(logcat, "failed to serialize tx extra registration tx"); + return false; + } + return true; } //--------------------------------------------------------------- @@ -779,7 +794,7 @@ namespace cryptonote value(newar, field); } while (ar.remaining_bytes() > 0); } catch (const std::exception& e) { - LOG_PRINT_L1(__func__ << ": failed to deserialize extra field: " << e.what() << "; extra = " << oxenc::to_hex(tx_extra.begin(), tx_extra.end())); + oxen::log::info(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); return false; } @@ -837,9 +852,12 @@ namespace cryptonote bool add_burned_amount_to_tx_extra(std::vector& tx_extra, uint64_t burn) { tx_extra_field field = tx_extra_burn{burn}; - bool result = add_tx_extra_field_to_tx_extra(tx_extra, field); - CHECK_AND_NO_ASSERT_MES_L1(result, false, "failed to serialize tx extra burn amount"); - return result; + if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) + { + oxen::log::info(logcat, "failed to serialize tx extra burn amount"); + return false; + } + return true; } //--------------------------------------------------------------- bool get_inputs_money_amount(const transaction& tx, uint64_t& money) @@ -883,14 +901,17 @@ namespace cryptonote //----------------------------------------------------------------------------------------------- bool check_outs_valid(const transaction& tx) { - if (!tx.is_transfer()) + if (!tx.is_transfer() && tx.vout.size() != 0) { - CHECK_AND_NO_ASSERT_MES(tx.vout.size() == 0, false, "tx type: " << tx.type << " must have 0 outputs, received: " << tx.vout.size() << ", id=" << get_transaction_hash(tx)); + oxen::log::warning(logcat, "tx type: {} must have 0 outputs, received: {}, id={}", transaction::type_to_string(tx.type), tx.vout.size(), get_transaction_hash(tx)); + return false; } - if (tx.version >= txversion::v3_per_output_unlock_times) + if (tx.version >= txversion::v3_per_output_unlock_times && tx.vout.size() != tx.output_unlock_times.size()) { - CHECK_AND_NO_ASSERT_MES(tx.vout.size() == tx.output_unlock_times.size(), false, "tx version: " << tx.version << "must have equal number of output unlock times and outputs"); + oxen::log::warning(logcat, "tx version: {} must have equal number of output unlock times and outputs", transaction::version_to_string(tx.version)); + return false; + } for(const tx_out& out: tx.vout) @@ -901,7 +922,11 @@ namespace cryptonote if (tx.version == txversion::v1) { - CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, "zero amount output in transaction id=" << get_transaction_hash(tx)); + if (out.amount <= 0) + { + oxen::log::warning(logcat, "zero amount output in transaction id={}", get_transaction_hash(tx)); + return false; + } } if(!check_key(var::get(out.target).key)) @@ -1202,7 +1227,7 @@ namespace cryptonote const_cast(t).rct_signatures.p.serialize_rctsig_prunable( ba, t.rct_signatures.type, t.vin.size(), t.vout.size(), mixin); } catch (const std::exception& e) { - LOG_ERROR("Failed to serialize rct signatures (prunable): " << e.what()); + oxen::log::error(logcat, "Failed to serialize rct signatures (prunable): {}", e.what()); return false; } cryptonote::get_blob_hash(ba.str(), res); @@ -1289,7 +1314,7 @@ namespace cryptonote try { tt.rct_signatures.serialize_rctsig_base(ba, t.vin.size(), t.vout.size()); } catch (const std::exception& e) { - LOG_ERROR("Failed to serialize rct signatures base: " << e.what()); + oxen::log::error(logcat, "Failed to serialize rct signatures base: {}", e.what()); return false; } cryptonote::get_blob_hash(ba.str(), hashes[1]); @@ -1302,7 +1327,7 @@ namespace cryptonote } else if (!calculate_transaction_prunable_hash(t, &blob, hashes[2])) { - LOG_ERROR("Failed to get tx prunable hash"); + oxen::log::error(logcat, "Failed to get tx prunable hash"); return false; } @@ -1422,7 +1447,7 @@ namespace cryptonote try { serialization::serialize(ba, b); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse block from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse block from blob: {}", e.what()); return false; } b.invalidate_hashes(); diff --git a/src/cryptonote_basic/cryptonote_format_utils.h b/src/cryptonote_basic/cryptonote_format_utils.h index 9471069bf..f54c1b4e3 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.h +++ b/src/cryptonote_basic/cryptonote_format_utils.h @@ -38,6 +38,7 @@ #include "common/meta.h" #include "common/string_util.h" #include "serialization/binary_utils.h" +#include "logging/oxen_logger.h" #include namespace epee @@ -272,7 +273,7 @@ namespace cryptonote blob = serialization::dump_binary(const_cast&>(val)); return true; } catch (const std::exception& e) { - LOG_ERROR("Serialization of " << tools::type_name(typeid(T)) << " failed: " << e.what()); + oxen::log::error(globallogcat, "Serialization of {} failed: {}", tools::type_name(typeid(T)), e.what()); return false; } } @@ -317,7 +318,7 @@ namespace cryptonote try { serialize(ar, obj); } catch (const std::exception& e) { - LOG_ERROR("obj_to_json_str failed: serialization failed: " << e.what()); + oxen::log::error(globallogcat, "obj_to_json_str failed: serialization failed: {}", e.what()); return ""s; } return ss.str(); diff --git a/src/cryptonote_basic/miner.cpp b/src/cryptonote_basic/miner.cpp index 573ec7997..5587b1845 100644 --- a/src/cryptonote_basic/miner.cpp +++ b/src/cryptonote_basic/miner.cpp @@ -39,9 +39,9 @@ #include "common/string_util.h" #include "epee/string_tools.h" #include "epee/storages/portable_storage_template_helper.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "miner" +#include +#include +#include #define AUTODETECT_WINDOW 10 // seconds #define AUTODETECT_GAIN_THRESHOLD 1.02f // 2% @@ -53,6 +53,7 @@ extern "C" void rx_slow_hash_free_state(); namespace cryptonote { + static auto logcat = oxen::log::Cat("miner"); namespace { @@ -102,7 +103,7 @@ namespace cryptonote if(!m_phandler->create_next_miner_block_template(bl, m_mine_address, di, height, expected_reward, ""s)) { - LOG_ERROR("Failed to get_block_template(), stopping mining"); + oxen::log::error(logcat, "Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di, height, expected_reward); @@ -147,7 +148,7 @@ namespace cryptonote address_parse_info info; if(!cryptonote::get_account_address_from_str(info, nettype, command_line::get_arg(vm, arg_start_mining)) || info.is_subaddress) { - LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled"); + oxen::log::error(logcat, "Target account address {} has wrong format, starting daemon canceled", command_line::get_arg(vm, arg_start_mining)); return false; } m_mine_address = info.address; @@ -184,13 +185,13 @@ namespace cryptonote std::unique_lock lock{m_threads_lock}; if(is_mining()) { - LOG_ERROR("Starting miner but it's already started"); + oxen::log::error(logcat, "Starting miner but it's already started"); return false; } if(!m_threads.empty()) { - LOG_ERROR("Unable to start miner because there are active mining threads"); + oxen::log::error(logcat, "Unable to start miner because there are active mining threads"); return false; } @@ -199,12 +200,12 @@ namespace cryptonote m_stop = false; m_stop_height = stop_after > 0 ? m_height + stop_after : std::numeric_limits::max(); if (stop_after > 0) - MGINFO("Mining until height " << m_stop_height); + oxen::log::info(logcat, "Mining until height {}", m_stop_height); for (int i = 0; i < m_threads_total; i++) m_threads.emplace_back([=] { return worker_thread(i, slow_mining); }); - MINFO("Mining has started with " << m_threads_total << " threads, good luck!" ); + oxen::log::info(logcat, "Mining has started with {} threads, good luck!", m_threads_total); return true; } @@ -222,13 +223,13 @@ namespace cryptonote //----------------------------------------------------------------------------------------------------- bool miner::stop() { - MTRACE("Miner has received stop signal"); + oxen::log::trace(logcat, "Miner has received stop signal"); std::unique_lock lock{m_threads_lock}; bool mining = !m_threads.empty(); if (!mining) { - MTRACE("Not mining - nothing to stop" ); + oxen::log::trace(logcat, "Not mining - nothing to stop" ); return true; } @@ -237,7 +238,7 @@ namespace cryptonote if (th.joinable()) th.join(); - MINFO("Mining has been stopped, " << m_threads.size() << " finished" ); + oxen::log::info(logcat, "Mining has been stopped, {} finished", m_threads.size()); m_threads.clear(); rx_stop_mining(); return true; @@ -271,30 +272,29 @@ namespace cryptonote void miner::pause() { std::unique_lock lock{m_miners_count_mutex}; - MDEBUG("miner::pause: " << m_pausers_count << " -> " << (m_pausers_count + 1)); + oxen::log::debug(logcat, "miner::pause: {} -> {}", m_pausers_count, (m_pausers_count + 1)); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) - MDEBUG("MINING PAUSED"); + oxen::log::debug(logcat, "MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { std::unique_lock lock{m_miners_count_mutex}; - MDEBUG("miner::resume: " << m_pausers_count << " -> " << (m_pausers_count - 1)); + oxen::log::debug(logcat, "miner::resume: {} -> {}", m_pausers_count, (m_pausers_count - 1)); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; - MERROR("Unexpected miner::resume() called"); + oxen::log::error(logcat, "Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) - MDEBUG("MINING RESUMED"); + oxen::log::debug(logcat, "MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread(uint32_t index, bool slow_mining) { - MLOG_SET_THREAD_NAME(std::string("[miner ") + std::to_string(index) + "]"); - MGINFO("Miner thread was started ["<< index << "]"); + oxen::log::info(logcat, "Miner thread was started [{}]", index); uint32_t nonce = m_starter_nonce + index; uint64_t height = 0; difficulty_type local_diff = 0; @@ -325,7 +325,7 @@ namespace cryptonote if(!local_template_ver)//no any set_block_template call { - LOG_PRINT_L2("Block template not set yet"); + oxen::log::debug(logcat, "Block template not set yet"); std::this_thread::sleep_for(1s); continue; } @@ -345,7 +345,7 @@ namespace cryptonote if(check_hash(h, local_diff)) { //we lucky! - MGINFO_GREEN("Found block " << get_block_hash(b) << " at height " << height << " for difficulty: " << local_diff); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Found block {} at height {} for difficulty: {}", get_block_hash(b), height, local_diff)); cryptonote::block_verification_context bvc; m_phandler->handle_block_found(b, bvc); } @@ -354,7 +354,7 @@ namespace cryptonote ++m_hashes; } rx_slow_hash_free_state(); - MGINFO("Miner thread stopped ["<< index << "]"); + oxen::log::info(logcat, "Miner thread stopped [{}]", index); if (call_stop) // Call in a detached thread because the thread calling stop() needs to be able to join this // worker thread. diff --git a/src/cryptonote_core/CMakeLists.txt b/src/cryptonote_core/CMakeLists.txt index f2725b7dc..187d856b4 100644 --- a/src/cryptonote_core/CMakeLists.txt +++ b/src/cryptonote_core/CMakeLists.txt @@ -58,6 +58,7 @@ target_link_libraries(cryptonote_core Boost::program_options SQLiteCpp systemd + logging extra) if(PER_BLOCK_CHECKPOINT) diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index e9cc5429c..a4c3dd3e2 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -35,6 +35,8 @@ #include #include #include +#include +#include #include "common/rules.h" #include "common/hex.h" @@ -59,7 +61,6 @@ #include "crypto/hash.h" #include "cryptonote_core.h" #include "ringct/rctSigs.h" -#include "common/perf_timer.h" #include "service_node_voting.h" #include "service_node_list.h" #include "common/varint.h" @@ -67,6 +68,7 @@ #include "common/lock.h" #include "common/meta.h" #include "common/sha256sum.h" +#include "logging/oxen_logger.h" #ifdef ENABLE_SYSTEMD extern "C" { @@ -74,9 +76,6 @@ extern "C" { } #endif -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "blockchain" - #define FIND_BLOCKCHAIN_SUPPLEMENT_MAX_SIZE (100*1024*1024) // 100 MB using namespace crypto; @@ -91,9 +90,10 @@ using namespace crypto; using namespace cryptonote; -DISABLE_VS_WARNINGS(4267) +static auto logcat = oxen::log::Cat("blockchain"); -#define MERROR_VER(x) MCERROR("verify", x) + +DISABLE_VS_WARNINGS(4267) // used to overestimate the block reward when estimating a per kB to use #define BLOCK_REWARD_OVERESTIMATE (10 * 1000000000000) @@ -124,7 +124,7 @@ Blockchain::Blockchain(tx_memory_pool& tx_pool, service_nodes::service_node_list m_batch_success(true), m_prepare_height(0) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); } //------------------------------------------------------------------ Blockchain::~Blockchain() @@ -135,7 +135,7 @@ Blockchain::~Blockchain() //------------------------------------------------------------------ bool Blockchain::have_tx(const crypto::hash &id) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -145,7 +145,7 @@ bool Blockchain::have_tx(const crypto::hash &id) const //------------------------------------------------------------------ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -159,7 +159,7 @@ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const template bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, visitor_t &vis, const crypto::hash &tx_prefix_hash, uint64_t* pmax_related_block_height) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // ND: Disable locking and make method private. //std::unique_lock lock{*this}; @@ -194,13 +194,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi m_db->get_output_key(epee::span(&tx_in_to_key.amount, 1), absolute_offsets, outputs, true); if (absolute_offsets.size() != outputs.size()) { - MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } catch (...) { - MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } @@ -209,7 +209,7 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi // check for partial results and add the rest if needed; if (outputs.size() < absolute_offsets.size() && outputs.size() > 0) { - MDEBUG("Additional outputs needed: " << absolute_offsets.size() - outputs.size()); + oxen::log::debug(logcat, "Additional outputs needed: {}", absolute_offsets.size() - outputs.size()); std::vector < uint64_t > add_offsets; std::vector add_outputs; add_outputs.reserve(absolute_offsets.size() - outputs.size()); @@ -220,13 +220,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi m_db->get_output_key(epee::span(&tx_in_to_key.amount, 1), add_offsets, add_outputs, true); if (add_offsets.size() != add_outputs.size()) { - MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } catch (...) { - MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end()); @@ -250,13 +250,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi // call to the passed boost visitor to grab the public key for the output if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment)) { - MERROR_VER("Failed to handle_output for output no = " << count << ", with absolute offset " << i); + oxen::log::error(oxen::log::Cat("verify"), "Failed to handle_output for output no = {}, with absolute offset {}", count, i); return false; } } catch (...) { - MERROR_VER("Output does not exist! amount = " << tx_in_to_key.amount << ", absolute_offset = " << i); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}, absolute_offset = {}", tx_in_to_key.amount, i); return false; } @@ -274,12 +274,12 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi } catch (const OUTPUT_DNE& e) { - MERROR_VER("Output does not exist: " << e.what()); + oxen::log::error(oxen::log::Cat("verify"), "Output does not exist: {}", e.what()); return false; } catch (const TX_DNE& e) { - MERROR_VER("Transaction does not exist: " << e.what()); + oxen::log::error(oxen::log::Cat("verify"), "Transaction does not exist: {}", e.what()); return false; } @@ -290,7 +290,7 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi //------------------------------------------------------------------ uint64_t Blockchain::get_current_blockchain_height(bool lock) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -329,7 +329,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() int64_t const total_blocks = static_cast(end_height) - static_cast(start_height); if (total_blocks <= 0) return true; if (total_blocks > 1) - MGINFO("Loading blocks into oxen subsystems, scanning blockchain from height: " << start_height << " to: " << end_height << " (snl: " << snl_height << ", ons: " << ons_height << ", sqlite: " << sqlite_height << ")"); + oxen::log::info(logcat, "Loading blocks into oxen subsystems, scanning blockchain from height: {} to: {} (snl: {}, ons: {}, sqlite: {})", start_height, end_height, snl_height, ons_height, sqlite_height); using clock = std::chrono::steady_clock; using dseconds = std::chrono::duration; @@ -347,12 +347,12 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() if (duration >= 10s) { m_service_node_list.store(); - MGINFO(fmt::format("... scanning height {} ({:.3f}s) (snl: {:.3f}s, ons: {:.3f}s, batch: {:.3f}s)", + oxen::log::info(logcat, "... scanning height {} ({:.3f}s) (snl: {:.3f}s, ons: {:.3f}s, batch: {:.3f}s)", start_height + (index * BLOCK_COUNT), duration.count(), snl_iteration_duration.count(), ons_iteration_duration.count(), - sqlite_iteration_duration.count())); + sqlite_iteration_duration.count()); #ifdef ENABLE_SYSTEMD // Tell systemd that we're doing something so that it should let us continue starting up // (giving us 120s until we have to send the next notification): @@ -372,7 +372,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() uint64_t height = start_height + (index * BLOCK_COUNT); if (!get_blocks_only(height, static_cast(BLOCK_COUNT), blocks)) { - LOG_ERROR("Unable to get checkpointed historical blocks for updating oxen subsystems"); + oxen::log::error(logcat, "Unable to get checkpointed historical blocks for updating oxen subsystems"); return false; } @@ -383,7 +383,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() std::vector txs; if (!get_transactions(blk.tx_hashes, txs)) { - MERROR("Unable to get transactions for block for updating ONS DB: " << cryptonote::get_block_hash(blk)); + oxen::log::error(logcat, "Unable to get transactions for block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); return false; } @@ -399,7 +399,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() try { m_service_node_list.block_add(blk, txs, checkpoint_ptr); } catch (const std::exception& e) { - MFATAL("Unable to process block {} for updating service node list: " << e.what()); + oxen::log::error(logcat, "Unable to process block for updating service node list: {}", e.what()); return false; } snl_iteration_duration += clock::now() - snl_start; @@ -410,7 +410,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() auto ons_start = clock::now(); if (!m_ons_db.add_block(blk, txs)) { - MFATAL("Unable to process block for updating ONS DB: " << cryptonote::get_block_hash(blk)); + oxen::log::error(logcat, "Unable to process block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); return false; } ons_iteration_duration += clock::now() - ons_start; @@ -421,7 +421,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() auto sqlite_start = clock::now(); if (!m_service_node_list.process_batching_rewards(blk)) { - MFATAL("Unable to process block for updating SQLite DB: " << cryptonote::get_block_hash(blk)); + oxen::log::error(logcat, "Unable to process block for updating SQLite DB: {}", cryptonote::get_block_hash(blk)); return false; } sqlite_iteration_duration += clock::now() - sqlite_start; @@ -431,8 +431,8 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() if (total_blocks > 1) { - MGINFO(fmt::format("Done recalculating oxen subsystems in {:.2f}s ({:.2f}s snl; {:.2f}s ons; {:.2f}s batch)", - dseconds{clock::now() - scan_start}.count(), snl_duration.count(), ons_duration.count(), sqlite_duration.count())); + oxen::log::info(logcat, "Done recalculating oxen subsystems in {:.2f}s ({:.2f}s snl; {:.2f}s ons; {:.2f}s batch)", + dseconds{clock::now() - scan_start}.count(), snl_duration.count(), ons_duration.count(), sqlite_duration.count()); } if (total_blocks > 0) @@ -446,7 +446,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptr sqlite_db, const network_type nettype, bool offline, const cryptonote::test_options *test_options, difficulty_type fixed_difficulty, const GetCheckpointsCallback& get_checkpoints/* = nullptr*/) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); CHECK_AND_ASSERT_MES(nettype != network_type::FAKECHAIN || test_options, false, "fake chain network type used without options"); @@ -454,12 +454,12 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptris_open()) { - LOG_ERROR("Attempted to init Blockchain with unopened DB"); + oxen::log::error(logcat, "Attempted to init Blockchain with unopened DB"); delete db; return false; } @@ -490,7 +490,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrheight()) { - MINFO("Blockchain not loaded, generating genesis block."); + oxen::log::info(logcat, "Blockchain not loaded, generating genesis block."); block bl; block_verification_context bvc{}; generate_genesis_block(bl, m_nettype); @@ -527,7 +527,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrheight() - 1 << ", " << epee::misc_utils::get_time_interval_string(timestamp_diff) << " time ago"); + oxen::log::info(logcat, "Blockchain initialized. last block: {}, {} time ago", m_db->height() - 1, epee::misc_utils::get_time_interval_string(timestamp_diff)); rtxn_guard.stop(); uint64_t num_popped_blocks = 0; @@ -540,15 +540,15 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptr 0) - MGINFO("Initial popping done, top block: " << top_id << ", top height: " << top_height << ", block version: " << (uint64_t)top_block.major_version); + oxen::log::info(logcat, "Initial popping done, top block: {}, top height: {}, block version: {}", top_id, top_height, (uint64_t)top_block.major_version); break; } else { if (num_popped_blocks == 0) - MGINFO("Current top block " << top_id << " at height " << top_height << " has version " << (uint64_t)top_block.major_version << " which disagrees with the ideal version " << (uint64_t)ideal_hf_version); + oxen::log::info(logcat, "Current top block {} at height {} has version {} which disagrees with the ideal version {}", top_id, top_height, (uint64_t)top_block.major_version, (uint64_t)ideal_hf_version); if (num_popped_blocks % 100 == 0) - MGINFO("Popping blocks... " << top_height); + oxen::log::info(logcat, "Popping blocks... {}", top_height); ++num_popped_blocks; block popped_block; std::vector popped_txs; @@ -557,7 +557,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrpop_block(popped_block, popped_txs); if (!m_service_node_list.pop_batching_rewards_block(popped_block)) { - LOG_ERROR("Failed to pop to batch rewards DB. throwing"); + oxen::log::error(logcat, "Failed to pop to batch rewards DB. throwing"); throw std::runtime_error("Failed to pop to batch reward DB."); } } @@ -565,12 +565,12 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptris_read_only() && !load_missing_blocks_into_oxen_subsystems()) { - MFATAL("Failed to load blocks into oxen subsystems"); + oxen::log::error(logcat, "Failed to load blocks into oxen subsystems"); return false; } @@ -616,7 +616,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrclose(); - MTRACE("Local blockchain read/write activity stopped successfully"); + oxen::log::trace(logcat, "Local blockchain read/write activity stopped successfully"); } } catch (const std::exception& e) { - LOG_ERROR(std::string("Error closing blockchain db: ") + e.what()); + oxen::log::error(logcat, std::string("Error closing blockchain db: ") + e.what()); } catch (...) { - LOG_ERROR("There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); + oxen::log::error(logcat, "There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); } delete m_db; @@ -685,7 +685,6 @@ void Blockchain::pop_blocks(uint64_t nblocks) { uint64_t i = 0; auto lock = tools::unique_locks(m_tx_pool, *this); - bool stop_batch = m_db->batch_start(); bool pop_batching_rewards; @@ -698,21 +697,24 @@ void Blockchain::pop_blocks(uint64_t nblocks) uint64_t constexpr PERCENT_PER_PROGRESS_UPDATE = 10; uint64_t const blocks_per_update = (nblocks / PERCENT_PER_PROGRESS_UPDATE); - tools::PerformanceTimer timer; pop_batching_rewards = m_service_node_list.state_history_exists(blockchain_height - nblocks); + std::chrono::steady_clock::time_point pop_blocks_started = std::chrono::steady_clock::now(); for (int progress = 0; i < nblocks; ++i) { if (nblocks >= BLOCKS_PER_DAY && (i != 0 && (i % blocks_per_update == 0))) { - MGINFO("... popping blocks " << (++progress * PERCENT_PER_PROGRESS_UPDATE) << "% completed, height: " << (blockchain_height - i) << " (" << tools::friendly_duration(timer.value()) << "s)"); - timer.reset(); + oxen::log::info(logcat, "... popping blocks {}% completed, height: {} ({}s)", + (++progress * PERCENT_PER_PROGRESS_UPDATE), (blockchain_height - i), + std::chrono::duration{std::chrono::steady_clock::now() - pop_blocks_started}.count() + ); + pop_blocks_started = std::chrono::steady_clock::now(); } pop_block_from_blockchain(pop_batching_rewards); } } catch (const std::exception& e) { - LOG_ERROR("Error when popping blocks after processing " << i << " blocks: " << e.what()); + oxen::log::error(logcat, "Error when popping blocks after processing {} blocks: {}", i, e.what()); if (stop_batch) m_db->batch_abort(); return; @@ -734,7 +736,7 @@ void Blockchain::pop_blocks(uint64_t nblocks) // from it to the tx_pool block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; @@ -753,18 +755,18 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) // so we re-throw catch (const std::exception& e) { - LOG_ERROR("Error popping block from blockchain: " << e.what()); + oxen::log::error(logcat, "Error popping block from blockchain: {}", e.what()); throw; } catch (...) { - LOG_ERROR("Error popping block from blockchain, throwing!"); + oxen::log::error(logcat, "Error popping block from blockchain, throwing!"); throw; } if (pop_batching_rewards && !m_service_node_list.pop_batching_rewards_block(popped_block)) { - LOG_ERROR("Failed to pop to batch rewards DB"); + oxen::log::error(logcat, "Failed to pop to batch rewards DB"); throw std::runtime_error("Failed to pop batch rewards DB"); } @@ -793,12 +795,12 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) bool r = m_tx_pool.add_tx(tx, tvc, tx_pool_options::from_block(), version); if (!r) { - LOG_ERROR("Error returning transaction to tx_pool"); + oxen::log::error(logcat, "Error returning transaction to tx_pool"); } } } if (pruned) - MWARNING(pruned << " pruned txes could not be added back to the txpool"); + oxen::log::warning(logcat, "{} pruned txes could not be added back to the txpool", pruned); m_blocks_longhash_table.clear(); m_scan_table.clear(); @@ -812,7 +814,7 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) //------------------------------------------------------------------ bool Blockchain::reset_and_set_genesis_block(const block& b) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; invalidate_block_template_cache(); @@ -832,14 +834,14 @@ bool Blockchain::reset_and_set_genesis_block(const block& b) //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id(uint64_t& height) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; return m_db->top_block_hash(&height); } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -857,7 +859,7 @@ crypto::hash Blockchain::get_tail_id() const */ void Blockchain::get_short_chain_history(std::list& ids) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t sz = m_db->height(); if(!sz) @@ -875,7 +877,7 @@ void Blockchain::get_short_chain_history(std::list& ids) const //------------------------------------------------------------------ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -889,12 +891,12 @@ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const } catch (const std::exception& e) { - MERROR(std::string("Something went wrong fetching block hash by height: ") + e.what()); + oxen::log::error(logcat, std::string("Something went wrong fetching block hash by height: ") + e.what()); throw; } catch (...) { - MERROR(std::string("Something went wrong fetching block hash by height")); + oxen::log::error(logcat, std::string("Something went wrong fetching block hash by height")); throw; } return null_hash; @@ -909,7 +911,7 @@ crypto::hash Blockchain::get_pending_block_id_by_height(uint64_t height) const //------------------------------------------------------------------ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // try to find block in main chain @@ -929,7 +931,7 @@ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orph { if (!cryptonote::parse_and_validate_block_from_blob(blob, blk)) { - MERROR("Found block " << h << " in alt chain, but failed to parse it"); + oxen::log::error(logcat, "Found block {} in alt chain, but failed to parse it", h); throw std::runtime_error("Found block in alt chain, but failed to parse it"); } if (orphan) @@ -939,12 +941,12 @@ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orph } catch (const std::exception& e) { - MERROR(std::string("Something went wrong fetching block by hash: ") + e.what()); + oxen::log::error(logcat, std::string("Something went wrong fetching block by hash: ") + e.what()); throw; } catch (...) { - MERROR(std::string("Something went wrong fetching block hash by hash")); + oxen::log::error(logcat, std::string("Something went wrong fetching block hash by hash")); throw; } @@ -968,7 +970,7 @@ bool Blockchain::get_block_by_height(uint64_t height, block &blk) const // less blocks than desired if there aren't enough. difficulty_type Blockchain::get_difficulty_for_next_block(bool pulse) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); if (m_fixed_difficulty) { return m_db->height() ? m_fixed_difficulty : 1; @@ -1028,7 +1030,7 @@ std::vector Blockchain::get_last_block_timestamps(unsigned int blocks) c // that had been removed. bool Blockchain::rollback_blockchain_switching(const std::list& original_chain, uint64_t rollback_height) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // fail if rollback_height passed is too high @@ -1059,10 +1061,10 @@ bool Blockchain::rollback_blockchain_switching(const std::listbatch_start(); - MDEBUG("Rolling back to height " << rollback_height); + oxen::log::debug(logcat, "Rolling back to height {}", rollback_height); bool ret = rollback_blockchain_switching({}, rollback_height); if (stop_batch) m_db->batch_stop(); @@ -1082,7 +1084,7 @@ bool Blockchain::blink_rollback(uint64_t rollback_height) // boolean based on success therein. bool Blockchain::switch_to_alternative_blockchain(const std::list& alt_chain, bool keep_disconnected_chain) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; @@ -1093,7 +1095,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listblock_exists(alt_chain.front().bl.prev_id)) { - LOG_ERROR("Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); + oxen::log::error(logcat, "Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); return false; } @@ -1127,7 +1129,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listremove_alt_block(blkid); alt_ch_iter++; @@ -1157,7 +1159,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listheight()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "REORGANIZE SUCCESS! on height: {}, new blockchain size: {}", split_height, m_db->height())); return true; } //------------------------------------------------------------------ @@ -1195,7 +1197,7 @@ difficulty_type Blockchain::get_difficulty_for_alternative_chain(const std::list if (pulse) return PULSE_FIXED_DIFFICULTY; - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); uint64_t block_count = 0; { @@ -1276,24 +1278,24 @@ difficulty_type Blockchain::get_difficulty_for_alternative_chain(const std::list // a non-overflowing tx amount (dubious necessity on this check) bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, hf hf_version) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); if (b.miner_tx.vout.size() > 0) { CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs"); CHECK_AND_ASSERT_MES(std::holds_alternative(b.miner_tx.vin[0]), false, "coinbase transaction in the block has the wrong type"); if (var::get(b.miner_tx.vin[0]).height != height) { - MWARNING("The miner transaction in block has invalid height: " << var::get(b.miner_tx.vin[0]).height << ", expected: " << height); + oxen::log::warning(logcat, "The miner transaction in block has invalid height: {}, expected: {}", var::get(b.miner_tx.vin[0]).height, height); return false; } - MDEBUG("Miner tx hash: " << get_transaction_hash(b.miner_tx)); + oxen::log::debug(logcat, "Miner tx hash: {}", get_transaction_hash(b.miner_tx)); CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction has the wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + MINED_MONEY_UNLOCK_WINDOW); if (hf_version >= hf::hf12_checkpointing) { if (b.miner_tx.type != txtype::standard) { - MERROR("Coinbase invalid transaction type for coinbase transaction."); + oxen::log::error(logcat, "Coinbase invalid transaction type for coinbase transaction."); return false; } @@ -1301,9 +1303,7 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, txversion max_version = transaction::get_min_version_for_hf(hf_version); if (b.miner_tx.version < min_version || b.miner_tx.version > max_version) { - MERROR_VER("Coinbase invalid version: " << b.miner_tx.version << - " for hardfork: " << static_cast(hf_version) << - " min/max version: " << min_version << "/" << max_version); + oxen::log::error(oxen::log::Cat("verify"), "Coinbase invalid version: {} for hardfork: {} min/max version: {}/{}", b.miner_tx.version, static_cast(hf_version), min_version, max_version); return false; } } @@ -1317,7 +1317,7 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, // does not overflow a uint64_t, and this transaction *is* a uint64_t... if(!check_outs_overflow(b.miner_tx)) { - MERROR("miner transaction has money overflow in block " << get_block_hash(b)); + oxen::log::error(logcat, "miner transaction has money overflow in block {}", get_block_hash(b)); return false; } } @@ -1328,12 +1328,12 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, // This function validates the miner transaction reward bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_weight, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, hf version) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); //validate reward uint64_t const money_in_use = get_outs_money_amount(b.miner_tx); if (b.miner_tx.vout.size() == 0) { if (b.major_version < hf::hf19_reward_batching) { - MERROR_VER("miner tx has no outputs"); + oxen::log::error(oxen::log::Cat("verify"), "miner tx has no outputs"); return false; } } @@ -1356,7 +1356,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl block_reward_context.height = height; if (!calc_batched_governance_reward(height, block_reward_context.batched_governance)) { - MERROR_VER("Failed to calculate batched governance reward"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to calculate batched governance reward"); return false; } @@ -1379,7 +1379,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl try { hook(hook_data); } catch (const std::exception& e) { - MGINFO_RED("Miner tx failed validation: " << e.what()); + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Miner tx failed validation: {}", e.what())); return false; } } @@ -1388,13 +1388,13 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl { if (version >= hf::hf10_bulletproofs && reward_parts.governance_paid == 0) { - MERROR("Governance reward should not be 0 after hardfork v10 if this height has a governance output because it is the batched payout height"); + oxen::log::error(logcat, "Governance reward should not be 0 after hardfork v10 if this height has a governance output because it is the batched payout height"); return false; } if (b.miner_tx.vout.back().amount != reward_parts.governance_paid) { - MERROR("Governance reward amount incorrect. Should be: " << print_money(reward_parts.governance_paid) << ", is: " << print_money(b.miner_tx.vout.back().amount)); + oxen::log::error(logcat, "Governance reward amount incorrect. Should be: {}, is: {}", print_money(reward_parts.governance_paid), print_money(b.miner_tx.vout.back().amount)); return false; } @@ -1406,7 +1406,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl var::get(b.miner_tx.vout.back().target).key, m_nettype)) { - MERROR("Governance reward public key incorrect."); + oxen::log::error(logcat, "Governance reward public key incorrect."); return false; } } @@ -1425,8 +1425,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl if (money_in_use > max_money_in_use) { - MERROR_VER("coinbase transaction spends too much money (" << print_money(money_in_use) << "). Maximum block reward is " - << print_money(max_money_in_use) << " (= " << print_money(max_base_reward) << " base + " << print_money(reward_parts.miner_fee) << " fees)"); + oxen::log::error(oxen::log::Cat("verify"), "coinbase transaction spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(money_in_use), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); return false; } @@ -1437,8 +1436,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl if (b.reward > reward_parts.base_miner + reward_parts.miner_fee + reward_parts.service_node_total) { - MERROR_VER("block reward to be batched spends too much money (" << print_money(b.reward) << "). Maximum block reward is " - << print_money(max_money_in_use) << " (= " << print_money(max_base_reward) << " base + " << print_money(reward_parts.miner_fee) << " fees)"); + oxen::log::error(oxen::log::Cat("verify"), "block reward to be batched spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(b.reward), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); return false; } @@ -1448,7 +1446,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl // get the block weights of the last blocks, and return by reference . void Blockchain::get_last_n_blocks_weights(std::vector& weights, size_t count) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto h = m_db->height(); @@ -1463,10 +1461,9 @@ void Blockchain::get_last_n_blocks_weights(std::vector& weights, size_ //------------------------------------------------------------------ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, size_t count) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; - PERF_TIMER(get_long_term_block_weights); CHECK_AND_ASSERT_THROW_MES(count > 0, "count == 0"); @@ -1482,7 +1479,7 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si if (cached) { - MTRACE("requesting " << count << " from " << start_height << ", cached"); + oxen::log::trace(logcat, "requesting {} from {}, cached", count, start_height); return m_long_term_block_weights_cache_rolling_median.median(); } @@ -1493,14 +1490,14 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si crypto::hash old_tip_hash = m_db->get_block_hash_from_height(tip_height - 1); if (old_tip_hash == m_long_term_block_weights_cache_tip_hash) { - MTRACE("requesting " << count << " from " << start_height << ", incremental"); + oxen::log::trace(logcat, "requesting {} from {}, incremental", count, start_height); m_long_term_block_weights_cache_tip_hash = tip_hash; m_long_term_block_weights_cache_rolling_median.insert(m_db->get_block_long_term_weight(tip_height)); return m_long_term_block_weights_cache_rolling_median.median(); } } - MTRACE("requesting " << count << " from " << start_height << ", uncached"); + oxen::log::trace(logcat, "requesting {} from {}, uncached", count, start_height); std::vector weights = m_db->get_long_term_block_weights(start_height, count); m_long_term_block_weights_cache_tip_hash = tip_hash; m_long_term_block_weights_cache_rolling_median.clear(); @@ -1511,13 +1508,13 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_limit() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); return m_current_block_cumul_weight_limit; } //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_median() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); return m_current_block_cumul_weight_median; } //------------------------------------------------------------------ @@ -1529,7 +1526,7 @@ uint64_t Blockchain::get_current_cumulative_block_weight_median() const // This function makes a new block for a miner to mine the hash for bool Blockchain::create_block_template_internal(block& b, const crypto::hash *from_block, const block_template_info& info, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const std::string& ex_nonce) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); size_t median_weight; uint64_t already_generated_coins; uint64_t pool_cookie; @@ -1543,7 +1540,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr // just after the block template was created if (info.miner_address != m_btc_address && m_btc_nonce == ex_nonce && m_btc_pool_cookie == m_tx_pool.cookie() && m_btc.prev_id == get_tail_id()) { - MDEBUG("Using cached template"); + oxen::log::debug(logcat, "Using cached template"); const uint64_t now = time(NULL); if (m_btc.timestamp < now /*ensures it can't get below the median of the last few blocks*/ || !info.is_miner) m_btc.timestamp = now; @@ -1553,7 +1550,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr expected_reward = m_btc_expected_reward; return true; } - MDEBUG("Not using cached template: address " << (bool)(info.miner_address != m_btc_address) << ", nonce " << (m_btc_nonce == ex_nonce) << ", cookie " << (m_btc_pool_cookie == m_tx_pool.cookie()) << ", from_block " << (!!from_block)); + oxen::log::debug(logcat, "Not using cached template: address {}, nonce {}, cookie {}, from_block {}", (bool)(info.miner_address != m_btc_address), (m_btc_nonce == ex_nonce), (m_btc_pool_cookie == m_tx_pool.cookie()), (!!from_block)); invalidate_block_template_cache(); } @@ -1568,7 +1565,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr bool parent_in_main = m_db->block_exists(*from_block); if (!parent_in_alt && !parent_in_main) { - MERROR("Unknown from block"); + oxen::log::error(logcat, "Unknown from block"); return false; } @@ -1659,7 +1656,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr : oxen_miner_tx_context::pulse_block(m_nettype, info.service_node_payout, m_service_node_list.get_block_leader()); if (!calc_batched_governance_reward(height, miner_tx_context.batched_governance)) { - LOG_ERROR("Failed to calculate batched governance reward"); + oxen::log::error(logcat, "Failed to calculate batched governance reward"); return false; } @@ -1698,11 +1695,11 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx)) { //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_weight - MDEBUG("Miner tx creation has no luck with delta_extra size = " << delta << " and " << delta - 1); + oxen::log::debug(logcat, "Miner tx creation has no luck with delta_extra size = {} and {}", delta, delta - 1); cumulative_weight += delta - 1; continue; } - MDEBUG("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count); + oxen::log::debug(logcat, "Setting extra for block: {}, try_count={}", b.miner_tx.extra.size(), try_count); } } CHECK_AND_ASSERT_MES(cumulative_weight == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx)); @@ -1719,7 +1716,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr b.height = height; return true; } - LOG_ERROR("Failed to create_block_template with " << 10 << " tries"); + oxen::log::error(logcat, "Failed to create_block_template with {} tries", 10); return false; } //------------------------------------------------------------------ @@ -1754,7 +1751,7 @@ bool Blockchain::create_next_pulse_block_template(block& b, const service_nodes: // the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector& timestamps) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; @@ -1850,7 +1847,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // make sure alt chain doesn't somehow start past the end of the main chain if (blockchain_height < alt_chain.front().height) { - LOG_PRINT_L1("main blockchain wrong height: " << m_db->height() << ", alt_chain: " << alt_chain.front().height); + oxen::log::info(logcat, "main blockchain wrong height: {}, alt_chain: {}", m_db->height(), alt_chain.front().height); failed = true; } @@ -1858,7 +1855,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // this alternate chain with it. if (!failed && !m_db->block_exists(alt_chain.front().bl.prev_id)) { - LOG_PRINT_L1("alternate chain does not appear to connect to main chain...: " << alt_chain.front().bl.prev_id); + oxen::log::info(logcat, "alternate chain does not appear to connect to main chain...: {}", alt_chain.front().bl.prev_id); failed = true; } @@ -1866,13 +1863,13 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, auto h = m_db->get_block_hash_from_height(alt_chain.front().height - 1); if (!failed && h != alt_chain.front().bl.prev_id) { - LOG_PRINT_L1("alternative chain has wrong connection to main chain: " << h << ", mismatched with: " << alt_chain.front().bl.prev_id); + oxen::log::info(logcat, "alternative chain has wrong connection to main chain: {}, mismatched with: {}", h, alt_chain.front().bl.prev_id); failed = true; } if (!failed && !m_checkpoints.is_alternative_block_allowed(blockchain_height, alt_chain.front().height, nullptr /*service_node_checkpoint*/)) { - LOG_PRINT_L2("alternative chain is too old to consider: " << h); + oxen::log::debug(logcat, "alternative chain is too old to consider: {}", h); failed = true; } @@ -1910,7 +1907,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // a long forked chain eventually. bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc, checkpoint_t const *checkpoint) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t const blk_height = get_block_height(b); @@ -1923,9 +1920,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id if (!(parent_in_main || parent_in_alt)) { bvc.m_marked_as_orphaned = true; - MERROR_VER("Block recognized as orphaned and rejected, id = " << id << ", height " << blk_height - << ", parent in alt " << parent_in_alt << ", parent in main " << parent_in_main - << " (parent " << b.prev_id << ", current top " << get_tail_id() << ", chain height " << chain_height << ")"); + oxen::log::error(oxen::log::Cat("verify"), "Block recognized as orphaned and rejected, id = {}, height {}, parent in alt {}, parent in main {} (parent {}, current top {}, chain height {})", id, blk_height, parent_in_alt, parent_in_main, b.prev_id, get_tail_id(), chain_height); return true; } @@ -1951,7 +1946,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id // (not earlier than the median of the last X blocks in the built alt chain) if(!check_block_timestamp(std::move(timestamps), b)) { - MERROR_VER("Block with id: " << id << std::endl << " for alternative chain, has invalid timestamp: " << b.timestamp); + oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} for alternative chain, has invalid timestamp: {}", id, b.timestamp); bvc.m_verifivation_failed = true; return false; } @@ -2015,7 +2010,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(blob, tx)) { - MERROR_VER("Block with id: " << tools::type_to_hex(id) << " (as alternative) refers to unparsable transaction hash " << txid << "."); + oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} (as alternative) refers to unparsable transaction hash {}.", tools::type_to_hex(id), txid); bvc.m_verifivation_failed = true; return false; } @@ -2055,7 +2050,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id { if (!service_node_checkpoint) { - LOG_ERROR("CHECKPOINT VALIDATION FAILED FOR ALT BLOCK"); + oxen::log::error(logcat, "CHECKPOINT VALIDATION FAILED FOR ALT BLOCK"); bvc.m_verifivation_failed = true; return false; } @@ -2079,14 +2074,14 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id std::string blob; if (!m_tx_pool.get_transaction(missed_tx, blob)) { - MERROR_VER("Alternative block references unknown TX, rejected alt block " << blk_height << " " << id); + oxen::log::error(oxen::log::Cat("verify"), "Alternative block references unknown TX, rejected alt block {} {}", blk_height, id); return false; } transaction tx; if (!parse_and_validate_tx_from_blob(blob, tx)) { - MERROR_VER("Failed to parse block blob from tx pool when querying the missed transactions in block " << blk_height << " " << id); + oxen::log::error(oxen::log::Cat("verify"), "Failed to parse block blob from tx pool when querying the missed transactions in block {} {}", blk_height, id); return false; } @@ -2099,7 +2094,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id try { hook(hook_data); } catch (const std::exception& e) { - LOG_PRINT_L1("Failed to add alt block: " << e.what()); + oxen::log::info(logcat, "Failed to add alt block: {}", e.what()); return false; } } @@ -2121,7 +2116,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id std::vector blocks; if (!get_blocks_only(start, end - start, blocks, nullptr /*txs*/)) { - MERROR("Unexpected failure to query blocks for alt chain switching calculation from " << start << " to " << (end - 1)); + oxen::log::error(logcat, "Unexpected failure to query blocks for alt chain switching calculation from {} to {}", start, (end - 1)); return false; } @@ -2171,7 +2166,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id if (!pulse_block) stream << " PoW: " << blk_pow.proof_of_work; stream << " difficulty: " << current_diff; - MGINFO_BLUE(stream.str()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "{}", stream.str())); return true; } } @@ -2187,12 +2182,12 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id bool keep_alt_chain = false; if (alt_chain_has_more_checkpoints) { - MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front().height << " of " << m_db->height() - 1 << ", checkpoint is found in alternative chain on height " << blk_height); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {}, checkpoint is found in alternative chain on height {}", alt_chain.front().height, m_db->height() - 1, blk_height)); } else { keep_alt_chain = true; - MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front().height << " of " << m_db->height() - 1 << " with cum_difficulty " << m_db->get_block_cumulative_difficulty(m_db->height() - 1) << "\n" << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << alt_data.cumulative_difficulty); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); } bool r = switch_to_alternative_blockchain(alt_chain, keep_alt_chain); @@ -2204,7 +2199,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - MGINFO_BLUE("----- " << block_type << " BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << blk_height << "\n" << "id:\t" << id << "\n" << "PoW:\t" << blk_pow.proof_of_work << "\n" << "difficulty:\t" << current_diff); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); return true; } } @@ -2212,7 +2207,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id { if (alt_chain_has_greater_pow) { - MGINFO_GREEN("###### REORGANIZE on height: " << alt_chain.front().height << " of " << m_db->height() - 1 << " with cum_difficulty " << m_db->get_block_cumulative_difficulty(m_db->height() - 1) << "\n" << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << alt_data.cumulative_difficulty); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); bool r = switch_to_alternative_blockchain(alt_chain, true); if (r) bvc.m_added_to_main_chain = true; @@ -2222,7 +2217,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - MGINFO_BLUE("----- " << block_type << " BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << blk_height << "\n" << "id:\t" << id << "\n" << "PoW:\t" << blk_pow.proof_of_work << "\n" << "difficulty:\t" << current_diff); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); return true; } } @@ -2233,7 +2228,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id //------------------------------------------------------------------ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vector& blocks, std::vector* txs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; const uint64_t height = m_db->height(); if(start_offset >= height) @@ -2249,7 +2244,7 @@ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vecto } catch(std::exception const &e) { - LOG_ERROR("Invalid block at height " << start_offset + i << ". " << e.what()); + oxen::log::error(logcat, "Invalid block at height {}. {}", start_offset + i, e.what()); return false; } } @@ -2269,7 +2264,7 @@ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vecto //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks, std::vector& txs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; if(start_offset >= m_db->height()) return false; @@ -2291,7 +2286,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; const uint64_t height = m_db->height(); if(start_offset >= height) @@ -2304,7 +2299,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vectorget_block_blob_from_height(start_offset + i), block{}); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { - LOG_ERROR("Invalid block"); + oxen::log::error(logcat, "Invalid block"); return false; } } @@ -2320,7 +2315,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector& blocks) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; blocks.reserve(m_db->get_alt_block_count()); m_db->for_all_alt_blocks([&blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string *block_blob, const std::string *checkpoint_blob) { if (!block_blob) { - MERROR("No blob, but blobs were requested"); + oxen::log::error(logcat, "No blob, but blobs were requested"); return false; } cryptonote::block bl; if (cryptonote::parse_and_validate_block_from_blob(*block_blob, bl)) blocks.push_back(std::move(bl)); else - MERROR("Failed to parse block from blob"); + oxen::log::error(logcat, "Failed to parse block from blob"); return true; }, true); return true; @@ -2458,7 +2450,7 @@ bool Blockchain::get_alternative_blocks(std::vector& blocks) const //------------------------------------------------------------------ size_t Blockchain::get_alternative_blocks_count() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; return m_db->get_alt_block_count(); } @@ -2492,7 +2484,7 @@ crypto::public_key Blockchain::get_output_key(uint64_t amount, uint64_t global_i //------------------------------------------------------------------ bool Blockchain::get_outs(const rpc::GET_OUTPUTS_BIN::request& req, rpc::GET_OUTPUTS_BIN::response& res) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; res.outs.clear(); @@ -2512,7 +2504,7 @@ bool Blockchain::get_outs(const rpc::GET_OUTPUTS_BIN::request& req, rpc::GET_OUT m_db->get_output_key(epee::span(amounts.data(), amounts.size()), offsets, data); if (data.size() != req.outputs.size()) { - MERROR("Unexpected output data size: expected " << req.outputs.size() << ", got " << data.size()); + oxen::log::error(logcat, "Unexpected output data size: expected {}, got {}", req.outputs.size(), data.size()); return false; } for (const auto &t: data) @@ -2592,14 +2584,14 @@ void Blockchain::get_output_blacklist(std::vector &blacklist) const // This is used to see what to send another node that needs to sync. bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, uint64_t& starter_offset) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // make sure the request includes at least the genesis block, otherwise // how can we expect to sync from the client that the block list came from? if(qblock_ids.empty()) { - MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << ", dropping connection"); + oxen::log::info(oxen::log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, dropping connection", qblock_ids.size()); return false; } @@ -2609,7 +2601,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc auto gen_hash = m_db->get_block_hash_from_height(0); if(qblock_ids.back() != gen_hash) { - MCERROR("net.p2p", "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: " << std::endl << "id: " << qblock_ids.back() << ", " << std::endl << "expected: " << gen_hash << "," << std::endl << " dropping connection"); + oxen::log::info(oxen::log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: id: {}, expected: {}, dropping connection", qblock_ids.back(), gen_hash); return false; } @@ -2626,7 +2618,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc } catch (const std::exception& e) { - MWARNING("Non-critical error trying to find block by hash in BlockchainDB, hash: " << *bl_it); + oxen::log::warning(logcat, "Non-critical error trying to find block by hash in BlockchainDB, hash: {}", *bl_it); return false; } } @@ -2635,7 +2627,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc // but just in case... if(bl_it == qblock_ids.end()) { - MERROR("Internal error handling connection, can't find split point"); + oxen::log::error(logcat, "Internal error handling connection, can't find split point"); return false; } @@ -2646,7 +2638,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc //------------------------------------------------------------------ uint64_t Blockchain::block_difficulty(uint64_t i) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -2657,7 +2649,7 @@ uint64_t Blockchain::block_difficulty(uint64_t i) const } catch (const BLOCK_DNE& e) { - MERROR("Attempted to get block difficulty for height above blockchain height"); + oxen::log::error(logcat, "Attempted to get block difficulty for height above blockchain height"); } return 0; } @@ -2666,7 +2658,7 @@ uint64_t Blockchain::block_difficulty(uint64_t i) const // alternatively, return true only if no blocks missed bool Blockchain::get_blocks(const std::vector& block_ids, std::vector>& blocks, std::unordered_set* missed_bs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; blocks.reserve(block_ids.size()); @@ -2680,7 +2672,7 @@ bool Blockchain::get_blocks(const std::vector& block_ids, std::vec blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(height), block())); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { - LOG_ERROR("Invalid block: " << block_hash); + oxen::log::error(logcat, "Invalid block: {}", block_hash); blocks.pop_back(); if (missed_bs) missed_bs->insert(block_hash); } @@ -2700,7 +2692,7 @@ bool Blockchain::get_blocks(const std::vector& block_ids, std::vec // alternatively, return true only if no transactions missed bool Blockchain::get_transactions_blobs(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs, bool pruned) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2726,7 +2718,7 @@ bool Blockchain::get_transactions_blobs(const std::vector& txs_ids //------------------------------------------------------------------ std::vector Blockchain::get_transactions_heights(const std::vector& txs_ids) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto heights = m_db->get_tx_block_heights(txs_ids); @@ -2750,7 +2742,7 @@ size_t get_transaction_version(const std::string &bd) //------------------------------------------------------------------ bool Blockchain::get_split_transactions_blobs(const std::vector& txs_ids, std::vector>& txs, std::unordered_set* missed_txs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2764,7 +2756,7 @@ bool Blockchain::get_split_transactions_blobs(const std::vector& t auto& [hash, pruned, pruned_hash, prunable] = txs.emplace_back(tx_hash, std::move(tx), crypto::null_hash, std::string()); if (!is_v1_tx(pruned) && !m_db->get_prunable_tx_hash(tx_hash, pruned_hash)) { - MERROR("Prunable data hash not found for " << tx_hash); + oxen::log::error(logcat, "Prunable data hash not found for {}", tx_hash); return false; } if (!m_db->get_prunable_tx_blob(tx_hash, prunable)) @@ -2783,7 +2775,7 @@ bool Blockchain::get_split_transactions_blobs(const std::vector& t //------------------------------------------------------------------ bool Blockchain::get_transactions(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2798,7 +2790,7 @@ bool Blockchain::get_transactions(const std::vector& txs_ids, std: txs.emplace_back(); if (!parse_and_validate_tx_from_blob(tx, txs.back())) { - LOG_ERROR("Invalid transaction"); + oxen::log::error(logcat, "Invalid transaction"); return false; } } @@ -2818,7 +2810,7 @@ bool Blockchain::get_transactions(const std::vector& txs_ids, std: // BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes. bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, std::vector& hashes, uint64_t& start_height, uint64_t& current_height, bool clip_pruned) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // if we can't find the split point, return false @@ -2848,7 +2840,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; bool result = find_blockchain_supplement(qblock_ids, resp.m_block_ids, resp.start_height, resp.total_height, true); @@ -2864,7 +2856,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc // blocks by reference. bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, const std::list& qblock_ids, std::vector, std::vector > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_count) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // if a specific start height has been requested @@ -2923,11 +2915,11 @@ bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, cons //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(cryptonote::block const &block) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto i_res = m_invalid_blocks.insert(get_block_hash(block)); CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid block returned status failed"); - MINFO("BLOCK ADDED AS INVALID: " << (*i_res.first) << std::endl << ", prev_id=" << block.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size()); + oxen::log::info(logcat, "BLOCK ADDED AS INVALID: {}\n, prev_id={}, m_invalid_blocks count={}", (*i_res.first), block.prev_id, m_invalid_blocks.size()); return true; } @@ -2939,31 +2931,31 @@ hf Blockchain::get_network_version(std::optional height) const { //------------------------------------------------------------------ void Blockchain::flush_invalid_blocks() { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_invalid_blocks.clear(); } //------------------------------------------------------------------ bool Blockchain::have_block(const crypto::hash& id) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; if(m_db->block_exists(id)) { - LOG_PRINT_L2("block " << id << " found in main chain"); + oxen::log::debug(logcat, "block {} found in main chain", id); return true; } if(m_db->get_alt_block(id, NULL, NULL, NULL)) { - LOG_PRINT_L2("block " << id << " found in alternative chains"); + oxen::log::debug(logcat, "block {} found in alternative chains", id); return true; } if(m_invalid_blocks.count(id)) { - LOG_PRINT_L2("block " << id << " found in m_invalid_blocks"); + oxen::log::debug(logcat, "block {} found in m_invalid_blocks", id); return true; } @@ -2972,7 +2964,7 @@ bool Blockchain::have_block(const crypto::hash& id) const //------------------------------------------------------------------ size_t Blockchain::get_total_transactions() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -2989,7 +2981,7 @@ size_t Blockchain::get_total_transactions() const // remove them later if the block fails validation. bool Blockchain::check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto add_transaction_input_visitor = [&keys_this_block, this](const auto& in) { using T = std::decay_t; @@ -3015,7 +3007,7 @@ bool Blockchain::check_for_double_spend(const transaction& tx, key_images_contai { if (!var::visit(add_transaction_input_visitor, in)) { - LOG_ERROR("Double spend detected!"); + oxen::log::error(logcat, "Double spend detected!"); return false; } } @@ -3025,12 +3017,12 @@ bool Blockchain::check_for_double_spend(const transaction& tx, key_images_contai //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector>& indexs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { - MERROR_VER("get_tx_outputs_gindexs failed to find transaction with id = " << tx_id); + oxen::log::error(oxen::log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); return false; } indexs = m_db->get_tx_amount_output_indices(tx_index, n_txes); @@ -3041,12 +3033,12 @@ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector& indexs) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { - MERROR_VER("get_tx_outputs_gindexs failed to find transaction with id = " << tx_id); + oxen::log::error(oxen::log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); return false; } std::vector> indices = m_db->get_tx_amount_output_indices(tx_index, 1); @@ -3068,8 +3060,7 @@ void Blockchain::on_new_tx_from_block(const cryptonote::transaction &tx) size_t ring_size = 0; if (!tx.vin.empty() && std::holds_alternative(tx.vin[0])) ring_size = var::get(tx.vin[0]).key_offsets.size(); - MINFO("HASH: " << "-" << " I/M/O: " << tx.vin.size() << "/" << ring_size << "/" << tx.vout.size() << " H: " << 0 << " chcktx: " << - tools::friendly_duration(std::chrono::steady_clock::now() - a)); + oxen::log::info(logcat, "HASH: - I/M/O: {}/{}/{} H: {} chcktx: {}", tx.vin.size(), ring_size, tx.vout.size(), 0, tools::friendly_duration(std::chrono::steady_clock::now() - a)); } } #endif @@ -3085,7 +3076,7 @@ void Blockchain::on_new_tx_from_block(const cryptonote::transaction &tx) // as a return-by-reference. bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block, std::unordered_set* key_image_conflicts) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; #if defined(PER_BLOCK_CHECKPOINT) @@ -3105,9 +3096,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_heigh size_t ring_size = 0; if (!tx.vin.empty() && std::holds_alternative(tx.vin[0])) ring_size = var::get(tx.vin[0]).key_offsets.size(); - MINFO("HASH: " << get_transaction_hash(tx) << " I/M/O: " << tx.vin.size() << "/" << ring_size << "/" << tx.vout.size() << - " H: " << max_used_block_height << " time: " << tools::friendly_duration(std::chrono::steady_clock::now() - a + m_fake_scan_time) << - " B: " << get_object_blobsize(tx) << " W: " << get_transaction_weight(tx)); + oxen::log::info(logcat, "HASH: {} I/M/O: {}/{}/{} H: {} ms: {} B: {} W: {}", get_transaction_hash(tx), tx.vin.size(), ring_size, tx.vout.size(), max_used_block_height, tools::friendly_duration(std::chrono::steady_clock::now() - a + m_fake_scan_time), get_object_blobsize(tx), get_transaction_weight(tx)); } if (!res) return false; @@ -3120,7 +3109,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_heigh //------------------------------------------------------------------ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context &tvc) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; for (const auto &o: tx.vout) { @@ -3148,7 +3137,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type); if (bulletproof || !tx.rct_signatures.p.bulletproofs.empty()) { - MERROR_VER("Bulletproofs are not allowed before v10"); + oxen::log::error(oxen::log::Cat("verify"), "Bulletproofs are not allowed before v10"); tvc.m_invalid_output = true; return false; } @@ -3161,7 +3150,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (auto hf10_height = hard_fork_begins(m_nettype, hf::hf10_bulletproofs); hf10_height && height > *hf10_height) { - MERROR_VER("Borromean range proofs are not allowed after v10"); + oxen::log::error(oxen::log::Cat("verify"), "Borromean range proofs are not allowed after v10"); tvc.m_invalid_output = true; return false; } @@ -3170,7 +3159,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (hf_version < feature::SMALLER_BP) { if (tx.rct_signatures.type == rct::RCTType::Bulletproof2) { - MERROR_VER("Ringct type " << (unsigned)rct::RCTType::Bulletproof2 << " is not allowed before v" << static_cast(feature::SMALLER_BP)); + oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::Bulletproof2, static_cast(feature::SMALLER_BP)); tvc.m_invalid_output = true; return false; } @@ -3181,7 +3170,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context { if (tx.rct_signatures.type == rct::RCTType::Bulletproof) { - MERROR_VER("Ringct type " << (unsigned)rct::RCTType::Bulletproof << " is not allowed after v" << static_cast(feature::SMALLER_BP)); + oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed after v{}", (unsigned)rct::RCTType::Bulletproof, static_cast(feature::SMALLER_BP)); tvc.m_invalid_output = true; return false; } @@ -3193,7 +3182,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (tx.version >= txversion::v4_tx_types && tx.is_transfer()) { if (tx.rct_signatures.type == rct::RCTType::CLSAG) { - MERROR_VER("Ringct type " << (unsigned)rct::RCTType::CLSAG << " is not allowed before v" << static_cast(feature::CLSAG)); + oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::CLSAG, static_cast(feature::CLSAG)); tvc.m_invalid_output = true; return false; } @@ -3208,7 +3197,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context && tx.version >= txversion::v4_tx_types && tx.is_transfer() && (hf_version > feature::CLSAG || height >= 10 + *hard_fork_begins(m_nettype, feature::CLSAG))) { - MERROR_VER("Ringct type " << (unsigned)tx.rct_signatures.type << " is not allowed from v" << static_cast(feature::CLSAG)); + oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed from v{}", (unsigned)tx.rct_signatures.type, static_cast(feature::CLSAG)); tvc.m_invalid_output = true; return false; } @@ -3218,7 +3207,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context //------------------------------------------------------------------ bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); for (const txin_v& in: tx.vin) { if (!std::holds_alternative(in)) @@ -3232,7 +3221,6 @@ bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const } bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector> &pubkeys) const { - PERF_TIMER(expand_transaction_2); CHECK_AND_ASSERT_MES(tx.version >= txversion::v2_ringct, false, "Transaction version is not 2 or greater"); rct::rctSig &rv = tx.rct_signatures; @@ -3319,8 +3307,7 @@ bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_pr // using threads, etc.) bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height, std::unordered_set* key_image_conflicts) { - PERF_TIMER(check_tx_inputs); - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); uint64_t max_used_block_height = 0; if (!pmax_used_block_height) pmax_used_block_height = &max_used_block_height; @@ -3337,8 +3324,10 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, tvc.m_invalid_version = tx.version < min_version || tx.version > max_version; if (tvc.m_invalid_version || tvc.m_invalid_type) { - if (tvc.m_invalid_version) MERROR_VER("TX Invalid version: " << tx.version << " for hardfork: " << (int)hf_version << " min/max version: " << min_version << "/" << max_version); - if (tvc.m_invalid_type) MERROR_VER("TX Invalid type: " << tx.type << " for hardfork: " << (int)hf_version << " max type: " << max_type); + if (tvc.m_invalid_version) + oxen::log::error(oxen::log::Cat("verify"), "TX Invalid version: {} for hardfork: {} min/max version: {}/{}", tx.version, (int)hf_version, min_version, max_version); + if (tvc.m_invalid_type) + oxen::log::error(oxen::log::Cat("verify"), "TX Invalid type: {} for hardfork: {} max type: {}", tx.type, (int)hf_version, max_type); return false; } } @@ -3347,7 +3336,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (tx.type != txtype::oxen_name_system && !std::holds_alternative(tx.vin[0]) && hf_version >= feature::MIN_2_OUTPUTS && tx.vout.size() < 2) { - MERROR_VER("Tx " << get_transaction_hash(tx) << " has fewer than two outputs, which is not allowed as of hardfork " << static_cast(feature::MIN_2_OUTPUTS)); + oxen::log::error(oxen::log::Cat("verify"), "Tx {} has fewer than two outputs, which is not allowed as of hardfork {}", get_transaction_hash(tx), static_cast(feature::MIN_2_OUTPUTS)); tvc.m_too_few_outputs = true; return false; } @@ -3374,7 +3363,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // Mixin Check, from hard fork 7, we require mixin at least 9, always. if (in_to_key.key_offsets.size() - 1 != cryptonote::TX_OUTPUT_DECOYS) { - MERROR_VER("Tx " << get_transaction_hash(tx) << " has incorrect ring size (" << in_to_key.key_offsets.size() - 1 << ", expected (" << cryptonote::TX_OUTPUT_DECOYS << ")"); + oxen::log::error(oxen::log::Cat("verify"), "Tx {} has incorrect ring size: {} expected: {}", get_transaction_hash(tx), in_to_key.key_offsets.size() - 1, cryptonote::TX_OUTPUT_DECOYS); tvc.m_low_mixin = true; return false; } @@ -3383,7 +3372,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (last_key_image && memcmp(&in_to_key.k_image, last_key_image, sizeof(*last_key_image)) >= 0) { - MERROR_VER("transaction has unsorted inputs"); + oxen::log::error(oxen::log::Cat("verify"), "transaction has unsorted inputs"); tvc.m_verifivation_failed = true; return false; } @@ -3392,7 +3381,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if(have_tx_keyimg_as_spent(in_to_key.k_image)) { - MERROR_VER("Key image already spent in blockchain: " << tools::type_to_hex(in_to_key.k_image)); + oxen::log::error(oxen::log::Cat("verify"), "Key image already spent in blockchain: {}", tools::type_to_hex(in_to_key.k_image)); if (key_image_conflicts) key_image_conflicts->insert(in_to_key.k_image); else @@ -3406,10 +3395,10 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // signature spending it. if (!check_tx_input(in_to_key, tx_prefix_hash, pubkeys[sig_index], pmax_used_block_height)) { - MERROR_VER("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ring signature for tx {} vin key with k_image: {} sig_index: {}", get_transaction_hash(tx), in_to_key.k_image, sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { - MERROR_VER(" *pmax_used_block_height: " << *pmax_used_block_height); + oxen::log::error(oxen::log::Cat("verify"), " *pmax_used_block_height: {}", *pmax_used_block_height); } return false; @@ -3426,7 +3415,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (in_to_key.k_image == entry.key_image) // Check if key image is on the blacklist { - MERROR_VER("Key image: " << tools::type_to_hex(entry.key_image) << " is blacklisted by the service node network"); + oxen::log::error(oxen::log::Cat("verify"), "Key image: {} is blacklisted by the service node network", tools::type_to_hex(entry.key_image)); tvc.m_key_image_blacklisted = true; return false; } @@ -3435,7 +3424,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t unlock_height = 0; if (m_service_node_list.is_key_image_locked(in_to_key.k_image, &unlock_height)) { - MERROR_VER("Key image: " << tools::type_to_hex(in_to_key.k_image) << " is locked in a stake until height: " << unlock_height); + oxen::log::error(oxen::log::Cat("verify"), "Key image: {} is locked in a stake until height: {}", tools::type_to_hex(in_to_key.k_image), unlock_height); tvc.m_key_image_locked_by_snode = true; return false; } @@ -3450,7 +3439,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys)) { - MERROR_VER("Failed to expand rct signatures!"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to expand rct signatures!"); return false; } @@ -3464,7 +3453,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // we only accept no signatures for coinbase txes if (!std::holds_alternative(tx.vin[0])) { - MERROR_VER("Null rct signature on non-coinbase tx"); + oxen::log::error(oxen::log::Cat("verify"), "Null rct signature on non-coinbase tx"); return false; } break; @@ -3478,14 +3467,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys.size() != rv.mixRing.size()) { - MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t i = 0; i < pubkeys.size(); ++i) { if (pubkeys[i].size() != rv.mixRing[i].size()) { - MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } } @@ -3496,12 +3485,12 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[n][m].dest)) { - MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[n][m].mask)) { - MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); return false; } } @@ -3511,7 +3500,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, const size_t n_sigs = rv.type == rct::RCTType::CLSAG ? rv.p.CLSAGs.size() : rv.p.MGs.size(); if (n_sigs != tx.vin.size()) { - MERROR_VER("Failed to check ringct signatures: mismatched MGs/vin sizes"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched MGs/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) @@ -3523,14 +3512,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, error = rv.p.MGs[n].II.empty() || memcmp(&var::get(tx.vin[n]).k_image, &rv.p.MGs[n].II[0], 32); if (error) { - MERROR_VER("Failed to check ringct signatures: mismatched key image"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched key image"); return false; } } if (!rct::verRctNonSemanticsSimple(rv)) { - MERROR_VER("Failed to check ringct signatures!"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures!"); return false; } break; @@ -3546,7 +3535,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, size_matches &= pubkeys.size() == rv.mixRing[i].size(); if (!size_matches) { - MERROR_VER("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } @@ -3556,12 +3545,12 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest)) { - MERROR_VER("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask)) { - MERROR_VER("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); return false; } } @@ -3570,32 +3559,32 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (rv.p.MGs.size() != 1) { - MERROR_VER("Failed to check ringct signatures: Bad MGs size"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: Bad MGs size"); return false; } if (rv.p.MGs.empty() || rv.p.MGs[0].II.size() != tx.vin.size()) { - MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (memcmp(&var::get(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32)) { - MERROR_VER("Failed to check ringct signatures: mismatched II/vin sizes"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); return false; } } if (!rct::verRct(rv, false)) { - MERROR_VER("Failed to check ringct signatures!"); + oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures!"); return false; } break; } default: - MERROR_VER(__func__ << ": Unsupported rct type: " << (int)rv.type); + oxen::log::error(oxen::log::Cat("verify"), "{}: Unsupported rct type: {}", __func__, (int)rv.type); return false; } @@ -3606,7 +3595,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (proof.V.size() > 1 && !hack::test_suite_permissive_txes) { - MERROR_VER("Multi output bulletproofs are invalid before v10"); + oxen::log::error(oxen::log::Cat("verify"), "Multi output bulletproofs are invalid before v10"); return false; } } @@ -3618,7 +3607,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, std::string fail_reason; if (!m_ons_db.validate_ons_tx(hf_version, get_current_blockchain_height(), tx, data, &fail_reason)) { - MERROR_VER("Failed to validate ONS TX reason: " << fail_reason); + oxen::log::error(oxen::log::Cat("verify"), "Failed to validate ONS TX reason: {}", fail_reason); tvc.m_verbose_error = std::move(fail_reason); return false; } @@ -3632,7 +3621,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { tvc.m_invalid_input = true; tvc.m_verifivation_failed = true; - MERROR_VER("TX type: " << tx.type << " should have 0 fee!"); + oxen::log::error(oxen::log::Cat("verify"), "TX type: {} should have 0 fee!", tx.type); return false; } @@ -3641,14 +3630,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, hf_version)) { - MERROR_VER("TX did not have the state change metadata in the tx_extra"); + oxen::log::error(oxen::log::Cat("verify"), "TX did not have the state change metadata in the tx_extra"); return false; } auto quorum = m_service_node_list.get_quorum(service_nodes::quorum_type::obligations, state_change.block_height); if (!quorum) { - MERROR_VER("could not get obligations quorum for recent state change tx"); + oxen::log::error(oxen::log::Cat("verify"), "could not get obligations quorum for recent state change tx"); return false; } @@ -3657,7 +3646,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // will be set by the above on serious failures (i.e. illegal value), but not for less // serious ones like state change heights slightly outside of allowed bounds: //tvc.m_verifivation_failed = true; - MERROR_VER("tx " << get_transaction_hash(tx) << ": state change tx could not be completely verified reason: " << print_vote_verification_context(tvc.m_vote_ctx)); + oxen::log::error(oxen::log::Cat("verify"), "tx: {}, state change tx could not be completely verified reason: {}", get_transaction_hash(tx), print_vote_verification_context(tvc.m_vote_ctx)); return false; } @@ -3668,14 +3657,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, std::vector service_node_array = m_service_node_list.get_service_node_list_state({state_change_service_node_pubkey}); if (service_node_array.empty()) { - MERROR_VER("Service Node no longer exists on the network, state change can be ignored"); + oxen::log::error(oxen::log::Cat("verify"), "Service Node no longer exists on the network, state change can be ignored"); return hf_version < hf::hf12_checkpointing; // NOTE: Used to be allowed pre HF12. } const auto& service_node_info = *service_node_array[0].info; if (!service_node_info.can_transition_to_state(hf_version, state_change.block_height, state_change.state)) { - MERROR_VER("State change trying to vote Service Node into the same state it invalid (expired, already applied, or impossible)"); + oxen::log::error(oxen::log::Cat("verify"), "State change trying to vote Service Node into the same state it invalid (expired, already applied, or impossible)"); tvc.m_double_spend = true; return false; } @@ -3685,7 +3674,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, cryptonote::tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - MERROR("TX extra didn't have key image unlock in the tx_extra"); + oxen::log::error(logcat, "TX extra didn't have key image unlock in the tx_extra"); return false; } @@ -3693,7 +3682,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t unlock_height = 0; if (!m_service_node_list.is_key_image_locked(unlock.key_image, &unlock_height, &contribution)) { - MERROR_VER("Requested key image: " << tools::type_to_hex(unlock.key_image) << " to unlock is not locked"); + oxen::log::error(oxen::log::Cat("verify"), "Requested key image: {} to unlock is not locked", tools::type_to_hex(unlock.key_image)); tvc.m_invalid_input = true; return false; } @@ -3701,7 +3690,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (!crypto::check_signature(service_nodes::generate_request_stake_unlock_hash(unlock.nonce), contribution.key_image_pub_key, unlock.signature)) { - MERROR("Could not verify key image unlock transaction signature for tx: " << get_transaction_hash(tx)); + oxen::log::error(logcat, "Could not verify key image unlock transaction signature for tx: {}", get_transaction_hash(tx)); return false; } @@ -3714,7 +3703,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, } else { - MERROR_VER("Unhandled tx type: " << tx.type << " rejecting tx: " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "Unhandled tx type: {} rejecting tx: {}", tx.type, get_transaction_hash(tx)); tvc.m_invalid_type = true;; return false; } @@ -3805,7 +3794,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee(uint64_t block_reward, siz // quantize fee up to 8 decimals uint64_t mask = get_fee_quantization_mask(); uint64_t qlo = (lo + mask - 1) / mask * mask; - MDEBUG("lo " << print_money(lo) << ", qlo " << print_money(qlo) << ", mask " << mask); + oxen::log::debug(logcat, "lo {}, qlo {}, mask {}", print_money(lo), print_money(qlo), mask); fees.first = qlo; return fees; @@ -3828,7 +3817,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 { const bool use_long_term_median_in_fee = version >= feature::LONG_TERM_BLOCK_WEIGHT; auto fees = get_dynamic_base_fee(base_reward, use_long_term_median_in_fee ? std::min(median, m_long_term_effective_median_block_weight) : median, version); - MDEBUG("Using " << print_money(fees.first) << "/byte + " << print_money(fees.second) << "/out fee"); + oxen::log::debug(logcat, "Using {}/byte + {}/out fee", print_money(fees.first), print_money(fees.second)); needed_fee = tx_weight * fees.first + tx_outs * fees.second; // quantize fee up to 8 decimals const uint64_t mask = get_fee_quantization_mask(); @@ -3838,7 +3827,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 { auto fees = get_dynamic_base_fee(base_reward, median, version); assert(fees.second == 0); - MDEBUG("Using " << print_money(fees.first) << "/kB fee"); + oxen::log::debug(logcat, "Using {}/kB fee", print_money(fees.first)); needed_fee = tx_weight / 1024; needed_fee += (tx_weight % 1024) ? 1 : 0; @@ -3854,7 +3843,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 if (fee < needed_fee) { - MERROR_VER("transaction fee is not enough: " << print_money(fee) << ", minimum fee: " << print_money(needed_fee)); + oxen::log::error(oxen::log::Cat("verify"), "transaction fee is not enough: {}, minimum fee: {}", print_money(fee), print_money(needed_fee)); return false; } @@ -3863,7 +3852,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 uint64_t need_burned = opts.burn_fixed + base_miner_fee * opts.burn_percent / 100; if (burned < need_burned) { - MERROR_VER("transaction burned fee is not enough: " << print_money(burned) << ", minimum fee: " << print_money(need_burned)); + oxen::log::error(oxen::log::Cat("verify"), "transaction burned fee is not enough: {}, minimum fee: {}", print_money(burned), print_money(need_burned)); return false; } } @@ -3894,7 +3883,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl uint64_t base_reward, base_reward_unpenalized; if (!get_base_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, base_reward_unpenalized, version, m_db->height())) { - MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound"); + oxen::log::error(logcat, "Failed to determine block reward, using placeholder {} as a high bound", print_money(BLOCK_REWARD_OVERESTIMATE)); base_reward = BLOCK_REWARD_OVERESTIMATE; } @@ -3902,8 +3891,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl const uint64_t use_median_value = use_long_term_median_in_fee ? std::min(median, m_long_term_effective_median_block_weight) : median; auto fee = get_dynamic_base_fee(base_reward, use_median_value, version); const bool per_byte = version < feature::PER_BYTE_FEE; - MDEBUG("Estimating " << grace_blocks << "-block fee at " << print_money(fee.first) << "/" << (per_byte ? "byte" : "kB") << - " + " << print_money(fee.second) << "/out"); + oxen::log::debug(logcat, "Estimating {}-block fee at {}/{} + {}.out", grace_blocks, print_money(fee.first), (per_byte ? "byte" : "kB"), print_money(fee.second)); return fee; } @@ -3912,7 +3900,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl // a block index or a unix time. bool Blockchain::is_output_spendtime_unlocked(uint64_t unlock_time) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); return cryptonote::rules::is_output_unlocked(unlock_time, m_db->height()); } //------------------------------------------------------------------ @@ -3920,7 +3908,7 @@ bool Blockchain::is_output_spendtime_unlocked(uint64_t unlock_time) const // and validates that they exist and are usable. bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_prefix_hash, std::vector &output_keys, uint64_t* pmax_related_block_height) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // ND: // 1. Disable locking and make method private. @@ -3939,7 +3927,7 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ //check tx unlock time if (!m_bch.is_output_spendtime_unlocked(unlock_time)) { - MERROR_VER("One of outputs for one of inputs has wrong tx.unlock_time = " << unlock_time); + oxen::log::error(oxen::log::Cat("verify"), "One of outputs for one of inputs has wrong tx.unlock_time = {}", unlock_time); return false; } @@ -3959,13 +3947,13 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ outputs_visitor vi(output_keys, *this); if (!scan_outputkeys_for_indexes(txin, vi, tx_prefix_hash, pmax_related_block_height)) { - MERROR_VER("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size()); + oxen::log::error(oxen::log::Cat("verify"), "Failed to get output keys for tx with amount = {} and count indixes {}", print_money(txin.amount), txin.key_offsets.size()); return false; } if(txin.key_offsets.size() != output_keys.size()) { - MERROR_VER("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size()); + oxen::log::error(oxen::log::Cat("verify"), "Output keys for tx with amount = {} and count indexes {} returned wrong keys count {}", txin.amount, txin.key_offsets.size(), output_keys.size()); return false; } // rct_signatures will be expanded after this @@ -3975,7 +3963,7 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ //TODO: Is this intended to do something else? Need to look into the todo there. uint64_t Blockchain::get_adjusted_time() const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); //TODO: add collecting median time return time(NULL); } @@ -3983,12 +3971,12 @@ uint64_t Blockchain::get_adjusted_time() const //TODO: revisit, has changed a bit on upstream bool Blockchain::check_block_timestamp(std::vector timestamps, const block& b, uint64_t& median_ts) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); median_ts = tools::median(std::move(timestamps)); if(b.timestamp < median_ts) { - MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts); + oxen::log::error(oxen::log::Cat("verify"), "Timestamp of block with id: {}, {}, less than median of last {} blocks, {}", get_block_hash(b), b.timestamp, BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW, median_ts); return false; } @@ -4004,11 +3992,11 @@ bool Blockchain::check_block_timestamp(std::vector timestamps, const b // false otherwise bool Blockchain::check_block_timestamp(const block& b, uint64_t& median_ts) const { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); uint64_t cryptonote_block_future_time_limit = old::BLOCK_FUTURE_TIME_LIMIT_V2; if(b.timestamp > get_adjusted_time() + cryptonote_block_future_time_limit) { - MERROR_VER("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + 2 hours"); + oxen::log::error(oxen::log::Cat("verify"), "Timestamp of block with id: {}, {}, bigger than adjusted time + 2 hours", get_block_hash(b), b.timestamp); return false; } @@ -4048,7 +4036,7 @@ void Blockchain::return_tx_to_pool(std::vector &txids) size_t tx_weight; uint64_t fee; bool relayed, do_not_relay, double_spend_seen; - MINFO("Removing txid " << txid << " from the pool"); + oxen::log::info(logcat, "Removing txid {} from the pool", txid); if(m_tx_pool.have_tx(txid) && !m_tx_pool.take_tx(txid, tx, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { - MERROR("Failed to remove txid " << txid << " from the pool"); + oxen::log::error(logcat, "Failed to remove txid {} from the pool", txid); res = false; } } @@ -4126,7 +4114,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co { if (blk_hash != expected_hash) { - MERROR_VER("Block with id is INVALID: " << blk_hash << ", expected " << expected_hash); + oxen::log::error(oxen::log::Cat("verify"), "Block with id is INVALID: {}, expected {}", blk_hash, expected_hash); result.valid = false; return result; } @@ -4135,7 +4123,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co } else { - MCINFO("verify", "No pre-validated hash at height " << chain_height << ", verifying fully"); + oxen::log::info(oxen::log::Cat("verify"), "No pre-validated hash at height {}, verifying fully", chain_height); } } #endif @@ -4162,7 +4150,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co // validate proof_of_work versus difficulty target result.valid = check_hash(result.proof_of_work, difficulty); if (!result.valid) - MGINFO_RED((alt_block ? "Alternative block" : "Block") << " with id: " << blk_hash << "\n does not have enough proof of work: " << result.proof_of_work << " at height " << blk_height << ", required difficulty: " << difficulty); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} with id: {}\n does not have enough proof of work: {} at height {}, required difficulty: {}", (alt_block ? "Alternative block" : "Block"), blk_hash, result.proof_of_work, blk_height, difficulty)); } return result; @@ -4179,13 +4167,13 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block { if(cryptonote::get_block_height(blk) == 0) { - MERROR_VER("Block with id: " << blk_hash << " (as alternative), but miner tx says height is 0."); + oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} (as alternative), but miner tx says height is 0.", blk_hash); return false; } if (!m_checkpoints.is_alternative_block_allowed(chain_height, blk_height, nullptr)) { - MERROR_VER("Block with id: " << blk_hash << " can't be accepted for alternative chain, block height: " << blk_height << ", chain height: " << chain_height); + oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} can't be accepted for alternative chain, block height: {}, chain height: {}", blk_hash, blk_height, chain_height); return false; } @@ -4194,8 +4182,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (auto v = get_network_version(blk_height); blk.major_version != v || (v < hf::hf19_reward_batching && blk.minor_version < static_cast(v))) { - LOG_PRINT_L1("Block with id: " << blk_hash << ", has invalid version " << static_cast(blk.major_version) << "." << +blk.minor_version << - "; current: " << static_cast(v) << "." << static_cast(v) << " for height " << blk_height); + oxen::log::info(logcat, "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(v), static_cast(v), blk_height); return false; } } @@ -4204,7 +4191,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block crypto::hash top_hash = get_tail_id(); if(blk.prev_id != top_hash) { - MGINFO_RED("Block with id: " << blk_hash << ", has wrong prev_id: " << blk.prev_id << ", expected: " << top_hash); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has wrong prev_id: {}, expected: {}", blk_hash, blk.prev_id, top_hash)); return false; } @@ -4216,12 +4203,11 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (auto now = std::chrono::steady_clock::now(); now > last_outdated_warning + 5min) { last_outdated_warning = now; - const el::Level level = el::Level::Warning; - MCLOG_RED(level, "global", "**********************************************************************"); - MCLOG_RED(level, "global", "A block was seen on the network with a version higher than the last"); - MCLOG_RED(level, "global", "known one. This may be an old version of the daemon, and a software"); - MCLOG_RED(level, "global", "update may be required to sync further. Try running: update check"); - MCLOG_RED(level, "global", "**********************************************************************"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "A block was seen on the network with a version higher than the last")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "known one. This may be an old version of the daemon, and a software")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "update may be required to sync further. Try running: update check")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); } } @@ -4229,8 +4215,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (blk.major_version != required_major_version || (blk.major_version < hf::hf19_reward_batching && blk.minor_version < static_cast(required_major_version))) { - MGINFO_RED("Block with id: " << blk_hash << ", has invalid version " << static_cast(blk.major_version) << "." << +blk.minor_version << - "; current: " << static_cast(required_major_version) << "." << static_cast(required_major_version) << " for height " << blk_height); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(required_major_version), static_cast(required_major_version), blk_height)); return false; } @@ -4243,7 +4228,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block { if (!service_node_checkpoint || (service_node_checkpoint && blk.major_version >= hf::hf13_enforce_checkpoints)) { - MGINFO_RED("CHECKPOINT VALIDATION FAILED"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "CHECKPOINT VALIDATION FAILED")); return false; } } @@ -4253,7 +4238,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // number of the most recent blocks. if(!check_block_timestamp(blk)) { - MGINFO_RED("Block with id: " << blk_hash << ", has invalid timestamp: " << blk.timestamp); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid timestamp: {}", blk_hash, blk.timestamp)); return false; } } @@ -4263,7 +4248,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // sanity check basic miner tx properties; if(!prevalidate_miner_transaction(blk, alt_block ? blk_height : chain_height, hf_version)) { - MGINFO_RED("Block with id: " << blk_hash << " failed to pass prevalidation"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} failed to pass prevalidation", blk_hash)); return false; } @@ -4275,7 +4260,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // m_db->add_block() bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc, checkpoint_t const *checkpoint, bool notify) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); auto block_processing_start = std::chrono::steady_clock::now(); std::unique_lock lock{*this}; @@ -4353,7 +4338,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if (m_db->tx_exists(tx_id)) { - MGINFO_RED("Block with id: " << id << " attempting to add transaction already in blockchain with id: " << tx_id); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} attempting to add transaction already in blockchain with id: {}", id, tx_id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4365,7 +4350,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // get transaction with hash from tx_pool if(!m_tx_pool.take_tx(tx_id, tx_tmp, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { - MGINFO_RED("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one unknown transaction with id: {}", id, tx_id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4387,7 +4372,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly. // if (!check_for_double_spend(tx, keys)) // { - // LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id); + // oxen::log::warning(logcat, "Double spend detected in transaction (id: {}", tx_id); // bvc.m_verifivation_failed = true; // break; // } @@ -4403,12 +4388,13 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& tx_verification_context tvc{}; if(!check_tx_inputs(tx, tvc)) { - MGINFO_RED("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id)); add_block_as_invalid(bl); - MGINFO_RED("Block with id " << id << " added as invalid because of wrong inputs in transactions"); - MGINFO_RED("tx_index " << tx_index << ", m_blocks_txs_check " << m_blocks_txs_check.size() << ":"); - for (const auto &h: m_blocks_txs_check) MERROR_VER(" " << h); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id {} added as invalid because of wrong inputs in transactions", id)); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "tx_index {}, m_blocks_txs_check {}:", tx_index, m_blocks_txs_check.size())); + for (const auto &h: m_blocks_txs_check) + oxen::log::error(oxen::log::Cat("verify"), " {}", h); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4421,9 +4407,9 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // the transaction inputs, but do some sanity checks anyway. if (tx_index >= m_blocks_txs_check.size() || memcmp(&m_blocks_txs_check[tx_index++], &tx_id, sizeof(tx_id)) != 0) { - MERROR_VER("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); + oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id); add_block_as_invalid(bl); - MERROR_VER("Block with id " << id << " added as invalid because of wrong inputs in transactions"); + oxen::log::error(oxen::log::Cat("verify"), "Block with id {} added as invalid because of wrong inputs in transactions", id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4442,7 +4428,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& uint64_t already_generated_coins = chain_height ? m_db->get_block_already_generated_coins(chain_height - 1) : 0; if(!validate_miner_transaction(bl, cumulative_block_weight, fee_summary, base_reward, already_generated_coins, get_network_version())) { - MGINFO_RED("Block " << (chain_height - 1) << " with id: " << id << " has incorrect miner transaction"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block {} with id: {} has incorrect miner transaction", (chain_height - 1), id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4478,7 +4464,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } catch (const KEY_IMAGE_EXISTS& e) { - MGINFO_RED("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4487,7 +4473,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& catch (const std::exception& e) { //TODO: figure out the best way to deal with this failure - MGINFO_RED("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4496,7 +4482,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } else { - MGINFO_RED("Blocks that failed verification should not reach here"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Blocks that failed verification should not reach here")); } auto abort_block = oxen::defer([&]() { @@ -4521,14 +4507,14 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { m_service_node_list.block_add(bl, only_txs, checkpoint); } catch (const std::exception& e) { - MGINFO_RED("Failed to add block to Service Node List: " << e.what()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to Service Node List: {}", e.what())); bvc.m_verifivation_failed = true; return false; } if (!m_ons_db.add_block(bl, only_txs)) { - MGINFO_RED("Failed to add block to ONS DB."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to ONS DB.")); bvc.m_verifivation_failed = true; return false; } @@ -4536,7 +4522,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if (m_sqlite_db) { if (!m_service_node_list.process_batching_rewards(bl)) { - MERROR("Failed to add block to batch rewards DB."); + oxen::log::error(logcat, "Failed to add block to batch rewards DB."); bvc.m_verifivation_failed = true; return false; } @@ -4551,7 +4537,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { hook(hook_data); } catch (const std::exception& e) { - MGINFO_RED("Block add hook failed with exception: " << e.what()); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block added hook failed with exception: ", e.what())); bvc.m_verifivation_failed = true; return false; } @@ -4562,7 +4548,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // do this after updating the hard fork state since the weight limit may change due to fork if (!update_next_cumulative_weight_limit()) { - MGINFO_RED("Failed to update next cumulative weight limit"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to update next cumulative weight limit")); return false; } @@ -4570,39 +4556,54 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& uint64_t const fee_after_penalty = get_outs_money_amount(bl.miner_tx) - base_reward; if (bl.signatures.size() == service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES) { - MINFO("+++++ PULSE BLOCK SUCCESSFULLY ADDED" - "\n\tid: " << id << - "\n\tHEIGHT: " << new_height-1 << ", v" << static_cast(bl.major_version) << '.' << +bl.minor_version << - "\n\tblock reward: " << print_money(fee_after_penalty + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_after_penalty) << ")" - ", coinbase_weight: " << coinbase_weight << - ", cumulative weight: " << cumulative_block_weight << - ", " << tools::friendly_duration(block_processing_time)); + oxen::log::info(logcat, "\n+++++ PULSE BLOCK SUCCESSFULLY ADDED\n\tid: {}\n\tHEIGHT: {}, v{}.{}\n\tblock reward: {}({} + {}) , coinbase_weight: {}, cumulative weight: {}, {}ms", + id, + new_height-1, + static_cast(bl.major_version), + +bl.minor_version, + print_money(fee_after_penalty + base_reward), + print_money(base_reward), + print_money(fee_after_penalty), + coinbase_weight, + cumulative_block_weight, + tools::friendly_duration(block_processing_time)); } else { assert(bl.signatures.empty() && "Signatures were supposed to be checked in Service Node List already."); - MINFO("+++++ MINER BLOCK SUCCESSFULLY ADDED\n" - "\n\tid: " << id << - "\n\tPoW: " << miner.blk_pow.proof_of_work << - "\n\tHEIGHT: " << new_height - 1 << ", v" << static_cast(bl.major_version) << '.' << +bl.minor_version << ", difficulty: " << current_diffic << - "\n\tblock reward: " << print_money(fee_after_penalty + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_after_penalty) << ")" - ", coinbase_weight: " << coinbase_weight << - ", cumulative weight: " << cumulative_block_weight << - ", " << tools::friendly_duration(block_processing_time) << "(" << tools::friendly_duration(miner.verify_pow_time) << ")"); + oxen::log::info(logcat, "\n+++++ MINER BLOCK SUCCESSFULLY ADDED\n\n\tid: {}\n\tPoW: {}\n\tHEIGHT: {}, v{}.{}, difficulty: {}\n\tblock reward: {}({} + {}), coinbase_weight: {}, cumulative weight: {}, {}({})", + id, + miner.blk_pow.proof_of_work, + new_height - 1, + static_cast(bl.major_version), + +bl.minor_version, + current_diffic, + print_money(fee_after_penalty + base_reward), + print_money(base_reward), + print_money(fee_after_penalty), + coinbase_weight, + cumulative_block_weight, + tools::friendly_duration(block_processing_time), + tools::friendly_duration(miner.verify_pow_time) + ); } if(m_show_time_stats) { - MINFO("Height: " << new_height << " coinbase weight: " << coinbase_weight << " cumm: " - << cumulative_block_weight << " p/t: " << tools::friendly_duration(block_processing_time) << " (" - << "/" << tools::friendly_duration(miner.verify_pow_time) - << "/" << tools::friendly_duration(t1_elapsed) - << "/" << tools::friendly_duration(t_exists) - << "/" << tools::friendly_duration(t_pool) - << "/" << tools::friendly_duration(t_checktx) - << "/" << tools::friendly_duration(t_dblspnd) - << "/" << tools::friendly_duration(vmt_elapsed) - << "/" << tools::friendly_duration(addblock_elapsed) << ")"); + oxen::log::info(logcat, + "Height: {} coinbase weight: {} cumm: {} p/t: {} ({}/{}/{}/{}/{}/{}/{}/{})", + new_height, + coinbase_weight, + cumulative_block_weight, + tools::friendly_duration(block_processing_time), + tools::friendly_duration(miner.verify_pow_time), + tools::friendly_duration(t1_elapsed), + tools::friendly_duration(t_exists), + tools::friendly_duration(t_pool), + tools::friendly_duration(t_checktx), + tools::friendly_duration(t_dblspnd), + tools::friendly_duration(vmt_elapsed), + tools::friendly_duration(addblock_elapsed)); } @@ -4642,7 +4643,6 @@ bool Blockchain::check_blockchain_pruning() //------------------------------------------------------------------ uint64_t Blockchain::get_next_long_term_block_weight(uint64_t block_weight) const { - PERF_TIMER(get_next_long_term_block_weight); const uint64_t db_height = m_db->height(); const uint64_t nblocks = std::min(m_long_term_block_weights_window, db_height); @@ -4661,9 +4661,8 @@ uint64_t Blockchain::get_next_long_term_block_weight(uint64_t block_weight) cons //------------------------------------------------------------------ bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight) { - PERF_TIMER(update_next_cumulative_weight_limit); - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); // when we reach this, the last hf version is not yet written to the db const uint64_t db_height = m_db->height(); @@ -4736,13 +4735,13 @@ bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effecti bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc, checkpoint_t const *checkpoint) { - LOG_PRINT_L3("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); crypto::hash id = get_block_hash(bl); auto lock = tools::unique_locks(m_tx_pool, *this); db_rtxn_guard rtxn_guard(m_db); if(have_block(id)) { - LOG_PRINT_L3("block with id = " << id << " already exists"); + oxen::log::trace(logcat, "block with id = {} already exists", id); bvc.m_already_exists = true; m_blocks_txs_check.clear(); return false; @@ -4762,7 +4761,7 @@ bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc, } catch (const std::exception &e) { - MERROR("Get block checkpoint from DB failed at height: " << block_height << ", what = " << e.what()); + oxen::log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", block_height, e.what()); } } @@ -4797,25 +4796,25 @@ bool Blockchain::update_checkpoints_from_json_file(const fs::path& file_path) std::vector::const_iterator one_past_last_to_check = checkpoint_hashes.end(); uint64_t prev_max_height = m_checkpoints.get_max_height(); - LOG_PRINT_L1("Adding checkpoints from blockchain hashfile: " << file_path); - LOG_PRINT_L1("Hard-coded max checkpoint height is " << prev_max_height); + oxen::log::info(logcat, "Adding checkpoints from blockchain hashfile: {}", file_path); + oxen::log::info(logcat, "Hard-coded max checkpoint height is {}", prev_max_height); for (std::vector::const_iterator it = checkpoint_hashes.begin(); it != one_past_last_to_check; it++) { uint64_t height; height = it->height; if (height <= prev_max_height) { - LOG_PRINT_L1("ignoring checkpoint height " << height); + oxen::log::info(logcat, "ignoring checkpoint height {}", height); } else { if (first_to_check == checkpoint_hashes.end()) first_to_check = it; std::string blockhash = it->hash; - LOG_PRINT_L1("Adding checkpoint height " << height << ", hash=" << blockhash); + oxen::log::info(logcat, "Adding checkpoint height {}, hash={}", height, blockhash); if (!m_checkpoints.add_checkpoint(height, blockhash)) { one_past_last_to_check = it; - LOG_PRINT_L1("Failed to add checkpoint at height " << height << ", hash=" << blockhash); + oxen::log::info(logcat, "Failed to add checkpoint at height {}, hash={}", height, blockhash); break; } } @@ -4841,7 +4840,7 @@ bool Blockchain::update_checkpoints_from_json_file(const fs::path& file_path) if (!m_checkpoints.check_block(block_height, m_db->get_block_hash_from_height(block_height), nullptr)) { // roll back to a couple of blocks before the checkpoint - LOG_ERROR("Local blockchain failed to pass a checkpoint, rolling back!"); + oxen::log::error(logcat, "Local blockchain failed to pass a checkpoint, rolling back!"); std::list empty; rollback_blockchain_switching(empty, block_height- 2); result = false; @@ -4884,8 +4883,7 @@ void Blockchain::block_longhash_worker(uint64_t height, const epee::span 0) @@ -4910,7 +4908,7 @@ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) } else if (m_db_sync_threshold && ((m_db_sync_on_blocks && m_sync_counter >= m_db_sync_threshold) || (!m_db_sync_on_blocks && m_bytes_to_sync >= m_db_sync_threshold))) { - MDEBUG("Sync threshold met, syncing"); + oxen::log::debug(logcat, "Sync threshold met, syncing"); if(m_db_sync_mode == db_async) { m_sync_counter = 0; @@ -4935,7 +4933,7 @@ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) // when we're well clear of the precomputed hashes, free the memory if (!m_blocks_hash_check.empty() && m_db->height() > m_blocks_hash_check.size() + 4096) { - MINFO("Dumping block hashes, we're now 4k past " << m_blocks_hash_check.size()); + oxen::log::info(logcat, "Dumping block hashes, we're now 4k past {}", m_blocks_hash_check.size()); m_blocks_hash_check.clear(); m_blocks_hash_check.shrink_to_fit(); } @@ -4957,7 +4955,7 @@ void Blockchain::output_scan_worker(const uint64_t amount, const std::vector::max() / 2, 0, "usable is negative"); return usable; } @@ -5109,7 +5107,7 @@ bool Blockchain::calc_batched_governance_reward(uint64_t height, uint64_t &rewar std::vector blocks; if (!get_blocks_only(start_height, num_blocks, blocks)) { - LOG_ERROR("Unable to get historical blocks to calculated batched governance payment"); + oxen::log::error(logcat, "Unable to get historical blocks to calculated batched governance payment"); return false; } @@ -5131,7 +5129,7 @@ bool Blockchain::calc_batched_governance_reward(uint64_t height, uint64_t &rewar // keys. bool Blockchain::prepare_handle_incoming_blocks(const std::vector &blocks_entry, std::vector &blocks) { - MTRACE("Blockchain::" << __func__); + oxen::log::trace(logcat, "Blockchain::{}", __func__); auto prepare = std::chrono::steady_clock::now(); uint64_t bytes = 0; size_t total_txs = 0; @@ -5191,7 +5189,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector> maps(threads); auto it = blocks_entry.begin(); unsigned blockidx = 0; @@ -5212,7 +5210,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector 1 && threads > 1 && m_show_time_stats) - MDEBUG("Prepare blocks took: " << tools::friendly_duration(prepare_elapsed)); + oxen::log::debug(logcat, "Prepare blocks took: {}", tools::friendly_duration(prepare_elapsed)); auto scantable = std::chrono::steady_clock::now(); @@ -5299,13 +5297,6 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector> tx_map; std::vector> txes(total_txs); -#define SCAN_TABLE_QUIT(m) \ - do { \ - MERROR_VER(m) ;\ - m_scan_table.clear(); \ - return false; \ - } while(0); \ - // generate sorted tables for all amounts and absolute offsets size_t tx_index = 0, block_index = 0; for (const auto &entry : blocks_entry) @@ -5316,18 +5307,30 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector= txes.size()) - SCAN_TABLE_QUIT("tx_index is out of sync"); + { + oxen::log::error(oxen::log::Cat("verify"), "tx_index is out of sync"); + m_scan_table.clear(); + return false; + } transaction &tx = txes[tx_index].first; crypto::hash &tx_prefix_hash = txes[tx_index].second; ++tx_index; if (!parse_and_validate_tx_base_from_blob(tx_blob, tx)) - SCAN_TABLE_QUIT("Could not parse tx from incoming blocks."); + { + oxen::log::error(oxen::log::Cat("verify"), "Could not parse tx from incoming blocks"); + m_scan_table.clear(); + return false; + } cryptonote::get_transaction_prefix_hash(tx, tx_prefix_hash); auto its = m_scan_table.find(tx_prefix_hash); if (its != m_scan_table.end()) - SCAN_TABLE_QUIT("Duplicate tx found from incoming blocks."); + { + oxen::log::error(oxen::log::Cat("verify"), "Duplicate tx found from incoming blocks."); + m_scan_table.clear(); + return false; + } m_scan_table.emplace(tx_prefix_hash, std::unordered_map>()); its = m_scan_table.find(tx_prefix_hash); @@ -5344,7 +5347,11 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vectorsecond.find(in_to_key.k_image); if (it != its->second.end()) - SCAN_TABLE_QUIT("Duplicate key_image found from incoming blocks."); + { + oxen::log::error(oxen::log::Cat("verify"), "Duplicate key_image found from incoming blocks."); + m_scan_table.clear(); + return false; + } amounts.push_back(in_to_key.amount); } @@ -5426,14 +5433,22 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector= txes.size()) - SCAN_TABLE_QUIT("tx_index is out of sync"); + { + oxen::log::error(oxen::log::Cat("verify"), "tx_index is out of sync"); + m_scan_table.clear(); + return false; + } const transaction &tx = txes[tx_index].first; const crypto::hash &tx_prefix_hash = txes[tx_index].second; ++tx_index; auto its = m_scan_table.find(tx_prefix_hash); if (its == m_scan_table.end()) - SCAN_TABLE_QUIT("Tx not found on scan table from incoming blocks."); + { + oxen::log::error(oxen::log::Cat("verify"), "Tx not found on scan table from incoming blocks."); + m_scan_table.clear(); + return false; + } for (const auto &txin : tx.vin) { @@ -5476,7 +5491,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector> m_db->for_all_alt_blocks([&alt_blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string *block_blob, const std::string *checkpoint_blob) { if (!block_blob) { - MERROR("No blob, but blobs were requested"); + oxen::log::error(logcat, "No blob, but blobs were requested"); return false; } @@ -5579,7 +5594,7 @@ std::vector> if (data.checkpointed && checkpoint_blob) { if (!t_serializable_object_from_blob(checkpoint, *checkpoint_blob)) - MERROR("Failed to parse checkpoint from blob"); + oxen::log::error(logcat, "Failed to parse checkpoint from blob"); } cryptonote::block block; @@ -5589,7 +5604,7 @@ std::vector> alt_blocks.insert(std::make_pair(cryptonote::get_block_hash(bei.bl), std::move(bei))); } else - MERROR("Failed to parse block from blob"); + oxen::log::error(logcat, "Failed to parse block from blob"); return true; }, true); @@ -5637,30 +5652,30 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get std::string_view checkpoints = get_checkpoints(m_nettype); if (!checkpoints.empty()) { - MINFO("Loading precomputed blocks (" << checkpoints.size() << " bytes)"); + oxen::log::info(logcat, "Loading precomputed blocks ({} bytes)", checkpoints.size()); if (m_nettype == network_type::MAINNET) { // first check hash crypto::hash hash; if (!tools::sha256sum_str(checkpoints, hash)) { - MERROR("Failed to hash precomputed blocks data"); + oxen::log::error(logcat, "Failed to hash precomputed blocks data"); return; } constexpr auto EXPECTED_SHA256_HASH = "d5772a74dadb64a439b60312f9dc3e5243157c5477037a318840b8c36da9644b"sv; - MINFO("Precomputed blocks hash: " << hash << ", expected " << EXPECTED_SHA256_HASH); + oxen::log::info(logcat, "Precomputed blocks hash: {}, expected {}", hash, EXPECTED_SHA256_HASH); crypto::hash expected_hash; if (!tools::hex_to_type(EXPECTED_SHA256_HASH, expected_hash)) { - MERROR("Failed to parse expected block hashes hash"); + oxen::log::error(logcat, "Failed to parse expected block hashes hash"); return; } if (hash != expected_hash) { - MERROR("Block hash data does not match expected hash"); + oxen::log::error(logcat, "Block hash data does not match expected hash"); return; } } @@ -5670,13 +5685,13 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get auto nblocks = oxenc::load_little_to_host(checkpoints.data()); if (nblocks > (std::numeric_limits::max() - 4) / sizeof(hash)) { - MERROR("Block hash data is too large"); + oxen::log::error(logcat, "Block hash data is too large"); return; } const size_t size_needed = 4 + (nblocks * sizeof(crypto::hash)); if(checkpoints.size() != size_needed) { - MERROR("Failed to load hashes - unexpected data size " << checkpoints.size() << ", expected " << size_needed); + oxen::log::error(logcat, "Failed to load hashes - unexpected data size {}, expected {}", checkpoints.size(), size_needed); return; } else if(nblocks > 0 && nblocks > (m_db->height() + HASH_OF_HASHES_STEP - 1) / HASH_OF_HASHES_STEP) @@ -5690,7 +5705,7 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get checkpoints.remove_prefix(sizeof(hash.data)); } m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, crypto::null_hash); - MINFO(nblocks << " block hashes loaded"); + oxen::log::info(logcat, "{} block hashes loaded", nblocks); // FIXME: clear tx_pool because the process might have been // terminated and caused it to store txs kept by blocks. @@ -5754,13 +5769,13 @@ bool Blockchain::for_all_outputs(uint64_t amount, std::function +#include +#include DISABLE_VS_WARNINGS(4355) -#define MERROR_VER(x) MCERROR("verify", x) - #define BAD_SEMANTICS_TXES_MAX_SIZE 100 // basically at least how many bytes the block itself serializes to without the miner tx @@ -85,6 +84,10 @@ DISABLE_VS_WARNINGS(4355) namespace cryptonote { + + static auto logcat = oxen::log::Cat("cn"); + static auto omqlogcat = oxen::log::Cat("omq"); + const command_line::arg_descriptor arg_testnet_on = { "testnet" , "Run on testnet. The wallet must be launched with --testnet flag." @@ -380,7 +383,7 @@ namespace cryptonote bool args_okay = true; if (m_quorumnet_port == 0) { - MFATAL("Quorumnet port cannot be 0; please specify a valid port to listen on with: '--" << arg_quorumnet_port.name << " '"); + oxen::log::error(logcat, "Quorumnet port cannot be 0; please specify a valid port to listen on with: '--{} '", arg_quorumnet_port.name); args_okay = false; } @@ -388,28 +391,28 @@ namespace cryptonote if (pub_ip.size()) { if (!epee::string_tools::get_ip_int32_from_string(m_sn_public_ip, pub_ip)) { - MFATAL("Unable to parse IPv4 public address from: " << pub_ip); + oxen::log::error(logcat, "Unable to parse IPv4 public address from: {}", pub_ip); args_okay = false; } if (!epee::net_utils::is_ip_public(m_sn_public_ip)) { if (m_service_node_list.debug_allow_local_ips) { - MWARNING("Address given for public-ip is not public; allowing it because dev-allow-local-ips was specified. This service node WILL NOT WORK ON THE PUBLIC OXEN NETWORK!"); + oxen::log::warning(logcat, "Address given for public-ip is not public; allowing it because dev-allow-local-ips was specified. This service node WILL NOT WORK ON THE PUBLIC OXEN NETWORK!"); } else { - MFATAL("Address given for public-ip is not public: " << epee::string_tools::get_ip_string_from_int32(m_sn_public_ip)); + oxen::log::error(logcat, "Address given for public-ip is not public: {}", epee::string_tools::get_ip_string_from_int32(m_sn_public_ip)); args_okay = false; } } } else { - MFATAL("Please specify an IPv4 public address which the service node & storage server is accessible from with: '--" << arg_public_ip.name << " '"); + oxen::log::error(logcat, "Please specify an IPv4 public address which the service node & storage server is accessible from with: '--{} '", arg_public_ip.name); args_okay = false; } if (!args_okay) { - MFATAL("IMPORTANT: One or more required service node-related configuration settings/options were omitted or invalid; " - << "please fix them and restart oxend."); + oxen::log::error(logcat, + "IMPORTANT: One or more required service node-related configuration settings/options were omitted or invalid please fix them and restart oxend."); return false; } } @@ -589,14 +592,14 @@ namespace cryptonote // make sure the data directory exists, and try to lock it if (std::error_code ec; !fs::is_directory(folder, ec) && !fs::create_directories(folder, ec) && ec) { - MFATAL("Failed to create directory " + folder.u8string() + (ec ? ": " + ec.message() : ""s)); + oxen::log::error(logcat, "Failed to create directory " + folder.u8string() + (ec ? ": " + ec.message() : ""s)); return false; } std::unique_ptr db(new_db()); if (!db) { - LOG_ERROR("Failed to initialize a database"); + oxen::log::error(logcat, "Failed to initialize a database"); return false; } @@ -612,7 +615,7 @@ namespace cryptonote auto sqliteDB = std::make_shared(m_nettype, sqlite_db_file_path); folder /= db->get_db_name(); - MGINFO("Loading blockchain from folder " << folder << " ..."); + oxen::log::info(logcat, "Loading blockchain from folder {} ...", folder); // default to fast:async:1 if overridden blockchain_db_sync_mode sync_mode = db_defaultsync; @@ -624,7 +627,7 @@ namespace cryptonote // reset the db by removing the database file before opening it if (!db->remove_data_file(folder)) { - MFATAL("Failed to remove data file in " << folder); + oxen::log::error(logcat, "Failed to remove data file in {}", folder); return false; } fs::remove(ons_db_file_path); @@ -640,7 +643,7 @@ namespace cryptonote const bool db_sync_mode_is_default = command_line::is_arg_defaulted(vm, cryptonote::arg_db_sync_mode); for(const auto &option : options) - MDEBUG("option: " << option); + oxen::log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -699,7 +702,7 @@ namespace cryptonote } else { - LOG_ERROR("Invalid db sync mode: " << options[2]); + oxen::log::error(logcat, "Invalid db sync mode: {}", options[2]); return false; } } @@ -713,7 +716,7 @@ namespace cryptonote } catch (const DB_ERROR& e) { - LOG_ERROR("Error opening database: " << e.what()); + oxen::log::error(logcat, "Error opening database: {}", e.what()); return false; } @@ -739,7 +742,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Failed to parse reorg notify spec"); + oxen::log::error(logcat, "Failed to parse reorg notify spec"); } try @@ -753,7 +756,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Failed to parse block notify spec"); + oxen::log::error(logcat, "Failed to parse block rate notify spec"); } cryptonote::test_options regtest_test_options{}; @@ -805,9 +808,9 @@ namespace cryptonote block_sync_size = command_line::get_arg(vm, arg_block_sync_size); if (block_sync_size > BLOCKS_SYNCHRONIZING_MAX_COUNT) - MERROR("Error --block-sync-size cannot be greater than " << BLOCKS_SYNCHRONIZING_MAX_COUNT); + oxen::log::error(logcat, "Error --block-sync-size cannot be greater than {}", BLOCKS_SYNCHRONIZING_MAX_COUNT); - MGINFO("Loading checkpoints"); + oxen::log::info(logcat, "Loading checkpoints"); CHECK_AND_ASSERT_MES(update_checkpoints_from_json_file(), false, "One or more checkpoints loaded from json conflicted with existing checkpoints."); r = m_miner.init(vm, m_nettype); @@ -821,7 +824,7 @@ namespace cryptonote // display a message if the blockchain is not pruned yet if (!m_blockchain_storage.get_blockchain_pruning_seed()) { - MGINFO("Pruning blockchain..."); + oxen::log::info(logcat, "Pruning blockchain..."); CHECK_AND_ASSERT_MES(m_blockchain_storage.prune_blockchain(), false, "Failed to prune blockchain"); } else @@ -860,7 +863,7 @@ namespace cryptonote try { generate_pair(privkey, pubkey); } catch (const std::exception& e) { - MFATAL("failed to generate keypair " << e.what()); + oxen::log::error(logcat, "failed to generate keypair {}", e.what()); return false; } @@ -939,34 +942,21 @@ namespace cryptonote } if (m_service_node) { - MGINFO_YELLOW("Service node public keys:"); - MGINFO_YELLOW("- primary: " << tools::type_to_hex(keys.pub)); - MGINFO_YELLOW("- ed25519: " << tools::type_to_hex(keys.pub_ed25519)); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Service node public keys:")); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- primary: {}", tools::type_to_hex(keys.pub))); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- ed25519: {}", tools::type_to_hex(keys.pub_ed25519))); // .snode address is the ed25519 pubkey, encoded with base32z and with .snode appended: - MGINFO_YELLOW("- lokinet: " << oxenc::to_base32z(tools::view_guts(keys.pub_ed25519)) << ".snode"); - MGINFO_YELLOW("- x25519: " << tools::type_to_hex(keys.pub_x25519)); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- lokinet: {}.snode", oxenc::to_base32z(tools::view_guts(keys.pub_ed25519)))); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- x25519: {}", tools::type_to_hex(keys.pub_x25519))); } else { // Only print the x25519 version because it's the only thing useful for a non-SN (for // encrypted LMQ RPC connections). - MGINFO_YELLOW("x25519 public key: " << tools::type_to_hex(keys.pub_x25519)); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "x25519 public key: {}", tools::type_to_hex(keys.pub_x25519))); } return true; } - static constexpr el::Level easylogging_level(oxenmq::LogLevel level) { - using namespace oxenmq; - switch (level) { - case LogLevel::fatal: return el::Level::Fatal; - case LogLevel::error: return el::Level::Error; - case LogLevel::warn: return el::Level::Warning; - case LogLevel::info: return el::Level::Info; - case LogLevel::debug: return el::Level::Debug; - case LogLevel::trace: return el::Level::Trace; - default: return el::Level::Unknown; - } - } - oxenmq::AuthLevel core::omq_check_access(const crypto::x25519_public_key& pubkey) const { auto it = m_omq_auth.find(pubkey); if (it != m_omq_auth.end()) @@ -995,29 +985,29 @@ namespace cryptonote if (user_auth >= AuthLevel::basic) { if (user_auth > auth) auth = user_auth; - MCINFO("omq", "Incoming " << auth << "-authenticated connection"); + oxen::log::info(oxen::log::Cat("omq"), "Incoming {}-authenticated connection", auth); } - MCINFO("omq", "Incoming [" << auth << "] curve connection from " << ip << "/" << x25519_pubkey); + oxen::log::info(oxen::log::Cat("omq"), "Incoming [{}] curve connection from {}/{}", auth, ip, x25519_pubkey); } else { - MCINFO("omq", "Incoming [" << auth << "] plain connection from " << ip); + oxen::log::info(oxen::log::Cat("omq"), "Incoming [{}] plain connection from {}", auth, ip); } return auth; } void core::init_oxenmq(const boost::program_options::variables_map& vm) { using namespace oxenmq; - MGINFO("Starting oxenmq"); + oxen::log::info(omqlogcat, "Starting oxenmq"); m_omq = std::make_unique( tools::copy_guts(m_service_keys.pub_x25519), tools::copy_guts(m_service_keys.key_x25519), m_service_node, [this](std::string_view x25519_pk) { return m_service_node_list.remote_lookup(x25519_pk); }, - [](LogLevel level, const char *file, int line, std::string msg) { - // What a lovely interface (<-- sarcasm) - if (ELPP->vRegistry()->allowed(easylogging_level(level), "omq")) - el::base::Writer(easylogging_level(level), file, line, ELPP_FUNC, el::base::DispatchAction::NormalLog).construct("omq") << msg; + [](LogLevel omqlevel, const char *file, int line, std::string msg) { + auto level = *oxen::logging::parse_level(omqlevel); + if(omqlogcat->should_log(level)) + omqlogcat->log({file, line, "omq"}, level, "{}", msg); }, oxenmq::LogLevel::trace ); @@ -1025,7 +1015,7 @@ namespace cryptonote // ping.ping: a simple debugging target for pinging the omq listener m_omq->add_category("ping", Access{AuthLevel::none}) .add_request_command("ping", [](Message& m) { - MCINFO("omq", "Received ping from " << m.conn); + oxen::log::info(oxen::log::Cat("omq"), "Received ping from {}", m.conn); m.send_reply("pong"); }) ; @@ -1037,7 +1027,7 @@ namespace cryptonote if (listen_ip.empty()) listen_ip = "0.0.0.0"; std::string qnet_listen = "tcp://" + listen_ip + ":" + std::to_string(m_quorumnet_port); - MGINFO("- listening on " << qnet_listen << " (quorumnet)"); + oxen::log::info(logcat, "- listening on {} (quorumnet)", qnet_listen); m_omq->listen_curve(qnet_listen, [this, public_=command_line::get_arg(vm, arg_omq_quorumnet_public)](std::string_view ip, std::string_view pk, bool) { return omq_allow(ip, pk, public_ ? AuthLevel::basic : AuthLevel::none); @@ -1116,14 +1106,14 @@ namespace cryptonote { if(tx_info.blob->size() > MAX_TX_SIZE) { - LOG_PRINT_L1("WRONG TRANSACTION BLOB, too big size " << tx_info.blob->size() << ", rejected"); + oxen::log::info(logcat, "WRONG TRANSACTION BLOB, too big size {}, rejected", tx_info.blob->size()); tx_info.tvc.m_verifivation_failed = true; tx_info.tvc.m_too_big = true; return; } else if (tx_info.blob->empty()) { - LOG_PRINT_L1("WRONG TRANSACTION BLOB, blob is empty, rejected"); + oxen::log::info(logcat, "WRONG TRANSACTION BLOB, blob is empty, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1131,7 +1121,7 @@ namespace cryptonote tx_info.parsed = parse_and_validate_tx_from_blob(*tx_info.blob, tx_info.tx, tx_info.tx_hash); if(!tx_info.parsed) { - LOG_PRINT_L1("WRONG TRANSACTION BLOB, Failed to parse, rejected"); + oxen::log::info(logcat, "WRONG TRANSACTION BLOB, Failed to parse, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1142,7 +1132,7 @@ namespace cryptonote { if (bad_semantics_txes[idx].find(tx_info.tx_hash) != bad_semantics_txes[idx].end()) { - LOG_PRINT_L1("Transaction already seen with bad semantics, rejected"); + oxen::log::info(logcat, "Transaction already seen with bad semantics, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1152,7 +1142,7 @@ namespace cryptonote //----------------------------------------------------------------------------------------------- void core::set_semantics_failed(const crypto::hash &tx_hash) { - LOG_PRINT_L1("WRONG TRANSACTION BLOB, Failed to check tx " << tx_hash << " semantic, rejected"); + oxen::log::info(logcat, "WRONG TRANSACTION BLOB, Failed to check tx {} semantic, rejected", tx_hash); bad_semantics_txes_lock.lock(); bad_semantics_txes[0].insert(tx_hash); if (bad_semantics_txes[0].size() >= BAD_SEMANTICS_TXES_MAX_SIZE) @@ -1177,7 +1167,7 @@ namespace cryptonote { if (kept_by_block && get_blockchain_storage().is_within_compiled_block_hash_area()) { - MTRACE("Skipping semantics check for txs kept by block in embedded hash area"); + oxen::log::trace(logcat, "Skipping semantics check for txs kept by block in embedded hash area"); return; } @@ -1201,7 +1191,7 @@ namespace cryptonote switch (rv.type) { case rct::RCTType::Null: // coinbase should not come here, so we reject for all other types - MERROR_VER("Unexpected Null rctSig type"); + oxen::log::error(oxen::log::Cat("verify"), "Unexpected Null rctSig type"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1209,7 +1199,7 @@ namespace cryptonote case rct::RCTType::Simple: if (!rct::verRctSemanticsSimple(rv)) { - MERROR_VER("rct signature semantics check failed"); + oxen::log::error(oxen::log::Cat("verify"), "rct signature semantics check failed"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1219,7 +1209,7 @@ namespace cryptonote case rct::RCTType::Full: if (!rct::verRct(rv, true)) { - MERROR_VER("rct signature semantics check failed"); + oxen::log::error(oxen::log::Cat("verify"), "rct signature semantics check failed"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1231,7 +1221,7 @@ namespace cryptonote case rct::RCTType::CLSAG: if (!is_canonical_bulletproof_layout(rv.p.bulletproofs)) { - MERROR_VER("Bulletproof does not have canonical form"); + oxen::log::error(oxen::log::Cat("verify"), "Bulletproof does not have canonical form"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1240,7 +1230,7 @@ namespace cryptonote rvv.push_back(&rv); // delayed batch verification break; default: - MERROR_VER("Unknown rct type: " << (int)rv.type); + oxen::log::error(oxen::log::Cat("verify"), "Unknown rct type: {}", (int)rv.type); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1249,7 +1239,7 @@ namespace cryptonote } if (!rvv.empty() && !rct::verRctSemanticsSimple(rvv)) { - LOG_PRINT_L1("One transaction among this group has bad semantics, verifying one at a time"); + oxen::log::info(logcat, "One transaction among this group has bad semantics, verifying one at a time"); const bool assumed_bad = rvv.size() == 1; // if there's only one tx, it must be the bad one for (size_t n = 0; n < tx_info.size(); ++n) { @@ -1284,7 +1274,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR_VER("Exception in handle_incoming_tx_pre: " << e.what()); + oxen::log::error(oxen::log::Cat("verify"), "Exception in handle_incoming_tx_pre: {}", e.what()); info.tvc.m_verifivation_failed = true; } }); @@ -1297,12 +1287,12 @@ namespace cryptonote if(m_mempool.have_tx(info.tx_hash)) { - LOG_PRINT_L2("tx " << info.tx_hash << " already have transaction in tx_pool"); + oxen::log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); info.already_have = true; } else if(m_blockchain_storage.have_tx(info.tx_hash)) { - LOG_PRINT_L2("tx " << info.tx_hash << " already have transaction in blockchain"); + oxen::log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); info.already_have = true; } } @@ -1346,15 +1336,15 @@ namespace cryptonote } if (m_mempool.add_tx(info.tx, info.tx_hash, *info.blob, weight, info.tvc, *local_opts, version, blink_rollback_height)) { - MDEBUG("tx added: " << info.tx_hash); + oxen::log::debug(logcat, "tx added: {}", info.tx_hash); } else { ok = false; if (info.tvc.m_verifivation_failed) - MERROR_VER("Transaction verification failed: " << info.tx_hash); + oxen::log::error(oxen::log::Cat("verify"), "Transaction verification failed: {}", info.tx_hash); else if (info.tvc.m_verifivation_impossible) - MERROR_VER("Transaction verification impossible: " << info.tx_hash); + oxen::log::error(oxen::log::Cat("verify"), "Transaction verification impossible: {}", info.tx_hash); } } @@ -1415,7 +1405,7 @@ namespace cryptonote } } - MDEBUG("Want " << want_count << " of " << blinks.size() << " incoming blink signature sets after filtering out immutable txes"); + oxen::log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out immutable txes", want_count, blinks.size()); if (!want_count) return results; // Step 2: filter out any transactions for which we already have a blink signature @@ -1425,14 +1415,14 @@ namespace cryptonote { if (want[i] && m_mempool.has_blink(blinks[i].tx_hash)) { - MDEBUG("Ignoring blink data for " << blinks[i].tx_hash << ": already have blink signatures"); + oxen::log::debug(logcat, "Ignoring blink data for {}: already have blink signatures", blinks[i].tx_hash); want[i] = false; // Already have it, move along want_count--; } } } - MDEBUG("Want " << want_count << " of " << blinks.size() << " incoming blink signature sets after filtering out existing blink sigs"); + oxen::log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out existing blink sigs", want_count, blinks.size()); if (!want_count) return results; // Step 3: create new blink_tx objects for txes and add the blink signatures. We can do all of @@ -1458,7 +1448,7 @@ namespace cryptonote std::any_of(bdata.position.begin(), bdata.position.end(), [](const auto &p) { return p >= service_nodes::BLINK_SUBQUORUM_SIZE; }) || // invalid position std::any_of(bdata.quorum.begin(), bdata.quorum.end(), [](const auto &qi) { return qi >= tools::enum_count; }) // invalid quorum index ) { - MINFO("Invalid blink tx " << bdata.tx_hash << ": invalid signature data"); + oxen::log::info(logcat, "Invalid blink tx {}: invalid signature data", bdata.tx_hash); continue; } @@ -1472,7 +1462,7 @@ namespace cryptonote q = get_quorum(service_nodes::quorum_type::blink, q_height); if (!q) { - MINFO("Don't have a quorum for height " << q_height << " (yet?), ignoring this blink"); + oxen::log::info(logcat, "Don't have a quorum for height {} (yet?), ignoring this blink", q_height); no_quorum = true; break; } @@ -1493,9 +1483,9 @@ namespace cryptonote } if (blink.approved()) { - MINFO("Blink tx " << bdata.tx_hash << " blink signatures approved with " << failures.size() << " signature validation failures"); + oxen::log::info(logcat, "Blink tx {} blink signatures approved with {} signature validation failures", bdata.tx_hash, failures.size()); for (auto &f : failures) - MDEBUG("- failure for quorum " << int(bdata.quorum[f.first]) << ", position " << int(bdata.position[f.first]) << ": " << f.second); + oxen::log::debug(logcat, "- failure for quorum {}, position {}: {}", int(bdata.quorum[f.first]), int(bdata.position[f.first]), f.second); } else { @@ -1503,7 +1493,7 @@ namespace cryptonote os << "Blink validation failed:"; for (auto &f : failures) os << " [" << int(bdata.quorum[f.first]) << ":" << int(bdata.position[f.first]) << "]: " << f.second; - MINFO("Invalid blink tx " << bdata.tx_hash << ": " << os.str()); + oxen::log::info(logcat, "Invalid blink tx {}: {}", bdata.tx_hash, os.str()); } } @@ -1525,7 +1515,7 @@ namespace cryptonote if (added) { - MINFO("Added blink signatures for " << added << " blinks"); + oxen::log::info(logcat, "Added blink signatures for {} blinks", added); long_poll_trigger(m_mempool); } @@ -1544,7 +1534,7 @@ namespace cryptonote { if (tx.vin.empty()) { - MERROR_VER("tx with empty inputs, rejected for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx with empty inputs, rejected for tx id= {}", get_transaction_hash(tx)); return false; } } @@ -1552,20 +1542,20 @@ namespace cryptonote { if (tx.vin.size() != 0) { - MERROR_VER("tx type: " << tx.type << " must have 0 inputs, received: " << tx.vin.size() << ", rejected for tx id = " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx type: {} must have 0 inputs, received: {}, rejected for tx id = {}", tx.type, tx.vin.size(), get_transaction_hash(tx)); return false; } } if(!check_inputs_types_supported(tx)) { - MERROR_VER("unsupported input types for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "unsupported input types for tx id= {}", get_transaction_hash(tx)); return false; } if(!check_outs_valid(tx)) { - MERROR_VER("tx with invalid outputs, rejected for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx with invalid outputs, rejected for tx id= {}", get_transaction_hash(tx)); return false; } @@ -1573,14 +1563,14 @@ namespace cryptonote { if (tx.rct_signatures.outPk.size() != tx.vout.size()) { - MERROR_VER("tx with mismatched vout/outPk count, rejected for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx with mismatched vout/outPk count, rejected for tx id= {}", get_transaction_hash(tx)); return false; } } if(!check_money_overflow(tx)) { - MERROR_VER("tx has money overflow, rejected for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx has money overflow, rejected for tx id= {}", get_transaction_hash(tx)); return false; } @@ -1592,32 +1582,32 @@ namespace cryptonote if(amount_in <= amount_out) { - MERROR_VER("tx with wrong amounts: ins " << amount_in << ", outs " << amount_out << ", rejected for tx id= " << get_transaction_hash(tx)); + oxen::log::error(oxen::log::Cat("verify"), "tx with wrong amounts: ins {}, outs {}, rejected for tx id= {}", amount_in, amount_out, get_transaction_hash(tx)); return false; } } if(!keeped_by_block && get_transaction_weight(tx) >= m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE) { - MERROR_VER("tx is too large " << get_transaction_weight(tx) << ", expected not bigger than " << m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE); + oxen::log::error(oxen::log::Cat("verify"), "tx is too large {}, expected not bigger than {}", get_transaction_weight(tx), m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE); return false; } if(!check_tx_inputs_keyimages_diff(tx)) { - MERROR_VER("tx uses a single key image more than once"); + oxen::log::error(oxen::log::Cat("verify"), "tx uses a single key image more than once"); return false; } if (!check_tx_inputs_ring_members_diff(tx)) { - MERROR_VER("tx uses duplicate ring members"); + oxen::log::error(oxen::log::Cat("verify"), "tx uses duplicate ring members"); return false; } if (!check_tx_inputs_keyimages_domain(tx)) { - MERROR_VER("tx uses key image not in the valid domain"); + oxen::log::error(oxen::log::Cat("verify"), "tx uses key image not in the valid domain"); return false; } @@ -1644,7 +1634,7 @@ namespace cryptonote "quorum.timestamp", [this, pubkey](bool success, std::vector data) { const time_t local_seconds = time(nullptr); - MDEBUG("Timestamp message received: " << data[0] <<", local time is: " << local_seconds); + oxen::log::debug(logcat, "Timestamp message received: {}, local time is: ", data[0], local_seconds); if(success){ int64_t received_seconds; if (tools::parse_int(data[0],received_seconds)){ @@ -1661,7 +1651,7 @@ namespace cryptonote // Counts the number of times we have been out of sync if (m_sn_times.failures() > (m_sn_times.size() * service_nodes::MAXIMUM_EXTERNAL_OUT_OF_SYNC/100)) { - MWARNING("service node time might be out of sync"); + oxen::log::warning(logcat, "service node time might be out of sync"); // If we are out of sync record the other service node as in sync m_service_node_list.record_timesync_status(pubkey, true); } else { @@ -1773,7 +1763,7 @@ namespace cryptonote if (cache_to > 0 && count > CACHE_EXCLUSIVE) { cache_build_started = std::chrono::steady_clock::now(); m_coinbase_cache.building = true; // Block out other threads until we're done - MINFO("Starting slow cache build request for get_coinbase_tx_sum(" << start_offset << ", " << count << ")"); + oxen::log::info(logcat, "Starting slow cache build request for get_coinbase_tx_sum({}, {})", start_offset, count); } } } @@ -1810,8 +1800,8 @@ namespace cryptonote if (m_coinbase_cache.building) { m_coinbase_cache.building = false; - MINFO("Finishing cache build for get_coinbase_tx_sum in " << - std::chrono::duration{std::chrono::steady_clock::now() - cache_build_started}.count() << "s"); + oxen::log::info(logcat, "Finishing cache build for get_coinbase_tx_sum in {} s", + std::chrono::duration{std::chrono::steady_clock::now() - cache_build_started}.count()); } cache_to = 0; } @@ -1904,7 +1894,7 @@ namespace cryptonote } if (relayed) - MGINFO("Submitted uptime-proof for Service Node (yours): " << m_service_keys.pub); + oxen::log::info(logcat, "Submitted uptime-proof for Service Node (yours): {}", m_service_keys.pub); return true; } @@ -1946,7 +1936,7 @@ namespace cryptonote crypto::hash tx_hash; if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash)) { - LOG_ERROR("Failed to parse relayed transaction"); + oxen::log::error(logcat, "Failed to parse relayed transaction"); return crypto::null_hash; } txs.push_back(std::make_pair(tx_hash, std::move(tx_blob))); @@ -2065,7 +2055,7 @@ namespace cryptonote std::vector pblocks; if (!prepare_handle_incoming_blocks(blocks, pblocks)) { - MERROR("Block found, but failed to prepare to add"); + oxen::log::error(logcat, "Block found, but failed to prepare to add"); return false; } // add_new_block will verify block and set bvc.m_verification_failed accordingly @@ -2077,7 +2067,7 @@ namespace cryptonote if (bvc.m_verifivation_failed) { bool pulse = cryptonote::block_has_pulse_components(b); - MERROR_VER((pulse ? "Pulse" : "Mined") << " block failed verification\n" << cryptonote::obj_to_json_str(b)); + oxen::log::error(oxen::log::Cat("verify"), "{} block failed verification\n{}", (pulse ? "Pulse" : "Mined"), cryptonote::obj_to_json_str(b)); return false; } else if(bvc.m_added_to_main_chain) @@ -2087,7 +2077,7 @@ namespace cryptonote m_blockchain_storage.get_transactions_blobs(b.tx_hashes, txs, &missed_txs); if(missed_txs.size() && m_blockchain_storage.get_block_id_by_height(get_block_height(b)) != get_block_hash(b)) { - LOG_PRINT_L1("Block found but, seems that reorganize just happened after that, do not relay this block"); + oxen::log::info(logcat, "Block found but, seems that reorganize just happened after that, do not relay this block"); return true; } CHECK_AND_ASSERT_MES(txs.size() == b.tx_hashes.size() && !missed_txs.size(), false, "can't find some transactions in found block:" << get_block_hash(b) << " txs.size()=" << txs.size() @@ -2157,7 +2147,7 @@ namespace cryptonote } if (((size_t)-1) <= 0xffffffff && block_blob.size() >= 0x3fffffff) - MWARNING("This block's size is " << block_blob.size() << ", closing on the 32 bit limit"); + oxen::log::warning(logcat, "This block's size is {}, closing on the 32 bit limit", block_blob.size()); CHECK_AND_ASSERT_MES(update_checkpoints_from_json_file(), false, "One or more checkpoints loaded from json conflicted with existing checkpoints."); @@ -2167,7 +2157,7 @@ namespace cryptonote crypto::hash block_hash; if(!parse_and_validate_block_from_blob(block_blob, lb, block_hash)) { - LOG_PRINT_L1("Failed to parse and validate new block"); + oxen::log::info(logcat, "Failed to parse and validate new block"); bvc.m_verifivation_failed = true; return false; } @@ -2192,7 +2182,7 @@ namespace cryptonote // plus the tx hashes, the weight will typically be much larger than the blob size if(block_blob.size() > m_blockchain_storage.get_current_cumulative_block_weight_limit() + BLOCK_SIZE_SANITY_LEEWAY) { - LOG_PRINT_L1("WRONG BLOCK BLOB, sanity check failed on size " << block_blob.size() << ", rejected"); + oxen::log::info(logcat, "WRONG BLOCK BLOB, sanity check failed on size {}, rejected", block_blob.size()); return false; } return true; @@ -2241,7 +2231,7 @@ namespace cryptonote const std::chrono::seconds elapsed{std::time(nullptr) - last_ping}; if (elapsed > lifetime) { - MWARNING("Have not heard from " << what << " " << + oxen::log::warning(logcat, "Have not heard from {} {}", what, (!last_ping ? "since starting" : "since more than " + tools::get_human_readable_timespan(elapsed) + " ago")); return false; @@ -2278,9 +2268,8 @@ namespace cryptonote auto pubkey = m_service_node_list.get_pubkey_from_x25519(m_service_keys.pub_x25519); if (pubkey != crypto::null_pkey && pubkey != m_service_keys.pub && m_service_node_list.is_service_node(pubkey, false /*don't require active*/)) { - MGINFO_RED( - "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as " - "this service node. This typically means both have the same 'key_ed25519' private key file."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as this service node. This typically means both have the same 'key_ed25519' private key file.")); return; } @@ -2295,12 +2284,7 @@ namespace cryptonote if (pk != m_service_keys.pub && proof.proof->public_ip == m_sn_public_ip && (proof.proof->qnet_port == m_quorumnet_port || ( m_nettype != network_type::DEVNET && (proof.proof->storage_https_port == storage_https_port() || proof.proof->storage_omq_port == storage_omq_port())))) - MGINFO_RED( - "Another service node (" << pk << ") is broadcasting the same public IP and ports as this service node (" << - epee::string_tools::get_ip_string_from_int32(m_sn_public_ip) << ":" << proof.proof->qnet_port << "[qnet], :" << - proof.proof->storage_https_port << "[SS-HTTP], :" << proof.proof->storage_omq_port << "[SS-LMQ]). " - "This will lead to deregistration of one or both service nodes if not corrected. " - "(Do both service nodes have the correct IP for the service-node-public-ip setting?)"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Another service node ({}) is broadcasting the same public IP and ports as this service node ({}:{}[qnet], :{}[SS-HTTP], :{}[SS-LMQ]). This will lead to deregistration of one or both service nodes if not corrected. (Do both service nodes have the correct IP for the service-node-public-ip setting?)", pk, epee::string_tools::get_ip_string_from_int32(m_sn_public_ip), proof.proof->qnet_port, proof.proof->storage_https_port, proof.proof->storage_omq_port)); }); } @@ -2308,16 +2292,14 @@ namespace cryptonote { if (!check_external_ping(m_last_storage_server_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "the storage server")) { - MGINFO_RED( - "Failed to submit uptime proof: have not heard from the storage server recently. Make sure that it " - "is running! It is required to run alongside the Loki daemon"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + "Failed to submit uptime proof: have not heard from the storage server recently. Make sure that it is running! It is required to run alongside the Loki daemon")); return; } if (!check_external_ping(m_last_lokinet_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "Lokinet")) { - MGINFO_RED( - "Failed to submit uptime proof: have not heard from lokinet recently. Make sure that it " - "is running! It is required to run alongside the Loki daemon"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + "Failed to submit uptime proof: have not heard from lokinet recently. Make sure that it is running! It is required to run alongside the Loki daemon")); return; } } @@ -2341,15 +2323,14 @@ namespace cryptonote main_message = "The daemon is running offline and will not attempt to sync to the Loki network."; else main_message = "The daemon will start synchronizing with the network. This may take a long time to complete."; - MGINFO_YELLOW("\n**********************************************************************\n" - << main_message << "\n" - << "\n" - << "You can set the level of process detailization through \"set_log \" command,\n" - << "where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING).\n" - << "\n" - << "Use the \"help\" command to see the list of available commands.\n" - << "Use \"help \" to see a command's documentation.\n" - << "**********************************************************************\n"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ +{}\n\n\ +You can set the level of process detailization through \"set_log \" command,\n\ +where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING).\n\ +\n\ +Use the \"help\" command to see the list of available commands.\n\ +Use \"help \" to see a command's documentation.\n\ +**********************************************************************\n", main_message)); m_starter_message_showed = true; } @@ -2380,10 +2361,7 @@ namespace cryptonote { uint64_t free_space = get_free_space(); if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB - { - const el::Level level = el::Level::Warning; - MCLOG_RED(level, "global", "Free space is below 1 GB on " << m_config_folder); - } + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Free space is below 1 GB on {}", m_config_folder)); return true; } //----------------------------------------------------------------------------------------------- @@ -2423,7 +2401,7 @@ namespace cryptonote { if (m_offline || m_nettype == network_type::FAKECHAIN || m_target_blockchain_height > get_current_blockchain_height() || m_target_blockchain_height == 0) { - MDEBUG("Not checking block rate, offline or syncing"); + oxen::log::debug(logcat, "Not checking block rate, offline or syncing"); return true; } @@ -2440,10 +2418,13 @@ namespace cryptonote const time_t time_boundary = now - static_cast(seconds[n]); for (time_t ts: timestamps) b += ts >= time_boundary; const double p = probability(b, seconds[n] / tools::to_seconds(TARGET_BLOCK_TIME)); - MDEBUG("blocks in the last " << seconds[n] / 60 << " minutes: " << b << " (probability " << p << ")"); + oxen::log::debug(logcat, "blocks in the last {} minutes: {} (probability {})", seconds[n] / 60, b, p); if (p < threshold) { - MWARNING("There were " << b << (b == max_blocks_checked ? " or more" : "") << " blocks in the last " << seconds[n] / 60 << " minutes, there might be large hash rate changes, or we might be partitioned, cut off from the Loki network or under attack, or your computer's time is off. Or it could be just sheer bad luck."); + oxen::log::warning(logcat, "There were {}{} blocks in the last {} minutes, \ + there might be large hash rate changes, or we might be partitioned, \ + cut off from the Loki network or under attack, or your computer's time is off. \ + Or it could be just sheer bad luck.", b, (b == max_blocks_checked ? " or more" : ""), seconds[n] / 60); break; // no need to look further } } diff --git a/src/cryptonote_core/cryptonote_tx_utils.cpp b/src/cryptonote_core/cryptonote_tx_utils.cpp index 65b8da30d..6bc59123d 100644 --- a/src/cryptonote_core/cryptonote_tx_utils.cpp +++ b/src/cryptonote_core/cryptonote_tx_utils.cpp @@ -41,6 +41,7 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "crypto/crypto.h" #include "crypto/hash.h" +#include "crypto/fmt.h" #include "ringct/rctSigs.h" #include "multisig/multisig.h" #include "epee/int-util.h" @@ -77,7 +78,7 @@ namespace cryptonote } } } - LOG_PRINT_L2("destinations include " << num_stdaddresses << " standard addresses and " << num_subaddresses << " subaddresses"); + oxen::log::debug(globallogcat, "destinations include {} standard addresses and {} subaddresses", num_stdaddresses, num_subaddresses); } keypair get_deterministic_keypair_from_height(uint64_t height) @@ -126,7 +127,7 @@ namespace cryptonote if (!get_deterministic_output_key(governance_wallet_address.address, gov_key, output_index, correct_key)) { - MERROR("Failed to generate deterministic output key for governance wallet output validation"); + oxen::log::error(globallogcat, "Failed to generate deterministic output key for governance wallet output validation"); return false; } @@ -288,7 +289,7 @@ namespace cryptonote block_reward_parts reward_parts{}; if(!get_oxen_block_reward(median_weight, current_block_weight, already_generated_coins, hard_fork_version, reward_parts, block_reward_context)) { - LOG_PRINT_L0("Failed to calculate block reward"); + oxen::log::warning(globallogcat, "Failed to calculate block reward"); return std::make_pair(false, block_rewards); } @@ -458,7 +459,7 @@ namespace cryptonote if (!get_deterministic_output_key(address, derivation_pair, it - rewards.begin(), out_eph_public_key)) { - MERROR("Failed to generate output one-time public key"); + oxen::log::error(globallogcat, "Failed to generate output one-time public key"); return std::make_pair(false, block_rewards); } @@ -514,13 +515,13 @@ namespace cryptonote uint64_t base_reward, base_reward_unpenalized; if (!get_base_block_reward(median_weight, current_block_weight, already_generated_coins, base_reward, base_reward_unpenalized, hard_fork_version, oxen_context.height)) { - MERROR("Failed to calculate base block reward"); + oxen::log::error(globallogcat, "Failed to calculate base block reward"); return false; } if (base_reward == 0) { - MERROR("Unexpected base reward of 0"); + oxen::log::error(globallogcat, "Unexpected base reward of 0"); return false; } @@ -574,9 +575,9 @@ namespace cryptonote if (allocated > base_reward_unpenalized || remainder != 0) { if (allocated > base_reward_unpenalized) - MERROR("We allocated more reward " << cryptonote::print_money(allocated) << " than what was available " << cryptonote::print_money(base_reward_unpenalized)); + oxen::log::error(globallogcat, "We allocated more reward {} than what was available {}", cryptonote::print_money(allocated), cryptonote::print_money(base_reward_unpenalized)); else - MERROR("We allocated reward but there was still " << cryptonote::print_money(remainder) << " oxen left to distribute."); + oxen::log::error(globallogcat, "We allocated reward but there was still {} oxen left to distribute.", cryptonote::print_money(remainder)); return false; } } @@ -617,7 +618,7 @@ namespace cryptonote if (sources.empty()) { - LOG_ERROR("Empty sources"); + oxen::log::error(globallogcat, "Empty sources"); return false; } @@ -639,7 +640,7 @@ namespace cryptonote if (tx_params.burn_percent) { - LOG_ERROR("cannot construct tx: internal error: burn percent must be converted to fixed burn amount in the wallet"); + oxen::log::error(globallogcat, "cannot construct tx: internal error: burn percent must be converted to fixed burn amount in the wallet"); return false; } @@ -648,9 +649,11 @@ namespace cryptonote if (tx.type == txtype::stake) { crypto::secret_key tx_sk{tx_key}; - bool added = hwdev.update_staking_tx_secret_key(tx_sk); - CHECK_AND_NO_ASSERT_MES(added, false, "Failed to add tx secret key to stake transaction"); - + if (!hwdev.update_staking_tx_secret_key(tx_sk)) + { + oxen::log::warning(globallogcat, "Failed to add tx secret key to stake transaction"); + return false; + } cryptonote::add_tx_secret_key_to_tx_extra(tx.extra, tx_sk); } @@ -667,17 +670,17 @@ namespace cryptonote crypto::hash8 payment_id8 = null_hash8; if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { - LOG_PRINT_L2("Encrypting payment id " << payment_id8); + oxen::log::debug(globallogcat, "Encrypting payment id {}", payment_id8); crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); if (view_key_pub == null_pkey) { - LOG_ERROR("Destinations have to have exactly one output to support encrypted payment ids"); + oxen::log::error(globallogcat, "Destinations have to have exactly one output to support encrypted payment ids"); return false; } if (!hwdev.encrypt_payment_id(payment_id8, view_key_pub, tx_key)) { - LOG_ERROR("Failed to encrypt payment id"); + oxen::log::error(globallogcat, "Failed to encrypt payment id"); return false; } @@ -686,10 +689,10 @@ namespace cryptonote remove_field_from_tx_extra(tx.extra); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) { - LOG_ERROR("Failed to add encrypted payment id to tx extra"); + oxen::log::error(globallogcat, "Failed to add encrypted payment id to tx extra"); return false; } - LOG_PRINT_L1("Encrypted payment ID: " << payment_id8); + oxen::log::info(globallogcat, "Encrypted payment ID: {}", payment_id8); add_dummy_payment_id = false; } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) @@ -711,7 +714,7 @@ namespace cryptonote crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); if (view_key_pub == null_pkey) { - LOG_ERROR("Failed to get key to encrypt dummy payment id with"); + oxen::log::error(globallogcat, "Failed to get key to encrypt dummy payment id with"); } else { @@ -719,7 +722,7 @@ namespace cryptonote set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) { - LOG_ERROR("Failed to add dummy encrypted payment id to tx extra"); + oxen::log::error(globallogcat, "Failed to add dummy encrypted payment id to tx extra"); // continue anyway } } @@ -727,7 +730,7 @@ namespace cryptonote } else { - MWARNING("Failed to parse tx extra"); + oxen::log::warning(globallogcat, "Failed to parse tx extra"); tx_extra_fields.clear(); } @@ -745,7 +748,7 @@ namespace cryptonote ++idx; if(src_entr.real_output >= src_entr.outputs.size()) { - LOG_ERROR("real_output index (" << src_entr.real_output << ")bigger than output_keys.size()=" << src_entr.outputs.size()); + oxen::log::error(globallogcat, "real_output index ({})bigger than output_keys.size()={}", src_entr.real_output, src_entr.outputs.size()); return false; } summary_inputs_money += src_entr.amount; @@ -757,18 +760,16 @@ namespace cryptonote const auto& out_key = reinterpret_cast(src_entr.outputs[src_entr.real_output].second.dest); if(!generate_key_image_helper(sender_account_keys, subaddresses, out_key, src_entr.real_out_tx_key, src_entr.real_out_additional_tx_keys, src_entr.real_output_in_tx_index, in_ephemeral,img, hwdev)) { - LOG_ERROR("Key image generation failed!"); + oxen::log::error(globallogcat, "Key image generation failed!"); return false; } //check that derivated key is equal with real output key (if non multisig) if(!msout && !(in_ephemeral.pub == src_entr.outputs[src_entr.real_output].second.dest) ) { - LOG_ERROR("derived public key mismatch with output public key at index " << idx << ", real out " << src_entr.real_output << "!\nderived_key:" - << tools::type_to_hex(in_ephemeral.pub) << "\nreal output_public_key:" - << tools::type_to_hex(src_entr.outputs[src_entr.real_output].second.dest) ); - LOG_ERROR("amount " << src_entr.amount << ", rct " << src_entr.rct); - LOG_ERROR("tx pubkey " << src_entr.real_out_tx_key << ", real_output_in_tx_index " << src_entr.real_output_in_tx_index); + oxen::log::error(globallogcat, "derived public key mismatch with output public key at index {}, real out {}!\nderived_key: {}\nreal output_public_key: {}", idx, src_entr.real_output, tools::type_to_hex(in_ephemeral.pub), tools::type_to_hex(src_entr.outputs[src_entr.real_output].second.dest)); + oxen::log::error(globallogcat, "amount {}, rct {}", src_entr.amount, src_entr.rct); + oxen::log::error(globallogcat, "tx pubkey {}, real_output_in_tx_index {}", src_entr.real_out_tx_key, src_entr.real_output_in_tx_index); return false; } @@ -873,7 +874,7 @@ namespace cryptonote keypair ephemeral_keys{}; if(!generate_key_image_helper(sender_account_keys, subaddresses, out_eph_public_key, txkey_pub, additional_tx_public_keys, output_index, ephemeral_keys, proof.key_image, hwdev)) { - LOG_ERROR("Key image generation failed for staking TX!"); + oxen::log::error(globallogcat, "Key image generation failed for staking TX!"); return false; } @@ -903,12 +904,12 @@ namespace cryptonote remove_field_from_tx_extra(tx.extra); - LOG_PRINT_L2("tx pubkey: " << txkey_pub); + oxen::log::debug(globallogcat, "tx pubkey: {}", txkey_pub); if (need_additional_txkeys) { - LOG_PRINT_L2("additional tx pubkeys: "); + oxen::log::debug(globallogcat, "additional tx pubkeys: "); for (size_t i = 0; i < additional_tx_public_keys.size(); ++i) - LOG_PRINT_L2(additional_tx_public_keys[i]); + oxen::log::debug(globallogcat, "{}", additional_tx_public_keys[i]); add_additional_tx_pub_keys_to_extra(tx.extra, additional_tx_public_keys); } @@ -918,7 +919,7 @@ namespace cryptonote //check money if(summary_outs_money > summary_inputs_money ) { - LOG_ERROR("Transaction inputs money ("<< summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")"); + oxen::log::error(globallogcat, "Transaction inputs money ({}) less than outputs money ({})", summary_inputs_money, summary_outs_money); return false; } @@ -928,7 +929,7 @@ namespace cryptonote zero_secret_key &= (sender_account_keys.m_spend_secret_key.data[i] == 0); if (zero_secret_key) { - MDEBUG("Null secret key, skipping signatures"); + oxen::log::debug(globallogcat, "Null secret key, skipping signatures"); } uint64_t amount_in = 0, amount_out = 0; @@ -978,13 +979,13 @@ namespace cryptonote { if (amount_in < amount_out + tx_params.burn_fixed) { - LOG_ERROR("invalid burn amount: tx does not have enough unspent funds available; amount_in: " << std::to_string(amount_in) << "; amount_out + tx_params.burn_fixed: " << std::to_string(amount_out) << " + " << std::to_string(tx_params.burn_fixed)); + oxen::log::error(globallogcat, "invalid burn amount: tx does not have enough unspent funds available; amount_in: {}; amount_out + tx_params.burn_fixed: {} + {}", std::to_string(amount_in), std::to_string(amount_out), std::to_string(tx_params.burn_fixed)); return false; } remove_field_from_tx_extra(tx.extra); // doesn't have to be present (but the wallet puts a dummy here as a safety to avoid growing the tx) if (!add_burned_amount_to_tx_extra(tx.extra, tx_params.burn_fixed)) { - LOG_ERROR("failed to add burn amount to tx extra"); + oxen::log::error(globallogcat, "failed to add burn amount to tx extra"); return false; } } @@ -1006,7 +1007,7 @@ namespace cryptonote CHECK_AND_ASSERT_MES(tx.vout.size() == outSk.size(), false, "outSk size does not match vout"); - MCINFO("construct_tx", "transaction_created: " << get_transaction_hash(tx) << "\n" << obj_to_json_str(tx) << "\n"); + oxen::log::info(oxen::log::Cat("construct_tx"), "transaction_created: {}\n{}\n", get_transaction_hash(tx), obj_to_json_str(tx)); tx.invalidate_hashes(); diff --git a/src/cryptonote_core/oxen_name_system.cpp b/src/cryptonote_core/oxen_name_system.cpp index 30c4befa5..b0eeda481 100644 --- a/src/cryptonote_core/oxen_name_system.cpp +++ b/src/cryptonote_core/oxen_name_system.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "common/hex.h" #include "cryptonote_config.h" #include "oxen_name_system.h" @@ -34,14 +35,13 @@ extern "C" #include } -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "ons" - using cryptonote::hf; namespace ons { +static auto logcat = oxen::log::Cat("ons"); + enum struct ons_sql_type { save_owner, @@ -361,7 +361,7 @@ bool sql_copy_blob(sql_compiled_statement& statement, I column, void *dest, size auto blob = get(statement, column); if (blob.data.size() != dest_size) { - LOG_PRINT_L0("Unexpected blob size=" << blob.data.size() << ", in ONS DB does not match expected size=" << dest_size); + oxen::log::warning(logcat, "Unexpected blob size={}, in ONS DB does not match expected size={}", blob.data.size(), dest_size); assert(blob.data.size() == dest_size); return false; } @@ -389,7 +389,7 @@ mapping_record sql_get_mapping_from_statement(sql_compiled_statement& statement) auto value = get(statement, mapping_record_column::encrypted_value); if (value.size() > result.encrypted_value.buffer.size()) { - MERROR("Unexpected encrypted value blob with size=" << value.size() << ", in ONS db larger than the available size=" << result.encrypted_value.buffer.size()); + oxen::log::error(logcat, "Unexpected encrypted value blob with size={}, in ONS db larger than the available size={}", value.size(), result.encrypted_value.buffer.size()); return result; } result.encrypted_value.len = value.size(); @@ -435,7 +435,7 @@ bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, voi { switch (type) { - default: MERROR("Unhandled ons type enum with value: " << (int)type << ", in: " << __func__); break; + default: oxen::log::error(logcat, "Unhandled ons type enum with value: {}, in: {}", (int)type, __func__); break; case ons_sql_type::internal_cmd: break; case ons_sql_type::get_owner: @@ -499,7 +499,7 @@ bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, voi default: { - LOG_PRINT_L1("Failed to execute statement: " << sqlite3_sql(statement.statement) <<", reason: " << sqlite3_errstr(step_result)); + oxen::log::info(logcat, "Failed to execute statement: {}, reason: {}", sqlite3_sql(statement.statement), sqlite3_errstr(step_result)); infinite_loop = false; break; } @@ -541,7 +541,7 @@ bool sql_compiled_statement::compile(std::string_view query, bool optimise_for_m #endif if (prepare_result != SQLITE_OK) { - MERROR("Can not compile SQL statement:\n" << query << "\nReason: " << sqlite3_errstr(prepare_result)); + oxen::log::error(logcat, "Can not compile SQL statement:\n{}\nReason: {}", query, sqlite3_errstr(prepare_result)); return false; } sqlite3_finalize(statement); @@ -568,7 +568,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int sql_init = sqlite3_initialize(); if (sql_init != SQLITE_OK) { - MERROR("Failed to initialize sqlite3: " << sqlite3_errstr(sql_init)); + oxen::log::error(logcat, "Failed to initialize sqlite3: {}", sqlite3_errstr(sql_init)); return nullptr; } @@ -576,7 +576,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int sql_open = sqlite3_open_v2(file_path.u8string().c_str(), &result, flags, nullptr); if (sql_open != SQLITE_OK) { - MERROR("Failed to open ONS db at: " << file_path << ", reason: " << sqlite3_errstr(sql_open)); + oxen::log::error(logcat, "Failed to open ONS db at: {}, reason: {}", file_path, sqlite3_errstr(sql_open)); return nullptr; } @@ -591,7 +591,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int exec = sqlite3_exec(result, "PRAGMA journal_mode = WAL", nullptr, nullptr, nullptr); if (exec != SQLITE_OK) { - MERROR("Failed to set journal mode to WAL: " << sqlite3_errstr(exec)); + oxen::log::error(logcat, "Failed to set journal mode to WAL: {}", sqlite3_errstr(exec)); return nullptr; } @@ -605,7 +605,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) exec = sqlite3_exec(result, "PRAGMA synchronous = NORMAL", nullptr, nullptr, nullptr); if (exec != SQLITE_OK) { - MERROR("Failed to set synchronous mode to NORMAL: " << sqlite3_errstr(exec)); + oxen::log::error(logcat, "Failed to set synchronous mode to NORMAL: {}", sqlite3_errstr(exec)); return nullptr; } @@ -664,7 +664,7 @@ std::string tx_extra_signature(std::string_view value, ons::generic_owner const static_assert(sizeof(crypto::hash) == crypto_generichash_BYTES, "Using libsodium generichash for signature hash, require we fit into crypto::hash"); if (value.size() > mapping_value::BUFFER_SIZE) { - MERROR("Unexpected value len=" << value.size() << " greater than the expected capacity=" << mapping_value::BUFFER_SIZE); + oxen::log::error(logcat, "Unexpected value len={} greater than the expected capacity={}", value.size(), mapping_value::BUFFER_SIZE); return ""s; } @@ -858,7 +858,7 @@ bool validate_ons_name(mapping_type type, std::string name, std::string *reason) } else { - MERROR("Type not implemented"); + oxen::log::error(logcat, "Type not implemented"); return false; } @@ -1410,7 +1410,7 @@ bool mapping_value::encrypt(std::string_view name, const crypto::hash* name_hash if (encryption_len > buffer.size()) { - MERROR("Encrypted value pre-allocated buffer too small=" << buffer.size() << ", required=" << encryption_len); + oxen::log::error(logcat, "Encrypted value pre-allocated buffer too small={}, required={}", buffer.size(), encryption_len); return false; } @@ -1482,18 +1482,18 @@ bool mapping_value::decrypt(std::string_view name, mapping_type type, const cryp plain_len == WALLET_ACCOUNT_BINARY_LENGTH_INC_PAYMENT_ID || plain_len == WALLET_ACCOUNT_BINARY_LENGTH_NO_PAYMENT_ID) { dec_length = plain_len; } else { - MERROR("Invalid wallet mapping_type length passed to mapping_value::decrypt"); + oxen::log::error(logcat, "Invalid wallet mapping_type length passed to mapping_value::decrypt"); return false; } break; - default: MERROR("Invalid mapping_type passed to mapping_value::decrypt"); + default: oxen::log::error(logcat, "Invalid mapping_type passed to mapping_value::decrypt"); return false; } auto expected_len = dec_length + crypto_aead_xchacha20poly1305_ietf_ABYTES + crypto_aead_xchacha20poly1305_ietf_NPUBBYTES; if (len != expected_len) { - MERROR("Encrypted value size is invalid=" << len << ", expected=" << expected_len); + oxen::log::error(logcat, "Encrypted value size is invalid={}, expected={}", len, expected_len); return false; } const auto& [enc, nonce] = value_nonce(type); @@ -1597,7 +1597,7 @@ CREATE INDEX IF NOT EXISTS mapping_type_name_exp ON mappings (type, name_hash, e int table_created = sqlite3_exec(ons_db.db, BUILD_TABLE_SQL.c_str(), nullptr /*callback*/, nullptr /*callback context*/, &table_err_msg); if (table_created != SQLITE_OK) { - MERROR("Can not generate SQL table for ONS: " << (table_err_msg ? table_err_msg : "??")); + oxen::log::error(logcat, "Can not generate SQL table for ONS: {}", (table_err_msg ? table_err_msg : "??")); sqlite3_free(table_err_msg); return false; } @@ -1627,7 +1627,7 @@ CREATE INDEX IF NOT EXISTS mapping_type_name_exp ON mappings (type, name_hash, e "ALTER TABLE mappings ADD COLUMN update_height INTEGER NOT NULL DEFAULT register_height", nullptr /*callback*/, nullptr /*callback ctx*/, nullptr /*errstr*/); - LOG_PRINT_L1("Migrating ONS mappings database to new format"); + oxen::log::info(logcat, "Migrating ONS mappings database to new format"); const std::string migrate = R"( BEGIN TRANSACTION; ALTER TABLE mappings RENAME TO mappings_old; @@ -1646,7 +1646,7 @@ COMMIT TRANSACTION; int migrated = sqlite3_exec(ons_db.db, migrate.c_str(), nullptr /*callback*/, nullptr /*callback context*/, &table_err_msg); if (migrated != SQLITE_OK) { - MERROR("Can not migrate SQL mappings table for ONS: " << (table_err_msg ? table_err_msg : "??")); + oxen::log::error(logcat, "Can not migrate SQL mappings table for ONS: {}", (table_err_msg ? table_err_msg : "??")); sqlite3_free(table_err_msg); return false; } @@ -1687,14 +1687,14 @@ scoped_db_transaction::scoped_db_transaction(name_system_db &ons_db) { if (ons_db.transaction_begun) { - MERROR("Failed to begin transaction, transaction exists previously that was not closed properly"); + oxen::log::error(logcat, "Failed to begin transaction, transaction exists previously that was not closed properly"); return; } char *sql_err = nullptr; if (sqlite3_exec(ons_db.db, "BEGIN;", nullptr, nullptr, &sql_err) != SQLITE_OK) { - MERROR("Failed to begin transaction " << ", reason=" << (sql_err ? sql_err : "??")); + oxen::log::error(logcat, "Failed to begin transaction , reason={}", (sql_err ? sql_err : "??")); sqlite3_free(sql_err); return; } @@ -1708,14 +1708,14 @@ scoped_db_transaction::~scoped_db_transaction() if (!initialised) return; if (!ons_db.transaction_begun) { - MERROR("Trying to apply non-existent transaction (no prior history of a db transaction beginning) to the ONS DB"); + oxen::log::error(logcat, "Trying to apply non-existent transaction (no prior history of a db transaction beginning) to the ONS DB"); return; } char *sql_err = nullptr; if (sqlite3_exec(ons_db.db, commit ? "END;" : "ROLLBACK;", NULL, NULL, &sql_err) != SQLITE_OK) { - MERROR("Failed to " << (commit ? "end " : "rollback ") << " transaction to ONS DB, reason=" << (sql_err ? sql_err : "??")); + oxen::log::error(logcat, "Failed to {} transaction to ONS DB, reason={}", (commit ? "end " : "rollback "), (sql_err ? sql_err : "??")); sqlite3_free(sql_err); return; } @@ -1792,13 +1792,13 @@ AND NOT EXISTS (SELECT * FROM mappings WHERE owner.id = mappings.backup_owner_ { if (!blockchain) { - MERROR("Migration required, blockchain can not be nullptr"); + oxen::log::error(logcat, "Migration required, blockchain can not be nullptr"); return false; } if (blockchain->get_db().is_read_only()) { - MERROR("DB is opened in read-only mode, unable to migrate ONS DB"); + oxen::log::error(logcat, "DB is opened in read-only mode, unable to migrate ONS DB"); return false; } @@ -1949,7 +1949,7 @@ std::optional add_or_get_owner_id(ons::name_system_db &ons_db, crypto:: { if (!ons_db.save_owner(key, &result)) { - LOG_PRINT_L1("Failed to save ONS owner to DB tx: " << tx_hash << ", type: " << entry.type << ", name_hash: " << entry.name_hash << ", owner: " << entry.owner.to_string(ons_db.network_type())); + oxen::log::info(logcat, "Failed to save ONS owner to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); return std::nullopt; } } @@ -1994,7 +1994,7 @@ SELECT type, name_hash, ?, ?)"; auto opt_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.owner); if (!opt_id) { - MERROR("Failed to add or get owner with key=" << entry.owner.to_string(ons_db.network_type())); + oxen::log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); assert(opt_id); return {}; } @@ -2009,7 +2009,7 @@ SELECT type, name_hash, ?, ?)"; auto opt_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.backup_owner); if (!opt_id) { - MERROR("Failed to add or get backup owner with key=" << entry.backup_owner.to_string(ons_db.network_type())); + oxen::log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); assert(opt_id); return {}; } @@ -2046,7 +2046,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ auto owner_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.owner); if (!owner_id) { - MERROR("Failed to add or get owner with key=" << entry.owner.to_string(ons_db.network_type())); + oxen::log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); assert(owner_id); return false; } @@ -2057,7 +2057,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ backup_owner_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.backup_owner); if (!backup_owner_id) { - MERROR("Failed to add or get backup owner with key=" << entry.backup_owner.to_string(ons_db.network_type())); + oxen::log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); assert(backup_owner_id); return false; } @@ -2067,7 +2067,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ if (expiry) *expiry += height; if (!ons_db.save_mapping(tx_hash, entry, height, expiry, *owner_id, backup_owner_id)) { - LOG_PRINT_L1("Failed to save ONS entry to DB tx: " << tx_hash << ", type: " << entry.type << ", name_hash: " << entry.name_hash << ", owner: " << entry.owner.to_string(ons_db.network_type())); + oxen::log::info(logcat, "Failed to save ONS entry to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); return false; } } @@ -2085,7 +2085,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ sql_compiled_statement statement{ons_db}; if (!statement.compile(sql, false /*optimise_for_multiple_usage*/)) { - MERROR("Failed to compile SQL statement for updating ONS record=" << sql); + oxen::log::error(logcat, "Failed to compile SQL statement for updating ONS record={}", sql); return false; } @@ -2123,7 +2123,7 @@ bool name_system_db::add_block(const cryptonote::block &block, const std::vector std::string fail_reason; if (!validate_ons_tx(block.major_version, height, tx, entry, &fail_reason)) { - MFATAL("ONS TX: Failed to validate for tx=" << get_transaction_hash(tx) << ". This should have failed validation earlier reason=" << fail_reason); + oxen::log::error(logcat, "ONS TX: Failed to validate for tx={}. This should have failed validation earlier reason={}", get_transaction_hash(tx), fail_reason); assert("Failed to validate acquire name service. Should already have failed validation prior" == nullptr); return false; } diff --git a/src/cryptonote_core/oxen_name_system.h b/src/cryptonote_core/oxen_name_system.h index a67277255..b12a251d4 100644 --- a/src/cryptonote_core/oxen_name_system.h +++ b/src/cryptonote_core/oxen_name_system.h @@ -340,5 +340,21 @@ private: sql_compiled_statement get_mappings_on_height_and_newer_sql{*this}; }; -}; // namespace service_nodes +}; // namespace ons + +template <> +struct fmt::formatter : fmt::formatter { + auto format(ons::mapping_value v, format_context& ctx) { + return formatter::format( + fmt::format("{}", oxenc::to_hex(v.to_view())), ctx); + } +}; +template <> +struct fmt::formatter : fmt::formatter { + auto format(ons::mapping_type t, format_context& ctx) { + return formatter::format( + fmt::format("{}", ons::mapping_type_str(t)), ctx); + } +}; + #endif // OXEN_NAME_SYSTEM_H diff --git a/src/cryptonote_core/pulse.cpp b/src/cryptonote_core/pulse.cpp index 78a1ed946..f7c8273c6 100644 --- a/src/cryptonote_core/pulse.cpp +++ b/src/cryptonote_core/pulse.cpp @@ -18,8 +18,7 @@ extern "C" #include }; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "pulse" +static auto logcat = oxen::log::Cat("pulse"); // Deliberately makes pulse communications flakey for testing purposes: //#define PULSE_TEST_CODE @@ -457,9 +456,7 @@ bool enforce_validator_participation_and_timeouts(round_context const &context, if (timed_out && !all_received) { - MDEBUG(log_prefix(context) << "Stage timed out: insufficient responses. Expected " - << "(" << bitset_view16(validator_bitset).count() << ") " << bitset_view16(validator_bitset) << " received " - << "(" << bitset_view16(stage.bitset).count() << ") " << bitset_view16(stage.bitset)); + oxen::log::debug(logcat, "{}Stage timed out: insufficient responses. Expected ({}) {} received ({}) {}", log_prefix(context), bitset_view16(validator_bitset).count(), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string()); return false; } @@ -469,7 +466,7 @@ bool enforce_validator_participation_and_timeouts(round_context const &context, bool unexpected_items = (stage.bitset | validator_bitset) != validator_bitset; if (stage.msgs_received == 0 || unexpected_items) { - MERROR(log_prefix(context) << "Internal error: expected bitset " << bitset_view16(validator_bitset) << ", but accepted and received " << bitset_view16(stage.bitset)); + oxen::log::error(logcat, "{}Internal error: expected bitset {}, but accepted and received {}", log_prefix(context), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).to_string()); return false; } @@ -523,13 +520,13 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) // marked an error, just ignored. print_err = false; - MTRACE(log_prefix(context) << "Received valid message from the past (round " << +msg.round << "), ignoring"); + oxen::log::trace(logcat, "{}Received valid message from the past (round {}), ignoring", log_prefix(context), +msg.round); break; } // else: Message has unknown origins, it is not something we know how to validate. } if (print_err) - MERROR(sig_check_err); + oxen::log::error(logcat, sig_check_err); return; } @@ -539,7 +536,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) { case pulse::message_type::invalid: { - MTRACE(log_prefix(context) << "Received invalid message type, dropped"); + oxen::log::trace(logcat, "{}Received invalid message type, dropped", log_prefix(context)); return; } @@ -568,7 +565,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto &[entry, queued] = stage->queue.buffer[msg.quorum_position]; if (queued == queueing_state::empty) { - MTRACE(log_prefix(context) << "Message received early " << msg_source_string(context, msg) << ", queueing until we're ready."); + oxen::log::trace(logcat, "{}Message received early {}, queueing until we're ready.", log_prefix(context), msg_source_string(context, msg)); stage->queue.count++; entry = std::move(msg); queued = queueing_state::received; @@ -585,15 +582,15 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) // locked in. Any stray messages from other validators are rejected. if ((validator_bit & context.transient.wait_for_handshake_bitsets.best_bitset) == 0) { - auto bitset_view = bitset_view16(context.transient.wait_for_handshake_bitsets.best_bitset); - MTRACE(log_prefix(context) << "Dropping " << msg_source_string(context, msg) << ". Not a locked in participant, bitset is " << bitset_view); + auto bitset_view = bitset_view16(context.transient.wait_for_handshake_bitsets.best_bitset).to_string(); + oxen::log::trace(logcat, "{}Dropping {}. Not a locked in participant, bitset is {}", log_prefix(context), msg_source_string(context, msg), bitset_view); return; } } if (msg.quorum_position >= service_nodes::PULSE_QUORUM_NUM_VALIDATORS) { - MTRACE(log_prefix(context) << "Dropping " << msg_source_string(context, msg) << ". Message quorum position indexes oob"); + oxen::log::trace(logcat, "{}Dropping {}. Message quorum position indexes oob", log_prefix(context), msg_source_string(context, msg)); return; } @@ -611,9 +608,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto &quorum = context.transient.send_and_wait_for_handshakes.data; if (quorum[msg.quorum_position]) return; quorum[msg.quorum_position] = true; - MTRACE(log_prefix(context) << "Received handshake with quorum position bit (" << msg.quorum_position << ") " - << bitset_view16(validator_bit) << " saved to bitset " - << bitset_view16(stage->bitset)); + oxen::log::trace(logcat, "{}Received handshake with quorum position bit ({}) {} saved to bitset {}", log_prefix(context), msg.quorum_position, bitset_view16(validator_bit).to_string(), bitset_view16(stage->bitset).to_string()); } break; @@ -634,14 +629,13 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) cryptonote::block block = {}; if (!cryptonote::t_serializable_object_from_blob(block, msg.block_template.blob)) { - MTRACE(log_prefix(context) << "Received unparsable pulse block template blob"); + oxen::log::trace(logcat, "{}Received unparsable pulse block template blob", log_prefix(context)); return; } if (block.pulse.round != context.prepare_for_round.round) { - MTRACE(log_prefix(context) << "Received pulse block template specifying different round " << +block.pulse.round - << ", expected " << +context.prepare_for_round.round); + oxen::log::trace(logcat, "{}Received pulse block template specifying different round {}, expected {}", log_prefix(context), +block.pulse.round, +context.prepare_for_round.round); return; } @@ -649,7 +643,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) { auto block_bitset = bitset_view16(block.pulse.validator_bitset); auto our_bitset = bitset_view16(context.transient.wait_for_handshake_bitsets.best_bitset); - MTRACE(log_prefix(context) << "Received pulse block template specifying different validator handshake bitsets " << block_bitset << ", expected " << our_bitset); + oxen::log::trace(logcat, "{}Received pulse block template specifying different validator handshake bitsets {}, expected {}", log_prefix(context), block_bitset.to_string(), our_bitset.to_string()); return; } @@ -677,9 +671,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto derived = blake2b_hash(msg.random_value.value.data, sizeof(msg.random_value.value.data)); if (derived != *hash) { - MTRACE(log_prefix(context) << "Dropping " << msg_source_string(context, msg) - << ". Rederived random value hash " << derived << " does not match original hash " - << *hash); + oxen::log::trace(logcat, "{}Dropping {}. Rederived random value hash {} does not match original hash {}", log_prefix(context), msg_source_string(context, msg), derived, *hash); return; } } @@ -700,10 +692,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) crypto::public_key const &validator_key = context.prepare_for_round.quorum.validators[msg.quorum_position]; if (!crypto::check_signature(final_block_hash, validator_key, msg.signed_block.signature_of_final_block_hash)) { - MTRACE(log_prefix(context) << "Dropping " << msg_source_string(context, msg) - << ". Signature signing final block hash " - << msg.signed_block.signature_of_final_block_hash - << " does not validate with the Service Node"); + oxen::log::trace(logcat, "{}Dropping {}. Signature signing final block hash {} does not validate with the Service Node", log_prefix(context), msg_source_string(context, msg), msg.signed_block.signature_of_final_block_hash); return; } @@ -1053,7 +1042,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (context.wait_for_next_block.height == chain_height) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - MDEBUG(log_prefix(context) << "Network is currently producing block " << chain_height << ", waiting until next block"); + oxen::log::debug(logcat, "{}Network is currently producing block {}, waiting until next block", log_prefix(context), chain_height); return round_state::wait_for_next_block; } @@ -1061,7 +1050,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (prev_hash == crypto::null_hash) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - MDEBUG(log_prefix(context) << "Failed to query the block hash for height " << chain_height - 1); + oxen::log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); return round_state::wait_for_next_block; } @@ -1073,7 +1062,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr catch(std::exception const &e) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - MDEBUG(log_prefix(context) << "Failed to query the block hash for height " << chain_height - 1); + oxen::log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); return round_state::wait_for_next_block; } @@ -1081,7 +1070,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (!get_round_timings(blockchain, chain_height, prev_timestamp, times)) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - MERROR(log_prefix(context) << "Failed to query the block data for Pulse timings"); + oxen::log::error(logcat, "{}Failed to query the block data for Pulse timings", log_prefix(context)); return round_state::wait_for_next_block; } @@ -1140,7 +1129,7 @@ round_state prepare_for_round(round_context &context, service_nodes::service_nod if (round_usize > 255) // Network stalled { - MINFO(log_prefix(context) << "Pulse has timed out, reverting to accepting miner blocks only."); + oxen::log::info(logcat, "{}Pulse has timed out, reverting to accepting miner blocks only.", log_prefix(context)); return goto_wait_for_next_block_and_clear_round_data(context); } @@ -1175,11 +1164,11 @@ round_state prepare_for_round(round_context &context, service_nodes::service_nod if (!service_nodes::verify_pulse_quorum_sizes(context.prepare_for_round.quorum)) { - MINFO(log_prefix(context) << "Insufficient Service Nodes to execute Pulse on height " << context.wait_for_next_block.height << ", we require a PoW miner block. Sleeping until next block."); + oxen::log::info(logcat, "{}Insufficient Service Nodes to execute Pulse on height {}, we require a PoW miner block. Sleeping until next block.", log_prefix(context), context.wait_for_next_block.height); return goto_wait_for_next_block_and_clear_round_data(context); } - MDEBUG(log_prefix(context) << "Generate Pulse quorum: " << context.prepare_for_round.quorum); + oxen::log::debug(logcat, "{}Generate Pulse quorum: {}", log_prefix(context), context.prepare_for_round.quorum); // // NOTE: Quorum participation @@ -1215,7 +1204,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const const auto curr_height = blockchain.get_current_blockchain_height(true /*lock*/); if (context.wait_for_next_block.height != curr_height) { - MDEBUG(log_prefix(context) << "Block height changed whilst waiting for round " << +context.prepare_for_round.round << ", restarting Pulse stages"); + oxen::log::debug(logcat, "{}Block height changed whilst waiting for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); return goto_wait_for_next_block_and_clear_round_data(context); } @@ -1223,7 +1212,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const if (auto now = pulse::clock::now(); now < start_time) { for (static uint64_t last_height = 0; last_height != context.wait_for_next_block.height; last_height = context.wait_for_next_block.height) - MINFO(log_prefix(context) << "Waiting for round " << +context.prepare_for_round.round << " to start in " << tools::friendly_duration(start_time - now)); + oxen::log::info(logcat, "{}Waiting for round {} to start in {}", log_prefix(context), +context.prepare_for_round.round, tools::friendly_duration(start_time - now)); return round_state::wait_for_round; } @@ -1236,7 +1225,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const size_t faulty_chance = tools::uniform_distribution_portable(tools::rng, 100); if (faulty_chance < 10) { - MDEBUG(log_prefix(context) << "FAULTY NODE ACTIVATED"); + oxen::log::debug(logcat, "{}FAULTY NODE ACTIVATED", log_prefix(context)); return goto_preparing_for_next_round(context); } @@ -1245,24 +1234,24 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const { auto sleep_time = std::chrono::seconds(tools::uniform_distribution_portable(tools::rng, 20)); std::this_thread::sleep_for(sleep_time); - MDEBUG(log_prefix(context) << "SLEEP TIME ACTIVATED " << tools::to_seconds(sleep_time) << "s"); + oxen::log::debug(logcat, "{}SLEEP TIME ACTIVATED {}s", log_prefix(context), tools::to_seconds(sleep_time)); } } #endif if (context.prepare_for_round.participant == sn_type::validator) { - MINFO(log_prefix(context) << "We are a pulse validator, sending handshake bit and collecting other handshakes."); + oxen::log::info(logcat, "{}We are a pulse validator, sending handshake bit and collecting other handshakes.", log_prefix(context)); return round_state::send_and_wait_for_handshakes; } else if (context.prepare_for_round.participant == sn_type::producer) { - MINFO(log_prefix(context) << "We are the block producer for height " << context.wait_for_next_block.height << " in round " << +context.prepare_for_round.round << ", awaiting handshake bitsets."); + oxen::log::info(logcat, "{}We are the block producer for height {} in round {}, awaiting handshake bitsets.", log_prefix(context), context.wait_for_next_block.height, +context.prepare_for_round.round); return round_state::wait_for_handshake_bitsets; } else { - MDEBUG(log_prefix(context) << "Non-participant for round, waiting on next round or block."); + oxen::log::debug(logcat, "{}Non-participant for round, waiting on next round or block.", log_prefix(context)); return goto_preparing_for_next_round(context); } } @@ -1282,7 +1271,7 @@ round_state send_and_wait_for_handshakes(round_context &context, void *quorumnet } catch (std::exception const &e) { - MERROR(log_prefix(context) << "Attempting to invoke and send a Pulse participation handshake unexpectedly failed. " << e.what()); + oxen::log::error(logcat, "{}Attempting to invoke and send a Pulse participation handshake unexpectedly failed. {}", log_prefix(context), e.what()); return goto_preparing_for_next_round(context); } } @@ -1303,7 +1292,7 @@ round_state send_and_wait_for_handshakes(round_context &context, void *quorumnet if (all_handshakes || timed_out) { bool missing_handshakes = timed_out && !all_handshakes; - MINFO(log_prefix(context) << "Collected validator handshakes " << bitset_view16(stage.bitset) << (missing_handshakes ? ", we timed out and some handshakes were not seen! " : ". ") << "Sending handshake bitset and collecting other validator bitsets."); + oxen::log::info(logcat, "{}Collected validator handshakes {}{}Sending handshake bitset and collecting other validator bitsets.", log_prefix(context), bitset_view16(stage.bitset).to_string(), (missing_handshakes ? ", we timed out and some handshakes were not seen! " : ". ")); return round_state::send_handshake_bitsets; } else @@ -1321,7 +1310,7 @@ round_state send_handshake_bitsets(round_context &context, void *quorumnet_state } catch(std::exception const &e) { - MERROR(log_prefix(context) << "Attempting to invoke and send a Pulse validator bitset unexpectedly failed. " << e.what()); + oxen::log::error(logcat, "{}Attempting to invoke and send a Pulse validator bitset unexpectedly failed. {}", log_prefix(context), e.what()); return goto_preparing_for_next_round(context); } } @@ -1351,7 +1340,7 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se best_bitset = *bitset; count = num; } - MTRACE(log_prefix(context) << "Collected from V[" << quorum_index << "], handshake bitset " << bitset_view16(*bitset)); + oxen::log::trace(logcat, "{}Collected from V[{}], handshake bitset {}", log_prefix(context), quorum_index, bitset_view16(*bitset).to_string()); } } @@ -1365,20 +1354,19 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se { // Less than the threshold of the validators can come to agreement about // which validators are online, we wait until the next round. - MDEBUG(log_prefix(context) << count << "/" << quorum.size() - << " validators did not send any handshake bitset or sent an empty handshake " - "bitset and have failed to come to agreement. Waiting until next round."); + oxen::log::debug(logcat, "{}{}/{} \ + validators did not send any handshake bitset or sent an empty handshake \ + bitset and have failed to come to agreement. Waiting until next round.", + log_prefix(context), count, quorum.size()); } else if (i_am_not_participating) { - MDEBUG(log_prefix(context) << "The participating validator bitset " << bitset_view16(best_bitset) - << " does not include us (quorum index " << context.prepare_for_round.my_quorum_position << "). Waiting until next round."); + oxen::log::debug(logcat, "{}The participating validator bitset {} does not include us (quorum index {}). Waiting until next round.", log_prefix(context), bitset_view16(best_bitset).to_string(), context.prepare_for_round.my_quorum_position); } else { // Can't come to agreement, see threshold comment above - MDEBUG(log_prefix(context) << "We heard back from less than " << service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES << " of the validators (" - << count << "/" << quorum.size() << "). Waiting until next round."); + oxen::log::debug(logcat, "{}We heard back from less than {} of the validators ({}/{}). Waiting until next round.", log_prefix(context), service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES, count, quorum.size()); } return goto_preparing_for_next_round(context); @@ -1386,9 +1374,8 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se context.transient.wait_for_handshake_bitsets.best_bitset = best_bitset; context.transient.wait_for_handshake_bitsets.best_count = count; - MINFO(log_prefix(context) << count << "/" << quorum.size() - << " validators agreed on the participating nodes in the quorum " << bitset_view16(best_bitset) - << (context.prepare_for_round.participant == sn_type::producer + oxen::log::info(logcat, "{}{}/{} validators agreed on the participating nodes in the quorum {}{}", log_prefix(context), count, quorum.size(), + bitset_view16(best_bitset).to_string(), (context.prepare_for_round.participant == sn_type::producer ? "" : ". Awaiting block template from block producer")); @@ -1409,14 +1396,14 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s // Invariants if (list_state.empty()) { - MWARNING(log_prefix(context) << "Block producer (us) is not available on the service node list, waiting until next round"); + oxen::log::warning(logcat, "{}Block producer (us) is not available on the service node list, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } std::shared_ptr info = list_state[0].info; if (!info->is_active()) { - MWARNING(log_prefix(context) << "Block producer (us) is not an active service node, waiting until next round"); + oxen::log::warning(logcat, "{}Block producer (us) is not an active service node, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } @@ -1431,13 +1418,13 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s context.transient.wait_for_handshake_bitsets.best_bitset, height)) { - MERROR(log_prefix(context) << "Failed to generate a block template, waiting until next round"); + oxen::log::error(logcat, "{}Failed to generate a block template, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } if (context.wait_for_next_block.height != height) { - MDEBUG(log_prefix(context) << "Block height changed whilst preparing block template for round " << +context.prepare_for_round.round << ", restarting Pulse stages"); + oxen::log::debug(logcat, "{}Block height changed whilst preparing block template for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); return goto_wait_for_next_block_and_clear_round_data(context); } } @@ -1449,7 +1436,7 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s crypto::generate_signature(msg_signature_hash(context.wait_for_next_block.top_hash, msg), key.pub, key.key, msg.signature); // Send - MINFO(log_prefix(context) << "Validators are handshaken and ready, sending block template from producer (us) to validators.\n" << cryptonote::obj_to_json_str(block)); + oxen::log::info(logcat, "{}Validators are handshaken and ready, sending block template from producer (us) to validators.\n{}", log_prefix(context), cryptonote::obj_to_json_str(block)); cryptonote::quorumnet_pulse_relay_message_to_quorum(quorumnet_state, msg, context.prepare_for_round.quorum, true /*block_producer*/); return goto_preparing_for_next_round(context); } @@ -1467,7 +1454,7 @@ round_state wait_for_block_template(round_context &context, service_nodes::servi if (received) { cryptonote::block const &block = context.transient.wait_for_block_template.block; - MINFO(log_prefix(context) << "Valid block received: " << cryptonote::obj_to_json_str(context.transient.wait_for_block_template.block)); + oxen::log::info(logcat, "{}Valid block received: {}", log_prefix(context), cryptonote::obj_to_json_str(context.transient.wait_for_block_template.block)); // Generate my random value and its hash crypto::generate_random_bytes_thread_safe(sizeof(context.transient.random_value.send.data), context.transient.random_value.send.data.data); @@ -1476,7 +1463,7 @@ round_state wait_for_block_template(round_context &context, service_nodes::servi } else { - MINFO(log_prefix(context) << "Timed out, block template was not received"); + oxen::log::info(logcat, "{}Timed out, block template was not received", log_prefix(context)); return goto_preparing_for_next_round(context); } } @@ -1516,7 +1503,7 @@ round_state send_and_wait_for_random_value_hashes(round_context &context, servic if (!enforce_validator_participation_and_timeouts(context, stage, node_list, timed_out, all_hashes)) return goto_preparing_for_next_round(context); - MINFO(log_prefix(context) << "Received " << bitset_view16(stage.bitset).count() << " random value hashes from " << bitset_view16(stage.bitset) << (timed_out ? ". We timed out and some hashes are missing" : "")); + oxen::log::info(logcat, "{}Received {} random value hashes from {}{}", log_prefix(context), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string(), (timed_out ? ". We timed out and some hashes are missing" : "")); return round_state::send_and_wait_for_random_value; } @@ -1574,7 +1561,7 @@ round_state send_and_wait_for_random_value(round_context &context, service_nodes string.data()[i] = '.'; #endif - MDEBUG(log_prefix(context) << "Final random value seeding with V[" << index << "] " << string.view()); + oxen::log::debug(logcat, "{}Final random value seeding with V[{}] {}", log_prefix(context), index, string.view()); crypto_generichash_update(&state, random_value->data, sizeof(random_value->data)); } } @@ -1596,7 +1583,7 @@ round_state send_and_wait_for_random_value(round_context &context, service_nodes crypto::hash const &final_block_hash = cryptonote::get_block_hash(final_block); crypto::generate_signature(final_block_hash, key.pub, key.key, context.transient.signed_block.send.data); - MINFO(log_prefix(context) << "Block final random value " << oxenc::to_hex(tools::view_guts(final_block.pulse.random_value.data)) << " generated from validators " << bitset_view16(stage.bitset)); + oxen::log::info(logcat, "{}Block final random value {} generated from validators {}", log_prefix(context), oxenc::to_hex(tools::view_guts(final_block.pulse.random_value.data)), bitset_view16(stage.bitset).to_string()); return round_state::send_and_wait_for_signed_blocks; } @@ -1658,12 +1645,12 @@ round_state send_and_wait_for_signed_blocks(round_context &context, service_node uint16_t validator_index = indices[index]; auto const &signature = quorum[validator_index]; assert(signature); - MDEBUG(log_prefix(context) << "Signature added: " << validator_index << ":" << context.prepare_for_round.quorum.validators[validator_index] << ", " << *signature); + oxen::log::debug(logcat, "{}Signature added: {}:{}, {}", log_prefix(context), validator_index, context.prepare_for_round.quorum.validators[validator_index], *signature); final_block.signatures.emplace_back(validator_index, *signature); } // Propagate Final Block - MDEBUG(log_prefix(context) << "Final signed block constructed\n" << cryptonote::obj_to_json_str(final_block)); + oxen::log::debug(logcat, "{}Final signed block constructed\n{}", log_prefix(context), cryptonote::obj_to_json_str(final_block)); cryptonote::block_verification_context bvc = {}; if (!core.handle_block_found(final_block, bvc)) return goto_preparing_for_next_round(context); @@ -1686,14 +1673,14 @@ void pulse::main(void *quorumnet_state, cryptonote::core &core) if (!hf16) { for (static bool once = true; once; once = !once) - MERROR("Pulse: HF16 is not defined, pulse worker waiting"); + oxen::log::error(logcat, "Pulse: HF16 is not defined, pulse worker waiting"); return; } if (uint64_t height = blockchain.get_current_blockchain_height(true /*lock*/); height < *hf16) { for (static bool once = true; once; once = !once) - MDEBUG("Pulse: Network at block " << height << " is not ready for Pulse until block " << *hf16 << ", waiting"); + oxen::log::debug(logcat, "Pulse: Network at block {} is not ready for Pulse until block {}, waiting", height, *hf16); return; } diff --git a/src/cryptonote_core/service_node_list.cpp b/src/cryptonote_core/service_node_list.cpp index 9aaae45ff..e2b5e5022 100644 --- a/src/cryptonote_core/service_node_list.cpp +++ b/src/cryptonote_core/service_node_list.cpp @@ -35,6 +35,7 @@ #include #include +#include #include #include @@ -65,16 +66,14 @@ extern "C" { #include "service_node_rules.h" #include "service_node_swarm.h" #include "version.h" - #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "service_nodes" - using cryptonote::hf; namespace service_nodes { + static auto logcat = oxen::log::Cat("service_nodes"); + size_t constexpr STORE_LONG_TERM_STATE_INTERVAL = 10000; constexpr auto X25519_MAP_PRUNING_INTERVAL = 5min; @@ -110,7 +109,7 @@ namespace service_nodes uint64_t current_height = m_blockchain.get_current_blockchain_height(); bool loaded = load(current_height); if (loaded && m_transient.old_quorum_states.size() < std::min(m_store_quorum_history, uint64_t{10})) { - LOG_PRINT_L0("Full history storage requested, but " << m_transient.old_quorum_states.size() << " old quorum states found"); + oxen::log::warning(logcat, "Full history storage requested, but {} old quorum states found", m_transient.old_quorum_states.size()); loaded = false; // Either we don't have stored history or the history is very short, so recalculation is necessary or cheap. } @@ -203,13 +202,13 @@ namespace service_nodes else if (group == quorum_group::worker) array = &quorum.workers; else { - MERROR("Invalid quorum group specified"); + oxen::log::error(logcat, "Invalid quorum group specified"); return false; } if (quorum_index >= array->size()) { - MERROR("Quorum indexing out of bounds: " << quorum_index << ", quorum_size: " << array->size()); + oxen::log::error(logcat, "Quorum indexing out of bounds: {}, quorum_size: {}", quorum_index, array->size()); return false; } @@ -222,7 +221,7 @@ namespace service_nodes std::shared_ptr quorum = get_quorum(type, height); if (!quorum) { - LOG_PRINT_L1("Quorum for height: " << height << ", was not stored by the daemon"); + oxen::log::info(logcat, "Quorum for height: {}, was not stored by the daemon", height); return false; } @@ -475,13 +474,13 @@ namespace service_nodes money_transferred = rct::decodeRct(tx.rct_signatures, rct::sk2rct(scalar1), i, mask, hwdev); break; default: - LOG_PRINT_L0(__func__ << ": Unsupported rct type: " << (int)tx.rct_signatures.type); + oxen::log::warning(logcat, "{}: Unsupported rct type: {}", __func__, (int)tx.rct_signatures.type); return 0; } } catch (const std::exception &e) { - LOG_PRINT_L0("Failed to decode input " << i); + oxen::log::warning(logcat, "Failed to decode input {}", i); return 0; } @@ -500,7 +499,7 @@ namespace service_nodes if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, contribution->tx_key)) { - LOG_PRINT_L1("TX: There was a service node contributor but no secret key in the tx extra for tx: " << txid); + oxen::log::info(logcat, "TX: There was a service node contributor but no secret key in the tx extra for tx: {}", txid); return false; } @@ -542,7 +541,7 @@ namespace service_nodes crypto::key_derivation derivation; if (!crypto::generate_key_derivation(contribution->address.m_view_public_key, contribution->tx_key, derivation)) { - LOG_PRINT_L1("TX: Failed to generate key derivation on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Failed to generate key derivation on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -565,7 +564,7 @@ namespace service_nodes cryptonote::tx_extra_tx_key_image_proofs key_image_proofs; if (!get_field_from_tx_extra(tx.extra, key_image_proofs)) { - LOG_PRINT_L1("TX: Didn't have key image proofs in the tx_extra, rejected on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Didn't have key image proofs in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); stake_decoded = false; } @@ -594,7 +593,7 @@ namespace service_nodes // P' := Derivation + B if (!hwdev.derive_public_key(derivation, output_index, contribution->address.m_spend_public_key, ephemeral_pub_key)) { - LOG_PRINT_L1("TX: Could not derive TX ephemeral key on height: " << block_height << " for tx: " << get_transaction_hash(tx) << " for output: " << output_index); + oxen::log::info(logcat, "TX: Could not derive TX ephemeral key on height: {} for tx: {} for output: {}", block_height, get_transaction_hash(tx), output_index); continue; } @@ -602,7 +601,7 @@ namespace service_nodes const auto& out_to_key = var::get(tx.vout[output_index].target); if (out_to_key.key != ephemeral_pub_key) { - LOG_PRINT_L1("TX: Derived TX ephemeral key did not match tx stored key on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx) << " for output: " << output_index); + oxen::log::info(logcat, "TX: Derived TX ephemeral key did not match tx stored key on height: {} for tx: {} for output: {}", block_height, cryptonote::get_transaction_hash(tx), output_index); continue; } } @@ -681,7 +680,7 @@ namespace service_nodes cryptonote::tx_extra_service_node_state_change state_change; if (!cryptonote::get_service_node_state_change_from_tx_extra(tx.extra, state_change, hf_version)) { - MERROR("Transaction: " << cryptonote::get_transaction_hash(tx) << ", did not have valid state change data in tx extra rejecting malformed tx"); + oxen::log::error(logcat, "Transaction: {}, did not have valid state change data in tx extra rejecting malformed tx", cryptonote::get_transaction_hash(tx)); return false; } @@ -691,10 +690,7 @@ namespace service_nodes it = state_archive.find(state_change.block_height); if (it == state_archive.end()) { - MERROR("Transaction: " << cryptonote::get_transaction_hash(tx) << " in block " - << cryptonote::get_block_height(block) << " " << cryptonote::get_block_hash(block) - << " references quorum height " << state_change.block_height - << " but that height is not stored!"); + oxen::log::error(logcat, "Transaction: {} in block {} {} references quorum height but that height is not stored!", cryptonote::get_transaction_hash(tx), cryptonote::get_block_height(block), cryptonote::get_block_hash(block), state_change.block_height); return false; } } @@ -720,20 +716,20 @@ namespace service_nodes if (!quorums) { - MERROR("Could not get a quorum that could completely validate the votes from state change in tx: " << get_transaction_hash(tx) << ", skipping transaction"); + oxen::log::error(logcat, "Could not get a quorum that could completely validate the votes from state change in tx: {}, skipping transaction", get_transaction_hash(tx)); return false; } crypto::public_key key; if (!get_pubkey_from_quorum(*quorums->obligations, quorum_group::worker, state_change.service_node_index, key)) { - MERROR("Retrieving the public key from state change in tx: " << cryptonote::get_transaction_hash(tx) << " failed"); + oxen::log::error(logcat, "Retrieving the public key from state change in tx: {} failed", cryptonote::get_transaction_hash(tx)); return false; } auto iter = service_nodes_infos.find(key); if (iter == service_nodes_infos.end()) { - LOG_PRINT_L2("Received state change tx for non-registered service node " << key << " (perhaps a delayed tx?)"); + oxen::log::debug(logcat, "Received state change tx for non-registered service node {} (perhaps a delayed tx?)", key); return false; } @@ -744,9 +740,9 @@ namespace service_nodes switch (state_change.state) { case new_state::deregister: if (is_me) - MGINFO_RED("Deregistration for service node (yours): " << key); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Deregistration for service node (yours): {}", key)); else - LOG_PRINT_L1("Deregistration for service node: " << key); + oxen::log::info(logcat, "Deregistration for service node: {}", key); if (hf_version >= hf::hf11_infinite_staking) { @@ -768,19 +764,19 @@ namespace service_nodes case new_state::decommission: if (hf_version < hf::hf12_checkpointing) { - MERROR("Invalid decommission transaction seen before network v12"); + oxen::log::error(logcat, "Invalid decommission transaction seen before network v12"); return false; } if (info.is_decommissioned()) { - LOG_PRINT_L2("Received decommission tx for already-decommissioned service node " << key << "; ignoring"); + oxen::log::debug(logcat, "Received decommission tx for already-decommissioned service node {}; ignoring", key); return false; } if (is_me) - MGINFO_RED("Temporary decommission for service node (yours): " << key); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Temporary decommission for service node (yours): {}", key)); else - LOG_PRINT_L1("Temporary decommission for service node: " << key); + oxen::log::info(logcat, "Temporary decommission for service node: {}", key); info.active_since_height = -info.active_since_height; info.last_decommission_height = block_height; @@ -806,19 +802,19 @@ namespace service_nodes case new_state::recommission: { if (hf_version < hf::hf12_checkpointing) { - MERROR("Invalid recommission transaction seen before network v12"); + oxen::log::error(logcat, "Invalid recommission transaction seen before network v12"); return false; } if (!info.is_decommissioned()) { - LOG_PRINT_L2("Received recommission tx for already-active service node " << key << "; ignoring"); + oxen::log::debug(logcat, "Received recommission tx for already-active service node {}; ignoring", key); return false; } if (is_me) - MGINFO_GREEN("Recommission for service node (yours): " << key); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Recommission for service node (yours): {}", key)); else - LOG_PRINT_L1("Recommission for service node: " << key); + oxen::log::info(logcat, "Recommission for service node: {}", key); // To figure out how much credit the node gets at recommissioned we need to know how much it // had when it got decommissioned, and how long it's been decommisioned. @@ -851,19 +847,19 @@ namespace service_nodes } case new_state::ip_change_penalty: if (hf_version < hf::hf12_checkpointing) { - MERROR("Invalid ip_change_penalty transaction seen before network v12"); + oxen::log::error(logcat, "Invalid ip_change_penalty transaction seen before network v12"); return false; } if (info.is_decommissioned()) { - LOG_PRINT_L2("Received reset position tx for service node " << key << " but it is already decommissioned; ignoring"); + oxen::log::debug(logcat, "Received reset position tx for service node {} but it is already decommissioned; ignoring", key); return false; } if (is_me) - MGINFO_RED("Reward position reset for service node (yours): " << key); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Reward position reset for service node (yours): {}", key)); else - LOG_PRINT_L1("Reward position reset for service node: " << key); + oxen::log::info(logcat, "Reward position reset for service node: {}", key); // Move the SN at the back of the list as if it had just registered (or just won) @@ -874,7 +870,7 @@ namespace service_nodes default: // dev bug! - MERROR("BUG: Service node state change tx has unknown state " << static_cast(state_change.state)); + oxen::log::error(logcat, "BUG: Service node state change tx has unknown state {}", static_cast(state_change.state)); return false; } } @@ -892,17 +888,14 @@ namespace service_nodes const service_node_info &node_info = *it->second; if (node_info.requested_unlock_height != KEY_IMAGE_AWAITING_UNLOCK_HEIGHT) { - LOG_PRINT_L1("Unlock TX: Node already requested an unlock at height: " - << node_info.requested_unlock_height << " rejected on height: " << block_height - << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "Unlock TX: Node already requested an unlock at height: {} rejected on height: {} for tx: {}", node_info.requested_unlock_height, block_height, cryptonote::get_transaction_hash(tx)); return false; } cryptonote::tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - LOG_PRINT_L1("Unlock TX: Didn't have key image unlock in the tx_extra, rejected on height: " - << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "Unlock TX: Didn't have key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -924,11 +917,7 @@ namespace service_nodes { if (cit->amount < small_contributor_amount_threshold && (block_height - node_info.registration_height) < service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) { - LOG_PRINT_L1("Unlock TX: small contributor trying to unlock node before " - << std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) - << " blocks have passed, rejected on height: " - << block_height << " for tx: " - << get_transaction_hash(tx)); + oxen::log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); return false; } } @@ -937,11 +926,7 @@ namespace service_nodes { if (cit->amount < 3749 && (block_height - node_info.registration_height) < service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) { - LOG_PRINT_L1("Unlock TX: small contributor trying to unlock node before " - << std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) - << " blocks have passed, rejected on height: " - << block_height << " for tx: " - << get_transaction_hash(tx)); + oxen::log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); return false; } } @@ -954,8 +939,7 @@ namespace service_nodes } else { - LOG_PRINT_L1("Unlock TX: Couldn't verify key image unlock in the tx_extra, rejected on height: " - << block_height << " for tx: " << get_transaction_hash(tx)); + oxen::log::info(logcat, "Unlock TX: Couldn't verify key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, get_transaction_hash(tx)); return false; } } @@ -1017,7 +1001,7 @@ namespace service_nodes } catch (const invalid_registration &e) { - LOG_PRINT_L1("Invalid registration (" << cryptonote::get_transaction_hash(tx) << " @ " << block_height << "): " << e.what()); + oxen::log::info(logcat, "Invalid registration ({} @ {}): {}", cryptonote::get_transaction_hash(tx), block_height, e.what()); return false; } @@ -1028,7 +1012,7 @@ namespace service_nodes staking_components stake = {}; if (!tx_get_staking_components_and_amounts(nettype, hf_version, tx, block_height, &stake)) { - LOG_PRINT_L1("Register TX: Had service node registration fields, but could not decode contribution on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "Register TX: Had service node registration fields, but could not decode contribution on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1038,7 +1022,7 @@ namespace service_nodes // 1. the staked amount in the tx must be a single output. if (stake.locked_contributions.size() != 1) { - LOG_PRINT_L1("Register TX invalid: multi-output registration transactions are not permitted as of HF16"); + oxen::log::info(logcat, "Register TX invalid: multi-output registration transactions are not permitted as of HF16"); return false; } @@ -1046,7 +1030,7 @@ namespace service_nodes // could manually construct a registration tx that stakes for someone *other* than the operator). if (stake.address != reg.reserved[0].first) { - LOG_PRINT_L1("Register TX invalid: registration stake is not from the operator"); + oxen::log::info(logcat, "Register TX invalid: registration stake is not from the operator"); return false; } @@ -1059,7 +1043,7 @@ namespace service_nodes const uint64_t min_transfer = get_min_node_contribution(hf_version, staking_requirement, 0, 0); if (stake.transferred < min_transfer) { - LOG_PRINT_L1("Register TX: Contribution transferred: " << stake.transferred << " didn't meet the minimum transfer requirement: " << min_transfer << " on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "Register TX: Contribution transferred: {} didn't meet the minimum transfer requirement: {} on height: {} for tx: {}", stake.transferred, min_transfer, block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1072,10 +1056,7 @@ namespace service_nodes // the registration details, and we disallow a non-operator registration. if (total_num_of_addr > oxen::MAX_CONTRIBUTORS_V1) { - LOG_PRINT_L1("Register TX: Number of participants: " << total_num_of_addr << - " exceeded the max number of contributors: " << oxen::MAX_CONTRIBUTORS_V1 << - " on height: " << block_height << - " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "Register TX: Number of participants: {} exceeded the max number of contributions: {} on height: {} for tx: {}", total_num_of_addr, oxen::MAX_CONTRIBUTORS_V1, block_height, cryptonote::get_transaction_hash(tx)); return false; } } @@ -1107,7 +1088,7 @@ namespace service_nodes { if (it2->first == addr) { - LOG_PRINT_L1("Invalid registration: duplicate reserved address in registration (tx " << cryptonote::get_transaction_hash(tx) << ")"); + oxen::log::info(logcat, "Invalid registration: duplicate reserved address in registration (tx {})", cryptonote::get_transaction_hash(tx)); return false; } } @@ -1127,7 +1108,7 @@ namespace service_nodes // reserved amount was higher (though wallets would never actually do this). if (hf_version >= hf::hf16_pulse && stake.transferred < info.contributors[0].reserved) { - LOG_PRINT_L1("Register TX rejected: TX does not have sufficient operator stake"); + oxen::log::info(logcat, "Register TX rejected: TX does not have sufficient operator stake"); return false; } @@ -1162,8 +1143,10 @@ namespace service_nodes proof.store(key, sn_list->m_blockchain); } - if (my_keys && my_keys->pub == key) MGINFO_GREEN("Service node registered (yours): " << key << " on height: " << block_height); - else LOG_PRINT_L1("New service node registered: " << key << " on height: " << block_height); + if (my_keys && my_keys->pub == key) + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} on height: {}", key, block_height)); + else + oxen::log::info(logcat, "New service node registered: {} on height: {}", key, block_height); } else { @@ -1195,16 +1178,16 @@ namespace service_nodes { if (registered_during_grace_period) { - MGINFO_GREEN("Service node re-registered (yours): " << key << " at block height: " << block_height); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node re-registered (yours): {} at block height: {}", key, block_height)); } else { - MGINFO_GREEN("Service node registered (yours): " << key << " at block height: " << block_height); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} at block height: {}", key, block_height)); } } else { - LOG_PRINT_L1("New service node registered: " << key << " at block height: " << block_height); + oxen::log::info(logcat, "New service node registered: {} at block height: {}", key, block_height); } } @@ -1221,33 +1204,27 @@ namespace service_nodes if (!tx_get_staking_components_and_amounts(nettype, hf_version, tx, block_height, &stake)) { if (stake.service_node_pubkey) - LOG_PRINT_L1("TX: Could not decode contribution for service node: " << stake.service_node_pubkey << " on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Could not decode contribution for service node: {} on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } auto iter = service_nodes_infos.find(stake.service_node_pubkey); if (iter == service_nodes_infos.end()) { - LOG_PRINT_L1("TX: Contribution received for service node: " - << stake.service_node_pubkey << ", but could not be found in the service node list on height: " - << block_height << " for tx: " << cryptonote::get_transaction_hash(tx) - << "\n" - "This could mean that the service node was deregistered before the contribution was processed."); + oxen::log::info(logcat, "TX: Contribution received for service node: {}, but could not be found in the service node list on height: {} for tx: {}\n This could mean that the service node was deregistered before the contribution was processed.", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } const service_node_info& curinfo = *iter->second; if (curinfo.is_fully_funded()) { - LOG_PRINT_L1("TX: Service node: " << stake.service_node_pubkey - << " is already fully funded, but contribution received on height: " - << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Service node: {} is already fully funded, but contribution received on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, stake.tx_key)) { - LOG_PRINT_L1("TX: Failed to get tx secret key from contribution received on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Failed to get tx secret key from contribution received on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1275,7 +1252,7 @@ namespace service_nodes { // Nothing has ever created stake txes with multiple stake outputs, but we start enforcing // that in HF16. - LOG_PRINT_L1("Ignoring staking tx: multi-output stakes are not permitted as of HF16"); + oxen::log::info(logcat, "Ignoring staking tx: multi-output stakes are not permitted as of HF16"); return false; } @@ -1297,10 +1274,7 @@ namespace service_nodes if (too_many_contributions) { - LOG_PRINT_L1("TX: Already hit the max number of contributions: " - << (hf_version >= hf::hf19_reward_batching ? oxen::MAX_CONTRIBUTORS_HF19 : oxen::MAX_CONTRIBUTORS_V1) - << " for contributor: " << cryptonote::get_account_address_as_str(nettype, false, stake.address) - << " on height: " << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Already hit the max number of contributions: {} for contributor: {} on height: {} for tx: {}", (hf_version >= hf::hf19_reward_batching ? oxen::MAX_CONTRIBUTORS_HF19 : oxen::MAX_CONTRIBUTORS_V1), cryptonote::get_account_address_as_str(nettype, false, stake.address), block_height, cryptonote::get_transaction_hash(tx)); return false; } } @@ -1327,9 +1301,7 @@ namespace service_nodes if (stake.transferred < min_contribution) { - LOG_PRINT_L1("TX: Amount " << stake.transferred << " did not meet min " << min_contribution - << " for service node: " << stake.service_node_pubkey << " on height: " - << block_height << " for tx: " << cryptonote::get_transaction_hash(tx)); + oxen::log::info(logcat, "TX: Amount {} did not meet min {} for service node: {} on height: {} for tx: {}", stake.transferred, min_contribution, stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1338,7 +1310,7 @@ namespace service_nodes if (auto max = get_max_node_contribution(hf_version, curinfo.staking_requirement, curinfo.total_reserved - contr_unfilled_reserved); stake.transferred > max) { - MINFO("TX: Amount " << stake.transferred << " is too large (max " << max << "). This is probably a result of competing stakes."); + oxen::log::info(logcat, "TX: Amount {} is too large (max {}). This is probably a result of competing stakes.", stake.transferred, max); return false; } @@ -1376,7 +1348,7 @@ namespace service_nodes for (const auto &contribution : stake.locked_contributions) contributor.locked_contributions.push_back(contribution); - LOG_PRINT_L1("Contribution of " << stake.transferred << " received for service node " << stake.service_node_pubkey); + oxen::log::info(logcat, "Contribution of {} received for service node {}", stake.transferred, stake.service_node_pubkey); if (info.is_fully_funded()) { info.active_since_height = block_height; return true; @@ -1422,7 +1394,7 @@ namespace service_nodes std::shared_ptr pulse_quorum, std::vector> &alt_pulse_quorums) { - std::string_view block_type = alt_block ? "alt block "sv : "block "sv; + std::string_view block_type = alt_block ? "alt block"sv : "block"sv; uint64_t height = cryptonote::get_block_height(block); crypto::hash hash = cryptonote::get_block_hash(block); @@ -1431,26 +1403,30 @@ namespace service_nodes if (cryptonote::block_has_pulse_components(block)) { - if (log_errors) MGINFO("Pulse " << block_type << "received but only miner blocks are permitted\n" << dump_pulse_block_data(block, pulse_quorum.get())); + if (log_errors) + oxen::log::info(logcat, "Pulse {} received but only miner blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } if (block.pulse.round != 0) { - if (log_errors) MGINFO("Miner " << block_type << "given but unexpectedly set round " << block.pulse.round << " on height " << height); + if (log_errors) + oxen::log::info(logcat, "Miner {} given but unexpectedly set round {} on height {}", block_type, block.pulse.round, height); return false; } if (block.pulse.validator_bitset != 0) { std::bitset<8 * sizeof(block.pulse.validator_bitset)> const bitset = block.pulse.validator_bitset; - if (log_errors) MGINFO("Miner " << block_type << "block given but unexpectedly set validator bitset " << bitset << " on height " << height); + if (log_errors) + oxen::log::info(logcat, "Miner {} block given but unexpectedly set validator bitset {} on height {}", block_type, bitset.to_string(), height); return false; } if (block.signatures.size()) { - if (log_errors) MGINFO("Miner " << block_type << "block given but unexpectedly has " << block.signatures.size() << " signatures on height " << height); + if (log_errors) + oxen::log::info(logcat, "Miner {} block given but unexpectedly has {} signatures on height {}", block_type, block.signatures.size(), height); return false; } @@ -1460,7 +1436,8 @@ namespace service_nodes { if (!cryptonote::block_has_pulse_components(block)) { - if (log_errors) MGINFO("Miner " << block_type << "received but only pulse blocks are permitted\n" << dump_pulse_block_data(block, pulse_quorum.get())); + if (log_errors) + oxen::log::info(logcat, "Miner {} received but only pulse blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } @@ -1478,14 +1455,16 @@ namespace service_nodes std::string time = tools::get_human_readable_timestamp(block.timestamp); std::string begin = tools::get_human_readable_timestamp(begin_time); std::string end = tools::get_human_readable_timestamp(end_time); - if (log_errors) MGINFO("Pulse " << block_type << "with round " << +block.pulse.round << " specifies timestamp " << time << " is not within an acceptable range of time [" << begin << ", " << end << "]"); + if (log_errors) + oxen::log::info(logcat, "Pulse {} with round {} specifies timestamp {} is not within an acceptable range of time [{}, {}]", block_type, +block.pulse.round, time, begin, end); return false; } } if (block.nonce != 0) { - if (log_errors) MGINFO("Pulse " << block_type << "specified a nonce when quorum block generation is available, nonce: " << block.nonce); + if (log_errors) + oxen::log::info(logcat, "Pulse {} specified a nonce when quorum block generation is available, nonce: {}", block_type, block.nonce); return false; } @@ -1497,7 +1476,7 @@ namespace service_nodes bool failed_quorum_verify = true; if (pulse_quorum) { - LOG_PRINT_L1("Verifying alt-block " << height << ":" << hash << " against main chain quorum"); + oxen::log::info(logcat, "Verifying alt-block {}:{} against main chain quorum", height, hash); failed_quorum_verify = service_nodes::verify_quorum_signatures(*pulse_quorum, quorum_type::pulse, block.major_version, @@ -1510,7 +1489,7 @@ namespace service_nodes // NOTE: Check alt pulse quorums if (failed_quorum_verify) { - LOG_PRINT_L1("Verifying alt-block " << height << ":" << hash << " against alt chain quorum(s)"); + oxen::log::info(logcat, "Verifying alt-block {}:{} against alt chain quorum(s)", height, hash); for (auto const &alt_quorum : alt_pulse_quorums) { if (service_nodes::verify_quorum_signatures(*alt_quorum, @@ -1537,7 +1516,8 @@ namespace service_nodes bool insufficient_nodes_for_pulse = pulse_quorum == nullptr; if (insufficient_nodes_for_pulse) { - if (log_errors) MGINFO("Pulse " << block_type << "specified but no quorum available " << dump_pulse_block_data(block, pulse_quorum.get())); + if (log_errors) + oxen::log::info(logcat, "Pulse {} specified but no quorum available {}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } @@ -1554,7 +1534,7 @@ namespace service_nodes { // NOTE: These invariants are already checked in verify_quorum_signatures if (alt_block) - LOG_PRINT_L1("Alt-block " << height << ":" << hash << " verified successfully"); + oxen::log::info(logcat, "Alt-block {}:{} verified successfully", height, hash); assert(block.pulse.validator_bitset != 0); assert(block.pulse.validator_bitset < (1 << PULSE_QUORUM_NUM_VALIDATORS)); assert(block.signatures.size() == service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES); @@ -1562,7 +1542,7 @@ namespace service_nodes else { if (log_errors) - MGINFO("Pulse " << block_type << "failed quorum verification\n" << dump_pulse_block_data(block, pulse_quorum.get())); + oxen::log::info(logcat, "Pulse {} failed quorum verification\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); } return quorum_verified; @@ -1578,18 +1558,18 @@ namespace service_nodes catch(std::exception const &e) { // ignore not found block, try alt db - LOG_PRINT_L1("Block " << hash << " not found in main DB, searching alt DB"); + oxen::log::info(logcat, "Block {} not found in main DB, searching alt DB", hash); cryptonote::alt_block_data_t alt_data; std::string blob; if (!db.get_alt_block(hash, &alt_data, &blob, nullptr)) { - MERROR("Failed to find block " << hash); + oxen::log::error(logcat, "Failed to find block {}", hash); return false; } if (!cryptonote::parse_and_validate_block_from_blob(blob, block, nullptr)) { - MERROR("Failed to parse alt block blob at " << alt_data.height << ":" << hash); + oxen::log::error(logcat, "Failed to parse alt block blob at {}:{}", alt_data.height, hash); return false; } } @@ -1777,7 +1757,7 @@ namespace service_nodes uint64_t block_height = cryptonote::get_block_height(block); if (m_blockchain.nettype() != cryptonote::network_type::FAKECHAIN && block.major_version >= hf::hf19_reward_batching && height() != block_height) { - MERROR("Service node list out of sync with the batching database, adding block will fail because the service node list is at height: " << height() << " and the batching database is at height: " << m_blockchain.sqlite_db()->height+1); + oxen::log::error(logcat, "Service node list out of sync with the batching database, adding block will fail because the service node list is at height: {} and the batching database is at height: {}", height(), m_blockchain.sqlite_db()->height+1); return false; } return m_blockchain.sqlite_db()->add_block(block, m_state); @@ -1896,7 +1876,7 @@ namespace service_nodes uint64_t const top_height = cryptonote::get_block_height(top_block); if (top_height < PULSE_QUORUM_ENTROPY_LAG) { - MERROR("Insufficient blocks to get quorum entropy for Pulse, height is " << top_height << ", we need " << PULSE_QUORUM_ENTROPY_LAG << " blocks."); + oxen::log::error(logcat, "Insufficient blocks to get quorum entropy for Pulse, height is {}, we need {} blocks.", top_height, PULSE_QUORUM_ENTROPY_LAG); return {}; } @@ -1916,7 +1896,7 @@ namespace service_nodes cryptonote::block block; if (!find_block_in_db(db, prev_hash, block)) { - MERROR("Failed to get quorum entropy for Pulse, block at " << prev_height << prev_hash); + oxen::log::error(logcat, "Failed to get quorum entropy for Pulse, block at {}{}", prev_height, prev_hash); return {}; } @@ -1937,7 +1917,7 @@ namespace service_nodes cryptonote::block top_block; if (!find_block_in_db(db, top_hash, top_block)) { - MERROR("Failed to get quorum entropy for Pulse, next block parent " << top_hash); + oxen::log::error(logcat, "Failed to get quorum entropy for Pulse, next block parent {}", top_hash); return {}; } @@ -1960,13 +1940,13 @@ namespace service_nodes service_nodes::quorum result = {}; if (active_snode_list.size() < pulse_min_service_nodes(nettype)) { - LOG_PRINT_L2("Insufficient active Service Nodes for Pulse: " << active_snode_list.size()); + oxen::log::debug(logcat, "Insufficient active Service Nodes for Pulse: {}", active_snode_list.size()); return result; } if (pulse_entropy.size() != PULSE_QUORUM_SIZE) { - LOG_PRINT_L2("Blockchain has insufficient blocks to generate Pulse data"); + oxen::log::debug(logcat, "Blockchain has insufficient blocks to generate Pulse data"); return result; } @@ -2123,7 +2103,7 @@ namespace service_nodes // NOTE: NOP. Pulse quorums are generated pre-Service Node List changes for the block case quorum_type::pulse: continue; - default: MERROR("Unhandled quorum type enum with value: " << type_int); continue; + default: oxen::log::error(logcat, "Unhandled quorum type enum with value: {}", type_int); continue; } quorum->validators.reserve(num_validators); @@ -2212,8 +2192,10 @@ namespace service_nodes auto i = service_nodes_infos.find(pubkey); if (i != service_nodes_infos.end()) { - if (my_keys && my_keys->pub == pubkey) MGINFO_GREEN("Service node expired (yours): " << pubkey << " at block height: " << block_height); - else LOG_PRINT_L1("Service node expired: " << pubkey << " at block height: " << block_height); + if (my_keys && my_keys->pub == pubkey) + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node expired (yours): {} at block height: {}", pubkey, block_height)); + else + oxen::log::info(logcat, "Service node expired: {} at block height: {}", pubkey, block_height); need_swarm_update += i->second->is_active(); service_nodes_infos.erase(i); @@ -2404,7 +2386,7 @@ namespace service_nodes } catch (std::exception const &e) { - LOG_ERROR("Failed to get historical block to find expired nodes in v9: " << e.what()); + oxen::log::error(logcat, "Failed to get historical block to find expired nodes in v9: {}", e.what()); return expired_nodes; } @@ -2416,7 +2398,7 @@ namespace service_nodes cryptonote::transaction tx; if (!db.get_tx(hash, tx)) { - LOG_ERROR("Failed to get historical tx to find expired service nodes in v9"); + oxen::log::error(logcat, "Failed to get historical tx to find expired service nodes in v9"); continue; } @@ -2600,7 +2582,7 @@ namespace service_nodes if (block.major_version >= hf::hf19_reward_batching) { mode = verify_mode::batched_sn_rewards; - MDEBUG("Batched miner reward"); + oxen::log::debug(logcat, "Batched miner reward"); } size_t expected_vouts_size; @@ -2907,7 +2889,7 @@ namespace service_nodes try { serialization::serialize(ba, m_transient.cache_long_term_data); } catch (const std::exception& e) { - LOG_ERROR("Failed to store service node info: failed to serialize long term data: " << e.what()); + oxen::log::error(logcat, "Failed to store service node info: failed to serialize long term data: {}", e.what()); return false; } m_transient.cache_data_blob.append(ba.str()); @@ -2924,7 +2906,7 @@ namespace service_nodes try { serialization::serialize(ba, m_transient.cache_short_term_data); } catch (const std::exception& e) { - LOG_ERROR("Failed to store service node info: failed to serialize short term data: " << e.what()); + oxen::log::error(logcat, "Failed to store service node info: failed to serialize short term data: {}", e.what()); return false; } m_transient.cache_data_blob.append(ba.str()); @@ -3088,20 +3070,22 @@ namespace service_nodes if (pk && 0 == crypto_sign_ed25519_pk_to_curve25519(pubkey_x25519.data, pk.data)) { proof->pubkey_ed25519 = pk; } else { - MWARNING("Failed to derive x25519 pubkey from ed25519 pubkey " << proof->pubkey_ed25519); + oxen::log::warning(logcat, "Failed to derive x25519 pubkey from ed25519 pubkey {}", proof->pubkey_ed25519); pubkey_x25519 = crypto::x25519_public_key::null(); proof->pubkey_ed25519 = crypto::ed25519_public_key::null(); } } -#define REJECT_PROOF(log) do { LOG_PRINT_L2("Rejecting uptime proof from " << proof.pubkey << ": " log); return false; } while (0) //TODO remove after HF18, snode revision 1 bool service_node_list::handle_uptime_proof(cryptonote::NOTIFY_UPTIME_PROOF::request const &proof, bool &my_uptime_proof_confirmation, crypto::x25519_public_key &x25519_pkey) { auto vers = get_network_version_revision(m_blockchain.nettype(), m_blockchain.get_current_blockchain_height()); if (vers >= std::make_pair(hf::hf18, uint8_t{1})) - REJECT_PROOF("Old format (non-bt) proofs are not acceptable from v18+1 onwards"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: Old format (non-bt) proofs are not acceptable from v18+1 onwards", proof.pubkey); + return false; + } auto& netconf = get_config(m_blockchain.nettype()); auto now = std::chrono::system_clock::now(); @@ -3109,15 +3093,23 @@ namespace service_nodes // Validate proof version, timestamp range, auto time_deviation = now - std::chrono::system_clock::from_time_t(proof.timestamp); if (time_deviation > netconf.UPTIME_PROOF_TOLERANCE || time_deviation < -netconf.UPTIME_PROOF_TOLERANCE) - REJECT_PROOF("timestamp is too far from now"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof.pubkey); + return false; + } for (auto const &min : MIN_UPTIME_PROOF_VERSIONS) if (vers >= min.hardfork_revision && proof.snode_version < min.oxend) - REJECT_PROOF("v" << tools::join(".", min.oxend) << "+ oxend version is required for v" - << static_cast(vers.first) << "." << +vers.second << "+ network proofs"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof.pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); + return false; + } if (!debug_allow_local_ips && !epee::net_utils::is_ip_public(proof.public_ip)) - REJECT_PROOF("public_ip is not actually public"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof.pubkey); + return false; + } // // Validate proof signature @@ -3126,46 +3118,65 @@ namespace service_nodes if (!crypto::check_signature(hash, proof.pubkey, proof.sig)) - REJECT_PROOF("signature validation failed"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof.pubkey); + return false; + } crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); if (!proof.pubkey_ed25519) - REJECT_PROOF("required ed25519 auxiliary pubkey " << proof.pubkey_ed25519 << " not included in proof"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof.pubkey, proof.pubkey_ed25519); + return false; + } if (0 != crypto_sign_verify_detached(proof.sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof.pubkey_ed25519.data)) - REJECT_PROOF("ed25519 signature validation failed"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof.pubkey); + return false; + } - if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof.pubkey_ed25519.data) - || !derived_x25519_pubkey) - REJECT_PROOF("invalid ed25519 pubkey included in proof (x25519 derivation failed)"); + if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof.pubkey_ed25519.data) || !derived_x25519_pubkey) + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof.pubkey); + return false; + } if (proof.qnet_port == 0) - REJECT_PROOF("invalid quorumnet port in uptime proof"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof.pubkey); + return false; + } auto locks = tools::unique_locks(m_blockchain, m_sn_mutex, m_x25519_map_mutex); auto it = m_state.service_nodes_infos.find(proof.pubkey); if (it == m_state.service_nodes_infos.end()) - REJECT_PROOF("no such service node is currently registered"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof.pubkey); + return false; + } auto &iproof = proofs[proof.pubkey]; if (now <= std::chrono::system_clock::from_time_t(iproof.timestamp) + std::chrono::seconds{netconf.UPTIME_PROOF_FREQUENCY} / 2) - REJECT_PROOF("already received one uptime proof for this node recently"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof.pubkey); + return false; + } if (m_service_node_keys && proof.pubkey == m_service_node_keys->pub) { my_uptime_proof_confirmation = true; - MGINFO("Received uptime-proof confirmation back from network for Service Node (yours): " << proof.pubkey); + oxen::log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof.pubkey); } else { my_uptime_proof_confirmation = false; - LOG_PRINT_L2("Accepted uptime proof from " << proof.pubkey); + oxen::log::debug(logcat, "Accepted uptime proof from {}", proof.pubkey); if (m_service_node_keys && proof.pubkey_ed25519 == m_service_node_keys->pub_ed25519) - MGINFO_RED("Uptime proof from SN " << proof.pubkey << " is not us, but is using our ed/x25519 keys; " - "this is likely to lead to deregistration of one or both service nodes."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof.pubkey)); } auto old_x25519 = iproof.pubkey_x25519; @@ -3191,9 +3202,6 @@ namespace service_nodes return true; } -#undef REJECT_PROOF -#define REJECT_PROOF(log) do { LOG_PRINT_L2("Rejecting uptime proof from " << proof->pubkey << ": " log); return false; } while (0) - bool service_node_list::handle_btencoded_uptime_proof(std::unique_ptr proof, bool &my_uptime_proof_confirmation, crypto::x25519_public_key &x25519_pkey) { auto vers = get_network_version_revision(m_blockchain.nettype(), m_blockchain.get_current_blockchain_height()); @@ -3203,21 +3211,36 @@ namespace service_nodes // Validate proof version, timestamp range, auto time_deviation = now - std::chrono::system_clock::from_time_t(proof->timestamp); if (time_deviation > netconf.UPTIME_PROOF_TOLERANCE || time_deviation < -netconf.UPTIME_PROOF_TOLERANCE) - REJECT_PROOF("timestamp is too far from now"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof->pubkey); + return false; + } for (auto const &min : MIN_UPTIME_PROOF_VERSIONS) { if (vers >= min.hardfork_revision && m_blockchain.nettype() != cryptonote::network_type::DEVNET) { if (proof->version < min.oxend) - REJECT_PROOF("v" << tools::join(".", min.oxend) << "+ oxend version is required for v" << static_cast(vers.first) << "." << +vers.second << "+ network proofs"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); + return false; + } if (proof->lokinet_version < min.lokinet) - REJECT_PROOF("v" << tools::join(".", min.lokinet) << "+ lokinet version is required for v" << static_cast(vers.first) << "." << +vers.second << "+ network proofs"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ lokinet version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.lokinet), static_cast(vers.first), vers.second); + return false; + } if (proof->storage_server_version < min.storage_server) - REJECT_PROOF("v" << tools::join(".", min.storage_server) << "+ storage server version is required for v" << static_cast(vers.first) << "." << +vers.second << "+ network proofs"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ storage server version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.storage_server), static_cast(vers.first), vers.second); + return false; + } } } if (!debug_allow_local_ips && !epee::net_utils::is_ip_public(proof->public_ip)) - REJECT_PROOF("public_ip is not actually public"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof->pubkey); + return false; + } // // Validate proof signature @@ -3225,45 +3248,64 @@ namespace service_nodes crypto::hash hash = proof->hash_uptime_proof(); if (!crypto::check_signature(hash, proof->pubkey, proof->sig)) - REJECT_PROOF("signature validation failed"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof->pubkey); + return false; + } crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); if (!proof->pubkey_ed25519) - REJECT_PROOF("required ed25519 auxiliary pubkey " << proof->pubkey_ed25519 << " not included in proof"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof->pubkey, proof->pubkey_ed25519); + return false; + } if (0 != crypto_sign_verify_detached(proof->sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof->pubkey_ed25519.data)) - REJECT_PROOF("ed25519 signature validation failed"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof->pubkey); + return false; + } - if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof->pubkey_ed25519.data) - || !derived_x25519_pubkey) - REJECT_PROOF("invalid ed25519 pubkey included in proof (x25519 derivation failed)"); + if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof->pubkey_ed25519.data) || !derived_x25519_pubkey) + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof->pubkey); + return false; + } if (proof->qnet_port == 0) - REJECT_PROOF("invalid quorumnet port in uptime proof"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof->pubkey); + return false; + } auto locks = tools::unique_locks(m_blockchain, m_sn_mutex, m_x25519_map_mutex); auto it = m_state.service_nodes_infos.find(proof->pubkey); if (it == m_state.service_nodes_infos.end()) - REJECT_PROOF("no such service node is currently registered"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof->pubkey); + return false; + } auto &iproof = proofs[proof->pubkey]; if (now <= std::chrono::system_clock::from_time_t(iproof.timestamp) + std::chrono::seconds{netconf.UPTIME_PROOF_FREQUENCY} / 2) - REJECT_PROOF("already received one uptime proof for this node recently"); + { + oxen::log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof->pubkey); + return false; + } if (m_service_node_keys && proof->pubkey == m_service_node_keys->pub) { my_uptime_proof_confirmation = true; - MGINFO("Received uptime-proof confirmation back from network for Service Node (yours): " << proof->pubkey); + oxen::log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof->pubkey); } else { my_uptime_proof_confirmation = false; - LOG_PRINT_L2("Accepted uptime proof from " << proof->pubkey); + oxen::log::debug(logcat, "Accepted uptime proof from {}", proof->pubkey); if (m_service_node_keys && proof->pubkey_ed25519 == m_service_node_keys->pub_ed25519) - MGINFO_RED("Uptime proof from SN " << proof->pubkey << " is not us, but is using our ed/x25519 keys; " - "this is likely to lead to deregistration of one or both service nodes."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof->pubkey)); } auto old_x25519 = iproof.pubkey_x25519; @@ -3293,7 +3335,7 @@ namespace service_nodes void service_node_list::cleanup_proofs() { - MDEBUG("Cleaning up expired SN proofs"); + oxen::log::debug(logcat, "Cleaning up expired SN proofs"); auto locks = tools::unique_locks(m_sn_mutex, m_blockchain); uint64_t now = std::time(nullptr); auto& db = m_blockchain.get_db(); @@ -3355,7 +3397,7 @@ namespace service_nodes auto pubkey = get_pubkey_from_x25519(x25519_pub); if (!pubkey) { - MDEBUG("no connection available: could not find primary pubkey from x25519 pubkey " << x25519_pub); + oxen::log::debug(logcat, "no connection available: could not find primary pubkey from x25519 pubkey {}", x25519_pub); return ""; } @@ -3369,11 +3411,11 @@ namespace service_nodes }); if (!found) { - MDEBUG("no connection available: primary pubkey " << pubkey << " is not registered"); + oxen::log::debug(logcat, "no connection available: primary pubkey {} is not registered", pubkey); return ""; } if (!(ip && port)) { - MDEBUG("no connection available: service node " << pubkey << " has no associated ip and/or port"); + oxen::log::debug(logcat, "no connection available: service node {} has no associated ip and/or port", pubkey); return ""; } @@ -3435,11 +3477,11 @@ namespace service_nodes const auto type = storage_server ? "storage server"sv : "lokinet"sv; if (!m_state.service_nodes_infos.count(pubkey)) { - MDEBUG("Dropping " << type << " reachable report: " << pubkey << " is not a registered SN pubkey"); + oxen::log::debug(logcat, "Dropping {} reachable report: {} is not a registered SN pubkey", type, pubkey); return false; } - MDEBUG("Received " << type << (reachable ? " reachable" : " UNREACHABLE") << " report for SN " << pubkey); + oxen::log::debug(logcat, "Received {}{} report for SN {}", type, (reachable ? " reachable" : " UNREACHABLE"), pubkey); const auto now = std::chrono::steady_clock::now(); @@ -3537,7 +3579,7 @@ namespace service_nodes bool service_node_list::load(const uint64_t current_height) { - LOG_PRINT_L1("service_node_list::load()"); + oxen::log::info(logcat, "service_node_list::load()"); reset(false); if (!m_blockchain.has_db()) { @@ -3574,9 +3616,7 @@ namespace service_nodes size_t const last_index = data_in.states.size() - 1; if ((data_in.states.back().height % STORE_LONG_TERM_STATE_INTERVAL) != 0) { - LOG_PRINT_L0("Last serialised quorum height: " << data_in.states.back().height - << " in archive is unexpectedly not a multiple of: " - << STORE_LONG_TERM_STATE_INTERVAL << ", regenerating state"); + oxen::log::warning(logcat, "Last serialised quorum height: {} in archive is unexpectedly not a multiple of: {}, regenerating state", data_in.states.back().height, STORE_LONG_TERM_STATE_INTERVAL); return false; } @@ -3629,7 +3669,7 @@ namespace service_nodes try { serialization::parse_binary(blob, data_in); } catch (const std::exception& e) { - LOG_ERROR("Failed to parse service node data from blob: " << e.what()); + oxen::log::error(logcat, "Failed to parse service node data from blob: {}", e.what()); return false; } @@ -3650,7 +3690,7 @@ namespace service_nodes if (states.height <= last_loaded_height) { - LOG_PRINT_L0("Serialised quorums is not stored in ascending order by height in DB, failed to load from DB"); + oxen::log::warning(logcat, "Serialised quorums is not stored in ascending order by height in DB, failed to load from DB"); return false; } last_loaded_height = states.height; @@ -3663,7 +3703,7 @@ namespace service_nodes size_t const last_index = data_in.states.size() - 1; if (data_in.states[last_index].only_stored_quorums) { - LOG_PRINT_L0("Unexpected last serialized state only has quorums loaded"); + oxen::log::warning(logcat, "Unexpected last serialized state only has quorums loaded"); return false; } @@ -3707,12 +3747,10 @@ namespace service_nodes initialize_x25519_map(); - MGINFO("Service node data loaded successfully, height: " << m_state.height); - MGINFO(m_state.service_nodes_infos.size() - << " nodes and " << m_transient.state_history.size() << " recent states loaded, " << m_transient.state_archive.size() - << " historical states loaded, (" << tools::get_human_readable_bytes(bytes_loaded) << ")"); + oxen::log::info(logcat, "Service node data loaded successfully, height: {}", m_state.height); + oxen::log::info(logcat, "{} nodes and {} recent states loaded, {} historical states loaded, ({})", m_state.service_nodes_infos.size(), m_transient.state_history.size(), m_transient.state_archive.size(), tools::get_human_readable_bytes(bytes_loaded)); - LOG_PRINT_L1("service_node_list::load() returning success"); + oxen::log::info(logcat, "service_node_list::load() returning success"); return true; } @@ -3907,7 +3945,7 @@ namespace service_nodes try { reg = convert_registration_args(nettype, hf_version, args, staking_requirement); } catch (const invalid_registration& e) { - MERROR(tr("Could not parse registration arguments: ") << e.what()); + oxen::log::error(logcat, "{}{}", tr("Could not parse registration arguments: "), e.what()); return false; } @@ -3939,23 +3977,23 @@ namespace service_nodes { // If the SN expired and was reregistered since the height we'll be voting on it prematurely if (!is_fully_funded()) { - MDEBUG("SN vote at height " << height << " invalid: not fully funded"); + oxen::log::debug(logcat, "SN vote at height {} invalid: not fully funded", height); return false; } else if (height <= registration_height) { - MDEBUG("SN vote at height " << height << " invalid: height <= reg height (" << registration_height << ")"); + oxen::log::debug(logcat, "SN vote at height {} invalid: height <= reg height ({})", height, registration_height); return false; } else if (is_decommissioned() && height <= last_decommission_height) { - MDEBUG("SN vote at height " << height << " invalid: height <= last decomm height (" << last_decommission_height << ")"); + oxen::log::debug(logcat, "SN vote at height {} invalid: height <= last decomm height ({})", height, last_decommission_height); return false; } else if (is_active()) { assert(active_since_height >= 0); // should be satisfied whenever is_active() is true if (height <= static_cast(active_since_height)) { - MDEBUG("SN vote at height " << height << " invalid: height <= active-since height (" << active_since_height << ")"); + oxen::log::debug(logcat, "SN vote at height {} invalid: height <= active-since height ({})", height, active_since_height); return false; } } - MTRACE("SN vote at height " << height << " is valid."); + oxen::log::trace(logcat, "SN vote at height {} is valid.", height); return true; } @@ -3963,25 +4001,25 @@ namespace service_nodes { if (hf_version >= hf::hf13_enforce_checkpoints) { if (!can_be_voted_on(height)) { - MDEBUG("SN state transition invalid: " << height << " is not a valid vote height"); + oxen::log::debug(logcat, "SN state transition invalid: {} is not a valid vote height", height); return false; } if (proposed_state == new_state::deregister) { if (height <= registration_height) { - MDEBUG("SN deregister invalid: vote height (" << height << ") <= registration_height (" << registration_height << ")"); + oxen::log::debug(logcat, "SN deregister invalid: vote height ({}) <= registration_height ({})", height, registration_height); return false; } } else if (proposed_state == new_state::ip_change_penalty) { if (height <= last_ip_change_height) { - MDEBUG("SN ip change penality invalid: vote height (" << height << ") <= last_ip_change_height (" << last_ip_change_height << ")"); + oxen::log::debug(logcat, "SN ip change penality invalid: vote height ({}) <= last_ip_change_height ({})", height, last_ip_change_height); return false; } } } else { // pre-HF13 if (proposed_state == new_state::deregister) { if (height < registration_height) { - MDEBUG("SN deregister invalid: vote height (" << height << ") < registration_height (" << registration_height << ")"); + oxen::log::debug(logcat, "SN deregister invalid: vote height ({}) < registration_height ({})", height, registration_height); return false; } } @@ -3989,18 +4027,18 @@ namespace service_nodes if (is_decommissioned()) { if (proposed_state == new_state::decommission) { - MDEBUG("SN decommission invalid: already decommissioned"); + oxen::log::debug(logcat, "SN decommission invalid: already decommissioned"); return false; } else if (proposed_state == new_state::ip_change_penalty) { - MDEBUG("SN ip change penalty invalid: currently decommissioned"); + oxen::log::debug(logcat, "SN ip change penalty invalid: currently decommissioned"); return false; } return true; // recomm or dereg } else if (proposed_state == new_state::recommission) { - MDEBUG("SN recommission invalid: not recommissioned"); + oxen::log::debug(logcat, "SN recommission invalid: not recommissioned"); return false; } - MTRACE("SN state change is valid"); + oxen::log::trace(logcat, "SN state change is valid"); return true; } diff --git a/src/cryptonote_core/service_node_quorum_cop.cpp b/src/cryptonote_core/service_node_quorum_cop.cpp index bb24b39a5..bbe9b49c4 100644 --- a/src/cryptonote_core/service_node_quorum_cop.cpp +++ b/src/cryptonote_core/service_node_quorum_cop.cpp @@ -39,13 +39,12 @@ #include "epee/net/local_ip.h" #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "quorum_cop" - using cryptonote::hf; namespace service_nodes { + static auto logcat = oxen::log::Cat("quorum_cop"); + std::optional> service_node_test_results::why() const { if (passed()) @@ -112,23 +111,20 @@ namespace service_nodes if (check_uptime_obligation && time_since_last_uptime_proof > netconf.UPTIME_PROOF_VALIDITY) { - LOG_PRINT_L1( - "Service Node: " << pubkey << ", failed uptime proof obligation check: the last uptime proof (" << - tools::get_human_readable_timespan(time_since_last_uptime_proof) << ") was older than max validity (" << - tools::get_human_readable_timespan(netconf.UPTIME_PROOF_VALIDITY) << ")"); + oxen::log::info(logcat, "Service Node: {}, failed uptime proof obligation check: the last uptime proof ({}) was older than max validity ({})", pubkey, tools::get_human_readable_timespan(time_since_last_uptime_proof), tools::get_human_readable_timespan(netconf.UPTIME_PROOF_VALIDITY)); result.uptime_proved = false; } if (!ss_reachable) { - LOG_PRINT_L1("Service Node storage server is not reachable for node: " << pubkey); + oxen::log::info(logcat, "Service Node storage server is not reachable for node: {}", pubkey); result.storage_server_reachable = false; } // TODO: perhaps come back and make this activate on some "soft fork" height before HF19? if (!lokinet_reachable && hf_version >= hf::hf19_reward_batching) { - LOG_PRINT_L1("Service Node lokinet is not reachable for node: " << pubkey); + oxen::log::info(logcat, "Service Node lokinet is not reachable for node: {}", pubkey); result.lokinet_reachable = false; } @@ -150,24 +146,24 @@ namespace service_nodes { if (check_checkpoint_obligation && checkpoint_participation.failures() > CHECKPOINT_MAX_MISSABLE_VOTES) { - LOG_PRINT_L1("Service Node: " << pubkey << ", failed checkpoint obligation check"); + oxen::log::info(logcat, "Service Node: {}, failed checkpoint obligation check", pubkey); result.checkpoint_participation = false; } if (pulse_participation.failures() > PULSE_MAX_MISSABLE_VOTES) { - LOG_PRINT_L1("Service Node: " << pubkey << ", failed pulse obligation check"); + oxen::log::info(logcat, "Service Node: {}, failed pulse obligation check", pubkey); result.pulse_participation = false; } if (timestamp_participation.failures() > TIMESTAMP_MAX_MISSABLE_VOTES) { - LOG_PRINT_L1("Service Node: " << pubkey << ", failed timestamp obligation check"); + oxen::log::info(logcat, "Service Node: {}, failed timestamp obligation check", pubkey); result.timestamp_participation = false; } if (timesync_status.failures() > TIMESYNC_MAX_UNSYNCED_VOTES) { - LOG_PRINT_L1("Service Node: " << pubkey << ", failed timesync obligation check"); + oxen::log::info(logcat, "Service Node: {}, failed timesync obligation check", pubkey); result.timesync_status = false; } } @@ -186,8 +182,8 @@ namespace service_nodes { if (!by_pop_blocks) { - LOG_ERROR("The blockchain was detached to height: " << height << ", but quorum cop has already processed votes for obligations up to " << m_obligations_height); - LOG_ERROR("This implies a reorg occured that was over " << REORG_SAFETY_BUFFER_BLOCKS << ". This should rarely happen! Please report this to the devs."); + oxen::log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for obligations up to {}", height, m_obligations_height); + oxen::log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); } m_obligations_height = height; } @@ -196,8 +192,8 @@ namespace service_nodes { if (!by_pop_blocks) { - LOG_ERROR("The blockchain was detached to height: " << height << ", but quorum cop has already processed votes for checkpointing up to " << m_last_checkpointed_height); - LOG_ERROR("This implies a reorg occured that was over " << REORG_SAFETY_BUFFER_BLOCKS << ". This should rarely happen! Please report this to the devs."); + oxen::log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for checkpointing up to {}", height, m_last_checkpointed_height); + oxen::log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); } m_last_checkpointed_height = height - (height % CHECKPOINT_INTERVAL); } @@ -261,7 +257,7 @@ namespace service_nodes default: { assert("Unhandled quorum type " == 0); - LOG_ERROR("Unhandled quorum type with value: " << (int)type); + oxen::log::error(logcat, "Unhandled quorum type with value: {}", (int)type); } break; case quorum_type::obligations: @@ -313,7 +309,7 @@ namespace service_nodes if (!quorum) { // TODO(oxen): Fatal error - LOG_ERROR("Obligations quorum for height: " << m_obligations_height << " was not cached in daemon!"); + oxen::log::error(logcat, "Obligations quorum for height: {} was not cached in daemon!", m_obligations_height); continue; } @@ -352,12 +348,12 @@ namespace service_nodes if (passed) { if (info.is_decommissioned()) { vote_for_state = new_state::recommission; - LOG_PRINT_L2("Decommissioned service node " << quorum->workers[node_index] << " is now passing required checks; voting to recommission"); + oxen::log::debug(logcat, "Decommissioned service node {} is now passing required checks; voting to recommission", quorum->workers[node_index]); } else if (!test_results.single_ip) { // Don't worry about this if the SN is getting recommissioned (above) -- it'll // already reenter at the bottom. vote_for_state = new_state::ip_change_penalty; - LOG_PRINT_L2("Service node " << quorum->workers[node_index] << " was observed with multiple IPs recently; voting to reset reward position"); + oxen::log::debug(logcat, "Service node {} was observed with multiple IPs recently; voting to reset reward position", quorum->workers[node_index]); } else { good++; continue; @@ -376,46 +372,35 @@ namespace service_nodes if (info.is_decommissioned()) { if (credit >= 0) { - LOG_PRINT_L2("Decommissioned service node " - << quorum->workers[node_index] - << " is still not passing required checks, but has remaining credit (" << credit - << " blocks); abstaining (to leave decommissioned)"); + oxen::log::debug(logcat, "Decommissioned service node {} is still not passing required checks, but has remaining credit ({} blocks); abstaining (to leave decommissioned)", quorum->workers[node_index], credit); continue; } - LOG_PRINT_L2("Decommissioned service node " << quorum->workers[node_index] << " has no remaining credit; voting to deregister"); + oxen::log::debug(logcat, "Decommissioned service node {} has no remaining credit; voting to deregister", quorum->workers[node_index]); vote_for_state = new_state::deregister; // Credit ran out! } else { if (credit >= DECOMMISSION_MINIMUM) { vote_for_state = new_state::decommission; - LOG_PRINT_L2("Service node " - << quorum->workers[node_index] - << " has stopped passing required checks, but has sufficient earned credit (" << credit << " blocks) to avoid deregistration; voting to decommission"); + oxen::log::debug(logcat, "Service node {} has stopped passing required checks, but has sufficient earned credit ({} blocks) to avoid deregistration; voting to decommission", quorum->workers[node_index], credit); } else { vote_for_state = new_state::deregister; - LOG_PRINT_L2("Service node " - << quorum->workers[node_index] - << " has stopped passing required checks, but does not have sufficient earned credit (" - << credit << " blocks, " << DECOMMISSION_MINIMUM - << " required) to decommission; voting to deregister"); + oxen::log::debug(logcat, "Service node {} has stopped passing required checks, but does not ahve sufficient earned credit ({} blocks, {} required) to decommission; voting to deregister", quorum->workers[node_index], credit, DECOMMISSION_MINIMUM); } } } if (vote_for_state == new_state::deregister && height - *cryptonote::get_hard_fork_heights(m_core.get_nettype(), hf_version).first < netconf.HARDFORK_DEREGISTRATION_GRACE_PERIOD) { - LOG_PRINT_L2("Decommissioned service node " - << quorum->workers[node_index] - << " is still not passing required checks, and has no remaining credits left. However it is within the grace period of a hardfork so has not been deregistered."); + oxen::log::debug(logcat, "Decommissioned service node {} is still not passing required checks, and has no remaining credits left. However it is within the grace period of a hardfork so has not been deregistered.", quorum->workers[node_index]); continue; } quorum_vote_t vote = service_nodes::make_state_change_vote(m_obligations_height, static_cast(index_in_group), node_index, vote_for_state, reason, my_keys); cryptonote::vote_verification_context vvc; if (!handle_vote(vote, vvc)) - LOG_ERROR("Failed to add state change vote; reason: " << print_vote_verification_context(vvc, &vote)); + oxen::log::error(logcat, "Failed to add state change vote; reason: {}", print_vote_verification_context(vvc, &vote)); } if (good > 0) - LOG_PRINT_L2(good << " of " << total << " service nodes are active and passing checks; no state change votes required"); + oxen::log::debug(logcat, "{} of {} service nodes are active and passing checks; no state change votes required", good, total); } else if (!tested_myself_once_per_block && (find_index_in_quorum_group(quorum->workers, my_keys.pub) >= 0)) { @@ -439,16 +424,15 @@ namespace service_nodes if (print_failings) { - LOG_PRINT_L0( - (info.is_decommissioned() + oxen::log::warning(logcat, "{}{}", (info.is_decommissioned() ? "Service Node (yours) is currently decommissioned and being tested in quorum: " - : "Service Node (yours) is active but is not passing tests for quorum: ") - << m_obligations_height); + : "Service Node (yours) is active but is not passing tests for quorum: "), + m_obligations_height); if (auto why = my_test_results.why()) - LOG_PRINT_L0(tools::join("\n", *why)); + oxen::log::warning(logcat, tools::join("\n", *why)); else - LOG_PRINT_L0("Service Node is passing all local tests"); - LOG_PRINT_L0("(Note that some tests, such as storage server and lokinet reachability, can only assessed by remote service nodes)"); + oxen::log::warning(logcat, "Service Node is passing all local tests"); + oxen::log::warning(logcat, "(Note that some tests, such as storage server and lokinet reachability, can only assessed by remote service nodes)"); } } } @@ -482,7 +466,7 @@ namespace service_nodes if (!quorum) { // TODO(oxen): Fatal error - LOG_ERROR("Checkpoint quorum for height: " << m_last_checkpointed_height << " was not cached in daemon!"); + oxen::log::error(logcat, "Checkpoint quorum for height: {} was not cached in daemon!", m_last_checkpointed_height); continue; } @@ -496,7 +480,7 @@ namespace service_nodes quorum_vote_t vote = make_checkpointing_vote(checkpointed_height_hf_version, block_hash, m_last_checkpointed_height, static_cast(index_in_group), my_keys); cryptonote::vote_verification_context vvc = {}; if (!handle_vote(vote, vvc)) - LOG_ERROR("Failed to add checkpoint vote; reason: " << print_vote_verification_context(vvc, &vote)); + oxen::log::error(logcat, "Failed to add checkpoint vote; reason: {}", print_vote_verification_context(vvc, &vote)); } } } @@ -521,7 +505,7 @@ namespace service_nodes { if (votes.size() < STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE) { - LOG_PRINT_L2("Don't have enough votes yet to submit a state change transaction: have " << votes.size() << " of " << STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE << " required"); + oxen::log::debug(logcat, "Don't have enough votes yet to submit a state change transaction: have {} of {} required", votes.size(), STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE); return true; } @@ -567,16 +551,12 @@ namespace service_nodes bool result = core.handle_incoming_tx(cryptonote::tx_to_blob(state_change_tx), tvc, cryptonote::tx_pool_options::new_tx()); if (!result || tvc.m_verifivation_failed) { - LOG_PRINT_L1("A full state change tx for height: " << vote.block_height << - " and service node: " << vote.state_change.worker_index << - " could not be verified and was not added to the memory pool, reason: " << - print_tx_verification_context(tvc, &state_change_tx)); + oxen::log::info(logcat, "A full state change tx for height: {} and service node: {} could not be verified and was not added to the memory pool, reason: {}", vote.block_height, vote.state_change.worker_index, print_tx_verification_context(tvc, &state_change_tx)); return false; } } else - LOG_PRINT_L1("Failed to add state change to tx extra for height: " - << vote.block_height << " and service node: " << vote.state_change.worker_index); + oxen::log::info(logcat, "Failed to add state change to tx extra for height: {} and service node: {}", vote.block_height, vote.state_change.worker_index); return true; } @@ -585,7 +565,7 @@ namespace service_nodes { if (votes.size() < CHECKPOINT_MIN_VOTES) { - LOG_PRINT_L2("Don't have enough votes yet to submit a checkpoint: have " << votes.size() << " of " << CHECKPOINT_MIN_VOTES << " required"); + oxen::log::debug(logcat, "Don't have enough votes yet to submit a checkpoint: have {} of {} required", votes.size(), CHECKPOINT_MIN_VOTES); return true; } @@ -677,7 +657,7 @@ namespace service_nodes { default: { - LOG_PRINT_L1("Unhandled vote type with value: " << (int)vote.type); + oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return false; }; diff --git a/src/cryptonote_core/service_node_quorum_cop.h b/src/cryptonote_core/service_node_quorum_cop.h index 9ab279ec9..e24f97af6 100644 --- a/src/cryptonote_core/service_node_quorum_cop.h +++ b/src/cryptonote_core/service_node_quorum_cop.h @@ -34,6 +34,7 @@ #include "cryptonote_core/service_node_voting.h" #include #include +#include namespace cryptonote { @@ -50,6 +51,16 @@ namespace service_nodes { std::vector validators; // Array of public keys identifying service nodes who validate and sign. std::vector workers; // Array of public keys of tested service nodes (if applicable). + // + inline std::string to_string() const + { + std::stringstream result; + for (size_t i = 0; i < validators.size(); i++) + result << "V[" << i << "] " << validators[i] << "\n"; + for (size_t i = 0; i < workers.size(); i++) + result << "W[" << std::to_string(i) + "] " << workers[i] << "\n"; + return result.str(); + }; BEGIN_SERIALIZE() FIELD(validators) @@ -59,11 +70,10 @@ namespace service_nodes inline std::ostream &operator<<(std::ostream &os, quorum const &q) { - for (size_t i = 0; i < q.validators.size(); i++) os << "V[" << i << "] " << q.validators[i] << "\n"; - for (size_t i = 0; i < q.workers.size(); i++) os << "W[" << i << "] " << q.workers[i] << "\n"; - return os; + return os << q.to_string(); } + struct quorum_manager { std::shared_ptr obligations; @@ -79,7 +89,7 @@ namespace service_nodes else if (type == quorum_type::checkpointing) return checkpointing; else if (type == quorum_type::blink) return blink; else if (type == quorum_type::pulse) return pulse; - MERROR("Developer error: Unhandled quorum enum with value: " << (size_t)type); + oxen::log::error(oxen::log::Cat("quorum_cop"), "Developer error: Unhandled quorum enum with value: {}", (size_t)type); assert(!"Developer error: Unhandled quorum enum with value: "); return nullptr; } @@ -155,3 +165,11 @@ namespace service_nodes */ uint64_t quorum_checksum(const std::vector &pubkeys, size_t offset = 0); } + +template <> +struct fmt::formatter : fmt::formatter { + auto format(service_nodes::quorum quorum, format_context& ctx) { + return formatter::format( + fmt::format("{}", quorum.to_string()), ctx); + } +}; diff --git a/src/cryptonote_core/service_node_rules.cpp b/src/cryptonote_core/service_node_rules.cpp index 9b0fdd80d..d2a39e599 100644 --- a/src/cryptonote_core/service_node_rules.cpp +++ b/src/cryptonote_core/service_node_rules.cpp @@ -16,6 +16,8 @@ using cryptonote::hf; namespace service_nodes { +static auto logcat = oxen::log::Cat("service_nodes"); + uint64_t get_staking_requirement(cryptonote::network_type nettype, hf hardfork) { assert(hardfork >= hf::hf16_pulse); @@ -110,11 +112,11 @@ bool check_service_node_portions(hf hf_version, const std::vector hf::hf19_reward_batching) { - LOG_PRINT_L1("Registration tx rejected: portions-based registrations not permitted after HF19"); + oxen::log::info(logcat, "Registration tx rejected: portions-based registrations not permitted after HF19"); return false; } if (portions.size() > oxen::MAX_CONTRIBUTORS_V1) { - LOG_PRINT_L1("Registration tx rejected: too many contributors (" << portions.size() << " > " << oxen::MAX_CONTRIBUTORS_V1 << ")"); + oxen::log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", portions.size(), oxen::MAX_CONTRIBUTORS_V1); return false; } @@ -125,11 +127,11 @@ bool check_service_node_portions(hf hf_version, const std::vector remaining) { - LOG_PRINT_L1("Registration tx rejected: portion " << i << " exceeds available portions"); + oxen::log::info(logcat, "Registration tx rejected: portion {} exceeds available portions", i); return false; } @@ -143,11 +145,11 @@ bool check_service_node_portions(hf hf_version, const std::vector>& stakes) { if (hf_version < hf::hf19_reward_batching) { - LOG_PRINT_L1("Registration tx rejected: amount-based registrations not accepted before HF19"); + oxen::log::info(logcat, "Registration tx rejected: amount-based registrations not accepted before HF19"); return false; // OXEN-based registrations not accepted before HF19 } if (stakes.size() > oxen::MAX_CONTRIBUTORS_HF19) { - LOG_PRINT_L1("Registration tx rejected: too many contributors (" << stakes.size() << " > " << oxen::MAX_CONTRIBUTORS_HF19 << ")"); + oxen::log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", stakes.size(), oxen::MAX_CONTRIBUTORS_HF19); return false; } @@ -161,11 +163,11 @@ bool check_service_node_stakes(hf hf_version, cryptonote::network_type nettype, const uint64_t min_stake = i == 0 ? operator_requirement : get_min_node_contribution(hf_version, staking_requirement, reserved, i); if (stakes[i].second < min_stake) { - LOG_PRINT_L1("Registration tx rejected: stake " << i << " too small (" << stakes[i].second << " < " << min_stake << ")"); + oxen::log::info(logcat, "Registration tx rejected: stake {} too small ({} < {})", i, stakes[i].second, min_stake); return false; } if (stakes[i].second > remaining) { - LOG_PRINT_L1("Registration tx rejected: stake " << i << " (" << stakes[i].second << ") exceeds available remaining stake (" << remaining << ")"); + oxen::log::info(logcat, "Registration tx rejected: stake {} ({}) exceeds available remaining stake ({})", i, stakes[i].second, remaining); return false; } diff --git a/src/cryptonote_core/service_node_swarm.cpp b/src/cryptonote_core/service_node_swarm.cpp index df767d1b9..4e583d448 100644 --- a/src/cryptonote_core/service_node_swarm.cpp +++ b/src/cryptonote_core/service_node_swarm.cpp @@ -1,9 +1,6 @@ #include "service_node_swarm.h" #include "common/random.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "service_nodes" - #ifdef UNIT_TEST #define prod_static #else @@ -12,6 +9,8 @@ namespace service_nodes { + static auto logcat = oxen::log::Cat("service_nodes"); + uint64_t get_new_swarm_id(const swarm_snode_map_t &swarm_to_snodes) { if (swarm_to_snodes.empty()) return 0; @@ -70,7 +69,7 @@ namespace service_nodes const ssize_t margin = pair.second.size() - EXCESS_BASE; return result + std::max(margin, ssize_t(0)); }); - LOG_PRINT_L2("Calculated excess: " << excess); + oxen::log::debug(logcat, "Calculated excess: {}", excess); return excess; }; @@ -81,7 +80,7 @@ namespace service_nodes prod_static size_t calc_threshold(const swarm_snode_map_t &swarm_to_snodes) { const size_t threshold = NEW_SWARM_SIZE + (swarm_to_snodes.size() * IDEAL_SWARM_MARGIN); - LOG_PRINT_L2("Calculated threshold: " << threshold); + oxen::log::debug(logcat, "Calculated threshold: {}", threshold); return threshold; }; @@ -137,7 +136,7 @@ namespace service_nodes while (calc_excess(swarm_to_snodes) >= calc_threshold(swarm_to_snodes)) { - LOG_PRINT_L2("New swarm creation"); + oxen::log::debug(logcat, "New swarm creation"); std::vector new_swarm_snodes; new_swarm_snodes.reserve(NEW_SWARM_SIZE); while (new_swarm_snodes.size() < NEW_SWARM_SIZE) @@ -146,7 +145,7 @@ namespace service_nodes get_excess_pool(EXCESS_BASE, swarm_to_snodes, pool_snodes, excess); if (pool_snodes.size() == 0) { - MERROR("Error while getting excess pool for new swarm creation"); + oxen::log::error(logcat, "Error while getting excess pool for new swarm creation"); return; } const auto& random_excess_snode = pick_from_excess_pool(pool_snodes, mt); @@ -156,12 +155,12 @@ namespace service_nodes const auto new_swarm_id = get_new_swarm_id(swarm_to_snodes); if (auto [it, ins] = swarm_to_snodes.emplace(new_swarm_id, std::move(new_swarm_snodes)); !ins) { - MFATAL("New swarm ID gave a swarm id (" << new_swarm_id << ") that already exists -- this is a bug!"); + oxen::log::error(logcat, "New swarm ID gave a swarm id ({}) that already exists -- this is a bug!", new_swarm_id); // If we actually abort() here then hitting this would potentially kill the whole network // if we hit this bug, so just warn very loudly and move on; if it happens we'll have to // track down the bug and fix it separately. } else { - LOG_PRINT_L2("Created new swarm from excess: " << new_swarm_id); + oxen::log::debug(logcat, "Created new swarm from excess: {}", new_swarm_id); } } } @@ -228,22 +227,22 @@ namespace service_nodes swarm_to_snodes.erase(it); } - LOG_PRINT_L3("calc_swarm_changes. swarms: " << swarm_to_snodes.size() << ", regs: " << unassigned_snodes.size()); + oxen::log::trace(logcat, "calc_swarm_changes. swarms: {}, regs: {}", swarm_to_snodes.size(), unassigned_snodes.size()); /// 0. Ensure there is always 1 swarm if (swarm_to_snodes.size() == 0) { const auto new_swarm_id = get_new_swarm_id({}); swarm_to_snodes.insert({new_swarm_id, {}}); - LOG_PRINT_L2("Created initial swarm " << new_swarm_id); + oxen::log::debug(logcat, "Created initial swarm {}", new_swarm_id); } /// 1. Assign new registered snodes assign_snodes(unassigned_snodes, swarm_to_snodes, mersenne_twister, FILL_SWARM_LOWER_PERCENTILE); - LOG_PRINT_L2("After assignment:"); + oxen::log::debug(logcat, "After assignment:"); for (const auto &entry : swarm_to_snodes) { - LOG_PRINT_L2(entry.first << ": " << entry.second.size()); + oxen::log::debug(logcat, "{}: {}", entry.first, entry.second.size()); } /// 2. *Robin Hood Round* steal snodes from wealthy swarms and give them to the poor @@ -276,7 +275,7 @@ namespace service_nodes remove_excess_snode_from_swarm(excess_snode, swarm_to_snodes); /// Add public key to poor swarm poor_swarm_snodes.push_back(excess_snode.public_key); - LOG_PRINT_L2("Stolen 1 snode from " << excess_snode.public_key << " and donated to " << swarm.swarm_id); + oxen::log::debug(logcat, "Stolen 1 snode from {} and donated to {}", excess_snode.public_key, swarm.swarm_id); } while (poor_swarm_snodes.size() < MIN_SWARM_SIZE); /// If there is not enough excess for the current swarm, @@ -302,7 +301,7 @@ namespace service_nodes if (it == swarm_to_snodes.end()) break; - MWARNING("swarm " << it->first << " is DECOMMISSIONED"); + oxen::log::warning(logcat, "swarm {} is DECOMMISSIONED", it->first); /// Good ol' switcheroo std::vector decommissioned_snodes; std::swap(decommissioned_snodes, it->second); @@ -314,10 +313,10 @@ namespace service_nodes } /// print - LOG_PRINT_L2("Swarm outputs:"); + oxen::log::debug(logcat, "Swarm outputs:"); for (const auto &entry : swarm_to_snodes) { - LOG_PRINT_L2(entry.first << ": " << entry.second.size()); + oxen::log::debug(logcat, "{}: {}", entry.first, entry.second.size()); } } } diff --git a/src/cryptonote_core/service_node_voting.cpp b/src/cryptonote_core/service_node_voting.cpp index f5537ebdb..b6a691a04 100644 --- a/src/cryptonote_core/service_node_voting.cpp +++ b/src/cryptonote_core/service_node_voting.cpp @@ -43,13 +43,12 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "service_nodes" - using cryptonote::hf; namespace service_nodes { + static auto logcat = oxen::log::Cat("service_nodes"); + static crypto::hash make_state_change_vote_hash(uint64_t block_height, uint32_t service_node_index, new_state state) { uint16_t state_int = static_cast(state); @@ -72,7 +71,7 @@ namespace service_nodes { default: { - LOG_PRINT_L1("Unhandled vote type with value: " << (int)vote.type); + oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return result; }; @@ -108,7 +107,7 @@ namespace service_nodes if (worker_index >= quorum.workers.size()) { if (vvc) vvc->m_worker_index_out_of_bounds = true; - LOG_PRINT_L1("Quorum worker index in was out of bounds: " << worker_index << ", expected to be in range of: [0, " << quorum.workers.size() << ")"); + oxen::log::info(logcat, "Quorum worker index in was out of bounds: {}, expected to be in range of: [0, {}", worker_index, quorum.workers.size()); return false; } return true; @@ -119,7 +118,7 @@ namespace service_nodes if (validator_index >= quorum.validators.size()) { if (vvc) vvc->m_validator_index_out_of_bounds = true; - LOG_PRINT_L1("Validator's index was out of bounds: " << validator_index << ", expected to be in range of: [0, " << quorum.validators.size() << ")"); + oxen::log::info(logcat, "Validator's index was out of bounds: {}, expected to be in range of: [0, {}", validator_index, quorum.validators.size()); return false; } return true; @@ -139,26 +138,26 @@ namespace service_nodes auto &vvc = tvc.m_vote_ctx; if (state_change.state != new_state::deregister && hf_version < hf::hf12_checkpointing) { - LOG_PRINT_L1("Non-deregister state changes are invalid before v12"); + oxen::log::info(logcat, "Non-deregister state changes are invalid before v12"); return bad_tx(tvc); } if (state_change.state >= new_state::_count) { - LOG_PRINT_L1("Unknown state change to new state: " << static_cast(state_change.state)); + oxen::log::info(logcat, "Unknown state change to new state: {}", static_cast(state_change.state)); return bad_tx(tvc); } if (state_change.votes.size() < service_nodes::STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE) { - LOG_PRINT_L1("Not enough votes"); + oxen::log::info(logcat, "Not enough votes"); vvc.m_not_enough_votes = true; return bad_tx(tvc); } if (state_change.votes.size() > service_nodes::STATE_CHANGE_QUORUM_SIZE) { - LOG_PRINT_L1("Too many votes"); + oxen::log::info(logcat, "Too many votes"); return bad_tx(tvc); } @@ -169,10 +168,7 @@ namespace service_nodes { if (state_change.block_height >= latest_height) { - LOG_PRINT_L1("Received state change tx for height: " << state_change.block_height - << " and service node: " << state_change.service_node_index - << ", is newer than current height: " << latest_height - << " blocks and has been rejected."); + oxen::log::info(logcat, "Received state change tx for height: {} and service node: {}, is newer than current height: {} blocks and has been rejected.", state_change.block_height, state_change.service_node_index, latest_height); vvc.m_invalid_block_height = true; if (state_change.block_height >= latest_height + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER) tvc.m_verifivation_failed = true; @@ -181,11 +177,7 @@ namespace service_nodes if (latest_height >= state_change.block_height + service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS) { - LOG_PRINT_L1("Received state change tx for height: " - << state_change.block_height << " and service node: " << state_change.service_node_index - << ", is older than: " << service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS - << " (current height: " << latest_height << ") " - << "blocks and has been rejected."); + oxen::log::info(logcat, "Received state change tx for height: {} and service node: {}, is older than: {} (current height: {}) blocks and has been rejected.", state_change.block_height, state_change.service_node_index, service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS, latest_height); vvc.m_invalid_block_height = true; if (latest_height >= state_change.block_height + (service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER)) tvc.m_verifivation_failed = true; @@ -203,8 +195,7 @@ namespace service_nodes if (validator_index_tracker >= static_cast(vote.validator_index)) { vvc.m_votes_not_sorted = true; - LOG_PRINT_L1("Vote validator index is not stored in ascending order, prev validator index: " - << validator_index_tracker << ", curr index: " << vote.validator_index); + oxen::log::info(logcat, "Vote validator index is not stored in ascending order, prev validator index: {}, curr index: {}", validator_index_tracker, vote.validator_index); return bad_tx(tvc); } validator_index_tracker = vote.validator_index; @@ -216,14 +207,14 @@ namespace service_nodes if (++validator_set[vote.validator_index] > 1) { vvc.m_duplicate_voters = true; - LOG_PRINT_L1("Voter quorum index is duplicated: " << vote.validator_index); + oxen::log::info(logcat, "Voter quorum index is duplicated: {}", vote.validator_index); return bad_tx(tvc); } crypto::public_key const &key = quorum.validators[vote.validator_index]; if (!crypto::check_signature(hash, key, vote.signature)) { - LOG_PRINT_L1("Invalid signature for voter " << vote.validator_index << "/" << key); + oxen::log::info(logcat, "Invalid signature for voter {}/{}", vote.validator_index, key); vvc.m_signature_not_valid = true; return bad_tx(tvc); } @@ -250,13 +241,13 @@ namespace service_nodes { if (signatures.size() < service_nodes::CHECKPOINT_MIN_VOTES) { - MGINFO("Checkpoint has insufficient signatures to be considered at height: " << height); + oxen::log::info(logcat, "Checkpoint has insufficient signatures to be considered at height: {}", height); return false; } if (signatures.size() > service_nodes::CHECKPOINT_QUORUM_SIZE) { - MGINFO("Checkpoint has too many signatures to be considered at height: " << height); + oxen::log::info(logcat, "Checkpoint has too many signatures to be considered at height: {}", height); return false; } @@ -268,13 +259,13 @@ namespace service_nodes { if (signatures.size() != PULSE_BLOCK_REQUIRED_SIGNATURES) { - MGINFO("Pulse block has " << signatures.size() << " signatures but requires " << PULSE_BLOCK_REQUIRED_SIGNATURES); + oxen::log::info(logcat, "Pulse block has {} signatures but requires {}", signatures.size(), PULSE_BLOCK_REQUIRED_SIGNATURES); return false; } if (!block) { - MGINFO("Internal Error: Wrong type passed in any object, expected block."); + oxen::log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); return false; } @@ -282,7 +273,7 @@ namespace service_nodes { auto mask = std::bitset(pulse_validator_bit_mask()); auto other = std::bitset(block->pulse.validator_bitset); - MGINFO("Pulse block specifies validator participation bits out of bounds. Expected the bit mask: " << mask << ", block: " << other); + oxen::log::info(logcat, "Pulse block specifies validator participation bits out of bounds. Expected the bit mask: {}, block: {}", mask.to_string(), other.to_string()); return false; } } @@ -299,7 +290,7 @@ namespace service_nodes if (curr >= next) { - MGINFO("Voters in signatures are not given in ascending order, failed verification at height: " << height); + oxen::log::info(logcat, "Voters in signatures are not given in ascending order, failed verification at height: {}", height); return false; } } @@ -311,14 +302,14 @@ namespace service_nodes { if (!block) { - MGINFO("Internal Error: Wrong type passed in any object, expected block."); + oxen::log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); return false; } uint16_t bit = 1 << quorum_signature.voter_index; if ((block->pulse.validator_bitset & bit) == 0) { - MGINFO("Received pulse signature from validator " << static_cast(quorum_signature.voter_index) << " that is not participating in round " << static_cast(block->pulse.round)); + oxen::log::info(logcat, "Received pulse signature from validator {} that is not participating in round {}", static_cast(quorum_signature.voter_index), static_cast(block->pulse.round)); return false; } } @@ -326,19 +317,19 @@ namespace service_nodes crypto::public_key const &key = quorum.validators[quorum_signature.voter_index]; if (quorum_signature.voter_index >= unique_vote_set.size()) { - MGINFO("Internal Error: Voter Index indexes out of bounds of the vote set, index: " << quorum_signature.voter_index << "vote set size: " << unique_vote_set.size()); + oxen::log::info(logcat, "Internal Error: Voter Index indexes out of bounds of the vote set, index: {}vote set size: {}", quorum_signature.voter_index, unique_vote_set.size()); return false; } if (unique_vote_set[quorum_signature.voter_index]++) { - MGINFO("Voter: " << tools::type_to_hex(key) << ", quorum index is duplicated: " << quorum_signature.voter_index << ", failed verification at height: " << height); + oxen::log::info(logcat, "Voter: {}, quorum index is duplicated: {}, failed verification at height: {}", tools::type_to_hex(key), quorum_signature.voter_index, height); return false; } if (!crypto::check_signature(hash, key, quorum_signature.signature)) { - MGINFO("Incorrect signature for vote, failed verification at height: " << height << " for voter: " << key << "\n" << quorum); + oxen::log::info(logcat, "Incorrect signature for vote, failed verification at height: {} for voter: {}\n{}", height, key, quorum); return false; } } @@ -358,13 +349,13 @@ namespace service_nodes { if ((checkpoint.height % service_nodes::CHECKPOINT_INTERVAL) != 0) { - LOG_PRINT_L1("Checkpoint given but not expecting a checkpoint at height: " << checkpoint.height); + oxen::log::info(logcat, "Checkpoint given but not expecting a checkpoint at height: {}", checkpoint.height); return false; } if (!verify_quorum_signatures(quorum, quorum_type::checkpointing, hf_version, checkpoint.height, checkpoint.block_hash, checkpoint.signatures)) { - LOG_PRINT_L1("Checkpoint failed signature validation at block " << checkpoint.height << " " << checkpoint.block_hash); + oxen::log::info(logcat, "Checkpoint failed signature validation at block {} {}", checkpoint.height, checkpoint.block_hash); return false; } } @@ -372,7 +363,7 @@ namespace service_nodes { if (checkpoint.signatures.size() != 0) { - LOG_PRINT_L1("Non service-node checkpoints should have no signatures, checkpoint failed at height: " << checkpoint.height); + oxen::log::info(logcat, "Non service-node checkpoints should have no signatures, checkpoint failed at height: {}", checkpoint.height); return false; } } @@ -422,15 +413,13 @@ namespace service_nodes if (latest_height > vote.block_height + VOTE_LIFETIME) { height_in_buffer = latest_height <= vote.block_height + (VOTE_LIFETIME + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER); - LOG_PRINT_L1("Received vote for height: " << vote.block_height << ", is older than: " << VOTE_LIFETIME - << " blocks and has been rejected."); + oxen::log::info(logcat, "Received vote for height: {}, is older than: {} blocks and has been rejected.", vote.block_height, VOTE_LIFETIME); vvc.m_invalid_block_height = true; } else if (vote.block_height > latest_height) { height_in_buffer = vote.block_height <= latest_height + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER; - LOG_PRINT_L1("Received vote for height: " << vote.block_height << ", is newer than: " << latest_height - << " (latest block height) and has been rejected."); + oxen::log::info(logcat, "Received vote for height: {}, is newer than: {} (latest block height) and has been rejected.", vote.block_height, latest_height); vvc.m_invalid_block_height = true; } @@ -476,7 +465,7 @@ namespace service_nodes { default: { - LOG_PRINT_L1("Unhandled vote type with value: " << (int)vote.type); + oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return false; }; @@ -485,7 +474,7 @@ namespace service_nodes { if (vote.group != quorum_group::validator) { - LOG_PRINT_L1("Vote received specifies incorrect voting group, expected vote from validator"); + oxen::log::info(logcat, "Vote received specifies incorrect voting group, expected vote from validator"); vvc.m_incorrect_voting_group = true; result = false; } @@ -502,7 +491,7 @@ namespace service_nodes { if (vote.group != quorum_group::validator) { - LOG_PRINT_L1("Vote received specifies incorrect voting group"); + oxen::log::info(logcat, "Vote received specifies incorrect voting group"); vvc.m_incorrect_voting_group = true; result = false; } @@ -520,9 +509,7 @@ namespace service_nodes result = crypto::check_signature(hash, key, vote.signature); if (result) - MDEBUG("Signature accepted for " << vote.type << " voter " << vote.index_in_group << "/" << key - << (vote.type == quorum_type::obligations ? " voting for worker " + std::to_string(vote.state_change.worker_index) : "") - << " at height " << vote.block_height); + oxen::log::debug(logcat, "Signature accepted for {} voter {}/{} voting for worker {} at height {}", vote.type, vote.index_in_group, key, (vote.type == quorum_type::obligations ? " voting for worker " + std::to_string(vote.state_change.worker_index) : ""), vote.block_height); else vvc.m_signature_not_valid = true; @@ -545,7 +532,7 @@ namespace service_nodes switch(find_vote.type) { default: - LOG_PRINT_L1("Unhandled find_vote type with value: " << (int)find_vote.type); + oxen::log::info(logcat, "Unhandled find_vote type with value: {}", (int)find_vote.type); assert("Unhandled find_vote type" == 0); return nullptr; @@ -656,7 +643,7 @@ namespace service_nodes cryptonote::tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, version)) { - LOG_ERROR("Could not get state change from tx, possibly corrupt tx"); + oxen::log::error(logcat, "Could not get state change from tx, possibly corrupt tx"); continue; } diff --git a/src/cryptonote_core/service_node_voting.h b/src/cryptonote_core/service_node_voting.h index 66ca6b9e2..6092489df 100644 --- a/src/cryptonote_core/service_node_voting.h +++ b/src/cryptonote_core/service_node_voting.h @@ -63,15 +63,20 @@ namespace service_nodes _count }; - inline std::ostream &operator<<(std::ostream &os, quorum_type v) { - switch(v) + inline std::string to_string(const quorum_type& q) + { + switch(q) { - case quorum_type::obligations: return os << "obligation"; - case quorum_type::checkpointing: return os << "checkpointing"; - case quorum_type::blink: return os << "blink"; - case quorum_type::pulse: return os << "pulse"; - default: assert(false); return os << "xx_unhandled_type"; + case quorum_type::obligations: return "obligation"; + case quorum_type::checkpointing: return "checkpointing"; + case quorum_type::blink: return "blink"; + case quorum_type::pulse: return "pulse"; + default: assert(false); return "xx_unhandled_type"; } + }; + + inline std::ostream &operator<<(std::ostream &os, quorum_type q) { + return os << to_string(q); } enum struct quorum_group : uint8_t { invalid, validator, worker, _count }; @@ -171,4 +176,12 @@ namespace service_nodes mutable std::recursive_mutex m_lock; }; }; // namespace service_nodes + // +template <> +struct fmt::formatter : fmt::formatter { + auto format(service_nodes::quorum_type quorum, format_context& ctx) { + return formatter::format( + fmt::format("{}", to_string(quorum)), ctx); + } +}; diff --git a/src/cryptonote_core/tx_blink.cpp b/src/cryptonote_core/tx_blink.cpp index edc77446d..b9e0525de 100644 --- a/src/cryptonote_core/tx_blink.cpp +++ b/src/cryptonote_core/tx_blink.cpp @@ -50,7 +50,7 @@ crypto::public_key blink_tx::get_sn_pubkey(subquorum q, int position, const serv if (!blink_quorum) { // TODO FIXME XXX - we don't want a failure here; if this happens we need to go back into state // history to retrieve the state info. (Or maybe this can't happen?) - MERROR("FIXME: could not get blink quorum for blink_tx"); + oxen::log::error(globallogcat, "FIXME: could not get blink quorum for blink_tx"); return crypto::null_pkey; } diff --git a/src/cryptonote_core/tx_pool.cpp b/src/cryptonote_core/tx_pool.cpp index 893834303..40de5928a 100644 --- a/src/cryptonote_core/tx_pool.cpp +++ b/src/cryptonote_core/tx_pool.cpp @@ -48,18 +48,17 @@ #include "common/median.h" #include "epee/int-util.h" #include "epee/warnings.h" -#include "common/perf_timer.h" #include "crypto/hash.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "txpool" - DISABLE_VS_WARNINGS(4244 4345 4503) //'boost::foreach_detail_::or_' : decorated name length exceeded, name was truncated using namespace crypto; namespace cryptonote { + + static auto logcat = oxen::log::Cat("txpool"); + namespace { //TODO: constants such as these should at least be in the header, @@ -104,7 +103,7 @@ namespace cryptonote tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, hard_fork_version)) { - MERROR("Could not get service node state change from tx: " << get_transaction_hash(tx) << ", possibly corrupt tx in your blockchain, rejecting malformed state change"); + oxen::log::error(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in your blockchain, rejecting malformed state change", get_transaction_hash(tx)); return false; } @@ -129,7 +128,7 @@ namespace cryptonote tx_extra_service_node_state_change pool_tx_state_change; if (!get_service_node_state_change_from_tx_extra(pool_tx.extra, pool_tx_state_change, hard_fork_version)) { - LOG_PRINT_L1("Could not get service node state change from tx: " << get_transaction_hash(pool_tx) << ", possibly corrupt tx in the pool"); + oxen::log::info(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(pool_tx)); continue; } @@ -161,7 +160,7 @@ namespace cryptonote tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - MERROR("Could not get key image unlock from tx: " << get_transaction_hash(tx) << ", tx to add is possibly invalid, rejecting"); + oxen::log::error(logcat, "Could not get key image unlock from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); return true; } @@ -175,13 +174,13 @@ namespace cryptonote tx_extra_tx_key_image_unlock pool_unlock; if (!cryptonote::get_field_from_tx_extra(pool_tx.extra, pool_unlock)) { - LOG_PRINT_L1("Could not get key image unlock from tx: " << get_transaction_hash(tx) << ", possibly corrupt tx in the pool"); + oxen::log::info(logcat, "Could not get key image unlock from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); return true; } if (unlock == pool_unlock) { - LOG_PRINT_L1("New TX: " << get_transaction_hash(tx) << ", has TX: " << get_transaction_hash(pool_tx) << " from the pool that is requesting to unlock the same key image already."); + oxen::log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting to unlock the same key image already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); return true; } } @@ -192,7 +191,7 @@ namespace cryptonote tx_extra_oxen_name_system data; if (!cryptonote::get_field_from_tx_extra(tx.extra, data)) { - MERROR("Could not get acquire name service from tx: " << get_transaction_hash(tx) << ", tx to add is possibly invalid, rejecting"); + oxen::log::error(logcat, "Could not get acquire name service from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); return true; } @@ -206,13 +205,13 @@ namespace cryptonote tx_extra_oxen_name_system pool_data; if (!cryptonote::get_field_from_tx_extra(pool_tx.extra, pool_data)) { - LOG_PRINT_L1("Could not get acquire name service from tx: " << get_transaction_hash(tx) << ", possibly corrupt tx in the pool"); + oxen::log::info(logcat, "Could not get acquire name service from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); return true; } if (data.type == pool_data.type && data.name_hash == pool_data.name_hash) { - LOG_PRINT_L1("New TX: " << get_transaction_hash(tx) << ", has TX: " << get_transaction_hash(pool_tx) << " from the pool that is requesting the same ONS entry already."); + oxen::log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting the same ONS entry already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); return true; } } @@ -222,7 +221,7 @@ namespace cryptonote if (tx.type != txtype::standard && tx.type != txtype::stake) { // NOTE(oxen): This is a developer error. If we come across this in production, be conservative and just reject - MERROR("Unrecognised transaction type: " << tx.type << " for tx: " << get_transaction_hash(tx)); + oxen::log::error(logcat, "Unrecognised transaction type: {} for tx: {}", tx.type, get_transaction_hash(tx)); return true; } } @@ -242,11 +241,10 @@ namespace cryptonote // this should already be called with that lock, but let's make it explicit for clarity std::unique_lock lock{m_transactions_lock}; - PERF_TIMER(add_tx); if (tx.version == txversion::v0) { // v0 never accepted - LOG_PRINT_L1("transaction version 0 is invalid"); + oxen::log::info(logcat, "transaction version 0 is invalid"); tvc.m_verifivation_failed = true; return false; } @@ -293,7 +291,7 @@ namespace cryptonote size_t tx_weight_limit = get_transaction_weight_limit(hf_version); if ((!opts.kept_by_block || hf_version >= feature::PER_BYTE_FEE) && tx_weight > tx_weight_limit) { - LOG_PRINT_L1("transaction is too heavy: " << tx_weight << " bytes, maximum weight: " << tx_weight_limit); + oxen::log::info(logcat, "transaction is too heavy: {} bytes, maximum weight: {}", tx_weight, tx_weight_limit); tvc.m_verifivation_failed = true; tvc.m_too_big = true; return false; @@ -317,7 +315,7 @@ namespace cryptonote if (tx_hash != id && m_blinks.count(tx_hash)) { // Warn on this because it almost certainly indicates something malicious - MWARNING("Not re-adding popped/incoming tx " << id << " to the mempool: it conflicts with blink tx " << tx_hash); + oxen::log::warning(logcat, "Not re-adding popped/incoming tx {} to the mempool: it conflicts with blink tx {}", id, tx_hash); double_spend = true; break; } @@ -325,17 +323,17 @@ namespace cryptonote } else if (opts.approved_blink) { - MDEBUG("Incoming blink tx is approved, but has " << conflict_txs.size() << " conflicting local tx(es); dropping conflicts"); + oxen::log::debug(logcat, "Incoming blink tx is approved, but has {} conflicting local tx(es); dropping conflicts", conflict_txs.size()); if (remove_blink_conflicts(id, conflict_txs, blink_rollback_height)) double_spend = false; else - MERROR("Blink error: incoming blink tx cannot be accepted as it conflicts with checkpointed txs"); + oxen::log::error(logcat, "Blink error: incoming blink tx cannot be accepted as it conflicts with checkpointed txs"); } if (double_spend) { mark_double_spend(tx); - LOG_PRINT_L1("Transaction with id= "<< id << " used already spent key images"); + oxen::log::info(logcat, "Transaction with id= {} used already spent key images", id); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; @@ -345,7 +343,7 @@ namespace cryptonote if (!opts.kept_by_block && have_duplicated_non_standard_tx(tx, hf_version)) { mark_double_spend(tx); - LOG_PRINT_L1("Transaction with id= "<< id << " already has a duplicate tx for height"); + oxen::log::info(logcat, "Transaction with id= {} already has a duplicate tx for height", id); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; @@ -353,7 +351,7 @@ namespace cryptonote if (!m_blockchain.check_tx_outputs(tx, tvc)) { - LOG_PRINT_L1("Transaction with id= "<< id << " has at least one invalid output"); + oxen::log::info(logcat, "Transaction with id= {} has at least one invalid output", id); tvc.m_verifivation_failed = true; tvc.m_invalid_output = true; return false; @@ -403,14 +401,14 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Error adding transaction to txpool: " << e.what()); + oxen::log::error(logcat, "Error adding transaction to txpool: {}", e.what()); return false; } tvc.m_verifivation_impossible = true; tvc.m_added_to_pool = true; }else { - LOG_PRINT_L1("tx used wrong inputs, rejected"); + oxen::log::info(logcat, "tx used wrong inputs, rejected"); tvc.m_verifivation_failed = true; tvc.m_invalid_input = true; return false; @@ -449,7 +447,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("internal error: error adding transaction to txpool: " << e.what()); + oxen::log::error(logcat, "internal error: error adding transaction to txpool: {}", e.what()); return false; } tvc.m_added_to_pool = true; @@ -463,7 +461,7 @@ namespace cryptonote ++m_cookie; - MINFO("Transaction added to pool: txid " << id << " weight: " << tx_weight << " fee/byte: " << (fee / (double)(tx_weight ? tx_weight : 1))); + oxen::log::info(logcat, "Transaction added to pool: txid {} weight: {} fee/byte: {}", id, tx_weight, (fee / (double)(tx_weight ? tx_weight : 1))); if (!opts.kept_by_block && !opts.do_not_relay) for (auto& notify : m_tx_notify) @@ -651,7 +649,7 @@ namespace cryptonote { if (m_blinks.count(tx_hash)) { - MERROR("Blink error: incoming blink tx " << id << " conflicts with another blink tx " << tx_hash); + oxen::log::error(logcat, "Blink error: incoming blink tx {} conflicts with another blink tx {}", id, tx_hash); return false; } } @@ -664,7 +662,7 @@ namespace cryptonote auto heights = m_blockchain.get_transactions_heights(conflict_txs); for (size_t i = 0; i < heights.size(); ++i) { - MDEBUG("Conflicting tx " << conflict_txs[i] << (heights[i] ? "mined at height " + std::to_string(heights[i]) : "in mempool")); + oxen::log::debug(logcat, "Conflicting tx {}{}", conflict_txs[i], (heights[i] ? "mined at height " + std::to_string(heights[i]) : "in mempool")); if (!heights[i]) { mempool_txs.push_back(conflict_txs[i]); @@ -684,10 +682,10 @@ namespace cryptonote LockedTXN txnlock(m_blockchain); for (auto &tx : mempool_txs) { - MWARNING("Removing conflicting tx " << tx << " from mempool for incoming blink tx " << id); + oxen::log::warning(logcat, "Removing conflicting tx {} from mempool for incoming blink tx {}", tx, id); if (!remove_tx(tx)) { - MERROR("Internal error: Unable to clear conflicting tx " << tx << " from mempool for incoming blink tx " << id); + oxen::log::error(logcat, "Internal error: Unable to clear conflicting tx {} from mempool for incoming blink tx {}", tx, id); return false; } } @@ -696,7 +694,7 @@ namespace cryptonote if (blink_rollback_height && rollback_height_needed < *blink_rollback_height) { - MINFO("Incoming blink tx requires a rollback to the " << rollback_height_needed << " to un-mine conflicting transactions"); + oxen::log::info(logcat, "Incoming blink tx requires a rollback to the {} to un-mine conflicting transactions", rollback_height_needed); *blink_rollback_height = rollback_height_needed; } @@ -721,7 +719,7 @@ namespace cryptonote const auto it = stc_it ? *stc_it : find_tx_in_sorted_container(txid); if (it == m_txs_by_fee_and_receive_time.end()) { - MERROR("Failed to find tx in txpool sorted list"); + oxen::log::error(logcat, "Failed to find tx in txpool sorted list"); return false; } @@ -729,7 +727,7 @@ namespace cryptonote cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(tx_blob, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); return false; } @@ -740,14 +738,14 @@ namespace cryptonote meta = &lookup_meta; else { - MERROR("Failed to find tx in txpool"); + oxen::log::error(logcat, "Failed to find tx in txpool"); return false; } } // remove first, in case this throws, so key images aren't removed const uint64_t tx_fee = std::get<1>(it->first); - MINFO("Removing tx " << txid << " from txpool: weight: " << meta->weight << ", fee/byte: " << tx_fee); + oxen::log::info(logcat, "Removing tx {} from txpool: weight: {}, fee/byte: {}", txid, meta->weight, tx_fee); m_blockchain.remove_txpool_tx(txid); m_txpool_weight -= meta->weight; remove_transaction_keyimages(tx, txid); @@ -774,7 +772,7 @@ namespace cryptonote txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { - MERROR("Failed to find tx in txpool"); + oxen::log::error(logcat, "Failed to find tx in txpool"); return false; } auto del_it = forward ? it++ : it--; @@ -794,7 +792,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Error while pruning txpool: " << e.what()); + oxen::log::error(logcat, "Error while pruning txpool: {}", e.what()); return false; } }; @@ -825,7 +823,7 @@ namespace cryptonote if (changed) ++m_cookie; if (m_txpool_weight > m_txpool_max_weight) - MINFO("Pool weight after pruning is still larger than limit: " << m_txpool_weight << "/" << m_txpool_max_weight); + oxen::log::info(logcat, "Pool weight after pruning is still larger than limit: {}/{}", m_txpool_weight, m_txpool_max_weight); } //--------------------------------------------------------------------------------- bool tx_memory_pool::insert_key_images(const transaction_prefix &tx, const crypto::hash &id, bool kept_by_block) @@ -898,7 +896,7 @@ namespace cryptonote txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(id, meta)) { - MERROR("Failed to find tx in txpool"); + oxen::log::error(logcat, "Failed to find tx in txpool"); return false; } txblob = m_blockchain.get_txpool_tx_blob(id); @@ -909,7 +907,7 @@ namespace cryptonote } else if (!parse_and_validate_tx_from_blob(txblob, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); return false; } else @@ -930,7 +928,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Failed to remove tx from txpool: " << e.what()); + oxen::log::error(logcat, "Failed to remove tx from txpool: {}", e.what()); return false; } @@ -973,11 +971,11 @@ namespace cryptonote if((tx_age > tools::to_seconds(MEMPOOL_TX_LIVETIME) && !meta.kept_by_block) || (tx_age > tools::to_seconds(MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME) && meta.kept_by_block) ) { - LOG_PRINT_L1("Tx " << txid << " removed from tx pool due to outdated, age: " << tx_age ); + oxen::log::info(logcat, "Tx {} removed from tx pool due to outdated, age: {}", txid, tx_age); auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { - LOG_PRINT_L1("Removing tx " << txid << " from tx pool, but it was not found in the sorted txs container!"); + oxen::log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); } else { @@ -1001,7 +999,7 @@ namespace cryptonote cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(bd, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); // continue } else @@ -1014,7 +1012,7 @@ namespace cryptonote } catch (const std::exception &e) { - MWARNING("Failed to remove stuck transaction: " << txid); + oxen::log::warning(logcat, "Failed to remove stuck transaction: {}", txid); // ignore error } } @@ -1048,7 +1046,7 @@ namespace cryptonote cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(bd, tx)) { - LOG_PRINT_L1("TX in pool could not be parsed from blob, txid: " << txid); + oxen::log::info(logcat, "TX in pool could not be parsed from blob, txid: {}", txid); return true; } @@ -1060,7 +1058,7 @@ namespace cryptonote crypto::hash max_used_block_id = null_hash; if (!m_blockchain.check_tx_inputs(tx, max_used_block_height, max_used_block_id, tvc, /*kept_by_block*/ false)) { - LOG_PRINT_L1("TX type: " << tx.type << " considered for relaying failed tx inputs check, txid: " << txid << ", reason: " << print_tx_verification_context(tvc, &tx)); + oxen::log::info(logcat, "TX type: {} considered for relaying failed tx inputs check, txid: {}, reason: {}", tx.type, txid, print_tx_verification_context(tvc, &tx)); return true; } } @@ -1069,7 +1067,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Failed to get transaction blob from db"); + oxen::log::error(logcat, "Failed to get transaction blob from db"); // ignore error } } @@ -1094,7 +1092,7 @@ namespace cryptonote ++updated; } } catch (const std::exception &e) { - MERROR("Failed to upate txpool transaction metadata: " << e.what()); + oxen::log::error(logcat, "Failed to upate txpool transaction metadata: {}", e.what()); } } lock.commit(); @@ -1122,7 +1120,7 @@ namespace cryptonote } catch (const std::exception &e) { - MERROR("Failed to update txpool transaction metadata: " << e.what()); + oxen::log::error(logcat, "Failed to update txpool transaction metadata: {}", e.what()); // continue } } @@ -1144,7 +1142,7 @@ namespace cryptonote transaction tx; if (!parse_and_validate_tx_from_blob(*bd, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); // continue return true; } @@ -1351,14 +1349,14 @@ namespace cryptonote crypto::hash tx_hash; if (!get_transaction_hash(pool_tx, tx_hash)) { - MERROR("Failed to get transaction hash from txpool to check if we can prune a state change"); + oxen::log::error(logcat, "Failed to get transaction hash from txpool to check if we can prune a state change"); continue; } txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(tx_hash, meta)) { - MERROR("Failed to get tx meta from txpool to check if we can prune a state change"); + oxen::log::error(logcat, "Failed to get tx meta from txpool to check if we can prune a state change"); continue; } @@ -1465,11 +1463,11 @@ namespace cryptonote { // Sanity check; if this happens checkpoints are failing and we can't guarantee blinks // anyway (because the blink quorums are not immutable). - MERROR("Unable to scan for conflicts: blockchain checkpoints are too far back"); + oxen::log::error(logcat, "Unable to scan for conflicts: blockchain checkpoints are too far back"); } else { - MDEBUG("Found " << key_image_conflicts.size() << " conflicting key images for blink tx " << txid << "; checking to see if we can roll back"); + oxen::log::debug(logcat, "Found {} conflicting key images for blink tx {}; checking to see if we can roll back", key_image_conflicts.size(), txid); // Check all the key images of all the blockchain transactions in blocks since the immutable // height, and remove any conflicts from the set of conflicts, updating the rollback height // as we go. If we remove all then rolling back will work, and we can accept the blink, @@ -1493,7 +1491,7 @@ namespace cryptonote txs.clear(); if (!m_blockchain.get_transactions(block.tx_hashes, txs)) { - MERROR("Unable to get transactions for block " << block.hash); + oxen::log::error(logcat, "Unable to get transactions for block {}", block.hash); can_fix_with_a_rollback = false; break; } @@ -1510,18 +1508,18 @@ namespace cryptonote end: if (key_image_conflicts.empty() && earliest < height && earliest > immutable) { - MDEBUG("Blink admission requires rolling back to height " << earliest); + oxen::log::debug(logcat, "Blink admission requires rolling back to height {}", earliest); can_fix_with_a_rollback = true; if (*blink_rollback_height == 0 || *blink_rollback_height > earliest) *blink_rollback_height = earliest; } } else - MERROR("Failed to retrieve blocks for trying a blink rollback!"); + oxen::log::error(logcat, "Failed to retrieve blocks for trying a blink rollback!"); } if (!can_fix_with_a_rollback) { - MWARNING("Blink admission of " << txid << " is not possible even with a rollback: found " << key_image_conflicts.size() << " key image conflicts in immutable blocks"); + oxen::log::warning(logcat, "Blink admission of {} is not possible even with a rollback: found {} key image conflicts in immutable blocks", txid, key_image_conflicts.size()); ret = false; tvc.m_double_spend = true; } @@ -1656,13 +1654,13 @@ end: txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { - MERROR("Failed to find tx meta in txpool"); + oxen::log::error(logcat, "Failed to find tx meta in txpool"); // continue, not fatal continue; } if (!meta.double_spend_seen) { - MDEBUG("Marking " << txid << " as double spending " << itk.k_image); + oxen::log::debug(logcat, "Marking {} as double spending {}", txid, itk.k_image); meta.double_spend_seen = true; changed = true; try @@ -1671,7 +1669,7 @@ end: } catch (const std::exception &e) { - MERROR("Failed to update tx meta: " << e.what()); + oxen::log::error(logcat, "Failed to update tx meta: {}", e.what()); // continue, not fatal } } @@ -1699,7 +1697,7 @@ end: block_reward_parts reward_parts = {}; if (!get_oxen_block_reward(median_weight, total_weight, already_generated_coins, version, reward_parts, block_reward_context)) { - MERROR("Failed to get block reward for empty block"); + oxen::log::error(logcat, "Failed to get block reward for empty block"); return false; } @@ -1709,7 +1707,7 @@ end: size_t const max_total_weight = 2 * median_weight - COINBASE_BLOB_RESERVED_SIZE; std::unordered_set k_images; - LOG_PRINT_L2("Filling block template, median weight " << median_weight << ", " << m_txs_by_fee_and_receive_time.size() << " txes in the pool"); + oxen::log::debug(logcat, "Filling block template, median weight {}, {} txes in the pool", median_weight, m_txs_by_fee_and_receive_time.size()); LockedTXN lock(m_blockchain); @@ -1721,15 +1719,15 @@ end: txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(sorted_it.second, meta)) { - MERROR(" failed to find tx meta"); + oxen::log::error(logcat, " failed to find tx meta"); continue; } - LOG_PRINT_L2("Considering " << sorted_it.second << ", weight " << meta.weight << ", current block weight " << total_weight << "/" << max_total_weight << ", current reward " << print_money(best_reward)); + oxen::log::debug(logcat, "Considering {}, weight {}, current block weight {}/{}, current reward {}", sorted_it.second, meta.weight, total_weight, max_total_weight, print_money(best_reward)); // Can not exceed maximum block weight if (max_total_weight < total_weight + meta.weight) { - LOG_PRINT_L2(" would exceed maximum block weight"); + oxen::log::debug(logcat, " would exceed maximum block weight"); continue; } @@ -1741,7 +1739,7 @@ end: block_reward_parts next_reward_parts = {}; if(!get_oxen_block_reward(median_weight, total_weight + meta.weight, already_generated_coins, version, next_reward_parts, next_block_reward_context)) { - LOG_PRINT_L2("Block reward calculation bug"); + oxen::log::debug(logcat, "Block reward calculation bug"); return false; } @@ -1761,7 +1759,7 @@ end: // If we're getting lower reward tx, don't include this TX if (next_reward < best_reward) { - LOG_PRINT_L2(" would decrease reward to " << print_money(next_reward)); + oxen::log::debug(logcat, " would decrease reward to {}", print_money(next_reward)); continue; } @@ -1784,7 +1782,7 @@ end: } catch (const std::exception &e) { - MERROR("Failed to check transaction readiness: " << e.what()); + oxen::log::error(logcat, "Failed to check transaction readiness: {}", e.what()); // continue, not fatal } if (memcmp(&original_meta, &meta, sizeof(meta))) @@ -1795,18 +1793,18 @@ end: } catch (const std::exception &e) { - MERROR("Failed to update tx meta: " << e.what()); + oxen::log::error(logcat, "Failed to update tx meta: {}", e.what()); // continue, not fatal } } if (!ready) { - LOG_PRINT_L2(" not ready to go"); + oxen::log::debug(logcat, " not ready to go"); continue; } if (have_key_images(k_images, tx)) { - LOG_PRINT_L2(" key images already seen"); + oxen::log::debug(logcat, " key images already seen"); continue; } @@ -1816,14 +1814,12 @@ end: net_fee = next_reward_parts.miner_fee; best_reward = next_reward; append_key_images(k_images, tx); - LOG_PRINT_L2(" added, new block weight " << total_weight << "/" << max_total_weight << ", reward " << print_money(best_reward)); + oxen::log::debug(logcat, " added, new block weight {}/{}, reward {}", total_weight, max_total_weight, print_money(best_reward)); } lock.commit(); expected_reward = best_reward; - LOG_PRINT_L2("Block template filled with " << bl.tx_hashes.size() << " txes, weight " - << total_weight << "/" << max_total_weight << ", reward " << print_money(best_reward) - << " (including " << print_money(net_fee) << " in fees)"); + oxen::log::debug(logcat, "Block template filled with {} txes, weight {}/{}, reward {} (including {} in fees)", bl.tx_hashes.size(), total_weight, max_total_weight, print_money(best_reward), print_money(net_fee)); return true; } //--------------------------------------------------------------------------------- @@ -1838,11 +1834,11 @@ end: m_blockchain.for_all_txpool_txes([this, &remove, tx_weight_limit](const crypto::hash &txid, const txpool_tx_meta_t &meta, const std::string*) { m_txpool_weight += meta.weight; if (meta.weight > tx_weight_limit) { - LOG_PRINT_L1("Transaction " << txid << " is too big (" << meta.weight << " bytes), removing it from pool"); + oxen::log::info(logcat, "Transaction {} is too big ({} bytes), removing it from pool", txid, meta.weight); remove.insert(txid); } else if (m_blockchain.have_tx(txid)) { - LOG_PRINT_L1("Transaction " << txid << " is in the blockchain, removing it from pool"); + oxen::log::info(logcat, "Transaction {} is in the blockchain, removing it from pool", txid); remove.insert(txid); } return true; @@ -1860,7 +1856,7 @@ end: cryptonote::transaction tx; if (!parse_and_validate_tx_from_blob(txblob, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); continue; } // remove tx from db first @@ -1870,7 +1866,7 @@ end: auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { - LOG_PRINT_L1("Removing tx " << txid << " from tx pool, but it was not found in the sorted txs container!"); + oxen::log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); } else { @@ -1880,7 +1876,7 @@ end: } catch (const std::exception &e) { - MERROR("Failed to remove invalid tx from pool"); + oxen::log::error(logcat, "Failed to remove invalid tx from pool"); // continue } } @@ -1912,13 +1908,13 @@ end: cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(*bd, tx)) { - MWARNING("Failed to parse tx from txpool, removing"); + oxen::log::warning(logcat, "Failed to parse tx from txpool, removing"); remove.push_back(txid); return true; } if (!insert_key_images(tx, txid, meta.kept_by_block)) { - MFATAL("Failed to insert key images from txpool tx"); + oxen::log::error(logcat, "Failed to insert key images from txpool tx"); return false; } @@ -1941,7 +1937,7 @@ end: } catch (const std::exception &e) { - MWARNING("Failed to remove corrupt transaction: " << txid); + oxen::log::warning(logcat, "Failed to remove corrupt transaction: {}", txid); // ignore error } } diff --git a/src/cryptonote_core/tx_sanity_check.cpp b/src/cryptonote_core/tx_sanity_check.cpp index 9b46c5f10..d58e5ae1c 100644 --- a/src/cryptonote_core/tx_sanity_check.cpp +++ b/src/cryptonote_core/tx_sanity_check.cpp @@ -34,25 +34,24 @@ #include "blockchain.h" #include "tx_sanity_check.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "verify" - namespace cryptonote { +static auto logcat = oxen::log::Cat("verify"); + bool tx_sanity_check(const std::string &tx_blob, uint64_t rct_outs_available) { cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(tx_blob, tx)) { - MERROR("Failed to parse transaction"); + oxen::log::error(logcat, "Failed to parse transaction"); return false; } if (cryptonote::is_coinbase(tx)) { - MERROR("Transaction is coinbase"); + oxen::log::error(logcat, "Transaction is coinbase"); return false; } std::set rct_indices; @@ -77,7 +76,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui { if (n_indices <= 10) { - MDEBUG("n_indices is only " << n_indices << ", not checking"); + oxen::log::debug(logcat, "n_indices is only {}, not checking", n_indices); return true; } @@ -86,7 +85,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui if (rct_indices.size() < n_indices * 8 / 10) { - MERROR("amount of unique indices is too low (amount of rct indices is " << rct_indices.size() << ", out of total " << n_indices << "indices."); + oxen::log::error(logcat, "amount of unique indices is too low (amount of rct indices is {}, out of total {} indices)", rct_indices.size(), n_indices); return false; } @@ -94,7 +93,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui uint64_t median = tools::median(std::move(offsets)); if (median < rct_outs_available * 6 / 10) { - MERROR("median offset index is too low (median is " << median << " out of total " << rct_outs_available << "offsets). Transactions should contain a higher fraction of recent outputs."); + oxen::log::error(logcat, "median offset index is too low (median is {} out of total {}offsets). Transactions should contain a higher fraction of recent outputs.", median, rct_outs_available); return false; } diff --git a/src/cryptonote_core/uptime_proof.cpp b/src/cryptonote_core/uptime_proof.cpp index da9211dab..b1634399b 100644 --- a/src/cryptonote_core/uptime_proof.cpp +++ b/src/cryptonote_core/uptime_proof.cpp @@ -3,18 +3,18 @@ #include "common/string_util.h" #include "epee/string_tools.h" #include "version.h" +#include "logging/oxen_logger.h" extern "C" { #include } -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "uptime_proof" - namespace uptime_proof { +static auto logcat = oxen::log::Cat("uptime_proof"); + //Constructor for the uptime proof, will take the service node keys as a param and sign Proof::Proof( uint32_t sn_public_ip, @@ -84,7 +84,7 @@ Proof::Proof(const std::string& serialized_proof) lokinet_version[k++] = static_cast(get_int(i)); } } catch (const std::exception& e) { - MWARNING("deserialization failed: " << e.what()); + oxen::log::warning(logcat, "deserialization failed: {}", e.what()); throw; } } diff --git a/src/cryptonote_protocol/CMakeLists.txt b/src/cryptonote_protocol/CMakeLists.txt index 3551da3e8..21d3118d8 100644 --- a/src/cryptonote_protocol/CMakeLists.txt +++ b/src/cryptonote_protocol/CMakeLists.txt @@ -40,6 +40,6 @@ target_link_libraries(cryptonote_protocol PUBLIC p2p PRIVATE - easylogging SQLiteCpp + logging extra) diff --git a/src/cryptonote_protocol/block_queue.cpp b/src/cryptonote_protocol/block_queue.cpp index f2336b8eb..e3ae75053 100644 --- a/src/cryptonote_protocol/block_queue.cpp +++ b/src/cryptonote_protocol/block_queue.cpp @@ -38,9 +38,6 @@ #include "common/pruning.h" #include "block_queue.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "cn.block_queue" - namespace std { template<> struct hash @@ -55,6 +52,8 @@ struct hash namespace cryptonote { + static auto logcat = oxen::log::Cat("cn.block_queue"); + void block_queue::add_blocks(uint64_t height, std::vector bcel, const boost::uuids::uuid &connection_id, float rate, size_t size) { std::unique_lock lock{mutex}; @@ -182,9 +181,9 @@ uint64_t block_queue::get_next_needed_height(uint64_t blockchain_height) const void block_queue::print() const { std::unique_lock lock{mutex}; - MDEBUG("Block queue has " << blocks.size() << " spans"); + oxen::log::debug(logcat, "Block queue has {} spans", blocks.size()); for (const auto &span: blocks) - MDEBUG(" " << span.start_block_height << " - " << (span.start_block_height+span.nblocks-1) << " (" << span.nblocks << ") - " << (span.blocks.empty() ? "scheduled" : "filled ") << " " << span.connection_id << " (" << ((unsigned)(span.rate*10/1024.f))/10.f << " kB/s)"); + oxen::log::debug(logcat, " {} - {} ({}) - {} {} ({} kB/s)", span.start_block_height, (span.start_block_height+span.nblocks-1), span.nblocks, (span.blocks.empty() ? "scheduled" : "filled "), boost::lexical_cast(span.connection_id), ((unsigned)(span.rate*10/1024.f))/10.f); } std::string block_queue::get_overview(uint64_t blockchain_height) const @@ -242,17 +241,15 @@ std::pair block_queue::reserve_span( { std::unique_lock lock{mutex}; - MDEBUG("reserve_span: first_block_height " << first_block_height << ", last_block_height " << last_block_height - << ", max " << max_blocks << ", seed " << epee::string_tools::to_string_hex(pruning_seed) << ", blockchain_height " << - blockchain_height << ", block hashes size " << block_hashes.size()); + oxen::log::debug(logcat, "reserve_span: first_block_height {}, last_block_height {}, max {}, seed {}, blockchain_height {}, block hashes size {}", first_block_height, last_block_height, max_blocks, epee::string_tools::to_string_hex(pruning_seed), blockchain_height, block_hashes.size()); if (last_block_height < first_block_height || max_blocks == 0) { - MDEBUG("reserve_span: early out: first_block_height " << first_block_height << ", last_block_height " << last_block_height << ", max_blocks " << max_blocks); + oxen::log::debug(logcat, "reserve_span: early out: first_block_height {}, last_block_height {}, max_blocks {}", first_block_height, last_block_height, max_blocks); return std::make_pair(0, 0); } if (block_hashes.size() > last_block_height) { - MDEBUG("reserve_span: more block hashes than fit within last_block_height: " << block_hashes.size() << " and " << last_block_height); + oxen::log::debug(logcat, "reserve_span: more block hashes than fit within last_block_height: {} and {}", block_hashes.size(), last_block_height); return std::make_pair(0, 0); } @@ -267,19 +264,17 @@ std::pair block_queue::reserve_span( // if the peer's pruned for the starting block and its unpruned stripe comes next, start downloading from there const uint32_t next_unpruned_height = tools::get_next_unpruned_block_height(span_start_height, blockchain_height, pruning_seed); - MDEBUG("reserve_span: next_unpruned_height " << next_unpruned_height << " from " << span_start_height << " and seed " - << epee::string_tools::to_string_hex(pruning_seed) << ", limit " << span_start_height + PRUNING_STRIPE_SIZE); + oxen::log::debug(logcat, "reserve_span: next_unpruned_height {} from {} and seed {}, limit {}", next_unpruned_height, span_start_height, epee::string_tools::to_string_hex(pruning_seed), span_start_height); if (next_unpruned_height > span_start_height && next_unpruned_height < span_start_height + PRUNING_STRIPE_SIZE) { - MDEBUG("We can download from next span: ideal height " << span_start_height << ", next unpruned height " << next_unpruned_height << - "(+" << next_unpruned_height - span_start_height << "), current seed " << pruning_seed); + oxen::log::debug(logcat, "We can download from next span: ideal height {}, next unpruned height {}(+{}), current seed {}", span_start_height, next_unpruned_height, next_unpruned_height - span_start_height, pruning_seed); span_start_height = next_unpruned_height; } - MDEBUG("span_start_height: " <= block_hashes.size() + block_hashes_start_height) { - MDEBUG("Out of hashes, cannot reserve"); + oxen::log::debug(logcat, "Out of hashes, cannot reserve"); return std::make_pair(0, 0); } @@ -300,10 +295,10 @@ std::pair block_queue::reserve_span( } if (span_length == 0) { - MDEBUG("span_length 0, cannot reserve"); + oxen::log::debug(logcat, "span_length 0, cannot reserve"); return std::make_pair(0, 0); } - MDEBUG("Reserving span " << span_start_height << " - " << (span_start_height + span_length - 1) << " for " << connection_id); + oxen::log::debug(logcat, "Reserving span {} - {} for {}", span_start_height, (span_start_height + span_length - 1), boost::lexical_cast(connection_id)); add_blocks(span_start_height, span_length, connection_id, std::chrono::steady_clock::now()); set_span_hashes(span_start_height, connection_id, hashes); return std::make_pair(span_start_height, span_length); @@ -469,7 +464,7 @@ float block_queue::get_speed(const boost::uuids::uuid &connection_id) const return 1.0f; // everything dead ? Can't happen, but let's trap anyway const float speed = conn_rate / best_rate; - MTRACE(" Relative speed for " << connection_id << ": " << speed << " (" << conn_rate << "/" << best_rate); + oxen::log::trace(logcat, " Relative speed for {}: {} ({}/{}", boost::lexical_cast(connection_id), speed, conn_rate, best_rate); return speed; } @@ -494,7 +489,7 @@ float block_queue::get_download_rate(const boost::uuids::uuid &connection_id) co if (conn_rate < 0) conn_rate = 0.0f; - MTRACE("Download rate for " << connection_id << ": " << conn_rate << " b/s"); + oxen::log::trace(logcat, "Download rate for {}: {} b/s", boost::lexical_cast(connection_id), conn_rate); return conn_rate; } diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.h b/src/cryptonote_protocol/cryptonote_protocol_handler.h index 63c2ef89f..ebc9a456e 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.h +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.h @@ -45,7 +45,6 @@ #include "cryptonote_protocol_defs.h" #include "cryptonote_protocol_handler_common.h" #include "block_queue.h" -#include "common/perf_timer.h" #include "common/meta.h" #include "cryptonote_basic/connection_context.h" #include @@ -56,6 +55,14 @@ DISABLE_VS_WARNINGS(4355) #define CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT 500 #define CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT 5000 +template <> +struct fmt::formatter : fmt::formatter { + auto format(cryptonote::cryptonote_connection_context connection_context, format_context& ctx) { + return formatter::format( + fmt::format("[{}]", epee::net_utils::print_connection_context_short(connection_context)), ctx); + } +}; + namespace cryptonote { template @@ -127,7 +134,7 @@ namespace cryptonote template bool relay_to_synchronized_peers(typename T::request& arg, cryptonote_connection_context& exclude_context) { - LOG_PRINT_L2("[" << epee::net_utils::print_connection_context_short(exclude_context) << "] post relay " << tools::type_name() << " -->"); + oxen::log::debug(globallogcat, "[{}] post relay {} -->", epee::net_utils::print_connection_context_short(exclude_context), tools::type_name()); std::vector> connections; m_p2p->for_each_connection([&exclude_context, &connections](connection_context& context, nodetool::peerid_type peer_id) { @@ -184,8 +191,8 @@ namespace cryptonote tools::periodic_task m_standby_checker{100ms}; tools::periodic_task m_sync_search_checker{101s}; std::atomic m_max_out_peers; - tools::PerformanceTimer m_sync_timer, m_add_timer; - std::optional m_last_add_end_time; + std::chrono::steady_clock::time_point m_sync_timer; + std::chrono::steady_clock::time_point m_last_add_end_time; uint64_t m_sync_spans_downloaded, m_sync_old_spans_downloaded, m_sync_bad_spans_downloaded; uint64_t m_sync_download_chain_size, m_sync_download_objects_size; size_t m_block_download_max_size; @@ -204,7 +211,7 @@ namespace cryptonote template bool post_notify(typename t_parameter::request& arg, cryptonote_connection_context& context) { - LOG_PRINT_L2("[" << epee::net_utils::print_connection_context_short(context) << "] post " << tools::type_name() << " -->"); + oxen::log::debug(globallogcat, "[{}] post {} -->", epee::net_utils::print_connection_context_short(context), tools::type_name()); std::string blob; epee::serialization::store_t_to_binary(arg, blob); return m_p2p->invoke_notify_to_peer(t_parameter::ID, epee::strspan(blob), context); diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.inl b/src/cryptonote_protocol/cryptonote_protocol_handler.inl index cb7248273..7e1763243 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.inl +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.inl @@ -55,27 +55,12 @@ #include "common/random.h" #include "common/lock.h" #include "common/util.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net.cn" - -#define MLOG_P2P_MESSAGE(x) MCINFO("net.p2p.msg", context << x) -#define MLOGIF_P2P_MESSAGE(init, test, x) \ - do { \ - const auto level = el::Level::Info; \ - const char *cat = "net.p2p.msg"; \ - if (ELPP->vRegistry()->allowed(level, cat)) { \ - init; \ - if (test) \ - el::base::Writer(level, __FILE__, __LINE__, ELPP_FUNC, el::base::DispatchAction::NormalLog).construct(cat) << x; \ - } \ - } while(0) - -#define MLOG_PEER_STATE(x) \ - MCINFO(OXEN_DEFAULT_LOG_CATEGORY, context << "[" << epee::string_tools::to_string_hex(context.m_pruning_seed) << "] state: " << x << " in state " << cryptonote::get_protocol_state_string(context.m_state)) +#include +#include namespace cryptonote { + static auto logcat = oxen::log::Cat("net.cn"); constexpr size_t BLOCK_QUEUE_NSPANS_THRESHOLD = 10; // chunks of N blocks constexpr size_t BLOCK_QUEUE_SIZE_THRESHOLD = 100*1024*1024; // bytes, i.e. 100 MB @@ -104,11 +89,8 @@ namespace cryptonote template bool t_cryptonote_protocol_handler::init(const boost::program_options::variables_map& vm) { - m_sync_timer.pause(); - m_sync_timer.reset(); - m_add_timer.pause(); - m_add_timer.reset(); - m_last_add_end_time = std::nullopt; + m_sync_timer = std::chrono::steady_clock::now(); + m_last_add_end_time = std::chrono::steady_clock::now(); m_sync_spans_downloaded = 0; m_sync_old_spans_downloaded = 0; m_sync_bad_spans_downloaded = 0; @@ -138,7 +120,7 @@ namespace cryptonote template bool t_cryptonote_protocol_handler::on_callback(cryptonote_connection_context& context) { - LOG_PRINT_CCONTEXT_L2("callback fired"); + oxen::log::debug(logcat, "callback fired"); CHECK_AND_ASSERT_MES_CC( context.m_callback_request_count > 0, false, "false callback fired, but context.m_callback_request_count=" << context.m_callback_request_count); --context.m_callback_request_count; @@ -147,9 +129,11 @@ namespace cryptonote NOTIFY_REQUEST_CHAIN::request r{}; context.m_needed_objects.clear(); m_core.get_blockchain_storage().get_short_chain_history(r.block_ids); - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() ); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); post_notify(r, context); - MLOG_PEER_STATE("requesting chain"); + + + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); } else if(context.m_state == cryptonote_connection_context::state_standby) { @@ -191,9 +175,9 @@ namespace cryptonote context.m_need_blink_sync = false; if (!r.heights.empty()) { - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_BLOCK_BLINKS: requesting blink tx lists for " << r.heights.size() << " blocks"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_BLOCK_BLINKS: requesting blink tx lists for {} blocks", r.heights.size()); post_notify(r, context); - MLOG_PEER_STATE("requesting block blinks"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting block blinks", cryptonote::get_protocol_state_string(context.m_state)); } } @@ -260,7 +244,7 @@ namespace cryptonote << std::setw(10) << up_sum << std::setw(13) << up_curr_sum << "\n"; - LOG_PRINT_L0("Connections:\n" << ss.str()); + oxen::log::warning(logcat, "Connections:\n{}", ss.str()); } //------------------------------------------------------------------------------------------------------------------------ // Returns a list of connection_info objects describing each open p2p connection @@ -331,9 +315,9 @@ namespace cryptonote } //------------------------------------------------------------------------------------------------------------------------ template - bool t_cryptonote_protocol_handler::process_payload_sync_data(CORE_SYNC_DATA&& hshd, cryptonote_connection_context& context, bool is_inital) + bool t_cryptonote_protocol_handler::process_payload_sync_data(CORE_SYNC_DATA&& hshd, cryptonote_connection_context& context, bool is_initial) { - if(context.m_state == cryptonote_connection_context::state_before_handshake && !is_inital) + if(context.m_state == cryptonote_connection_context::state_before_handshake && !is_initial) return true; if(context.m_state == cryptonote_connection_context::state_synchronizing) @@ -347,9 +331,7 @@ namespace cryptonote if (version != hshd.top_version) { if (version < hshd.top_version && version == get_network_version(nettype, m_core.get_current_blockchain_height())) - MCLOG_RED(el::Level::Warning, "global", context << " peer claims higher version than we think (" << - (unsigned)hshd.top_version << " for " << (hshd.current_height - 1) << " instead of " << (unsigned)version << - ") - we may be forked from the network and a software upgrade may be needed"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "{} peer claims higher version than we think ({} for {} instead of {}) 0 we may be forked from the network and a software upgrade may be needed", context, (unsigned)hshd.top_version, (hshd.current_height - 1), (unsigned)version)); return false; } } @@ -360,7 +342,7 @@ namespace cryptonote const uint32_t log_stripes = tools::get_pruning_log_stripes(hshd.pruning_seed); if (log_stripes != PRUNING_LOG_STRIPES || tools::get_pruning_stripe(hshd.pruning_seed) > (1u << log_stripes)) { - MWARNING(context << " peer claim unexpected pruning seed " << epee::string_tools::to_string_hex(hshd.pruning_seed) << ", disconnecting"); + oxen::log::warning(logcat, "{} peer claim unexpected pruning seed {}, disconnecting", context, epee::string_tools::to_string_hex(hshd.pruning_seed)); return false; } } @@ -369,7 +351,7 @@ namespace cryptonote context.m_pruning_seed = hshd.pruning_seed; if constexpr (PRUNING_DEBUG_SPOOF_SEED) { context.m_pruning_seed = tools::make_pruning_seed(1 + (context.m_remote_address.as().ip()) % (1 << PRUNING_LOG_STRIPES), PRUNING_LOG_STRIPES); - LOG_INFO_CC(context, "New connection posing as pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << ", seed address " << &context.m_pruning_seed); + oxen::log::info(logcat, "{}{}, seed address {}", context, "New connection posing as pruning seed ", epee::string_tools::to_string_hex(context.m_pruning_seed), &context.m_pruning_seed); } // No chain synchronization over hidden networks (tor, i2p, etc.) @@ -387,12 +369,12 @@ namespace cryptonote { if (hshd.blink_blocks.size() != hshd.blink_hash.size()) { - MWARNING(context << " peer sent illegal mismatched blink heights/hashes; disconnecting"); + oxen::log::warning(logcat, "{} peer sent illegal mismatched blink heights/hashes; disconnecting", context); return false; } else if (hshd.blink_blocks.size() > 1000) { - MWARNING(context << " peer sent too many post-checkpoint blink blocks; disconnecting"); + oxen::log::warning(logcat, "{} peer sent too many post-checkpoint blink blocks; disconnecting", context); return false; } @@ -406,13 +388,13 @@ namespace cryptonote context.m_blink_state.erase(context.m_blink_state.lower_bound(1), context.m_blink_state.lower_bound(immutable_height + 1)); auto our_blink_hashes = m_core.get_pool().get_blink_checksums(); uint64_t last_height; - MDEBUG("Peer sent " << hshd.blink_blocks.size() << " blink hashes"); + oxen::log::debug(logcat, "Peer sent {} blink hashes", hshd.blink_blocks.size()); for (size_t i = 0; i < hshd.blink_blocks.size(); i++) { auto &height = hshd.blink_blocks[i]; if (i == 0 || height > last_height) last_height = height; else { - MWARNING(context << " peer sent blink tx heights out of order, which is not valid; disconnecting"); + oxen::log::warning(logcat, "{} peer sent blink tx heights out of order, which is not valid; disconnecting", context); return false; } @@ -447,7 +429,7 @@ namespace cryptonote } if (context.m_need_blink_sync) - MINFO(context << "Need to synchronized blink signatures"); + oxen::log::info(logcat, "{}Need to synchronized blink signatures", context); } uint64_t target = m_core.get_target_blockchain_height(); @@ -458,16 +440,17 @@ namespace cryptonote if (!have_block && hshd.current_height > target) { - /* As I don't know if accessing hshd from core could be a good practice, - I prefer pushing target height to the core at the same time it is pushed to the user. - Nz. */ - int64_t diff = static_cast(hshd.current_height) - static_cast(curr_height); - uint64_t abs_diff = std::abs(diff); - uint64_t max_block_height = std::max(hshd.current_height, curr_height); - MCLOG(is_inital ? el::Level::Info : el::Level::Debug, "global", context << "Sync data returned a new top block candidate: " << curr_height << " -> " << hshd.current_height - << " [Your node is " << abs_diff << " blocks (" << tools::get_human_readable_timespan(abs_diff * TARGET_BLOCK_TIME) << " " - << (0 <= diff ? "behind" : "ahead") - << ")]\nSYNCHRONIZATION started"); + /* As I don't know if accessing hshd from core could be a good practice, + I prefer pushing target height to the core at the same time it is pushed to the user. + Nz. */ + int64_t diff = static_cast(hshd.current_height) - static_cast(curr_height); + uint64_t abs_diff = std::abs(diff); + uint64_t max_block_height = std::max(hshd.current_height, curr_height); + std::string sync_msg = fmt::format("{}Sync data returned a new top block candidate: {} -> {} [Your node is {} blocks ({} {})]\nSYNCHRONIZATION started", context, curr_height, hshd.current_height, abs_diff, tools::get_human_readable_timespan(abs_diff*TARGET_BLOCK_TIME), (0 <= diff ? "behind" : "ahead")); + if (is_initial) + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::cyan), sync_msg)); + else + oxen::log::debug(globallogcat, sync_msg); m_period_start_time = m_sync_start_time = std::chrono::steady_clock::now(); m_sync_start_height = curr_height; @@ -478,11 +461,8 @@ namespace cryptonote } if (m_core.get_target_blockchain_height() == 0) // only when sync starts { - m_sync_timer.resume(); - m_sync_timer.reset(); - m_add_timer.pause(); - m_add_timer.reset(); - m_last_add_end_time = std::nullopt; + m_sync_timer = std::chrono::steady_clock::now(); + m_last_add_end_time = std::chrono::steady_clock::now(); m_sync_spans_downloaded = 0; m_sync_old_spans_downloaded = 0; m_sync_bad_spans_downloaded = 0; @@ -501,7 +481,7 @@ namespace cryptonote if(have_block) { context.m_state = cryptonote_connection_context::state_normal; - if(is_inital && hshd.current_height >= target && target == m_core.get_current_blockchain_height()) + if(is_initial && hshd.current_height >= target && target == m_core.get_current_blockchain_height()) on_connection_synchronized(); } else @@ -511,12 +491,12 @@ namespace cryptonote if (context.m_need_blink_sync || context.m_state == cryptonote_connection_context::state_synchronizing) { - MINFO(context << "Remote blockchain height: " << hshd.current_height << ", id: " << hshd.top_id); + oxen::log::debug(logcat, "{}Remote blockchain height: {}, id: {}", context, hshd.current_height, hshd.top_id); //let the socket to send response to handshake, but request callback, to let send request data after response - LOG_PRINT_CCONTEXT_L2("requesting callback"); + oxen::log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); - MLOG_PEER_STATE("requesting callback"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); } return true; } @@ -552,13 +532,20 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_fluffy_block(int command, NOTIFY_NEW_FLUFFY_BLOCK::request& arg, cryptonote_connection_context& context) { - MLOGIF_P2P_MESSAGE(crypto::hash hash; cryptonote::block b; bool ret = cryptonote::parse_and_validate_block_from_blob(arg.b.block, b, &hash);, ret, "Received NOTIFY_NEW_FLUFFY_BLOCK " << hash << " (height " << arg.current_blockchain_height << ", " << arg.b.txs.size() << " txes)"); + if(oxen::log::Cat("net.p2p,msg")->should_log(oxen::log::Level::info)) + { + crypto::hash hash; + cryptonote::block b; + bool ret = cryptonote::parse_and_validate_block_from_blob(arg.b.block, b, &hash); + if (ret) + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_FLUFFY_BLOCK {} (height {}, {} txes)", hash, arg.current_blockchain_height, arg.b.txs.size()); + } if(context.m_state != cryptonote_connection_context::state_normal) return 1; if(!is_synchronized() || m_no_sync) // can happen if a peer connection goes to normal but another thread still hasn't finished adding queued blocks { - LOG_DEBUG_CC(context, "Received new block while syncing, ignored"); + oxen::log::debug(logcat, "{}Received new block while syncing, ignored", context); return 1; } @@ -573,15 +560,7 @@ namespace cryptonote // What we asked for != to what we received .. if(context.m_requested_objects.size() != arg.b.txs.size()) { - LOG_ERROR_CCONTEXT - ( - "NOTIFY_NEW_FLUFFY_BLOCK -> request/response mismatch, " - << "block = " << tools::type_to_hex(get_blob_hash(arg.b.block)) - << ", requested = " << context.m_requested_objects.size() - << ", received = " << new_block.tx_hashes.size() - << ", dropping connection" - ); - + oxen::log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK -> request/response mismatch, block = {}, requested = {}, received = {}, dropping connection", tools::type_to_hex(get_blob_hash(arg.b.block)), context.m_requested_objects.size(), new_block.tx_hashes.size()); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -609,12 +588,7 @@ namespace cryptonote { if(!get_transaction_hash(tx, tx_hash)) { - LOG_PRINT_CCONTEXT_L1 - ( - "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed" - << ", dropping connection" - ); - + oxen::log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -622,13 +596,7 @@ namespace cryptonote } catch(...) { - LOG_PRINT_CCONTEXT_L1 - ( - "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed" - << ", exception thrown" - << ", dropping connection" - ); - + oxen::log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, exception thrown, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -646,13 +614,7 @@ namespace cryptonote auto req_tx_it = context.m_requested_objects.find(tx_hash); if(req_tx_it == context.m_requested_objects.end()) { - LOG_ERROR_CCONTEXT - ( - "Peer sent wrong transaction (NOTIFY_NEW_FLUFFY_BLOCK): " - << "transaction with id = " << tx_hash << " wasn't requested, " - << "dropping connection" - ); - + oxen::log::error(logcat, "Peer sent wrong transaction (NOTIFY_NEW_FLUFFY_BLOCK): transaction with id = {} wasn't requested, dropping connection", tx_hash); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -665,11 +627,11 @@ namespace cryptonote // sent in our pool, so don't verify again.. if(!m_core.get_pool().have_tx(tx_hash)) { - MDEBUG("Incoming tx " << tx_hash << " not in pool, adding"); + oxen::log::debug(logcat, "Incoming tx {} not in pool, adding", tx_hash); cryptonote::tx_verification_context tvc{}; if(!m_core.handle_incoming_tx(tx_blob, tvc, tx_pool_options::from_block()) || tvc.m_verifivation_failed) { - LOG_PRINT_CCONTEXT_L1("Block verification failed: transaction verification failed, dropping connection"); + oxen::log::info(logcat, "Block verification failed: transaction verification failed, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -685,13 +647,7 @@ namespace cryptonote } else { - LOG_ERROR_CCONTEXT - ( - "sent wrong tx: failed to parse and validate transaction: " - << oxenc::to_hex(tx_blob) - << ", dropping connection" - ); - + oxen::log::error(logcat, "sent wrong tx: failed to parse and validate transaction: {}, dropping connection", oxenc::to_hex(tx_blob)); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -704,13 +660,7 @@ namespace cryptonote // ones we received. if(context.m_requested_objects.size()) { - MERROR - ( - "NOTIFY_NEW_FLUFFY_BLOCK: peer sent the number of transaction requested" - << ", but not the actual transactions requested" - << ", context.m_requested_objects.size() = " << context.m_requested_objects.size() - << ", dropping connection" - ); + oxen::log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: peer sent the number of transaction requested, but not the actual transactions requested, context.m_requested_objects.size() = {}, dropping connection", context.m_requested_objects.size()); drop_connection(context, false, false); m_core.resume_mine(); @@ -739,14 +689,14 @@ namespace cryptonote } else { - MERROR("1 tx requested, none not found, but " << txes.size() << " returned"); + oxen::log::error(logcat, "1 tx requested, none not found, but {} returned", txes.size()); m_core.resume_mine(); return 1; } } else { - MDEBUG("Tx " << tx_hash << " not found in pool"); + oxen::log::debug(logcat, "Tx {} not found in pool", tx_hash); need_tx_indices.push_back(tx_idx); } } @@ -757,21 +707,21 @@ namespace cryptonote if(!need_tx_indices.empty()) // drats, we don't have everything.. { // request non-mempool txs - MDEBUG("We are missing " << need_tx_indices.size() << " txes for this fluffy block"); + oxen::log::debug(logcat, "We are missing {} txes for this fluffy block", need_tx_indices.size()); for (auto txidx: need_tx_indices) - MDEBUG(" tx " << new_block.tx_hashes[txidx]); + oxen::log::debug(logcat, " tx {}", new_block.tx_hashes[txidx]); NOTIFY_REQUEST_FLUFFY_MISSING_TX::request missing_tx_req; missing_tx_req.block_hash = get_block_hash(new_block); missing_tx_req.current_blockchain_height = arg.current_blockchain_height; missing_tx_req.missing_tx_indices = std::move(need_tx_indices); m_core.resume_mine(); - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_indices.size()=" << missing_tx_req.missing_tx_indices.size() ); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_indices.size()={}", missing_tx_req.missing_tx_indices.size()); post_notify(missing_tx_req, context); } else // whoo-hoo we've got em all .. { - MDEBUG("We have all needed txes for this fluffy block"); + oxen::log::debug(logcat, "We have all needed txes for this fluffy block"); block_complete_entry b = {}; b.block = arg.b.block; @@ -784,7 +734,7 @@ namespace cryptonote std::vector pblocks; if (!m_core.prepare_handle_incoming_blocks(blocks, pblocks)) { - LOG_PRINT_CCONTEXT_L0("Failure in prepare_handle_incoming_blocks"); + oxen::log::warning(logcat, "Failure in prepare_handle_incoming_blocks"); m_core.resume_mine(); return 1; } @@ -793,7 +743,7 @@ namespace cryptonote m_core.handle_incoming_block(arg.b.block, pblocks.empty() ? NULL : &pblocks[0], bvc, nullptr /*checkpoint*/); // got block from handle_notify_new_block if (!m_core.cleanup_handle_incoming_blocks(true)) { - LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks"); + oxen::log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); m_core.resume_mine(); return 1; } @@ -801,7 +751,7 @@ namespace cryptonote if( bvc.m_verifivation_failed ) { - LOG_PRINT_CCONTEXT_L0("Block verification failed, dropping connection"); + oxen::log::warning(logcat, "Block verification failed, dropping connection"); drop_connection(context, true, false); return 1; } @@ -819,20 +769,15 @@ namespace cryptonote context.m_state = cryptonote_connection_context::state_synchronizing; NOTIFY_REQUEST_CHAIN::request r{}; m_core.get_blockchain_storage().get_short_chain_history(r.block_ids); - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() ); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); post_notify(r, context); - MLOG_PEER_STATE("requesting chain"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); } } } else { - LOG_ERROR_CCONTEXT - ( - "sent wrong block: failed to parse and validate block: " - << oxenc::to_hex(arg.b.block) - << ", dropping connection" - ); + oxen::log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(arg.b.block)); m_core.resume_mine(); drop_connection(context, false, false); @@ -846,7 +791,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_uptime_proof(int command, NOTIFY_UPTIME_PROOF::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_UPTIME_PROOF"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_UPTIME_PROOF"); // NOTE: Don't relay your own uptime proof, otherwise we have the following situation // Node1 sends uptime -> @@ -878,7 +823,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_btencoded_uptime_proof(int command, NOTIFY_BTENCODED_UPTIME_PROOF::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_BTENCODED_UPTIME_PROOF"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_BTENCODED_UPTIME_PROOF"); // NOTE: Don't relay your own uptime proof, otherwise we have the following situation // Node1 sends uptime -> @@ -912,14 +857,14 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_service_node_vote(int command, NOTIFY_NEW_SERVICE_NODE_VOTE::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_NEW_SERVICE_NODE_VOTE (" << arg.votes.size() << " txes)"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_SERVICE_NODE_VOTE ({} txes)", arg.votes.size()); if(context.m_state != cryptonote_connection_context::state_normal) return 1; if(!is_synchronized() || m_no_sync) { - LOG_DEBUG_CC(context, "Received new service node vote while syncing, ignored"); + oxen::log::debug(logcat, "{}Received new service node vote while syncing, ignored", context); return 1; } @@ -930,7 +875,7 @@ namespace cryptonote if (vvc.m_verification_failed) { - LOG_PRINT_CCONTEXT_L1("Vote type: " << it->type << ", verification failed, dropping connection"); + oxen::log::info(logcat, "Vote type: {}, verification failed, dropping connection", it->type); drop_connection(context, false /*add_fail*/, false /*flush_all_spans i.e. delete cached block data from this peer*/); return 1; } @@ -955,7 +900,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_request_fluffy_missing_tx(int command, NOTIFY_REQUEST_FLUFFY_MISSING_TX::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_FLUFFY_MISSING_TX (" << arg.missing_tx_indices.size() << " txes), block hash " << arg.block_hash); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_FLUFFY_MISSING_TX ({} txes), block hash {}", arg.missing_tx_indices.size(), arg.block_hash); std::vector> local_blocks; std::vector local_txs; @@ -963,7 +908,7 @@ namespace cryptonote block b; if (!m_core.get_block_by_hash(arg.block_hash, b)) { - LOG_ERROR_CCONTEXT("failed to find block: " << arg.block_hash << ", dropping connection"); + oxen::log::error(logcat, "failed to find block: {}, dropping connection", arg.block_hash); drop_connection(context, false, false); return 1; } @@ -982,14 +927,7 @@ namespace cryptonote { if (!requested_index_set.insert(requested_index).second) { - LOG_ERROR_CCONTEXT - ( - "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX" - << ", request is asking for the same tx index more than once " - << ", tx index = " << requested_index << ", block tx count " << b.tx_hashes.size() - << ", block_height = " << arg.current_blockchain_height - << ", dropping connection" - ); + oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for the same tx index more than once, tx index = {}, block tx count {}, block_height = {}, dropping connection", requested_index, b.tx_hashes.size(), arg.current_blockchain_height); drop_connection(context, false, false); return 1; @@ -1001,19 +939,12 @@ namespace cryptonote { if(tx_idx < b.tx_hashes.size()) { - MDEBUG(" tx " << b.tx_hashes[tx_idx]); + oxen::log::debug(logcat, " tx {}", b.tx_hashes[tx_idx]); txids.push_back(b.tx_hashes[tx_idx]); } else { - LOG_ERROR_CCONTEXT - ( - "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX" - << ", request is asking for a tx whose index is out of bounds " - << ", tx index = " << tx_idx << ", block tx count " << b.tx_hashes.size() - << ", block_height = " << arg.current_blockchain_height - << ", dropping connection" - ); + oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for a tx whose index is out of bounds, tx index = {}, block tx count {}, block_height = {}, dropping connection ", tx_idx, b.tx_hashes.size(), arg.current_blockchain_height); drop_connection(context, false, false); return 1; @@ -1024,15 +955,13 @@ namespace cryptonote std::unordered_set missed; if (!m_core.get_transactions(txids, txs, &missed)) { - LOG_ERROR_CCONTEXT("Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, " - << "failed to get requested transactions"); + oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, failed to get requested transactions"); drop_connection(context, false, false); return 1; } if (!missed.empty() || txs.size() != txids.size()) { - LOG_ERROR_CCONTEXT("Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, " - << missed.size() << " requested transactions not found" << ", dropping connection"); + oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, {} requested transactions not found, dropping connection", missed.size()); drop_connection(context, false, false); return 1; } @@ -1042,12 +971,7 @@ namespace cryptonote fluffy_response.b.txs.push_back(t_serializable_object_to_blob(tx)); } - MLOG_P2P_MESSAGE - ( - "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: " - << ", txs.size()=" << fluffy_response.b.txs.size() - << ", rsp.current_blockchain_height=" << fluffy_response.current_blockchain_height - ); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: txs.size()={}, rsp.current_blockchain_height={}", fluffy_response.b.txs.size(), fluffy_response.current_blockchain_height); post_notify(fluffy_response, context); return 1; @@ -1056,9 +980,16 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_transactions(int command, NOTIFY_NEW_TRANSACTIONS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_NEW_TRANSACTIONS (" << arg.txs.size() << " txes w/ " << arg.blinks.size() << " blinks)"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_TRANSACTIONS ({} txes w/ {} blinks)", arg.txs.size(), arg.blinks.size()); for (const auto &blob: arg.txs) - MLOGIF_P2P_MESSAGE(cryptonote::transaction tx; crypto::hash hash; bool ret = cryptonote::parse_and_validate_tx_from_blob(blob, tx, hash);, ret, "Including transaction " << hash); + if(OXEN_LOG_ENABLED(info)) + { + cryptonote::transaction tx; + crypto::hash hash; + bool ret = cryptonote::parse_and_validate_tx_from_blob(blob, tx, hash); + if (ret) + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Including transaction {}", hash); + } if(context.m_state != cryptonote_connection_context::state_normal) return 1; @@ -1069,7 +1000,7 @@ namespace cryptonote bool syncing = !is_synchronized(); if((syncing && !arg.requested) || m_no_sync) { - LOG_DEBUG_CC(context, "Received new tx while syncing, ignored"); + oxen::log::debug(logcat, "{}Received new tx while syncing, ignored", context); return 1; } @@ -1119,7 +1050,7 @@ namespace cryptonote if (blink_rollback_height > 0) { - MDEBUG("after handling parsed txes we need to rollback to height: " << blink_rollback_height); + oxen::log::debug(logcat, "after handling parsed txes we need to rollback to height: {}", blink_rollback_height); // We need to clear back to and including block at height blink_rollback_height (so that the // new blockchain "height", i.e. of current top_block_height+1, is blink_rollback_height). auto &blockchain = m_core.get_blockchain_storage(); @@ -1129,13 +1060,13 @@ namespace cryptonote immutable = blockchain.get_immutable_height(); if (immutable >= blink_rollback_height) { - MWARNING("blink rollback specified a block at or before the immutable height; we can only roll back to the immutable height."); + oxen::log::warning(logcat, "blink rollback specified a block at or before the immutable height; we can only roll back to the immutable height."); blink_rollback_height = immutable + 1; } if (blink_rollback_height < height) m_core.get_blockchain_storage().blink_rollback(blink_rollback_height); else - MDEBUG("Nothing to roll back"); + oxen::log::debug(logcat, "Nothing to roll back"); } } @@ -1152,7 +1083,7 @@ namespace cryptonote // so don't drop the connection). if (!syncing && (!all_okay || bad_blinks)) { - LOG_PRINT_CCONTEXT_L1((!all_okay && bad_blinks ? "Tx and Blink" : !all_okay ? "Tx" : "Blink") << " verification(s) failed, dropping connection"); + oxen::log::info(logcat, "{} verification(s) failed, dropping connection", (!all_okay && bad_blinks ? "Tx and Blink" : !all_okay ? "Tx" : "Blink")); drop_connection(context, false, false); } @@ -1162,13 +1093,10 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_request_get_blocks(int command, NOTIFY_REQUEST_GET_BLOCKS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_GET_BLOCKS (" << arg.blocks.size() << " blocks)"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_BLOCKS ({} blocks)", arg.blocks.size()); if (arg.blocks.size() > CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT) { - LOG_ERROR_CCONTEXT( - "Requested blocks count is too big (" - << arg.blocks.size() << ") expected not more than " - << CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT); + oxen::log::error(logcat, "Requested blocks count is too big ({}) expected not more than {}", arg.blocks.size(), CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT); drop_connection(context, false, false); return 1; } @@ -1176,12 +1104,11 @@ namespace cryptonote NOTIFY_RESPONSE_GET_BLOCKS::request rsp; if(!m_core.get_blockchain_storage().handle_get_blocks(arg, rsp)) { - LOG_ERROR_CCONTEXT("failed to handle request NOTIFY_REQUEST_GET_BLOCKS, dropping connection"); + oxen::log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_BLOCKS, dropping connection"); drop_connection(context, false, false); return 1; } - MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_GET_BLOCKS: blocks.size()=" << rsp.blocks.size() - << ", rsp.m_current_blockchain_height=" << rsp.current_blockchain_height << ", missed_ids.size()=" << rsp.missed_ids.size()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_GET_BLOCKS: blocks.size()={}, rsp.m_current_blockchain_height={}, missed_ids.size()={}", rsp.blocks.size(), rsp.current_blockchain_height, rsp.missed_ids.size()); post_notify(rsp, context); return 1; } @@ -1191,8 +1118,8 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_response_get_blocks(int command, NOTIFY_RESPONSE_GET_BLOCKS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_GET_BLOCKS (" << arg.blocks.size() << " blocks)"); - MLOG_PEER_STATE("received blocks"); + oxen::log::debug(logcat, "Received NOTIFY_RESPONSE_GET_BLOCKS ({} blocks)", arg.blocks.size()); + oxen::log::debug(oxen::log::Cat("net.p2p.msg"), "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received blocks", cryptonote::get_protocol_state_string(context.m_state)); auto request_time = *context.m_last_request_time; context.m_last_request_time.reset(); @@ -1220,12 +1147,11 @@ namespace cryptonote } ++m_sync_spans_downloaded; m_sync_download_objects_size += size; - MDEBUG(context << " downloaded " << size << " bytes worth of blocks"); + oxen::log::debug(logcat, "{} downloaded {} bytes worth of blocks", context, size); if(context.m_last_response_height > arg.current_blockchain_height) { - LOG_ERROR_CCONTEXT("sent wrong NOTIFY_GET_BLOCKS: arg.m_current_blockchain_height=" << arg.current_blockchain_height - << " < m_last_response_height=" << context.m_last_response_height << ", dropping connection"); + oxen::log::error(logcat, "sent wrong NOTIFY_GET_BLOCKS: arg.m_current_blockchain_height={} < m_last_response_height={}, dropping connection", arg.current_blockchain_height, context.m_last_response_height); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1250,16 +1176,14 @@ namespace cryptonote crypto::hash block_hash; if(!parse_and_validate_block_from_blob(block_entry.block, b, block_hash)) { - LOG_ERROR_CCONTEXT("sent wrong block: failed to parse and validate block: " - << oxenc::to_hex(block_entry.block) << ", dropping connection"); + oxen::log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(block_entry.block)); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } if (b.miner_tx.vin.size() != 1 || !std::holds_alternative(b.miner_tx.vin.front())) { - LOG_ERROR_CCONTEXT("sent wrong block: block: miner tx does not have exactly one txin_gen input" - << oxenc::to_hex(block_entry.block) << ", dropping connection"); + oxen::log::error(logcat, "sent wrong block: block: miner tx does not have exactly one txin_gen input {}, dropping connection", oxenc::to_hex(block_entry.block)); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1270,16 +1194,14 @@ namespace cryptonote auto req_it = context.m_requested_objects.find(block_hash); if(req_it == context.m_requested_objects.end()) { - LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id=" << tools::type_to_hex(get_blob_hash(block_entry.block)) - << " wasn't requested, dropping connection"); + oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={} wasn't requested, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block))); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } if(b.tx_hashes.size() != block_entry.txs.size()) { - LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id=" << tools::type_to_hex(get_blob_hash(block_entry.block)) - << ", tx_hashes.size()=" << b.tx_hashes.size() << " mismatch with block_complete_entry.m_txs.size()=" << block_entry.txs.size() << ", dropping connection"); + oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={}, tx_hashes.size()= {} mismatch with block_complete_entry.m_txs.size()= {}, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block)), b.tx_hashes.size(), block_entry.txs.size()); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1291,22 +1213,19 @@ namespace cryptonote if(!context.m_requested_objects.empty()) { - MERROR(context << "returned not all requested objects (context.m_requested_objects.size()=" - << context.m_requested_objects.size() << "), dropping connection"); + oxen::log::error(logcat, "{}returned not all requested objects (context.m_requested_objects.size()={}), dropping connection", context, context.m_requested_objects.size()); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } { - MLOG_YELLOW(el::Level::Debug, context << " Got NEW BLOCKS inside of " << __FUNCTION__ << ": size: " << arg.blocks.size() - << ", blocks: " << start_height << " - " << (start_height + arg.blocks.size() - 1) << - " (pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << ")"); + oxen::log::debug(globallogcat, fmt::format(fg(fmt::terminal_color::yellow), "{} Got NEW BLOCKS inside of {}: size: {}, blocks: {} - {} (pruning seed {})", context, __FUNCTION__, arg.blocks.size(), start_height, (start_height + arg.blocks.size() - 1), epee::string_tools::to_string_hex(context.m_pruning_seed))); // add that new span to the block queue seconds_f dt = now - request_time; const double rate = size / dt.count(); - MDEBUG(context << " adding span: " << arg.blocks.size() << " at height " << start_height << ", " << dt.count() << " seconds, " << (rate/1024) << " kB/s, size now " << (m_block_queue.get_data_size() + blocks_size) / 1048576.f << " MB"); + oxen::log::debug(logcat, "{} adding span: {} at height {}, {} seconds, {} kB/s, size now {} MB", context, arg.blocks.size(), start_height, dt.count(), (rate/1024), (m_block_queue.get_data_size() + blocks_size) / 1048576.f); m_block_queue.add_blocks(start_height, arg.blocks, context.m_connection_id, rate, blocks_size); const crypto::hash last_block_hash = cryptonote::get_block_hash(b); @@ -1380,19 +1299,17 @@ namespace cryptonote const std::unique_lock sync{m_sync_lock, std::try_to_lock}; if (!sync) { - MINFO(context << "Failed to lock m_sync_lock, going back to download"); + oxen::log::debug(logcat, "{}Failed to lock m_sync_lock, going back to download", context); goto skip; } - MDEBUG(context << " lock m_sync_lock, adding blocks to chain..."); - MLOG_PEER_STATE("adding blocks"); + oxen::log::debug(logcat, "{} lock m_sync_lock, adding blocks to chain...", context); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "adding blocks", cryptonote::get_protocol_state_string(context.m_state)); { m_core.pause_mine(); - m_add_timer.resume(); bool starting = true; OXEN_DEFER { - m_add_timer.pause(); m_core.resume_mine(); if (!starting) m_last_add_end_time = std::chrono::steady_clock::now(); }; @@ -1405,39 +1322,38 @@ namespace cryptonote boost::uuids::uuid span_connection_id; if (!m_block_queue.get_next_span(start_height, blocks, span_connection_id)) { - MDEBUG(context << " no next span found, going back to download"); + oxen::log::debug(logcat, "{} no next span found, going back to download", context); break; } if (blocks.empty()) { - MERROR(context << "Next span has no blocks"); + oxen::log::error(logcat, "{}Next span has no blocks", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } - MDEBUG(context << " next span in the queue has blocks " << start_height << "-" << (start_height + blocks.size() - 1) - << ", we need " << previous_height); + oxen::log::debug(logcat, "{} next span in the queue has blocks {}-{}, we need {}", context, start_height, (start_height + blocks.size() - 1), previous_height); block new_block; crypto::hash last_block_hash; if (!parse_and_validate_block_from_blob(blocks.back().block, new_block, last_block_hash)) { - MERROR(context << "Failed to parse block, but it should already have been parsed"); + oxen::log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } if (m_core.have_block(last_block_hash)) { const uint64_t subchain_height = start_height + blocks.size(); - LOG_DEBUG_CC(context, "These are old blocks, ignoring: blocks " << start_height << " - " << (subchain_height-1) << ", blockchain height " << m_core.get_current_blockchain_height()); + oxen::log::debug(logcat, "{}{} - {}, blockchain height {}", context, "These are old blocks, ignoring: blocks ", start_height, (subchain_height-1), m_core.get_current_blockchain_height()); m_block_queue.remove_spans(span_connection_id, start_height); ++m_sync_old_spans_downloaded; continue; } if (!parse_and_validate_block_from_blob(blocks.front().block, new_block)) { - MERROR(context << "Failed to parse block, but it should already have been parsed"); + oxen::log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } @@ -1460,20 +1376,20 @@ namespace cryptonote { if (should_drop_connection(context, get_next_needed_pruning_stripe().first)) { - MDEBUG(context << "Got block with unknown parent which was not requested, but peer does not have that block - dropping connection"); + oxen::log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - dropping connection", context); if (!context.m_is_income) m_p2p->add_used_stripe_peer(context); drop_connection(context, false, true); return 1; } - MDEBUG(context << "Got block with unknown parent which was not requested, but peer does not have that block - back to download"); + oxen::log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - back to download", context); goto skip; } // this can happen if a connection was sicced onto a late span, if it did not have those blocks, // since we don't know that at the sic time - LOG_ERROR_CCONTEXT("Got block with unknown parent which was not requested - querying block hashes"); + oxen::log::error(logcat, "Got block with unknown parent which was not requested - querying block hashes"); m_block_queue.remove_spans(span_connection_id, start_height); context.m_needed_objects.clear(); context.m_last_response_height = 0; @@ -1481,7 +1397,7 @@ namespace cryptonote } // parent was requested, so we wait for it to be retrieved - MINFO(context << " parent was requested, we'll get back to it"); + oxen::log::debug(logcat, "{} parent was requested, we'll get back to it", context); break; } @@ -1490,17 +1406,14 @@ namespace cryptonote if (starting) { starting = false; - if (m_last_add_end_time) - { - auto elapsed = std::chrono::steady_clock::now() - *m_last_add_end_time; - MINFO("Restarting adding block after idle for " << tools::friendly_duration(elapsed)); - } + auto elapsed = std::chrono::steady_clock::now() - m_last_add_end_time; + oxen::log::debug(logcat, "Restarting adding block after idle for {} seconds", tools::friendly_duration(elapsed)); } std::vector pblocks; if (!m_core.prepare_handle_incoming_blocks(blocks, pblocks)) { - LOG_ERROR_CCONTEXT("Failure in prepare_handle_incoming_blocks"); + oxen::log::error(logcat, "Failure in prepare_handle_incoming_blocks"); return 1; } @@ -1509,7 +1422,7 @@ namespace cryptonote OXEN_DEFER { if (!m_core.cleanup_handle_incoming_blocks()) - LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks"); + oxen::log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it if (remove_spans) @@ -1518,7 +1431,7 @@ namespace cryptonote if (!pblocks.empty() && pblocks.size() != blocks.size()) { - LOG_ERROR_CCONTEXT("Internal error: blocks.size() != block_entry.txs.size()"); + oxen::log::error(logcat, "Internal error: blocks.size() != block_entry.txs.size()"); return 1; } @@ -1542,12 +1455,11 @@ namespace cryptonote if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool{ cryptonote::transaction tx; parse_and_validate_tx_from_blob(block_entry.txs[i], tx); // must succeed if we got here - LOG_ERROR_CCONTEXT("transaction verification failed on NOTIFY_RESPONSE_GET_BLOCKS, tx_id = " - << tools::type_to_hex(cryptonote::get_transaction_hash(tx)) << ", dropping connection"); + oxen::log::error(logcat, "transaction verification failed on NOTIFY_RESPONSE_GET_BLOCKS, tx_id = {}, dropping connection", tools::type_to_hex(cryptonote::get_transaction_hash(tx))); drop_connection(context, false, true); return 1; })) - LOG_ERROR_CCONTEXT("span connection id not found"); + oxen::log::error(logcat, "span connection id not found"); remove_spans = true; return 1; @@ -1568,7 +1480,7 @@ namespace cryptonote if (!t_serializable_object_from_blob(checkpoint_allocated_on_stack_, block_entry.checkpoint)) { - MERROR("Checkpoint blob available but failed to parse"); + oxen::log::error(logcat, "Checkpoint blob available but failed to parse"); return false; } @@ -1585,16 +1497,16 @@ namespace cryptonote if (bvc.m_verifivation_failed || bvc.m_marked_as_orphaned) { if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool{ - char const *ERR_MSG = + std::string const err_msg = bvc.m_verifivation_failed ? "Block verification failed, dropping connection" : "Block received at sync phase was marked as orphaned, dropping connection"; - LOG_PRINT_CCONTEXT_L1(ERR_MSG); + oxen::log::info(logcat, err_msg); drop_connection(context, true, true); return 1; })) - LOG_ERROR_CCONTEXT("span connection id not found"); + oxen::log::error(logcat, "span connection id not found"); remove_spans = true; return 1; @@ -1606,10 +1518,13 @@ namespace cryptonote } // each download block remove_spans = true; - MDEBUG(context << "Block process time (" << blocks.size() << " blocks, " << num_txs << " txs): " << - tools::friendly_duration(block_process_time_full + transactions_process_time_full) << " (" << - tools::friendly_duration(transactions_process_time_full) << "+" << - tools::friendly_duration(block_process_time_full) << ")"); + oxen::log::debug(logcat, "{}Block process time ({} blocks, {} txs): {} ({}/{})", + context, + blocks.size(), + num_txs, + tools::friendly_duration(block_process_time_full + transactions_process_time_full), + tools::friendly_duration(transactions_process_time_full), + tools::friendly_duration(block_process_time_full)); } const uint64_t current_blockchain_height = m_core.get_current_blockchain_height(); @@ -1638,23 +1553,22 @@ namespace cryptonote const uint32_t previous_stripe = tools::get_pruning_stripe(previous_height, target_blockchain_height, PRUNING_LOG_STRIPES); const uint32_t current_stripe = tools::get_pruning_stripe(current_blockchain_height, target_blockchain_height, PRUNING_LOG_STRIPES); std::string timing_message = ""; - if (ELPP->vRegistry()->allowed(el::Level::Info, "sync-info")) + if (OXEN_LOG_ENABLED(info)) timing_message = std::string(" (") + std::to_string(dt.count()) + " sec, " + std::to_string((current_blockchain_height - previous_height) / dt.count()) + " blocks/sec), " + std::to_string(m_block_queue.get_data_size() / 1048576.f) + " MB queued in " + std::to_string(m_block_queue.get_num_filled_spans()) + " spans, stripe " + std::to_string(previous_stripe) + " -> " + std::to_string(current_stripe); - if (ELPP->vRegistry()->allowed(el::Level::Debug, "sync-info")) + if (OXEN_LOG_ENABLED(debug)) timing_message += std::string(": ") + m_block_queue.get_overview(current_blockchain_height); - MGINFO_YELLOW("Synced " << current_blockchain_height << "/" << target_blockchain_height - << progress_message << timing_message); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {}/{} {} {}", current_blockchain_height, target_blockchain_height, progress_message, timing_message)); if (previous_stripe != current_stripe) notify_new_stripe(context, current_stripe); } } } - MLOG_PEER_STATE("stopping adding blocks"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "stopping adding blocks", cryptonote::get_protocol_state_string(context.m_state)); if (should_download_next_span(context, false)) { @@ -1674,7 +1588,7 @@ namespace cryptonote skip: if (!request_missing_objects(context, true, force_next_span)) { - LOG_ERROR_CCONTEXT("Failed to request missing objects, dropping connection"); + oxen::log::error(logcat, "Failed to request missing objects, dropping connection"); drop_connection(context, false, false); return 1; } @@ -1694,10 +1608,10 @@ skip: if (stripe && peer_stripe && peer_stripe != stripe) return true; context.m_state = cryptonote_connection_context::state_synchronizing; - LOG_PRINT_CCONTEXT_L2("requesting callback"); + oxen::log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); - MLOG_PEER_STATE("requesting callback"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); } return true; }); @@ -1708,12 +1622,11 @@ skip: template int t_cryptonote_protocol_handler::handle_request_get_txs(int command, NOTIFY_REQUEST_GET_TXS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_GET_TXS (" << arg.txs.size() << " txs)"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_TXS ({} txs)", arg.txs.size()); if (arg.txs.size() > CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT) { - LOG_ERROR_CCONTEXT( - "Requested txs count is too big (" << arg.txs.size() << ") expected not more than " << CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); + oxen::log::error(logcat, "Requested txs count is too big ({}) expected not mroe than {}", arg.txs.size(), CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); drop_connection(context, false, false); return 1; } @@ -1722,11 +1635,11 @@ skip: rsp.requested = true; if(!m_core.get_blockchain_storage().handle_get_txs(arg, rsp)) { - LOG_ERROR_CCONTEXT("failed to handle request NOTIFY_REQUEST_GET_TXS, dropping connection"); + oxen::log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_TXS, dropping connection"); drop_connection(context, false, false); return 1; } - MLOG_P2P_MESSAGE("-->>NOTIFY_NEW_TRANSACTIONS: requested=true, txs[" << rsp.txs.size() << "], blinks[" << rsp.blinks.size() << "]"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_NEW_TRANSACTIONS: requested=true, txs[{}], blinks[{}]", rsp.txs.size(), rsp.blinks.size()); post_notify(rsp, context); return 1; } @@ -1743,7 +1656,7 @@ skip: template bool t_cryptonote_protocol_handler::kick_idle_peers() { - MTRACE("Checking for idle peers..."); + oxen::log::trace(logcat, "Checking for idle peers..."); m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool { if (context.m_state == cryptonote_connection_context::state_synchronizing && context.m_last_request_time) @@ -1751,8 +1664,8 @@ skip: const auto dt = std::chrono::steady_clock::now() - *context.m_last_request_time; if (dt > IDLE_PEER_KICK_TIME) { - MINFO(context << " kicking idle peer, last update " << seconds_f{dt}.count() << " seconds ago"); - LOG_PRINT_CCONTEXT_L2("requesting callback"); + oxen::log::info(logcat, "{} kicking idle peer, last update {} seconds ago", context, seconds_f{dt}.count()); + oxen::log::debug(logcat, "requesting callback"); context.m_last_request_time.reset(); context.m_state = cryptonote_connection_context::state_standby; // we'll go back to adding, then (if we can't), download ++context.m_callback_request_count; @@ -1772,7 +1685,7 @@ skip: if (target > height) // if we're not synced yet, don't do it return true; - MTRACE("Checking for outgoing syncing peers..."); + oxen::log::trace(logcat, "Checking for outgoing syncing peers..."); unsigned n_syncing = 0, n_synced = 0; boost::uuids::uuid last_synced_peer_id(boost::uuids::nil_uuid()); m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool @@ -1789,17 +1702,17 @@ skip: } return true; }); - MTRACE(n_syncing << " syncing, " << n_synced << " synced"); + oxen::log::trace(logcat, "{} syncing, {} synced", n_syncing, n_synced); // if we're at max out peers, and not enough are syncing if (n_synced + n_syncing >= m_max_out_peers && n_syncing < p2p::DEFAULT_SYNC_SEARCH_CONNECTIONS_COUNT && last_synced_peer_id != boost::uuids::nil_uuid()) { if (!m_p2p->for_connection(last_synced_peer_id, [&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id)->bool{ - MINFO(ctx << "dropping synced peer, " << n_syncing << " syncing, " << n_synced << " synced"); + oxen::log::debug(logcat, "{}dropping synced peer, {} syncing, {} synced", ctx, n_syncing, n_synced); drop_connection(ctx, false, false); return true; })) - MDEBUG("Failed to find peer we wanted to drop"); + oxen::log::debug(logcat, "Failed to find peer we wanted to drop"); } return true; @@ -1812,7 +1725,7 @@ skip: { if (context.m_state == cryptonote_connection_context::state_standby) { - LOG_PRINT_CCONTEXT_L2("requesting callback"); + oxen::log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); } @@ -1824,15 +1737,15 @@ skip: template int t_cryptonote_protocol_handler::handle_request_chain(int command, NOTIFY_REQUEST_CHAIN::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_CHAIN (" << arg.block_ids.size() << " blocks"); + oxen::log::debug(logcat, "Received NOTIFY_REQUEST_CHAIN ({} blocks)", arg.block_ids.size()); NOTIFY_RESPONSE_CHAIN_ENTRY::request r; if(!m_core.find_blockchain_supplement(arg.block_ids, r)) { - LOG_ERROR_CCONTEXT("Failed to handle NOTIFY_REQUEST_CHAIN."); + oxen::log::error(logcat, "Failed to handle NOTIFY_REQUEST_CHAIN."); drop_connection(context, false, false); return 1; } - MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height=" << r.start_height << ", m_total_height=" << r.total_height << ", m_block_ids.size()=" << r.m_block_ids.size()); + oxen::log::debug(logcat, "-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height={}, m_total_height={}, m_block_ids.size()={}", r.start_height, r.total_height, r.m_block_ids.size()); post_notify(r, context); return 1; } @@ -1854,7 +1767,7 @@ skip: { if (!m_block_queue.has_next_span(blockchain_height, filled, request_time, connection_id)) { - MDEBUG(context << " we should download it as no peer reserved it"); + oxen::log::debug(logcat, "{} we should download it as no peer reserved it", context); return true; } if (!filled) @@ -1862,7 +1775,7 @@ skip: const auto dt = now - request_time; if (dt >= REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD) { - MDEBUG(context << " we should download it as it's not been received yet after " << seconds_f{dt}.count()); + oxen::log::debug(logcat, "{} we should download it as it's not been received yet after {}", context, seconds_f{dt}.count()); return true; } @@ -1878,7 +1791,7 @@ skip: const bool stalled = last_activity > LAST_ACTIVITY_STALL_THRESHOLD; if (stalled) { - MDEBUG(context << " we should download it as the downloading peer is stalling for " << seconds_f{last_activity}.count() << " seconds"); + oxen::log::debug(logcat, "{} we should download it as the downloading peer is stalling for {} seconds", context, seconds_f{last_activity}.count()); download = true; return true; } @@ -1906,8 +1819,7 @@ skip: } if (dl_speed * .8f > ctx.m_current_speed_down * multiplier) { - MDEBUG(context << " we should download it as we are substantially faster (" << dl_speed << " vs " - << ctx.m_current_speed_down << ", multiplier " << multiplier << " after " << seconds_f{dt}.count() << " seconds)"); + oxen::log::debug(logcat, "{} we should download it as we are substantially faster ({} vs {}, multiplier {} after {} seconds)", context, dl_speed, ctx.m_current_speed_down, multiplier, seconds_f{dt}.count()); download = true; return true; } @@ -1919,7 +1831,7 @@ skip: } else { - MWARNING(context << " we should download it as the downloading peer is unexpectedly not known to us"); + oxen::log::warning(logcat, "{} we should download it as the downloading peer is unexpectedly not known to us", context); return true; } } @@ -1934,19 +1846,19 @@ skip: { if (context.m_anchor) { - MDEBUG(context << "This is an anchor peer, not dropping"); + oxen::log::debug(logcat, "{}This is an anchor peer, not dropping", context); return false; } if (context.m_pruning_seed == 0) { - MDEBUG(context << "This peer is not striped, not dropping"); + oxen::log::debug(logcat, "{}This peer is not striped, not dropping", context); return false; } const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed); if (next_stripe == peer_stripe) { - MDEBUG(context << "This peer has needed stripe " << peer_stripe << ", not dropping"); + oxen::log::debug(logcat, "{}This peer has needed stripe {}, not dropping", context, peer_stripe); return false; } @@ -1955,7 +1867,7 @@ skip: const uint64_t next_available_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1; if (tools::has_unpruned_block(next_available_block_height, context.m_remote_blockchain_height, context.m_pruning_seed)) { - MDEBUG(context << "This peer has unpruned next block at height " << next_available_block_height << ", not dropping"); + oxen::log::debug(logcat, "{}This peer has unpruned next block at height {}, not dropping", context, next_available_block_height); return false; } } @@ -1973,13 +1885,11 @@ skip: const uint32_t distance = (peer_stripe + (1<= m_max_out_peers && n_peers_on_next_stripe == 0) || (distance > 1 && n_peers_on_next_stripe <= 2) || distance > 2) { - MDEBUG(context << "we want seed " << next_stripe << ", and either " << n_out_peers << " is at max out peers (" - << m_max_out_peers << ") or distance " << distance << " from " << next_stripe << " to " << peer_stripe << - " is too large and we have only " << n_peers_on_next_stripe << " peers on next seed, dropping connection to make space"); + oxen::log::debug(logcat, "{}we want seed {}, and either {} is at max out peers ({}) or distance {} from {} to {} is too large and we have only {} peers on next seed, dropping connection to make space", context, next_stripe, n_out_peers, m_max_out_peers, distance, next_stripe, peer_stripe, n_peers_on_next_stripe); return true; } } - MDEBUG(context << "End of checks, not dropping"); + oxen::log::debug(logcat, "{}End of checks, not dropping", context); return false; } //------------------------------------------------------------------------------------------------------------------------ @@ -1998,7 +1908,7 @@ skip: } if (skip > 0) { - MDEBUG(context << "skipping " << skip << "/" << context.m_needed_objects.size() << " blocks"); + oxen::log::debug(logcat, "{}skipping {}/{} blocks", context, skip, context.m_needed_objects.size()); context.m_needed_objects = std::vector(context.m_needed_objects.begin() + skip, context.m_needed_objects.end()); } } @@ -2046,20 +1956,17 @@ skip: return false; // drop outgoing connections } - MDEBUG(context << "proceed " << proceed << " (queue " << queue_proceed << ", stripe " << stripe_proceed_main << "/" << - stripe_proceed_secondary << "), " << next_needed_pruning_stripe.first << "-" << next_needed_pruning_stripe.second << - " needed, bc add stripe " << add_stripe << ", we have " << peer_stripe << "), bc_height " << bc_height); - MDEBUG(context << " - next_block_height " << next_block_height << ", seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << - ", next_needed_height "<< next_needed_height); - MDEBUG(context << " - last_response_height " << context.m_last_response_height << ", m_needed_objects size " << context.m_needed_objects.size()); + oxen::log::debug(logcat, "{}proceed {} (queue {}, stripe {}/{}), {}-{} needed, bc add stripe {}, we have {}), bc_height {}", context, proceed, queue_proceed, stripe_proceed_main, stripe_proceed_secondary, next_needed_pruning_stripe.first, next_needed_pruning_stripe.second, add_stripe, peer_stripe, bc_height); + oxen::log::debug(logcat, "{} - next_block_height {}, seed {}, next_needed_height {}", context, next_block_height, epee::string_tools::to_string_hex(context.m_pruning_seed), next_needed_height); + oxen::log::debug(logcat, "{} - last_response_height {}, m_needed_objects size {}", context, context.m_last_response_height, context.m_needed_objects.size()); // if we're waiting for next span, try to get it before unblocking threads below, // or a runaway downloading of future spans might happen if (stripe_proceed_main && should_download_next_span(context, true)) { - MDEBUG(context << " we should try for that next span too, we think we could get it faster, resuming"); + oxen::log::debug(logcat, "{} we should try for that next span too, we think we could get it faster, resuming", context); force_next_span = true; - MLOG_PEER_STATE("resuming"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); break; } @@ -2067,8 +1974,8 @@ skip: { if (context.m_state != cryptonote_connection_context::state_standby) { - LOG_DEBUG_CC(context, "Block queue is " << nspans << " and " << size << ", resuming"); - MLOG_PEER_STATE("resuming"); + oxen::log::debug(logcat, "{}{} and {}, resuming", context, "Block queue is ", nspans, size); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); } break; } @@ -2083,8 +1990,8 @@ skip: boost::uuids::uuid connection_id; if (m_block_queue.has_next_span(m_core.get_current_blockchain_height(), filled, time, connection_id) && filled) { - LOG_DEBUG_CC(context, "No other thread is adding blocks, and next span needed is ready, resuming"); - MLOG_PEER_STATE("resuming"); + oxen::log::debug(logcat, "{}No other thread is adding blocks, and next span needed is ready, resuming", context); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); context.m_state = cryptonote_connection_context::state_standby; ++context.m_callback_request_count; m_p2p->request_callback(context); @@ -2097,10 +2004,10 @@ skip: // if this has gone on for too long, drop incoming connection to guard against some wedge state if (!context.m_is_income) { - auto ns = std::chrono::steady_clock::now() - m_last_add_end_time.value_or(std::chrono::steady_clock::time_point::min()); + auto ns = std::chrono::steady_clock::now() - m_last_add_end_time; if (ns >= DROP_ON_SYNC_WEDGE_THRESHOLD) { - MDEBUG(context << "Block addition seems to have wedged, dropping connection"); + oxen::log::debug(logcat, "{}Block addition seems to have wedged, dropping connection", context); return false; } } @@ -2110,11 +2017,11 @@ skip: if (context.m_state != cryptonote_connection_context::state_standby) { if (!queue_proceed) - LOG_DEBUG_CC(context, "Block queue is " << nspans << " and " << size << ", pausing"); + oxen::log::debug(logcat, "{}{} and {}, pausing", context, "Block queue is ", nspans, size); else if (!stripe_proceed_main && !stripe_proceed_secondary) - LOG_DEBUG_CC(context, "We do not have the stripe required to download another block, pausing"); + oxen::log::debug(logcat, "{}We do not have the stripe required to download another block, pausing", context); context.m_state = cryptonote_connection_context::state_standby; - MLOG_PEER_STATE("pausing"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "pausing", cryptonote::get_protocol_state_string(context.m_state)); } return true; @@ -2122,9 +2029,7 @@ skip: context.m_state = cryptonote_connection_context::state_synchronizing; } - MDEBUG(context << " request_missing_objects: check " << check_having_blocks << ", force_next_span " << force_next_span - << ", m_needed_objects " << context.m_needed_objects.size() << " lrh " << context.m_last_response_height << ", chain " - << m_core.get_current_blockchain_height() << ", pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed)); + oxen::log::debug(logcat, "{} request_missing_objects: check {}, force_next_span {}, m_needed_objects {} lrh {}, chain {}, pruning seed {}", context, check_having_blocks, force_next_span, context.m_needed_objects.size(), context.m_last_response_height, m_core.get_current_blockchain_height(), epee::string_tools::to_string_hex(context.m_pruning_seed)); if(context.m_needed_objects.size() || force_next_span) { //we know objects that we need, request this objects @@ -2154,10 +2059,10 @@ skip: } if (span.second == 0) { - MDEBUG(context << " span size is 0"); + oxen::log::debug(logcat, "{} span size is 0", context); if (context.m_last_response_height + 1 < context.m_needed_objects.size()) { - MERROR(context << " ERROR: inconsistent context: lrh " << context.m_last_response_height << ", nos " << context.m_needed_objects.size()); + oxen::log::error(logcat, "{} ERROR: inconsistent context: lrh {}, nos {}", context, context.m_last_response_height, context.m_needed_objects.size()); context.m_needed_objects.clear(); context.m_last_response_height = 0; goto skip; @@ -2166,20 +2071,19 @@ skip: const uint64_t first_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1; span = m_block_queue.reserve_span(first_block_height, context.m_last_response_height, count_limit, context.m_connection_id, context.m_pruning_seed, context.m_remote_blockchain_height, context.m_needed_objects); - MDEBUG(context << " span from " << first_block_height << ": " << span.first << "/" << span.second); + oxen::log::debug(logcat, "{} span from {}: {}/{}", context, first_block_height, span.first, span.second); if (span.second > 0) { const uint32_t stripe = tools::get_pruning_stripe(span.first, context.m_remote_blockchain_height, PRUNING_LOG_STRIPES); if (context.m_pruning_seed && stripe != tools::get_pruning_stripe(context.m_pruning_seed)) { - MDEBUG(context << " starting early on next seed (" << span.first << " with stripe " << stripe << - ", context seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << ")"); + oxen::log::debug(logcat, "{} starting early on next seed ({} with stripe {}, context seed {})", context, span.first, stripe, epee::string_tools::to_string_hex(context.m_pruning_seed)); } } } if (span.second == 0 && !force_next_span) { - MDEBUG(context << " still no span reserved, we may be in the corner case of next span scheduled and everything else scheduled/filled"); + oxen::log::debug(logcat, "{} still no span reserved, we may be in the corner case of next span scheduled and everything else scheduled/filled", context); std::vector hashes; boost::uuids::uuid span_connection_id; span = m_block_queue.get_next_span_if_scheduled(hashes, span_connection_id); @@ -2200,7 +2104,7 @@ skip: } } } - MDEBUG(context << " span: " << span.first << "/" << span.second << " (" << span.first << " - " << (span.first + span.second - 1) << ")"); + oxen::log::debug(logcat, "{} span: {}/{} ({} - {})", context, span.first, span.second, span.first, (span.first + span.second - 1)); if (span.second > 0) { if (!is_next) @@ -2209,14 +2113,14 @@ skip: uint64_t skip = span.first - first_context_block_height; if (skip > context.m_needed_objects.size()) { - MERROR("ERROR: skip " << skip << ", m_needed_objects " << context.m_needed_objects.size() << ", first_context_block_height" << first_context_block_height); + oxen::log::error(logcat, "ERROR: skip {}, m_needed_objects {}, first_context_block_height{}", skip, context.m_needed_objects.size(), first_context_block_height); return false; } if (skip > 0) context.m_needed_objects = std::vector(context.m_needed_objects.begin() + skip, context.m_needed_objects.end()); if (context.m_needed_objects.size() < span.second) { - MERROR("ERROR: span " << span.first << "/" << span.second << ", m_needed_objects " << context.m_needed_objects.size()); + oxen::log::error(logcat, "ERROR: span {}/{}, m_needed_objects {}", span.first, span.second, context.m_needed_objects.size()); return false; } @@ -2230,11 +2134,10 @@ skip: } context.m_last_request_time = std::chrono::steady_clock::now(); - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()=" << req.blocks.size() - << "requested blocks count=" << count << " / " << count_limit << " from " << span.first << ", first hash " << req.blocks.front()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()={}, requested blocks count={} / {} from {}, first hash {}", req.blocks.size(), count, count_limit, span.first, req.blocks.front()); post_notify(req, context); - MLOG_PEER_STATE("requesting objects"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting objects", cryptonote::get_protocol_state_string(context.m_state)); return true; } @@ -2246,8 +2149,7 @@ skip: { // at this point, we have to either close the connection, or start getting blocks past the // current point, or become dormant - MDEBUG(context << "this peer is pruned at seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << - ", next stripe needed is " << next_stripe); + oxen::log::debug(logcat, "{}this peer is pruned at seed {}, next stripe needed is {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), next_stripe); if (!context.m_is_income) { if (should_drop_connection(context, next_stripe)) @@ -2258,7 +2160,7 @@ skip: } // we'll get back stuck waiting for the go ahead context.m_state = cryptonote_connection_context::state_normal; - MLOG_PEER_STATE("Nothing to do for now, switching to normal state"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "Nothing to do for now, switching to normal state", cryptonote::get_protocol_state_string(context.m_state)); return true; } } @@ -2280,8 +2182,8 @@ skip: bool filled = false; if (m_block_queue.get_next_span(start_height, blocks, span_connection_id, filled) && filled) { - LOG_DEBUG_CC(context, "No other thread is adding blocks, resuming"); - MLOG_PEER_STATE("will try to add blocks next"); + oxen::log::debug(logcat, "{}No other thread is adding blocks, resuming", context); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "will try to add blocks next", cryptonote::get_protocol_state_string(context.m_state)); context.m_state = cryptonote_connection_context::state_standby; ++context.m_callback_request_count; m_p2p->request_callback(context); @@ -2305,9 +2207,9 @@ skip: } context.m_last_request_time = std::chrono::steady_clock::now(); - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() << ", start_from_current_chain " << start_from_current_chain); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, start_from_current_chain {}", r.block_ids.size(), start_from_current_chain); post_notify(r, context); - MLOG_PEER_STATE("requesting chain"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); }else { CHECK_AND_ASSERT_MES(context.m_last_response_height == context.m_remote_blockchain_height-1 @@ -2324,13 +2226,13 @@ skip: { if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height()) { - MGINFO_GREEN("SYNCHRONIZED OK"); + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "SYNCHRONIZED OK")); on_connection_synchronized(); } } else { - MINFO(context << " we've reached this peer's blockchain height"); + oxen::log::info(logcat, "{} we've reached this peer's blockchain height", context); } } return true; @@ -2353,31 +2255,22 @@ skip: if (synced_seconds == 0s) synced_seconds = 1s; float blocks_per_second = synced_blocks / (float)synced_seconds.count(); - MGINFO_YELLOW("Synced " << synced_blocks << " blocks in " - << tools::get_human_readable_timespan(synced_seconds) << " (" << blocks_per_second << " blocks per second)"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {} blocks in {} ({} blocks per second)", synced_blocks, tools::get_human_readable_timespan(synced_seconds), blocks_per_second)); } } - MGINFO_YELLOW("\n**********************************************************************\n" - << "You are now synchronized with the network. You may now start oxen-wallet-cli.\n" - << "\n" - << "Use the \"help\" command to see the list of available commands.\n" - << "**********************************************************************"); - m_sync_timer.pause(); - if (CLOG_ENABLED(Info, "sync-info")) + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ +You are now synchronized with the network. You may now start oxen-wallet-cli.\n\ +\n\ +Use the \"help\" command to see the list of available commands.\n\ +**********************************************************************")); + if (OXEN_LOG_ENABLED(info)) { - const auto sync_time = m_sync_timer.value(); - const auto add_time = m_add_timer.value(); - if (sync_time > 0ns && add_time > 0ns) - { - MCLOG_YELLOW(el::Level::Info, "sync-info", - fmt::format("Sync time: {}, idle time {:.2f}%, {:.1f} + {:.1f} MB downloaded, {:.2f}% old spans, {:2f}% bad spans", - tools::friendly_duration(sync_time), - ((sync_time - add_time) / sync_time) * 100.0, - m_sync_download_objects_size / 1'000'000.0, - m_sync_download_chain_size / 1'000'000.0, - 100.0 * m_sync_old_spans_downloaded / m_sync_spans_downloaded, - 100.0 * m_sync_bad_spans_downloaded / m_sync_spans_downloaded)); - } + const std::chrono::duration sync_time{std::chrono::steady_clock::now() - m_sync_timer}; + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Sync time: {:.0f} min, {} + {} MB downloaded, {}% old spans, {}% bad spans", sync_time.count()/1e9/60, + (10 * m_sync_download_objects_size / 1024 / 1024) / 10.f, + (10 * m_sync_download_chain_size / 1024 / 1024) / 10.f, + 100.0f * m_sync_old_spans_downloaded / m_sync_spans_downloaded, + 100.0f * m_sync_bad_spans_downloaded / m_sync_spans_downloaded)); } m_core.on_synchronized(); } @@ -2401,9 +2294,8 @@ skip: template int t_cryptonote_protocol_handler::handle_response_chain_entry(int command, NOTIFY_RESPONSE_CHAIN_ENTRY::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()=" << arg.m_block_ids.size() - << ", m_start_height=" << arg.start_height << ", m_total_height=" << arg.total_height); - MLOG_PEER_STATE("received chain"); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()={}, m_start_height={}, m_total_height={}", arg.m_block_ids.size(), arg.start_height, arg.total_height); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received chain", cryptonote::get_protocol_state_string(context.m_state)); context.m_last_request_time.reset(); @@ -2411,21 +2303,21 @@ skip: if(!arg.m_block_ids.size()) { - LOG_ERROR_CCONTEXT("sent empty m_block_ids, dropping connection"); + oxen::log::error(logcat, "sent empty m_block_ids, dropping connection"); drop_connection(context, true, false); return 1; } if (arg.total_height < arg.m_block_ids.size() || arg.start_height > arg.total_height - arg.m_block_ids.size()) { - LOG_ERROR_CCONTEXT("sent invalid start/nblocks/height, dropping connection"); + oxen::log::error(logcat, "sent invalid start/nblocks/height, dropping connection"); drop_connection(context, true, false); return 1; } - MDEBUG(context << "first block hash " << arg.m_block_ids.front() << ", last " << arg.m_block_ids.back()); + oxen::log::debug(logcat, "{}first block hash {}, last {}", context, arg.m_block_ids.front(), arg.m_block_ids.back()); if (arg.total_height >= MAX_BLOCK_NUMBER || arg.m_block_ids.size() >= MAX_BLOCK_NUMBER) { - LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with total_height=" << arg.total_height << " and block_ids=" << arg.m_block_ids.size()); + oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with total_height={} and block_ids={}", arg.total_height, arg.m_block_ids.size()); drop_connection(context, false, false); return 1; } @@ -2433,9 +2325,7 @@ skip: context.m_last_response_height = arg.start_height + arg.m_block_ids.size()-1; if(context.m_last_response_height > context.m_remote_blockchain_height) { - LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with m_total_height=" << arg.total_height - << ", m_start_height=" << arg.start_height - << ", m_block_ids.size()=" << arg.m_block_ids.size()); + oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with m_total_height={}, m_start_height= {}, m_block_ids.size()={}", arg.total_height, arg.start_height, arg.m_block_ids.size()); drop_connection(context, false, false); return 1; } @@ -2443,7 +2333,7 @@ skip: uint64_t n_use_blocks = m_core.prevalidate_block_hashes(arg.start_height, arg.m_block_ids); if (n_use_blocks + HASH_OF_HASHES_STEP <= arg.m_block_ids.size()) { - LOG_ERROR_CCONTEXT("Most blocks are invalid, dropping connection"); + oxen::log::error(logcat, "Most blocks are invalid, dropping connection"); drop_connection(context, true, false); return 1; } @@ -2460,7 +2350,7 @@ skip: if (!request_missing_objects(context, false)) { - LOG_ERROR_CCONTEXT("Failed to request missing objects, dropping connection"); + oxen::log::error(logcat, "Failed to request missing objects, dropping connection"); drop_connection(context, false, false); return 1; } @@ -2475,12 +2365,12 @@ skip: template int t_cryptonote_protocol_handler::handle_request_block_blinks(int command, NOTIFY_REQUEST_BLOCK_BLINKS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_BLOCK_BLINKS: heights.size()=" << arg.heights.size()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_BLOCK_BLINKS: heights.size()={}", arg.heights.size()); NOTIFY_RESPONSE_BLOCK_BLINKS::request r; r.txs = m_core.get_pool().get_mined_blinks({arg.heights.begin(), arg.heights.end()}); - MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()=" << r.txs.size()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", r.txs.size()); post_notify(r, context); return 1; } @@ -2488,12 +2378,12 @@ skip: template int t_cryptonote_protocol_handler::handle_response_block_blinks(int command, NOTIFY_RESPONSE_BLOCK_BLINKS::request& arg, cryptonote_connection_context& context) { - MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()=" << arg.txs.size()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", arg.txs.size()); m_core.get_pool().keep_missing_blinks(arg.txs); if (arg.txs.empty()) { - MDEBUG("NOTIFY_RESPONSE_BLOCKS_BLINKS included only blink txes we already knew about"); + oxen::log::debug(logcat, "NOTIFY_RESPONSE_BLOCKS_BLINKS included only blink txes we already knew about"); return 1; } @@ -2508,10 +2398,10 @@ skip: arg.txs.resize(arg.txs.size() - CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); } - MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_GET_TXS: requesting for tx & blink data, txs.size()=" << req.txs.size()); + oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_TXS: requesting for tx & blink data, txs.size()={}", req.txs.size()); post_notify(req, context); } - MLOG_PEER_STATE("requesting missing blink txs"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting missing blink txs", cryptonote::get_protocol_state_string(context.m_state)); return 1; } //------------------------------------------------------------------------------------------------------------------------ @@ -2524,7 +2414,7 @@ skip: { if (peer_id && exclude_context.m_connection_id != context.m_connection_id && context.m_remote_address.get_zone() == epee::net_utils::zone::public_) { - LOG_DEBUG_CC(context, "PEER FLUFFY BLOCKS - RELAYING THIN/COMPACT WHATEVER BLOCK"); + oxen::log::debug(logcat, "{}PEER FLUFFY BLOCKS - RELAYING THIN/COMPACT WHATEVER BLOCK", context); fluffyConnections.push_back({context.m_remote_address.get_zone(), context.m_connection_id}); } return true; @@ -2542,7 +2432,7 @@ skip: // relay_block is only meant to send the header, tx blobs should be // requested subsequently in handle notify fluffy transactions - LOG_PRINT_L1("relay_block called with argument that contains TX blobs, this is the non-expected case"); + oxen::log::debug(logcat, "relay_block called with argument that contains TX blobs, this is the non-expected case"); NOTIFY_NEW_FLUFFY_BLOCK::request arg_without_tx_blobs = {}; arg_without_tx_blobs.current_blockchain_height = arg.current_blockchain_height; arg_without_tx_blobs.b.block = arg.b.block; @@ -2660,12 +2550,8 @@ skip: }); const bool use_next = (n_next > m_max_out_peers / 2 && n_subsequent <= 1) || (n_next > 2 && n_subsequent == 0); const uint32_t ret_stripe = use_next ? subsequent_pruning_stripe: next_pruning_stripe; - MIDEBUG(const std::string po = get_peers_overview(), "get_next_needed_pruning_stripe: want height " << want_height << " (" << - want_height_from_blockchain << " from blockchain, " << want_height_from_block_queue << " from block queue), stripe " << - next_pruning_stripe << " (" << n_next << "/" << m_max_out_peers << " on it and " << n_subsequent << " on " << - subsequent_pruning_stripe << ", " << n_others << " others) -> " << ret_stripe << " (+" << - (ret_stripe - next_pruning_stripe + (1 << PRUNING_LOG_STRIPES)) % (1 << PRUNING_LOG_STRIPES) << - "), current peers " << po); + const std::string po = get_peers_overview(); + oxen::log::debug(oxen::log::Cat(po), "get_next_needed_pruning_stripe: want height {} ({} from blockchain, {} from block queue), stripe {} ({}/{} on it and {} on {}, {} others) -> {} (+{}), current peers {}", want_height, want_height_from_blockchain, want_height_from_block_queue, next_pruning_stripe, n_next, m_max_out_peers, n_subsequent, subsequent_pruning_stripe, n_others, ret_stripe, (ret_stripe - next_pruning_stripe + (1 << PRUNING_LOG_STRIPES)) % (1 << PRUNING_LOG_STRIPES), po); return std::make_pair(next_pruning_stripe, ret_stripe); } //------------------------------------------------------------------------------------------------------------------------ @@ -2690,9 +2576,7 @@ skip: template void t_cryptonote_protocol_handler::drop_connection(cryptonote_connection_context &context, bool add_fail, bool flush_all_spans) { - LOG_DEBUG_CC(context, "dropping connection id " << context.m_connection_id << " (pruning seed " << - epee::string_tools::to_string_hex(context.m_pruning_seed) << - "), add_fail " << add_fail << ", flush_all_spans " << flush_all_spans); + oxen::log::debug(logcat, "{}dropping connection id {} (pruning seed {}), add_fail {}, flush_all_spans {}", context, boost::lexical_cast(context.m_connection_id), epee::string_tools::to_string_hex(context.m_pruning_seed), add_fail, flush_all_spans); if (add_fail) m_p2p->add_host_fail(context.m_remote_address); @@ -2705,7 +2589,7 @@ skip: // them before we close the connection and so might never learn of the problem. if (context.m_drop_count >= 1) { - LOG_DEBUG_CC(context, "giving connect id " << context.m_connection_id << " a second chance before dropping"); + oxen::log::debug(logcat, "{}{} a second chance before dropping", context, "giving connect id ", boost::lexical_cast(context.m_connection_id)); ++context.m_drop_count; } else @@ -2724,14 +2608,14 @@ skip: const uint64_t previous_target = m_core.get_target_blockchain_height(); if (target < previous_target) { - MINFO("Target height decreasing from " << previous_target << " to " << target); + oxen::log::info(logcat, "Target height decreasing from {} to {}", previous_target, target); m_core.set_target_blockchain_height(target); if (target == 0 && context.m_state > cryptonote_connection_context::state_before_handshake && !m_stopping) - MCWARNING("global", "oxend is now disconnected from the network"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::yellow), "oxend is now disconnected from the network")); } m_block_queue.flush_spans(context.m_connection_id, false); - MLOG_PEER_STATE("closed"); + oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "closed", cryptonote::get_protocol_state_string(context.m_state)); } //------------------------------------------------------------------------------------------------------------------------ diff --git a/src/cryptonote_protocol/levin_notify.cpp b/src/cryptonote_protocol/levin_notify.cpp index 9dfbbc1e1..4f4a1262c 100644 --- a/src/cryptonote_protocol/levin_notify.cpp +++ b/src/cryptonote_protocol/levin_notify.cpp @@ -43,11 +43,10 @@ #include "net/dandelionpp.h" #include "p2p/net_node.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net.p2p.tx" - namespace cryptonote::levin { + static auto logcat = oxen::log::Cat("net.p2p.tx"); + namespace { constexpr std::size_t connection_id_reserve_size = 100; @@ -237,7 +236,7 @@ namespace cryptonote::levin if (!channel.connection.is_nil()) channel.queue.push_back(std::move(message_)); else if (destination_ == 0 && zone_->connection_count == 0) - MWARNING("Unable to send transaction(s) over anonymity network - no available outbound connections"); + oxen::log::warning(logcat, "Unable to send transaction(s) over anonymity network - no available outbound connections"); } }; @@ -440,7 +439,7 @@ namespace cryptonote::levin auto connections = get_out_connections(*zone_->p2p); if (connections.empty()) - MWARNING("Lost all outbound connections to anonymity network - currently unable to send transaction(s)"); + oxen::log::warning(logcat, "Lost all outbound connections to anonymity network - currently unable to send transaction(s)"); zone_->strand.post(update_channels{zone_, std::move(connections)}); } @@ -554,7 +553,7 @@ namespace cryptonote::levin )}; if (MAX_FRAGMENTS * zone_->noise.size() < message.size()) { - MERROR("notify::send_txs provided message exceeding covert fragment size"); + oxen::log::error(logcat, "notify::send_txs provided message exceeding covert fragment size"); return false; } diff --git a/src/cryptonote_protocol/quorumnet.cpp b/src/cryptonote_protocol/quorumnet.cpp index 31297ad28..5bc02cdf6 100644 --- a/src/cryptonote_protocol/quorumnet.cpp +++ b/src/cryptonote_protocol/quorumnet.cpp @@ -45,11 +45,10 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "qnet" - namespace quorumnet { + static auto logcat = oxen::log::Cat("qnet"); + namespace { using namespace service_nodes; @@ -163,19 +162,18 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It for (auto it = quorum_begin; it != quorum_end; it++) candidates.insert((*it)->validators.begin(), (*it)->validators.end()); - MDEBUG("Have " << candidates.size() << " SN candidates"); + oxen::log::debug(logcat, "Have {} SN candidates", candidates.size()); std::vectorversion)>> remotes; // {x25519 pubkey, connect string, version} remotes.reserve(candidates.size()); core.get_service_node_list().for_each_service_node_info_and_proof(candidates.begin(), candidates.end(), [&remotes](const auto &pubkey, const auto &info, const auto &proof) { if (!info.is_active()) { - MTRACE("Not include inactive node " << pubkey); + oxen::log::trace(logcat, "Not include inactive node {}", pubkey); return; } if (!proof.pubkey_x25519 || !proof.proof->qnet_port || !proof.proof->public_ip) { - MTRACE("Not including node " << pubkey << ": missing x25519(" << to_hex(get_data_as_string(proof.pubkey_x25519)) << "), " - "public_ip(" << epee::string_tools::get_ip_string_from_int32(proof.proof->public_ip) << "), or qnet port(" << proof.proof->qnet_port << ")"); + oxen::log::trace(logcat, "Not including node {}: missing x25519({}), public_ip({}), or qnet port({})", pubkey, to_hex(get_data_as_string(proof.pubkey_x25519)), epee::string_tools::get_ip_string_from_int32(proof.proof->public_ip), proof.proof->qnet_port); return; } remotes.emplace_back(get_data_as_string(proof.pubkey_x25519), @@ -184,7 +182,7 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It }); // Select 4 random SNs to send the data to, but prefer SNs with newer versions because they may have network fixes. - MDEBUG("Have " << remotes.size() << " candidates after checking active status and connection details"); + oxen::log::debug(logcat, "Have {} candidates after checking active status and connection details", remotes.size()); std::vector indices(remotes.size()); std::iota(indices.begin(), indices.end(), 0); std::shuffle(indices.begin(), indices.end(), tools::rng); @@ -208,7 +206,7 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It void peer_relay_to_prepared_destinations(cryptonote::core &core, std::vector const &destinations, std::string_view command, std::string &&data) { for (auto const &[x25519_string, connect_string]: destinations) { - MINFO("Relaying data to " << to_hex(x25519_string) << " @ " << connect_string); + oxen::log::info(logcat, "Relaying data to {} @ {}", to_hex(x25519_string), connect_string); core.get_omq().send(x25519_string, command, std::move(data), send_option::hint{connect_string}); } } @@ -362,10 +360,10 @@ private: size_t i = 0; for (QuorumIt qit = qbegin; qit != qend; ++i, ++qit) { if (my_position[i] < 0) { - MTRACE("Not in subquorum " << (i == 0 ? "Q" : "Q'")); + oxen::log::trace(logcat, "Not in subquorum {}", (i == 0 ? "Q" : "Q'")); continue; } else { - MTRACE("I am in subquorum " << (i == 0 ? "Q" : "Q'") << " position " << my_position[i]); + oxen::log::trace(logcat, "I am in subquorum {} position {}", (i == 0 ? "Q" : "Q'"), my_position[i]); } auto &validators = (*qit)->validators; @@ -373,14 +371,14 @@ private: // Relay to all my outgoing targets within the quorum (connecting if not already connected) for (int j : quorum_outgoing_conns(my_position[i], validators.size())) { if (add_peer(validators[j])) - MTRACE("Relaying within subquorum " << (i == 0 ? "Q" : "Q'") << "[" << my_position[i] << "] to [" << j << "] " << validators[j]); + oxen::log::trace(logcat, "Relaying within subquorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); } // Opportunistically relay to all my *incoming* sources within the quorum *if* I already // have a connection open with them, but don't open a new connection if I don't. for (int j : quorum_incoming_conns(my_position[i], validators.size())) { if (add_peer(validators[j], false /*!strong*/)) - MTRACE("Optional opportunistic relay within quorum " << (i == 0 ? "Q" : "Q'") << "[" << my_position[i] << "] to [" << j << "] " << validators[j]); + oxen::log::trace(logcat, "Optional opportunistic relay within quorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); } // Now establish strong interconnections between quorums, if we have multiple subquorums @@ -404,13 +402,12 @@ private: if (my_position[i] >= half && my_position[i] < half*2) { int next_pos = my_position[i] - half; bool added = add_peer(next_validators[next_pos]); - MTRACE("Inter-quorum relay from Q[" << my_position[i] << "] (me) to Q'[" << next_pos << "] = " << next_validators[next_pos] - << (added ? "" : " (skipping; already relaying to that SN)")); + oxen::log::trace(logcat, "Inter-quorum relay from Q[{}] (me) to Q'[{}] = {}{}", my_position[i], next_pos, next_validators[next_pos], (added ? "" : " (skipping; already relaying to that SN)")); } else { - MTRACE("Q[" << my_position[i] << "] is not a Q -> Q' inter-quorum relay position"); + oxen::log::trace(logcat, "Q[{}] is not a Q -> Q' inter-quorum relay position", my_position[i]); } } else if (qnext != qend) { - MTRACE("Not doing inter-quorum relaying because I am in both quorums (Q[" << my_position[i] << "], Q'[" << my_position[i+1] << "])"); + oxen::log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i], my_position[i+1]); } // Exactly the same connections as above, but in reverse: the first half of Q' sends to @@ -422,13 +419,12 @@ private: if (my_position[i] < half) { int prev_pos = half + my_position[i]; bool added = add_peer(prev_validators[prev_pos]); - MTRACE("Inter-quorum relay from Q'[" << my_position[i] << "] (me) to Q[" << prev_pos << "] = " << prev_validators[prev_pos] - << (added ? "" : " (already relaying to that SN)")); + oxen::log::trace(logcat, "Inter-quorum relay from Q'[{}] (me) to Q[{}] = {}{}", my_position[i], prev_pos, prev_validators[prev_pos], (added ? "" : " (already relaying to that SN)")); } else { - MTRACE("Q'[" << my_position[i] << "] is not a Q' -> Q inter-quorum relay position"); + oxen::log::trace(logcat, "Q'[{}] is not a Q' -> Q inter-quorum relay position", my_position[i]); } } else if (qit != qbegin) { - MTRACE("Not doing inter-quorum relaying because I am in both quorums (Q[" << my_position[i-1] << "], Q'[" << my_position[i] << "])"); + oxen::log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i-1], my_position[i]); } } } @@ -437,7 +433,7 @@ private: template void relay_to_peers_impl(const std::string_view &cmd, std::array relay_data, std::index_sequence) { for (auto &peer : peers) { - MTRACE("Relaying " << cmd << " to peer " << to_hex(peer.first) << (peer.second.empty() ? " (if connected)"s : " @ " + peer.second)); + oxen::log::trace(logcat, "Relaying {} to peer {}{}", cmd, to_hex(peer.first), (peer.second.empty() ? " (if connected)"s : " @ " + peer.second)); if (peer.second.empty()) omq.send(peer.first, cmd, relay_data[I]..., send_option::optional{}); else @@ -498,47 +494,45 @@ void relay_obligation_votes(void *obj, const std::vector relayed_votes; relayed_votes.reserve(votes.size()); for (auto &vote : votes) { if (vote.type != quorum_type::obligations) { - MERROR("Internal logic error: quorumnet asked to relay a " << vote.type << " vote, but should only be called with obligations votes"); + oxen::log::error(logcat, "Internal logic error: quorumnet asked to relay a {} vote, but should only be called with obligations votes", vote.type); continue; } auto quorum = qnet.core.get_service_node_list().get_quorum(vote.type, vote.block_height); if (!quorum) { - MWARNING("Unable to relay vote: no " << vote.type << " quorum available for height " << vote.block_height); + oxen::log::warning(logcat, "Unable to relay vote: no {} quorum available for height {}", vote.type, vote.block_height); continue; } auto &quorum_voters = quorum->validators; if (quorum_voters.size() < service_nodes::min_votes_for_quorum_type(vote.type)) { - MWARNING("Invalid vote relay: " << vote.type << " quorum @ height " << vote.block_height << - " does not have enough validators (" << quorum_voters.size() << ") to reach the minimum required votes (" - << service_nodes::min_votes_for_quorum_type(vote.type) << ")"); + oxen::log::warning(logcat, "Invalid vote relay: {} quorum @ height {} does not have enough validators ({}) to reach the minimum required votes ({})", vote.type, vote.block_height, quorum_voters.size(), service_nodes::min_votes_for_quorum_type(vote.type)); continue; } peer_info pinfo{qnet, vote.type, quorum.get()}; if (!pinfo.my_position_count) { - MWARNING("Invalid vote relay: vote to relay does not include this service node"); + oxen::log::warning(logcat, "Invalid vote relay: vote to relay does not include this service node"); continue; } pinfo.relay_to_peers("quorum.vote_ob", serialize_vote(vote)); relayed_votes.push_back(vote); } - MDEBUG("Relayed " << relayed_votes.size() << " votes"); + oxen::log::debug(logcat, "Relayed {} votes", relayed_votes.size()); qnet.core.set_service_node_votes_relayed(relayed_votes); } void handle_obligation_vote(Message& m, QnetState& qnet) { - MDEBUG("Received a relayed obligation vote from " << to_hex(m.conn.pubkey())); + oxen::log::debug(logcat, "Received a relayed obligation vote from {}", to_hex(m.conn.pubkey())); if (m.data.size() != 1) { - MINFO("Ignoring vote: expected 1 data part, not " << m.data.size()); + oxen::log::info(logcat, "Ignoring vote: expected 1 data part, not {}", m.data.size()); return; } @@ -548,11 +542,11 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { auto& vote = vvote.back(); if (vote.type != quorum_type::obligations) { - MWARNING("Received invalid non-obligations vote via quorumnet; ignoring"); + oxen::log::warning(logcat, "Received invalid non-obligations vote via quorumnet; ignoring"); return; } if (vote.block_height > qnet.core.get_current_blockchain_height()) { - MDEBUG("Ignoring vote: block height " << vote.block_height << " is too high"); + oxen::log::debug(logcat, "Ignoring vote: block height {} is too high", vote.block_height); return; } @@ -560,7 +554,7 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { qnet.core.add_service_node_vote(vote, vvc); if (vvc.m_verification_failed) { - MWARNING("Vote verification failed; ignoring vote"); + oxen::log::warning(logcat, "Vote verification failed; ignoring vote"); return; } @@ -568,12 +562,12 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { relay_obligation_votes(&qnet, std::move(vvote)); } catch (const std::exception &e) { - MWARNING("Deserialization of vote from " << to_hex(m.conn.pubkey()) << " failed: " << e.what()); + oxen::log::warning(logcat, "Deserialization of vote from {} failed: {}", to_hex(m.conn.pubkey()), e.what()); } } void handle_timestamp(Message& m) { - MDEBUG("Received a timestamp request from " << to_hex(m.conn.pubkey())); + oxen::log::debug(logcat, "Received a timestamp request from {}", to_hex(m.conn.pubkey())); const time_t seconds = time(nullptr); m.send_reply(std::to_string(seconds)); } @@ -613,13 +607,13 @@ quorum_array get_blink_quorums(uint64_t blink_height, const service_node_list &s throw std::runtime_error("not enough blink nodes to form a quorum"); local_checksum += quorum_checksum(v, qi * BLINK_SUBQUORUM_SIZE); } - MTRACE("Verified enough active blink nodes for a quorum; quorum checksum: " << local_checksum); + oxen::log::trace(logcat, "Verified enough active blink nodes for a quorum; quorum checksum: {}", local_checksum); if (input_checksum) { if (*input_checksum != local_checksum) throw std::runtime_error("wrong quorum checksum: expected " + std::to_string(local_checksum) + ", received " + std::to_string(*input_checksum)); - MTRACE("Blink quorum checksum matched"); + oxen::log::trace(logcat, "Blink quorum checksum matched"); } if (output_checksum) *output_checksum = local_checksum; @@ -670,7 +664,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (position < 0 || position >= (int) validators.size()) { - MWARNING("Invalid blink signature: subquorum position is invalid"); + oxen::log::warning(logcat, "Invalid blink signature: subquorum position is invalid"); it = signatures.erase(it); } else if (btx.get_signature_status(subquorum, position) != blink_tx::signature_status::none) { it = signatures.erase(it); @@ -694,7 +688,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (!crypto::check_signature(btx.hash(approval), validators[position], signature)) { - MWARNING("Invalid blink signature: signature verification failed"); + oxen::log::warning(logcat, "Invalid blink signature: signature verification failed"); it = signatures.erase(it); continue; } @@ -711,7 +705,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & bool already_approved = btx.approved(), already_rejected = !already_approved && btx.rejected(); - MTRACE("Before recording new signatures I have existing signatures: " << debug_known_signatures(btx, blink_quorums)); + oxen::log::trace(logcat, "Before recording new signatures I have existing signatures: {}", debug_known_signatures(btx, blink_quorums)); // Now actually add them (and do one last check on them) for (auto it = signatures.begin(); it != signatures.end(); ) { @@ -725,7 +719,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (btx.add_prechecked_signature(subquorum, position, approval, signature)) { - MDEBUG("Validated and stored " << (approval ? "approval" : "rejection") << " signature for tx " << btx.get_txhash() << ", subquorum " << int{qi} << ", position " << position); + oxen::log::debug(logcat, "Validated and stored {} signature for tx {}, subquorum {}, position {}", (approval ? "approval" : "rejection"), btx.get_txhash(), int{qi}, position); ++it; } else { @@ -736,7 +730,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & } if (!signatures.empty()) { - MDEBUG("Updated signatures; now have signatures: " << debug_known_signatures(btx, blink_quorums)); + oxen::log::debug(logcat, "Updated signatures; now have signatures: {}", debug_known_signatures(btx, blink_quorums)); if (!already_approved && !already_rejected) { if (btx.approved()) { @@ -749,7 +743,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & } if (became_approved) { - MINFO("Accumulated enough signatures for blink tx: enabling tx relay"); + oxen::log::info(logcat, "Accumulated enough signatures for blink tx: enabling tx relay"); auto &pool = qnet.core.get_pool(); { auto lock = pool.blink_unique_lock(); @@ -773,8 +767,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & peer_info pinfo{qnet, quorum_type::blink, blink_quorums.begin(), blink_quorums.end(), true /*opportunistic*/, std::move(relay_exclude)}; - MDEBUG("Relaying " << signatures.size() << " blink signatures to " << pinfo.strong_peers << " (strong) + " << - (pinfo.peers.size() - pinfo.strong_peers) << " (opportunistic) blink peers"); + oxen::log::debug(logcat, "Relaying {} blink signatures to {} (strong) + {} (opportunistic blink peers)", signatures.size(), pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); bt_list i_list, p_list, r_list, s_list; for (auto &s : signatures) { @@ -796,14 +789,14 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & pinfo.relay_to_peers("quorum.blink_sign", blink_sign_data); - MTRACE("Done blink signature relay"); + oxen::log::trace(logcat, "Done blink signature relay"); if (reply_tag && reply_conn) { if (became_approved) { - MINFO("Blink tx became approved; sending result back to originating node"); + oxen::log::info(logcat, "Blink tx became approved; sending result back to originating node"); qnet.omq.send(reply_conn, "bl.good", bt_serialize(bt_dict{{"!", reply_tag}}), send_option::optional{}); } else if (became_rejected) { - MINFO("Blink tx became rejected; sending result back to originating node"); + oxen::log::info(logcat, "Blink tx became rejected; sending result back to originating node"); qnet.omq.send(reply_conn, "bl.bad", bt_serialize(bt_dict{{"!", reply_tag}}), send_option::optional{}); } } @@ -841,7 +834,7 @@ void handle_blink(Message& m, QnetState& qnet) { // message and close it. // If an outgoing connection - refuse reconnections via ZAP and just close it. - MDEBUG("Received a blink tx from " << (m.conn.sn() ? "SN " : "non-SN ") << to_hex(m.conn.pubkey())); + oxen::log::debug(logcat, "Received a blink tx from {}{}", (m.conn.sn() ? "SN " : "non-SN "), to_hex(m.conn.pubkey())); assert(qnet.core.service_node()); if (!qnet.core.service_node()) @@ -849,7 +842,7 @@ void handle_blink(Message& m, QnetState& qnet) { const auto& keys = qnet.core.get_service_keys(); if (m.data.size() != 1) { - MINFO("Rejecting blink message: expected one data entry not " << m.data.size()); + oxen::log::info(logcat, "Rejecting blink message: expected one data entry not {}", m.data.size()); // No valid data and so no reply tag; we can't send a response return; } @@ -861,7 +854,7 @@ void handle_blink(Message& m, QnetState& qnet) { auto hf_version = get_network_version(qnet.core.get_nettype(), local_height); if (hf_version < cryptonote::feature::BLINK) { - MWARNING("Rejecting blink message: blink is not available for hardfork " << (int) hf_version); + oxen::log::warning(logcat, "Rejecting blink message: blink is not available for hardfork {}", (int) hf_version); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; @@ -871,29 +864,29 @@ void handle_blink(Message& m, QnetState& qnet) { auto blink_height = get_int(data.at("h")); if (blink_height < local_height - 2) { - MINFO("Rejecting blink tx because blink auth height is too low (" << blink_height << " vs. " << local_height << ")"); + oxen::log::info(logcat, "Rejecting blink tx because blink auth height is too low ({} vs. {})", blink_height, local_height); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; } else if (blink_height > local_height + 2) { // TODO: if within some threshold (maybe 5-10?) we could hold it and process it once we are // within 2. - MINFO("Rejecting blink tx because blink auth height is too high (" << blink_height << " vs. " << local_height << ")"); + oxen::log::info(logcat, "Rejecting blink tx because blink auth height is too high ({} vs. {})", blink_height, local_height); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; } - MTRACE("Blink tx auth height " << blink_height << " is valid (local height is " << local_height << ")"); + oxen::log::trace(logcat, "Blink tx auth height {} is valid (local height is {})", blink_height, local_height); auto t_it = data.find("t"); if (t_it == data.end()) { - MINFO("Rejecting blink tx: no tx data included in request"); + oxen::log::info(logcat, "Rejecting blink tx: no tx data included in request"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "No transaction included in blink request"sv}})); return; } const std::string &tx_data = var::get(t_it->second); - MTRACE("Blink tx data is " << tx_data.size() << " bytes"); + oxen::log::trace(logcat, "Blink tx data is {} bytes", tx_data.size()); // "hash" is optional -- it lets us short-circuit processing the tx if we've already seen it, // and is added internally by SN-to-SN forwards but not the original submitter. We don't trust @@ -917,8 +910,7 @@ void handle_blink(Message& m, QnetState& qnet) { if (already_approved || already_rejected) { // Quorum approved/rejected the tx before we received the submitted blink, // reply with a bl.good/bl.bad immediately (done below, outside the lock). - MINFO("Submitted blink tx already " << (already_approved ? "approved" : "rejected") << - "; sending result back to originating node"); + oxen::log::info(logcat, "Submitted blink tx already {}; sending result back to originating node", (already_approved ? "approved" : "rejected")); } else { // We've already seen it but are still waiting on more signatures to // determine the result, so stash the tag & pubkey in the metadata to delay @@ -929,14 +921,14 @@ void handle_blink(Message& m, QnetState& qnet) { return; } } else { - MDEBUG("Already seen and forwarded this blink tx, ignoring it."); + oxen::log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); return; } } } - MTRACE("Blink tx hash: " << to_hex(tx_hash.data)); + oxen::log::trace(logcat, "Blink tx hash: {}", to_hex(tx_hash.data)); } else { - MINFO("Rejecting blink tx: invalid tx hash included in request"); + oxen::log::info(logcat, "Rejecting blink tx: invalid tx hash included in request"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid transaction hash"s}})); return; @@ -952,7 +944,7 @@ void handle_blink(Message& m, QnetState& qnet) { try { blink_quorums = get_blink_quorums(blink_height, qnet.core.get_service_node_list(), &checksum); } catch (const std::runtime_error &e) { - MINFO("Rejecting blink tx: " << e.what()); + oxen::log::info(logcat, "Rejecting blink tx: {}", e.what()); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Unable to retrieve blink quorum: "s + e.what()}})); return; @@ -963,9 +955,9 @@ void handle_blink(Message& m, QnetState& qnet) { }; if (pinfo.my_position_count > 0) - MTRACE("Found this SN in " << pinfo.my_position_count << " subquorums"); + oxen::log::trace(logcat, "Found this SN in {} subquorums", pinfo.my_position_count); else { - MINFO("Rejecting blink tx: this service node is not a member of the blink quorum!"); + oxen::log::info(logcat, "Rejecting blink tx: this service node is not a member of the blink quorum!"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Blink tx relayed to non-blink quorum member"sv}})); return; @@ -982,27 +974,27 @@ void handle_blink(Message& m, QnetState& qnet) { { crypto::hash tx_hash_actual; if (!cryptonote::parse_and_validate_tx_from_blob(tx_data, tx, tx_hash_actual)) { - MINFO("Rejecting blink tx: failed to parse transaction data"); + oxen::log::info(logcat, "Rejecting blink tx: failed to parse transaction data"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Failed to parse transaction data"sv}})); return; } - MTRACE("Successfully parsed transaction data"); + oxen::log::trace(logcat, "Successfully parsed transaction data"); if (tx_hash != tx_hash_actual) { - MINFO("Rejecting blink tx: submitted tx hash " << tx_hash << " did not match actual tx hash " << tx_hash_actual); + oxen::log::info(logcat, "Rejecting blink tx: submitted tx hash {} did not match actual tx hash {}", tx_hash, tx_hash_actual); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid transaction hash"sv}})); return; } else { - MTRACE("Pre-computed tx hash matches actual tx hash"); + oxen::log::trace(logcat, "Pre-computed tx hash matches actual tx hash"); } } // Abort if we don't have at least one strong peer to send it to. This can only happen if it's // a brand new SN (not just restarted!) that hasn't received uptime proofs before. if (!pinfo.strong_peers) { - MWARNING("Could not find connection info for any blink quorum peers. Aborting blink tx"); + oxen::log::warning(logcat, "Could not find connection info for any blink quorum peers. Aborting blink tx"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "No quorum peers are currently reachable"sv}})); return; @@ -1015,7 +1007,7 @@ void handle_blink(Message& m, QnetState& qnet) { std::unique_lock lock{qnet.mutex}; auto &bl_info = qnet.blinks[blink_height][tx_hash]; if (bl_info.btxptr) { - MDEBUG("Already seen and forwarded this blink tx, ignoring it."); + oxen::log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); return; } bl_info.btxptr = btxptr; @@ -1027,7 +1019,7 @@ void handle_blink(Message& m, QnetState& qnet) { bl_info.reply_conn = m.conn; } } - MTRACE("Accepted new blink tx for verification"); + oxen::log::trace(logcat, "Accepted new blink tx for verification"); // The submission looks good. We distribute it first, *before* we start verifying the actual tx // details, for two reasons: we want other quorum members to start verifying ASAP, and we want @@ -1046,7 +1038,7 @@ void handle_blink(Message& m, QnetState& qnet) { {"t", tx_data}, {"#", tx_hash_str}, }; - MDEBUG("Relaying blink tx to " << pinfo.strong_peers << " strong and " << (pinfo.peers.size() - pinfo.strong_peers) << " opportunistic blink peers"); + oxen::log::debug(logcat, "Relaying blink tx to {} strong and {} opportunistic blink peers", pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); pinfo.relay_to_peers("blink.submit", blink_data); } @@ -1058,15 +1050,15 @@ void handle_blink(Message& m, QnetState& qnet) { max = tx.get_max_version_for_hf(hf_version); if (tx.version < min || tx.version > max) { approved = false; - MINFO("Blink TX " << tx_hash << " rejected because TX version " << tx.version << " invalid: TX version not between " << min << " and " << max); + oxen::log::info(logcat, "Blink TX {} rejected because TX version {} invalid: TX version not between {} and {}", tx_hash, tx.version, min, max); } else { bool already_in_mempool; cryptonote::tx_verification_context tvc = {}; approved = qnet.core.get_pool().add_new_blink(btxptr, tvc, already_in_mempool); - MINFO("Blink TX " << tx_hash << (approved ? " approved and added to mempool" : " rejected")); + oxen::log::info(logcat, "Blink TX {}{}", tx_hash, (approved ? " approved and added to mempool" : " rejected")); if (!approved) - MDEBUG("TX rejected because: " << print_tx_verification_context(tvc)); + oxen::log::debug(logcat, "TX rejected because: {}", print_tx_verification_context(tvc)); } auto hash_to_sign = btx.hash(approved); @@ -1129,7 +1121,7 @@ crypto::signature convert_string_view_bytes_to_signature(std::string_view sig_st /// /// Signatures will be forwarded if new; known signatures will be ignored. void handle_blink_signature(Message& m, QnetState& qnet) { - MDEBUG("Received a blink tx signature from SN " << to_hex(m.conn.pubkey())); + oxen::log::debug(logcat, "Received a blink tx signature from SN {}", to_hex(m.conn.pubkey())); if (m.data.size() != 1) throw std::runtime_error("Rejecting blink signature: expected one data entry not " + std::to_string(m.data.size())); @@ -1227,7 +1219,7 @@ void handle_blink_signature(Message& m, QnetState& qnet) { // exclusive mutex, so check it again before we stash a delayed signature. find_blink(); if (!btxptr) { - MINFO("Blink tx not found in local blink cache; delaying signature verification"); + oxen::log::info(logcat, "Blink tx not found in local blink cache; delaying signature verification"); auto &delayed = qnet.blinks[blink_height][tx_hash].pending_sigs; for (auto &sig : signatures) delayed.insert(std::move(sig)); @@ -1235,7 +1227,7 @@ void handle_blink_signature(Message& m, QnetState& qnet) { } } - MINFO("Found blink tx in local blink cache"); + oxen::log::info(logcat, "Found blink tx in local blink cache"); process_blink_signatures(qnet, btxptr, blink_quorums, checksum, std::move(signatures), reply_tag, reply_conn, m.conn.pubkey()); } @@ -1377,14 +1369,14 @@ void common_blink_response(uint64_t tag, cryptonote::blink_result res, std::stri /// promise unless we get a nostart response from a majority of the remotes. void handle_blink_not_started(Message& m) { if (m.data.size() != 1) { - MERROR("Bad blink not started response: expected one data entry not " << m.data.size()); + oxen::log::error(logcat, "Bad blink not started response: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); auto tag = get_int(data.at("!")); auto& error = var::get(data.at("e")); - MINFO("Received no-start blink response: " << error); + oxen::log::info(logcat, "Received no-start blink response: {}", error); common_blink_response(tag, cryptonote::blink_result::rejected, std::move(error), true /*nostart*/); } @@ -1396,7 +1388,7 @@ void handle_blink_not_started(Message& m) { /// void handle_blink_failure(Message &m) { if (m.data.size() != 1) { - MERROR("Blink failure message not understood: expected one data entry not " << m.data.size()); + oxen::log::error(logcat, "Blink failure message not understood: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); @@ -1408,7 +1400,7 @@ void handle_blink_failure(Message &m) { // signature receipt, not at rejection time), so for now we don't include it. //auto &error = var::get(data.at("e")); - MINFO("Received blink failure response"); + oxen::log::info(logcat, "Received blink failure response"); common_blink_response(tag, cryptonote::blink_result::rejected, "Transaction rejected by quorum"s); } @@ -1420,13 +1412,13 @@ void handle_blink_failure(Message &m) { /// void handle_blink_success(Message& m) { if (m.data.size() != 1) { - MERROR("Blink success message not understood: expected one data entry not " << m.data.size()); + oxen::log::error(logcat, "Blink success message not understood: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); auto tag = get_int(data.at("!")); - MINFO("Received blink success response"); + oxen::log::info(logcat, "Received blink success response"); common_blink_response(tag, cryptonote::blink_result::accepted, ""s); } diff --git a/src/daemon/CMakeLists.txt b/src/daemon/CMakeLists.txt index e3dfd6c0f..3299031bb 100644 --- a/src/daemon/CMakeLists.txt +++ b/src/daemon/CMakeLists.txt @@ -44,6 +44,7 @@ target_link_libraries(daemon cryptonote_protocol daemonizer daemon_rpc_server + logging version filesystem Boost::program_options diff --git a/src/daemon/command_line_args.h b/src/daemon/command_line_args.h index 9252aaad5..a09f42eab 100644 --- a/src/daemon/command_line_args.h +++ b/src/daemon/command_line_args.h @@ -49,12 +49,12 @@ namespace daemon_args const command_line::arg_descriptor arg_max_log_file_size = { "max-log-file-size" , "Specify maximum log file size [B]" - , MAX_LOG_FILE_SIZE + , 104850000 }; const command_line::arg_descriptor arg_max_log_files = { "max-log-files" , "Specify maximum number of rotated log files to be saved (no limit by setting to 0)" - , MAX_LOG_FILES + , 50 }; const command_line::arg_descriptor arg_log_level = { "log-level" diff --git a/src/daemon/command_parser_executor.cpp b/src/daemon/command_parser_executor.cpp index 67dc2718a..7fce0e33c 100644 --- a/src/daemon/command_parser_executor.cpp +++ b/src/daemon/command_parser_executor.cpp @@ -37,11 +37,10 @@ #include "daemon/command_parser_executor.h" #include "rpc/core_rpc_server_commands_defs.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon" - namespace daemonize { +static auto logcat = oxen::log::Cat("daemon"); + // Consumes an argument from the given list, if present, parsing it into `var`. // Returns false upon parse failure, true otherwise. template @@ -360,7 +359,7 @@ bool command_parser_executor::print_block(const std::vector& args) crypto::hash block_hash; if (tools::hex_to_type(arg, block_hash)) return m_executor.print_block_by_hash(block_hash, include_hex); - MERROR("Invalid hash or height value: " << arg); + oxen::log::error(logcat, "Invalid hash or height value: {}", arg); } return false; @@ -397,7 +396,7 @@ bool command_parser_executor::print_transaction(const std::vector& if (tools::hex_to_type(str_hash, tx_hash)) m_executor.print_transaction(tx_hash, include_metadata, include_hex, include_json); else - MERROR("Invalid transaction hash: " << str_hash); + oxen::log::error(logcat, "Invalid transaction hash: {}", str_hash); return true; } @@ -547,7 +546,7 @@ bool command_parser_executor::out_peers(const std::vector& args) } catch(const std::exception& ex) { - MERROR("stoi exception"); + oxen::log::error(logcat, "stoi exception"); return false; } @@ -567,7 +566,7 @@ bool command_parser_executor::in_peers(const std::vector& args) } catch(const std::exception& ex) { - MERROR("stoi exception"); + oxen::log::error(logcat, "stoi exception"); return false; } diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index 6e2117ae1..032c94a89 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include "cryptonote_config.h" #include "cryptonote_core/cryptonote_core.h" @@ -66,11 +67,10 @@ extern "C" { using namespace std::literals; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon" - namespace daemonize { +static auto logcat = oxen::log::Cat("daemon"); + std::pair parse_ip_port(std::string_view ip_port, const std::string& argname) { std::pair result; @@ -110,13 +110,13 @@ daemon::daemon(boost::program_options::variables_map vm_) : p2p{std::make_unique(*protocol)}, rpc{std::make_unique(*core, *p2p)} { - MGINFO_BLUE("Initializing daemon objects..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Initializing daemon objects...")); - MGINFO("- cryptonote protocol"); + oxen::log::info(logcat, "- cryptonote protocol"); if (!protocol->init(vm)) throw std::runtime_error("Failed to initialize cryptonote protocol."); - MGINFO("- p2p"); + oxen::log::info(logcat, "- p2p"); if (!p2p->init(vm)) throw std::runtime_error("Failed to initialize p2p server."); @@ -145,7 +145,7 @@ daemon::daemon(boost::program_options::variables_map vm_) : std::vector> rpc_listen_admin, rpc_listen_public; if (deprecated_rpc_options) { - MGINFO_RED(deprecated_option_names << " options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead", deprecated_option_names)); // These old options from Monero are really janky: --restricted-rpc turns the main port // restricted, but then we also have --rpc-restricted-bind-port but both are stuck with @@ -208,55 +208,55 @@ daemon::daemon(boost::program_options::variables_map vm_) : if (!rpc_listen_admin.empty()) { - MGINFO("- admin HTTP RPC server"); + oxen::log::info(logcat, "- admin HTTP RPC server"); http_rpc_admin.emplace(*rpc, rpc_config, false /*not restricted*/, std::move(rpc_listen_admin)); } if (!rpc_listen_public.empty()) { - MGINFO("- public HTTP RPC server"); + oxen::log::info(logcat, "- public HTTP RPC server"); http_rpc_public.emplace(*rpc, rpc_config, true /*restricted*/, std::move(rpc_listen_public)); } - MGINFO_BLUE("Done daemon object initialization"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Done daemon object initialization")); } daemon::~daemon() { - MGINFO_BLUE("Deinitializing daemon objects..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitializing daemon objects...")); if (http_rpc_public) { - MGINFO("- public HTTP RPC server"); + oxen::log::info(logcat, "- public HTTP RPC server"); http_rpc_public.reset(); } if (http_rpc_admin) { - MGINFO("- admin HTTP RPC server"); + oxen::log::info(logcat, "- admin HTTP RPC server"); http_rpc_admin.reset(); } - MGINFO("- p2p"); + oxen::log::info(logcat, "- p2p"); try { p2p->deinit(); } catch (const std::exception& e) { - MERROR("Failed to deinitialize p2p: " << e.what()); + oxen::log::error(logcat, "Failed to deinitialize p2p: {}", e.what()); } - MGINFO("- core"); + oxen::log::info(logcat, "- core"); try { core->deinit(); core->set_cryptonote_protocol(nullptr); } catch (const std::exception& e) { - MERROR("Failed to deinitialize core: " << e.what()); + oxen::log::error(logcat, "Failed to deinitialize core: {}", e.what()); } - MGINFO("- cryptonote protocol"); + oxen::log::info(logcat, "- cryptonote protocol"); try { protocol->deinit(); protocol->set_p2p_endpoint(nullptr); } catch (const std::exception& e) { - MERROR("Failed to stop cryptonote protocol: " << e.what()); + oxen::log::error(logcat, "Failed to stop cryptonote protocol: {}", e.what()); } - MGINFO_BLUE("Deinitialization complete"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitialization complete")); } void daemon::init_options(boost::program_options::options_description& option_spec, boost::program_options::options_description& hidden) @@ -297,32 +297,32 @@ bool daemon::run(bool interactive) try { - MGINFO_BLUE("Starting up oxend services..."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Starting up oxend services...")); cryptonote::GetCheckpointsCallback get_checkpoints; #if defined(PER_BLOCK_CHECKPOINT) get_checkpoints = blocks::GetCheckpointsData; #endif - MGINFO("Starting core"); + oxen::log::info(logcat, "Starting core"); if (!core->init(vm, nullptr, get_checkpoints)) throw std::runtime_error("Failed to start core"); - MGINFO("Starting OxenMQ"); + oxen::log::info(logcat, "Starting OxenMQ"); omq_rpc = std::make_unique(*core, *rpc, vm); core->start_oxenmq(); if (http_rpc_admin) { - MGINFO("Starting admin HTTP RPC server"); + oxen::log::info(logcat, "Starting admin HTTP RPC server"); http_rpc_admin->start(); } if (http_rpc_public) { - MGINFO("Starting public HTTP RPC server"); + oxen::log::info(logcat, "Starting public HTTP RPC server"); http_rpc_public->start(); } std::optional rpc_commands; if (interactive) { - MGINFO("Starting command-line processor"); + oxen::log::info(logcat, "Starting command-line processor"); auto& omq = core->get_omq(); std::promise p; @@ -341,42 +341,42 @@ bool daemon::run(bool interactive) rpc_commands->start_handling([this] { stop(); }); } - MGINFO_GREEN("Starting up main network"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Starting up main network")); #ifdef ENABLE_SYSTEMD sd_notify(0, ("READY=1\nSTATUS=" + core->get_status_string()).c_str()); #endif p2p->run(); // blocks until p2p goes down - MGINFO_YELLOW("Main network stopped"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Main network stopped")); if (rpc_commands) { - MGINFO("Stopping RPC command processor"); + oxen::log::info(logcat, "Stopping RPC command processor"); rpc_commands->stop_handling(); rpc_commands.reset(); } if (http_rpc_public) { - MGINFO("Stopping public HTTP RPC server..."); + oxen::log::info(logcat, "Stopping public HTTP RPC server..."); http_rpc_public->shutdown(); } if (http_rpc_admin) { - MGINFO("Stopping admin HTTP RPC server..."); + oxen::log::info(logcat, "Stopping admin HTTP RPC server..."); http_rpc_admin->shutdown(); } - MGINFO("Node stopped."); + oxen::log::info(logcat, "Node stopped."); return true; } catch (std::exception const& ex) { - MFATAL(ex.what()); + oxen::log::error(logcat, ex.what()); return false; } catch (...) { - MFATAL("Unknown exception occured!"); + oxen::log::error(logcat, "Unknown exception occured!"); return false; } } diff --git a/src/daemon/daemon.h b/src/daemon/daemon.h index d2c877f53..f1623453d 100644 --- a/src/daemon/daemon.h +++ b/src/daemon/daemon.h @@ -40,7 +40,6 @@ #include "rpc/core_rpc_server.h" #include "cryptonote_core/cryptonote_core.h" #include "cryptonote_protocol/cryptonote_protocol_handler.h" -#include "epee/misc_log_ex.h" #undef OXEN_DEFAULT_LOG_CATEGORY #define OXEN_DEFAULT_LOG_CATEGORY "daemon" diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp index bc1e84999..9c4957c1f 100644 --- a/src/daemon/main.cpp +++ b/src/daemon/main.cpp @@ -39,6 +39,7 @@ #include "cryptonote_core/cryptonote_core.h" #include "daemonizer/daemonizer.h" #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "p2p/net_node.h" #include "rpc/common/rpc_args.h" #include "rpc/core_rpc_server.h" @@ -48,14 +49,14 @@ #include "command_server.h" #include "daemon.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon" - namespace po = boost::program_options; using namespace std::literals; namespace { + + static auto logcat = oxen::log::Cat("daemon"); + // Some ANSI color sequences that we use here (before the log system is initialized): constexpr auto RESET = "\033[0m"; constexpr auto RED = "\033[31;1m"; @@ -294,18 +295,21 @@ int main(int argc, char const * argv[]) // if log-file argument given: // absolute path // relative path: relative to data_dir + oxen::log::Level log_level; + if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, daemon_args::arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, daemon_args::arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } auto log_file_path = data_dir / cryptonote::LOG_FILENAME; if (!command_line::is_arg_defaulted(vm, daemon_args::arg_log_file)) log_file_path = command_line::get_arg(vm, daemon_args::arg_log_file); if (log_file_path.is_relative()) log_file_path = fs::absolute(data_dir / log_file_path); - mlog_configure(log_file_path.string(), true, command_line::get_arg(vm, daemon_args::arg_max_log_file_size), command_line::get_arg(vm, daemon_args::arg_max_log_files)); - // Set log level - if (!command_line::is_arg_defaulted(vm, daemon_args::arg_log_level)) - { - mlog_set_log(command_line::get_arg(vm, daemon_args::arg_log_level).c_str()); - } + oxen::logging::init(log_file_path, log_level); + logs_initialized = true; if (!command_line::is_arg_defaulted(vm, daemon_args::arg_max_concurrency)) @@ -313,7 +317,7 @@ int main(int argc, char const * argv[]) // logging is now set up // FIXME: only print this when starting up as a daemon but not when running rpc commands - MGINFO_CYAN("Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")"); + oxen::log::info(logcat, "Oxen '{}' (v{})", OXEN_RELEASE_NAME, OXEN_VERSION_FULL); // If there are positional options, we're running a daemon command { @@ -350,7 +354,7 @@ int main(int argc, char const * argv[]) } } - MINFO("Moving from main() into the daemonize now."); + oxen::log::info(logcat, "Moving from main() into the daemonize now."); return daemonizer::daemonize("Oxen Daemon", argc, argv, std::move(vm)) ? 0 : 1; @@ -358,14 +362,14 @@ int main(int argc, char const * argv[]) catch (std::exception const & ex) { if (logs_initialized) - LOG_ERROR("Exception in main! " << ex.what()); + oxen::log::error(logcat, "Exception in main! {}", ex.what()); else std::cerr << RED << "Exception in main! " << ex.what() << RESET << "\n"; } catch (...) { if (logs_initialized) - LOG_ERROR("Exception in main! (unknown exception type)"); + oxen::log::error(logcat, "Exception in main! (unknown exception type)"); else std::cerr << RED << "Exception in main! (unknown exception type)" << RESET << "\n"; } diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index 9e6c7db25..5a3ead82a 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -59,9 +59,6 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon" - using namespace cryptonote::rpc; using cryptonote::hf; @@ -1937,14 +1934,6 @@ std::string highlight_money(uint64_t amount) { bool rpc_command_executor::prepare_registration(bool force_registration) { - // RAII-style class to temporarily clear categories and restore upon destruction (i.e. upon returning). - struct clear_log_categories { - std::string categories; - clear_log_categories() { categories = mlog_get_categories(); mlog_set_categories(""); } - ~clear_log_categories() { mlog_set_categories(categories.c_str()); } - }; - auto scoped_log_cats = std::unique_ptr(new clear_log_categories()); - auto maybe_info = try_running([this] { return invoke(); }, "Failed to retrieve node info"); if (!maybe_info) return false; @@ -2341,8 +2330,6 @@ The Service Node will not activate until the entire stake has been contributed. args.push_back(std::to_string(portion)); } - scoped_log_cats.reset(); - { auto maybe_registration = try_running([this, staking_requirement, &args] { return invoke(json{{"staking_requirement", staking_requirement}, {"args", args}, {"make_friendly", true}}); }, "Failed to validate registration arguments; check the addresses and registration parameters and that the Daemon is running with the '--service-node' flag"); if (!maybe_registration) diff --git a/src/daemonizer/posix_daemonizer.inl b/src/daemonizer/posix_daemonizer.inl index cdff675f8..56bd216cf 100644 --- a/src/daemonizer/posix_daemonizer.inl +++ b/src/daemonizer/posix_daemonizer.inl @@ -77,7 +77,7 @@ namespace daemonizer (void)name; (void)argc; (void)argv; // Only used for Windows if (command_line::has_arg(vm, arg_detach)) { - MFATAL("--detach is no longer supported. Use systemd (or another process manager), tmux, screen, or nohup instead"); + oxen::log::error(globallogcat, "--detach is no longer supported. Use systemd (or another process manager), tmux, screen, or nohup instead"); return false; } bool interactive = !command_line::has_arg(vm, arg_non_interactive); diff --git a/src/debug_utilities/CMakeLists.txt b/src/debug_utilities/CMakeLists.txt index 38a10f77f..65914cdb0 100644 --- a/src/debug_utilities/CMakeLists.txt +++ b/src/debug_utilities/CMakeLists.txt @@ -35,6 +35,7 @@ target_link_libraries(cn_deserialize PRIVATE Boost::program_options p2p + logging extra) oxen_add_executable(object_sizes "oxen-utils-object-sizes" @@ -46,5 +47,6 @@ target_link_libraries(object_sizes lmdb p2p cpr::cpr + logging extra ) diff --git a/src/debug_utilities/cn_deserialize.cpp b/src/debug_utilities/cn_deserialize.cpp index b692d93ea..420220565 100644 --- a/src/debug_utilities/cn_deserialize.cpp +++ b/src/debug_utilities/cn_deserialize.cpp @@ -36,8 +36,7 @@ #include "version.h" #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "debugtools.deserialize" +static auto logcat = oxen::log::Cat("debugtools.deserialize"); namespace po = boost::program_options; @@ -135,14 +134,14 @@ constexpr static std::string_view network_type_str(network_type nettype) int main(int argc, char* argv[]) { - uint32_t log_level = 0; + uint32_t default_log_level = 0; std::string input; tools::on_startup(); po::options_description desc_cmd_only("Command line options"); po::options_description desc_cmd_sett("Command line options and settings options"); - const command_line::arg_descriptor arg_log_level = {"log-level", "", log_level}; + const command_line::arg_descriptor arg_log_level = {"log-level", "", default_log_level}; const command_line::arg_descriptor arg_input = { "input", "Specify a wallet address or hex string of a Cryptonote type for decoding, supporting\n" " - TX Extra\n" @@ -175,7 +174,6 @@ int main(int argc, char* argv[]) return 1; } - log_level = command_line::get_arg(vm, arg_log_level); input = command_line::get_arg(vm, arg_input); if (input.empty()) { @@ -183,7 +181,16 @@ int main(int argc, char* argv[]) return 1; } - mlog_configure("", true); + auto log_file_path = "cn_deserialize.log"; + oxen::log::Level log_level; + if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level))) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level) << std::endl; + throw std::runtime_error{"Incorrect log level"}; + } + oxen::logging::init(log_file_path, log_level); + oxen::log::warning(logcat, "Starting..."); if (oxenc::is_hex(input)) { diff --git a/src/debug_utilities/object_sizes.cpp b/src/debug_utilities/object_sizes.cpp index 6f31e2fd1..149271688 100644 --- a/src/debug_utilities/object_sizes.cpp +++ b/src/debug_utilities/object_sizes.cpp @@ -45,9 +45,6 @@ #include "wallet/api/unsigned_transaction.h" #include "wallet/api/pending_transaction.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "debugtools.objectsizes" - class size_logger { public: @@ -68,7 +65,8 @@ int main(int argc, char* argv[]) tools::on_startup(); - mlog_configure("", true); + auto log_file_path = "object_sizes.log"; + oxen::logging::init(log_file_path, oxen::log::Level::info); SL(boost::thread); SL(boost::asio::io_service); diff --git a/src/device/CMakeLists.txt b/src/device/CMakeLists.txt index a6d5ce613..68bbbca7d 100644 --- a/src/device/CMakeLists.txt +++ b/src/device/CMakeLists.txt @@ -42,6 +42,7 @@ target_link_libraries(device PRIVATE SQLiteCpp version + logging extra) option(HWDEVICE_DEBUG "Enable hardware wallet debugging (requires also using a debug build of the Ledger wallet)" OFF) diff --git a/src/device/device.cpp b/src/device/device.cpp index 6e51ba6cd..c0a825d5f 100644 --- a/src/device/device.cpp +++ b/src/device/device.cpp @@ -36,6 +36,8 @@ namespace hw { + + static auto logcat = oxen::log::Cat("device"); /* ======================================================================= */ /* SETUP */ @@ -83,9 +85,9 @@ namespace hw { auto device = registry.find(device_descriptor_lookup); if (device == registry.end()) { - MERROR("Device not found in registry: '" << device_descriptor << "'. Known devices: "); + oxen::log::error(logcat, "Device not found in registry: '{}'. Known devices: ", device_descriptor); for (const auto& sm_pair : registry) - MERROR(" - " << sm_pair.first); + oxen::log::error(logcat, " - {}", sm_pair.first); throw std::runtime_error("device not found: " + device_descriptor); } return *device->second; diff --git a/src/device/device_ledger.cpp b/src/device/device_ledger.cpp index 082560307..9d8fbb104 100644 --- a/src/device/device_ledger.cpp +++ b/src/device/device_ledger.cpp @@ -39,6 +39,7 @@ #include "common/lock.h" #include "common/varint.h" #include +#include "logging/oxen_logger.h" #include #ifdef DEBUG_HWDEVICE @@ -49,8 +50,7 @@ namespace hw::ledger { #ifdef WITH_DEVICE_LEDGER - #undef OXEN_DEFAULT_LOG_CATEGORY - #define OXEN_DEFAULT_LOG_CATEGORY "device.ledger" + static auto logcat = oxen::log::Cat("device.ledger"); /* ===================================================================== */ /* === Debug ==== */ @@ -319,7 +319,7 @@ namespace hw::ledger { reset_buffer(); has_view_key = false; tx_in_progress = false; - MDEBUG("Device " << id << " Created"); + oxen::log::debug(logcat, "Device {} Created", id); } device_ledger::device_ledger(io::ledger_tcp&& tcp) : hw_device{std::make_unique(std::move(tcp))} { @@ -327,12 +327,12 @@ namespace hw::ledger { reset_buffer(); has_view_key = false; tx_in_progress = false; - MDEBUG("Device " << id << " (tcp) created"); + oxen::log::debug(logcat, "Device {} (tcp) created", id); } device_ledger::~device_ledger() { release(); - MDEBUG("Device " << id << " Destroyed"); + oxen::log::debug(logcat, "Device {} Destroyed", id); } /* ======================================================================= */ @@ -341,24 +341,24 @@ namespace hw::ledger { //lock the device for a long sequence void device_ledger::lock() { - MDEBUG("Ask for LOCKING for device " << name << " in thread "); + oxen::log::debug(logcat, "Ask for LOCKING for device {} in thread ", name); device_locker.lock(); - MDEBUG("Device " << name << " LOCKed"); + oxen::log::debug(logcat, "Device {} LOCKed", name); } //lock the device for a long sequence bool device_ledger::try_lock() { - MDEBUG("Ask for LOCKING(try) for device " << name << " in thread "); + oxen::log::debug(logcat, "Ask for LOCKING(try) for device {} in thread ", name); bool r = device_locker.try_lock(); - MDEBUG("Device " << name << (r ? "" : " not") << " LOCKed(try)"); + oxen::log::debug(logcat, "Device {}{} LOCKed(try)", name, (r ? "" : " not")); return r; } //unlock the device after a long sequence void device_ledger::unlock() { - MDEBUG("Ask for UNLOCKING for device " << name << " in thread "); + oxen::log::debug(logcat, "Ask for UNLOCKING for device {} in thread ", name); device_locker.unlock(); - MDEBUG("Device " << name << " UNLOCKed"); + oxen::log::debug(logcat, "Device {} UNLOCKed", name); } @@ -381,16 +381,14 @@ namespace hw::ledger { #endif cmd << " p=(0x" << std::setw(2) << +buffer_send[2] << ",0x" << std::setw(2) << +buffer_send[3] << ')'; cmd << " sz=0x" << std::setw(2) << +buffer_send[4] << '[' << std::to_string(buffer_send[4]) << "] "; - MDEBUG("CMD: " << cmd.str() << oxenc::to_hex(buffer_send + 5, buffer_send + length_send)); + oxen::log::debug(logcat, "CMD: {}{}", cmd.str(), oxenc::to_hex(buffer_send + 5, buffer_send + length_send)); last_cmd = std::chrono::steady_clock::now(); } } void device_ledger::logRESP() { if (apdu_verbose) - MDEBUG("RESP (+" << tools::short_duration(std::chrono::steady_clock::now() - last_cmd) << "): " - << oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}) - << ' ' << oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); + oxen::log::debug(logcat, "RESP (+{}): {} {}", tools::short_duration(std::chrono::steady_clock::now() - last_cmd), oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}), oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); } int device_ledger::set_command_header(unsigned char ins, unsigned char p1, unsigned char p2) { @@ -455,7 +453,7 @@ namespace hw::ledger { } void device_ledger::send_secret(const unsigned char sec[32], int &offset) { - MDEBUG("send_secret: " << tx_in_progress); + oxen::log::debug(logcat, "send_secret: {}", tx_in_progress); send_bytes(sec, 32, offset); if (tx_in_progress) { CHECK_AND_ASSERT_THROW_MES(offset + 32 <= BUFFER_SEND_SIZE, "send_secret: out of bounds write (mac)"); @@ -465,7 +463,7 @@ namespace hw::ledger { } void device_ledger::receive_secret(unsigned char sec[32], int &offset) { - MDEBUG("receive_secret: " << tx_in_progress); + oxen::log::debug(logcat, "receive_secret: {}", tx_in_progress); receive_bytes(sec, 32, offset); if (tx_in_progress) { CHECK_AND_ASSERT_THROW_MES(offset + 32 <= BUFFER_RECV_SIZE, "receive_secret: out of bounds read (mac)"); @@ -565,7 +563,7 @@ namespace hw::ledger { #endif release(); hw_device->init(); - MDEBUG("Device " << id <<" HIDUSB inited"); + oxen::log::debug(logcat, "Device {} HIDUSB inited", id); return true; } @@ -655,7 +653,7 @@ namespace hw::ledger { std::string coin{reinterpret_cast(buffer_recv), 4}; auto device_nettype = static_cast(buffer_recv[4]); - MDEBUG("Ledger wallet is set to " << coin << " " << nettype_string(device_nettype)); + oxen::log::debug(logcat, "Ledger wallet is set to {} {}", coin, nettype_string(device_nettype)); if (coin != COIN_NETWORK) throw std::runtime_error{"Invalid wallet app: expected " + std::string{COIN_NETWORK} + ", got " + coin}; if (device_nettype != nettype) @@ -685,7 +683,7 @@ namespace hw::ledger { case mode::NONE: break; } - MDEBUG("Switch to mode: " << +static_cast(m)); + oxen::log::debug(logcat, "Switch to mode: {}", +static_cast(m)); return device::set_mode(m); } @@ -719,7 +717,7 @@ namespace hw::ledger { //View key is retrieved, if allowed, to speed up blockchain parsing receive_bytes(viewkey.data, 32); has_view_key = !is_fake_view_key(viewkey); - MDEBUG((has_view_key ? "Have view key" : "Have no view key")); + oxen::log::debug(logcat, "{}", (has_view_key ? "Have view key" : "Have no view key")); #ifdef DEBUG_HWDEVICE send_simple(INS_GET_KEY, 0x04); @@ -786,7 +784,7 @@ namespace hw::ledger { if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { //If we are in TRANSACTION_PARSE, the given derivation has been retrieved uncrypted (wihtout the help //of the device), so continue that way. - MDEBUG("derive_subaddress_public_key : PARSE mode with known viewkey"); + oxen::log::debug(logcat, "derive_subaddress_public_key : PARSE mode with known viewkey"); crypto::derive_subaddress_public_key(pub, derivation, output_index, derived_pub); } else { @@ -1100,7 +1098,7 @@ namespace hw::ledger { if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { //A derivation is requested in PARSE mode and we have the view key, //so do that without the device and return the derivation unencrypted. - MDEBUG( "generate_key_derivation : PARSE mode with known viewkey"); + oxen::log::debug(logcat, "generate_key_derivation : PARSE mode with known viewkey"); //Note derivation in PARSE mode can only happen with viewkey, so assert it! assert(is_fake_view_key(sec)); r = crypto::generate_key_derivation(pub, viewkey, derivation); @@ -1132,12 +1130,12 @@ namespace hw::ledger { const crypto::public_key *pkey = nullptr; if (derivation == main_derivation) { pkey = &tx_pub_key; - MDEBUG("conceal derivation with main tx pub key"); + oxen::log::debug(logcat, "conceal derivation with main tx pub key"); } else { for (size_t n = 0; n < additional_derivations.size(); ++n) { if (derivation == additional_derivations[n]) { pkey = &additional_tx_pub_keys[n]; - MDEBUG("conceal derivation with additionnal tx pub key"); + oxen::log::debug(logcat, "conceal derivation with additionnal tx pub key"); break; } } @@ -1433,7 +1431,7 @@ namespace hw::ledger { log_hexbuffer("GENERATE_TX_PROOF: **r** ", sig.r.data, sizeof(sig.r.data)); debug_device->generate_tx_proof(prefix_hash_x, R_x, A_x, B_x, D_x, r_x, sig_x); - MDEBUG("FAIL is normal if random is not fixed in proof"); + oxen::log::debug(logcat, "FAIL is normal if random is not fixed in proof"); check32("generate_tx_proof", "c", sig_x.c.data, sig.c.data); check32("generate_tx_proof", "r", sig_x.r.data, sig.r.data); @@ -1495,7 +1493,7 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE crypto::hash h_x; debug_device->get_transaction_prefix_hash(tx, h_x); - MDEBUG("get_transaction_prefix_hash [[IN]] h_x/1 " << h_x); + oxen::log::debug(logcat, "get_transaction_prefix_hash [[IN]] h_x/1 {}", h_x); #endif // As of protocol version 4, we send: @@ -1746,7 +1744,7 @@ namespace hw::ledger { receive_bytes(unmasked.mask.bytes, 32, offset); #ifdef DEBUG_HWDEVICE - MDEBUG("ecdhEncode: Akout: "<') << " : " << oxenc::to_hex(buffer, buffer + block_len)); + oxen::log::debug(logcat, "HID {} : {}", (read ? '<' : '>'), oxenc::to_hex(buffer, buffer + block_len)); } void hid::init() { @@ -91,10 +90,9 @@ namespace hw::io { hid_device_info* hid::find_device(hid_device_info* devices_list, std::optional interface_number, std::optional usage_page) { bool select_any = !interface_number && !usage_page; - MDEBUG( "Looking for " << - (select_any ? "any HID Device" : "HID Device with") << - (interface_number ? (" interface_number " + std::to_string(*interface_number)) : "") << - ((interface_number && usage_page) ? " or" : "") << + oxen::log::debug(logcat, "Looking for {}{}{}{}", (select_any ? "any HID Device" : "HID Device with"), + (interface_number ? (" interface_number " + std::to_string(*interface_number)) : ""), + ((interface_number && usage_page) ? " or" : ""), (usage_page ? (" usage_page " + std::to_string(*usage_page)) : "")); hid_device_info* result = nullptr; @@ -104,11 +102,10 @@ namespace hw::io { || (usage_page && devices_list->usage_page == *usage_page)) result = devices_list; - MDEBUG( (result == devices_list ? "SELECTED" : "SKIPPED ") << - " HID Device" << - " path " << safe_hid_path(devices_list) << - " interface_number " << devices_list->interface_number << - " usage_page " << devices_list->usage_page); + oxen::log::debug(logcat, "{} HID Device path {} interface_number {} usage_page {}", (result == devices_list ? "SELECTED" : "SKIPPED ") + ,safe_hid_path(devices_list) + ,devices_list->interface_number + ,devices_list->usage_page); } return result; @@ -120,7 +117,7 @@ namespace hw::io { hid_device_info* hwdev_info_list = hid_enumerate(vid, pid); if (!hwdev_info_list) { - MDEBUG("Unable to enumerate device " << vid << ":" << pid << ": " << safe_hid_error(usb_device)); + oxen::log::debug(logcat, "Unable to enumerate device {}:{}: {}", vid, pid, safe_hid_error(usb_device)); return false; } hid_device* hwdev = nullptr; diff --git a/src/device/io_ledger_tcp.cpp b/src/device/io_ledger_tcp.cpp index ddb4f194c..953131bf2 100644 --- a/src/device/io_ledger_tcp.cpp +++ b/src/device/io_ledger_tcp.cpp @@ -5,6 +5,7 @@ #include #include #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" extern "C" { #ifdef _WIN32 @@ -21,11 +22,10 @@ extern "C" { #include } -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "device.io" - namespace hw::io { +static auto logcat = oxen::log::Cat("device.io"); + static std::string to_string(const addrinfo* a) { std::array buf; std::string addr; @@ -77,7 +77,7 @@ void ledger_tcp::connect() { bool connected = false; const char* err = "An unknown error occurred"; for (a = addr; a && !connected; a = a->ai_next) { - MDEBUG("Attempting to connect to " << to_string(a)); + oxen::log::debug(logcat, "Attempting to connect to {}", to_string(a)); int rc = ::connect(fd, a->ai_addr, a->ai_addrlen); connected = rc == 0; if (rc == -1) { @@ -103,7 +103,7 @@ void ledger_tcp::connect() { if (!connected) throw std::runtime_error{"Failed to connect to " + host + ":" + port + ": " + err}; - MDEBUG("Connected to " << to_string(a)); + oxen::log::debug(logcat, "Connected to {}", to_string(a)); #ifdef _WIN32 blocking_param = 0; diff --git a/src/device/log.cpp b/src/device/log.cpp index a6daae639..0100a21d2 100644 --- a/src/device/log.cpp +++ b/src/device/log.cpp @@ -34,23 +34,21 @@ namespace hw { - #undef OXEN_DEFAULT_LOG_CATEGORY - #define OXEN_DEFAULT_LOG_CATEGORY "device" + static auto logcat = oxen::log::Cat("device"); void log_hexbuffer(std::string_view msg, const void* buff, size_t len) { - MDEBUG(msg << ": " << oxenc::to_hex(std::string_view{reinterpret_cast(buff), len})); + oxen::log::debug(logcat, "{}: {}", msg, oxenc::to_hex(std::string_view{reinterpret_cast(buff), len})); } void log_message(std::string_view msg, std::string_view info) { - MDEBUG(msg << ": " << info); + oxen::log::debug(logcat, "{}: {}", msg, info); } #ifdef WITH_DEVICE_LEDGER namespace ledger { - #undef OXEN_DEFAULT_LOG_CATEGORY - #define OXEN_DEFAULT_LOG_CATEGORY "device.ledger" + static auto logcat = oxen::log::Cat("device.ledger"); #ifdef DEBUG_HWDEVICE diff --git a/src/device_trezor/device_trezor.cpp b/src/device_trezor/device_trezor.cpp index 5b954e095..af1e06715 100644 --- a/src/device_trezor/device_trezor.cpp +++ b/src/device_trezor/device_trezor.cpp @@ -35,8 +35,7 @@ namespace trezor { #ifdef WITH_DEVICE_TREZOR -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "device.trezor" +static auto logcat = oxen::log::Cat("device.trezor"); #define HW_TREZOR_NAME "Trezor" @@ -68,7 +67,7 @@ namespace trezor { disconnect(); release(); } catch(std::exception const& e){ - MWARNING("Could not disconnect and release: " << e.what()); + oxen::log::warning(logcat, "Could not disconnect and release: {}", e.what()); } } @@ -113,7 +112,7 @@ namespace trezor { } catch(const std::exception & e) { - MERROR("Live refresh could not be terminated: " << e.what()); + oxen::log::error(logcat, "Live refresh could not be terminated: {}", e.what()); } } @@ -143,14 +142,14 @@ namespace trezor { continue; } - MTRACE("Closing live refresh process due to inactivity"); + oxen::log::trace(logcat, "Closing live refresh process due to inactivity"); try { live_refresh_finish(); } catch(const std::exception &e) { - MWARNING("Live refresh auto-finish failed: " << e.what()); + oxen::log::warning(logcat, "Live refresh auto-finish failed: {}", e.what()); } } } @@ -172,14 +171,14 @@ namespace trezor { return true; } catch(std::exception const& e){ - MERROR("Get public address exception: " << e.what()); + oxen::log::error(logcat, "Get public address exception: {}", e.what()); return false; } } bool device_trezor::get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) { try { - MDEBUG("Loading view-only key from the Trezor. Please check the Trezor for a confirmation."); + oxen::log::debug(logcat, "Loading view-only key from the Trezor. Please check the Trezor for a confirmation."); auto res = get_view_key(); CHECK_AND_ASSERT_MES(res->watch_key().size() == 32, false, "Trezor returned invalid view key"); @@ -196,7 +195,7 @@ namespace trezor { return true; } catch(std::exception const& e){ - MERROR("Get secret keys exception: " << e.what()); + oxen::log::error(logcat, "Get secret keys exception: {}", e.what()); return false; } } @@ -237,7 +236,7 @@ namespace trezor { } auto response = this->client_exchange(req); - MTRACE("Get address response received"); + oxen::log::trace(logcat, "Get address response received"); return response; } @@ -253,7 +252,7 @@ namespace trezor { this->set_msg_addr(req.get(), path, network_type); auto response = this->client_exchange(req); - MTRACE("Get watch key response received"); + oxen::log::trace(logcat, "Get watch key response received"); return response; } @@ -282,7 +281,7 @@ namespace trezor { this->set_msg_addr(req.get()); auto response = this->client_exchange(req); - MTRACE("Get TX key response received"); + oxen::log::trace(logcat, "Get TX key response received"); protocol::tx::get_tx_key_ack(tx_keys, tx_aux_data.tx_prefix_hash, view_key_priv, response); } @@ -328,7 +327,7 @@ namespace trezor { kis.push_back(ckis); } - MTRACE("Batch " << cur << " / " << num_batches << " batches processed"); + oxen::log::trace(logcat, "Batch {} / {} batches processed", cur, num_batches); EVENT_PROGRESS((double)cur * batch_size / mtds.size()); } EVENT_PROGRESS(1.); @@ -373,7 +372,7 @@ namespace trezor { try{ return is_live_refresh_enabled(); } catch(const std::exception & e){ - MERROR("Could not detect if live refresh is enabled: " << e.what()); + oxen::log::error(logcat, "Could not detect if live refresh is enabled: {}", e.what()); } return false; } @@ -462,7 +461,7 @@ namespace trezor { } catch(const std::exception & e) { - MWARNING("KI computation state change failed, started: " << started << ", e: " << e.what()); + oxen::log::warning(logcat, "KI computation state change failed, started: {}, e: {}", started, e.what()); } } @@ -525,7 +524,7 @@ namespace trezor { // Transaction check try { - MDEBUG("signed transaction: " << cryptonote::get_transaction_hash(cpend.tx) << "\n" << cryptonote::obj_to_json_str(cpend.tx) << "\n"); + oxen::log::debug(logcat, "signed transaction: {}\n{}\n", cryptonote::get_transaction_hash(cpend.tx), cryptonote::obj_to_json_str(cpend.tx)); transaction_check(cdata, aux_data); } catch(const std::exception &e){ throw exc::ProtocolException(std::string("Transaction verification failed: ") + e.what()); @@ -688,7 +687,7 @@ namespace trezor { if ((env_trezor_client_version = getenv("TREZOR_CLIENT_VERSION")) != nullptr){ auto succ = epee::string_tools::get_xtype_from_string(client_version, env_trezor_client_version); if (succ){ - MINFO("Trezor client version overriden by TREZOR_CLIENT_VERSION to: " << client_version); + oxen::log::info(logcat, "Trezor client version overriden by TREZOR_CLIENT_VERSION to: {}", client_version); } } #endif diff --git a/src/device_trezor/device_trezor_base.cpp b/src/device_trezor/device_trezor_base.cpp index 12442a125..ef561596c 100644 --- a/src/device_trezor/device_trezor_base.cpp +++ b/src/device_trezor/device_trezor_base.cpp @@ -37,8 +37,7 @@ namespace trezor { #ifdef WITH_DEVICE_TREZOR -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "device.trezor" +static auto logcat = oxen::log::Cat("device.trezor"); #define TREZOR_BIP44_HARDENED_ZERO 0x80000000 const uint32_t device_trezor_base::DEFAULT_BIP44_PATH[] = {0x8000002c, 0x80000080}; @@ -54,7 +53,7 @@ namespace trezor { disconnect(); release(); } catch(std::exception const& e){ - MERROR("Could not disconnect and release: " << e.what()); + oxen::log::error(logcat, "Could not disconnect and release: {}", e.what()); } } @@ -85,7 +84,7 @@ namespace trezor { bool device_trezor_base::init() { if (!release()){ - MERROR("Release failed"); + oxen::log::error(logcat, "Release failed"); return false; } @@ -98,7 +97,7 @@ namespace trezor { return true; } catch(std::exception const& e){ - MERROR("Release exception: " << e.what()); + oxen::log::error(logcat, "Release exception: {}", e.what()); return false; } } @@ -111,26 +110,26 @@ namespace trezor { try { hw::trezor::t_transport_vect trans; - MDEBUG("Enumerating Trezor devices..."); + oxen::log::debug(logcat, "Enumerating Trezor devices..."); enumerate(trans); sort_transports_by_env(trans); - MDEBUG("Enumeration yielded " << trans.size() << " Trezor devices"); + oxen::log::debug(logcat, "Enumeration yielded {} Trezor devices", trans.size()); for (auto &cur : trans) { - MDEBUG(" device: " << *(cur.get())); + oxen::log::debug(logcat, " device: {}", *(cur.get())); } for (auto &cur : trans) { std::string cur_path = cur->get_path(); if (tools::starts_with(cur_path, name)) { - MDEBUG("Device Match: " << cur_path); + oxen::log::debug(logcat, "Device Match: {}", cur_path); m_transport = cur; break; } } if (!m_transport) { - MERROR("No matching Trezor device found. Device specifier: \"" << name << "\""); + oxen::log::error(logcat, "No matching Trezor device found. Device specifier: \"{}\"", name); return false; } @@ -142,7 +141,7 @@ namespace trezor { return true; } catch(std::exception const& e){ - MERROR("Open exception: " << e.what()); + oxen::log::error(logcat, "Open exception: {}", e.what()); return false; } } @@ -158,7 +157,7 @@ namespace trezor { m_transport = nullptr; } catch(std::exception const& e){ - MERROR("Disconnect exception: " << e.what()); + oxen::log::error(logcat, "Disconnect exception: {}", e.what()); m_transport = nullptr; return false; } @@ -179,28 +178,28 @@ namespace trezor { //lock the device for a long sequence void device_trezor_base::lock() { - MTRACE("Ask for LOCKING for device " << name << " in thread "); + oxen::log::trace(logcat, "Ask for LOCKING for device {} in thread ", name); device_locker.lock(); - MTRACE("Device " << name << " LOCKed"); + oxen::log::trace(logcat, "Device {} LOCKed", name); } //lock the device for a long sequence bool device_trezor_base::try_lock() { - MTRACE("Ask for LOCKING(try) for device " << name << " in thread "); + oxen::log::trace(logcat, "Ask for LOCKING(try) for device {} in thread ", name); bool r = device_locker.try_lock(); if (r) { - MTRACE("Device " << name << " LOCKed(try)"); + oxen::log::trace(logcat, "Device {} LOCKed(try)", name); } else { - MDEBUG("Device " << name << " not LOCKed(try)"); + oxen::log::debug(logcat, "Device {} not LOCKed(try)", name); } return r; } //unlock the device void device_trezor_base::unlock() { - MTRACE("Ask for UNLOCKING for device " << name << " in thread "); + oxen::log::trace(logcat, "Ask for UNLOCKING for device {} in thread ", name); device_locker.unlock(); - MTRACE("Device " << name << " UNLOCKed"); + oxen::log::trace(logcat, "Device {} UNLOCKed", name); } /* ======================================================================= */ @@ -237,7 +236,7 @@ namespace trezor { pingMsg->set_message("PING"); auto success = client_exchange(pingMsg); // messages::MessageType_Success - MDEBUG("Ping response " << success->message()); + oxen::log::debug(logcat, "Ping response {}", success->message()); (void)success; } @@ -248,7 +247,7 @@ namespace trezor { call_ping_unsafe(); } catch(exc::TrezorException const& e){ - MINFO("Trezor does not respond: " << e.what()); + oxen::log::info(logcat, "Trezor does not respond: {}", e.what()); throw exc::DeviceNotResponsiveException(std::string("Trezor not responding: ") + e.what()); } } @@ -341,7 +340,7 @@ namespace trezor { bool device_trezor_base::ping() { auto locks = tools::unique_locks(device_locker, command_locker); if (!m_transport){ - MINFO("Ping failed, device not connected"); + oxen::log::info(logcat, "Ping failed, device not connected"); return false; } @@ -350,9 +349,9 @@ namespace trezor { return true; } catch(std::exception const& e) { - MERROR("Ping failed, exception thrown " << e.what()); + oxen::log::error(logcat, "Ping failed, exception thrown {}", e.what()); } catch(...){ - MERROR("Ping failed, general exception thrown"); + oxen::log::error(logcat, "Ping failed, general exception thrown"); } return false; @@ -409,7 +408,7 @@ namespace trezor { if (debug_transport) { m_debug_callback = std::make_shared(debug_transport); } else { - MDEBUG("Transport does not have debug link option"); + oxen::log::debug(logcat, "Transport does not have debug link option"); } } } @@ -422,7 +421,7 @@ namespace trezor { void device_trezor_base::on_button_request(GenericMessage & resp, const messages::common::ButtonRequest * msg) { CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); - MDEBUG("on_button_request, code: " << msg->code()); + oxen::log::debug(logcat, "on_button_request, code: {}", msg->code()); TREZOR_CALLBACK(on_button_request, msg->code()); @@ -439,7 +438,7 @@ namespace trezor { void device_trezor_base::on_pin_request(GenericMessage & resp, const messages::common::PinMatrixRequest * msg) { - MDEBUG("on_pin_request"); + oxen::log::debug(logcat, "on_pin_request"); CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); std::optional pin; @@ -469,7 +468,7 @@ namespace trezor { void device_trezor_base::on_passphrase_request(GenericMessage & resp, const messages::common::PassphraseRequest * msg) { CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); - MDEBUG("on_passhprase_request"); + oxen::log::debug(logcat, "on_passhprase_request"); // Backward compatibility, migration clause. if (msg->has__on_device() && msg->_on_device()){ @@ -525,7 +524,7 @@ namespace trezor { void device_trezor_base::on_passphrase_state_request(GenericMessage & resp, const messages::common::Deprecated_PassphraseStateRequest * msg) { - MDEBUG("on_passhprase_state_request"); + oxen::log::debug(logcat, "on_passhprase_state_request"); CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); if (msg->has_state()) { diff --git a/src/device_trezor/trezor/transport.cpp b/src/device_trezor/trezor/transport.cpp index 5a7832a99..8e8f903db 100644 --- a/src/device_trezor/trezor/transport.cpp +++ b/src/device_trezor/trezor/transport.cpp @@ -302,12 +302,12 @@ namespace trezor{ bool Transport::pre_open(){ if (m_open_counter > 0){ - MTRACE("Already opened, count: " << m_open_counter); + oxen::log::trace(logcat, "Already opened, count: {}", m_open_counter); m_open_counter += 1; return false; } else if (m_open_counter < 0){ - MTRACE("Negative open value: " << m_open_counter); + oxen::log::trace(logcat, "Negative open value: {}", m_open_counter); } @@ -320,7 +320,7 @@ namespace trezor{ m_open_counter -= 1; if (m_open_counter < 0){ - MDEBUG("Already closed. Counter " << m_open_counter); + oxen::log::debug(logcat, "Already closed. Counter {}", m_open_counter); } else if (m_open_counter == 0) { return true; @@ -353,7 +353,7 @@ namespace trezor{ } else if (!tools::starts_with(m_bridge_url, "http://") && !tools::starts_with(m_bridge_url, "https://")) m_bridge_url.insert(0, "http://"); - MDEBUG("Bridge host: " << m_bridge_url); + oxen::log::debug(logcat, "Bridge host: {}", m_bridge_url); } std::string BridgeTransport::get_path() const { @@ -386,11 +386,11 @@ namespace trezor{ const auto id_product = (uint16_t) itr_product->value.GetUint64(); const auto device_idx = get_device_idx(id_vendor, id_product); if (!is_device_supported(device_idx)){ - MDEBUG("Device with idx " << device_idx << " is not supported. Vendor: " << id_vendor << ", product: " << id_product); + oxen::log::debug(logcat, "Device with idx {} is not supported. Vendor: {}, product: {}", device_idx, id_vendor, id_product); continue; } } catch(const std::exception &e){ - MERROR("Could not detect vendor & product: " << e.what()); + oxen::log::error(logcat, "Could not detect vendor & product: {}", e.what()); } } @@ -426,7 +426,7 @@ namespace trezor{ return; } - MTRACE("Closing Trezor:BridgeTransport"); + oxen::log::trace(logcat, "Closing Trezor:BridgeTransport"); if (!m_device_path || !m_session){ throw exc::CommunicationException("Device not open"); } @@ -580,7 +580,7 @@ namespace trezor{ parse_udp_path(m_device_host, m_device_port, *device_path); } else if ((env_trezor_path = getenv("TREZOR_PATH")) != nullptr && tools::starts_with(env_trezor_path, UdpTransport::PATH_PREFIX)){ parse_udp_path(m_device_host, m_device_port, std::string(env_trezor_path)); - MDEBUG("Applied TREZOR_PATH: " << m_device_host << ":" << m_device_port); + oxen::log::debug(logcat, "Applied TREZOR_PATH: {}:{}", m_device_host, m_device_port); } else { m_device_host = DEFAULT_HOST; } @@ -664,7 +664,7 @@ namespace trezor{ return; } - MTRACE("Closing Trezor:UdpTransport"); + oxen::log::trace(logcat, "Closing Trezor:UdpTransport"); if (!m_socket) { throw exc::CommunicationException("Socket is already closed"); } @@ -682,7 +682,7 @@ namespace trezor{ t->m_device_port = m_device_port + 1; return t; #else - MINFO("Debug link is disabled in production"); + oxen::log::info(logcat, "Debug link is disabled in production"); return nullptr; #endif } @@ -726,7 +726,7 @@ namespace trezor{ } catch(exc::CommunicationException const& e){ throw; } catch(std::exception const& e){ - MWARNING("Error reading chunk, reason: " << e.what()); + oxen::log::warning(logcat, "Error reading chunk, reason: {}", e.what()); throw exc::CommunicationException(std::string("Chunk read error: ") + std::string(e.what())); } } @@ -774,7 +774,7 @@ namespace trezor{ throw exc::TimeoutException(); } else if (ec) { - MWARNING("Reading from UDP socket failed: " << ec.message()); + oxen::log::warning(logcat, "Reading from UDP socket failed: {}", ec.message()); throw exc::CommunicationException(); } @@ -945,13 +945,13 @@ namespace trezor{ throw std::runtime_error("Unable to enumerate libusb devices"); } - MTRACE("Libusb devices: " << cnt); + oxen::log::trace(logcat, "Libusb devices: {}", cnt); for(ssize_t i = 0; i < cnt; i++) { libusb_device_descriptor desc{}; r = libusb_get_device_descriptor(devs[i], &desc); if (r < 0){ - MERROR("Unable to get libusb device descriptor " << i); + oxen::log::error(logcat, "Unable to get libusb device descriptor {}", i); continue; } @@ -960,7 +960,7 @@ namespace trezor{ continue; } - MTRACE("Found Trezor device: " << desc.idVendor << ":" << desc.idProduct << " dev_idx " << (int)trezor_dev_idx); + oxen::log::trace(logcat, "Found Trezor device: {}:{} dev_idx {}", desc.idVendor, desc.idProduct, (int)trezor_dev_idx); auto t = std::make_shared(std::make_optional(&desc)); t->m_bus_id = libusb_get_bus_number(devs[i]); @@ -1016,7 +1016,7 @@ namespace trezor{ libusb_device_descriptor desc{}; r = libusb_get_device_descriptor(devs[i], &desc); if (r < 0){ - MERROR("Unable to get libusb device descriptor " << i); + oxen::log::error(logcat, "Unable to get libusb device descriptor {}", i); continue; } @@ -1031,7 +1031,7 @@ namespace trezor{ // Port resolution may fail. Non-critical error, just addressing precision is decreased. get_libusb_ports(devs[i], path); - MTRACE("Found Trezor device: " << desc.idVendor << ":" << desc.idProduct + oxen::log::trace(logcat, "Found Trezor device: {}:{}", desc.idVendor, desc.idProduct << ", dev_idx: " << (int)trezor_dev_idx << ". path: " << get_usb_path(bus_id, path)); @@ -1077,12 +1077,12 @@ namespace trezor{ return; } - MTRACE("Closing Trezor:WebUsbTransport"); + oxen::log::trace(logcat, "Closing Trezor:WebUsbTransport"); m_proto->session_end(*this); int r = libusb_release_interface(m_usb_device_handle, get_interface()); if (r != 0){ - MERROR("Could not release libusb interface: " << r); + oxen::log::error(logcat, "Could not release libusb interface: {}", r); } m_usb_device = nullptr; @@ -1107,7 +1107,7 @@ namespace trezor{ t->m_debug_mode = true; return t; #else - MINFO("Debug link is disabled in production"); + oxen::log::info(logcat, "Debug link is disabled in production"); return nullptr; #endif } @@ -1199,7 +1199,7 @@ namespace trezor{ try{ bt.enumerate(res); } catch (const std::exception & e){ - MERROR("BridgeTransport enumeration failed:" << e.what()); + oxen::log::error(logcat, "BridgeTransport enumeration failed:{}", e.what()); } #ifdef WITH_DEVICE_TREZOR_WEBUSB @@ -1207,7 +1207,7 @@ namespace trezor{ try{ btw.enumerate(res); } catch (const std::exception & e){ - MERROR("WebUsbTransport enumeration failed:" << e.what()); + oxen::log::error(logcat, "WebUsbTransport enumeration failed:{}", e.what()); } #endif @@ -1216,7 +1216,7 @@ namespace trezor{ try{ btu.enumerate(res); } catch (const std::exception & e){ - MERROR("UdpTransport enumeration failed:" << e.what()); + oxen::log::error(logcat, "UdpTransport enumeration failed:{}", e.what()); } #endif } diff --git a/src/gen_multisig/CMakeLists.txt b/src/gen_multisig/CMakeLists.txt index 9af0a22fa..5aaff52a4 100644 --- a/src/gen_multisig/CMakeLists.txt +++ b/src/gen_multisig/CMakeLists.txt @@ -40,4 +40,5 @@ target_link_libraries(gen_multisig Boost::program_options filesystem version + logging extra) diff --git a/src/gen_multisig/gen_multisig.cpp b/src/gen_multisig/gen_multisig.cpp index 795a0ff32..774638684 100644 --- a/src/gen_multisig/gen_multisig.cpp +++ b/src/gen_multisig/gen_multisig.cpp @@ -51,20 +51,18 @@ using namespace cryptonote; using boost::lexical_cast; namespace po = boost::program_options; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.gen_multisig" - namespace genms { const char* tr(const char* str) { return i18n_translate(str, "tools::gen_multisig"); } - } namespace { + static auto logcat = oxen::log::Cat("wallet.gen_multisig"); + const command_line::arg_descriptor arg_filename_base = {"filename-base", genms::tr("Base filename (-1, -2, etc suffixes will be appended as needed)"), ""}; const command_line::arg_descriptor arg_scheme = {"scheme", genms::tr("Give threshold and participants at once as M/N"), ""}; const command_line::arg_descriptor arg_participants = {"participants", genms::tr("How many participants will share parts of the multisig wallet"), 0}; @@ -181,7 +179,7 @@ int main(int argc, char* argv[]) desc_params, po::options_description{}, boost::program_options::positional_options_description(), - [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; }, + [](const std::string &s){ tools::scoped_message_writer() << s; }, "oxen-gen-multisig.log" ); if (!vm) diff --git a/src/logging/CMakeLists.txt b/src/logging/CMakeLists.txt new file mode 100644 index 000000000..87dc3c389 --- /dev/null +++ b/src/logging/CMakeLists.txt @@ -0,0 +1,5 @@ + +add_library(logging STATIC + oxen_logger.cpp +) +target_link_libraries(logging PUBLIC oxen::logging oxenmq) diff --git a/src/logging/dev_sink.h b/src/logging/dev_sink.h new file mode 100644 index 000000000..a69e9c563 --- /dev/null +++ b/src/logging/dev_sink.h @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include +#include +// A sink used to store most important logs for developers + +namespace oxen::logging +{ + template + class dev_sink : public spdlog::sinks::base_sink + { + using Base = spdlog::sinks::base_sink; + + // Potentially all entries will be returned in a + // single message, so we should keep the limit + // relatively small + static constexpr size_t BUFFER_SIZE = 100; + static constexpr size_t MAX_ENTRIES = 2 * BUFFER_SIZE; + + std::vector primary_buffer_; + std::vector secondary_buffer_; + // size_t log_entires + + protected: + void + sink_it_(const spdlog::details::log_msg& msg) override + { + spdlog::memory_buf_t formatted; + Base::formatter_->format(msg, formatted); + + if (primary_buffer_.size() >= BUFFER_SIZE) + { + secondary_buffer_ = std::move(primary_buffer_); + primary_buffer_.clear(); + } + + primary_buffer_.push_back(fmt::to_string(formatted)); + } + + void + flush_() override + { + // no op + } + + public: + dev_sink() : spdlog::sinks::base_sink() + { + primary_buffer_.reserve(BUFFER_SIZE); + secondary_buffer_.reserve(BUFFER_SIZE); + } + + std::vector + peek() + { + std::lock_guard lock{this->mutex_}; + + std::vector result; + result.reserve(MAX_ENTRIES); + + for (auto it = primary_buffer_.end() - 1; + it >= primary_buffer_.begin() && result.size() < MAX_ENTRIES; + --it) + { + result.push_back(*it); + } + + for (auto it = secondary_buffer_.end() - 1; + it >= secondary_buffer_.begin() && result.size() < MAX_ENTRIES; + --it) + { + result.push_back(*it); + } + + return result; + } + }; + +#include + using dev_sink_mt = dev_sink; + +} // namespace oxen::logging diff --git a/src/logging/oxen_logger.cpp b/src/logging/oxen_logger.cpp new file mode 100644 index 000000000..66bd74c8b --- /dev/null +++ b/src/logging/oxen_logger.cpp @@ -0,0 +1,173 @@ +#include "oxen_logger.h" +#include +#include + +#include +#include + +namespace oxen::logging +{ + static auto logcat = oxen::log::Cat("logging"); + + void + set_additional_log_categories(oxen::log::Level& log_level) + { + switch (log_level) + { + case log::Level::critical: + break; + case log::Level::err: + break; + case log::Level::warn: + log::set_level("net", log::Level::err); + log::set_level("net.http", log::Level::err); + log::set_level("net.p2p", log::Level::err); + log::set_level("net.p2p.msg", log::Level::err); + log::set_level("global", log::Level::info); + log::set_level("verify", log::Level::err); + log::set_level("serialization", log::Level::err); + log::set_level("logging", log::Level::info); + log::set_level("msgwriter", log::Level::info); + break; + case log::Level::info: + log::set_level("net", log::Level::err); + log::set_level("net.http", log::Level::err); + log::set_level("net.p2p", log::Level::err); + log::set_level("net.p2p.msg", log::Level::err); + log::set_level("verify", log::Level::err); + log::set_level("serialization", log::Level::err); + log::set_level("blockchain", log::Level::warn); + log::set_level("blockchain.db.lmdb", log::Level::warn); + log::set_level("service_nodes", log::Level::warn); + log::set_level("txpool", log::Level::warn); + log::set_level("construct_tx", log::Level::warn); + break; + case log::Level::debug: + break; + case log::Level::trace: + break; + default: + break; + } + } + + void + process_categories_string(const std::string& categories) + { + std::istringstream iss(categories); + std::string single_category_and_level, single_category, level_str; + std::optional log_level; + std::string::size_type level_separator = 0; + + while (getline(iss, single_category_and_level, ',')) + { + if ((level_separator = single_category_and_level.find(':')) != std::string::npos) + { + single_category = single_category_and_level.substr(0, level_separator); + level_str = single_category_and_level.substr(level_separator + 1, std::string::npos); + log_level = parse_level(level_str); + if (log_level.has_value()) + { + if (single_category == "*") + log::reset_level(*log_level); + else + log::set_level(single_category, *log_level); + } + } + } + log::info(logcat, "New log categories"); + } + + void + init(const std::string& log_location, oxen::log::Level log_level) + { + log::reset_level(log_level); + log::add_sink(log::Type::Print, "stdout"); + + constexpr size_t LOG_FILE_SIZE_LIMIT = 1024 * 1024 * 50; // 50MiB + constexpr size_t EXTRA_FILES = 1; + + // setting this to `true` can be useful for debugging on testnet + bool rotate_on_open = false; + + try + { + auto file_sink = std::make_shared( + log_location, LOG_FILE_SIZE_LIMIT, EXTRA_FILES, rotate_on_open); + + log::add_sink(std::move(file_sink)); + } + catch (const spdlog::spdlog_ex& ex) + { + log::error( + logcat, + "Failed to open {} for logging: {}. File logging disabled.", + log_location, + ex.what()); + return; + } + + set_additional_log_categories(log_level); + + log::info(logcat, "Writing logs to {}", log_location); + } + + using namespace std::literals; + + static constexpr std::array, 12> logLevels = { + {{""sv, oxen::log::Level::info}, + {"4"sv, oxen::log::Level::trace}, + {"3", oxen::log::Level::trace}, + {"2", oxen::log::Level::debug}, + {"1", oxen::log::Level::info}, + {"0", oxen::log::Level::warn}, + {"trace", oxen::log::Level::trace}, + {"debug", oxen::log::Level::debug}, + {"info", oxen::log::Level::info}, + {"warning", oxen::log::Level::warn}, + {"error", oxen::log::Level::err}, + {"critical", oxen::log::Level::critical}}}; + + std::optional + parse_level(std::string_view input) + { + for (const auto& [str, lvl] : logLevels) + if (str == input) + return lvl; + return std::nullopt; + } + + static constexpr std::array, 5> intLogLevels = { + {{4, oxen::log::Level::trace}, + {3, oxen::log::Level::trace}, + {2, oxen::log::Level::debug}, + {1, oxen::log::Level::info}, + {0, oxen::log::Level::warn}}}; + + std::optional + parse_level(uint8_t input) + { + for (const auto& [str, lvl] : intLogLevels) + if (str == input) + return lvl; + return std::nullopt; + } + + static constexpr std::array, 6> omqLogLevels = { + {{oxenmq::LogLevel::trace, oxen::log::Level::trace}, + {oxenmq::LogLevel::debug, oxen::log::Level::debug}, + {oxenmq::LogLevel::info, oxen::log::Level::info}, + {oxenmq::LogLevel::warn, oxen::log::Level::warn}, + {oxenmq::LogLevel::error, oxen::log::Level::err}, + {oxenmq::LogLevel::fatal, oxen::log::Level::critical}}}; + + std::optional + parse_level(oxenmq::LogLevel input) + { + for (const auto& [str, lvl] : omqLogLevels) + if (str == input) + return lvl; + return std::nullopt; + } + +} // namespace oxen::logging diff --git a/src/logging/oxen_logger.h b/src/logging/oxen_logger.h new file mode 100644 index 000000000..efa00d509 --- /dev/null +++ b/src/logging/oxen_logger.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include +#include + +#define OXEN_LOG_ENABLED(LVL) logcat->should_log(spdlog::level::LVL) + +inline auto globallogcat = oxen::log::Cat("global"); + +namespace oxen::logging +{ + void + init(const std::string& log_location, oxen::log::Level log_level); + void + set_additional_log_categories(const oxen::log::Level& log_level); + void + process_categories_string(const std::string& categories); + + std::optional + parse_level(std::string_view input); + std::optional + parse_level(uint8_t input); + std::optional + parse_level(oxenmq::LogLevel input); + +} // namespace oxen::logging diff --git a/src/mnemonics/CMakeLists.txt b/src/mnemonics/CMakeLists.txt index 1e6d3d16d..bf1670131 100644 --- a/src/mnemonics/CMakeLists.txt +++ b/src/mnemonics/CMakeLists.txt @@ -34,5 +34,5 @@ target_link_libraries(mnemonics PRIVATE cncrypto epee - easylogging + logging extra) diff --git a/src/mnemonics/chinese_simplified.h b/src/mnemonics/chinese_simplified.h index ff035dde0..cf9556d2c 100644 --- a/src/mnemonics/chinese_simplified.h +++ b/src/mnemonics/chinese_simplified.h @@ -1,1712 +1,1712 @@ -// Word list originally created by dabura667 and released under The MIT License (MIT) -// -// The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file chinese_simplified.h - * - * \brief Simplified Chinese word list and map. - */ - -#ifndef CHINESE_SIMPLIFIED_H -#define CHINESE_SIMPLIFIED_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Chinese_Simplified: public Base - { - public: - Chinese_Simplified(): Base("简体中文 (中国)", "Chinese (simplified)", {}, 1) - { - static constexpr const char * const words[NWORDS] = - { - "的", - "一", - "是", - "在", - "不", - "了", - "有", - "和", - "人", - "这", - "中", - "大", - "为", - "上", - "个", - "国", - "我", - "以", - "要", - "他", - "时", - "来", - "用", - "们", - "生", - "到", - "作", - "地", - "于", - "出", - "就", - "分", - "对", - "成", - "会", - "可", - "主", - "发", - "年", - "动", - "同", - "工", - "也", - "能", - "下", - "过", - "子", - "说", - "产", - "种", - "面", - "而", - "方", - "后", - "多", - "定", - "行", - "学", - "法", - "所", - "民", - "得", - "经", - "十", - "三", - "之", - "进", - "着", - "等", - "部", - "度", - "家", - "电", - "力", - "里", - "如", - "水", - "化", - "高", - "自", - "二", - "理", - "起", - "小", - "物", - "现", - "实", - "加", - "量", - "都", - "两", - "体", - "制", - "机", - "当", - "使", - "点", - "从", - "业", - "本", - "去", - "把", - "性", - "好", - "应", - "开", - "它", - "合", - "还", - "因", - "由", - "其", - "些", - "然", - "前", - "外", - "天", - "政", - "四", - "日", - "那", - "社", - "义", - "事", - "平", - "形", - "相", - "全", - "表", - "间", - "样", - "与", - "关", - "各", - "重", - "新", - "线", - "内", - "数", - "正", - "心", - "反", - "你", - "明", - "看", - "原", - "又", - "么", - "利", - "比", - "或", - "但", - "质", - "气", - "第", - "向", - "道", - "命", - "此", - "变", - "条", - "只", - "没", - "结", - "解", - "问", - "意", - "建", - "月", - "公", - "无", - "系", - "军", - "很", - "情", - "者", - "最", - "立", - "代", - "想", - "已", - "通", - "并", - "提", - "直", - "题", - "党", - "程", - "展", - "五", - "果", - "料", - "象", - "员", - "革", - "位", - "入", - "常", - "文", - "总", - "次", - "品", - "式", - "活", - "设", - "及", - "管", - "特", - "件", - "长", - "求", - "老", - "头", - "基", - "资", - "边", - "流", - "路", - "级", - "少", - "图", - "山", - "统", - "接", - "知", - "较", - "将", - "组", - "见", - "计", - "别", - "她", - "手", - "角", - "期", - "根", - "论", - "运", - "农", - "指", - "几", - "九", - "区", - "强", - "放", - "决", - "西", - "被", - "干", - "做", - "必", - "战", - "先", - "回", - "则", - "任", - "取", - "据", - "处", - "队", - "南", - "给", - "色", - "光", - "门", - "即", - "保", - "治", - "北", - "造", - "百", - "规", - "热", - "领", - "七", - "海", - "口", - "东", - "导", - "器", - "压", - "志", - "世", - "金", - "增", - "争", - "济", - "阶", - "油", - "思", - "术", - "极", - "交", - "受", - "联", - "什", - "认", - "六", - "共", - "权", - "收", - "证", - "改", - "清", - "美", - "再", - "采", - "转", - "更", - "单", - "风", - "切", - "打", - "白", - "教", - "速", - "花", - "带", - "安", - "场", - "身", - "车", - "例", - "真", - "务", - "具", - "万", - "每", - "目", - "至", - "达", - "走", - "积", - "示", - "议", - "声", - "报", - "斗", - "完", - "类", - "八", - "离", - "华", - "名", - "确", - "才", - "科", - "张", - "信", - "马", - "节", - "话", - "米", - "整", - "空", - "元", - "况", - "今", - "集", - "温", - "传", - "土", - "许", - "步", - "群", - "广", - "石", - "记", - "需", - "段", - "研", - "界", - "拉", - "林", - "律", - "叫", - "且", - "究", - "观", - "越", - "织", - "装", - "影", - "算", - "低", - "持", - "音", - "众", - "书", - "布", - "复", - "容", - "儿", - "须", - "际", - "商", - "非", - "验", - "连", - "断", - "深", - "难", - "近", - "矿", - "千", - "周", - "委", - "素", - "技", - "备", - "半", - "办", - "青", - "省", - "列", - "习", - "响", - "约", - "支", - "般", - "史", - "感", - "劳", - "便", - "团", - "往", - "酸", - "历", - "市", - "克", - "何", - "除", - "消", - "构", - "府", - "称", - "太", - "准", - "精", - "值", - "号", - "率", - "族", - "维", - "划", - "选", - "标", - "写", - "存", - "候", - "毛", - "亲", - "快", - "效", - "斯", - "院", - "查", - "江", - "型", - "眼", - "王", - "按", - "格", - "养", - "易", - "置", - "派", - "层", - "片", - "始", - "却", - "专", - "状", - "育", - "厂", - "京", - "识", - "适", - "属", - "圆", - "包", - "火", - "住", - "调", - "满", - "县", - "局", - "照", - "参", - "红", - "细", - "引", - "听", - "该", - "铁", - "价", - "严", - "首", - "底", - "液", - "官", - "德", - "随", - "病", - "苏", - "失", - "尔", - "死", - "讲", - "配", - "女", - "黄", - "推", - "显", - "谈", - "罪", - "神", - "艺", - "呢", - "席", - "含", - "企", - "望", - "密", - "批", - "营", - "项", - "防", - "举", - "球", - "英", - "氧", - "势", - "告", - "李", - "台", - "落", - "木", - "帮", - "轮", - "破", - "亚", - "师", - "围", - "注", - "远", - "字", - "材", - "排", - "供", - "河", - "态", - "封", - "另", - "施", - "减", - "树", - "溶", - "怎", - "止", - "案", - "言", - "士", - "均", - "武", - "固", - "叶", - "鱼", - "波", - "视", - "仅", - "费", - "紧", - "爱", - "左", - "章", - "早", - "朝", - "害", - "续", - "轻", - "服", - "试", - "食", - "充", - "兵", - "源", - "判", - "护", - "司", - "足", - "某", - "练", - "差", - "致", - "板", - "田", - "降", - "黑", - "犯", - "负", - "击", - "范", - "继", - "兴", - "似", - "余", - "坚", - "曲", - "输", - "修", - "故", - "城", - "夫", - "够", - "送", - "笔", - "船", - "占", - "右", - "财", - "吃", - "富", - "春", - "职", - "觉", - "汉", - "画", - "功", - "巴", - "跟", - "虽", - "杂", - "飞", - "检", - "吸", - "助", - "升", - "阳", - "互", - "初", - "创", - "抗", - "考", - "投", - "坏", - "策", - "古", - "径", - "换", - "未", - "跑", - "留", - "钢", - "曾", - "端", - "责", - "站", - "简", - "述", - "钱", - "副", - "尽", - "帝", - "射", - "草", - "冲", - "承", - "独", - "令", - "限", - "阿", - "宣", - "环", - "双", - "请", - "超", - "微", - "让", - "控", - "州", - "良", - "轴", - "找", - "否", - "纪", - "益", - "依", - "优", - "顶", - "础", - "载", - "倒", - "房", - "突", - "坐", - "粉", - "敌", - "略", - "客", - "袁", - "冷", - "胜", - "绝", - "析", - "块", - "剂", - "测", - "丝", - "协", - "诉", - "念", - "陈", - "仍", - "罗", - "盐", - "友", - "洋", - "错", - "苦", - "夜", - "刑", - "移", - "频", - "逐", - "靠", - "混", - "母", - "短", - "皮", - "终", - "聚", - "汽", - "村", - "云", - "哪", - "既", - "距", - "卫", - "停", - "烈", - "央", - "察", - "烧", - "迅", - "境", - "若", - "印", - "洲", - "刻", - "括", - "激", - "孔", - "搞", - "甚", - "室", - "待", - "核", - "校", - "散", - "侵", - "吧", - "甲", - "游", - "久", - "菜", - "味", - "旧", - "模", - "湖", - "货", - "损", - "预", - "阻", - "毫", - "普", - "稳", - "乙", - "妈", - "植", - "息", - "扩", - "银", - "语", - "挥", - "酒", - "守", - "拿", - "序", - "纸", - "医", - "缺", - "雨", - "吗", - "针", - "刘", - "啊", - "急", - "唱", - "误", - "训", - "愿", - "审", - "附", - "获", - "茶", - "鲜", - "粮", - "斤", - "孩", - "脱", - "硫", - "肥", - "善", - "龙", - "演", - "父", - "渐", - "血", - "欢", - "械", - "掌", - "歌", - "沙", - "刚", - "攻", - "谓", - "盾", - "讨", - "晚", - "粒", - "乱", - "燃", - "矛", - "乎", - "杀", - "药", - "宁", - "鲁", - "贵", - "钟", - "煤", - "读", - "班", - "伯", - "香", - "介", - "迫", - "句", - "丰", - "培", - "握", - "兰", - "担", - "弦", - "蛋", - "沉", - "假", - "穿", - "执", - "答", - "乐", - "谁", - "顺", - "烟", - "缩", - "征", - "脸", - "喜", - "松", - "脚", - "困", - "异", - "免", - "背", - "星", - "福", - "买", - "染", - "井", - "概", - "慢", - "怕", - "磁", - "倍", - "祖", - "皇", - "促", - "静", - "补", - "评", - "翻", - "肉", - "践", - "尼", - "衣", - "宽", - "扬", - "棉", - "希", - "伤", - "操", - "垂", - "秋", - "宜", - "氢", - "套", - "督", - "振", - "架", - "亮", - "末", - "宪", - "庆", - "编", - "牛", - "触", - "映", - "雷", - "销", - "诗", - "座", - "居", - "抓", - "裂", - "胞", - "呼", - "娘", - "景", - "威", - "绿", - "晶", - "厚", - "盟", - "衡", - "鸡", - "孙", - "延", - "危", - "胶", - "屋", - "乡", - "临", - "陆", - "顾", - "掉", - "呀", - "灯", - "岁", - "措", - "束", - "耐", - "剧", - "玉", - "赵", - "跳", - "哥", - "季", - "课", - "凯", - "胡", - "额", - "款", - "绍", - "卷", - "齐", - "伟", - "蒸", - "殖", - "永", - "宗", - "苗", - "川", - "炉", - "岩", - "弱", - "零", - "杨", - "奏", - "沿", - "露", - "杆", - "探", - "滑", - "镇", - "饭", - "浓", - "航", - "怀", - "赶", - "库", - "夺", - "伊", - "灵", - "税", - "途", - "灭", - "赛", - "归", - "召", - "鼓", - "播", - "盘", - "裁", - "险", - "康", - "唯", - "录", - "菌", - "纯", - "借", - "糖", - "盖", - "横", - "符", - "私", - "努", - "堂", - "域", - "枪", - "润", - "幅", - "哈", - "竟", - "熟", - "虫", - "泽", - "脑", - "壤", - "碳", - "欧", - "遍", - "侧", - "寨", - "敢", - "彻", - "虑", - "斜", - "薄", - "庭", - "纳", - "弹", - "饲", - "伸", - "折", - "麦", - "湿", - "暗", - "荷", - "瓦", - "塞", - "床", - "筑", - "恶", - "户", - "访", - "塔", - "奇", - "透", - "梁", - "刀", - "旋", - "迹", - "卡", - "氯", - "遇", - "份", - "毒", - "泥", - "退", - "洗", - "摆", - "灰", - "彩", - "卖", - "耗", - "夏", - "择", - "忙", - "铜", - "献", - "硬", - "予", - "繁", - "圈", - "雪", - "函", - "亦", - "抽", - "篇", - "阵", - "阴", - "丁", - "尺", - "追", - "堆", - "雄", - "迎", - "泛", - "爸", - "楼", - "避", - "谋", - "吨", - "野", - "猪", - "旗", - "累", - "偏", - "典", - "馆", - "索", - "秦", - "脂", - "潮", - "爷", - "豆", - "忽", - "托", - "惊", - "塑", - "遗", - "愈", - "朱", - "替", - "纤", - "粗", - "倾", - "尚", - "痛", - "楚", - "谢", - "奋", - "购", - "磨", - "君", - "池", - "旁", - "碎", - "骨", - "监", - "捕", - "弟", - "暴", - "割", - "贯", - "殊", - "释", - "词", - "亡", - "壁", - "顿", - "宝", - "午", - "尘", - "闻", - "揭", - "炮", - "残", - "冬", - "桥", - "妇", - "警", - "综", - "招", - "吴", - "付", - "浮", - "遭", - "徐", - "您", - "摇", - "谷", - "赞", - "箱", - "隔", - "订", - "男", - "吹", - "园", - "纷", - "唐", - "败", - "宋", - "玻", - "巨", - "耕", - "坦", - "荣", - "闭", - "湾", - "键", - "凡", - "驻", - "锅", - "救", - "恩", - "剥", - "凝", - "碱", - "齿", - "截", - "炼", - "麻", - "纺", - "禁", - "废", - "盛", - "版", - "缓", - "净", - "睛", - "昌", - "婚", - "涉", - "筒", - "嘴", - "插", - "岸", - "朗", - "庄", - "街", - "藏", - "姑", - "贸", - "腐", - "奴", - "啦", - "惯", - "乘", - "伙", - "恢", - "匀", - "纱", - "扎", - "辩", - "耳", - "彪", - "臣", - "亿", - "璃", - "抵", - "脉", - "秀", - "萨", - "俄", - "网", - "舞", - "店", - "喷", - "纵", - "寸", - "汗", - "挂", - "洪", - "贺", - "闪", - "柬", - "爆", - "烯", - "津", - "稻", - "墙", - "软", - "勇", - "像", - "滚", - "厘", - "蒙", - "芳", - "肯", - "坡", - "柱", - "荡", - "腿", - "仪", - "旅", - "尾", - "轧", - "冰", - "贡", - "登", - "黎", - "削", - "钻", - "勒", - "逃", - "障", - "氨", - "郭", - "峰", - "币", - "港", - "伏", - "轨", - "亩", - "毕", - "擦", - "莫", - "刺", - "浪", - "秘", - "援", - "株", - "健", - "售", - "股", - "岛", - "甘", - "泡", - "睡", - "童", - "铸", - "汤", - "阀", - "休", - "汇", - "舍", - "牧", - "绕", - "炸", - "哲", - "磷", - "绩", - "朋", - "淡", - "尖", - "启", - "陷", - "柴", - "呈", - "徒", - "颜", - "泪", - "稍", - "忘", - "泵", - "蓝", - "拖", - "洞", - "授", - "镜", - "辛", - "壮", - "锋", - "贫", - "虚", - "弯", - "摩", - "泰", - "幼", - "廷", - "尊", - "窗", - "纲", - "弄", - "隶", - "疑", - "氏", - "宫", - "姐", - "震", - "瑞", - "怪", - "尤", - "琴", - "循", - "描", - "膜", - "违", - "夹", - "腰", - "缘", - "珠", - "穷", - "森", - "枝", - "竹", - "沟", - "催", - "绳", - "忆", - "邦", - "剩", - "幸", - "浆", - "栏", - "拥", - "牙", - "贮", - "礼", - "滤", - "钠", - "纹", - "罢", - "拍", - "咱", - "喊", - "袖", - "埃", - "勤", - "罚", - "焦", - "潜", - "伍", - "墨", - "欲", - "缝", - "姓", - "刊", - "饱", - "仿", - "奖", - "铝", - "鬼", - "丽", - "跨", - "默", - "挖", - "链", - "扫", - "喝", - "袋", - "炭", - "污", - "幕", - "诸", - "弧", - "励", - "梅", - "奶", - "洁", - "灾", - "舟", - "鉴", - "苯", - "讼", - "抱", - "毁", - "懂", - "寒", - "智", - "埔", - "寄", - "届", - "跃", - "渡", - "挑", - "丹", - "艰", - "贝", - "碰", - "拔", - "爹", - "戴", - "码", - "梦", - "芽", - "熔", - "赤", - "渔", - "哭", - "敬", - "颗", - "奔", - "铅", - "仲", - "虎", - "稀", - "妹", - "乏", - "珍", - "申", - "桌", - "遵", - "允", - "隆", - "螺", - "仓", - "魏", - "锐", - "晓", - "氮", - "兼", - "隐", - "碍", - "赫", - "拨", - "忠", - "肃", - "缸", - "牵", - "抢", - "博", - "巧", - "壳", - "兄", - "杜", - "讯", - "诚", - "碧", - "祥", - "柯", - "页", - "巡", - "矩", - "悲", - "灌", - "龄", - "伦", - "票", - "寻", - "桂", - "铺", - "圣", - "恐", - "恰", - "郑", - "趣", - "抬", - "荒", - "腾", - "贴", - "柔", - "滴", - "猛", - "阔", - "辆", - "妻", - "填", - "撤", - "储", - "签", - "闹", - "扰", - "紫", - "砂", - "递", - "戏", - "吊", - "陶", - "伐", - "喂", - "疗", - "瓶", - "婆", - "抚", - "臂", - "摸", - "忍", - "虾", - "蜡", - "邻", - "胸", - "巩", - "挤", - "偶", - "弃", - "槽", - "劲", - "乳", - "邓", - "吉", - "仁", - "烂", - "砖", - "租", - "乌", - "舰", - "伴", - "瓜", - "浅", - "丙", - "暂", - "燥", - "橡", - "柳", - "迷", - "暖", - "牌", - "秧", - "胆", - "详", - "簧", - "踏", - "瓷", - "谱", - "呆", - "宾", - "糊", - "洛", - "辉", - "愤", - "竞", - "隙", - "怒", - "粘", - "乃", - "绪", - "肩", - "籍", - "敏", - "涂", - "熙", - "皆", - "侦", - "悬", - "掘", - "享", - "纠", - "醒", - "狂", - "锁", - "淀", - "恨", - "牲", - "霸", - "爬", - "赏", - "逆", - "玩", - "陵", - "祝", - "秒", - "浙", - "貌" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list originally created by dabura667 and released under The MIT License (MIT) +// +// The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file chinese_simplified.h + * + * \brief Simplified Chinese word list and map. + */ + +#ifndef CHINESE_SIMPLIFIED_H +#define CHINESE_SIMPLIFIED_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Chinese_Simplified: public Base + { + public: + Chinese_Simplified(): Base("简体中文 (中国)", "Chinese (simplified)", {}, 1) + { + static constexpr const char * const words[NWORDS] = + { + "的", + "一", + "是", + "在", + "不", + "了", + "有", + "和", + "人", + "这", + "中", + "大", + "为", + "上", + "个", + "国", + "我", + "以", + "要", + "他", + "时", + "来", + "用", + "们", + "生", + "到", + "作", + "地", + "于", + "出", + "就", + "分", + "对", + "成", + "会", + "可", + "主", + "发", + "年", + "动", + "同", + "工", + "也", + "能", + "下", + "过", + "子", + "说", + "产", + "种", + "面", + "而", + "方", + "后", + "多", + "定", + "行", + "学", + "法", + "所", + "民", + "得", + "经", + "十", + "三", + "之", + "进", + "着", + "等", + "部", + "度", + "家", + "电", + "力", + "里", + "如", + "水", + "化", + "高", + "自", + "二", + "理", + "起", + "小", + "物", + "现", + "实", + "加", + "量", + "都", + "两", + "体", + "制", + "机", + "当", + "使", + "点", + "从", + "业", + "本", + "去", + "把", + "性", + "好", + "应", + "开", + "它", + "合", + "还", + "因", + "由", + "其", + "些", + "然", + "前", + "外", + "天", + "政", + "四", + "日", + "那", + "社", + "义", + "事", + "平", + "形", + "相", + "全", + "表", + "间", + "样", + "与", + "关", + "各", + "重", + "新", + "线", + "内", + "数", + "正", + "心", + "反", + "你", + "明", + "看", + "原", + "又", + "么", + "利", + "比", + "或", + "但", + "质", + "气", + "第", + "向", + "道", + "命", + "此", + "变", + "条", + "只", + "没", + "结", + "解", + "问", + "意", + "建", + "月", + "公", + "无", + "系", + "军", + "很", + "情", + "者", + "最", + "立", + "代", + "想", + "已", + "通", + "并", + "提", + "直", + "题", + "党", + "程", + "展", + "五", + "果", + "料", + "象", + "员", + "革", + "位", + "入", + "常", + "文", + "总", + "次", + "品", + "式", + "活", + "设", + "及", + "管", + "特", + "件", + "长", + "求", + "老", + "头", + "基", + "资", + "边", + "流", + "路", + "级", + "少", + "图", + "山", + "统", + "接", + "知", + "较", + "将", + "组", + "见", + "计", + "别", + "她", + "手", + "角", + "期", + "根", + "论", + "运", + "农", + "指", + "几", + "九", + "区", + "强", + "放", + "决", + "西", + "被", + "干", + "做", + "必", + "战", + "先", + "回", + "则", + "任", + "取", + "据", + "处", + "队", + "南", + "给", + "色", + "光", + "门", + "即", + "保", + "治", + "北", + "造", + "百", + "规", + "热", + "领", + "七", + "海", + "口", + "东", + "导", + "器", + "压", + "志", + "世", + "金", + "增", + "争", + "济", + "阶", + "油", + "思", + "术", + "极", + "交", + "受", + "联", + "什", + "认", + "六", + "共", + "权", + "收", + "证", + "改", + "清", + "美", + "再", + "采", + "转", + "更", + "单", + "风", + "切", + "打", + "白", + "教", + "速", + "花", + "带", + "安", + "场", + "身", + "车", + "例", + "真", + "务", + "具", + "万", + "每", + "目", + "至", + "达", + "走", + "积", + "示", + "议", + "声", + "报", + "斗", + "完", + "类", + "八", + "离", + "华", + "名", + "确", + "才", + "科", + "张", + "信", + "马", + "节", + "话", + "米", + "整", + "空", + "元", + "况", + "今", + "集", + "温", + "传", + "土", + "许", + "步", + "群", + "广", + "石", + "记", + "需", + "段", + "研", + "界", + "拉", + "林", + "律", + "叫", + "且", + "究", + "观", + "越", + "织", + "装", + "影", + "算", + "低", + "持", + "音", + "众", + "书", + "布", + "复", + "容", + "儿", + "须", + "际", + "商", + "非", + "验", + "连", + "断", + "深", + "难", + "近", + "矿", + "千", + "周", + "委", + "素", + "技", + "备", + "半", + "办", + "青", + "省", + "列", + "习", + "响", + "约", + "支", + "般", + "史", + "感", + "劳", + "便", + "团", + "往", + "酸", + "历", + "市", + "克", + "何", + "除", + "消", + "构", + "府", + "称", + "太", + "准", + "精", + "值", + "号", + "率", + "族", + "维", + "划", + "选", + "标", + "写", + "存", + "候", + "毛", + "亲", + "快", + "效", + "斯", + "院", + "查", + "江", + "型", + "眼", + "王", + "按", + "格", + "养", + "易", + "置", + "派", + "层", + "片", + "始", + "却", + "专", + "状", + "育", + "厂", + "京", + "识", + "适", + "属", + "圆", + "包", + "火", + "住", + "调", + "满", + "县", + "局", + "照", + "参", + "红", + "细", + "引", + "听", + "该", + "铁", + "价", + "严", + "首", + "底", + "液", + "官", + "德", + "随", + "病", + "苏", + "失", + "尔", + "死", + "讲", + "配", + "女", + "黄", + "推", + "显", + "谈", + "罪", + "神", + "艺", + "呢", + "席", + "含", + "企", + "望", + "密", + "批", + "营", + "项", + "防", + "举", + "球", + "英", + "氧", + "势", + "告", + "李", + "台", + "落", + "木", + "帮", + "轮", + "破", + "亚", + "师", + "围", + "注", + "远", + "字", + "材", + "排", + "供", + "河", + "态", + "封", + "另", + "施", + "减", + "树", + "溶", + "怎", + "止", + "案", + "言", + "士", + "均", + "武", + "固", + "叶", + "鱼", + "波", + "视", + "仅", + "费", + "紧", + "爱", + "左", + "章", + "早", + "朝", + "害", + "续", + "轻", + "服", + "试", + "食", + "充", + "兵", + "源", + "判", + "护", + "司", + "足", + "某", + "练", + "差", + "致", + "板", + "田", + "降", + "黑", + "犯", + "负", + "击", + "范", + "继", + "兴", + "似", + "余", + "坚", + "曲", + "输", + "修", + "故", + "城", + "夫", + "够", + "送", + "笔", + "船", + "占", + "右", + "财", + "吃", + "富", + "春", + "职", + "觉", + "汉", + "画", + "功", + "巴", + "跟", + "虽", + "杂", + "飞", + "检", + "吸", + "助", + "升", + "阳", + "互", + "初", + "创", + "抗", + "考", + "投", + "坏", + "策", + "古", + "径", + "换", + "未", + "跑", + "留", + "钢", + "曾", + "端", + "责", + "站", + "简", + "述", + "钱", + "副", + "尽", + "帝", + "射", + "草", + "冲", + "承", + "独", + "令", + "限", + "阿", + "宣", + "环", + "双", + "请", + "超", + "微", + "让", + "控", + "州", + "良", + "轴", + "找", + "否", + "纪", + "益", + "依", + "优", + "顶", + "础", + "载", + "倒", + "房", + "突", + "坐", + "粉", + "敌", + "略", + "客", + "袁", + "冷", + "胜", + "绝", + "析", + "块", + "剂", + "测", + "丝", + "协", + "诉", + "念", + "陈", + "仍", + "罗", + "盐", + "友", + "洋", + "错", + "苦", + "夜", + "刑", + "移", + "频", + "逐", + "靠", + "混", + "母", + "短", + "皮", + "终", + "聚", + "汽", + "村", + "云", + "哪", + "既", + "距", + "卫", + "停", + "烈", + "央", + "察", + "烧", + "迅", + "境", + "若", + "印", + "洲", + "刻", + "括", + "激", + "孔", + "搞", + "甚", + "室", + "待", + "核", + "校", + "散", + "侵", + "吧", + "甲", + "游", + "久", + "菜", + "味", + "旧", + "模", + "湖", + "货", + "损", + "预", + "阻", + "毫", + "普", + "稳", + "乙", + "妈", + "植", + "息", + "扩", + "银", + "语", + "挥", + "酒", + "守", + "拿", + "序", + "纸", + "医", + "缺", + "雨", + "吗", + "针", + "刘", + "啊", + "急", + "唱", + "误", + "训", + "愿", + "审", + "附", + "获", + "茶", + "鲜", + "粮", + "斤", + "孩", + "脱", + "硫", + "肥", + "善", + "龙", + "演", + "父", + "渐", + "血", + "欢", + "械", + "掌", + "歌", + "沙", + "刚", + "攻", + "谓", + "盾", + "讨", + "晚", + "粒", + "乱", + "燃", + "矛", + "乎", + "杀", + "药", + "宁", + "鲁", + "贵", + "钟", + "煤", + "读", + "班", + "伯", + "香", + "介", + "迫", + "句", + "丰", + "培", + "握", + "兰", + "担", + "弦", + "蛋", + "沉", + "假", + "穿", + "执", + "答", + "乐", + "谁", + "顺", + "烟", + "缩", + "征", + "脸", + "喜", + "松", + "脚", + "困", + "异", + "免", + "背", + "星", + "福", + "买", + "染", + "井", + "概", + "慢", + "怕", + "磁", + "倍", + "祖", + "皇", + "促", + "静", + "补", + "评", + "翻", + "肉", + "践", + "尼", + "衣", + "宽", + "扬", + "棉", + "希", + "伤", + "操", + "垂", + "秋", + "宜", + "氢", + "套", + "督", + "振", + "架", + "亮", + "末", + "宪", + "庆", + "编", + "牛", + "触", + "映", + "雷", + "销", + "诗", + "座", + "居", + "抓", + "裂", + "胞", + "呼", + "娘", + "景", + "威", + "绿", + "晶", + "厚", + "盟", + "衡", + "鸡", + "孙", + "延", + "危", + "胶", + "屋", + "乡", + "临", + "陆", + "顾", + "掉", + "呀", + "灯", + "岁", + "措", + "束", + "耐", + "剧", + "玉", + "赵", + "跳", + "哥", + "季", + "课", + "凯", + "胡", + "额", + "款", + "绍", + "卷", + "齐", + "伟", + "蒸", + "殖", + "永", + "宗", + "苗", + "川", + "炉", + "岩", + "弱", + "零", + "杨", + "奏", + "沿", + "露", + "杆", + "探", + "滑", + "镇", + "饭", + "浓", + "航", + "怀", + "赶", + "库", + "夺", + "伊", + "灵", + "税", + "途", + "灭", + "赛", + "归", + "召", + "鼓", + "播", + "盘", + "裁", + "险", + "康", + "唯", + "录", + "菌", + "纯", + "借", + "糖", + "盖", + "横", + "符", + "私", + "努", + "堂", + "域", + "枪", + "润", + "幅", + "哈", + "竟", + "熟", + "虫", + "泽", + "脑", + "壤", + "碳", + "欧", + "遍", + "侧", + "寨", + "敢", + "彻", + "虑", + "斜", + "薄", + "庭", + "纳", + "弹", + "饲", + "伸", + "折", + "麦", + "湿", + "暗", + "荷", + "瓦", + "塞", + "床", + "筑", + "恶", + "户", + "访", + "塔", + "奇", + "透", + "梁", + "刀", + "旋", + "迹", + "卡", + "氯", + "遇", + "份", + "毒", + "泥", + "退", + "洗", + "摆", + "灰", + "彩", + "卖", + "耗", + "夏", + "择", + "忙", + "铜", + "献", + "硬", + "予", + "繁", + "圈", + "雪", + "函", + "亦", + "抽", + "篇", + "阵", + "阴", + "丁", + "尺", + "追", + "堆", + "雄", + "迎", + "泛", + "爸", + "楼", + "避", + "谋", + "吨", + "野", + "猪", + "旗", + "累", + "偏", + "典", + "馆", + "索", + "秦", + "脂", + "潮", + "爷", + "豆", + "忽", + "托", + "惊", + "塑", + "遗", + "愈", + "朱", + "替", + "纤", + "粗", + "倾", + "尚", + "痛", + "楚", + "谢", + "奋", + "购", + "磨", + "君", + "池", + "旁", + "碎", + "骨", + "监", + "捕", + "弟", + "暴", + "割", + "贯", + "殊", + "释", + "词", + "亡", + "壁", + "顿", + "宝", + "午", + "尘", + "闻", + "揭", + "炮", + "残", + "冬", + "桥", + "妇", + "警", + "综", + "招", + "吴", + "付", + "浮", + "遭", + "徐", + "您", + "摇", + "谷", + "赞", + "箱", + "隔", + "订", + "男", + "吹", + "园", + "纷", + "唐", + "败", + "宋", + "玻", + "巨", + "耕", + "坦", + "荣", + "闭", + "湾", + "键", + "凡", + "驻", + "锅", + "救", + "恩", + "剥", + "凝", + "碱", + "齿", + "截", + "炼", + "麻", + "纺", + "禁", + "废", + "盛", + "版", + "缓", + "净", + "睛", + "昌", + "婚", + "涉", + "筒", + "嘴", + "插", + "岸", + "朗", + "庄", + "街", + "藏", + "姑", + "贸", + "腐", + "奴", + "啦", + "惯", + "乘", + "伙", + "恢", + "匀", + "纱", + "扎", + "辩", + "耳", + "彪", + "臣", + "亿", + "璃", + "抵", + "脉", + "秀", + "萨", + "俄", + "网", + "舞", + "店", + "喷", + "纵", + "寸", + "汗", + "挂", + "洪", + "贺", + "闪", + "柬", + "爆", + "烯", + "津", + "稻", + "墙", + "软", + "勇", + "像", + "滚", + "厘", + "蒙", + "芳", + "肯", + "坡", + "柱", + "荡", + "腿", + "仪", + "旅", + "尾", + "轧", + "冰", + "贡", + "登", + "黎", + "削", + "钻", + "勒", + "逃", + "障", + "氨", + "郭", + "峰", + "币", + "港", + "伏", + "轨", + "亩", + "毕", + "擦", + "莫", + "刺", + "浪", + "秘", + "援", + "株", + "健", + "售", + "股", + "岛", + "甘", + "泡", + "睡", + "童", + "铸", + "汤", + "阀", + "休", + "汇", + "舍", + "牧", + "绕", + "炸", + "哲", + "磷", + "绩", + "朋", + "淡", + "尖", + "启", + "陷", + "柴", + "呈", + "徒", + "颜", + "泪", + "稍", + "忘", + "泵", + "蓝", + "拖", + "洞", + "授", + "镜", + "辛", + "壮", + "锋", + "贫", + "虚", + "弯", + "摩", + "泰", + "幼", + "廷", + "尊", + "窗", + "纲", + "弄", + "隶", + "疑", + "氏", + "宫", + "姐", + "震", + "瑞", + "怪", + "尤", + "琴", + "循", + "描", + "膜", + "违", + "夹", + "腰", + "缘", + "珠", + "穷", + "森", + "枝", + "竹", + "沟", + "催", + "绳", + "忆", + "邦", + "剩", + "幸", + "浆", + "栏", + "拥", + "牙", + "贮", + "礼", + "滤", + "钠", + "纹", + "罢", + "拍", + "咱", + "喊", + "袖", + "埃", + "勤", + "罚", + "焦", + "潜", + "伍", + "墨", + "欲", + "缝", + "姓", + "刊", + "饱", + "仿", + "奖", + "铝", + "鬼", + "丽", + "跨", + "默", + "挖", + "链", + "扫", + "喝", + "袋", + "炭", + "污", + "幕", + "诸", + "弧", + "励", + "梅", + "奶", + "洁", + "灾", + "舟", + "鉴", + "苯", + "讼", + "抱", + "毁", + "懂", + "寒", + "智", + "埔", + "寄", + "届", + "跃", + "渡", + "挑", + "丹", + "艰", + "贝", + "碰", + "拔", + "爹", + "戴", + "码", + "梦", + "芽", + "熔", + "赤", + "渔", + "哭", + "敬", + "颗", + "奔", + "铅", + "仲", + "虎", + "稀", + "妹", + "乏", + "珍", + "申", + "桌", + "遵", + "允", + "隆", + "螺", + "仓", + "魏", + "锐", + "晓", + "氮", + "兼", + "隐", + "碍", + "赫", + "拨", + "忠", + "肃", + "缸", + "牵", + "抢", + "博", + "巧", + "壳", + "兄", + "杜", + "讯", + "诚", + "碧", + "祥", + "柯", + "页", + "巡", + "矩", + "悲", + "灌", + "龄", + "伦", + "票", + "寻", + "桂", + "铺", + "圣", + "恐", + "恰", + "郑", + "趣", + "抬", + "荒", + "腾", + "贴", + "柔", + "滴", + "猛", + "阔", + "辆", + "妻", + "填", + "撤", + "储", + "签", + "闹", + "扰", + "紫", + "砂", + "递", + "戏", + "吊", + "陶", + "伐", + "喂", + "疗", + "瓶", + "婆", + "抚", + "臂", + "摸", + "忍", + "虾", + "蜡", + "邻", + "胸", + "巩", + "挤", + "偶", + "弃", + "槽", + "劲", + "乳", + "邓", + "吉", + "仁", + "烂", + "砖", + "租", + "乌", + "舰", + "伴", + "瓜", + "浅", + "丙", + "暂", + "燥", + "橡", + "柳", + "迷", + "暖", + "牌", + "秧", + "胆", + "详", + "簧", + "踏", + "瓷", + "谱", + "呆", + "宾", + "糊", + "洛", + "辉", + "愤", + "竞", + "隙", + "怒", + "粘", + "乃", + "绪", + "肩", + "籍", + "敏", + "涂", + "熙", + "皆", + "侦", + "悬", + "掘", + "享", + "纠", + "醒", + "狂", + "锁", + "淀", + "恨", + "牲", + "霸", + "爬", + "赏", + "逆", + "玩", + "陵", + "祝", + "秒", + "浙", + "貌" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/dutch.h b/src/mnemonics/dutch.h index 14ba56a7e..083e84a2b 100644 --- a/src/mnemonics/dutch.h +++ b/src/mnemonics/dutch.h @@ -1,1689 +1,1689 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file dutch.h - * - * \brief New Dutch word list and map. - */ - -#ifndef DUTCH_H -#define DUTCH_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Dutch: public Base - { - public: - Dutch(): Base("Nederlands", "Dutch", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "aalglad", - "aalscholver", - "aambeeld", - "aangeef", - "aanlandig", - "aanvaard", - "aanwakker", - "aapmens", - "aarten", - "abdicatie", - "abnormaal", - "abrikoos", - "accu", - "acuut", - "adjudant", - "admiraal", - "advies", - "afbidding", - "afdracht", - "affaire", - "affiche", - "afgang", - "afkick", - "afknap", - "aflees", - "afmijner", - "afname", - "afpreekt", - "afrader", - "afspeel", - "aftocht", - "aftrek", - "afzijdig", - "ahornboom", - "aktetas", - "akzo", - "alchemist", - "alcohol", - "aldaar", - "alexander", - "alfabet", - "alfredo", - "alice", - "alikruik", - "allrisk", - "altsax", - "alufolie", - "alziend", - "amai", - "ambacht", - "ambieer", - "amina", - "amnestie", - "amok", - "ampul", - "amuzikaal", - "angela", - "aniek", - "antje", - "antwerpen", - "anya", - "aorta", - "apache", - "apekool", - "appelaar", - "arganolie", - "argeloos", - "armoede", - "arrenslee", - "artritis", - "arubaan", - "asbak", - "ascii", - "asgrauw", - "asjes", - "asml", - "aspunt", - "asurn", - "asveld", - "aterling", - "atomair", - "atrium", - "atsma", - "atypisch", - "auping", - "aura", - "avifauna", - "axiaal", - "azoriaan", - "azteek", - "azuur", - "bachelor", - "badderen", - "badhotel", - "badmantel", - "badsteden", - "balie", - "ballans", - "balvers", - "bamibal", - "banneling", - "barracuda", - "basaal", - "batelaan", - "batje", - "beambte", - "bedlamp", - "bedwelmd", - "befaamd", - "begierd", - "begraaf", - "behield", - "beijaard", - "bejaagd", - "bekaaid", - "beks", - "bektas", - "belaad", - "belboei", - "belderbos", - "beloerd", - "beluchten", - "bemiddeld", - "benadeeld", - "benijd", - "berechten", - "beroemd", - "besef", - "besseling", - "best", - "betichten", - "bevind", - "bevochten", - "bevraagd", - "bewust", - "bidplaats", - "biefstuk", - "biemans", - "biezen", - "bijbaan", - "bijeenkom", - "bijfiguur", - "bijkaart", - "bijlage", - "bijpaard", - "bijtgaar", - "bijweg", - "bimmel", - "binck", - "bint", - "biobak", - "biotisch", - "biseks", - "bistro", - "bitter", - "bitumen", - "bizar", - "blad", - "bleken", - "blender", - "bleu", - "blief", - "blijven", - "blozen", - "bock", - "boef", - "boei", - "boks", - "bolder", - "bolus", - "bolvormig", - "bomaanval", - "bombarde", - "bomma", - "bomtapijt", - "bookmaker", - "boos", - "borg", - "bosbes", - "boshuizen", - "bosloop", - "botanicus", - "bougie", - "bovag", - "boxspring", - "braad", - "brasem", - "brevet", - "brigade", - "brinckman", - "bruid", - "budget", - "buffel", - "buks", - "bulgaar", - "buma", - "butaan", - "butler", - "buuf", - "cactus", - "cafeetje", - "camcorder", - "cannabis", - "canyon", - "capoeira", - "capsule", - "carkit", - "casanova", - "catalaan", - "ceintuur", - "celdeling", - "celplasma", - "cement", - "censeren", - "ceramisch", - "cerberus", - "cerebraal", - "cesium", - "cirkel", - "citeer", - "civiel", - "claxon", - "clenbuterol", - "clicheren", - "clijsen", - "coalitie", - "coassistentschap", - "coaxiaal", - "codetaal", - "cofinanciering", - "cognac", - "coltrui", - "comfort", - "commandant", - "condensaat", - "confectie", - "conifeer", - "convector", - "copier", - "corfu", - "correct", - "coup", - "couvert", - "creatie", - "credit", - "crematie", - "cricket", - "croupier", - "cruciaal", - "cruijff", - "cuisine", - "culemborg", - "culinair", - "curve", - "cyrano", - "dactylus", - "dading", - "dagblind", - "dagje", - "daglicht", - "dagprijs", - "dagranden", - "dakdekker", - "dakpark", - "dakterras", - "dalgrond", - "dambord", - "damkat", - "damlengte", - "damman", - "danenberg", - "debbie", - "decibel", - "defect", - "deformeer", - "degelijk", - "degradant", - "dejonghe", - "dekken", - "deppen", - "derek", - "derf", - "derhalve", - "detineren", - "devalueer", - "diaken", - "dicht", - "dictaat", - "dief", - "digitaal", - "dijbreuk", - "dijkmans", - "dimbaar", - "dinsdag", - "diode", - "dirigeer", - "disbalans", - "dobermann", - "doenbaar", - "doerak", - "dogma", - "dokhaven", - "dokwerker", - "doling", - "dolphijn", - "dolven", - "dombo", - "dooraderd", - "dopeling", - "doping", - "draderig", - "drama", - "drenkbak", - "dreumes", - "drol", - "drug", - "duaal", - "dublin", - "duplicaat", - "durven", - "dusdanig", - "dutchbat", - "dutje", - "dutten", - "duur", - "duwwerk", - "dwaal", - "dweil", - "dwing", - "dyslexie", - "ecostroom", - "ecotaks", - "educatie", - "eeckhout", - "eede", - "eemland", - "eencellig", - "eeneiig", - "eenruiter", - "eenwinter", - "eerenberg", - "eerrover", - "eersel", - "eetmaal", - "efteling", - "egaal", - "egtberts", - "eickhoff", - "eidooier", - "eiland", - "eind", - "eisden", - "ekster", - "elburg", - "elevatie", - "elfkoppig", - "elfrink", - "elftal", - "elimineer", - "elleboog", - "elma", - "elodie", - "elsa", - "embleem", - "embolie", - "emoe", - "emonds", - "emplooi", - "enduro", - "enfin", - "engageer", - "entourage", - "entstof", - "epileer", - "episch", - "eppo", - "erasmus", - "erboven", - "erebaan", - "erelijst", - "ereronden", - "ereteken", - "erfhuis", - "erfwet", - "erger", - "erica", - "ermitage", - "erna", - "ernie", - "erts", - "ertussen", - "eruitzien", - "ervaar", - "erven", - "erwt", - "esbeek", - "escort", - "esdoorn", - "essing", - "etage", - "eter", - "ethanol", - "ethicus", - "etholoog", - "eufonisch", - "eurocent", - "evacuatie", - "exact", - "examen", - "executant", - "exen", - "exit", - "exogeen", - "exotherm", - "expeditie", - "expletief", - "expres", - "extase", - "extinctie", - "faal", - "faam", - "fabel", - "facultair", - "fakir", - "fakkel", - "faliekant", - "fallisch", - "famke", - "fanclub", - "fase", - "fatsoen", - "fauna", - "federaal", - "feedback", - "feest", - "feilbaar", - "feitelijk", - "felblauw", - "figurante", - "fiod", - "fitheid", - "fixeer", - "flap", - "fleece", - "fleur", - "flexibel", - "flits", - "flos", - "flow", - "fluweel", - "foezelen", - "fokkelman", - "fokpaard", - "fokvee", - "folder", - "follikel", - "folmer", - "folteraar", - "fooi", - "foolen", - "forfait", - "forint", - "formule", - "fornuis", - "fosfaat", - "foxtrot", - "foyer", - "fragiel", - "frater", - "freak", - "freddie", - "fregat", - "freon", - "frijnen", - "fructose", - "frunniken", - "fuiven", - "funshop", - "furieus", - "fysica", - "gadget", - "galder", - "galei", - "galg", - "galvlieg", - "galzuur", - "ganesh", - "gaswet", - "gaza", - "gazelle", - "geaaid", - "gebiecht", - "gebufferd", - "gedijd", - "geef", - "geflanst", - "gefreesd", - "gegaan", - "gegijzeld", - "gegniffel", - "gegraaid", - "gehikt", - "gehobbeld", - "gehucht", - "geiser", - "geiten", - "gekaakt", - "gekheid", - "gekijf", - "gekmakend", - "gekocht", - "gekskap", - "gekte", - "gelubberd", - "gemiddeld", - "geordend", - "gepoederd", - "gepuft", - "gerda", - "gerijpt", - "geseald", - "geshockt", - "gesierd", - "geslaagd", - "gesnaaid", - "getracht", - "getwijfel", - "geuit", - "gevecht", - "gevlagd", - "gewicht", - "gezaagd", - "gezocht", - "ghanees", - "giebelen", - "giechel", - "giepmans", - "gips", - "giraal", - "gistachtig", - "gitaar", - "glaasje", - "gletsjer", - "gleuf", - "glibberen", - "glijbaan", - "gloren", - "gluipen", - "gluren", - "gluur", - "gnoe", - "goddelijk", - "godgans", - "godschalk", - "godzalig", - "goeierd", - "gogme", - "goklustig", - "gokwereld", - "gonggrijp", - "gonje", - "goor", - "grabbel", - "graf", - "graveer", - "grif", - "grolleman", - "grom", - "groosman", - "grubben", - "gruijs", - "grut", - "guacamole", - "guido", - "guppy", - "haazen", - "hachelijk", - "haex", - "haiku", - "hakhout", - "hakken", - "hanegem", - "hans", - "hanteer", - "harrie", - "hazebroek", - "hedonist", - "heil", - "heineken", - "hekhuis", - "hekman", - "helbig", - "helga", - "helwegen", - "hengelaar", - "herkansen", - "hermafrodiet", - "hertaald", - "hiaat", - "hikspoors", - "hitachi", - "hitparade", - "hobo", - "hoeve", - "holocaust", - "hond", - "honnepon", - "hoogacht", - "hotelbed", - "hufter", - "hugo", - "huilbier", - "hulk", - "humus", - "huwbaar", - "huwelijk", - "hype", - "iconisch", - "idema", - "ideogram", - "idolaat", - "ietje", - "ijker", - "ijkheid", - "ijklijn", - "ijkmaat", - "ijkwezen", - "ijmuiden", - "ijsbox", - "ijsdag", - "ijselijk", - "ijskoud", - "ilse", - "immuun", - "impliceer", - "impuls", - "inbijten", - "inbuigen", - "indijken", - "induceer", - "indy", - "infecteer", - "inhaak", - "inkijk", - "inluiden", - "inmijnen", - "inoefenen", - "inpolder", - "inrijden", - "inslaan", - "invitatie", - "inwaaien", - "ionisch", - "isaac", - "isolatie", - "isotherm", - "isra", - "italiaan", - "ivoor", - "jacobs", - "jakob", - "jammen", - "jampot", - "jarig", - "jehova", - "jenever", - "jezus", - "joana", - "jobdienst", - "josua", - "joule", - "juich", - "jurk", - "juut", - "kaas", - "kabelaar", - "kabinet", - "kagenaar", - "kajuit", - "kalebas", - "kalm", - "kanjer", - "kapucijn", - "karregat", - "kart", - "katvanger", - "katwijk", - "kegelaar", - "keiachtig", - "keizer", - "kenletter", - "kerdijk", - "keus", - "kevlar", - "kezen", - "kickback", - "kieviet", - "kijken", - "kikvors", - "kilheid", - "kilobit", - "kilsdonk", - "kipschnitzel", - "kissebis", - "klad", - "klagelijk", - "klak", - "klapbaar", - "klaver", - "klene", - "klets", - "klijnhout", - "klit", - "klok", - "klonen", - "klotefilm", - "kluif", - "klumper", - "klus", - "knabbel", - "knagen", - "knaven", - "kneedbaar", - "knmi", - "knul", - "knus", - "kokhals", - "komiek", - "komkommer", - "kompaan", - "komrij", - "komvormig", - "koning", - "kopbal", - "kopklep", - "kopnagel", - "koppejan", - "koptekst", - "kopwand", - "koraal", - "kosmisch", - "kostbaar", - "kram", - "kraneveld", - "kras", - "kreling", - "krengen", - "kribbe", - "krik", - "kruid", - "krulbol", - "kuijper", - "kuipbank", - "kuit", - "kuiven", - "kutsmoes", - "kuub", - "kwak", - "kwatong", - "kwetsbaar", - "kwezelaar", - "kwijnen", - "kwik", - "kwinkslag", - "kwitantie", - "lading", - "lakbeits", - "lakken", - "laklaag", - "lakmoes", - "lakwijk", - "lamheid", - "lamp", - "lamsbout", - "lapmiddel", - "larve", - "laser", - "latijn", - "latuw", - "lawaai", - "laxeerpil", - "lebberen", - "ledeboer", - "leefbaar", - "leeman", - "lefdoekje", - "lefhebber", - "legboor", - "legsel", - "leguaan", - "leiplaat", - "lekdicht", - "lekrijden", - "leksteen", - "lenen", - "leraar", - "lesbienne", - "leugenaar", - "leut", - "lexicaal", - "lezing", - "lieten", - "liggeld", - "lijdzaam", - "lijk", - "lijmstang", - "lijnschip", - "likdoorn", - "likken", - "liksteen", - "limburg", - "link", - "linoleum", - "lipbloem", - "lipman", - "lispelen", - "lissabon", - "litanie", - "liturgie", - "lochem", - "loempia", - "loesje", - "logheid", - "lonen", - "lonneke", - "loom", - "loos", - "losbaar", - "loslaten", - "losplaats", - "loting", - "lotnummer", - "lots", - "louie", - "lourdes", - "louter", - "lowbudget", - "luijten", - "luikenaar", - "luilak", - "luipaard", - "luizenbos", - "lulkoek", - "lumen", - "lunzen", - "lurven", - "lutjeboer", - "luttel", - "lutz", - "luuk", - "luwte", - "luyendijk", - "lyceum", - "lynx", - "maakbaar", - "magdalena", - "malheid", - "manchet", - "manfred", - "manhaftig", - "mank", - "mantel", - "marion", - "marxist", - "masmeijer", - "massaal", - "matsen", - "matverf", - "matze", - "maude", - "mayonaise", - "mechanica", - "meifeest", - "melodie", - "meppelink", - "midvoor", - "midweeks", - "midzomer", - "miezel", - "mijnraad", - "minus", - "mirck", - "mirte", - "mispakken", - "misraden", - "miswassen", - "mitella", - "moker", - "molecule", - "mombakkes", - "moonen", - "mopperaar", - "moraal", - "morgana", - "mormel", - "mosselaar", - "motregen", - "mouw", - "mufheid", - "mutueel", - "muzelman", - "naaidoos", - "naald", - "nadeel", - "nadruk", - "nagy", - "nahon", - "naima", - "nairobi", - "napalm", - "napels", - "napijn", - "napoleon", - "narigheid", - "narratief", - "naseizoen", - "nasibal", - "navigatie", - "nawijn", - "negatief", - "nekletsel", - "nekwervel", - "neolatijn", - "neonataal", - "neptunus", - "nerd", - "nest", - "neuzelaar", - "nihiliste", - "nijenhuis", - "nijging", - "nijhoff", - "nijl", - "nijptang", - "nippel", - "nokkenas", - "noordam", - "noren", - "normaal", - "nottelman", - "notulant", - "nout", - "nuance", - "nuchter", - "nudorp", - "nulde", - "nullijn", - "nulmeting", - "nunspeet", - "nylon", - "obelisk", - "object", - "oblie", - "obsceen", - "occlusie", - "oceaan", - "ochtend", - "ockhuizen", - "oerdom", - "oergezond", - "oerlaag", - "oester", - "okhuijsen", - "olifant", - "olijfboer", - "omaans", - "ombudsman", - "omdat", - "omdijken", - "omdoen", - "omgebouwd", - "omkeer", - "omkomen", - "ommegaand", - "ommuren", - "omroep", - "omruil", - "omslaan", - "omsmeden", - "omvaar", - "onaardig", - "onedel", - "onenig", - "onheilig", - "onrecht", - "onroerend", - "ontcijfer", - "onthaal", - "ontvallen", - "ontzadeld", - "onzacht", - "onzin", - "onzuiver", - "oogappel", - "ooibos", - "ooievaar", - "ooit", - "oorarts", - "oorhanger", - "oorijzer", - "oorklep", - "oorschelp", - "oorworm", - "oorzaak", - "opdagen", - "opdien", - "opdweilen", - "opel", - "opgebaard", - "opinie", - "opjutten", - "opkijken", - "opklaar", - "opkuisen", - "opkwam", - "opnaaien", - "opossum", - "opsieren", - "opsmeer", - "optreden", - "opvijzel", - "opvlammen", - "opwind", - "oraal", - "orchidee", - "orkest", - "ossuarium", - "ostendorf", - "oublie", - "oudachtig", - "oudbakken", - "oudnoors", - "oudshoorn", - "oudtante", - "oven", - "over", - "oxidant", - "pablo", - "pacht", - "paktafel", - "pakzadel", - "paljas", - "panharing", - "papfles", - "paprika", - "parochie", - "paus", - "pauze", - "paviljoen", - "peek", - "pegel", - "peigeren", - "pekela", - "pendant", - "penibel", - "pepmiddel", - "peptalk", - "periferie", - "perron", - "pessarium", - "peter", - "petfles", - "petgat", - "peuk", - "pfeifer", - "picknick", - "pief", - "pieneman", - "pijlkruid", - "pijnacker", - "pijpelink", - "pikdonker", - "pikeer", - "pilaar", - "pionier", - "pipet", - "piscine", - "pissebed", - "pitchen", - "pixel", - "plamuren", - "plan", - "plausibel", - "plegen", - "plempen", - "pleonasme", - "plezant", - "podoloog", - "pofmouw", - "pokdalig", - "ponywagen", - "popachtig", - "popidool", - "porren", - "positie", - "potten", - "pralen", - "prezen", - "prijzen", - "privaat", - "proef", - "prooi", - "prozawerk", - "pruik", - "prul", - "publiceer", - "puck", - "puilen", - "pukkelig", - "pulveren", - "pupil", - "puppy", - "purmerend", - "pustjens", - "putemmer", - "puzzelaar", - "queenie", - "quiche", - "raam", - "raar", - "raat", - "raes", - "ralf", - "rally", - "ramona", - "ramselaar", - "ranonkel", - "rapen", - "rapunzel", - "rarekiek", - "rarigheid", - "rattenhol", - "ravage", - "reactie", - "recreant", - "redacteur", - "redster", - "reewild", - "regie", - "reijnders", - "rein", - "replica", - "revanche", - "rigide", - "rijbaan", - "rijdansen", - "rijgen", - "rijkdom", - "rijles", - "rijnwijn", - "rijpma", - "rijstafel", - "rijtaak", - "rijzwepen", - "rioleer", - "ripdeal", - "riphagen", - "riskant", - "rits", - "rivaal", - "robbedoes", - "robot", - "rockact", - "rodijk", - "rogier", - "rohypnol", - "rollaag", - "rolpaal", - "roltafel", - "roof", - "roon", - "roppen", - "rosbief", - "rosharig", - "rosielle", - "rotan", - "rotleven", - "rotten", - "rotvaart", - "royaal", - "royeer", - "rubato", - "ruby", - "ruche", - "rudge", - "ruggetje", - "rugnummer", - "rugpijn", - "rugtitel", - "rugzak", - "ruilbaar", - "ruis", - "ruit", - "rukwind", - "rulijs", - "rumoeren", - "rumsdorp", - "rumtaart", - "runnen", - "russchen", - "ruwkruid", - "saboteer", - "saksisch", - "salade", - "salpeter", - "sambabal", - "samsam", - "satelliet", - "satineer", - "saus", - "scampi", - "scarabee", - "scenario", - "schobben", - "schubben", - "scout", - "secessie", - "secondair", - "seculair", - "sediment", - "seeland", - "settelen", - "setwinst", - "sheriff", - "shiatsu", - "siciliaan", - "sidderaal", - "sigma", - "sijben", - "silvana", - "simkaart", - "sinds", - "situatie", - "sjaak", - "sjardijn", - "sjezen", - "sjor", - "skinhead", - "skylab", - "slamixen", - "sleijpen", - "slijkerig", - "slordig", - "slowaak", - "sluieren", - "smadelijk", - "smiecht", - "smoel", - "smos", - "smukken", - "snackcar", - "snavel", - "sneaker", - "sneu", - "snijdbaar", - "snit", - "snorder", - "soapbox", - "soetekouw", - "soigneren", - "sojaboon", - "solo", - "solvabel", - "somber", - "sommatie", - "soort", - "soppen", - "sopraan", - "soundbar", - "spanen", - "spawater", - "spijgat", - "spinaal", - "spionage", - "spiraal", - "spleet", - "splijt", - "spoed", - "sporen", - "spul", - "spuug", - "spuw", - "stalen", - "standaard", - "star", - "stefan", - "stencil", - "stijf", - "stil", - "stip", - "stopdas", - "stoten", - "stoven", - "straat", - "strobbe", - "strubbel", - "stucadoor", - "stuif", - "stukadoor", - "subhoofd", - "subregent", - "sudoku", - "sukade", - "sulfaat", - "surinaams", - "suus", - "syfilis", - "symboliek", - "sympathie", - "synagoge", - "synchroon", - "synergie", - "systeem", - "taanderij", - "tabak", - "tachtig", - "tackelen", - "taiwanees", - "talman", - "tamheid", - "tangaslip", - "taps", - "tarkan", - "tarwe", - "tasman", - "tatjana", - "taxameter", - "teil", - "teisman", - "telbaar", - "telco", - "telganger", - "telstar", - "tenant", - "tepel", - "terzet", - "testament", - "ticket", - "tiesinga", - "tijdelijk", - "tika", - "tiksel", - "tilleman", - "timbaal", - "tinsteen", - "tiplijn", - "tippelaar", - "tjirpen", - "toezeggen", - "tolbaas", - "tolgeld", - "tolhek", - "tolo", - "tolpoort", - "toltarief", - "tolvrij", - "tomaat", - "tondeuse", - "toog", - "tooi", - "toonbaar", - "toos", - "topclub", - "toppen", - "toptalent", - "topvrouw", - "toque", - "torment", - "tornado", - "tosti", - "totdat", - "toucheer", - "toulouse", - "tournedos", - "tout", - "trabant", - "tragedie", - "trailer", - "traject", - "traktaat", - "trauma", - "tray", - "trechter", - "tred", - "tref", - "treur", - "troebel", - "tros", - "trucage", - "truffel", - "tsaar", - "tucht", - "tuenter", - "tuitelig", - "tukje", - "tuktuk", - "tulp", - "tuma", - "tureluurs", - "twijfel", - "twitteren", - "tyfoon", - "typograaf", - "ugandees", - "uiachtig", - "uier", - "uisnipper", - "ultiem", - "unitair", - "uranium", - "urbaan", - "urendag", - "ursula", - "uurcirkel", - "uurglas", - "uzelf", - "vaat", - "vakantie", - "vakleraar", - "valbijl", - "valpartij", - "valreep", - "valuatie", - "vanmiddag", - "vanonder", - "varaan", - "varken", - "vaten", - "veenbes", - "veeteler", - "velgrem", - "vellekoop", - "velvet", - "veneberg", - "venlo", - "vent", - "venusberg", - "venw", - "veredeld", - "verf", - "verhaaf", - "vermaak", - "vernaaid", - "verraad", - "vers", - "veruit", - "verzaagd", - "vetachtig", - "vetlok", - "vetmesten", - "veto", - "vetrek", - "vetstaart", - "vetten", - "veurink", - "viaduct", - "vibrafoon", - "vicariaat", - "vieux", - "vieveen", - "vijfvoud", - "villa", - "vilt", - "vimmetje", - "vindbaar", - "vips", - "virtueel", - "visdieven", - "visee", - "visie", - "vlaag", - "vleugel", - "vmbo", - "vocht", - "voesenek", - "voicemail", - "voip", - "volg", - "vork", - "vorselaar", - "voyeur", - "vracht", - "vrekkig", - "vreten", - "vrije", - "vrozen", - "vrucht", - "vucht", - "vugt", - "vulkaan", - "vulmiddel", - "vulva", - "vuren", - "waas", - "wacht", - "wadvogel", - "wafel", - "waffel", - "walhalla", - "walnoot", - "walraven", - "wals", - "walvis", - "wandaad", - "wanen", - "wanmolen", - "want", - "warklomp", - "warm", - "wasachtig", - "wasteil", - "watt", - "webhandel", - "weblog", - "webpagina", - "webzine", - "wedereis", - "wedstrijd", - "weeda", - "weert", - "wegmaaien", - "wegscheer", - "wekelijks", - "wekken", - "wekroep", - "wektoon", - "weldaad", - "welwater", - "wendbaar", - "wenkbrauw", - "wens", - "wentelaar", - "wervel", - "wesseling", - "wetboek", - "wetmatig", - "whirlpool", - "wijbrands", - "wijdbeens", - "wijk", - "wijnbes", - "wijting", - "wild", - "wimpelen", - "wingebied", - "winplaats", - "winter", - "winzucht", - "wipstaart", - "wisgerhof", - "withaar", - "witmaker", - "wokkel", - "wolf", - "wonenden", - "woning", - "worden", - "worp", - "wortel", - "wrat", - "wrijf", - "wringen", - "yoghurt", - "ypsilon", - "zaaijer", - "zaak", - "zacharias", - "zakelijk", - "zakkam", - "zakwater", - "zalf", - "zalig", - "zaniken", - "zebracode", - "zeeblauw", - "zeef", - "zeegaand", - "zeeuw", - "zege", - "zegje", - "zeil", - "zesbaans", - "zesenhalf", - "zeskantig", - "zesmaal", - "zetbaas", - "zetpil", - "zeulen", - "ziezo", - "zigzag", - "zijaltaar", - "zijbeuk", - "zijlijn", - "zijmuur", - "zijn", - "zijwaarts", - "zijzelf", - "zilt", - "zimmerman", - "zinledig", - "zinnelijk", - "zionist", - "zitdag", - "zitruimte", - "zitzak", - "zoal", - "zodoende", - "zoekbots", - "zoem", - "zoiets", - "zojuist", - "zondaar", - "zotskap", - "zottebol", - "zucht", - "zuivel", - "zulk", - "zult", - "zuster", - "zuur", - "zweedijk", - "zwendel", - "zwepen", - "zwiep", - "zwijmel", - "zworen" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file dutch.h + * + * \brief New Dutch word list and map. + */ + +#ifndef DUTCH_H +#define DUTCH_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Dutch: public Base + { + public: + Dutch(): Base("Nederlands", "Dutch", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "aalglad", + "aalscholver", + "aambeeld", + "aangeef", + "aanlandig", + "aanvaard", + "aanwakker", + "aapmens", + "aarten", + "abdicatie", + "abnormaal", + "abrikoos", + "accu", + "acuut", + "adjudant", + "admiraal", + "advies", + "afbidding", + "afdracht", + "affaire", + "affiche", + "afgang", + "afkick", + "afknap", + "aflees", + "afmijner", + "afname", + "afpreekt", + "afrader", + "afspeel", + "aftocht", + "aftrek", + "afzijdig", + "ahornboom", + "aktetas", + "akzo", + "alchemist", + "alcohol", + "aldaar", + "alexander", + "alfabet", + "alfredo", + "alice", + "alikruik", + "allrisk", + "altsax", + "alufolie", + "alziend", + "amai", + "ambacht", + "ambieer", + "amina", + "amnestie", + "amok", + "ampul", + "amuzikaal", + "angela", + "aniek", + "antje", + "antwerpen", + "anya", + "aorta", + "apache", + "apekool", + "appelaar", + "arganolie", + "argeloos", + "armoede", + "arrenslee", + "artritis", + "arubaan", + "asbak", + "ascii", + "asgrauw", + "asjes", + "asml", + "aspunt", + "asurn", + "asveld", + "aterling", + "atomair", + "atrium", + "atsma", + "atypisch", + "auping", + "aura", + "avifauna", + "axiaal", + "azoriaan", + "azteek", + "azuur", + "bachelor", + "badderen", + "badhotel", + "badmantel", + "badsteden", + "balie", + "ballans", + "balvers", + "bamibal", + "banneling", + "barracuda", + "basaal", + "batelaan", + "batje", + "beambte", + "bedlamp", + "bedwelmd", + "befaamd", + "begierd", + "begraaf", + "behield", + "beijaard", + "bejaagd", + "bekaaid", + "beks", + "bektas", + "belaad", + "belboei", + "belderbos", + "beloerd", + "beluchten", + "bemiddeld", + "benadeeld", + "benijd", + "berechten", + "beroemd", + "besef", + "besseling", + "best", + "betichten", + "bevind", + "bevochten", + "bevraagd", + "bewust", + "bidplaats", + "biefstuk", + "biemans", + "biezen", + "bijbaan", + "bijeenkom", + "bijfiguur", + "bijkaart", + "bijlage", + "bijpaard", + "bijtgaar", + "bijweg", + "bimmel", + "binck", + "bint", + "biobak", + "biotisch", + "biseks", + "bistro", + "bitter", + "bitumen", + "bizar", + "blad", + "bleken", + "blender", + "bleu", + "blief", + "blijven", + "blozen", + "bock", + "boef", + "boei", + "boks", + "bolder", + "bolus", + "bolvormig", + "bomaanval", + "bombarde", + "bomma", + "bomtapijt", + "bookmaker", + "boos", + "borg", + "bosbes", + "boshuizen", + "bosloop", + "botanicus", + "bougie", + "bovag", + "boxspring", + "braad", + "brasem", + "brevet", + "brigade", + "brinckman", + "bruid", + "budget", + "buffel", + "buks", + "bulgaar", + "buma", + "butaan", + "butler", + "buuf", + "cactus", + "cafeetje", + "camcorder", + "cannabis", + "canyon", + "capoeira", + "capsule", + "carkit", + "casanova", + "catalaan", + "ceintuur", + "celdeling", + "celplasma", + "cement", + "censeren", + "ceramisch", + "cerberus", + "cerebraal", + "cesium", + "cirkel", + "citeer", + "civiel", + "claxon", + "clenbuterol", + "clicheren", + "clijsen", + "coalitie", + "coassistentschap", + "coaxiaal", + "codetaal", + "cofinanciering", + "cognac", + "coltrui", + "comfort", + "commandant", + "condensaat", + "confectie", + "conifeer", + "convector", + "copier", + "corfu", + "correct", + "coup", + "couvert", + "creatie", + "credit", + "crematie", + "cricket", + "croupier", + "cruciaal", + "cruijff", + "cuisine", + "culemborg", + "culinair", + "curve", + "cyrano", + "dactylus", + "dading", + "dagblind", + "dagje", + "daglicht", + "dagprijs", + "dagranden", + "dakdekker", + "dakpark", + "dakterras", + "dalgrond", + "dambord", + "damkat", + "damlengte", + "damman", + "danenberg", + "debbie", + "decibel", + "defect", + "deformeer", + "degelijk", + "degradant", + "dejonghe", + "dekken", + "deppen", + "derek", + "derf", + "derhalve", + "detineren", + "devalueer", + "diaken", + "dicht", + "dictaat", + "dief", + "digitaal", + "dijbreuk", + "dijkmans", + "dimbaar", + "dinsdag", + "diode", + "dirigeer", + "disbalans", + "dobermann", + "doenbaar", + "doerak", + "dogma", + "dokhaven", + "dokwerker", + "doling", + "dolphijn", + "dolven", + "dombo", + "dooraderd", + "dopeling", + "doping", + "draderig", + "drama", + "drenkbak", + "dreumes", + "drol", + "drug", + "duaal", + "dublin", + "duplicaat", + "durven", + "dusdanig", + "dutchbat", + "dutje", + "dutten", + "duur", + "duwwerk", + "dwaal", + "dweil", + "dwing", + "dyslexie", + "ecostroom", + "ecotaks", + "educatie", + "eeckhout", + "eede", + "eemland", + "eencellig", + "eeneiig", + "eenruiter", + "eenwinter", + "eerenberg", + "eerrover", + "eersel", + "eetmaal", + "efteling", + "egaal", + "egtberts", + "eickhoff", + "eidooier", + "eiland", + "eind", + "eisden", + "ekster", + "elburg", + "elevatie", + "elfkoppig", + "elfrink", + "elftal", + "elimineer", + "elleboog", + "elma", + "elodie", + "elsa", + "embleem", + "embolie", + "emoe", + "emonds", + "emplooi", + "enduro", + "enfin", + "engageer", + "entourage", + "entstof", + "epileer", + "episch", + "eppo", + "erasmus", + "erboven", + "erebaan", + "erelijst", + "ereronden", + "ereteken", + "erfhuis", + "erfwet", + "erger", + "erica", + "ermitage", + "erna", + "ernie", + "erts", + "ertussen", + "eruitzien", + "ervaar", + "erven", + "erwt", + "esbeek", + "escort", + "esdoorn", + "essing", + "etage", + "eter", + "ethanol", + "ethicus", + "etholoog", + "eufonisch", + "eurocent", + "evacuatie", + "exact", + "examen", + "executant", + "exen", + "exit", + "exogeen", + "exotherm", + "expeditie", + "expletief", + "expres", + "extase", + "extinctie", + "faal", + "faam", + "fabel", + "facultair", + "fakir", + "fakkel", + "faliekant", + "fallisch", + "famke", + "fanclub", + "fase", + "fatsoen", + "fauna", + "federaal", + "feedback", + "feest", + "feilbaar", + "feitelijk", + "felblauw", + "figurante", + "fiod", + "fitheid", + "fixeer", + "flap", + "fleece", + "fleur", + "flexibel", + "flits", + "flos", + "flow", + "fluweel", + "foezelen", + "fokkelman", + "fokpaard", + "fokvee", + "folder", + "follikel", + "folmer", + "folteraar", + "fooi", + "foolen", + "forfait", + "forint", + "formule", + "fornuis", + "fosfaat", + "foxtrot", + "foyer", + "fragiel", + "frater", + "freak", + "freddie", + "fregat", + "freon", + "frijnen", + "fructose", + "frunniken", + "fuiven", + "funshop", + "furieus", + "fysica", + "gadget", + "galder", + "galei", + "galg", + "galvlieg", + "galzuur", + "ganesh", + "gaswet", + "gaza", + "gazelle", + "geaaid", + "gebiecht", + "gebufferd", + "gedijd", + "geef", + "geflanst", + "gefreesd", + "gegaan", + "gegijzeld", + "gegniffel", + "gegraaid", + "gehikt", + "gehobbeld", + "gehucht", + "geiser", + "geiten", + "gekaakt", + "gekheid", + "gekijf", + "gekmakend", + "gekocht", + "gekskap", + "gekte", + "gelubberd", + "gemiddeld", + "geordend", + "gepoederd", + "gepuft", + "gerda", + "gerijpt", + "geseald", + "geshockt", + "gesierd", + "geslaagd", + "gesnaaid", + "getracht", + "getwijfel", + "geuit", + "gevecht", + "gevlagd", + "gewicht", + "gezaagd", + "gezocht", + "ghanees", + "giebelen", + "giechel", + "giepmans", + "gips", + "giraal", + "gistachtig", + "gitaar", + "glaasje", + "gletsjer", + "gleuf", + "glibberen", + "glijbaan", + "gloren", + "gluipen", + "gluren", + "gluur", + "gnoe", + "goddelijk", + "godgans", + "godschalk", + "godzalig", + "goeierd", + "gogme", + "goklustig", + "gokwereld", + "gonggrijp", + "gonje", + "goor", + "grabbel", + "graf", + "graveer", + "grif", + "grolleman", + "grom", + "groosman", + "grubben", + "gruijs", + "grut", + "guacamole", + "guido", + "guppy", + "haazen", + "hachelijk", + "haex", + "haiku", + "hakhout", + "hakken", + "hanegem", + "hans", + "hanteer", + "harrie", + "hazebroek", + "hedonist", + "heil", + "heineken", + "hekhuis", + "hekman", + "helbig", + "helga", + "helwegen", + "hengelaar", + "herkansen", + "hermafrodiet", + "hertaald", + "hiaat", + "hikspoors", + "hitachi", + "hitparade", + "hobo", + "hoeve", + "holocaust", + "hond", + "honnepon", + "hoogacht", + "hotelbed", + "hufter", + "hugo", + "huilbier", + "hulk", + "humus", + "huwbaar", + "huwelijk", + "hype", + "iconisch", + "idema", + "ideogram", + "idolaat", + "ietje", + "ijker", + "ijkheid", + "ijklijn", + "ijkmaat", + "ijkwezen", + "ijmuiden", + "ijsbox", + "ijsdag", + "ijselijk", + "ijskoud", + "ilse", + "immuun", + "impliceer", + "impuls", + "inbijten", + "inbuigen", + "indijken", + "induceer", + "indy", + "infecteer", + "inhaak", + "inkijk", + "inluiden", + "inmijnen", + "inoefenen", + "inpolder", + "inrijden", + "inslaan", + "invitatie", + "inwaaien", + "ionisch", + "isaac", + "isolatie", + "isotherm", + "isra", + "italiaan", + "ivoor", + "jacobs", + "jakob", + "jammen", + "jampot", + "jarig", + "jehova", + "jenever", + "jezus", + "joana", + "jobdienst", + "josua", + "joule", + "juich", + "jurk", + "juut", + "kaas", + "kabelaar", + "kabinet", + "kagenaar", + "kajuit", + "kalebas", + "kalm", + "kanjer", + "kapucijn", + "karregat", + "kart", + "katvanger", + "katwijk", + "kegelaar", + "keiachtig", + "keizer", + "kenletter", + "kerdijk", + "keus", + "kevlar", + "kezen", + "kickback", + "kieviet", + "kijken", + "kikvors", + "kilheid", + "kilobit", + "kilsdonk", + "kipschnitzel", + "kissebis", + "klad", + "klagelijk", + "klak", + "klapbaar", + "klaver", + "klene", + "klets", + "klijnhout", + "klit", + "klok", + "klonen", + "klotefilm", + "kluif", + "klumper", + "klus", + "knabbel", + "knagen", + "knaven", + "kneedbaar", + "knmi", + "knul", + "knus", + "kokhals", + "komiek", + "komkommer", + "kompaan", + "komrij", + "komvormig", + "koning", + "kopbal", + "kopklep", + "kopnagel", + "koppejan", + "koptekst", + "kopwand", + "koraal", + "kosmisch", + "kostbaar", + "kram", + "kraneveld", + "kras", + "kreling", + "krengen", + "kribbe", + "krik", + "kruid", + "krulbol", + "kuijper", + "kuipbank", + "kuit", + "kuiven", + "kutsmoes", + "kuub", + "kwak", + "kwatong", + "kwetsbaar", + "kwezelaar", + "kwijnen", + "kwik", + "kwinkslag", + "kwitantie", + "lading", + "lakbeits", + "lakken", + "laklaag", + "lakmoes", + "lakwijk", + "lamheid", + "lamp", + "lamsbout", + "lapmiddel", + "larve", + "laser", + "latijn", + "latuw", + "lawaai", + "laxeerpil", + "lebberen", + "ledeboer", + "leefbaar", + "leeman", + "lefdoekje", + "lefhebber", + "legboor", + "legsel", + "leguaan", + "leiplaat", + "lekdicht", + "lekrijden", + "leksteen", + "lenen", + "leraar", + "lesbienne", + "leugenaar", + "leut", + "lexicaal", + "lezing", + "lieten", + "liggeld", + "lijdzaam", + "lijk", + "lijmstang", + "lijnschip", + "likdoorn", + "likken", + "liksteen", + "limburg", + "link", + "linoleum", + "lipbloem", + "lipman", + "lispelen", + "lissabon", + "litanie", + "liturgie", + "lochem", + "loempia", + "loesje", + "logheid", + "lonen", + "lonneke", + "loom", + "loos", + "losbaar", + "loslaten", + "losplaats", + "loting", + "lotnummer", + "lots", + "louie", + "lourdes", + "louter", + "lowbudget", + "luijten", + "luikenaar", + "luilak", + "luipaard", + "luizenbos", + "lulkoek", + "lumen", + "lunzen", + "lurven", + "lutjeboer", + "luttel", + "lutz", + "luuk", + "luwte", + "luyendijk", + "lyceum", + "lynx", + "maakbaar", + "magdalena", + "malheid", + "manchet", + "manfred", + "manhaftig", + "mank", + "mantel", + "marion", + "marxist", + "masmeijer", + "massaal", + "matsen", + "matverf", + "matze", + "maude", + "mayonaise", + "mechanica", + "meifeest", + "melodie", + "meppelink", + "midvoor", + "midweeks", + "midzomer", + "miezel", + "mijnraad", + "minus", + "mirck", + "mirte", + "mispakken", + "misraden", + "miswassen", + "mitella", + "moker", + "molecule", + "mombakkes", + "moonen", + "mopperaar", + "moraal", + "morgana", + "mormel", + "mosselaar", + "motregen", + "mouw", + "mufheid", + "mutueel", + "muzelman", + "naaidoos", + "naald", + "nadeel", + "nadruk", + "nagy", + "nahon", + "naima", + "nairobi", + "napalm", + "napels", + "napijn", + "napoleon", + "narigheid", + "narratief", + "naseizoen", + "nasibal", + "navigatie", + "nawijn", + "negatief", + "nekletsel", + "nekwervel", + "neolatijn", + "neonataal", + "neptunus", + "nerd", + "nest", + "neuzelaar", + "nihiliste", + "nijenhuis", + "nijging", + "nijhoff", + "nijl", + "nijptang", + "nippel", + "nokkenas", + "noordam", + "noren", + "normaal", + "nottelman", + "notulant", + "nout", + "nuance", + "nuchter", + "nudorp", + "nulde", + "nullijn", + "nulmeting", + "nunspeet", + "nylon", + "obelisk", + "object", + "oblie", + "obsceen", + "occlusie", + "oceaan", + "ochtend", + "ockhuizen", + "oerdom", + "oergezond", + "oerlaag", + "oester", + "okhuijsen", + "olifant", + "olijfboer", + "omaans", + "ombudsman", + "omdat", + "omdijken", + "omdoen", + "omgebouwd", + "omkeer", + "omkomen", + "ommegaand", + "ommuren", + "omroep", + "omruil", + "omslaan", + "omsmeden", + "omvaar", + "onaardig", + "onedel", + "onenig", + "onheilig", + "onrecht", + "onroerend", + "ontcijfer", + "onthaal", + "ontvallen", + "ontzadeld", + "onzacht", + "onzin", + "onzuiver", + "oogappel", + "ooibos", + "ooievaar", + "ooit", + "oorarts", + "oorhanger", + "oorijzer", + "oorklep", + "oorschelp", + "oorworm", + "oorzaak", + "opdagen", + "opdien", + "opdweilen", + "opel", + "opgebaard", + "opinie", + "opjutten", + "opkijken", + "opklaar", + "opkuisen", + "opkwam", + "opnaaien", + "opossum", + "opsieren", + "opsmeer", + "optreden", + "opvijzel", + "opvlammen", + "opwind", + "oraal", + "orchidee", + "orkest", + "ossuarium", + "ostendorf", + "oublie", + "oudachtig", + "oudbakken", + "oudnoors", + "oudshoorn", + "oudtante", + "oven", + "over", + "oxidant", + "pablo", + "pacht", + "paktafel", + "pakzadel", + "paljas", + "panharing", + "papfles", + "paprika", + "parochie", + "paus", + "pauze", + "paviljoen", + "peek", + "pegel", + "peigeren", + "pekela", + "pendant", + "penibel", + "pepmiddel", + "peptalk", + "periferie", + "perron", + "pessarium", + "peter", + "petfles", + "petgat", + "peuk", + "pfeifer", + "picknick", + "pief", + "pieneman", + "pijlkruid", + "pijnacker", + "pijpelink", + "pikdonker", + "pikeer", + "pilaar", + "pionier", + "pipet", + "piscine", + "pissebed", + "pitchen", + "pixel", + "plamuren", + "plan", + "plausibel", + "plegen", + "plempen", + "pleonasme", + "plezant", + "podoloog", + "pofmouw", + "pokdalig", + "ponywagen", + "popachtig", + "popidool", + "porren", + "positie", + "potten", + "pralen", + "prezen", + "prijzen", + "privaat", + "proef", + "prooi", + "prozawerk", + "pruik", + "prul", + "publiceer", + "puck", + "puilen", + "pukkelig", + "pulveren", + "pupil", + "puppy", + "purmerend", + "pustjens", + "putemmer", + "puzzelaar", + "queenie", + "quiche", + "raam", + "raar", + "raat", + "raes", + "ralf", + "rally", + "ramona", + "ramselaar", + "ranonkel", + "rapen", + "rapunzel", + "rarekiek", + "rarigheid", + "rattenhol", + "ravage", + "reactie", + "recreant", + "redacteur", + "redster", + "reewild", + "regie", + "reijnders", + "rein", + "replica", + "revanche", + "rigide", + "rijbaan", + "rijdansen", + "rijgen", + "rijkdom", + "rijles", + "rijnwijn", + "rijpma", + "rijstafel", + "rijtaak", + "rijzwepen", + "rioleer", + "ripdeal", + "riphagen", + "riskant", + "rits", + "rivaal", + "robbedoes", + "robot", + "rockact", + "rodijk", + "rogier", + "rohypnol", + "rollaag", + "rolpaal", + "roltafel", + "roof", + "roon", + "roppen", + "rosbief", + "rosharig", + "rosielle", + "rotan", + "rotleven", + "rotten", + "rotvaart", + "royaal", + "royeer", + "rubato", + "ruby", + "ruche", + "rudge", + "ruggetje", + "rugnummer", + "rugpijn", + "rugtitel", + "rugzak", + "ruilbaar", + "ruis", + "ruit", + "rukwind", + "rulijs", + "rumoeren", + "rumsdorp", + "rumtaart", + "runnen", + "russchen", + "ruwkruid", + "saboteer", + "saksisch", + "salade", + "salpeter", + "sambabal", + "samsam", + "satelliet", + "satineer", + "saus", + "scampi", + "scarabee", + "scenario", + "schobben", + "schubben", + "scout", + "secessie", + "secondair", + "seculair", + "sediment", + "seeland", + "settelen", + "setwinst", + "sheriff", + "shiatsu", + "siciliaan", + "sidderaal", + "sigma", + "sijben", + "silvana", + "simkaart", + "sinds", + "situatie", + "sjaak", + "sjardijn", + "sjezen", + "sjor", + "skinhead", + "skylab", + "slamixen", + "sleijpen", + "slijkerig", + "slordig", + "slowaak", + "sluieren", + "smadelijk", + "smiecht", + "smoel", + "smos", + "smukken", + "snackcar", + "snavel", + "sneaker", + "sneu", + "snijdbaar", + "snit", + "snorder", + "soapbox", + "soetekouw", + "soigneren", + "sojaboon", + "solo", + "solvabel", + "somber", + "sommatie", + "soort", + "soppen", + "sopraan", + "soundbar", + "spanen", + "spawater", + "spijgat", + "spinaal", + "spionage", + "spiraal", + "spleet", + "splijt", + "spoed", + "sporen", + "spul", + "spuug", + "spuw", + "stalen", + "standaard", + "star", + "stefan", + "stencil", + "stijf", + "stil", + "stip", + "stopdas", + "stoten", + "stoven", + "straat", + "strobbe", + "strubbel", + "stucadoor", + "stuif", + "stukadoor", + "subhoofd", + "subregent", + "sudoku", + "sukade", + "sulfaat", + "surinaams", + "suus", + "syfilis", + "symboliek", + "sympathie", + "synagoge", + "synchroon", + "synergie", + "systeem", + "taanderij", + "tabak", + "tachtig", + "tackelen", + "taiwanees", + "talman", + "tamheid", + "tangaslip", + "taps", + "tarkan", + "tarwe", + "tasman", + "tatjana", + "taxameter", + "teil", + "teisman", + "telbaar", + "telco", + "telganger", + "telstar", + "tenant", + "tepel", + "terzet", + "testament", + "ticket", + "tiesinga", + "tijdelijk", + "tika", + "tiksel", + "tilleman", + "timbaal", + "tinsteen", + "tiplijn", + "tippelaar", + "tjirpen", + "toezeggen", + "tolbaas", + "tolgeld", + "tolhek", + "tolo", + "tolpoort", + "toltarief", + "tolvrij", + "tomaat", + "tondeuse", + "toog", + "tooi", + "toonbaar", + "toos", + "topclub", + "toppen", + "toptalent", + "topvrouw", + "toque", + "torment", + "tornado", + "tosti", + "totdat", + "toucheer", + "toulouse", + "tournedos", + "tout", + "trabant", + "tragedie", + "trailer", + "traject", + "traktaat", + "trauma", + "tray", + "trechter", + "tred", + "tref", + "treur", + "troebel", + "tros", + "trucage", + "truffel", + "tsaar", + "tucht", + "tuenter", + "tuitelig", + "tukje", + "tuktuk", + "tulp", + "tuma", + "tureluurs", + "twijfel", + "twitteren", + "tyfoon", + "typograaf", + "ugandees", + "uiachtig", + "uier", + "uisnipper", + "ultiem", + "unitair", + "uranium", + "urbaan", + "urendag", + "ursula", + "uurcirkel", + "uurglas", + "uzelf", + "vaat", + "vakantie", + "vakleraar", + "valbijl", + "valpartij", + "valreep", + "valuatie", + "vanmiddag", + "vanonder", + "varaan", + "varken", + "vaten", + "veenbes", + "veeteler", + "velgrem", + "vellekoop", + "velvet", + "veneberg", + "venlo", + "vent", + "venusberg", + "venw", + "veredeld", + "verf", + "verhaaf", + "vermaak", + "vernaaid", + "verraad", + "vers", + "veruit", + "verzaagd", + "vetachtig", + "vetlok", + "vetmesten", + "veto", + "vetrek", + "vetstaart", + "vetten", + "veurink", + "viaduct", + "vibrafoon", + "vicariaat", + "vieux", + "vieveen", + "vijfvoud", + "villa", + "vilt", + "vimmetje", + "vindbaar", + "vips", + "virtueel", + "visdieven", + "visee", + "visie", + "vlaag", + "vleugel", + "vmbo", + "vocht", + "voesenek", + "voicemail", + "voip", + "volg", + "vork", + "vorselaar", + "voyeur", + "vracht", + "vrekkig", + "vreten", + "vrije", + "vrozen", + "vrucht", + "vucht", + "vugt", + "vulkaan", + "vulmiddel", + "vulva", + "vuren", + "waas", + "wacht", + "wadvogel", + "wafel", + "waffel", + "walhalla", + "walnoot", + "walraven", + "wals", + "walvis", + "wandaad", + "wanen", + "wanmolen", + "want", + "warklomp", + "warm", + "wasachtig", + "wasteil", + "watt", + "webhandel", + "weblog", + "webpagina", + "webzine", + "wedereis", + "wedstrijd", + "weeda", + "weert", + "wegmaaien", + "wegscheer", + "wekelijks", + "wekken", + "wekroep", + "wektoon", + "weldaad", + "welwater", + "wendbaar", + "wenkbrauw", + "wens", + "wentelaar", + "wervel", + "wesseling", + "wetboek", + "wetmatig", + "whirlpool", + "wijbrands", + "wijdbeens", + "wijk", + "wijnbes", + "wijting", + "wild", + "wimpelen", + "wingebied", + "winplaats", + "winter", + "winzucht", + "wipstaart", + "wisgerhof", + "withaar", + "witmaker", + "wokkel", + "wolf", + "wonenden", + "woning", + "worden", + "worp", + "wortel", + "wrat", + "wrijf", + "wringen", + "yoghurt", + "ypsilon", + "zaaijer", + "zaak", + "zacharias", + "zakelijk", + "zakkam", + "zakwater", + "zalf", + "zalig", + "zaniken", + "zebracode", + "zeeblauw", + "zeef", + "zeegaand", + "zeeuw", + "zege", + "zegje", + "zeil", + "zesbaans", + "zesenhalf", + "zeskantig", + "zesmaal", + "zetbaas", + "zetpil", + "zeulen", + "ziezo", + "zigzag", + "zijaltaar", + "zijbeuk", + "zijlijn", + "zijmuur", + "zijn", + "zijwaarts", + "zijzelf", + "zilt", + "zimmerman", + "zinledig", + "zinnelijk", + "zionist", + "zitdag", + "zitruimte", + "zitzak", + "zoal", + "zodoende", + "zoekbots", + "zoem", + "zoiets", + "zojuist", + "zondaar", + "zotskap", + "zottebol", + "zucht", + "zuivel", + "zulk", + "zult", + "zuster", + "zuur", + "zweedijk", + "zwendel", + "zwepen", + "zwiep", + "zwijmel", + "zworen" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/electrum-words.cpp b/src/mnemonics/electrum-words.cpp index e2deeba2f..0345d1034 100644 --- a/src/mnemonics/electrum-words.cpp +++ b/src/mnemonics/electrum-words.cpp @@ -62,11 +62,9 @@ #include "language_base.h" #include "singleton.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "mnemonic" - namespace crypto { + namespace ElectrumWords { std::vector get_language_list(); @@ -75,6 +73,8 @@ namespace crypto namespace { + static auto logcat = oxen::log::Cat("mnemonic"); + uint32_t create_checksum_index(const std::vector &word_list, const Language::Base *language); bool checksum_test(std::vector seed, const Language::Base *language); @@ -160,7 +160,7 @@ namespace if (full_match) { *language = *it1; - MINFO("Full match for language " << (*language)->get_english_language_name()); + oxen::log::info(logcat, "Full match for language {}", (*language)->get_english_language_name()); return true; } // Some didn't match. Clear the index array. @@ -174,11 +174,11 @@ namespace if (fallback) { *language = fallback; - MINFO("Fallback match for language " << (*language)->get_english_language_name()); + oxen::log::info(logcat, "Fallback match for language {}", (*language)->get_english_language_name()); return true; } - MINFO("No match found"); + oxen::log::info(logcat, "No match found"); memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0])); return false; } @@ -234,7 +234,7 @@ namespace epee::wipeable_string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) : last_word; bool ret = Language::WordEqual()(trimmed_checksum, trimmed_last_word); - MINFO("Checksum is " << (ret ? "valid" : "invalid")); + oxen::log::info(logcat, "Checksum is {}", (ret ? "valid" : "invalid")); return ret; } } @@ -271,7 +271,7 @@ namespace crypto if (len % 4) { - MERROR("Invalid seed: not a multiple of 4"); + oxen::log::error(logcat, "Invalid seed: not a multiple of 4"); return false; } @@ -283,7 +283,7 @@ namespace crypto if (seed.size() != expected/2 && seed.size() != expected && seed.size() != expected + 1) { - MERROR("Invalid seed: unexpected number of words"); + oxen::log::error(logcat, "Invalid seed: unexpected number of words"); return false; } @@ -296,7 +296,7 @@ namespace crypto Language::Base *language; if (!find_seed_language(seed, has_checksum, matched_indices, &language)) { - MERROR("Invalid seed: language not found"); + oxen::log::error(logcat, "Invalid seed: language not found"); return false; } language_name = language->get_language_name(); @@ -307,7 +307,7 @@ namespace crypto if (!checksum_test(seed, language)) { // Checksum fail - MERROR("Invalid seed: invalid checksum"); + oxen::log::error(logcat, "Invalid seed: invalid checksum"); return false; } seed.pop_back(); @@ -326,7 +326,7 @@ namespace crypto if (!(w[0]% word_list_length == w[1])) { memwipe(w, sizeof(w)); - MERROR("Invalid seed: mumble mumble"); + oxen::log::error(logcat, "Invalid seed: mumble mumble"); return false; } @@ -360,12 +360,12 @@ namespace crypto epee::wipeable_string s; if (!words_to_bytes(words, s, sizeof(dst), true, language_name)) { - MERROR("Invalid seed: failed to convert words to bytes"); + oxen::log::error(logcat, "Invalid seed: failed to convert words to bytes"); return false; } if (s.size() != sizeof(dst)) { - MERROR("Invalid seed: wrong output size"); + oxen::log::error(logcat, "Invalid seed: wrong output size"); return false; } dst = *(const crypto::secret_key*)s.data(); diff --git a/src/mnemonics/english.h b/src/mnemonics/english.h index 677b70052..4870ddb41 100644 --- a/src/mnemonics/english.h +++ b/src/mnemonics/english.h @@ -1,1689 +1,1689 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file english.h - * - * \brief New English word list and map. - */ - -#ifndef ENGLISH_H -#define ENGLISH_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class English: public Base - { - public: - English(): Base("English", "English", {}, 3) - { - static constexpr const char * const words[NWORDS] = - { - "abbey", - "abducts", - "ability", - "ablaze", - "abnormal", - "abort", - "abrasive", - "absorb", - "abyss", - "academy", - "aces", - "aching", - "acidic", - "acoustic", - "acquire", - "across", - "actress", - "acumen", - "adapt", - "addicted", - "adept", - "adhesive", - "adjust", - "adopt", - "adrenalin", - "adult", - "adventure", - "aerial", - "afar", - "affair", - "afield", - "afloat", - "afoot", - "afraid", - "after", - "against", - "agenda", - "aggravate", - "agile", - "aglow", - "agnostic", - "agony", - "agreed", - "ahead", - "aided", - "ailments", - "aimless", - "airport", - "aisle", - "ajar", - "akin", - "alarms", - "album", - "alchemy", - "alerts", - "algebra", - "alkaline", - "alley", - "almost", - "aloof", - "alpine", - "already", - "also", - "altitude", - "alumni", - "always", - "amaze", - "ambush", - "amended", - "amidst", - "ammo", - "amnesty", - "among", - "amply", - "amused", - "anchor", - "android", - "anecdote", - "angled", - "ankle", - "annoyed", - "answers", - "antics", - "anvil", - "anxiety", - "anybody", - "apart", - "apex", - "aphid", - "aplomb", - "apology", - "apply", - "apricot", - "aptitude", - "aquarium", - "arbitrary", - "archer", - "ardent", - "arena", - "argue", - "arises", - "army", - "around", - "arrow", - "arsenic", - "artistic", - "ascend", - "ashtray", - "aside", - "asked", - "asleep", - "aspire", - "assorted", - "asylum", - "athlete", - "atlas", - "atom", - "atrium", - "attire", - "auburn", - "auctions", - "audio", - "august", - "aunt", - "austere", - "autumn", - "avatar", - "avidly", - "avoid", - "awakened", - "awesome", - "awful", - "awkward", - "awning", - "awoken", - "axes", - "axis", - "axle", - "aztec", - "azure", - "baby", - "bacon", - "badge", - "baffles", - "bagpipe", - "bailed", - "bakery", - "balding", - "bamboo", - "banjo", - "baptism", - "basin", - "batch", - "bawled", - "bays", - "because", - "beer", - "befit", - "begun", - "behind", - "being", - "below", - "bemused", - "benches", - "berries", - "bested", - "betting", - "bevel", - "beware", - "beyond", - "bias", - "bicycle", - "bids", - "bifocals", - "biggest", - "bikini", - "bimonthly", - "binocular", - "biology", - "biplane", - "birth", - "biscuit", - "bite", - "biweekly", - "blender", - "blip", - "bluntly", - "boat", - "bobsled", - "bodies", - "bogeys", - "boil", - "boldly", - "bomb", - "border", - "boss", - "both", - "bounced", - "bovine", - "bowling", - "boxes", - "boyfriend", - "broken", - "brunt", - "bubble", - "buckets", - "budget", - "buffet", - "bugs", - "building", - "bulb", - "bumper", - "bunch", - "business", - "butter", - "buying", - "buzzer", - "bygones", - "byline", - "bypass", - "cabin", - "cactus", - "cadets", - "cafe", - "cage", - "cajun", - "cake", - "calamity", - "camp", - "candy", - "casket", - "catch", - "cause", - "cavernous", - "cease", - "cedar", - "ceiling", - "cell", - "cement", - "cent", - "certain", - "chlorine", - "chrome", - "cider", - "cigar", - "cinema", - "circle", - "cistern", - "citadel", - "civilian", - "claim", - "click", - "clue", - "coal", - "cobra", - "cocoa", - "code", - "coexist", - "coffee", - "cogs", - "cohesive", - "coils", - "colony", - "comb", - "cool", - "copy", - "corrode", - "costume", - "cottage", - "cousin", - "cowl", - "criminal", - "cube", - "cucumber", - "cuddled", - "cuffs", - "cuisine", - "cunning", - "cupcake", - "custom", - "cycling", - "cylinder", - "cynical", - "dabbing", - "dads", - "daft", - "dagger", - "daily", - "damp", - "dangerous", - "dapper", - "darted", - "dash", - "dating", - "dauntless", - "dawn", - "daytime", - "dazed", - "debut", - "decay", - "dedicated", - "deepest", - "deftly", - "degrees", - "dehydrate", - "deity", - "dejected", - "delayed", - "demonstrate", - "dented", - "deodorant", - "depth", - "desk", - "devoid", - "dewdrop", - "dexterity", - "dialect", - "dice", - "diet", - "different", - "digit", - "dilute", - "dime", - "dinner", - "diode", - "diplomat", - "directed", - "distance", - "ditch", - "divers", - "dizzy", - "doctor", - "dodge", - "does", - "dogs", - "doing", - "dolphin", - "domestic", - "donuts", - "doorway", - "dormant", - "dosage", - "dotted", - "double", - "dove", - "down", - "dozen", - "dreams", - "drinks", - "drowning", - "drunk", - "drying", - "dual", - "dubbed", - "duckling", - "dude", - "duets", - "duke", - "dullness", - "dummy", - "dunes", - "duplex", - "duration", - "dusted", - "duties", - "dwarf", - "dwelt", - "dwindling", - "dying", - "dynamite", - "dyslexic", - "each", - "eagle", - "earth", - "easy", - "eating", - "eavesdrop", - "eccentric", - "echo", - "eclipse", - "economics", - "ecstatic", - "eden", - "edgy", - "edited", - "educated", - "eels", - "efficient", - "eggs", - "egotistic", - "eight", - "either", - "eject", - "elapse", - "elbow", - "eldest", - "eleven", - "elite", - "elope", - "else", - "eluded", - "emails", - "ember", - "emerge", - "emit", - "emotion", - "empty", - "emulate", - "energy", - "enforce", - "enhanced", - "enigma", - "enjoy", - "enlist", - "enmity", - "enough", - "enraged", - "ensign", - "entrance", - "envy", - "epoxy", - "equip", - "erase", - "erected", - "erosion", - "error", - "eskimos", - "espionage", - "essential", - "estate", - "etched", - "eternal", - "ethics", - "etiquette", - "evaluate", - "evenings", - "evicted", - "evolved", - "examine", - "excess", - "exhale", - "exit", - "exotic", - "exquisite", - "extra", - "exult", - "fabrics", - "factual", - "fading", - "fainted", - "faked", - "fall", - "family", - "fancy", - "farming", - "fatal", - "faulty", - "fawns", - "faxed", - "fazed", - "feast", - "february", - "federal", - "feel", - "feline", - "females", - "fences", - "ferry", - "festival", - "fetches", - "fever", - "fewest", - "fiat", - "fibula", - "fictional", - "fidget", - "fierce", - "fifteen", - "fight", - "films", - "firm", - "fishing", - "fitting", - "five", - "fixate", - "fizzle", - "fleet", - "flippant", - "flying", - "foamy", - "focus", - "foes", - "foggy", - "foiled", - "folding", - "fonts", - "foolish", - "fossil", - "fountain", - "fowls", - "foxes", - "foyer", - "framed", - "friendly", - "frown", - "fruit", - "frying", - "fudge", - "fuel", - "fugitive", - "fully", - "fuming", - "fungal", - "furnished", - "fuselage", - "future", - "fuzzy", - "gables", - "gadget", - "gags", - "gained", - "galaxy", - "gambit", - "gang", - "gasp", - "gather", - "gauze", - "gave", - "gawk", - "gaze", - "gearbox", - "gecko", - "geek", - "gels", - "gemstone", - "general", - "geometry", - "germs", - "gesture", - "getting", - "geyser", - "ghetto", - "ghost", - "giant", - "giddy", - "gifts", - "gigantic", - "gills", - "gimmick", - "ginger", - "girth", - "giving", - "glass", - "gleeful", - "glide", - "gnaw", - "gnome", - "goat", - "goblet", - "godfather", - "goes", - "goggles", - "going", - "goldfish", - "gone", - "goodbye", - "gopher", - "gorilla", - "gossip", - "gotten", - "gourmet", - "governing", - "gown", - "greater", - "grunt", - "guarded", - "guest", - "guide", - "gulp", - "gumball", - "guru", - "gusts", - "gutter", - "guys", - "gymnast", - "gypsy", - "gyrate", - "habitat", - "hacksaw", - "haggled", - "hairy", - "hamburger", - "happens", - "hashing", - "hatchet", - "haunted", - "having", - "hawk", - "haystack", - "hazard", - "hectare", - "hedgehog", - "heels", - "hefty", - "height", - "hemlock", - "hence", - "heron", - "hesitate", - "hexagon", - "hickory", - "hiding", - "highway", - "hijack", - "hiker", - "hills", - "himself", - "hinder", - "hippo", - "hire", - "history", - "hitched", - "hive", - "hoax", - "hobby", - "hockey", - "hoisting", - "hold", - "honked", - "hookup", - "hope", - "hornet", - "hospital", - "hotel", - "hounded", - "hover", - "howls", - "hubcaps", - "huddle", - "huge", - "hull", - "humid", - "hunter", - "hurried", - "husband", - "huts", - "hybrid", - "hydrogen", - "hyper", - "iceberg", - "icing", - "icon", - "identity", - "idiom", - "idled", - "idols", - "igloo", - "ignore", - "iguana", - "illness", - "imagine", - "imbalance", - "imitate", - "impel", - "inactive", - "inbound", - "incur", - "industrial", - "inexact", - "inflamed", - "ingested", - "initiate", - "injury", - "inkling", - "inline", - "inmate", - "innocent", - "inorganic", - "input", - "inquest", - "inroads", - "insult", - "intended", - "inundate", - "invoke", - "inwardly", - "ionic", - "irate", - "iris", - "irony", - "irritate", - "island", - "isolated", - "issued", - "italics", - "itches", - "items", - "itinerary", - "itself", - "ivory", - "jabbed", - "jackets", - "jaded", - "jagged", - "jailed", - "jamming", - "january", - "jargon", - "jaunt", - "javelin", - "jaws", - "jazz", - "jeans", - "jeers", - "jellyfish", - "jeopardy", - "jerseys", - "jester", - "jetting", - "jewels", - "jigsaw", - "jingle", - "jittery", - "jive", - "jobs", - "jockey", - "jogger", - "joining", - "joking", - "jolted", - "jostle", - "journal", - "joyous", - "jubilee", - "judge", - "juggled", - "juicy", - "jukebox", - "july", - "jump", - "junk", - "jury", - "justice", - "juvenile", - "kangaroo", - "karate", - "keep", - "kennel", - "kept", - "kernels", - "kettle", - "keyboard", - "kickoff", - "kidneys", - "king", - "kiosk", - "kisses", - "kitchens", - "kiwi", - "knapsack", - "knee", - "knife", - "knowledge", - "knuckle", - "koala", - "laboratory", - "ladder", - "lagoon", - "lair", - "lakes", - "lamb", - "language", - "laptop", - "large", - "last", - "later", - "launching", - "lava", - "lawsuit", - "layout", - "lazy", - "lectures", - "ledge", - "leech", - "left", - "legion", - "leisure", - "lemon", - "lending", - "leopard", - "lesson", - "lettuce", - "lexicon", - "liar", - "library", - "licks", - "lids", - "lied", - "lifestyle", - "light", - "likewise", - "lilac", - "limits", - "linen", - "lion", - "lipstick", - "liquid", - "listen", - "lively", - "loaded", - "lobster", - "locker", - "lodge", - "lofty", - "logic", - "loincloth", - "long", - "looking", - "lopped", - "lordship", - "losing", - "lottery", - "loudly", - "love", - "lower", - "loyal", - "lucky", - "luggage", - "lukewarm", - "lullaby", - "lumber", - "lunar", - "lurk", - "lush", - "luxury", - "lymph", - "lynx", - "lyrics", - "macro", - "madness", - "magically", - "mailed", - "major", - "makeup", - "malady", - "mammal", - "maps", - "masterful", - "match", - "maul", - "maverick", - "maximum", - "mayor", - "maze", - "meant", - "mechanic", - "medicate", - "meeting", - "megabyte", - "melting", - "memoir", - "menu", - "merger", - "mesh", - "metro", - "mews", - "mice", - "midst", - "mighty", - "mime", - "mirror", - "misery", - "mittens", - "mixture", - "moat", - "mobile", - "mocked", - "mohawk", - "moisture", - "molten", - "moment", - "money", - "moon", - "mops", - "morsel", - "mostly", - "motherly", - "mouth", - "movement", - "mowing", - "much", - "muddy", - "muffin", - "mugged", - "mullet", - "mumble", - "mundane", - "muppet", - "mural", - "musical", - "muzzle", - "myriad", - "mystery", - "myth", - "nabbing", - "nagged", - "nail", - "names", - "nanny", - "napkin", - "narrate", - "nasty", - "natural", - "nautical", - "navy", - "nearby", - "necklace", - "needed", - "negative", - "neither", - "neon", - "nephew", - "nerves", - "nestle", - "network", - "neutral", - "never", - "newt", - "nexus", - "nibs", - "niche", - "niece", - "nifty", - "nightly", - "nimbly", - "nineteen", - "nirvana", - "nitrogen", - "nobody", - "nocturnal", - "nodes", - "noises", - "nomad", - "noodles", - "northern", - "nostril", - "noted", - "nouns", - "novelty", - "nowhere", - "nozzle", - "nuance", - "nucleus", - "nudged", - "nugget", - "nuisance", - "null", - "number", - "nuns", - "nurse", - "nutshell", - "nylon", - "oaks", - "oars", - "oasis", - "oatmeal", - "obedient", - "object", - "obliged", - "obnoxious", - "observant", - "obtains", - "obvious", - "occur", - "ocean", - "october", - "odds", - "odometer", - "offend", - "often", - "oilfield", - "ointment", - "okay", - "older", - "olive", - "olympics", - "omega", - "omission", - "omnibus", - "onboard", - "oncoming", - "oneself", - "ongoing", - "onion", - "online", - "onslaught", - "onto", - "onward", - "oozed", - "opacity", - "opened", - "opposite", - "optical", - "opus", - "orange", - "orbit", - "orchid", - "orders", - "organs", - "origin", - "ornament", - "orphans", - "oscar", - "ostrich", - "otherwise", - "otter", - "ouch", - "ought", - "ounce", - "ourselves", - "oust", - "outbreak", - "oval", - "oven", - "owed", - "owls", - "owner", - "oxidant", - "oxygen", - "oyster", - "ozone", - "pact", - "paddles", - "pager", - "pairing", - "palace", - "pamphlet", - "pancakes", - "paper", - "paradise", - "pastry", - "patio", - "pause", - "pavements", - "pawnshop", - "payment", - "peaches", - "pebbles", - "peculiar", - "pedantic", - "peeled", - "pegs", - "pelican", - "pencil", - "people", - "pepper", - "perfect", - "pests", - "petals", - "phase", - "pheasants", - "phone", - "phrases", - "physics", - "piano", - "picked", - "pierce", - "pigment", - "piloted", - "pimple", - "pinched", - "pioneer", - "pipeline", - "pirate", - "pistons", - "pitched", - "pivot", - "pixels", - "pizza", - "playful", - "pledge", - "pliers", - "plotting", - "plus", - "plywood", - "poaching", - "pockets", - "podcast", - "poetry", - "point", - "poker", - "polar", - "ponies", - "pool", - "popular", - "portents", - "possible", - "potato", - "pouch", - "poverty", - "powder", - "pram", - "present", - "pride", - "problems", - "pruned", - "prying", - "psychic", - "public", - "puck", - "puddle", - "puffin", - "pulp", - "pumpkins", - "punch", - "puppy", - "purged", - "push", - "putty", - "puzzled", - "pylons", - "pyramid", - "python", - "queen", - "quick", - "quote", - "rabbits", - "racetrack", - "radar", - "rafts", - "rage", - "railway", - "raking", - "rally", - "ramped", - "randomly", - "rapid", - "rarest", - "rash", - "rated", - "ravine", - "rays", - "razor", - "react", - "rebel", - "recipe", - "reduce", - "reef", - "refer", - "regular", - "reheat", - "reinvest", - "rejoices", - "rekindle", - "relic", - "remedy", - "renting", - "reorder", - "repent", - "request", - "reruns", - "rest", - "return", - "reunion", - "revamp", - "rewind", - "rhino", - "rhythm", - "ribbon", - "richly", - "ridges", - "rift", - "rigid", - "rims", - "ringing", - "riots", - "ripped", - "rising", - "ritual", - "river", - "roared", - "robot", - "rockets", - "rodent", - "rogue", - "roles", - "romance", - "roomy", - "roped", - "roster", - "rotate", - "rounded", - "rover", - "rowboat", - "royal", - "ruby", - "rudely", - "ruffled", - "rugged", - "ruined", - "ruling", - "rumble", - "runway", - "rural", - "rustled", - "ruthless", - "sabotage", - "sack", - "sadness", - "safety", - "saga", - "sailor", - "sake", - "salads", - "sample", - "sanity", - "sapling", - "sarcasm", - "sash", - "satin", - "saucepan", - "saved", - "sawmill", - "saxophone", - "sayings", - "scamper", - "scenic", - "school", - "science", - "scoop", - "scrub", - "scuba", - "seasons", - "second", - "sedan", - "seeded", - "segments", - "seismic", - "selfish", - "semifinal", - "sensible", - "september", - "sequence", - "serving", - "session", - "setup", - "seventh", - "sewage", - "shackles", - "shelter", - "shipped", - "shocking", - "shrugged", - "shuffled", - "shyness", - "siblings", - "sickness", - "sidekick", - "sieve", - "sifting", - "sighting", - "silk", - "simplest", - "sincerely", - "sipped", - "siren", - "situated", - "sixteen", - "sizes", - "skater", - "skew", - "skirting", - "skulls", - "skydive", - "slackens", - "sleepless", - "slid", - "slower", - "slug", - "smash", - "smelting", - "smidgen", - "smog", - "smuggled", - "snake", - "sneeze", - "sniff", - "snout", - "snug", - "soapy", - "sober", - "soccer", - "soda", - "software", - "soggy", - "soil", - "solved", - "somewhere", - "sonic", - "soothe", - "soprano", - "sorry", - "southern", - "sovereign", - "sowed", - "soya", - "space", - "speedy", - "sphere", - "spiders", - "splendid", - "spout", - "sprig", - "spud", - "spying", - "square", - "stacking", - "stellar", - "stick", - "stockpile", - "strained", - "stunning", - "stylishly", - "subtly", - "succeed", - "suddenly", - "suede", - "suffice", - "sugar", - "suitcase", - "sulking", - "summon", - "sunken", - "superior", - "surfer", - "sushi", - "suture", - "swagger", - "swept", - "swiftly", - "sword", - "swung", - "syllabus", - "symptoms", - "syndrome", - "syringe", - "system", - "taboo", - "tacit", - "tadpoles", - "tagged", - "tail", - "taken", - "talent", - "tamper", - "tanks", - "tapestry", - "tarnished", - "tasked", - "tattoo", - "taunts", - "tavern", - "tawny", - "taxi", - "teardrop", - "technical", - "tedious", - "teeming", - "tell", - "template", - "tender", - "tepid", - "tequila", - "terminal", - "testing", - "tether", - "textbook", - "thaw", - "theatrics", - "thirsty", - "thorn", - "threaten", - "thumbs", - "thwart", - "ticket", - "tidy", - "tiers", - "tiger", - "tilt", - "timber", - "tinted", - "tipsy", - "tirade", - "tissue", - "titans", - "toaster", - "tobacco", - "today", - "toenail", - "toffee", - "together", - "toilet", - "token", - "tolerant", - "tomorrow", - "tonic", - "toolbox", - "topic", - "torch", - "tossed", - "total", - "touchy", - "towel", - "toxic", - "toyed", - "trash", - "trendy", - "tribal", - "trolling", - "truth", - "trying", - "tsunami", - "tubes", - "tucks", - "tudor", - "tuesday", - "tufts", - "tugs", - "tuition", - "tulips", - "tumbling", - "tunnel", - "turnip", - "tusks", - "tutor", - "tuxedo", - "twang", - "tweezers", - "twice", - "twofold", - "tycoon", - "typist", - "tyrant", - "ugly", - "ulcers", - "ultimate", - "umbrella", - "umpire", - "unafraid", - "unbending", - "uncle", - "under", - "uneven", - "unfit", - "ungainly", - "unhappy", - "union", - "unjustly", - "unknown", - "unlikely", - "unmask", - "unnoticed", - "unopened", - "unplugs", - "unquoted", - "unrest", - "unsafe", - "until", - "unusual", - "unveil", - "unwind", - "unzip", - "upbeat", - "upcoming", - "update", - "upgrade", - "uphill", - "upkeep", - "upload", - "upon", - "upper", - "upright", - "upstairs", - "uptight", - "upwards", - "urban", - "urchins", - "urgent", - "usage", - "useful", - "usher", - "using", - "usual", - "utensils", - "utility", - "utmost", - "utopia", - "uttered", - "vacation", - "vague", - "vain", - "value", - "vampire", - "vane", - "vapidly", - "vary", - "vastness", - "vats", - "vaults", - "vector", - "veered", - "vegan", - "vehicle", - "vein", - "velvet", - "venomous", - "verification", - "vessel", - "veteran", - "vexed", - "vials", - "vibrate", - "victim", - "video", - "viewpoint", - "vigilant", - "viking", - "village", - "vinegar", - "violin", - "vipers", - "virtual", - "visited", - "vitals", - "vivid", - "vixen", - "vocal", - "vogue", - "voice", - "volcano", - "vortex", - "voted", - "voucher", - "vowels", - "voyage", - "vulture", - "wade", - "waffle", - "wagtail", - "waist", - "waking", - "wallets", - "wanted", - "warped", - "washing", - "water", - "waveform", - "waxing", - "wayside", - "weavers", - "website", - "wedge", - "weekday", - "weird", - "welders", - "went", - "wept", - "were", - "western", - "wetsuit", - "whale", - "when", - "whipped", - "whole", - "wickets", - "width", - "wield", - "wife", - "wiggle", - "wildly", - "winter", - "wipeout", - "wiring", - "wise", - "withdrawn", - "wives", - "wizard", - "wobbly", - "woes", - "woken", - "wolf", - "womanly", - "wonders", - "woozy", - "worry", - "wounded", - "woven", - "wrap", - "wrist", - "wrong", - "yacht", - "yahoo", - "yanks", - "yard", - "yawning", - "yearbook", - "yellow", - "yesterday", - "yeti", - "yields", - "yodel", - "yoga", - "younger", - "yoyo", - "zapped", - "zeal", - "zebra", - "zero", - "zesty", - "zigzags", - "zinger", - "zippers", - "zodiac", - "zombie", - "zones", - "zoom" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file english.h + * + * \brief New English word list and map. + */ + +#ifndef ENGLISH_H +#define ENGLISH_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class English: public Base + { + public: + English(): Base("English", "English", {}, 3) + { + static constexpr const char * const words[NWORDS] = + { + "abbey", + "abducts", + "ability", + "ablaze", + "abnormal", + "abort", + "abrasive", + "absorb", + "abyss", + "academy", + "aces", + "aching", + "acidic", + "acoustic", + "acquire", + "across", + "actress", + "acumen", + "adapt", + "addicted", + "adept", + "adhesive", + "adjust", + "adopt", + "adrenalin", + "adult", + "adventure", + "aerial", + "afar", + "affair", + "afield", + "afloat", + "afoot", + "afraid", + "after", + "against", + "agenda", + "aggravate", + "agile", + "aglow", + "agnostic", + "agony", + "agreed", + "ahead", + "aided", + "ailments", + "aimless", + "airport", + "aisle", + "ajar", + "akin", + "alarms", + "album", + "alchemy", + "alerts", + "algebra", + "alkaline", + "alley", + "almost", + "aloof", + "alpine", + "already", + "also", + "altitude", + "alumni", + "always", + "amaze", + "ambush", + "amended", + "amidst", + "ammo", + "amnesty", + "among", + "amply", + "amused", + "anchor", + "android", + "anecdote", + "angled", + "ankle", + "annoyed", + "answers", + "antics", + "anvil", + "anxiety", + "anybody", + "apart", + "apex", + "aphid", + "aplomb", + "apology", + "apply", + "apricot", + "aptitude", + "aquarium", + "arbitrary", + "archer", + "ardent", + "arena", + "argue", + "arises", + "army", + "around", + "arrow", + "arsenic", + "artistic", + "ascend", + "ashtray", + "aside", + "asked", + "asleep", + "aspire", + "assorted", + "asylum", + "athlete", + "atlas", + "atom", + "atrium", + "attire", + "auburn", + "auctions", + "audio", + "august", + "aunt", + "austere", + "autumn", + "avatar", + "avidly", + "avoid", + "awakened", + "awesome", + "awful", + "awkward", + "awning", + "awoken", + "axes", + "axis", + "axle", + "aztec", + "azure", + "baby", + "bacon", + "badge", + "baffles", + "bagpipe", + "bailed", + "bakery", + "balding", + "bamboo", + "banjo", + "baptism", + "basin", + "batch", + "bawled", + "bays", + "because", + "beer", + "befit", + "begun", + "behind", + "being", + "below", + "bemused", + "benches", + "berries", + "bested", + "betting", + "bevel", + "beware", + "beyond", + "bias", + "bicycle", + "bids", + "bifocals", + "biggest", + "bikini", + "bimonthly", + "binocular", + "biology", + "biplane", + "birth", + "biscuit", + "bite", + "biweekly", + "blender", + "blip", + "bluntly", + "boat", + "bobsled", + "bodies", + "bogeys", + "boil", + "boldly", + "bomb", + "border", + "boss", + "both", + "bounced", + "bovine", + "bowling", + "boxes", + "boyfriend", + "broken", + "brunt", + "bubble", + "buckets", + "budget", + "buffet", + "bugs", + "building", + "bulb", + "bumper", + "bunch", + "business", + "butter", + "buying", + "buzzer", + "bygones", + "byline", + "bypass", + "cabin", + "cactus", + "cadets", + "cafe", + "cage", + "cajun", + "cake", + "calamity", + "camp", + "candy", + "casket", + "catch", + "cause", + "cavernous", + "cease", + "cedar", + "ceiling", + "cell", + "cement", + "cent", + "certain", + "chlorine", + "chrome", + "cider", + "cigar", + "cinema", + "circle", + "cistern", + "citadel", + "civilian", + "claim", + "click", + "clue", + "coal", + "cobra", + "cocoa", + "code", + "coexist", + "coffee", + "cogs", + "cohesive", + "coils", + "colony", + "comb", + "cool", + "copy", + "corrode", + "costume", + "cottage", + "cousin", + "cowl", + "criminal", + "cube", + "cucumber", + "cuddled", + "cuffs", + "cuisine", + "cunning", + "cupcake", + "custom", + "cycling", + "cylinder", + "cynical", + "dabbing", + "dads", + "daft", + "dagger", + "daily", + "damp", + "dangerous", + "dapper", + "darted", + "dash", + "dating", + "dauntless", + "dawn", + "daytime", + "dazed", + "debut", + "decay", + "dedicated", + "deepest", + "deftly", + "degrees", + "dehydrate", + "deity", + "dejected", + "delayed", + "demonstrate", + "dented", + "deodorant", + "depth", + "desk", + "devoid", + "dewdrop", + "dexterity", + "dialect", + "dice", + "diet", + "different", + "digit", + "dilute", + "dime", + "dinner", + "diode", + "diplomat", + "directed", + "distance", + "ditch", + "divers", + "dizzy", + "doctor", + "dodge", + "does", + "dogs", + "doing", + "dolphin", + "domestic", + "donuts", + "doorway", + "dormant", + "dosage", + "dotted", + "double", + "dove", + "down", + "dozen", + "dreams", + "drinks", + "drowning", + "drunk", + "drying", + "dual", + "dubbed", + "duckling", + "dude", + "duets", + "duke", + "dullness", + "dummy", + "dunes", + "duplex", + "duration", + "dusted", + "duties", + "dwarf", + "dwelt", + "dwindling", + "dying", + "dynamite", + "dyslexic", + "each", + "eagle", + "earth", + "easy", + "eating", + "eavesdrop", + "eccentric", + "echo", + "eclipse", + "economics", + "ecstatic", + "eden", + "edgy", + "edited", + "educated", + "eels", + "efficient", + "eggs", + "egotistic", + "eight", + "either", + "eject", + "elapse", + "elbow", + "eldest", + "eleven", + "elite", + "elope", + "else", + "eluded", + "emails", + "ember", + "emerge", + "emit", + "emotion", + "empty", + "emulate", + "energy", + "enforce", + "enhanced", + "enigma", + "enjoy", + "enlist", + "enmity", + "enough", + "enraged", + "ensign", + "entrance", + "envy", + "epoxy", + "equip", + "erase", + "erected", + "erosion", + "error", + "eskimos", + "espionage", + "essential", + "estate", + "etched", + "eternal", + "ethics", + "etiquette", + "evaluate", + "evenings", + "evicted", + "evolved", + "examine", + "excess", + "exhale", + "exit", + "exotic", + "exquisite", + "extra", + "exult", + "fabrics", + "factual", + "fading", + "fainted", + "faked", + "fall", + "family", + "fancy", + "farming", + "fatal", + "faulty", + "fawns", + "faxed", + "fazed", + "feast", + "february", + "federal", + "feel", + "feline", + "females", + "fences", + "ferry", + "festival", + "fetches", + "fever", + "fewest", + "fiat", + "fibula", + "fictional", + "fidget", + "fierce", + "fifteen", + "fight", + "films", + "firm", + "fishing", + "fitting", + "five", + "fixate", + "fizzle", + "fleet", + "flippant", + "flying", + "foamy", + "focus", + "foes", + "foggy", + "foiled", + "folding", + "fonts", + "foolish", + "fossil", + "fountain", + "fowls", + "foxes", + "foyer", + "framed", + "friendly", + "frown", + "fruit", + "frying", + "fudge", + "fuel", + "fugitive", + "fully", + "fuming", + "fungal", + "furnished", + "fuselage", + "future", + "fuzzy", + "gables", + "gadget", + "gags", + "gained", + "galaxy", + "gambit", + "gang", + "gasp", + "gather", + "gauze", + "gave", + "gawk", + "gaze", + "gearbox", + "gecko", + "geek", + "gels", + "gemstone", + "general", + "geometry", + "germs", + "gesture", + "getting", + "geyser", + "ghetto", + "ghost", + "giant", + "giddy", + "gifts", + "gigantic", + "gills", + "gimmick", + "ginger", + "girth", + "giving", + "glass", + "gleeful", + "glide", + "gnaw", + "gnome", + "goat", + "goblet", + "godfather", + "goes", + "goggles", + "going", + "goldfish", + "gone", + "goodbye", + "gopher", + "gorilla", + "gossip", + "gotten", + "gourmet", + "governing", + "gown", + "greater", + "grunt", + "guarded", + "guest", + "guide", + "gulp", + "gumball", + "guru", + "gusts", + "gutter", + "guys", + "gymnast", + "gypsy", + "gyrate", + "habitat", + "hacksaw", + "haggled", + "hairy", + "hamburger", + "happens", + "hashing", + "hatchet", + "haunted", + "having", + "hawk", + "haystack", + "hazard", + "hectare", + "hedgehog", + "heels", + "hefty", + "height", + "hemlock", + "hence", + "heron", + "hesitate", + "hexagon", + "hickory", + "hiding", + "highway", + "hijack", + "hiker", + "hills", + "himself", + "hinder", + "hippo", + "hire", + "history", + "hitched", + "hive", + "hoax", + "hobby", + "hockey", + "hoisting", + "hold", + "honked", + "hookup", + "hope", + "hornet", + "hospital", + "hotel", + "hounded", + "hover", + "howls", + "hubcaps", + "huddle", + "huge", + "hull", + "humid", + "hunter", + "hurried", + "husband", + "huts", + "hybrid", + "hydrogen", + "hyper", + "iceberg", + "icing", + "icon", + "identity", + "idiom", + "idled", + "idols", + "igloo", + "ignore", + "iguana", + "illness", + "imagine", + "imbalance", + "imitate", + "impel", + "inactive", + "inbound", + "incur", + "industrial", + "inexact", + "inflamed", + "ingested", + "initiate", + "injury", + "inkling", + "inline", + "inmate", + "innocent", + "inorganic", + "input", + "inquest", + "inroads", + "insult", + "intended", + "inundate", + "invoke", + "inwardly", + "ionic", + "irate", + "iris", + "irony", + "irritate", + "island", + "isolated", + "issued", + "italics", + "itches", + "items", + "itinerary", + "itself", + "ivory", + "jabbed", + "jackets", + "jaded", + "jagged", + "jailed", + "jamming", + "january", + "jargon", + "jaunt", + "javelin", + "jaws", + "jazz", + "jeans", + "jeers", + "jellyfish", + "jeopardy", + "jerseys", + "jester", + "jetting", + "jewels", + "jigsaw", + "jingle", + "jittery", + "jive", + "jobs", + "jockey", + "jogger", + "joining", + "joking", + "jolted", + "jostle", + "journal", + "joyous", + "jubilee", + "judge", + "juggled", + "juicy", + "jukebox", + "july", + "jump", + "junk", + "jury", + "justice", + "juvenile", + "kangaroo", + "karate", + "keep", + "kennel", + "kept", + "kernels", + "kettle", + "keyboard", + "kickoff", + "kidneys", + "king", + "kiosk", + "kisses", + "kitchens", + "kiwi", + "knapsack", + "knee", + "knife", + "knowledge", + "knuckle", + "koala", + "laboratory", + "ladder", + "lagoon", + "lair", + "lakes", + "lamb", + "language", + "laptop", + "large", + "last", + "later", + "launching", + "lava", + "lawsuit", + "layout", + "lazy", + "lectures", + "ledge", + "leech", + "left", + "legion", + "leisure", + "lemon", + "lending", + "leopard", + "lesson", + "lettuce", + "lexicon", + "liar", + "library", + "licks", + "lids", + "lied", + "lifestyle", + "light", + "likewise", + "lilac", + "limits", + "linen", + "lion", + "lipstick", + "liquid", + "listen", + "lively", + "loaded", + "lobster", + "locker", + "lodge", + "lofty", + "logic", + "loincloth", + "long", + "looking", + "lopped", + "lordship", + "losing", + "lottery", + "loudly", + "love", + "lower", + "loyal", + "lucky", + "luggage", + "lukewarm", + "lullaby", + "lumber", + "lunar", + "lurk", + "lush", + "luxury", + "lymph", + "lynx", + "lyrics", + "macro", + "madness", + "magically", + "mailed", + "major", + "makeup", + "malady", + "mammal", + "maps", + "masterful", + "match", + "maul", + "maverick", + "maximum", + "mayor", + "maze", + "meant", + "mechanic", + "medicate", + "meeting", + "megabyte", + "melting", + "memoir", + "menu", + "merger", + "mesh", + "metro", + "mews", + "mice", + "midst", + "mighty", + "mime", + "mirror", + "misery", + "mittens", + "mixture", + "moat", + "mobile", + "mocked", + "mohawk", + "moisture", + "molten", + "moment", + "money", + "moon", + "mops", + "morsel", + "mostly", + "motherly", + "mouth", + "movement", + "mowing", + "much", + "muddy", + "muffin", + "mugged", + "mullet", + "mumble", + "mundane", + "muppet", + "mural", + "musical", + "muzzle", + "myriad", + "mystery", + "myth", + "nabbing", + "nagged", + "nail", + "names", + "nanny", + "napkin", + "narrate", + "nasty", + "natural", + "nautical", + "navy", + "nearby", + "necklace", + "needed", + "negative", + "neither", + "neon", + "nephew", + "nerves", + "nestle", + "network", + "neutral", + "never", + "newt", + "nexus", + "nibs", + "niche", + "niece", + "nifty", + "nightly", + "nimbly", + "nineteen", + "nirvana", + "nitrogen", + "nobody", + "nocturnal", + "nodes", + "noises", + "nomad", + "noodles", + "northern", + "nostril", + "noted", + "nouns", + "novelty", + "nowhere", + "nozzle", + "nuance", + "nucleus", + "nudged", + "nugget", + "nuisance", + "null", + "number", + "nuns", + "nurse", + "nutshell", + "nylon", + "oaks", + "oars", + "oasis", + "oatmeal", + "obedient", + "object", + "obliged", + "obnoxious", + "observant", + "obtains", + "obvious", + "occur", + "ocean", + "october", + "odds", + "odometer", + "offend", + "often", + "oilfield", + "ointment", + "okay", + "older", + "olive", + "olympics", + "omega", + "omission", + "omnibus", + "onboard", + "oncoming", + "oneself", + "ongoing", + "onion", + "online", + "onslaught", + "onto", + "onward", + "oozed", + "opacity", + "opened", + "opposite", + "optical", + "opus", + "orange", + "orbit", + "orchid", + "orders", + "organs", + "origin", + "ornament", + "orphans", + "oscar", + "ostrich", + "otherwise", + "otter", + "ouch", + "ought", + "ounce", + "ourselves", + "oust", + "outbreak", + "oval", + "oven", + "owed", + "owls", + "owner", + "oxidant", + "oxygen", + "oyster", + "ozone", + "pact", + "paddles", + "pager", + "pairing", + "palace", + "pamphlet", + "pancakes", + "paper", + "paradise", + "pastry", + "patio", + "pause", + "pavements", + "pawnshop", + "payment", + "peaches", + "pebbles", + "peculiar", + "pedantic", + "peeled", + "pegs", + "pelican", + "pencil", + "people", + "pepper", + "perfect", + "pests", + "petals", + "phase", + "pheasants", + "phone", + "phrases", + "physics", + "piano", + "picked", + "pierce", + "pigment", + "piloted", + "pimple", + "pinched", + "pioneer", + "pipeline", + "pirate", + "pistons", + "pitched", + "pivot", + "pixels", + "pizza", + "playful", + "pledge", + "pliers", + "plotting", + "plus", + "plywood", + "poaching", + "pockets", + "podcast", + "poetry", + "point", + "poker", + "polar", + "ponies", + "pool", + "popular", + "portents", + "possible", + "potato", + "pouch", + "poverty", + "powder", + "pram", + "present", + "pride", + "problems", + "pruned", + "prying", + "psychic", + "public", + "puck", + "puddle", + "puffin", + "pulp", + "pumpkins", + "punch", + "puppy", + "purged", + "push", + "putty", + "puzzled", + "pylons", + "pyramid", + "python", + "queen", + "quick", + "quote", + "rabbits", + "racetrack", + "radar", + "rafts", + "rage", + "railway", + "raking", + "rally", + "ramped", + "randomly", + "rapid", + "rarest", + "rash", + "rated", + "ravine", + "rays", + "razor", + "react", + "rebel", + "recipe", + "reduce", + "reef", + "refer", + "regular", + "reheat", + "reinvest", + "rejoices", + "rekindle", + "relic", + "remedy", + "renting", + "reorder", + "repent", + "request", + "reruns", + "rest", + "return", + "reunion", + "revamp", + "rewind", + "rhino", + "rhythm", + "ribbon", + "richly", + "ridges", + "rift", + "rigid", + "rims", + "ringing", + "riots", + "ripped", + "rising", + "ritual", + "river", + "roared", + "robot", + "rockets", + "rodent", + "rogue", + "roles", + "romance", + "roomy", + "roped", + "roster", + "rotate", + "rounded", + "rover", + "rowboat", + "royal", + "ruby", + "rudely", + "ruffled", + "rugged", + "ruined", + "ruling", + "rumble", + "runway", + "rural", + "rustled", + "ruthless", + "sabotage", + "sack", + "sadness", + "safety", + "saga", + "sailor", + "sake", + "salads", + "sample", + "sanity", + "sapling", + "sarcasm", + "sash", + "satin", + "saucepan", + "saved", + "sawmill", + "saxophone", + "sayings", + "scamper", + "scenic", + "school", + "science", + "scoop", + "scrub", + "scuba", + "seasons", + "second", + "sedan", + "seeded", + "segments", + "seismic", + "selfish", + "semifinal", + "sensible", + "september", + "sequence", + "serving", + "session", + "setup", + "seventh", + "sewage", + "shackles", + "shelter", + "shipped", + "shocking", + "shrugged", + "shuffled", + "shyness", + "siblings", + "sickness", + "sidekick", + "sieve", + "sifting", + "sighting", + "silk", + "simplest", + "sincerely", + "sipped", + "siren", + "situated", + "sixteen", + "sizes", + "skater", + "skew", + "skirting", + "skulls", + "skydive", + "slackens", + "sleepless", + "slid", + "slower", + "slug", + "smash", + "smelting", + "smidgen", + "smog", + "smuggled", + "snake", + "sneeze", + "sniff", + "snout", + "snug", + "soapy", + "sober", + "soccer", + "soda", + "software", + "soggy", + "soil", + "solved", + "somewhere", + "sonic", + "soothe", + "soprano", + "sorry", + "southern", + "sovereign", + "sowed", + "soya", + "space", + "speedy", + "sphere", + "spiders", + "splendid", + "spout", + "sprig", + "spud", + "spying", + "square", + "stacking", + "stellar", + "stick", + "stockpile", + "strained", + "stunning", + "stylishly", + "subtly", + "succeed", + "suddenly", + "suede", + "suffice", + "sugar", + "suitcase", + "sulking", + "summon", + "sunken", + "superior", + "surfer", + "sushi", + "suture", + "swagger", + "swept", + "swiftly", + "sword", + "swung", + "syllabus", + "symptoms", + "syndrome", + "syringe", + "system", + "taboo", + "tacit", + "tadpoles", + "tagged", + "tail", + "taken", + "talent", + "tamper", + "tanks", + "tapestry", + "tarnished", + "tasked", + "tattoo", + "taunts", + "tavern", + "tawny", + "taxi", + "teardrop", + "technical", + "tedious", + "teeming", + "tell", + "template", + "tender", + "tepid", + "tequila", + "terminal", + "testing", + "tether", + "textbook", + "thaw", + "theatrics", + "thirsty", + "thorn", + "threaten", + "thumbs", + "thwart", + "ticket", + "tidy", + "tiers", + "tiger", + "tilt", + "timber", + "tinted", + "tipsy", + "tirade", + "tissue", + "titans", + "toaster", + "tobacco", + "today", + "toenail", + "toffee", + "together", + "toilet", + "token", + "tolerant", + "tomorrow", + "tonic", + "toolbox", + "topic", + "torch", + "tossed", + "total", + "touchy", + "towel", + "toxic", + "toyed", + "trash", + "trendy", + "tribal", + "trolling", + "truth", + "trying", + "tsunami", + "tubes", + "tucks", + "tudor", + "tuesday", + "tufts", + "tugs", + "tuition", + "tulips", + "tumbling", + "tunnel", + "turnip", + "tusks", + "tutor", + "tuxedo", + "twang", + "tweezers", + "twice", + "twofold", + "tycoon", + "typist", + "tyrant", + "ugly", + "ulcers", + "ultimate", + "umbrella", + "umpire", + "unafraid", + "unbending", + "uncle", + "under", + "uneven", + "unfit", + "ungainly", + "unhappy", + "union", + "unjustly", + "unknown", + "unlikely", + "unmask", + "unnoticed", + "unopened", + "unplugs", + "unquoted", + "unrest", + "unsafe", + "until", + "unusual", + "unveil", + "unwind", + "unzip", + "upbeat", + "upcoming", + "update", + "upgrade", + "uphill", + "upkeep", + "upload", + "upon", + "upper", + "upright", + "upstairs", + "uptight", + "upwards", + "urban", + "urchins", + "urgent", + "usage", + "useful", + "usher", + "using", + "usual", + "utensils", + "utility", + "utmost", + "utopia", + "uttered", + "vacation", + "vague", + "vain", + "value", + "vampire", + "vane", + "vapidly", + "vary", + "vastness", + "vats", + "vaults", + "vector", + "veered", + "vegan", + "vehicle", + "vein", + "velvet", + "venomous", + "verification", + "vessel", + "veteran", + "vexed", + "vials", + "vibrate", + "victim", + "video", + "viewpoint", + "vigilant", + "viking", + "village", + "vinegar", + "violin", + "vipers", + "virtual", + "visited", + "vitals", + "vivid", + "vixen", + "vocal", + "vogue", + "voice", + "volcano", + "vortex", + "voted", + "voucher", + "vowels", + "voyage", + "vulture", + "wade", + "waffle", + "wagtail", + "waist", + "waking", + "wallets", + "wanted", + "warped", + "washing", + "water", + "waveform", + "waxing", + "wayside", + "weavers", + "website", + "wedge", + "weekday", + "weird", + "welders", + "went", + "wept", + "were", + "western", + "wetsuit", + "whale", + "when", + "whipped", + "whole", + "wickets", + "width", + "wield", + "wife", + "wiggle", + "wildly", + "winter", + "wipeout", + "wiring", + "wise", + "withdrawn", + "wives", + "wizard", + "wobbly", + "woes", + "woken", + "wolf", + "womanly", + "wonders", + "woozy", + "worry", + "wounded", + "woven", + "wrap", + "wrist", + "wrong", + "yacht", + "yahoo", + "yanks", + "yard", + "yawning", + "yearbook", + "yellow", + "yesterday", + "yeti", + "yields", + "yodel", + "yoga", + "younger", + "yoyo", + "zapped", + "zeal", + "zebra", + "zero", + "zesty", + "zigzags", + "zinger", + "zippers", + "zodiac", + "zombie", + "zones", + "zoom" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/english_old.h b/src/mnemonics/english_old.h index 179fc45ec..676c05cf6 100644 --- a/src/mnemonics/english_old.h +++ b/src/mnemonics/english_old.h @@ -1,1691 +1,1691 @@ -// Word list originally created as part of the Electrum project, Copyright (C) 2014 Thomas Voegtlin -// -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file english_old.h - * - * \brief Older version of English word list and map. - */ - -#ifndef ENGLISH_OLD_H -#define ENGLISH_OLD_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class EnglishOld: public Base - { - public: - EnglishOld(): Base("EnglishOld", "English (old)", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "like", - "just", - "love", - "know", - "never", - "want", - "time", - "out", - "there", - "make", - "look", - "eye", - "down", - "only", - "think", - "heart", - "back", - "then", - "into", - "about", - "more", - "away", - "still", - "them", - "take", - "thing", - "even", - "through", - "long", - "always", - "world", - "too", - "friend", - "tell", - "try", - "hand", - "thought", - "over", - "here", - "other", - "need", - "smile", - "again", - "much", - "cry", - "been", - "night", - "ever", - "little", - "said", - "end", - "some", - "those", - "around", - "mind", - "people", - "girl", - "leave", - "dream", - "left", - "turn", - "myself", - "give", - "nothing", - "really", - "off", - "before", - "something", - "find", - "walk", - "wish", - "good", - "once", - "place", - "ask", - "stop", - "keep", - "watch", - "seem", - "everything", - "wait", - "got", - "yet", - "made", - "remember", - "start", - "alone", - "run", - "hope", - "maybe", - "believe", - "body", - "hate", - "after", - "close", - "talk", - "stand", - "own", - "each", - "hurt", - "help", - "home", - "god", - "soul", - "new", - "many", - "two", - "inside", - "should", - "true", - "first", - "fear", - "mean", - "better", - "play", - "another", - "gone", - "change", - "use", - "wonder", - "someone", - "hair", - "cold", - "open", - "best", - "any", - "behind", - "happen", - "water", - "dark", - "laugh", - "stay", - "forever", - "name", - "work", - "show", - "sky", - "break", - "came", - "deep", - "door", - "put", - "black", - "together", - "upon", - "happy", - "such", - "great", - "white", - "matter", - "fill", - "past", - "please", - "burn", - "cause", - "enough", - "touch", - "moment", - "soon", - "voice", - "scream", - "anything", - "stare", - "sound", - "red", - "everyone", - "hide", - "kiss", - "truth", - "death", - "beautiful", - "mine", - "blood", - "broken", - "very", - "pass", - "next", - "forget", - "tree", - "wrong", - "air", - "mother", - "understand", - "lip", - "hit", - "wall", - "memory", - "sleep", - "free", - "high", - "realize", - "school", - "might", - "skin", - "sweet", - "perfect", - "blue", - "kill", - "breath", - "dance", - "against", - "fly", - "between", - "grow", - "strong", - "under", - "listen", - "bring", - "sometimes", - "speak", - "pull", - "person", - "become", - "family", - "begin", - "ground", - "real", - "small", - "father", - "sure", - "feet", - "rest", - "young", - "finally", - "land", - "across", - "today", - "different", - "guy", - "line", - "fire", - "reason", - "reach", - "second", - "slowly", - "write", - "eat", - "smell", - "mouth", - "step", - "learn", - "three", - "floor", - "promise", - "breathe", - "darkness", - "push", - "earth", - "guess", - "save", - "song", - "above", - "along", - "both", - "color", - "house", - "almost", - "sorry", - "anymore", - "brother", - "okay", - "dear", - "game", - "fade", - "already", - "apart", - "warm", - "beauty", - "heard", - "notice", - "question", - "shine", - "began", - "piece", - "whole", - "shadow", - "secret", - "street", - "within", - "finger", - "point", - "morning", - "whisper", - "child", - "moon", - "green", - "story", - "glass", - "kid", - "silence", - "since", - "soft", - "yourself", - "empty", - "shall", - "angel", - "answer", - "baby", - "bright", - "dad", - "path", - "worry", - "hour", - "drop", - "follow", - "power", - "war", - "half", - "flow", - "heaven", - "act", - "chance", - "fact", - "least", - "tired", - "children", - "near", - "quite", - "afraid", - "rise", - "sea", - "taste", - "window", - "cover", - "nice", - "trust", - "lot", - "sad", - "cool", - "force", - "peace", - "return", - "blind", - "easy", - "ready", - "roll", - "rose", - "drive", - "held", - "music", - "beneath", - "hang", - "mom", - "paint", - "emotion", - "quiet", - "clear", - "cloud", - "few", - "pretty", - "bird", - "outside", - "paper", - "picture", - "front", - "rock", - "simple", - "anyone", - "meant", - "reality", - "road", - "sense", - "waste", - "bit", - "leaf", - "thank", - "happiness", - "meet", - "men", - "smoke", - "truly", - "decide", - "self", - "age", - "book", - "form", - "alive", - "carry", - "escape", - "damn", - "instead", - "able", - "ice", - "minute", - "throw", - "catch", - "leg", - "ring", - "course", - "goodbye", - "lead", - "poem", - "sick", - "corner", - "desire", - "known", - "problem", - "remind", - "shoulder", - "suppose", - "toward", - "wave", - "drink", - "jump", - "woman", - "pretend", - "sister", - "week", - "human", - "joy", - "crack", - "grey", - "pray", - "surprise", - "dry", - "knee", - "less", - "search", - "bleed", - "caught", - "clean", - "embrace", - "future", - "king", - "son", - "sorrow", - "chest", - "hug", - "remain", - "sat", - "worth", - "blow", - "daddy", - "final", - "parent", - "tight", - "also", - "create", - "lonely", - "safe", - "cross", - "dress", - "evil", - "silent", - "bone", - "fate", - "perhaps", - "anger", - "class", - "scar", - "snow", - "tiny", - "tonight", - "continue", - "control", - "dog", - "edge", - "mirror", - "month", - "suddenly", - "comfort", - "given", - "loud", - "quickly", - "gaze", - "plan", - "rush", - "stone", - "town", - "battle", - "ignore", - "spirit", - "stood", - "stupid", - "yours", - "brown", - "build", - "dust", - "hey", - "kept", - "pay", - "phone", - "twist", - "although", - "ball", - "beyond", - "hidden", - "nose", - "taken", - "fail", - "float", - "pure", - "somehow", - "wash", - "wrap", - "angry", - "cheek", - "creature", - "forgotten", - "heat", - "rip", - "single", - "space", - "special", - "weak", - "whatever", - "yell", - "anyway", - "blame", - "job", - "choose", - "country", - "curse", - "drift", - "echo", - "figure", - "grew", - "laughter", - "neck", - "suffer", - "worse", - "yeah", - "disappear", - "foot", - "forward", - "knife", - "mess", - "somewhere", - "stomach", - "storm", - "beg", - "idea", - "lift", - "offer", - "breeze", - "field", - "five", - "often", - "simply", - "stuck", - "win", - "allow", - "confuse", - "enjoy", - "except", - "flower", - "seek", - "strength", - "calm", - "grin", - "gun", - "heavy", - "hill", - "large", - "ocean", - "shoe", - "sigh", - "straight", - "summer", - "tongue", - "accept", - "crazy", - "everyday", - "exist", - "grass", - "mistake", - "sent", - "shut", - "surround", - "table", - "ache", - "brain", - "destroy", - "heal", - "nature", - "shout", - "sign", - "stain", - "choice", - "doubt", - "glance", - "glow", - "mountain", - "queen", - "stranger", - "throat", - "tomorrow", - "city", - "either", - "fish", - "flame", - "rather", - "shape", - "spin", - "spread", - "ash", - "distance", - "finish", - "image", - "imagine", - "important", - "nobody", - "shatter", - "warmth", - "became", - "feed", - "flesh", - "funny", - "lust", - "shirt", - "trouble", - "yellow", - "attention", - "bare", - "bite", - "money", - "protect", - "amaze", - "appear", - "born", - "choke", - "completely", - "daughter", - "fresh", - "friendship", - "gentle", - "probably", - "six", - "deserve", - "expect", - "grab", - "middle", - "nightmare", - "river", - "thousand", - "weight", - "worst", - "wound", - "barely", - "bottle", - "cream", - "regret", - "relationship", - "stick", - "test", - "crush", - "endless", - "fault", - "itself", - "rule", - "spill", - "art", - "circle", - "join", - "kick", - "mask", - "master", - "passion", - "quick", - "raise", - "smooth", - "unless", - "wander", - "actually", - "broke", - "chair", - "deal", - "favorite", - "gift", - "note", - "number", - "sweat", - "box", - "chill", - "clothes", - "lady", - "mark", - "park", - "poor", - "sadness", - "tie", - "animal", - "belong", - "brush", - "consume", - "dawn", - "forest", - "innocent", - "pen", - "pride", - "stream", - "thick", - "clay", - "complete", - "count", - "draw", - "faith", - "press", - "silver", - "struggle", - "surface", - "taught", - "teach", - "wet", - "bless", - "chase", - "climb", - "enter", - "letter", - "melt", - "metal", - "movie", - "stretch", - "swing", - "vision", - "wife", - "beside", - "crash", - "forgot", - "guide", - "haunt", - "joke", - "knock", - "plant", - "pour", - "prove", - "reveal", - "steal", - "stuff", - "trip", - "wood", - "wrist", - "bother", - "bottom", - "crawl", - "crowd", - "fix", - "forgive", - "frown", - "grace", - "loose", - "lucky", - "party", - "release", - "surely", - "survive", - "teacher", - "gently", - "grip", - "speed", - "suicide", - "travel", - "treat", - "vein", - "written", - "cage", - "chain", - "conversation", - "date", - "enemy", - "however", - "interest", - "million", - "page", - "pink", - "proud", - "sway", - "themselves", - "winter", - "church", - "cruel", - "cup", - "demon", - "experience", - "freedom", - "pair", - "pop", - "purpose", - "respect", - "shoot", - "softly", - "state", - "strange", - "bar", - "birth", - "curl", - "dirt", - "excuse", - "lord", - "lovely", - "monster", - "order", - "pack", - "pants", - "pool", - "scene", - "seven", - "shame", - "slide", - "ugly", - "among", - "blade", - "blonde", - "closet", - "creek", - "deny", - "drug", - "eternity", - "gain", - "grade", - "handle", - "key", - "linger", - "pale", - "prepare", - "swallow", - "swim", - "tremble", - "wheel", - "won", - "cast", - "cigarette", - "claim", - "college", - "direction", - "dirty", - "gather", - "ghost", - "hundred", - "loss", - "lung", - "orange", - "present", - "swear", - "swirl", - "twice", - "wild", - "bitter", - "blanket", - "doctor", - "everywhere", - "flash", - "grown", - "knowledge", - "numb", - "pressure", - "radio", - "repeat", - "ruin", - "spend", - "unknown", - "buy", - "clock", - "devil", - "early", - "false", - "fantasy", - "pound", - "precious", - "refuse", - "sheet", - "teeth", - "welcome", - "add", - "ahead", - "block", - "bury", - "caress", - "content", - "depth", - "despite", - "distant", - "marry", - "purple", - "threw", - "whenever", - "bomb", - "dull", - "easily", - "grasp", - "hospital", - "innocence", - "normal", - "receive", - "reply", - "rhyme", - "shade", - "someday", - "sword", - "toe", - "visit", - "asleep", - "bought", - "center", - "consider", - "flat", - "hero", - "history", - "ink", - "insane", - "muscle", - "mystery", - "pocket", - "reflection", - "shove", - "silently", - "smart", - "soldier", - "spot", - "stress", - "train", - "type", - "view", - "whether", - "bus", - "energy", - "explain", - "holy", - "hunger", - "inch", - "magic", - "mix", - "noise", - "nowhere", - "prayer", - "presence", - "shock", - "snap", - "spider", - "study", - "thunder", - "trail", - "admit", - "agree", - "bag", - "bang", - "bound", - "butterfly", - "cute", - "exactly", - "explode", - "familiar", - "fold", - "further", - "pierce", - "reflect", - "scent", - "selfish", - "sharp", - "sink", - "spring", - "stumble", - "universe", - "weep", - "women", - "wonderful", - "action", - "ancient", - "attempt", - "avoid", - "birthday", - "branch", - "chocolate", - "core", - "depress", - "drunk", - "especially", - "focus", - "fruit", - "honest", - "match", - "palm", - "perfectly", - "pillow", - "pity", - "poison", - "roar", - "shift", - "slightly", - "thump", - "truck", - "tune", - "twenty", - "unable", - "wipe", - "wrote", - "coat", - "constant", - "dinner", - "drove", - "egg", - "eternal", - "flight", - "flood", - "frame", - "freak", - "gasp", - "glad", - "hollow", - "motion", - "peer", - "plastic", - "root", - "screen", - "season", - "sting", - "strike", - "team", - "unlike", - "victim", - "volume", - "warn", - "weird", - "attack", - "await", - "awake", - "built", - "charm", - "crave", - "despair", - "fought", - "grant", - "grief", - "horse", - "limit", - "message", - "ripple", - "sanity", - "scatter", - "serve", - "split", - "string", - "trick", - "annoy", - "blur", - "boat", - "brave", - "clearly", - "cling", - "connect", - "fist", - "forth", - "imagination", - "iron", - "jock", - "judge", - "lesson", - "milk", - "misery", - "nail", - "naked", - "ourselves", - "poet", - "possible", - "princess", - "sail", - "size", - "snake", - "society", - "stroke", - "torture", - "toss", - "trace", - "wise", - "bloom", - "bullet", - "cell", - "check", - "cost", - "darling", - "during", - "footstep", - "fragile", - "hallway", - "hardly", - "horizon", - "invisible", - "journey", - "midnight", - "mud", - "nod", - "pause", - "relax", - "shiver", - "sudden", - "value", - "youth", - "abuse", - "admire", - "blink", - "breast", - "bruise", - "constantly", - "couple", - "creep", - "curve", - "difference", - "dumb", - "emptiness", - "gotta", - "honor", - "plain", - "planet", - "recall", - "rub", - "ship", - "slam", - "soar", - "somebody", - "tightly", - "weather", - "adore", - "approach", - "bond", - "bread", - "burst", - "candle", - "coffee", - "cousin", - "crime", - "desert", - "flutter", - "frozen", - "grand", - "heel", - "hello", - "language", - "level", - "movement", - "pleasure", - "powerful", - "random", - "rhythm", - "settle", - "silly", - "slap", - "sort", - "spoken", - "steel", - "threaten", - "tumble", - "upset", - "aside", - "awkward", - "bee", - "blank", - "board", - "button", - "card", - "carefully", - "complain", - "crap", - "deeply", - "discover", - "drag", - "dread", - "effort", - "entire", - "fairy", - "giant", - "gotten", - "greet", - "illusion", - "jeans", - "leap", - "liquid", - "march", - "mend", - "nervous", - "nine", - "replace", - "rope", - "spine", - "stole", - "terror", - "accident", - "apple", - "balance", - "boom", - "childhood", - "collect", - "demand", - "depression", - "eventually", - "faint", - "glare", - "goal", - "group", - "honey", - "kitchen", - "laid", - "limb", - "machine", - "mere", - "mold", - "murder", - "nerve", - "painful", - "poetry", - "prince", - "rabbit", - "shelter", - "shore", - "shower", - "soothe", - "stair", - "steady", - "sunlight", - "tangle", - "tease", - "treasure", - "uncle", - "begun", - "bliss", - "canvas", - "cheer", - "claw", - "clutch", - "commit", - "crimson", - "crystal", - "delight", - "doll", - "existence", - "express", - "fog", - "football", - "gay", - "goose", - "guard", - "hatred", - "illuminate", - "mass", - "math", - "mourn", - "rich", - "rough", - "skip", - "stir", - "student", - "style", - "support", - "thorn", - "tough", - "yard", - "yearn", - "yesterday", - "advice", - "appreciate", - "autumn", - "bank", - "beam", - "bowl", - "capture", - "carve", - "collapse", - "confusion", - "creation", - "dove", - "feather", - "girlfriend", - "glory", - "government", - "harsh", - "hop", - "inner", - "loser", - "moonlight", - "neighbor", - "neither", - "peach", - "pig", - "praise", - "screw", - "shield", - "shimmer", - "sneak", - "stab", - "subject", - "throughout", - "thrown", - "tower", - "twirl", - "wow", - "army", - "arrive", - "bathroom", - "bump", - "cease", - "cookie", - "couch", - "courage", - "dim", - "guilt", - "howl", - "hum", - "husband", - "insult", - "led", - "lunch", - "mock", - "mostly", - "natural", - "nearly", - "needle", - "nerd", - "peaceful", - "perfection", - "pile", - "price", - "remove", - "roam", - "sanctuary", - "serious", - "shiny", - "shook", - "sob", - "stolen", - "tap", - "vain", - "void", - "warrior", - "wrinkle", - "affection", - "apologize", - "blossom", - "bounce", - "bridge", - "cheap", - "crumble", - "decision", - "descend", - "desperately", - "dig", - "dot", - "flip", - "frighten", - "heartbeat", - "huge", - "lazy", - "lick", - "odd", - "opinion", - "process", - "puzzle", - "quietly", - "retreat", - "score", - "sentence", - "separate", - "situation", - "skill", - "soak", - "square", - "stray", - "taint", - "task", - "tide", - "underneath", - "veil", - "whistle", - "anywhere", - "bedroom", - "bid", - "bloody", - "burden", - "careful", - "compare", - "concern", - "curtain", - "decay", - "defeat", - "describe", - "double", - "dreamer", - "driver", - "dwell", - "evening", - "flare", - "flicker", - "grandma", - "guitar", - "harm", - "horrible", - "hungry", - "indeed", - "lace", - "melody", - "monkey", - "nation", - "object", - "obviously", - "rainbow", - "salt", - "scratch", - "shown", - "shy", - "stage", - "stun", - "third", - "tickle", - "useless", - "weakness", - "worship", - "worthless", - "afternoon", - "beard", - "boyfriend", - "bubble", - "busy", - "certain", - "chin", - "concrete", - "desk", - "diamond", - "doom", - "drawn", - "due", - "felicity", - "freeze", - "frost", - "garden", - "glide", - "harmony", - "hopefully", - "hunt", - "jealous", - "lightning", - "mama", - "mercy", - "peel", - "physical", - "position", - "pulse", - "punch", - "quit", - "rant", - "respond", - "salty", - "sane", - "satisfy", - "savior", - "sheep", - "slept", - "social", - "sport", - "tuck", - "utter", - "valley", - "wolf", - "aim", - "alas", - "alter", - "arrow", - "awaken", - "beaten", - "belief", - "brand", - "ceiling", - "cheese", - "clue", - "confidence", - "connection", - "daily", - "disguise", - "eager", - "erase", - "essence", - "everytime", - "expression", - "fan", - "flag", - "flirt", - "foul", - "fur", - "giggle", - "glorious", - "ignorance", - "law", - "lifeless", - "measure", - "mighty", - "muse", - "north", - "opposite", - "paradise", - "patience", - "patient", - "pencil", - "petal", - "plate", - "ponder", - "possibly", - "practice", - "slice", - "spell", - "stock", - "strife", - "strip", - "suffocate", - "suit", - "tender", - "tool", - "trade", - "velvet", - "verse", - "waist", - "witch", - "aunt", - "bench", - "bold", - "cap", - "certainly", - "click", - "companion", - "creator", - "dart", - "delicate", - "determine", - "dish", - "dragon", - "drama", - "drum", - "dude", - "everybody", - "feast", - "forehead", - "former", - "fright", - "fully", - "gas", - "hook", - "hurl", - "invite", - "juice", - "manage", - "moral", - "possess", - "raw", - "rebel", - "royal", - "scale", - "scary", - "several", - "slight", - "stubborn", - "swell", - "talent", - "tea", - "terrible", - "thread", - "torment", - "trickle", - "usually", - "vast", - "violence", - "weave", - "acid", - "agony", - "ashamed", - "awe", - "belly", - "blend", - "blush", - "character", - "cheat", - "common", - "company", - "coward", - "creak", - "danger", - "deadly", - "defense", - "define", - "depend", - "desperate", - "destination", - "dew", - "duck", - "dusty", - "embarrass", - "engine", - "example", - "explore", - "foe", - "freely", - "frustrate", - "generation", - "glove", - "guilty", - "health", - "hurry", - "idiot", - "impossible", - "inhale", - "jaw", - "kingdom", - "mention", - "mist", - "moan", - "mumble", - "mutter", - "observe", - "ode", - "pathetic", - "pattern", - "pie", - "prefer", - "puff", - "rape", - "rare", - "revenge", - "rude", - "scrape", - "spiral", - "squeeze", - "strain", - "sunset", - "suspend", - "sympathy", - "thigh", - "throne", - "total", - "unseen", - "weapon", - "weary" - }; - set_words(words); - populate_maps(ALLOW_DUPLICATE_PREFIXES | ALLOW_SHORT_WORDS); - } - }; -} - -#endif +// Word list originally created as part of the Electrum project, Copyright (C) 2014 Thomas Voegtlin +// +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file english_old.h + * + * \brief Older version of English word list and map. + */ + +#ifndef ENGLISH_OLD_H +#define ENGLISH_OLD_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class EnglishOld: public Base + { + public: + EnglishOld(): Base("EnglishOld", "English (old)", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "like", + "just", + "love", + "know", + "never", + "want", + "time", + "out", + "there", + "make", + "look", + "eye", + "down", + "only", + "think", + "heart", + "back", + "then", + "into", + "about", + "more", + "away", + "still", + "them", + "take", + "thing", + "even", + "through", + "long", + "always", + "world", + "too", + "friend", + "tell", + "try", + "hand", + "thought", + "over", + "here", + "other", + "need", + "smile", + "again", + "much", + "cry", + "been", + "night", + "ever", + "little", + "said", + "end", + "some", + "those", + "around", + "mind", + "people", + "girl", + "leave", + "dream", + "left", + "turn", + "myself", + "give", + "nothing", + "really", + "off", + "before", + "something", + "find", + "walk", + "wish", + "good", + "once", + "place", + "ask", + "stop", + "keep", + "watch", + "seem", + "everything", + "wait", + "got", + "yet", + "made", + "remember", + "start", + "alone", + "run", + "hope", + "maybe", + "believe", + "body", + "hate", + "after", + "close", + "talk", + "stand", + "own", + "each", + "hurt", + "help", + "home", + "god", + "soul", + "new", + "many", + "two", + "inside", + "should", + "true", + "first", + "fear", + "mean", + "better", + "play", + "another", + "gone", + "change", + "use", + "wonder", + "someone", + "hair", + "cold", + "open", + "best", + "any", + "behind", + "happen", + "water", + "dark", + "laugh", + "stay", + "forever", + "name", + "work", + "show", + "sky", + "break", + "came", + "deep", + "door", + "put", + "black", + "together", + "upon", + "happy", + "such", + "great", + "white", + "matter", + "fill", + "past", + "please", + "burn", + "cause", + "enough", + "touch", + "moment", + "soon", + "voice", + "scream", + "anything", + "stare", + "sound", + "red", + "everyone", + "hide", + "kiss", + "truth", + "death", + "beautiful", + "mine", + "blood", + "broken", + "very", + "pass", + "next", + "forget", + "tree", + "wrong", + "air", + "mother", + "understand", + "lip", + "hit", + "wall", + "memory", + "sleep", + "free", + "high", + "realize", + "school", + "might", + "skin", + "sweet", + "perfect", + "blue", + "kill", + "breath", + "dance", + "against", + "fly", + "between", + "grow", + "strong", + "under", + "listen", + "bring", + "sometimes", + "speak", + "pull", + "person", + "become", + "family", + "begin", + "ground", + "real", + "small", + "father", + "sure", + "feet", + "rest", + "young", + "finally", + "land", + "across", + "today", + "different", + "guy", + "line", + "fire", + "reason", + "reach", + "second", + "slowly", + "write", + "eat", + "smell", + "mouth", + "step", + "learn", + "three", + "floor", + "promise", + "breathe", + "darkness", + "push", + "earth", + "guess", + "save", + "song", + "above", + "along", + "both", + "color", + "house", + "almost", + "sorry", + "anymore", + "brother", + "okay", + "dear", + "game", + "fade", + "already", + "apart", + "warm", + "beauty", + "heard", + "notice", + "question", + "shine", + "began", + "piece", + "whole", + "shadow", + "secret", + "street", + "within", + "finger", + "point", + "morning", + "whisper", + "child", + "moon", + "green", + "story", + "glass", + "kid", + "silence", + "since", + "soft", + "yourself", + "empty", + "shall", + "angel", + "answer", + "baby", + "bright", + "dad", + "path", + "worry", + "hour", + "drop", + "follow", + "power", + "war", + "half", + "flow", + "heaven", + "act", + "chance", + "fact", + "least", + "tired", + "children", + "near", + "quite", + "afraid", + "rise", + "sea", + "taste", + "window", + "cover", + "nice", + "trust", + "lot", + "sad", + "cool", + "force", + "peace", + "return", + "blind", + "easy", + "ready", + "roll", + "rose", + "drive", + "held", + "music", + "beneath", + "hang", + "mom", + "paint", + "emotion", + "quiet", + "clear", + "cloud", + "few", + "pretty", + "bird", + "outside", + "paper", + "picture", + "front", + "rock", + "simple", + "anyone", + "meant", + "reality", + "road", + "sense", + "waste", + "bit", + "leaf", + "thank", + "happiness", + "meet", + "men", + "smoke", + "truly", + "decide", + "self", + "age", + "book", + "form", + "alive", + "carry", + "escape", + "damn", + "instead", + "able", + "ice", + "minute", + "throw", + "catch", + "leg", + "ring", + "course", + "goodbye", + "lead", + "poem", + "sick", + "corner", + "desire", + "known", + "problem", + "remind", + "shoulder", + "suppose", + "toward", + "wave", + "drink", + "jump", + "woman", + "pretend", + "sister", + "week", + "human", + "joy", + "crack", + "grey", + "pray", + "surprise", + "dry", + "knee", + "less", + "search", + "bleed", + "caught", + "clean", + "embrace", + "future", + "king", + "son", + "sorrow", + "chest", + "hug", + "remain", + "sat", + "worth", + "blow", + "daddy", + "final", + "parent", + "tight", + "also", + "create", + "lonely", + "safe", + "cross", + "dress", + "evil", + "silent", + "bone", + "fate", + "perhaps", + "anger", + "class", + "scar", + "snow", + "tiny", + "tonight", + "continue", + "control", + "dog", + "edge", + "mirror", + "month", + "suddenly", + "comfort", + "given", + "loud", + "quickly", + "gaze", + "plan", + "rush", + "stone", + "town", + "battle", + "ignore", + "spirit", + "stood", + "stupid", + "yours", + "brown", + "build", + "dust", + "hey", + "kept", + "pay", + "phone", + "twist", + "although", + "ball", + "beyond", + "hidden", + "nose", + "taken", + "fail", + "float", + "pure", + "somehow", + "wash", + "wrap", + "angry", + "cheek", + "creature", + "forgotten", + "heat", + "rip", + "single", + "space", + "special", + "weak", + "whatever", + "yell", + "anyway", + "blame", + "job", + "choose", + "country", + "curse", + "drift", + "echo", + "figure", + "grew", + "laughter", + "neck", + "suffer", + "worse", + "yeah", + "disappear", + "foot", + "forward", + "knife", + "mess", + "somewhere", + "stomach", + "storm", + "beg", + "idea", + "lift", + "offer", + "breeze", + "field", + "five", + "often", + "simply", + "stuck", + "win", + "allow", + "confuse", + "enjoy", + "except", + "flower", + "seek", + "strength", + "calm", + "grin", + "gun", + "heavy", + "hill", + "large", + "ocean", + "shoe", + "sigh", + "straight", + "summer", + "tongue", + "accept", + "crazy", + "everyday", + "exist", + "grass", + "mistake", + "sent", + "shut", + "surround", + "table", + "ache", + "brain", + "destroy", + "heal", + "nature", + "shout", + "sign", + "stain", + "choice", + "doubt", + "glance", + "glow", + "mountain", + "queen", + "stranger", + "throat", + "tomorrow", + "city", + "either", + "fish", + "flame", + "rather", + "shape", + "spin", + "spread", + "ash", + "distance", + "finish", + "image", + "imagine", + "important", + "nobody", + "shatter", + "warmth", + "became", + "feed", + "flesh", + "funny", + "lust", + "shirt", + "trouble", + "yellow", + "attention", + "bare", + "bite", + "money", + "protect", + "amaze", + "appear", + "born", + "choke", + "completely", + "daughter", + "fresh", + "friendship", + "gentle", + "probably", + "six", + "deserve", + "expect", + "grab", + "middle", + "nightmare", + "river", + "thousand", + "weight", + "worst", + "wound", + "barely", + "bottle", + "cream", + "regret", + "relationship", + "stick", + "test", + "crush", + "endless", + "fault", + "itself", + "rule", + "spill", + "art", + "circle", + "join", + "kick", + "mask", + "master", + "passion", + "quick", + "raise", + "smooth", + "unless", + "wander", + "actually", + "broke", + "chair", + "deal", + "favorite", + "gift", + "note", + "number", + "sweat", + "box", + "chill", + "clothes", + "lady", + "mark", + "park", + "poor", + "sadness", + "tie", + "animal", + "belong", + "brush", + "consume", + "dawn", + "forest", + "innocent", + "pen", + "pride", + "stream", + "thick", + "clay", + "complete", + "count", + "draw", + "faith", + "press", + "silver", + "struggle", + "surface", + "taught", + "teach", + "wet", + "bless", + "chase", + "climb", + "enter", + "letter", + "melt", + "metal", + "movie", + "stretch", + "swing", + "vision", + "wife", + "beside", + "crash", + "forgot", + "guide", + "haunt", + "joke", + "knock", + "plant", + "pour", + "prove", + "reveal", + "steal", + "stuff", + "trip", + "wood", + "wrist", + "bother", + "bottom", + "crawl", + "crowd", + "fix", + "forgive", + "frown", + "grace", + "loose", + "lucky", + "party", + "release", + "surely", + "survive", + "teacher", + "gently", + "grip", + "speed", + "suicide", + "travel", + "treat", + "vein", + "written", + "cage", + "chain", + "conversation", + "date", + "enemy", + "however", + "interest", + "million", + "page", + "pink", + "proud", + "sway", + "themselves", + "winter", + "church", + "cruel", + "cup", + "demon", + "experience", + "freedom", + "pair", + "pop", + "purpose", + "respect", + "shoot", + "softly", + "state", + "strange", + "bar", + "birth", + "curl", + "dirt", + "excuse", + "lord", + "lovely", + "monster", + "order", + "pack", + "pants", + "pool", + "scene", + "seven", + "shame", + "slide", + "ugly", + "among", + "blade", + "blonde", + "closet", + "creek", + "deny", + "drug", + "eternity", + "gain", + "grade", + "handle", + "key", + "linger", + "pale", + "prepare", + "swallow", + "swim", + "tremble", + "wheel", + "won", + "cast", + "cigarette", + "claim", + "college", + "direction", + "dirty", + "gather", + "ghost", + "hundred", + "loss", + "lung", + "orange", + "present", + "swear", + "swirl", + "twice", + "wild", + "bitter", + "blanket", + "doctor", + "everywhere", + "flash", + "grown", + "knowledge", + "numb", + "pressure", + "radio", + "repeat", + "ruin", + "spend", + "unknown", + "buy", + "clock", + "devil", + "early", + "false", + "fantasy", + "pound", + "precious", + "refuse", + "sheet", + "teeth", + "welcome", + "add", + "ahead", + "block", + "bury", + "caress", + "content", + "depth", + "despite", + "distant", + "marry", + "purple", + "threw", + "whenever", + "bomb", + "dull", + "easily", + "grasp", + "hospital", + "innocence", + "normal", + "receive", + "reply", + "rhyme", + "shade", + "someday", + "sword", + "toe", + "visit", + "asleep", + "bought", + "center", + "consider", + "flat", + "hero", + "history", + "ink", + "insane", + "muscle", + "mystery", + "pocket", + "reflection", + "shove", + "silently", + "smart", + "soldier", + "spot", + "stress", + "train", + "type", + "view", + "whether", + "bus", + "energy", + "explain", + "holy", + "hunger", + "inch", + "magic", + "mix", + "noise", + "nowhere", + "prayer", + "presence", + "shock", + "snap", + "spider", + "study", + "thunder", + "trail", + "admit", + "agree", + "bag", + "bang", + "bound", + "butterfly", + "cute", + "exactly", + "explode", + "familiar", + "fold", + "further", + "pierce", + "reflect", + "scent", + "selfish", + "sharp", + "sink", + "spring", + "stumble", + "universe", + "weep", + "women", + "wonderful", + "action", + "ancient", + "attempt", + "avoid", + "birthday", + "branch", + "chocolate", + "core", + "depress", + "drunk", + "especially", + "focus", + "fruit", + "honest", + "match", + "palm", + "perfectly", + "pillow", + "pity", + "poison", + "roar", + "shift", + "slightly", + "thump", + "truck", + "tune", + "twenty", + "unable", + "wipe", + "wrote", + "coat", + "constant", + "dinner", + "drove", + "egg", + "eternal", + "flight", + "flood", + "frame", + "freak", + "gasp", + "glad", + "hollow", + "motion", + "peer", + "plastic", + "root", + "screen", + "season", + "sting", + "strike", + "team", + "unlike", + "victim", + "volume", + "warn", + "weird", + "attack", + "await", + "awake", + "built", + "charm", + "crave", + "despair", + "fought", + "grant", + "grief", + "horse", + "limit", + "message", + "ripple", + "sanity", + "scatter", + "serve", + "split", + "string", + "trick", + "annoy", + "blur", + "boat", + "brave", + "clearly", + "cling", + "connect", + "fist", + "forth", + "imagination", + "iron", + "jock", + "judge", + "lesson", + "milk", + "misery", + "nail", + "naked", + "ourselves", + "poet", + "possible", + "princess", + "sail", + "size", + "snake", + "society", + "stroke", + "torture", + "toss", + "trace", + "wise", + "bloom", + "bullet", + "cell", + "check", + "cost", + "darling", + "during", + "footstep", + "fragile", + "hallway", + "hardly", + "horizon", + "invisible", + "journey", + "midnight", + "mud", + "nod", + "pause", + "relax", + "shiver", + "sudden", + "value", + "youth", + "abuse", + "admire", + "blink", + "breast", + "bruise", + "constantly", + "couple", + "creep", + "curve", + "difference", + "dumb", + "emptiness", + "gotta", + "honor", + "plain", + "planet", + "recall", + "rub", + "ship", + "slam", + "soar", + "somebody", + "tightly", + "weather", + "adore", + "approach", + "bond", + "bread", + "burst", + "candle", + "coffee", + "cousin", + "crime", + "desert", + "flutter", + "frozen", + "grand", + "heel", + "hello", + "language", + "level", + "movement", + "pleasure", + "powerful", + "random", + "rhythm", + "settle", + "silly", + "slap", + "sort", + "spoken", + "steel", + "threaten", + "tumble", + "upset", + "aside", + "awkward", + "bee", + "blank", + "board", + "button", + "card", + "carefully", + "complain", + "crap", + "deeply", + "discover", + "drag", + "dread", + "effort", + "entire", + "fairy", + "giant", + "gotten", + "greet", + "illusion", + "jeans", + "leap", + "liquid", + "march", + "mend", + "nervous", + "nine", + "replace", + "rope", + "spine", + "stole", + "terror", + "accident", + "apple", + "balance", + "boom", + "childhood", + "collect", + "demand", + "depression", + "eventually", + "faint", + "glare", + "goal", + "group", + "honey", + "kitchen", + "laid", + "limb", + "machine", + "mere", + "mold", + "murder", + "nerve", + "painful", + "poetry", + "prince", + "rabbit", + "shelter", + "shore", + "shower", + "soothe", + "stair", + "steady", + "sunlight", + "tangle", + "tease", + "treasure", + "uncle", + "begun", + "bliss", + "canvas", + "cheer", + "claw", + "clutch", + "commit", + "crimson", + "crystal", + "delight", + "doll", + "existence", + "express", + "fog", + "football", + "gay", + "goose", + "guard", + "hatred", + "illuminate", + "mass", + "math", + "mourn", + "rich", + "rough", + "skip", + "stir", + "student", + "style", + "support", + "thorn", + "tough", + "yard", + "yearn", + "yesterday", + "advice", + "appreciate", + "autumn", + "bank", + "beam", + "bowl", + "capture", + "carve", + "collapse", + "confusion", + "creation", + "dove", + "feather", + "girlfriend", + "glory", + "government", + "harsh", + "hop", + "inner", + "loser", + "moonlight", + "neighbor", + "neither", + "peach", + "pig", + "praise", + "screw", + "shield", + "shimmer", + "sneak", + "stab", + "subject", + "throughout", + "thrown", + "tower", + "twirl", + "wow", + "army", + "arrive", + "bathroom", + "bump", + "cease", + "cookie", + "couch", + "courage", + "dim", + "guilt", + "howl", + "hum", + "husband", + "insult", + "led", + "lunch", + "mock", + "mostly", + "natural", + "nearly", + "needle", + "nerd", + "peaceful", + "perfection", + "pile", + "price", + "remove", + "roam", + "sanctuary", + "serious", + "shiny", + "shook", + "sob", + "stolen", + "tap", + "vain", + "void", + "warrior", + "wrinkle", + "affection", + "apologize", + "blossom", + "bounce", + "bridge", + "cheap", + "crumble", + "decision", + "descend", + "desperately", + "dig", + "dot", + "flip", + "frighten", + "heartbeat", + "huge", + "lazy", + "lick", + "odd", + "opinion", + "process", + "puzzle", + "quietly", + "retreat", + "score", + "sentence", + "separate", + "situation", + "skill", + "soak", + "square", + "stray", + "taint", + "task", + "tide", + "underneath", + "veil", + "whistle", + "anywhere", + "bedroom", + "bid", + "bloody", + "burden", + "careful", + "compare", + "concern", + "curtain", + "decay", + "defeat", + "describe", + "double", + "dreamer", + "driver", + "dwell", + "evening", + "flare", + "flicker", + "grandma", + "guitar", + "harm", + "horrible", + "hungry", + "indeed", + "lace", + "melody", + "monkey", + "nation", + "object", + "obviously", + "rainbow", + "salt", + "scratch", + "shown", + "shy", + "stage", + "stun", + "third", + "tickle", + "useless", + "weakness", + "worship", + "worthless", + "afternoon", + "beard", + "boyfriend", + "bubble", + "busy", + "certain", + "chin", + "concrete", + "desk", + "diamond", + "doom", + "drawn", + "due", + "felicity", + "freeze", + "frost", + "garden", + "glide", + "harmony", + "hopefully", + "hunt", + "jealous", + "lightning", + "mama", + "mercy", + "peel", + "physical", + "position", + "pulse", + "punch", + "quit", + "rant", + "respond", + "salty", + "sane", + "satisfy", + "savior", + "sheep", + "slept", + "social", + "sport", + "tuck", + "utter", + "valley", + "wolf", + "aim", + "alas", + "alter", + "arrow", + "awaken", + "beaten", + "belief", + "brand", + "ceiling", + "cheese", + "clue", + "confidence", + "connection", + "daily", + "disguise", + "eager", + "erase", + "essence", + "everytime", + "expression", + "fan", + "flag", + "flirt", + "foul", + "fur", + "giggle", + "glorious", + "ignorance", + "law", + "lifeless", + "measure", + "mighty", + "muse", + "north", + "opposite", + "paradise", + "patience", + "patient", + "pencil", + "petal", + "plate", + "ponder", + "possibly", + "practice", + "slice", + "spell", + "stock", + "strife", + "strip", + "suffocate", + "suit", + "tender", + "tool", + "trade", + "velvet", + "verse", + "waist", + "witch", + "aunt", + "bench", + "bold", + "cap", + "certainly", + "click", + "companion", + "creator", + "dart", + "delicate", + "determine", + "dish", + "dragon", + "drama", + "drum", + "dude", + "everybody", + "feast", + "forehead", + "former", + "fright", + "fully", + "gas", + "hook", + "hurl", + "invite", + "juice", + "manage", + "moral", + "possess", + "raw", + "rebel", + "royal", + "scale", + "scary", + "several", + "slight", + "stubborn", + "swell", + "talent", + "tea", + "terrible", + "thread", + "torment", + "trickle", + "usually", + "vast", + "violence", + "weave", + "acid", + "agony", + "ashamed", + "awe", + "belly", + "blend", + "blush", + "character", + "cheat", + "common", + "company", + "coward", + "creak", + "danger", + "deadly", + "defense", + "define", + "depend", + "desperate", + "destination", + "dew", + "duck", + "dusty", + "embarrass", + "engine", + "example", + "explore", + "foe", + "freely", + "frustrate", + "generation", + "glove", + "guilty", + "health", + "hurry", + "idiot", + "impossible", + "inhale", + "jaw", + "kingdom", + "mention", + "mist", + "moan", + "mumble", + "mutter", + "observe", + "ode", + "pathetic", + "pattern", + "pie", + "prefer", + "puff", + "rape", + "rare", + "revenge", + "rude", + "scrape", + "spiral", + "squeeze", + "strain", + "sunset", + "suspend", + "sympathy", + "thigh", + "throne", + "total", + "unseen", + "weapon", + "weary" + }; + set_words(words); + populate_maps(ALLOW_DUPLICATE_PREFIXES | ALLOW_SHORT_WORDS); + } + }; +} + +#endif diff --git a/src/mnemonics/esperanto.h b/src/mnemonics/esperanto.h index ef63a2235..047145791 100644 --- a/src/mnemonics/esperanto.h +++ b/src/mnemonics/esperanto.h @@ -1,1698 +1,1698 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file esperanto.h - * - * \brief New Esperanto word list and map. - */ - -/* - * Word list authored by: dnaleor, Engelberg, ProkhorZ - * Sources: - * Baza Radikaro Oficiala - * Reta Vortaro (http://www.reta-vortaro.de/revo/) - * Esperanto Panorama - Esperanto-English Dictionary (https://www.esperanto-panorama.net/vortaro/eoen.htm) - * ESPDIC - Paul Denisowski (http://www.denisowski.org/Esperanto/ESPDIC/espdic.txt) - */ - -#ifndef ESPERANTO_H -#define ESPERANTO_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Esperanto: public Base - { - public: - Esperanto(): Base("Esperanto", "Esperanto", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "abako", - "abdiki", - "abelo", - "abituriento", - "ablativo", - "abnorma", - "abonantoj", - "abrikoto", - "absoluta", - "abunda", - "acetono", - "acida", - "adapti", - "adekvata", - "adheri", - "adicii", - "adjektivo", - "administri", - "adolesko", - "adreso", - "adstringa", - "adulto", - "advokato", - "adzo", - "aeroplano", - "aferulo", - "afgana", - "afiksi", - "aflaba", - "aforismo", - "afranki", - "aftozo", - "afusto", - "agavo", - "agento", - "agiti", - "aglo", - "agmaniero", - "agnoski", - "agordo", - "agrabla", - "agtipo", - "agutio", - "aikido", - "ailanto", - "aina", - "ajatolo", - "ajgenvaloro", - "ajlobulbo", - "ajnlitera", - "ajuto", - "ajzi", - "akademio", - "akcepti", - "akeo", - "akiri", - "aklamado", - "akmeo", - "akno", - "akompani", - "akrobato", - "akselo", - "aktiva", - "akurata", - "akvofalo", - "alarmo", - "albumo", - "alcedo", - "aldoni", - "aleo", - "alfabeto", - "algo", - "alhasti", - "aligatoro", - "alkoholo", - "almozo", - "alnomo", - "alojo", - "alpinisto", - "alrigardi", - "alskribi", - "alta", - "alumeto", - "alveni", - "alzaca", - "amaso", - "ambasado", - "amdeklaro", - "amebo", - "amfibio", - "amhara", - "amiko", - "amkanto", - "amletero", - "amnestio", - "amoranto", - "amplekso", - "amrakonto", - "amsterdama", - "amuzi", - "ananaso", - "androido", - "anekdoto", - "anfrakto", - "angulo", - "anheli", - "animo", - "anjono", - "ankro", - "anonci", - "anpriskribo", - "ansero", - "antikva", - "anuitato", - "aorto", - "aparta", - "aperti", - "apika", - "aplikado", - "apneo", - "apogi", - "aprobi", - "apsido", - "apterigo", - "apudesto", - "araneo", - "arbo", - "ardeco", - "aresti", - "argilo", - "aristokrato", - "arko", - "arlekeno", - "armi", - "arniko", - "aromo", - "arpio", - "arsenalo", - "artisto", - "aruba", - "arvorto", - "asaio", - "asbesto", - "ascendi", - "asekuri", - "asfalto", - "asisti", - "askalono", - "asocio", - "aspekti", - "astro", - "asulo", - "atakonto", - "atendi", - "atingi", - "atleto", - "atmosfero", - "atomo", - "atropino", - "atuto", - "avataro", - "aventuro", - "aviadilo", - "avokado", - "azaleo", - "azbuko", - "azenino", - "azilpetanto", - "azoto", - "azteka", - "babili", - "bacilo", - "badmintono", - "bagatelo", - "bahama", - "bajoneto", - "baki", - "balai", - "bambuo", - "bani", - "baobabo", - "bapti", - "baro", - "bastono", - "batilo", - "bavara", - "bazalto", - "beata", - "bebofono", - "bedo", - "begonio", - "behaviorismo", - "bejlo", - "bekero", - "belarto", - "bemolo", - "benko", - "bereto", - "besto", - "betulo", - "bevelo", - "bezoni", - "biaso", - "biblioteko", - "biciklo", - "bidaro", - "bieno", - "bifsteko", - "bigamiulo", - "bijekcio", - "bikino", - "bildo", - "bimetalismo", - "bindi", - "biografio", - "birdo", - "biskvito", - "bitlibro", - "bivako", - "bizara", - "bjalistoka", - "blanka", - "bleki", - "blinda", - "blovi", - "blua", - "boato", - "bobsledo", - "bocvanano", - "bodisatvo", - "bofratino", - "bogefratoj", - "bohema", - "boji", - "bokalo", - "boli", - "bombono", - "bona", - "bopatrino", - "bordo", - "bosko", - "botelo", - "bovido", - "brakpleno", - "bretaro", - "brikmuro", - "broso", - "brulema", - "bubalo", - "buctrapi", - "budo", - "bufedo", - "bugio", - "bujabeso", - "buklo", - "buldozo", - "bumerango", - "bunta", - "burokrataro", - "busbileto", - "butero", - "buzuko", - "caro", - "cebo", - "ceceo", - "cedro", - "cefalo", - "cejana", - "cekumo", - "celebri", - "cemento", - "cent", - "cepo", - "certa", - "cetera", - "cezio", - "ciano", - "cibeto", - "cico", - "cidro", - "cifero", - "cigaredo", - "ciklo", - "cilindro", - "cimbalo", - "cinamo", - "cipreso", - "cirkonstanco", - "cisterno", - "citrono", - "ciumi", - "civilizado", - "colo", - "congo", - "cunamo", - "cvana", - "dabi", - "daco", - "dadaismo", - "dafodilo", - "dago", - "daimio", - "dajmono", - "daktilo", - "dalio", - "damo", - "danki", - "darmo", - "datumoj", - "dazipo", - "deadmoni", - "debeto", - "decidi", - "dedukti", - "deerigi", - "defendi", - "degeli", - "dehaki", - "deirpunkto", - "deklaracio", - "delikata", - "demandi", - "dento", - "dependi", - "derivi", - "desegni", - "detrui", - "devi", - "deziri", - "dialogo", - "dicentro", - "didaktika", - "dieto", - "diferenci", - "digesti", - "diino", - "dikfingro", - "diligenta", - "dimensio", - "dinamo", - "diodo", - "diplomo", - "direkte", - "diskuti", - "diurno", - "diversa", - "dizajno", - "dobrogitaro", - "docento", - "dogano", - "dojeno", - "doktoro", - "dolori", - "domego", - "donaci", - "dopado", - "dormi", - "dosierujo", - "dotita", - "dozeno", - "drato", - "dresi", - "drinki", - "droni", - "druido", - "duaranga", - "dubi", - "ducent", - "dudek", - "duelo", - "dufoje", - "dugongo", - "duhufa", - "duilo", - "dujare", - "dukato", - "duloka", - "dumtempe", - "dungi", - "duobla", - "dupiedulo", - "dura", - "dusenca", - "dutaga", - "duuma", - "duvalvuloj", - "duzo", - "ebena", - "eblecoj", - "ebono", - "ebria", - "eburo", - "ecaro", - "ecigi", - "ecoj", - "edelvejso", - "editoro", - "edro", - "eduki", - "edzino", - "efektiva", - "efiki", - "efloreski", - "egala", - "egeco", - "egiptologo", - "eglefino", - "egoista", - "egreto", - "ejakuli", - "ejlo", - "ekarto", - "ekbruligi", - "ekceli", - "ekde", - "ekesti", - "ekfirmao", - "ekgliti", - "ekhavi", - "ekipi", - "ekkapti", - "eklezio", - "ekmalsati", - "ekonomio", - "ekpluvi", - "ekrano", - "ekster", - "ektiri", - "ekumeno", - "ekvilibro", - "ekzemplo", - "elasta", - "elbalai", - "elcento", - "eldoni", - "elektro", - "elfari", - "elgliti", - "elhaki", - "elipso", - "elkovi", - "ellasi", - "elmeti", - "elnutri", - "elokventa", - "elparoli", - "elrevigi", - "elstari", - "elteni", - "eluzita", - "elvoki", - "elzasa", - "emajlo", - "embaraso", - "emerito", - "emfazo", - "eminenta", - "emocio", - "empiria", - "emulsio", - "enarkivigi", - "enboteligi", - "enciklopedio", - "endorfino", - "energio", - "enfermi", - "engluti", - "enhavo", - "enigmo", - "enjekcio", - "enketi", - "enlanda", - "enmeti", - "enorma", - "enplanti", - "enradiki", - "enspezo", - "entrepreni", - "enui", - "envolvi", - "enzimo", - "eono", - "eosto", - "epitafo", - "epoko", - "epriskribebla", - "epsilono", - "erari", - "erbio", - "erco", - "erekti", - "ergonomia", - "erikejo", - "ermito", - "erotika", - "erpilo", - "erupcio", - "esameno", - "escepti", - "esenco", - "eskapi", - "esotera", - "esperi", - "estonto", - "etapo", - "etendi", - "etfingro", - "etikedo", - "etlitero", - "etmakleristo", - "etnika", - "etoso", - "etradio", - "etskala", - "etullernejo", - "evakui", - "evento", - "eviti", - "evolui", - "ezoko", - "fabriko", - "facila", - "fadeno", - "fagoto", - "fajro", - "fakto", - "fali", - "familio", - "fanatiko", - "farbo", - "fasko", - "fatala", - "favora", - "fazeolo", - "febro", - "federacio", - "feino", - "fekunda", - "felo", - "femuro", - "fenestro", - "fermi", - "festi", - "fetora", - "fezo", - "fiasko", - "fibro", - "fidela", - "fiera", - "fifama", - "figuro", - "fiherbo", - "fiinsekto", - "fiksa", - "filmo", - "fimensa", - "finalo", - "fiolo", - "fiparoli", - "firmao", - "fisko", - "fitingo", - "fiuzanto", - "fivorto", - "fiziko", - "fjordo", - "flago", - "flegi", - "flirti", - "floro", - "flugi", - "fobio", - "foceno", - "foirejo", - "fojfoje", - "fokuso", - "folio", - "fomenti", - "fonto", - "formulo", - "fosforo", - "fotografi", - "fratino", - "fremda", - "friti", - "frosto", - "frua", - "ftizo", - "fuelo", - "fugo", - "fuksia", - "fulmilo", - "fumanto", - "fundamento", - "fuorto", - "furioza", - "fusilo", - "futbalo", - "fuzio", - "gabardino", - "gado", - "gaela", - "gafo", - "gagato", - "gaja", - "gaki", - "galanta", - "gamao", - "ganto", - "gapulo", - "gardi", - "gasto", - "gavio", - "gazeto", - "geamantoj", - "gebani", - "geedzeco", - "gefratoj", - "geheno", - "gejsero", - "geko", - "gelateno", - "gemisto", - "geniulo", - "geografio", - "gepardo", - "geranio", - "gestolingvo", - "geto", - "geumo", - "gibono", - "giganta", - "gildo", - "gimnastiko", - "ginekologo", - "gipsi", - "girlando", - "gistfungo", - "gitaro", - "glazuro", - "glebo", - "gliti", - "globo", - "gluti", - "gnafalio", - "gnejso", - "gnomo", - "gnuo", - "gobio", - "godetio", - "goeleto", - "gojo", - "golfludejo", - "gombo", - "gondolo", - "gorilo", - "gospelo", - "gotika", - "granda", - "greno", - "griza", - "groto", - "grupo", - "guano", - "gubernatoro", - "gudrotuko", - "gufo", - "gujavo", - "guldeno", - "gumi", - "gupio", - "guruo", - "gusto", - "guto", - "guvernistino", - "gvardio", - "gverilo", - "gvidanto", - "habitato", - "hadito", - "hafnio", - "hagiografio", - "haitiano", - "hajlo", - "hakbloko", - "halti", - "hamstro", - "hangaro", - "hapalo", - "haro", - "hasta", - "hati", - "havebla", - "hazardo", - "hebrea", - "hedero", - "hegemonio", - "hejmo", - "hektaro", - "helpi", - "hemisfero", - "heni", - "hepato", - "herbo", - "hesa", - "heterogena", - "heziti", - "hiacinto", - "hibrida", - "hidrogeno", - "hieroglifo", - "higieno", - "hihii", - "hilumo", - "himno", - "hindino", - "hiperteksto", - "hirundo", - "historio", - "hobio", - "hojli", - "hokeo", - "hologramo", - "homido", - "honesta", - "hopi", - "horizonto", - "hospitalo", - "hotelo", - "huadi", - "hubo", - "hufumo", - "hugenoto", - "hukero", - "huligano", - "humana", - "hundo", - "huoj", - "hupilo", - "hurai", - "husaro", - "hutuo", - "huzo", - "iafoje", - "iagrade", - "iamaniere", - "iarelate", - "iaspeca", - "ibekso", - "ibiso", - "idaro", - "ideala", - "idiomo", - "idolo", - "iele", - "igluo", - "ignori", - "iguamo", - "igvano", - "ikono", - "iksodo", - "ikto", - "iliaflanke", - "ilkomputilo", - "ilobreto", - "ilremedo", - "ilumini", - "imagi", - "imitado", - "imperio", - "imuna", - "incidento", - "industrio", - "inerta", - "infano", - "ingenra", - "inhali", - "iniciati", - "injekti", - "inklino", - "inokuli", - "insekto", - "inteligenta", - "inundi", - "inviti", - "ioma", - "ionosfero", - "iperito", - "ipomeo", - "irana", - "irejo", - "irigacio", - "ironio", - "isato", - "islamo", - "istempo", - "itinero", - "itrio", - "iuloke", - "iumaniere", - "iutempe", - "izolita", - "jado", - "jaguaro", - "jakto", - "jama", - "januaro", - "japano", - "jarringo", - "jazo", - "jenoj", - "jesulo", - "jetavio", - "jezuito", - "jodli", - "joviala", - "juano", - "jubileo", - "judismo", - "jufto", - "juki", - "julio", - "juneca", - "jupo", - "juristo", - "juste", - "juvelo", - "kabineto", - "kadrato", - "kafo", - "kahelo", - "kajako", - "kakao", - "kalkuli", - "kampo", - "kanti", - "kapitalo", - "karaktero", - "kaserolo", - "katapulto", - "kaverna", - "kazino", - "kebabo", - "kefiro", - "keglo", - "kejlo", - "kekso", - "kelka", - "kemio", - "kerno", - "kesto", - "kiamaniere", - "kibuco", - "kidnapi", - "kielo", - "kikero", - "kilogramo", - "kimono", - "kinejo", - "kiosko", - "kirurgo", - "kisi", - "kitelo", - "kivio", - "klavaro", - "klerulo", - "klini", - "klopodi", - "klubo", - "knabo", - "knedi", - "koalo", - "kobalto", - "kodigi", - "kofro", - "kohera", - "koincidi", - "kojoto", - "kokoso", - "koloro", - "komenci", - "kontrakto", - "kopio", - "korekte", - "kosti", - "kotono", - "kovri", - "krajono", - "kredi", - "krii", - "krom", - "kruco", - "ksantino", - "ksenono", - "ksilofono", - "ksosa", - "kubuto", - "kudri", - "kuglo", - "kuiri", - "kuko", - "kulero", - "kumuluso", - "kuneco", - "kupro", - "kuri", - "kuseno", - "kutimo", - "kuvo", - "kuzino", - "kvalito", - "kverko", - "kvin", - "kvoto", - "labori", - "laculo", - "ladbotelo", - "lafo", - "laguno", - "laikino", - "laktobovino", - "lampolumo", - "landkarto", - "laosa", - "lapono", - "larmoguto", - "lastjare", - "latitudo", - "lavejo", - "lazanjo", - "leciono", - "ledosako", - "leganto", - "lekcio", - "lemura", - "lentuga", - "leopardo", - "leporo", - "lerni", - "lesivo", - "letero", - "levilo", - "lezi", - "liano", - "libera", - "liceo", - "lieno", - "lifto", - "ligilo", - "likvoro", - "lila", - "limono", - "lingvo", - "lipo", - "lirika", - "listo", - "literatura", - "liveri", - "lobio", - "logika", - "lojala", - "lokalo", - "longa", - "lordo", - "lotado", - "loza", - "luanto", - "lubriki", - "lucida", - "ludema", - "luigi", - "lukso", - "luli", - "lumbilda", - "lunde", - "lupago", - "lustro", - "lutilo", - "luzerno", - "maato", - "maceri", - "madono", - "mafiano", - "magazeno", - "mahometano", - "maizo", - "majstro", - "maketo", - "malgranda", - "mamo", - "mandareno", - "maorio", - "mapigi", - "marini", - "masko", - "mateno", - "mazuto", - "meandro", - "meblo", - "mecenato", - "medialo", - "mefito", - "megafono", - "mejlo", - "mekanika", - "melodia", - "membro", - "mendi", - "mergi", - "mespilo", - "metoda", - "mevo", - "mezuri", - "miaflanke", - "micelio", - "mielo", - "migdalo", - "mikrofilmo", - "militi", - "mimiko", - "mineralo", - "miopa", - "miri", - "mistera", - "mitralo", - "mizeri", - "mjelo", - "mnemoniko", - "mobilizi", - "mocio", - "moderna", - "mohajro", - "mokadi", - "molaro", - "momento", - "monero", - "mopso", - "mordi", - "moskito", - "motoro", - "movimento", - "mozaiko", - "mueli", - "mukozo", - "muldi", - "mumio", - "munti", - "muro", - "muskolo", - "mutacio", - "muzikisto", - "nabo", - "nacio", - "nadlo", - "nafto", - "naiva", - "najbaro", - "nanometro", - "napo", - "narciso", - "naski", - "naturo", - "navigi", - "naztruo", - "neatendite", - "nebulo", - "necesa", - "nedankinde", - "neebla", - "nefari", - "negoco", - "nehavi", - "neimagebla", - "nektaro", - "nelonga", - "nematura", - "nenia", - "neordinara", - "nepra", - "nervuro", - "nesto", - "nete", - "neulo", - "nevino", - "nifo", - "nigra", - "nihilisto", - "nikotino", - "nilono", - "nimfeo", - "nitrogeno", - "nivelo", - "nobla", - "nocio", - "nodozo", - "nokto", - "nomkarto", - "norda", - "nostalgio", - "notbloko", - "novico", - "nuanco", - "nuboza", - "nuda", - "nugato", - "nuklea", - "nuligi", - "numero", - "nuntempe", - "nupto", - "nura", - "nutri", - "oazo", - "obei", - "objekto", - "oblikva", - "obolo", - "observi", - "obtuza", - "obuso", - "oceano", - "odekolono", - "odori", - "oferti", - "oficiala", - "ofsajdo", - "ofte", - "ogivo", - "ogro", - "ojstredoj", - "okaze", - "okcidenta", - "okro", - "oksido", - "oktobro", - "okulo", - "oldulo", - "oleo", - "olivo", - "omaro", - "ombro", - "omego", - "omikrono", - "omleto", - "omnibuso", - "onagro", - "ondo", - "oneco", - "onidire", - "onklino", - "onlajna", - "onomatopeo", - "ontologio", - "opaka", - "operacii", - "opinii", - "oportuna", - "opresi", - "optimisto", - "oratoro", - "orbito", - "ordinara", - "orelo", - "orfino", - "organizi", - "orienta", - "orkestro", - "orlo", - "orminejo", - "ornami", - "ortangulo", - "orumi", - "oscedi", - "osmozo", - "ostocerbo", - "ovalo", - "ovingo", - "ovoblanko", - "ovri", - "ovulado", - "ozono", - "pacama", - "padeli", - "pafilo", - "pagigi", - "pajlo", - "paketo", - "palaco", - "pampelmo", - "pantalono", - "papero", - "paroli", - "pasejo", - "patro", - "pavimo", - "peco", - "pedalo", - "peklita", - "pelikano", - "pensiono", - "peplomo", - "pesilo", - "petanto", - "pezoforto", - "piano", - "picejo", - "piede", - "pigmento", - "pikema", - "pilkoludo", - "pimento", - "pinglo", - "pioniro", - "pipromento", - "pirato", - "pistolo", - "pitoreska", - "piulo", - "pivoti", - "pizango", - "planko", - "plektita", - "plibonigi", - "ploradi", - "plurlingva", - "pobo", - "podio", - "poeto", - "pogranda", - "pohora", - "pokalo", - "politekniko", - "pomarbo", - "ponevosto", - "populara", - "porcelana", - "postkompreno", - "poteto", - "poviga", - "pozitiva", - "prapatroj", - "precize", - "pridemandi", - "probable", - "pruntanto", - "psalmo", - "psikologio", - "psoriazo", - "pterido", - "publiko", - "pudro", - "pufo", - "pugnobato", - "pulovero", - "pumpi", - "punkto", - "pupo", - "pureo", - "puso", - "putrema", - "puzlo", - "rabate", - "racionala", - "radiko", - "rafinado", - "raguo", - "rajto", - "rakonti", - "ralio", - "rampi", - "rando", - "rapida", - "rastruma", - "ratifiki", - "raviolo", - "razeno", - "reakcio", - "rebildo", - "recepto", - "redakti", - "reenigi", - "reformi", - "regiono", - "rehavi", - "reinspekti", - "rejesi", - "reklamo", - "relativa", - "rememori", - "renkonti", - "reorganizado", - "reprezenti", - "respondi", - "retumilo", - "reuzebla", - "revidi", - "rezulti", - "rialo", - "ribeli", - "ricevi", - "ridiga", - "rifuginto", - "rigardi", - "rikolti", - "rilati", - "rimarki", - "rinocero", - "ripozi", - "riski", - "ritmo", - "rivero", - "rizokampo", - "roboto", - "rododendro", - "rojo", - "rokmuziko", - "rolvorto", - "romantika", - "ronroni", - "rosino", - "rotondo", - "rovero", - "rozeto", - "rubando", - "rudimenta", - "rufa", - "rugbeo", - "ruino", - "ruleto", - "rumoro", - "runo", - "rupio", - "rura", - "rustimuna", - "ruzulo", - "sabato", - "sadismo", - "safario", - "sagaca", - "sakfluto", - "salti", - "samtage", - "sandalo", - "sapejo", - "sarongo", - "satelito", - "savano", - "sbiro", - "sciado", - "seanco", - "sebo", - "sedativo", - "segligno", - "sekretario", - "selektiva", - "semajno", - "senpeza", - "separeo", - "servilo", - "sesangulo", - "setli", - "seurigi", - "severa", - "sezono", - "sfagno", - "sfero", - "sfinkso", - "siatempe", - "siblado", - "sidejo", - "siesto", - "sifono", - "signalo", - "siklo", - "silenti", - "simpla", - "sinjoro", - "siropo", - "sistemo", - "situacio", - "siverto", - "sizifa", - "skatolo", - "skemo", - "skianto", - "sklavo", - "skorpio", - "skribisto", - "skulpti", - "skvamo", - "slango", - "sledeto", - "sliparo", - "smeraldo", - "smirgi", - "smokingo", - "smuto", - "snoba", - "snufegi", - "sobra", - "sociano", - "sodakvo", - "sofo", - "soifi", - "sojlo", - "soklo", - "soldato", - "somero", - "sonilo", - "sopiri", - "sorto", - "soulo", - "soveto", - "sparkado", - "speciala", - "spiri", - "splito", - "sporto", - "sprita", - "spuro", - "stabila", - "stelfiguro", - "stimulo", - "stomako", - "strato", - "studanto", - "subgrupo", - "suden", - "suferanta", - "sugesti", - "suito", - "sukero", - "sulko", - "sume", - "sunlumo", - "super", - "surskribeto", - "suspekti", - "suturo", - "svati", - "svenfali", - "svingi", - "svopo", - "tabako", - "taglumo", - "tajloro", - "taksimetro", - "talento", - "tamen", - "tanko", - "taoismo", - "tapioko", - "tarifo", - "tasko", - "tatui", - "taverno", - "teatro", - "tedlaboro", - "tegmento", - "tehoro", - "teknika", - "telefono", - "tempo", - "tenisejo", - "teorie", - "teraso", - "testudo", - "tetablo", - "teujo", - "tezo", - "tialo", - "tibio", - "tielnomata", - "tifono", - "tigro", - "tikli", - "timida", - "tinkturo", - "tiom", - "tiparo", - "tirkesto", - "titolo", - "tiutempe", - "tizano", - "tobogano", - "tofeo", - "togo", - "toksa", - "tolerema", - "tombolo", - "tondri", - "topografio", - "tordeti", - "tosti", - "totalo", - "traduko", - "tredi", - "triangulo", - "tropika", - "trumpeto", - "tualeto", - "tubisto", - "tufgrebo", - "tuja", - "tukano", - "tulipo", - "tumulto", - "tunelo", - "turisto", - "tusi", - "tutmonda", - "tvisto", - "udono", - "uesto", - "ukazo", - "ukelelo", - "ulcero", - "ulmo", - "ultimato", - "ululi", - "umbiliko", - "unco", - "ungego", - "uniformo", - "unkti", - "unukolora", - "uragano", - "urbano", - "uretro", - "urino", - "ursido", - "uskleco", - "usonigi", - "utero", - "utila", - "utopia", - "uverturo", - "uzadi", - "uzeblo", - "uzino", - "uzkutimo", - "uzofini", - "uzurpi", - "uzvaloro", - "vadejo", - "vafleto", - "vagono", - "vahabismo", - "vajco", - "vakcino", - "valoro", - "vampiro", - "vangharoj", - "vaporo", - "varma", - "vasta", - "vato", - "vazaro", - "veaspekta", - "vedismo", - "vegetalo", - "vehiklo", - "vejno", - "vekita", - "velstango", - "vemieno", - "vendi", - "vepro", - "verando", - "vespero", - "veturi", - "veziko", - "viando", - "vibri", - "vico", - "videbla", - "vifio", - "vigla", - "viktimo", - "vila", - "vimeno", - "vintro", - "violo", - "vippuno", - "virtuala", - "viskoza", - "vitro", - "viveca", - "viziti", - "vobli", - "vodko", - "vojeto", - "vokegi", - "volbo", - "vomema", - "vono", - "vortaro", - "vosto", - "voti", - "vrako", - "vringi", - "vualo", - "vulkano", - "vundo", - "vuvuzelo", - "zamenhofa", - "zapi", - "zebro", - "zefiro", - "zeloto", - "zenismo", - "zeolito", - "zepelino", - "zeto", - "zigzagi", - "zinko", - "zipo", - "zirkonio", - "zodiako", - "zoeto", - "zombio", - "zono", - "zoologio", - "zorgi", - "zukino", - "zumilo", - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file esperanto.h + * + * \brief New Esperanto word list and map. + */ + +/* + * Word list authored by: dnaleor, Engelberg, ProkhorZ + * Sources: + * Baza Radikaro Oficiala + * Reta Vortaro (http://www.reta-vortaro.de/revo/) + * Esperanto Panorama - Esperanto-English Dictionary (https://www.esperanto-panorama.net/vortaro/eoen.htm) + * ESPDIC - Paul Denisowski (http://www.denisowski.org/Esperanto/ESPDIC/espdic.txt) + */ + +#ifndef ESPERANTO_H +#define ESPERANTO_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Esperanto: public Base + { + public: + Esperanto(): Base("Esperanto", "Esperanto", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "abako", + "abdiki", + "abelo", + "abituriento", + "ablativo", + "abnorma", + "abonantoj", + "abrikoto", + "absoluta", + "abunda", + "acetono", + "acida", + "adapti", + "adekvata", + "adheri", + "adicii", + "adjektivo", + "administri", + "adolesko", + "adreso", + "adstringa", + "adulto", + "advokato", + "adzo", + "aeroplano", + "aferulo", + "afgana", + "afiksi", + "aflaba", + "aforismo", + "afranki", + "aftozo", + "afusto", + "agavo", + "agento", + "agiti", + "aglo", + "agmaniero", + "agnoski", + "agordo", + "agrabla", + "agtipo", + "agutio", + "aikido", + "ailanto", + "aina", + "ajatolo", + "ajgenvaloro", + "ajlobulbo", + "ajnlitera", + "ajuto", + "ajzi", + "akademio", + "akcepti", + "akeo", + "akiri", + "aklamado", + "akmeo", + "akno", + "akompani", + "akrobato", + "akselo", + "aktiva", + "akurata", + "akvofalo", + "alarmo", + "albumo", + "alcedo", + "aldoni", + "aleo", + "alfabeto", + "algo", + "alhasti", + "aligatoro", + "alkoholo", + "almozo", + "alnomo", + "alojo", + "alpinisto", + "alrigardi", + "alskribi", + "alta", + "alumeto", + "alveni", + "alzaca", + "amaso", + "ambasado", + "amdeklaro", + "amebo", + "amfibio", + "amhara", + "amiko", + "amkanto", + "amletero", + "amnestio", + "amoranto", + "amplekso", + "amrakonto", + "amsterdama", + "amuzi", + "ananaso", + "androido", + "anekdoto", + "anfrakto", + "angulo", + "anheli", + "animo", + "anjono", + "ankro", + "anonci", + "anpriskribo", + "ansero", + "antikva", + "anuitato", + "aorto", + "aparta", + "aperti", + "apika", + "aplikado", + "apneo", + "apogi", + "aprobi", + "apsido", + "apterigo", + "apudesto", + "araneo", + "arbo", + "ardeco", + "aresti", + "argilo", + "aristokrato", + "arko", + "arlekeno", + "armi", + "arniko", + "aromo", + "arpio", + "arsenalo", + "artisto", + "aruba", + "arvorto", + "asaio", + "asbesto", + "ascendi", + "asekuri", + "asfalto", + "asisti", + "askalono", + "asocio", + "aspekti", + "astro", + "asulo", + "atakonto", + "atendi", + "atingi", + "atleto", + "atmosfero", + "atomo", + "atropino", + "atuto", + "avataro", + "aventuro", + "aviadilo", + "avokado", + "azaleo", + "azbuko", + "azenino", + "azilpetanto", + "azoto", + "azteka", + "babili", + "bacilo", + "badmintono", + "bagatelo", + "bahama", + "bajoneto", + "baki", + "balai", + "bambuo", + "bani", + "baobabo", + "bapti", + "baro", + "bastono", + "batilo", + "bavara", + "bazalto", + "beata", + "bebofono", + "bedo", + "begonio", + "behaviorismo", + "bejlo", + "bekero", + "belarto", + "bemolo", + "benko", + "bereto", + "besto", + "betulo", + "bevelo", + "bezoni", + "biaso", + "biblioteko", + "biciklo", + "bidaro", + "bieno", + "bifsteko", + "bigamiulo", + "bijekcio", + "bikino", + "bildo", + "bimetalismo", + "bindi", + "biografio", + "birdo", + "biskvito", + "bitlibro", + "bivako", + "bizara", + "bjalistoka", + "blanka", + "bleki", + "blinda", + "blovi", + "blua", + "boato", + "bobsledo", + "bocvanano", + "bodisatvo", + "bofratino", + "bogefratoj", + "bohema", + "boji", + "bokalo", + "boli", + "bombono", + "bona", + "bopatrino", + "bordo", + "bosko", + "botelo", + "bovido", + "brakpleno", + "bretaro", + "brikmuro", + "broso", + "brulema", + "bubalo", + "buctrapi", + "budo", + "bufedo", + "bugio", + "bujabeso", + "buklo", + "buldozo", + "bumerango", + "bunta", + "burokrataro", + "busbileto", + "butero", + "buzuko", + "caro", + "cebo", + "ceceo", + "cedro", + "cefalo", + "cejana", + "cekumo", + "celebri", + "cemento", + "cent", + "cepo", + "certa", + "cetera", + "cezio", + "ciano", + "cibeto", + "cico", + "cidro", + "cifero", + "cigaredo", + "ciklo", + "cilindro", + "cimbalo", + "cinamo", + "cipreso", + "cirkonstanco", + "cisterno", + "citrono", + "ciumi", + "civilizado", + "colo", + "congo", + "cunamo", + "cvana", + "dabi", + "daco", + "dadaismo", + "dafodilo", + "dago", + "daimio", + "dajmono", + "daktilo", + "dalio", + "damo", + "danki", + "darmo", + "datumoj", + "dazipo", + "deadmoni", + "debeto", + "decidi", + "dedukti", + "deerigi", + "defendi", + "degeli", + "dehaki", + "deirpunkto", + "deklaracio", + "delikata", + "demandi", + "dento", + "dependi", + "derivi", + "desegni", + "detrui", + "devi", + "deziri", + "dialogo", + "dicentro", + "didaktika", + "dieto", + "diferenci", + "digesti", + "diino", + "dikfingro", + "diligenta", + "dimensio", + "dinamo", + "diodo", + "diplomo", + "direkte", + "diskuti", + "diurno", + "diversa", + "dizajno", + "dobrogitaro", + "docento", + "dogano", + "dojeno", + "doktoro", + "dolori", + "domego", + "donaci", + "dopado", + "dormi", + "dosierujo", + "dotita", + "dozeno", + "drato", + "dresi", + "drinki", + "droni", + "druido", + "duaranga", + "dubi", + "ducent", + "dudek", + "duelo", + "dufoje", + "dugongo", + "duhufa", + "duilo", + "dujare", + "dukato", + "duloka", + "dumtempe", + "dungi", + "duobla", + "dupiedulo", + "dura", + "dusenca", + "dutaga", + "duuma", + "duvalvuloj", + "duzo", + "ebena", + "eblecoj", + "ebono", + "ebria", + "eburo", + "ecaro", + "ecigi", + "ecoj", + "edelvejso", + "editoro", + "edro", + "eduki", + "edzino", + "efektiva", + "efiki", + "efloreski", + "egala", + "egeco", + "egiptologo", + "eglefino", + "egoista", + "egreto", + "ejakuli", + "ejlo", + "ekarto", + "ekbruligi", + "ekceli", + "ekde", + "ekesti", + "ekfirmao", + "ekgliti", + "ekhavi", + "ekipi", + "ekkapti", + "eklezio", + "ekmalsati", + "ekonomio", + "ekpluvi", + "ekrano", + "ekster", + "ektiri", + "ekumeno", + "ekvilibro", + "ekzemplo", + "elasta", + "elbalai", + "elcento", + "eldoni", + "elektro", + "elfari", + "elgliti", + "elhaki", + "elipso", + "elkovi", + "ellasi", + "elmeti", + "elnutri", + "elokventa", + "elparoli", + "elrevigi", + "elstari", + "elteni", + "eluzita", + "elvoki", + "elzasa", + "emajlo", + "embaraso", + "emerito", + "emfazo", + "eminenta", + "emocio", + "empiria", + "emulsio", + "enarkivigi", + "enboteligi", + "enciklopedio", + "endorfino", + "energio", + "enfermi", + "engluti", + "enhavo", + "enigmo", + "enjekcio", + "enketi", + "enlanda", + "enmeti", + "enorma", + "enplanti", + "enradiki", + "enspezo", + "entrepreni", + "enui", + "envolvi", + "enzimo", + "eono", + "eosto", + "epitafo", + "epoko", + "epriskribebla", + "epsilono", + "erari", + "erbio", + "erco", + "erekti", + "ergonomia", + "erikejo", + "ermito", + "erotika", + "erpilo", + "erupcio", + "esameno", + "escepti", + "esenco", + "eskapi", + "esotera", + "esperi", + "estonto", + "etapo", + "etendi", + "etfingro", + "etikedo", + "etlitero", + "etmakleristo", + "etnika", + "etoso", + "etradio", + "etskala", + "etullernejo", + "evakui", + "evento", + "eviti", + "evolui", + "ezoko", + "fabriko", + "facila", + "fadeno", + "fagoto", + "fajro", + "fakto", + "fali", + "familio", + "fanatiko", + "farbo", + "fasko", + "fatala", + "favora", + "fazeolo", + "febro", + "federacio", + "feino", + "fekunda", + "felo", + "femuro", + "fenestro", + "fermi", + "festi", + "fetora", + "fezo", + "fiasko", + "fibro", + "fidela", + "fiera", + "fifama", + "figuro", + "fiherbo", + "fiinsekto", + "fiksa", + "filmo", + "fimensa", + "finalo", + "fiolo", + "fiparoli", + "firmao", + "fisko", + "fitingo", + "fiuzanto", + "fivorto", + "fiziko", + "fjordo", + "flago", + "flegi", + "flirti", + "floro", + "flugi", + "fobio", + "foceno", + "foirejo", + "fojfoje", + "fokuso", + "folio", + "fomenti", + "fonto", + "formulo", + "fosforo", + "fotografi", + "fratino", + "fremda", + "friti", + "frosto", + "frua", + "ftizo", + "fuelo", + "fugo", + "fuksia", + "fulmilo", + "fumanto", + "fundamento", + "fuorto", + "furioza", + "fusilo", + "futbalo", + "fuzio", + "gabardino", + "gado", + "gaela", + "gafo", + "gagato", + "gaja", + "gaki", + "galanta", + "gamao", + "ganto", + "gapulo", + "gardi", + "gasto", + "gavio", + "gazeto", + "geamantoj", + "gebani", + "geedzeco", + "gefratoj", + "geheno", + "gejsero", + "geko", + "gelateno", + "gemisto", + "geniulo", + "geografio", + "gepardo", + "geranio", + "gestolingvo", + "geto", + "geumo", + "gibono", + "giganta", + "gildo", + "gimnastiko", + "ginekologo", + "gipsi", + "girlando", + "gistfungo", + "gitaro", + "glazuro", + "glebo", + "gliti", + "globo", + "gluti", + "gnafalio", + "gnejso", + "gnomo", + "gnuo", + "gobio", + "godetio", + "goeleto", + "gojo", + "golfludejo", + "gombo", + "gondolo", + "gorilo", + "gospelo", + "gotika", + "granda", + "greno", + "griza", + "groto", + "grupo", + "guano", + "gubernatoro", + "gudrotuko", + "gufo", + "gujavo", + "guldeno", + "gumi", + "gupio", + "guruo", + "gusto", + "guto", + "guvernistino", + "gvardio", + "gverilo", + "gvidanto", + "habitato", + "hadito", + "hafnio", + "hagiografio", + "haitiano", + "hajlo", + "hakbloko", + "halti", + "hamstro", + "hangaro", + "hapalo", + "haro", + "hasta", + "hati", + "havebla", + "hazardo", + "hebrea", + "hedero", + "hegemonio", + "hejmo", + "hektaro", + "helpi", + "hemisfero", + "heni", + "hepato", + "herbo", + "hesa", + "heterogena", + "heziti", + "hiacinto", + "hibrida", + "hidrogeno", + "hieroglifo", + "higieno", + "hihii", + "hilumo", + "himno", + "hindino", + "hiperteksto", + "hirundo", + "historio", + "hobio", + "hojli", + "hokeo", + "hologramo", + "homido", + "honesta", + "hopi", + "horizonto", + "hospitalo", + "hotelo", + "huadi", + "hubo", + "hufumo", + "hugenoto", + "hukero", + "huligano", + "humana", + "hundo", + "huoj", + "hupilo", + "hurai", + "husaro", + "hutuo", + "huzo", + "iafoje", + "iagrade", + "iamaniere", + "iarelate", + "iaspeca", + "ibekso", + "ibiso", + "idaro", + "ideala", + "idiomo", + "idolo", + "iele", + "igluo", + "ignori", + "iguamo", + "igvano", + "ikono", + "iksodo", + "ikto", + "iliaflanke", + "ilkomputilo", + "ilobreto", + "ilremedo", + "ilumini", + "imagi", + "imitado", + "imperio", + "imuna", + "incidento", + "industrio", + "inerta", + "infano", + "ingenra", + "inhali", + "iniciati", + "injekti", + "inklino", + "inokuli", + "insekto", + "inteligenta", + "inundi", + "inviti", + "ioma", + "ionosfero", + "iperito", + "ipomeo", + "irana", + "irejo", + "irigacio", + "ironio", + "isato", + "islamo", + "istempo", + "itinero", + "itrio", + "iuloke", + "iumaniere", + "iutempe", + "izolita", + "jado", + "jaguaro", + "jakto", + "jama", + "januaro", + "japano", + "jarringo", + "jazo", + "jenoj", + "jesulo", + "jetavio", + "jezuito", + "jodli", + "joviala", + "juano", + "jubileo", + "judismo", + "jufto", + "juki", + "julio", + "juneca", + "jupo", + "juristo", + "juste", + "juvelo", + "kabineto", + "kadrato", + "kafo", + "kahelo", + "kajako", + "kakao", + "kalkuli", + "kampo", + "kanti", + "kapitalo", + "karaktero", + "kaserolo", + "katapulto", + "kaverna", + "kazino", + "kebabo", + "kefiro", + "keglo", + "kejlo", + "kekso", + "kelka", + "kemio", + "kerno", + "kesto", + "kiamaniere", + "kibuco", + "kidnapi", + "kielo", + "kikero", + "kilogramo", + "kimono", + "kinejo", + "kiosko", + "kirurgo", + "kisi", + "kitelo", + "kivio", + "klavaro", + "klerulo", + "klini", + "klopodi", + "klubo", + "knabo", + "knedi", + "koalo", + "kobalto", + "kodigi", + "kofro", + "kohera", + "koincidi", + "kojoto", + "kokoso", + "koloro", + "komenci", + "kontrakto", + "kopio", + "korekte", + "kosti", + "kotono", + "kovri", + "krajono", + "kredi", + "krii", + "krom", + "kruco", + "ksantino", + "ksenono", + "ksilofono", + "ksosa", + "kubuto", + "kudri", + "kuglo", + "kuiri", + "kuko", + "kulero", + "kumuluso", + "kuneco", + "kupro", + "kuri", + "kuseno", + "kutimo", + "kuvo", + "kuzino", + "kvalito", + "kverko", + "kvin", + "kvoto", + "labori", + "laculo", + "ladbotelo", + "lafo", + "laguno", + "laikino", + "laktobovino", + "lampolumo", + "landkarto", + "laosa", + "lapono", + "larmoguto", + "lastjare", + "latitudo", + "lavejo", + "lazanjo", + "leciono", + "ledosako", + "leganto", + "lekcio", + "lemura", + "lentuga", + "leopardo", + "leporo", + "lerni", + "lesivo", + "letero", + "levilo", + "lezi", + "liano", + "libera", + "liceo", + "lieno", + "lifto", + "ligilo", + "likvoro", + "lila", + "limono", + "lingvo", + "lipo", + "lirika", + "listo", + "literatura", + "liveri", + "lobio", + "logika", + "lojala", + "lokalo", + "longa", + "lordo", + "lotado", + "loza", + "luanto", + "lubriki", + "lucida", + "ludema", + "luigi", + "lukso", + "luli", + "lumbilda", + "lunde", + "lupago", + "lustro", + "lutilo", + "luzerno", + "maato", + "maceri", + "madono", + "mafiano", + "magazeno", + "mahometano", + "maizo", + "majstro", + "maketo", + "malgranda", + "mamo", + "mandareno", + "maorio", + "mapigi", + "marini", + "masko", + "mateno", + "mazuto", + "meandro", + "meblo", + "mecenato", + "medialo", + "mefito", + "megafono", + "mejlo", + "mekanika", + "melodia", + "membro", + "mendi", + "mergi", + "mespilo", + "metoda", + "mevo", + "mezuri", + "miaflanke", + "micelio", + "mielo", + "migdalo", + "mikrofilmo", + "militi", + "mimiko", + "mineralo", + "miopa", + "miri", + "mistera", + "mitralo", + "mizeri", + "mjelo", + "mnemoniko", + "mobilizi", + "mocio", + "moderna", + "mohajro", + "mokadi", + "molaro", + "momento", + "monero", + "mopso", + "mordi", + "moskito", + "motoro", + "movimento", + "mozaiko", + "mueli", + "mukozo", + "muldi", + "mumio", + "munti", + "muro", + "muskolo", + "mutacio", + "muzikisto", + "nabo", + "nacio", + "nadlo", + "nafto", + "naiva", + "najbaro", + "nanometro", + "napo", + "narciso", + "naski", + "naturo", + "navigi", + "naztruo", + "neatendite", + "nebulo", + "necesa", + "nedankinde", + "neebla", + "nefari", + "negoco", + "nehavi", + "neimagebla", + "nektaro", + "nelonga", + "nematura", + "nenia", + "neordinara", + "nepra", + "nervuro", + "nesto", + "nete", + "neulo", + "nevino", + "nifo", + "nigra", + "nihilisto", + "nikotino", + "nilono", + "nimfeo", + "nitrogeno", + "nivelo", + "nobla", + "nocio", + "nodozo", + "nokto", + "nomkarto", + "norda", + "nostalgio", + "notbloko", + "novico", + "nuanco", + "nuboza", + "nuda", + "nugato", + "nuklea", + "nuligi", + "numero", + "nuntempe", + "nupto", + "nura", + "nutri", + "oazo", + "obei", + "objekto", + "oblikva", + "obolo", + "observi", + "obtuza", + "obuso", + "oceano", + "odekolono", + "odori", + "oferti", + "oficiala", + "ofsajdo", + "ofte", + "ogivo", + "ogro", + "ojstredoj", + "okaze", + "okcidenta", + "okro", + "oksido", + "oktobro", + "okulo", + "oldulo", + "oleo", + "olivo", + "omaro", + "ombro", + "omego", + "omikrono", + "omleto", + "omnibuso", + "onagro", + "ondo", + "oneco", + "onidire", + "onklino", + "onlajna", + "onomatopeo", + "ontologio", + "opaka", + "operacii", + "opinii", + "oportuna", + "opresi", + "optimisto", + "oratoro", + "orbito", + "ordinara", + "orelo", + "orfino", + "organizi", + "orienta", + "orkestro", + "orlo", + "orminejo", + "ornami", + "ortangulo", + "orumi", + "oscedi", + "osmozo", + "ostocerbo", + "ovalo", + "ovingo", + "ovoblanko", + "ovri", + "ovulado", + "ozono", + "pacama", + "padeli", + "pafilo", + "pagigi", + "pajlo", + "paketo", + "palaco", + "pampelmo", + "pantalono", + "papero", + "paroli", + "pasejo", + "patro", + "pavimo", + "peco", + "pedalo", + "peklita", + "pelikano", + "pensiono", + "peplomo", + "pesilo", + "petanto", + "pezoforto", + "piano", + "picejo", + "piede", + "pigmento", + "pikema", + "pilkoludo", + "pimento", + "pinglo", + "pioniro", + "pipromento", + "pirato", + "pistolo", + "pitoreska", + "piulo", + "pivoti", + "pizango", + "planko", + "plektita", + "plibonigi", + "ploradi", + "plurlingva", + "pobo", + "podio", + "poeto", + "pogranda", + "pohora", + "pokalo", + "politekniko", + "pomarbo", + "ponevosto", + "populara", + "porcelana", + "postkompreno", + "poteto", + "poviga", + "pozitiva", + "prapatroj", + "precize", + "pridemandi", + "probable", + "pruntanto", + "psalmo", + "psikologio", + "psoriazo", + "pterido", + "publiko", + "pudro", + "pufo", + "pugnobato", + "pulovero", + "pumpi", + "punkto", + "pupo", + "pureo", + "puso", + "putrema", + "puzlo", + "rabate", + "racionala", + "radiko", + "rafinado", + "raguo", + "rajto", + "rakonti", + "ralio", + "rampi", + "rando", + "rapida", + "rastruma", + "ratifiki", + "raviolo", + "razeno", + "reakcio", + "rebildo", + "recepto", + "redakti", + "reenigi", + "reformi", + "regiono", + "rehavi", + "reinspekti", + "rejesi", + "reklamo", + "relativa", + "rememori", + "renkonti", + "reorganizado", + "reprezenti", + "respondi", + "retumilo", + "reuzebla", + "revidi", + "rezulti", + "rialo", + "ribeli", + "ricevi", + "ridiga", + "rifuginto", + "rigardi", + "rikolti", + "rilati", + "rimarki", + "rinocero", + "ripozi", + "riski", + "ritmo", + "rivero", + "rizokampo", + "roboto", + "rododendro", + "rojo", + "rokmuziko", + "rolvorto", + "romantika", + "ronroni", + "rosino", + "rotondo", + "rovero", + "rozeto", + "rubando", + "rudimenta", + "rufa", + "rugbeo", + "ruino", + "ruleto", + "rumoro", + "runo", + "rupio", + "rura", + "rustimuna", + "ruzulo", + "sabato", + "sadismo", + "safario", + "sagaca", + "sakfluto", + "salti", + "samtage", + "sandalo", + "sapejo", + "sarongo", + "satelito", + "savano", + "sbiro", + "sciado", + "seanco", + "sebo", + "sedativo", + "segligno", + "sekretario", + "selektiva", + "semajno", + "senpeza", + "separeo", + "servilo", + "sesangulo", + "setli", + "seurigi", + "severa", + "sezono", + "sfagno", + "sfero", + "sfinkso", + "siatempe", + "siblado", + "sidejo", + "siesto", + "sifono", + "signalo", + "siklo", + "silenti", + "simpla", + "sinjoro", + "siropo", + "sistemo", + "situacio", + "siverto", + "sizifa", + "skatolo", + "skemo", + "skianto", + "sklavo", + "skorpio", + "skribisto", + "skulpti", + "skvamo", + "slango", + "sledeto", + "sliparo", + "smeraldo", + "smirgi", + "smokingo", + "smuto", + "snoba", + "snufegi", + "sobra", + "sociano", + "sodakvo", + "sofo", + "soifi", + "sojlo", + "soklo", + "soldato", + "somero", + "sonilo", + "sopiri", + "sorto", + "soulo", + "soveto", + "sparkado", + "speciala", + "spiri", + "splito", + "sporto", + "sprita", + "spuro", + "stabila", + "stelfiguro", + "stimulo", + "stomako", + "strato", + "studanto", + "subgrupo", + "suden", + "suferanta", + "sugesti", + "suito", + "sukero", + "sulko", + "sume", + "sunlumo", + "super", + "surskribeto", + "suspekti", + "suturo", + "svati", + "svenfali", + "svingi", + "svopo", + "tabako", + "taglumo", + "tajloro", + "taksimetro", + "talento", + "tamen", + "tanko", + "taoismo", + "tapioko", + "tarifo", + "tasko", + "tatui", + "taverno", + "teatro", + "tedlaboro", + "tegmento", + "tehoro", + "teknika", + "telefono", + "tempo", + "tenisejo", + "teorie", + "teraso", + "testudo", + "tetablo", + "teujo", + "tezo", + "tialo", + "tibio", + "tielnomata", + "tifono", + "tigro", + "tikli", + "timida", + "tinkturo", + "tiom", + "tiparo", + "tirkesto", + "titolo", + "tiutempe", + "tizano", + "tobogano", + "tofeo", + "togo", + "toksa", + "tolerema", + "tombolo", + "tondri", + "topografio", + "tordeti", + "tosti", + "totalo", + "traduko", + "tredi", + "triangulo", + "tropika", + "trumpeto", + "tualeto", + "tubisto", + "tufgrebo", + "tuja", + "tukano", + "tulipo", + "tumulto", + "tunelo", + "turisto", + "tusi", + "tutmonda", + "tvisto", + "udono", + "uesto", + "ukazo", + "ukelelo", + "ulcero", + "ulmo", + "ultimato", + "ululi", + "umbiliko", + "unco", + "ungego", + "uniformo", + "unkti", + "unukolora", + "uragano", + "urbano", + "uretro", + "urino", + "ursido", + "uskleco", + "usonigi", + "utero", + "utila", + "utopia", + "uverturo", + "uzadi", + "uzeblo", + "uzino", + "uzkutimo", + "uzofini", + "uzurpi", + "uzvaloro", + "vadejo", + "vafleto", + "vagono", + "vahabismo", + "vajco", + "vakcino", + "valoro", + "vampiro", + "vangharoj", + "vaporo", + "varma", + "vasta", + "vato", + "vazaro", + "veaspekta", + "vedismo", + "vegetalo", + "vehiklo", + "vejno", + "vekita", + "velstango", + "vemieno", + "vendi", + "vepro", + "verando", + "vespero", + "veturi", + "veziko", + "viando", + "vibri", + "vico", + "videbla", + "vifio", + "vigla", + "viktimo", + "vila", + "vimeno", + "vintro", + "violo", + "vippuno", + "virtuala", + "viskoza", + "vitro", + "viveca", + "viziti", + "vobli", + "vodko", + "vojeto", + "vokegi", + "volbo", + "vomema", + "vono", + "vortaro", + "vosto", + "voti", + "vrako", + "vringi", + "vualo", + "vulkano", + "vundo", + "vuvuzelo", + "zamenhofa", + "zapi", + "zebro", + "zefiro", + "zeloto", + "zenismo", + "zeolito", + "zepelino", + "zeto", + "zigzagi", + "zinko", + "zipo", + "zirkonio", + "zodiako", + "zoeto", + "zombio", + "zono", + "zoologio", + "zorgi", + "zukino", + "zumilo", + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/german.h b/src/mnemonics/german.h index 40116970c..309f4cff8 100644 --- a/src/mnemonics/german.h +++ b/src/mnemonics/german.h @@ -1,1691 +1,1691 @@ -// Word list created by Monero contributor Shrikez -// -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file german.h - * - * \brief German word list and map. - */ - -#ifndef GERMAN_H -#define GERMAN_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class German: public Base - { - public: - German(): Base("Deutsch", "German", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "Abakus", - "Abart", - "abbilden", - "Abbruch", - "Abdrift", - "Abendrot", - "Abfahrt", - "abfeuern", - "Abflug", - "abfragen", - "Abglanz", - "abhärten", - "abheben", - "Abhilfe", - "Abitur", - "Abkehr", - "Ablauf", - "ablecken", - "Ablösung", - "Abnehmer", - "abnutzen", - "Abonnent", - "Abrasion", - "Abrede", - "abrüsten", - "Absicht", - "Absprung", - "Abstand", - "absuchen", - "Abteil", - "Abundanz", - "abwarten", - "Abwurf", - "Abzug", - "Achse", - "Achtung", - "Acker", - "Aderlass", - "Adler", - "Admiral", - "Adresse", - "Affe", - "Affront", - "Afrika", - "Aggregat", - "Agilität", - "ähneln", - "Ahnung", - "Ahorn", - "Akazie", - "Akkord", - "Akrobat", - "Aktfoto", - "Aktivist", - "Albatros", - "Alchimie", - "Alemanne", - "Alibi", - "Alkohol", - "Allee", - "Allüre", - "Almosen", - "Almweide", - "Aloe", - "Alpaka", - "Alpental", - "Alphabet", - "Alpinist", - "Alraune", - "Altbier", - "Alter", - "Altflöte", - "Altruist", - "Alublech", - "Aludose", - "Amateur", - "Amazonas", - "Ameise", - "Amnesie", - "Amok", - "Ampel", - "Amphibie", - "Ampulle", - "Amsel", - "Amulett", - "Anakonda", - "Analogie", - "Ananas", - "Anarchie", - "Anatomie", - "Anbau", - "Anbeginn", - "anbieten", - "Anblick", - "ändern", - "andocken", - "Andrang", - "anecken", - "Anflug", - "Anfrage", - "Anführer", - "Angebot", - "Angler", - "Anhalter", - "Anhöhe", - "Animator", - "Anis", - "Anker", - "ankleben", - "Ankunft", - "Anlage", - "anlocken", - "Anmut", - "Annahme", - "Anomalie", - "Anonymus", - "Anorak", - "anpeilen", - "Anrecht", - "Anruf", - "Ansage", - "Anschein", - "Ansicht", - "Ansporn", - "Anteil", - "Antlitz", - "Antrag", - "Antwort", - "Anwohner", - "Aorta", - "Apfel", - "Appetit", - "Applaus", - "Aquarium", - "Arbeit", - "Arche", - "Argument", - "Arktis", - "Armband", - "Aroma", - "Asche", - "Askese", - "Asphalt", - "Asteroid", - "Ästhetik", - "Astronom", - "Atelier", - "Athlet", - "Atlantik", - "Atmung", - "Audienz", - "aufatmen", - "Auffahrt", - "aufholen", - "aufregen", - "Aufsatz", - "Auftritt", - "Aufwand", - "Augapfel", - "Auktion", - "Ausbruch", - "Ausflug", - "Ausgabe", - "Aushilfe", - "Ausland", - "Ausnahme", - "Aussage", - "Autobahn", - "Avocado", - "Axthieb", - "Bach", - "backen", - "Badesee", - "Bahnhof", - "Balance", - "Balkon", - "Ballett", - "Balsam", - "Banane", - "Bandage", - "Bankett", - "Barbar", - "Barde", - "Barett", - "Bargeld", - "Barkasse", - "Barriere", - "Bart", - "Bass", - "Bastler", - "Batterie", - "Bauch", - "Bauer", - "Bauholz", - "Baujahr", - "Baum", - "Baustahl", - "Bauteil", - "Bauweise", - "Bazar", - "beachten", - "Beatmung", - "beben", - "Becher", - "Becken", - "bedanken", - "beeilen", - "beenden", - "Beere", - "befinden", - "Befreier", - "Begabung", - "Begierde", - "begrüßen", - "Beiboot", - "Beichte", - "Beifall", - "Beigabe", - "Beil", - "Beispiel", - "Beitrag", - "beizen", - "bekommen", - "beladen", - "Beleg", - "bellen", - "belohnen", - "Bemalung", - "Bengel", - "Benutzer", - "Benzin", - "beraten", - "Bereich", - "Bergluft", - "Bericht", - "Bescheid", - "Besitz", - "besorgen", - "Bestand", - "Besuch", - "betanken", - "beten", - "betören", - "Bett", - "Beule", - "Beute", - "Bewegung", - "bewirken", - "Bewohner", - "bezahlen", - "Bezug", - "biegen", - "Biene", - "Bierzelt", - "bieten", - "Bikini", - "Bildung", - "Billard", - "binden", - "Biobauer", - "Biologe", - "Bionik", - "Biotop", - "Birke", - "Bison", - "Bitte", - "Biwak", - "Bizeps", - "blasen", - "Blatt", - "Blauwal", - "Blende", - "Blick", - "Blitz", - "Blockade", - "Blödelei", - "Blondine", - "Blues", - "Blume", - "Blut", - "Bodensee", - "Bogen", - "Boje", - "Bollwerk", - "Bonbon", - "Bonus", - "Boot", - "Bordarzt", - "Börse", - "Böschung", - "Boudoir", - "Boxkampf", - "Boykott", - "Brahms", - "Brandung", - "Brauerei", - "Brecher", - "Breitaxt", - "Bremse", - "brennen", - "Brett", - "Brief", - "Brigade", - "Brillanz", - "bringen", - "brodeln", - "Brosche", - "Brötchen", - "Brücke", - "Brunnen", - "Brüste", - "Brutofen", - "Buch", - "Büffel", - "Bugwelle", - "Bühne", - "Buletten", - "Bullauge", - "Bumerang", - "bummeln", - "Buntglas", - "Bürde", - "Burgherr", - "Bursche", - "Busen", - "Buslinie", - "Bussard", - "Butangas", - "Butter", - "Cabrio", - "campen", - "Captain", - "Cartoon", - "Cello", - "Chalet", - "Charisma", - "Chefarzt", - "Chiffon", - "Chipsatz", - "Chirurg", - "Chor", - "Chronik", - "Chuzpe", - "Clubhaus", - "Cockpit", - "Codewort", - "Cognac", - "Coladose", - "Computer", - "Coupon", - "Cousin", - "Cracking", - "Crash", - "Curry", - "Dach", - "Dackel", - "daddeln", - "daliegen", - "Dame", - "Dammbau", - "Dämon", - "Dampflok", - "Dank", - "Darm", - "Datei", - "Datsche", - "Datteln", - "Datum", - "Dauer", - "Daunen", - "Deckel", - "Decoder", - "Defekt", - "Degen", - "Dehnung", - "Deiche", - "Dekade", - "Dekor", - "Delfin", - "Demut", - "denken", - "Deponie", - "Design", - "Desktop", - "Dessert", - "Detail", - "Detektiv", - "Dezibel", - "Diadem", - "Diagnose", - "Dialekt", - "Diamant", - "Dichter", - "Dickicht", - "Diesel", - "Diktat", - "Diplom", - "Direktor", - "Dirne", - "Diskurs", - "Distanz", - "Docht", - "Dohle", - "Dolch", - "Domäne", - "Donner", - "Dorade", - "Dorf", - "Dörrobst", - "Dorsch", - "Dossier", - "Dozent", - "Drachen", - "Draht", - "Drama", - "Drang", - "Drehbuch", - "Dreieck", - "Dressur", - "Drittel", - "Drossel", - "Druck", - "Duell", - "Duft", - "Düne", - "Dünung", - "dürfen", - "Duschbad", - "Düsenjet", - "Dynamik", - "Ebbe", - "Echolot", - "Echse", - "Eckball", - "Edding", - "Edelweiß", - "Eden", - "Edition", - "Efeu", - "Effekte", - "Egoismus", - "Ehre", - "Eiablage", - "Eiche", - "Eidechse", - "Eidotter", - "Eierkopf", - "Eigelb", - "Eiland", - "Eilbote", - "Eimer", - "einatmen", - "Einband", - "Eindruck", - "Einfall", - "Eingang", - "Einkauf", - "einladen", - "Einöde", - "Einrad", - "Eintopf", - "Einwurf", - "Einzug", - "Eisbär", - "Eisen", - "Eishöhle", - "Eismeer", - "Eiweiß", - "Ekstase", - "Elan", - "Elch", - "Elefant", - "Eleganz", - "Element", - "Elfe", - "Elite", - "Elixier", - "Ellbogen", - "Eloquenz", - "Emigrant", - "Emission", - "Emotion", - "Empathie", - "Empfang", - "Endzeit", - "Energie", - "Engpass", - "Enkel", - "Enklave", - "Ente", - "entheben", - "Entität", - "entladen", - "Entwurf", - "Episode", - "Epoche", - "erachten", - "Erbauer", - "erblühen", - "Erdbeere", - "Erde", - "Erdgas", - "Erdkunde", - "Erdnuss", - "Erdöl", - "Erdteil", - "Ereignis", - "Eremit", - "erfahren", - "Erfolg", - "erfreuen", - "erfüllen", - "Ergebnis", - "erhitzen", - "erkalten", - "erkennen", - "erleben", - "Erlösung", - "ernähren", - "erneuern", - "Ernte", - "Eroberer", - "eröffnen", - "Erosion", - "Erotik", - "Erpel", - "erraten", - "Erreger", - "erröten", - "Ersatz", - "Erstflug", - "Ertrag", - "Eruption", - "erwarten", - "erwidern", - "Erzbau", - "Erzeuger", - "erziehen", - "Esel", - "Eskimo", - "Eskorte", - "Espe", - "Espresso", - "essen", - "Etage", - "Etappe", - "Etat", - "Ethik", - "Etikett", - "Etüde", - "Eule", - "Euphorie", - "Europa", - "Everest", - "Examen", - "Exil", - "Exodus", - "Extrakt", - "Fabel", - "Fabrik", - "Fachmann", - "Fackel", - "Faden", - "Fagott", - "Fahne", - "Faible", - "Fairness", - "Fakt", - "Fakultät", - "Falke", - "Fallobst", - "Fälscher", - "Faltboot", - "Familie", - "Fanclub", - "Fanfare", - "Fangarm", - "Fantasie", - "Farbe", - "Farmhaus", - "Farn", - "Fasan", - "Faser", - "Fassung", - "fasten", - "Faulheit", - "Fauna", - "Faust", - "Favorit", - "Faxgerät", - "Fazit", - "fechten", - "Federboa", - "Fehler", - "Feier", - "Feige", - "feilen", - "Feinripp", - "Feldbett", - "Felge", - "Fellpony", - "Felswand", - "Ferien", - "Ferkel", - "Fernweh", - "Ferse", - "Fest", - "Fettnapf", - "Feuer", - "Fiasko", - "Fichte", - "Fiktion", - "Film", - "Filter", - "Filz", - "Finanzen", - "Findling", - "Finger", - "Fink", - "Finnwal", - "Fisch", - "Fitness", - "Fixpunkt", - "Fixstern", - "Fjord", - "Flachbau", - "Flagge", - "Flamenco", - "Flanke", - "Flasche", - "Flaute", - "Fleck", - "Flegel", - "flehen", - "Fleisch", - "fliegen", - "Flinte", - "Flirt", - "Flocke", - "Floh", - "Floskel", - "Floß", - "Flöte", - "Flugzeug", - "Flunder", - "Flusstal", - "Flutung", - "Fockmast", - "Fohlen", - "Föhnlage", - "Fokus", - "folgen", - "Foliant", - "Folklore", - "Fontäne", - "Förde", - "Forelle", - "Format", - "Forscher", - "Fortgang", - "Forum", - "Fotograf", - "Frachter", - "Fragment", - "Fraktion", - "fräsen", - "Frauenpo", - "Freak", - "Fregatte", - "Freiheit", - "Freude", - "Frieden", - "Frohsinn", - "Frosch", - "Frucht", - "Frühjahr", - "Fuchs", - "Fügung", - "fühlen", - "Füller", - "Fundbüro", - "Funkboje", - "Funzel", - "Furnier", - "Fürsorge", - "Fusel", - "Fußbad", - "Futteral", - "Gabelung", - "gackern", - "Gage", - "gähnen", - "Galaxie", - "Galeere", - "Galopp", - "Gameboy", - "Gamsbart", - "Gandhi", - "Gang", - "Garage", - "Gardine", - "Garküche", - "Garten", - "Gasthaus", - "Gattung", - "gaukeln", - "Gazelle", - "Gebäck", - "Gebirge", - "Gebräu", - "Geburt", - "Gedanke", - "Gedeck", - "Gedicht", - "Gefahr", - "Gefieder", - "Geflügel", - "Gefühl", - "Gegend", - "Gehirn", - "Gehöft", - "Gehweg", - "Geige", - "Geist", - "Gelage", - "Geld", - "Gelenk", - "Gelübde", - "Gemälde", - "Gemeinde", - "Gemüse", - "genesen", - "Genuss", - "Gepäck", - "Geranie", - "Gericht", - "Germane", - "Geruch", - "Gesang", - "Geschenk", - "Gesetz", - "Gesindel", - "Gesöff", - "Gespan", - "Gestade", - "Gesuch", - "Getier", - "Getränk", - "Getümmel", - "Gewand", - "Geweih", - "Gewitter", - "Gewölbe", - "Geysir", - "Giftzahn", - "Gipfel", - "Giraffe", - "Gitarre", - "glänzen", - "Glasauge", - "Glatze", - "Gleis", - "Globus", - "Glück", - "glühen", - "Glutofen", - "Goldzahn", - "Gondel", - "gönnen", - "Gottheit", - "graben", - "Grafik", - "Grashalm", - "Graugans", - "greifen", - "Grenze", - "grillen", - "Groschen", - "Grotte", - "Grube", - "Grünalge", - "Gruppe", - "gruseln", - "Gulasch", - "Gummibär", - "Gurgel", - "Gürtel", - "Güterzug", - "Haarband", - "Habicht", - "hacken", - "hadern", - "Hafen", - "Hagel", - "Hähnchen", - "Haifisch", - "Haken", - "Halbaffe", - "Halsader", - "halten", - "Halunke", - "Handbuch", - "Hanf", - "Harfe", - "Harnisch", - "härten", - "Harz", - "Hasenohr", - "Haube", - "hauchen", - "Haupt", - "Haut", - "Havarie", - "Hebamme", - "hecheln", - "Heck", - "Hedonist", - "Heiler", - "Heimat", - "Heizung", - "Hektik", - "Held", - "helfen", - "Helium", - "Hemd", - "hemmen", - "Hengst", - "Herd", - "Hering", - "Herkunft", - "Hermelin", - "Herrchen", - "Herzdame", - "Heulboje", - "Hexe", - "Hilfe", - "Himbeere", - "Himmel", - "Hingabe", - "hinhören", - "Hinweis", - "Hirsch", - "Hirte", - "Hitzkopf", - "Hobel", - "Hochform", - "Hocker", - "hoffen", - "Hofhund", - "Hofnarr", - "Höhenzug", - "Hohlraum", - "Hölle", - "Holzboot", - "Honig", - "Honorar", - "horchen", - "Hörprobe", - "Höschen", - "Hotel", - "Hubraum", - "Hufeisen", - "Hügel", - "huldigen", - "Hülle", - "Humbug", - "Hummer", - "Humor", - "Hund", - "Hunger", - "Hupe", - "Hürde", - "Hurrikan", - "Hydrant", - "Hypnose", - "Ibis", - "Idee", - "Idiot", - "Igel", - "Illusion", - "Imitat", - "impfen", - "Import", - "Inferno", - "Ingwer", - "Inhalte", - "Inland", - "Insekt", - "Ironie", - "Irrfahrt", - "Irrtum", - "Isolator", - "Istwert", - "Jacke", - "Jade", - "Jagdhund", - "Jäger", - "Jaguar", - "Jahr", - "Jähzorn", - "Jazzfest", - "Jetpilot", - "jobben", - "Jochbein", - "jodeln", - "Jodsalz", - "Jolle", - "Journal", - "Jubel", - "Junge", - "Junimond", - "Jupiter", - "Jutesack", - "Juwel", - "Kabarett", - "Kabine", - "Kabuff", - "Käfer", - "Kaffee", - "Kahlkopf", - "Kaimauer", - "Kajüte", - "Kaktus", - "Kaliber", - "Kaltluft", - "Kamel", - "kämmen", - "Kampagne", - "Kanal", - "Känguru", - "Kanister", - "Kanone", - "Kante", - "Kanu", - "kapern", - "Kapitän", - "Kapuze", - "Karneval", - "Karotte", - "Käsebrot", - "Kasper", - "Kastanie", - "Katalog", - "Kathode", - "Katze", - "kaufen", - "Kaugummi", - "Kauz", - "Kehle", - "Keilerei", - "Keksdose", - "Kellner", - "Keramik", - "Kerze", - "Kessel", - "Kette", - "keuchen", - "kichern", - "Kielboot", - "Kindheit", - "Kinnbart", - "Kinosaal", - "Kiosk", - "Kissen", - "Klammer", - "Klang", - "Klapprad", - "Klartext", - "kleben", - "Klee", - "Kleinod", - "Klima", - "Klingel", - "Klippe", - "Klischee", - "Kloster", - "Klugheit", - "Klüngel", - "kneten", - "Knie", - "Knöchel", - "knüpfen", - "Kobold", - "Kochbuch", - "Kohlrabi", - "Koje", - "Kokosöl", - "Kolibri", - "Kolumne", - "Kombüse", - "Komiker", - "kommen", - "Konto", - "Konzept", - "Kopfkino", - "Kordhose", - "Korken", - "Korsett", - "Kosename", - "Krabbe", - "Krach", - "Kraft", - "Krähe", - "Kralle", - "Krapfen", - "Krater", - "kraulen", - "Kreuz", - "Krokodil", - "Kröte", - "Kugel", - "Kuhhirt", - "Kühnheit", - "Künstler", - "Kurort", - "Kurve", - "Kurzfilm", - "kuscheln", - "küssen", - "Kutter", - "Labor", - "lachen", - "Lackaffe", - "Ladeluke", - "Lagune", - "Laib", - "Lakritze", - "Lammfell", - "Land", - "Langmut", - "Lappalie", - "Last", - "Laterne", - "Latzhose", - "Laubsäge", - "laufen", - "Laune", - "Lausbub", - "Lavasee", - "Leben", - "Leder", - "Leerlauf", - "Lehm", - "Lehrer", - "leihen", - "Lektüre", - "Lenker", - "Lerche", - "Leseecke", - "Leuchter", - "Lexikon", - "Libelle", - "Libido", - "Licht", - "Liebe", - "liefern", - "Liftboy", - "Limonade", - "Lineal", - "Linoleum", - "List", - "Liveband", - "Lobrede", - "locken", - "Löffel", - "Logbuch", - "Logik", - "Lohn", - "Loipe", - "Lokal", - "Lorbeer", - "Lösung", - "löten", - "Lottofee", - "Löwe", - "Luchs", - "Luder", - "Luftpost", - "Luke", - "Lümmel", - "Lunge", - "lutschen", - "Luxus", - "Macht", - "Magazin", - "Magier", - "Magnet", - "mähen", - "Mahlzeit", - "Mahnmal", - "Maibaum", - "Maisbrei", - "Makel", - "malen", - "Mammut", - "Maniküre", - "Mantel", - "Marathon", - "Marder", - "Marine", - "Marke", - "Marmor", - "Märzluft", - "Maske", - "Maßanzug", - "Maßkrug", - "Mastkorb", - "Material", - "Matratze", - "Mauerbau", - "Maulkorb", - "Mäuschen", - "Mäzen", - "Medium", - "Meinung", - "melden", - "Melodie", - "Mensch", - "Merkmal", - "Messe", - "Metall", - "Meteor", - "Methode", - "Metzger", - "Mieze", - "Milchkuh", - "Mimose", - "Minirock", - "Minute", - "mischen", - "Missetat", - "mitgehen", - "Mittag", - "Mixtape", - "Möbel", - "Modul", - "mögen", - "Möhre", - "Molch", - "Moment", - "Monat", - "Mondflug", - "Monitor", - "Monokini", - "Monster", - "Monument", - "Moorhuhn", - "Moos", - "Möpse", - "Moral", - "Mörtel", - "Motiv", - "Motorrad", - "Möwe", - "Mühe", - "Mulatte", - "Müller", - "Mumie", - "Mund", - "Münze", - "Muschel", - "Muster", - "Mythos", - "Nabel", - "Nachtzug", - "Nackedei", - "Nagel", - "Nähe", - "Nähnadel", - "Namen", - "Narbe", - "Narwal", - "Nasenbär", - "Natur", - "Nebel", - "necken", - "Neffe", - "Neigung", - "Nektar", - "Nenner", - "Neptun", - "Nerz", - "Nessel", - "Nestbau", - "Netz", - "Neubau", - "Neuerung", - "Neugier", - "nicken", - "Niere", - "Nilpferd", - "nisten", - "Nocke", - "Nomade", - "Nordmeer", - "Notdurft", - "Notstand", - "Notwehr", - "Nudismus", - "Nuss", - "Nutzhanf", - "Oase", - "Obdach", - "Oberarzt", - "Objekt", - "Oboe", - "Obsthain", - "Ochse", - "Odyssee", - "Ofenholz", - "öffnen", - "Ohnmacht", - "Ohrfeige", - "Ohrwurm", - "Ökologie", - "Oktave", - "Ölberg", - "Olive", - "Ölkrise", - "Omelett", - "Onkel", - "Oper", - "Optiker", - "Orange", - "Orchidee", - "ordnen", - "Orgasmus", - "Orkan", - "Ortskern", - "Ortung", - "Ostasien", - "Ozean", - "Paarlauf", - "Packeis", - "paddeln", - "Paket", - "Palast", - "Pandabär", - "Panik", - "Panorama", - "Panther", - "Papagei", - "Papier", - "Paprika", - "Paradies", - "Parka", - "Parodie", - "Partner", - "Passant", - "Patent", - "Patzer", - "Pause", - "Pavian", - "Pedal", - "Pegel", - "peilen", - "Perle", - "Person", - "Pfad", - "Pfau", - "Pferd", - "Pfleger", - "Physik", - "Pier", - "Pilotwal", - "Pinzette", - "Piste", - "Plakat", - "Plankton", - "Platin", - "Plombe", - "plündern", - "Pobacke", - "Pokal", - "polieren", - "Popmusik", - "Porträt", - "Posaune", - "Postamt", - "Pottwal", - "Pracht", - "Pranke", - "Preis", - "Primat", - "Prinzip", - "Protest", - "Proviant", - "Prüfung", - "Pubertät", - "Pudding", - "Pullover", - "Pulsader", - "Punkt", - "Pute", - "Putsch", - "Puzzle", - "Python", - "quaken", - "Qualle", - "Quark", - "Quellsee", - "Querkopf", - "Quitte", - "Quote", - "Rabauke", - "Rache", - "Radclub", - "Radhose", - "Radio", - "Radtour", - "Rahmen", - "Rampe", - "Randlage", - "Ranzen", - "Rapsöl", - "Raserei", - "rasten", - "Rasur", - "Rätsel", - "Raubtier", - "Raumzeit", - "Rausch", - "Reaktor", - "Realität", - "Rebell", - "Rede", - "Reetdach", - "Regatta", - "Regen", - "Rehkitz", - "Reifen", - "Reim", - "Reise", - "Reizung", - "Rekord", - "Relevanz", - "Rennboot", - "Respekt", - "Restmüll", - "retten", - "Reue", - "Revolte", - "Rhetorik", - "Rhythmus", - "Richtung", - "Riegel", - "Rindvieh", - "Rippchen", - "Ritter", - "Robbe", - "Roboter", - "Rockband", - "Rohdaten", - "Roller", - "Roman", - "röntgen", - "Rose", - "Rosskur", - "Rost", - "Rotahorn", - "Rotglut", - "Rotznase", - "Rubrik", - "Rückweg", - "Rufmord", - "Ruhe", - "Ruine", - "Rumpf", - "Runde", - "Rüstung", - "rütteln", - "Saaltür", - "Saatguts", - "Säbel", - "Sachbuch", - "Sack", - "Saft", - "sagen", - "Sahneeis", - "Salat", - "Salbe", - "Salz", - "Sammlung", - "Samt", - "Sandbank", - "Sanftmut", - "Sardine", - "Satire", - "Sattel", - "Satzbau", - "Sauerei", - "Saum", - "Säure", - "Schall", - "Scheitel", - "Schiff", - "Schlager", - "Schmied", - "Schnee", - "Scholle", - "Schrank", - "Schulbus", - "Schwan", - "Seeadler", - "Seefahrt", - "Seehund", - "Seeufer", - "segeln", - "Sehnerv", - "Seide", - "Seilzug", - "Senf", - "Sessel", - "Seufzer", - "Sexgott", - "Sichtung", - "Signal", - "Silber", - "singen", - "Sinn", - "Sirup", - "Sitzbank", - "Skandal", - "Skikurs", - "Skipper", - "Skizze", - "Smaragd", - "Socke", - "Sohn", - "Sommer", - "Songtext", - "Sorte", - "Spagat", - "Spannung", - "Spargel", - "Specht", - "Speiseöl", - "Spiegel", - "Sport", - "spülen", - "Stadtbus", - "Stall", - "Stärke", - "Stativ", - "staunen", - "Stern", - "Stiftung", - "Stollen", - "Strömung", - "Sturm", - "Substanz", - "Südalpen", - "Sumpf", - "surfen", - "Tabak", - "Tafel", - "Tagebau", - "takeln", - "Taktung", - "Talsohle", - "Tand", - "Tanzbär", - "Tapir", - "Tarantel", - "Tarnname", - "Tasse", - "Tatnacht", - "Tatsache", - "Tatze", - "Taube", - "tauchen", - "Taufpate", - "Taumel", - "Teelicht", - "Teich", - "teilen", - "Tempo", - "Tenor", - "Terrasse", - "Testflug", - "Theater", - "Thermik", - "ticken", - "Tiefflug", - "Tierart", - "Tigerhai", - "Tinte", - "Tischler", - "toben", - "Toleranz", - "Tölpel", - "Tonband", - "Topf", - "Topmodel", - "Torbogen", - "Torlinie", - "Torte", - "Tourist", - "Tragesel", - "trampeln", - "Trapez", - "Traum", - "treffen", - "Trennung", - "Treue", - "Trick", - "trimmen", - "Trödel", - "Trost", - "Trumpf", - "tüfteln", - "Turban", - "Turm", - "Übermut", - "Ufer", - "Uhrwerk", - "umarmen", - "Umbau", - "Umfeld", - "Umgang", - "Umsturz", - "Unart", - "Unfug", - "Unimog", - "Unruhe", - "Unwucht", - "Uranerz", - "Urlaub", - "Urmensch", - "Utopie", - "Vakuum", - "Valuta", - "Vandale", - "Vase", - "Vektor", - "Ventil", - "Verb", - "Verdeck", - "Verfall", - "Vergaser", - "verhexen", - "Verlag", - "Vers", - "Vesper", - "Vieh", - "Viereck", - "Vinyl", - "Virus", - "Vitrine", - "Vollblut", - "Vorbote", - "Vorrat", - "Vorsicht", - "Vulkan", - "Wachstum", - "Wade", - "Wagemut", - "Wahlen", - "Wahrheit", - "Wald", - "Walhai", - "Wallach", - "Walnuss", - "Walzer", - "wandeln", - "Wanze", - "wärmen", - "Warnruf", - "Wäsche", - "Wasser", - "Weberei", - "wechseln", - "Wegegeld", - "wehren", - "Weiher", - "Weinglas", - "Weißbier", - "Weitwurf", - "Welle", - "Weltall", - "Werkbank", - "Werwolf", - "Wetter", - "wiehern", - "Wildgans", - "Wind", - "Wohl", - "Wohnort", - "Wolf", - "Wollust", - "Wortlaut", - "Wrack", - "Wunder", - "Wurfaxt", - "Wurst", - "Yacht", - "Yeti", - "Zacke", - "Zahl", - "zähmen", - "Zahnfee", - "Zäpfchen", - "Zaster", - "Zaumzeug", - "Zebra", - "zeigen", - "Zeitlupe", - "Zellkern", - "Zeltdach", - "Zensor", - "Zerfall", - "Zeug", - "Ziege", - "Zielfoto", - "Zimteis", - "Zobel", - "Zollhund", - "Zombie", - "Zöpfe", - "Zucht", - "Zufahrt", - "Zugfahrt", - "Zugvogel", - "Zündung", - "Zweck", - "Zyklop" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list created by Monero contributor Shrikez +// +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file german.h + * + * \brief German word list and map. + */ + +#ifndef GERMAN_H +#define GERMAN_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class German: public Base + { + public: + German(): Base("Deutsch", "German", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "Abakus", + "Abart", + "abbilden", + "Abbruch", + "Abdrift", + "Abendrot", + "Abfahrt", + "abfeuern", + "Abflug", + "abfragen", + "Abglanz", + "abhärten", + "abheben", + "Abhilfe", + "Abitur", + "Abkehr", + "Ablauf", + "ablecken", + "Ablösung", + "Abnehmer", + "abnutzen", + "Abonnent", + "Abrasion", + "Abrede", + "abrüsten", + "Absicht", + "Absprung", + "Abstand", + "absuchen", + "Abteil", + "Abundanz", + "abwarten", + "Abwurf", + "Abzug", + "Achse", + "Achtung", + "Acker", + "Aderlass", + "Adler", + "Admiral", + "Adresse", + "Affe", + "Affront", + "Afrika", + "Aggregat", + "Agilität", + "ähneln", + "Ahnung", + "Ahorn", + "Akazie", + "Akkord", + "Akrobat", + "Aktfoto", + "Aktivist", + "Albatros", + "Alchimie", + "Alemanne", + "Alibi", + "Alkohol", + "Allee", + "Allüre", + "Almosen", + "Almweide", + "Aloe", + "Alpaka", + "Alpental", + "Alphabet", + "Alpinist", + "Alraune", + "Altbier", + "Alter", + "Altflöte", + "Altruist", + "Alublech", + "Aludose", + "Amateur", + "Amazonas", + "Ameise", + "Amnesie", + "Amok", + "Ampel", + "Amphibie", + "Ampulle", + "Amsel", + "Amulett", + "Anakonda", + "Analogie", + "Ananas", + "Anarchie", + "Anatomie", + "Anbau", + "Anbeginn", + "anbieten", + "Anblick", + "ändern", + "andocken", + "Andrang", + "anecken", + "Anflug", + "Anfrage", + "Anführer", + "Angebot", + "Angler", + "Anhalter", + "Anhöhe", + "Animator", + "Anis", + "Anker", + "ankleben", + "Ankunft", + "Anlage", + "anlocken", + "Anmut", + "Annahme", + "Anomalie", + "Anonymus", + "Anorak", + "anpeilen", + "Anrecht", + "Anruf", + "Ansage", + "Anschein", + "Ansicht", + "Ansporn", + "Anteil", + "Antlitz", + "Antrag", + "Antwort", + "Anwohner", + "Aorta", + "Apfel", + "Appetit", + "Applaus", + "Aquarium", + "Arbeit", + "Arche", + "Argument", + "Arktis", + "Armband", + "Aroma", + "Asche", + "Askese", + "Asphalt", + "Asteroid", + "Ästhetik", + "Astronom", + "Atelier", + "Athlet", + "Atlantik", + "Atmung", + "Audienz", + "aufatmen", + "Auffahrt", + "aufholen", + "aufregen", + "Aufsatz", + "Auftritt", + "Aufwand", + "Augapfel", + "Auktion", + "Ausbruch", + "Ausflug", + "Ausgabe", + "Aushilfe", + "Ausland", + "Ausnahme", + "Aussage", + "Autobahn", + "Avocado", + "Axthieb", + "Bach", + "backen", + "Badesee", + "Bahnhof", + "Balance", + "Balkon", + "Ballett", + "Balsam", + "Banane", + "Bandage", + "Bankett", + "Barbar", + "Barde", + "Barett", + "Bargeld", + "Barkasse", + "Barriere", + "Bart", + "Bass", + "Bastler", + "Batterie", + "Bauch", + "Bauer", + "Bauholz", + "Baujahr", + "Baum", + "Baustahl", + "Bauteil", + "Bauweise", + "Bazar", + "beachten", + "Beatmung", + "beben", + "Becher", + "Becken", + "bedanken", + "beeilen", + "beenden", + "Beere", + "befinden", + "Befreier", + "Begabung", + "Begierde", + "begrüßen", + "Beiboot", + "Beichte", + "Beifall", + "Beigabe", + "Beil", + "Beispiel", + "Beitrag", + "beizen", + "bekommen", + "beladen", + "Beleg", + "bellen", + "belohnen", + "Bemalung", + "Bengel", + "Benutzer", + "Benzin", + "beraten", + "Bereich", + "Bergluft", + "Bericht", + "Bescheid", + "Besitz", + "besorgen", + "Bestand", + "Besuch", + "betanken", + "beten", + "betören", + "Bett", + "Beule", + "Beute", + "Bewegung", + "bewirken", + "Bewohner", + "bezahlen", + "Bezug", + "biegen", + "Biene", + "Bierzelt", + "bieten", + "Bikini", + "Bildung", + "Billard", + "binden", + "Biobauer", + "Biologe", + "Bionik", + "Biotop", + "Birke", + "Bison", + "Bitte", + "Biwak", + "Bizeps", + "blasen", + "Blatt", + "Blauwal", + "Blende", + "Blick", + "Blitz", + "Blockade", + "Blödelei", + "Blondine", + "Blues", + "Blume", + "Blut", + "Bodensee", + "Bogen", + "Boje", + "Bollwerk", + "Bonbon", + "Bonus", + "Boot", + "Bordarzt", + "Börse", + "Böschung", + "Boudoir", + "Boxkampf", + "Boykott", + "Brahms", + "Brandung", + "Brauerei", + "Brecher", + "Breitaxt", + "Bremse", + "brennen", + "Brett", + "Brief", + "Brigade", + "Brillanz", + "bringen", + "brodeln", + "Brosche", + "Brötchen", + "Brücke", + "Brunnen", + "Brüste", + "Brutofen", + "Buch", + "Büffel", + "Bugwelle", + "Bühne", + "Buletten", + "Bullauge", + "Bumerang", + "bummeln", + "Buntglas", + "Bürde", + "Burgherr", + "Bursche", + "Busen", + "Buslinie", + "Bussard", + "Butangas", + "Butter", + "Cabrio", + "campen", + "Captain", + "Cartoon", + "Cello", + "Chalet", + "Charisma", + "Chefarzt", + "Chiffon", + "Chipsatz", + "Chirurg", + "Chor", + "Chronik", + "Chuzpe", + "Clubhaus", + "Cockpit", + "Codewort", + "Cognac", + "Coladose", + "Computer", + "Coupon", + "Cousin", + "Cracking", + "Crash", + "Curry", + "Dach", + "Dackel", + "daddeln", + "daliegen", + "Dame", + "Dammbau", + "Dämon", + "Dampflok", + "Dank", + "Darm", + "Datei", + "Datsche", + "Datteln", + "Datum", + "Dauer", + "Daunen", + "Deckel", + "Decoder", + "Defekt", + "Degen", + "Dehnung", + "Deiche", + "Dekade", + "Dekor", + "Delfin", + "Demut", + "denken", + "Deponie", + "Design", + "Desktop", + "Dessert", + "Detail", + "Detektiv", + "Dezibel", + "Diadem", + "Diagnose", + "Dialekt", + "Diamant", + "Dichter", + "Dickicht", + "Diesel", + "Diktat", + "Diplom", + "Direktor", + "Dirne", + "Diskurs", + "Distanz", + "Docht", + "Dohle", + "Dolch", + "Domäne", + "Donner", + "Dorade", + "Dorf", + "Dörrobst", + "Dorsch", + "Dossier", + "Dozent", + "Drachen", + "Draht", + "Drama", + "Drang", + "Drehbuch", + "Dreieck", + "Dressur", + "Drittel", + "Drossel", + "Druck", + "Duell", + "Duft", + "Düne", + "Dünung", + "dürfen", + "Duschbad", + "Düsenjet", + "Dynamik", + "Ebbe", + "Echolot", + "Echse", + "Eckball", + "Edding", + "Edelweiß", + "Eden", + "Edition", + "Efeu", + "Effekte", + "Egoismus", + "Ehre", + "Eiablage", + "Eiche", + "Eidechse", + "Eidotter", + "Eierkopf", + "Eigelb", + "Eiland", + "Eilbote", + "Eimer", + "einatmen", + "Einband", + "Eindruck", + "Einfall", + "Eingang", + "Einkauf", + "einladen", + "Einöde", + "Einrad", + "Eintopf", + "Einwurf", + "Einzug", + "Eisbär", + "Eisen", + "Eishöhle", + "Eismeer", + "Eiweiß", + "Ekstase", + "Elan", + "Elch", + "Elefant", + "Eleganz", + "Element", + "Elfe", + "Elite", + "Elixier", + "Ellbogen", + "Eloquenz", + "Emigrant", + "Emission", + "Emotion", + "Empathie", + "Empfang", + "Endzeit", + "Energie", + "Engpass", + "Enkel", + "Enklave", + "Ente", + "entheben", + "Entität", + "entladen", + "Entwurf", + "Episode", + "Epoche", + "erachten", + "Erbauer", + "erblühen", + "Erdbeere", + "Erde", + "Erdgas", + "Erdkunde", + "Erdnuss", + "Erdöl", + "Erdteil", + "Ereignis", + "Eremit", + "erfahren", + "Erfolg", + "erfreuen", + "erfüllen", + "Ergebnis", + "erhitzen", + "erkalten", + "erkennen", + "erleben", + "Erlösung", + "ernähren", + "erneuern", + "Ernte", + "Eroberer", + "eröffnen", + "Erosion", + "Erotik", + "Erpel", + "erraten", + "Erreger", + "erröten", + "Ersatz", + "Erstflug", + "Ertrag", + "Eruption", + "erwarten", + "erwidern", + "Erzbau", + "Erzeuger", + "erziehen", + "Esel", + "Eskimo", + "Eskorte", + "Espe", + "Espresso", + "essen", + "Etage", + "Etappe", + "Etat", + "Ethik", + "Etikett", + "Etüde", + "Eule", + "Euphorie", + "Europa", + "Everest", + "Examen", + "Exil", + "Exodus", + "Extrakt", + "Fabel", + "Fabrik", + "Fachmann", + "Fackel", + "Faden", + "Fagott", + "Fahne", + "Faible", + "Fairness", + "Fakt", + "Fakultät", + "Falke", + "Fallobst", + "Fälscher", + "Faltboot", + "Familie", + "Fanclub", + "Fanfare", + "Fangarm", + "Fantasie", + "Farbe", + "Farmhaus", + "Farn", + "Fasan", + "Faser", + "Fassung", + "fasten", + "Faulheit", + "Fauna", + "Faust", + "Favorit", + "Faxgerät", + "Fazit", + "fechten", + "Federboa", + "Fehler", + "Feier", + "Feige", + "feilen", + "Feinripp", + "Feldbett", + "Felge", + "Fellpony", + "Felswand", + "Ferien", + "Ferkel", + "Fernweh", + "Ferse", + "Fest", + "Fettnapf", + "Feuer", + "Fiasko", + "Fichte", + "Fiktion", + "Film", + "Filter", + "Filz", + "Finanzen", + "Findling", + "Finger", + "Fink", + "Finnwal", + "Fisch", + "Fitness", + "Fixpunkt", + "Fixstern", + "Fjord", + "Flachbau", + "Flagge", + "Flamenco", + "Flanke", + "Flasche", + "Flaute", + "Fleck", + "Flegel", + "flehen", + "Fleisch", + "fliegen", + "Flinte", + "Flirt", + "Flocke", + "Floh", + "Floskel", + "Floß", + "Flöte", + "Flugzeug", + "Flunder", + "Flusstal", + "Flutung", + "Fockmast", + "Fohlen", + "Föhnlage", + "Fokus", + "folgen", + "Foliant", + "Folklore", + "Fontäne", + "Förde", + "Forelle", + "Format", + "Forscher", + "Fortgang", + "Forum", + "Fotograf", + "Frachter", + "Fragment", + "Fraktion", + "fräsen", + "Frauenpo", + "Freak", + "Fregatte", + "Freiheit", + "Freude", + "Frieden", + "Frohsinn", + "Frosch", + "Frucht", + "Frühjahr", + "Fuchs", + "Fügung", + "fühlen", + "Füller", + "Fundbüro", + "Funkboje", + "Funzel", + "Furnier", + "Fürsorge", + "Fusel", + "Fußbad", + "Futteral", + "Gabelung", + "gackern", + "Gage", + "gähnen", + "Galaxie", + "Galeere", + "Galopp", + "Gameboy", + "Gamsbart", + "Gandhi", + "Gang", + "Garage", + "Gardine", + "Garküche", + "Garten", + "Gasthaus", + "Gattung", + "gaukeln", + "Gazelle", + "Gebäck", + "Gebirge", + "Gebräu", + "Geburt", + "Gedanke", + "Gedeck", + "Gedicht", + "Gefahr", + "Gefieder", + "Geflügel", + "Gefühl", + "Gegend", + "Gehirn", + "Gehöft", + "Gehweg", + "Geige", + "Geist", + "Gelage", + "Geld", + "Gelenk", + "Gelübde", + "Gemälde", + "Gemeinde", + "Gemüse", + "genesen", + "Genuss", + "Gepäck", + "Geranie", + "Gericht", + "Germane", + "Geruch", + "Gesang", + "Geschenk", + "Gesetz", + "Gesindel", + "Gesöff", + "Gespan", + "Gestade", + "Gesuch", + "Getier", + "Getränk", + "Getümmel", + "Gewand", + "Geweih", + "Gewitter", + "Gewölbe", + "Geysir", + "Giftzahn", + "Gipfel", + "Giraffe", + "Gitarre", + "glänzen", + "Glasauge", + "Glatze", + "Gleis", + "Globus", + "Glück", + "glühen", + "Glutofen", + "Goldzahn", + "Gondel", + "gönnen", + "Gottheit", + "graben", + "Grafik", + "Grashalm", + "Graugans", + "greifen", + "Grenze", + "grillen", + "Groschen", + "Grotte", + "Grube", + "Grünalge", + "Gruppe", + "gruseln", + "Gulasch", + "Gummibär", + "Gurgel", + "Gürtel", + "Güterzug", + "Haarband", + "Habicht", + "hacken", + "hadern", + "Hafen", + "Hagel", + "Hähnchen", + "Haifisch", + "Haken", + "Halbaffe", + "Halsader", + "halten", + "Halunke", + "Handbuch", + "Hanf", + "Harfe", + "Harnisch", + "härten", + "Harz", + "Hasenohr", + "Haube", + "hauchen", + "Haupt", + "Haut", + "Havarie", + "Hebamme", + "hecheln", + "Heck", + "Hedonist", + "Heiler", + "Heimat", + "Heizung", + "Hektik", + "Held", + "helfen", + "Helium", + "Hemd", + "hemmen", + "Hengst", + "Herd", + "Hering", + "Herkunft", + "Hermelin", + "Herrchen", + "Herzdame", + "Heulboje", + "Hexe", + "Hilfe", + "Himbeere", + "Himmel", + "Hingabe", + "hinhören", + "Hinweis", + "Hirsch", + "Hirte", + "Hitzkopf", + "Hobel", + "Hochform", + "Hocker", + "hoffen", + "Hofhund", + "Hofnarr", + "Höhenzug", + "Hohlraum", + "Hölle", + "Holzboot", + "Honig", + "Honorar", + "horchen", + "Hörprobe", + "Höschen", + "Hotel", + "Hubraum", + "Hufeisen", + "Hügel", + "huldigen", + "Hülle", + "Humbug", + "Hummer", + "Humor", + "Hund", + "Hunger", + "Hupe", + "Hürde", + "Hurrikan", + "Hydrant", + "Hypnose", + "Ibis", + "Idee", + "Idiot", + "Igel", + "Illusion", + "Imitat", + "impfen", + "Import", + "Inferno", + "Ingwer", + "Inhalte", + "Inland", + "Insekt", + "Ironie", + "Irrfahrt", + "Irrtum", + "Isolator", + "Istwert", + "Jacke", + "Jade", + "Jagdhund", + "Jäger", + "Jaguar", + "Jahr", + "Jähzorn", + "Jazzfest", + "Jetpilot", + "jobben", + "Jochbein", + "jodeln", + "Jodsalz", + "Jolle", + "Journal", + "Jubel", + "Junge", + "Junimond", + "Jupiter", + "Jutesack", + "Juwel", + "Kabarett", + "Kabine", + "Kabuff", + "Käfer", + "Kaffee", + "Kahlkopf", + "Kaimauer", + "Kajüte", + "Kaktus", + "Kaliber", + "Kaltluft", + "Kamel", + "kämmen", + "Kampagne", + "Kanal", + "Känguru", + "Kanister", + "Kanone", + "Kante", + "Kanu", + "kapern", + "Kapitän", + "Kapuze", + "Karneval", + "Karotte", + "Käsebrot", + "Kasper", + "Kastanie", + "Katalog", + "Kathode", + "Katze", + "kaufen", + "Kaugummi", + "Kauz", + "Kehle", + "Keilerei", + "Keksdose", + "Kellner", + "Keramik", + "Kerze", + "Kessel", + "Kette", + "keuchen", + "kichern", + "Kielboot", + "Kindheit", + "Kinnbart", + "Kinosaal", + "Kiosk", + "Kissen", + "Klammer", + "Klang", + "Klapprad", + "Klartext", + "kleben", + "Klee", + "Kleinod", + "Klima", + "Klingel", + "Klippe", + "Klischee", + "Kloster", + "Klugheit", + "Klüngel", + "kneten", + "Knie", + "Knöchel", + "knüpfen", + "Kobold", + "Kochbuch", + "Kohlrabi", + "Koje", + "Kokosöl", + "Kolibri", + "Kolumne", + "Kombüse", + "Komiker", + "kommen", + "Konto", + "Konzept", + "Kopfkino", + "Kordhose", + "Korken", + "Korsett", + "Kosename", + "Krabbe", + "Krach", + "Kraft", + "Krähe", + "Kralle", + "Krapfen", + "Krater", + "kraulen", + "Kreuz", + "Krokodil", + "Kröte", + "Kugel", + "Kuhhirt", + "Kühnheit", + "Künstler", + "Kurort", + "Kurve", + "Kurzfilm", + "kuscheln", + "küssen", + "Kutter", + "Labor", + "lachen", + "Lackaffe", + "Ladeluke", + "Lagune", + "Laib", + "Lakritze", + "Lammfell", + "Land", + "Langmut", + "Lappalie", + "Last", + "Laterne", + "Latzhose", + "Laubsäge", + "laufen", + "Laune", + "Lausbub", + "Lavasee", + "Leben", + "Leder", + "Leerlauf", + "Lehm", + "Lehrer", + "leihen", + "Lektüre", + "Lenker", + "Lerche", + "Leseecke", + "Leuchter", + "Lexikon", + "Libelle", + "Libido", + "Licht", + "Liebe", + "liefern", + "Liftboy", + "Limonade", + "Lineal", + "Linoleum", + "List", + "Liveband", + "Lobrede", + "locken", + "Löffel", + "Logbuch", + "Logik", + "Lohn", + "Loipe", + "Lokal", + "Lorbeer", + "Lösung", + "löten", + "Lottofee", + "Löwe", + "Luchs", + "Luder", + "Luftpost", + "Luke", + "Lümmel", + "Lunge", + "lutschen", + "Luxus", + "Macht", + "Magazin", + "Magier", + "Magnet", + "mähen", + "Mahlzeit", + "Mahnmal", + "Maibaum", + "Maisbrei", + "Makel", + "malen", + "Mammut", + "Maniküre", + "Mantel", + "Marathon", + "Marder", + "Marine", + "Marke", + "Marmor", + "Märzluft", + "Maske", + "Maßanzug", + "Maßkrug", + "Mastkorb", + "Material", + "Matratze", + "Mauerbau", + "Maulkorb", + "Mäuschen", + "Mäzen", + "Medium", + "Meinung", + "melden", + "Melodie", + "Mensch", + "Merkmal", + "Messe", + "Metall", + "Meteor", + "Methode", + "Metzger", + "Mieze", + "Milchkuh", + "Mimose", + "Minirock", + "Minute", + "mischen", + "Missetat", + "mitgehen", + "Mittag", + "Mixtape", + "Möbel", + "Modul", + "mögen", + "Möhre", + "Molch", + "Moment", + "Monat", + "Mondflug", + "Monitor", + "Monokini", + "Monster", + "Monument", + "Moorhuhn", + "Moos", + "Möpse", + "Moral", + "Mörtel", + "Motiv", + "Motorrad", + "Möwe", + "Mühe", + "Mulatte", + "Müller", + "Mumie", + "Mund", + "Münze", + "Muschel", + "Muster", + "Mythos", + "Nabel", + "Nachtzug", + "Nackedei", + "Nagel", + "Nähe", + "Nähnadel", + "Namen", + "Narbe", + "Narwal", + "Nasenbär", + "Natur", + "Nebel", + "necken", + "Neffe", + "Neigung", + "Nektar", + "Nenner", + "Neptun", + "Nerz", + "Nessel", + "Nestbau", + "Netz", + "Neubau", + "Neuerung", + "Neugier", + "nicken", + "Niere", + "Nilpferd", + "nisten", + "Nocke", + "Nomade", + "Nordmeer", + "Notdurft", + "Notstand", + "Notwehr", + "Nudismus", + "Nuss", + "Nutzhanf", + "Oase", + "Obdach", + "Oberarzt", + "Objekt", + "Oboe", + "Obsthain", + "Ochse", + "Odyssee", + "Ofenholz", + "öffnen", + "Ohnmacht", + "Ohrfeige", + "Ohrwurm", + "Ökologie", + "Oktave", + "Ölberg", + "Olive", + "Ölkrise", + "Omelett", + "Onkel", + "Oper", + "Optiker", + "Orange", + "Orchidee", + "ordnen", + "Orgasmus", + "Orkan", + "Ortskern", + "Ortung", + "Ostasien", + "Ozean", + "Paarlauf", + "Packeis", + "paddeln", + "Paket", + "Palast", + "Pandabär", + "Panik", + "Panorama", + "Panther", + "Papagei", + "Papier", + "Paprika", + "Paradies", + "Parka", + "Parodie", + "Partner", + "Passant", + "Patent", + "Patzer", + "Pause", + "Pavian", + "Pedal", + "Pegel", + "peilen", + "Perle", + "Person", + "Pfad", + "Pfau", + "Pferd", + "Pfleger", + "Physik", + "Pier", + "Pilotwal", + "Pinzette", + "Piste", + "Plakat", + "Plankton", + "Platin", + "Plombe", + "plündern", + "Pobacke", + "Pokal", + "polieren", + "Popmusik", + "Porträt", + "Posaune", + "Postamt", + "Pottwal", + "Pracht", + "Pranke", + "Preis", + "Primat", + "Prinzip", + "Protest", + "Proviant", + "Prüfung", + "Pubertät", + "Pudding", + "Pullover", + "Pulsader", + "Punkt", + "Pute", + "Putsch", + "Puzzle", + "Python", + "quaken", + "Qualle", + "Quark", + "Quellsee", + "Querkopf", + "Quitte", + "Quote", + "Rabauke", + "Rache", + "Radclub", + "Radhose", + "Radio", + "Radtour", + "Rahmen", + "Rampe", + "Randlage", + "Ranzen", + "Rapsöl", + "Raserei", + "rasten", + "Rasur", + "Rätsel", + "Raubtier", + "Raumzeit", + "Rausch", + "Reaktor", + "Realität", + "Rebell", + "Rede", + "Reetdach", + "Regatta", + "Regen", + "Rehkitz", + "Reifen", + "Reim", + "Reise", + "Reizung", + "Rekord", + "Relevanz", + "Rennboot", + "Respekt", + "Restmüll", + "retten", + "Reue", + "Revolte", + "Rhetorik", + "Rhythmus", + "Richtung", + "Riegel", + "Rindvieh", + "Rippchen", + "Ritter", + "Robbe", + "Roboter", + "Rockband", + "Rohdaten", + "Roller", + "Roman", + "röntgen", + "Rose", + "Rosskur", + "Rost", + "Rotahorn", + "Rotglut", + "Rotznase", + "Rubrik", + "Rückweg", + "Rufmord", + "Ruhe", + "Ruine", + "Rumpf", + "Runde", + "Rüstung", + "rütteln", + "Saaltür", + "Saatguts", + "Säbel", + "Sachbuch", + "Sack", + "Saft", + "sagen", + "Sahneeis", + "Salat", + "Salbe", + "Salz", + "Sammlung", + "Samt", + "Sandbank", + "Sanftmut", + "Sardine", + "Satire", + "Sattel", + "Satzbau", + "Sauerei", + "Saum", + "Säure", + "Schall", + "Scheitel", + "Schiff", + "Schlager", + "Schmied", + "Schnee", + "Scholle", + "Schrank", + "Schulbus", + "Schwan", + "Seeadler", + "Seefahrt", + "Seehund", + "Seeufer", + "segeln", + "Sehnerv", + "Seide", + "Seilzug", + "Senf", + "Sessel", + "Seufzer", + "Sexgott", + "Sichtung", + "Signal", + "Silber", + "singen", + "Sinn", + "Sirup", + "Sitzbank", + "Skandal", + "Skikurs", + "Skipper", + "Skizze", + "Smaragd", + "Socke", + "Sohn", + "Sommer", + "Songtext", + "Sorte", + "Spagat", + "Spannung", + "Spargel", + "Specht", + "Speiseöl", + "Spiegel", + "Sport", + "spülen", + "Stadtbus", + "Stall", + "Stärke", + "Stativ", + "staunen", + "Stern", + "Stiftung", + "Stollen", + "Strömung", + "Sturm", + "Substanz", + "Südalpen", + "Sumpf", + "surfen", + "Tabak", + "Tafel", + "Tagebau", + "takeln", + "Taktung", + "Talsohle", + "Tand", + "Tanzbär", + "Tapir", + "Tarantel", + "Tarnname", + "Tasse", + "Tatnacht", + "Tatsache", + "Tatze", + "Taube", + "tauchen", + "Taufpate", + "Taumel", + "Teelicht", + "Teich", + "teilen", + "Tempo", + "Tenor", + "Terrasse", + "Testflug", + "Theater", + "Thermik", + "ticken", + "Tiefflug", + "Tierart", + "Tigerhai", + "Tinte", + "Tischler", + "toben", + "Toleranz", + "Tölpel", + "Tonband", + "Topf", + "Topmodel", + "Torbogen", + "Torlinie", + "Torte", + "Tourist", + "Tragesel", + "trampeln", + "Trapez", + "Traum", + "treffen", + "Trennung", + "Treue", + "Trick", + "trimmen", + "Trödel", + "Trost", + "Trumpf", + "tüfteln", + "Turban", + "Turm", + "Übermut", + "Ufer", + "Uhrwerk", + "umarmen", + "Umbau", + "Umfeld", + "Umgang", + "Umsturz", + "Unart", + "Unfug", + "Unimog", + "Unruhe", + "Unwucht", + "Uranerz", + "Urlaub", + "Urmensch", + "Utopie", + "Vakuum", + "Valuta", + "Vandale", + "Vase", + "Vektor", + "Ventil", + "Verb", + "Verdeck", + "Verfall", + "Vergaser", + "verhexen", + "Verlag", + "Vers", + "Vesper", + "Vieh", + "Viereck", + "Vinyl", + "Virus", + "Vitrine", + "Vollblut", + "Vorbote", + "Vorrat", + "Vorsicht", + "Vulkan", + "Wachstum", + "Wade", + "Wagemut", + "Wahlen", + "Wahrheit", + "Wald", + "Walhai", + "Wallach", + "Walnuss", + "Walzer", + "wandeln", + "Wanze", + "wärmen", + "Warnruf", + "Wäsche", + "Wasser", + "Weberei", + "wechseln", + "Wegegeld", + "wehren", + "Weiher", + "Weinglas", + "Weißbier", + "Weitwurf", + "Welle", + "Weltall", + "Werkbank", + "Werwolf", + "Wetter", + "wiehern", + "Wildgans", + "Wind", + "Wohl", + "Wohnort", + "Wolf", + "Wollust", + "Wortlaut", + "Wrack", + "Wunder", + "Wurfaxt", + "Wurst", + "Yacht", + "Yeti", + "Zacke", + "Zahl", + "zähmen", + "Zahnfee", + "Zäpfchen", + "Zaster", + "Zaumzeug", + "Zebra", + "zeigen", + "Zeitlupe", + "Zellkern", + "Zeltdach", + "Zensor", + "Zerfall", + "Zeug", + "Ziege", + "Zielfoto", + "Zimteis", + "Zobel", + "Zollhund", + "Zombie", + "Zöpfe", + "Zucht", + "Zufahrt", + "Zugfahrt", + "Zugvogel", + "Zündung", + "Zweck", + "Zyklop" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/italian.h b/src/mnemonics/italian.h index 204fdcb78..85f52eaef 100644 --- a/src/mnemonics/italian.h +++ b/src/mnemonics/italian.h @@ -1,1691 +1,1691 @@ -// Word list created by Monero contributor Shrikez -// -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file italian.h - * - * \brief Italian word list and map. - */ - -#ifndef ITALIAN_H -#define ITALIAN_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Italian: public Base - { - public: - Italian(): Base("Italiano", "Italian", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "abbinare", - "abbonato", - "abisso", - "abitare", - "abominio", - "accadere", - "accesso", - "acciaio", - "accordo", - "accumulo", - "acido", - "acqua", - "acrobata", - "acustico", - "adattare", - "addetto", - "addio", - "addome", - "adeguato", - "aderire", - "adorare", - "adottare", - "adozione", - "adulto", - "aereo", - "aerobica", - "affare", - "affetto", - "affidare", - "affogato", - "affronto", - "africano", - "afrodite", - "agenzia", - "aggancio", - "aggeggio", - "aggiunta", - "agio", - "agire", - "agitare", - "aglio", - "agnello", - "agosto", - "aiutare", - "albero", - "albo", - "alce", - "alchimia", - "alcool", - "alfabeto", - "algebra", - "alimento", - "allarme", - "alleanza", - "allievo", - "alloggio", - "alluce", - "alpi", - "alterare", - "altro", - "aluminio", - "amante", - "amarezza", - "ambiente", - "ambrosia", - "america", - "amico", - "ammalare", - "ammirare", - "amnesia", - "amnistia", - "amore", - "ampliare", - "amputare", - "analisi", - "anamnesi", - "ananas", - "anarchia", - "anatra", - "anca", - "ancorato", - "andare", - "androide", - "aneddoto", - "anello", - "angelo", - "angolino", - "anguilla", - "anidride", - "anima", - "annegare", - "anno", - "annuncio", - "anomalia", - "antenna", - "anticipo", - "aperto", - "apostolo", - "appalto", - "appello", - "appiglio", - "applauso", - "appoggio", - "appurare", - "aprile", - "aquila", - "arabo", - "arachidi", - "aragosta", - "arancia", - "arbitrio", - "archivio", - "arco", - "argento", - "argilla", - "aria", - "ariete", - "arma", - "armonia", - "aroma", - "arrivare", - "arrosto", - "arsenale", - "arte", - "artiglio", - "asfalto", - "asfissia", - "asino", - "asparagi", - "aspirina", - "assalire", - "assegno", - "assolto", - "assurdo", - "asta", - "astratto", - "atlante", - "atletica", - "atomo", - "atropina", - "attacco", - "attesa", - "attico", - "atto", - "attrarre", - "auguri", - "aula", - "aumento", - "aurora", - "auspicio", - "autista", - "auto", - "autunno", - "avanzare", - "avarizia", - "avere", - "aviatore", - "avido", - "avorio", - "avvenire", - "avviso", - "avvocato", - "azienda", - "azione", - "azzardo", - "azzurro", - "babbuino", - "bacio", - "badante", - "baffi", - "bagaglio", - "bagliore", - "bagno", - "balcone", - "balena", - "ballare", - "balordo", - "balsamo", - "bambola", - "bancomat", - "banda", - "barato", - "barba", - "barista", - "barriera", - "basette", - "basilico", - "bassista", - "bastare", - "battello", - "bavaglio", - "beccare", - "beduino", - "bellezza", - "bene", - "benzina", - "berretto", - "bestia", - "bevitore", - "bianco", - "bibbia", - "biberon", - "bibita", - "bici", - "bidone", - "bilancia", - "biliardo", - "binario", - "binocolo", - "biologia", - "biondina", - "biopsia", - "biossido", - "birbante", - "birra", - "biscotto", - "bisogno", - "bistecca", - "bivio", - "blindare", - "bloccare", - "bocca", - "bollire", - "bombola", - "bonifico", - "borghese", - "borsa", - "bottino", - "botulino", - "braccio", - "bradipo", - "branco", - "bravo", - "bresaola", - "bretelle", - "brevetto", - "briciola", - "brigante", - "brillare", - "brindare", - "brivido", - "broccoli", - "brontolo", - "bruciare", - "brufolo", - "bucare", - "buddista", - "budino", - "bufera", - "buffo", - "bugiardo", - "buio", - "buono", - "burrone", - "bussola", - "bustina", - "buttare", - "cabernet", - "cabina", - "cacao", - "cacciare", - "cactus", - "cadavere", - "caffe", - "calamari", - "calcio", - "caldaia", - "calmare", - "calunnia", - "calvario", - "calzone", - "cambiare", - "camera", - "camion", - "cammello", - "campana", - "canarino", - "cancello", - "candore", - "cane", - "canguro", - "cannone", - "canoa", - "cantare", - "canzone", - "caos", - "capanna", - "capello", - "capire", - "capo", - "capperi", - "capra", - "capsula", - "caraffa", - "carbone", - "carciofo", - "cardigan", - "carenza", - "caricare", - "carota", - "carrello", - "carta", - "casa", - "cascare", - "caserma", - "cashmere", - "casino", - "cassetta", - "castello", - "catalogo", - "catena", - "catorcio", - "cattivo", - "causa", - "cauzione", - "cavallo", - "caverna", - "caviglia", - "cavo", - "cazzotto", - "celibato", - "cemento", - "cenare", - "centrale", - "ceramica", - "cercare", - "ceretta", - "cerniera", - "certezza", - "cervello", - "cessione", - "cestino", - "cetriolo", - "chiave", - "chiedere", - "chilo", - "chimera", - "chiodo", - "chirurgo", - "chitarra", - "chiudere", - "ciabatta", - "ciao", - "cibo", - "ciccia", - "cicerone", - "ciclone", - "cicogna", - "cielo", - "cifra", - "cigno", - "ciliegia", - "cimitero", - "cinema", - "cinque", - "cintura", - "ciondolo", - "ciotola", - "cipolla", - "cippato", - "circuito", - "cisterna", - "citofono", - "ciuccio", - "civetta", - "civico", - "clausola", - "cliente", - "clima", - "clinica", - "cobra", - "coccole", - "cocktail", - "cocomero", - "codice", - "coesione", - "cogliere", - "cognome", - "colla", - "colomba", - "colpire", - "coltello", - "comando", - "comitato", - "commedia", - "comodino", - "compagna", - "comune", - "concerto", - "condotto", - "conforto", - "congiura", - "coniglio", - "consegna", - "conto", - "convegno", - "coperta", - "copia", - "coprire", - "corazza", - "corda", - "corleone", - "cornice", - "corona", - "corpo", - "corrente", - "corsa", - "cortesia", - "corvo", - "coso", - "costume", - "cotone", - "cottura", - "cozza", - "crampo", - "cratere", - "cravatta", - "creare", - "credere", - "crema", - "crescere", - "crimine", - "criterio", - "croce", - "crollare", - "cronaca", - "crostata", - "croupier", - "cubetto", - "cucciolo", - "cucina", - "cultura", - "cuoco", - "cuore", - "cupido", - "cupola", - "cura", - "curva", - "cuscino", - "custode", - "danzare", - "data", - "decennio", - "decidere", - "decollo", - "dedicare", - "dedurre", - "definire", - "delegare", - "delfino", - "delitto", - "demone", - "dentista", - "denuncia", - "deposito", - "derivare", - "deserto", - "designer", - "destino", - "detonare", - "dettagli", - "diagnosi", - "dialogo", - "diamante", - "diario", - "diavolo", - "dicembre", - "difesa", - "digerire", - "digitare", - "diluvio", - "dinamica", - "dipinto", - "diploma", - "diramare", - "dire", - "dirigere", - "dirupo", - "discesa", - "disdetta", - "disegno", - "disporre", - "dissenso", - "distacco", - "dito", - "ditta", - "diva", - "divenire", - "dividere", - "divorare", - "docente", - "dolcetto", - "dolore", - "domatore", - "domenica", - "dominare", - "donatore", - "donna", - "dorato", - "dormire", - "dorso", - "dosaggio", - "dottore", - "dovere", - "download", - "dragone", - "dramma", - "dubbio", - "dubitare", - "duetto", - "durata", - "ebbrezza", - "eccesso", - "eccitare", - "eclissi", - "economia", - "edera", - "edificio", - "editore", - "edizione", - "educare", - "effetto", - "egitto", - "egiziano", - "elastico", - "elefante", - "eleggere", - "elemento", - "elenco", - "elezione", - "elmetto", - "elogio", - "embrione", - "emergere", - "emettere", - "eminenza", - "emisfero", - "emozione", - "empatia", - "energia", - "enfasi", - "enigma", - "entrare", - "enzima", - "epidemia", - "epilogo", - "episodio", - "epoca", - "equivoco", - "erba", - "erede", - "eroe", - "erotico", - "errore", - "eruzione", - "esaltare", - "esame", - "esaudire", - "eseguire", - "esempio", - "esigere", - "esistere", - "esito", - "esperto", - "espresso", - "essere", - "estasi", - "esterno", - "estrarre", - "eterno", - "etica", - "euforico", - "europa", - "evacuare", - "evasione", - "evento", - "evidenza", - "evitare", - "evolvere", - "fabbrica", - "facciata", - "fagiano", - "fagotto", - "falco", - "fame", - "famiglia", - "fanale", - "fango", - "fantasia", - "farfalla", - "farmacia", - "faro", - "fase", - "fastidio", - "faticare", - "fatto", - "favola", - "febbre", - "femmina", - "femore", - "fenomeno", - "fermata", - "feromoni", - "ferrari", - "fessura", - "festa", - "fiaba", - "fiamma", - "fianco", - "fiat", - "fibbia", - "fidare", - "fieno", - "figa", - "figlio", - "figura", - "filetto", - "filmato", - "filosofo", - "filtrare", - "finanza", - "finestra", - "fingere", - "finire", - "finta", - "finzione", - "fiocco", - "fioraio", - "firewall", - "firmare", - "fisico", - "fissare", - "fittizio", - "fiume", - "flacone", - "flagello", - "flirtare", - "flusso", - "focaccia", - "foglio", - "fognario", - "follia", - "fonderia", - "fontana", - "forbici", - "forcella", - "foresta", - "forgiare", - "formare", - "fornace", - "foro", - "fortuna", - "forzare", - "fosforo", - "fotoni", - "fracasso", - "fragola", - "frantumi", - "fratello", - "frazione", - "freccia", - "freddo", - "frenare", - "fresco", - "friggere", - "frittata", - "frivolo", - "frizione", - "fronte", - "frullato", - "frumento", - "frusta", - "frutto", - "fucile", - "fuggire", - "fulmine", - "fumare", - "funzione", - "fuoco", - "furbizia", - "furgone", - "furia", - "furore", - "fusibile", - "fuso", - "futuro", - "gabbiano", - "galassia", - "gallina", - "gamba", - "gancio", - "garanzia", - "garofano", - "gasolio", - "gatto", - "gazebo", - "gazzetta", - "gelato", - "gemelli", - "generare", - "genitori", - "gennaio", - "geologia", - "germania", - "gestire", - "gettare", - "ghepardo", - "ghiaccio", - "giaccone", - "giaguaro", - "giallo", - "giappone", - "giardino", - "gigante", - "gioco", - "gioiello", - "giorno", - "giovane", - "giraffa", - "giudizio", - "giurare", - "giusto", - "globo", - "gloria", - "glucosio", - "gnocca", - "gocciola", - "godere", - "gomito", - "gomma", - "gonfiare", - "gorilla", - "governo", - "gradire", - "graffiti", - "granchio", - "grappolo", - "grasso", - "grattare", - "gridare", - "grissino", - "grondaia", - "grugnito", - "gruppo", - "guadagno", - "guaio", - "guancia", - "guardare", - "gufo", - "guidare", - "guscio", - "gusto", - "icona", - "idea", - "identico", - "idolo", - "idoneo", - "idrante", - "idrogeno", - "igiene", - "ignoto", - "imbarco", - "immagine", - "immobile", - "imparare", - "impedire", - "impianto", - "importo", - "impresa", - "impulso", - "incanto", - "incendio", - "incidere", - "incontro", - "incrocia", - "incubo", - "indagare", - "indice", - "indotto", - "infanzia", - "inferno", - "infinito", - "infranto", - "ingerire", - "inglese", - "ingoiare", - "ingresso", - "iniziare", - "innesco", - "insalata", - "inserire", - "insicuro", - "insonnia", - "insulto", - "interno", - "introiti", - "invasori", - "inverno", - "invito", - "invocare", - "ipnosi", - "ipocrita", - "ipotesi", - "ironia", - "irrigare", - "iscritto", - "isola", - "ispirare", - "isterico", - "istinto", - "istruire", - "italiano", - "jazz", - "labbra", - "labrador", - "ladro", - "lago", - "lamento", - "lampone", - "lancetta", - "lanterna", - "lapide", - "larva", - "lasagne", - "lasciare", - "lastra", - "latte", - "laurea", - "lavagna", - "lavorare", - "leccare", - "legare", - "leggere", - "lenzuolo", - "leone", - "lepre", - "letargo", - "lettera", - "levare", - "levitare", - "lezione", - "liberare", - "libidine", - "libro", - "licenza", - "lievito", - "limite", - "lince", - "lingua", - "liquore", - "lire", - "listino", - "litigare", - "litro", - "locale", - "lottare", - "lucciola", - "lucidare", - "luglio", - "luna", - "macchina", - "madama", - "madre", - "maestro", - "maggio", - "magico", - "maglione", - "magnolia", - "mago", - "maialino", - "maionese", - "malattia", - "male", - "malloppo", - "mancare", - "mandorla", - "mangiare", - "manico", - "manopola", - "mansarda", - "mantello", - "manubrio", - "manzo", - "mappa", - "mare", - "margine", - "marinaio", - "marmotta", - "marocco", - "martello", - "marzo", - "maschera", - "matrice", - "maturare", - "mazzetta", - "meandri", - "medaglia", - "medico", - "medusa", - "megafono", - "melone", - "membrana", - "menta", - "mercato", - "meritare", - "merluzzo", - "mese", - "mestiere", - "metafora", - "meteo", - "metodo", - "mettere", - "miele", - "miglio", - "miliardo", - "mimetica", - "minatore", - "minuto", - "miracolo", - "mirtillo", - "missile", - "mistero", - "misura", - "mito", - "mobile", - "moda", - "moderare", - "moglie", - "molecola", - "molle", - "momento", - "moneta", - "mongolia", - "monologo", - "montagna", - "morale", - "morbillo", - "mordere", - "mosaico", - "mosca", - "mostro", - "motivare", - "moto", - "mulino", - "mulo", - "muovere", - "muraglia", - "muscolo", - "museo", - "musica", - "mutande", - "nascere", - "nastro", - "natale", - "natura", - "nave", - "navigare", - "negare", - "negozio", - "nemico", - "nero", - "nervo", - "nessuno", - "nettare", - "neutroni", - "neve", - "nevicare", - "nicotina", - "nido", - "nipote", - "nocciola", - "noleggio", - "nome", - "nonno", - "norvegia", - "notare", - "notizia", - "nove", - "nucleo", - "nuda", - "nuotare", - "nutrire", - "obbligo", - "occhio", - "occupare", - "oceano", - "odissea", - "odore", - "offerta", - "officina", - "offrire", - "oggetto", - "oggi", - "olfatto", - "olio", - "oliva", - "ombelico", - "ombrello", - "omuncolo", - "ondata", - "onore", - "opera", - "opinione", - "opuscolo", - "opzione", - "orario", - "orbita", - "orchidea", - "ordine", - "orecchio", - "orgasmo", - "orgoglio", - "origine", - "orologio", - "oroscopo", - "orso", - "oscurare", - "ospedale", - "ospite", - "ossigeno", - "ostacolo", - "ostriche", - "ottenere", - "ottimo", - "ottobre", - "ovest", - "pacco", - "pace", - "pacifico", - "padella", - "pagare", - "pagina", - "pagnotta", - "palazzo", - "palestra", - "palpebre", - "pancetta", - "panfilo", - "panino", - "pannello", - "panorama", - "papa", - "paperino", - "paradiso", - "parcella", - "parente", - "parlare", - "parodia", - "parrucca", - "partire", - "passare", - "pasta", - "patata", - "patente", - "patogeno", - "patriota", - "pausa", - "pazienza", - "peccare", - "pecora", - "pedalare", - "pelare", - "pena", - "pendenza", - "penisola", - "pennello", - "pensare", - "pentirsi", - "percorso", - "perdono", - "perfetto", - "perizoma", - "perla", - "permesso", - "persona", - "pesare", - "pesce", - "peso", - "petardo", - "petrolio", - "pezzo", - "piacere", - "pianeta", - "piastra", - "piatto", - "piazza", - "piccolo", - "piede", - "piegare", - "pietra", - "pigiama", - "pigliare", - "pigrizia", - "pilastro", - "pilota", - "pinguino", - "pioggia", - "piombo", - "pionieri", - "piovra", - "pipa", - "pirata", - "pirolisi", - "piscina", - "pisolino", - "pista", - "pitone", - "piumino", - "pizza", - "plastica", - "platino", - "poesia", - "poiana", - "polaroid", - "polenta", - "polimero", - "pollo", - "polmone", - "polpetta", - "poltrona", - "pomodoro", - "pompa", - "popolo", - "porco", - "porta", - "porzione", - "possesso", - "postino", - "potassio", - "potere", - "poverino", - "pranzo", - "prato", - "prefisso", - "prelievo", - "premio", - "prendere", - "prestare", - "pretesa", - "prezzo", - "primario", - "privacy", - "problema", - "processo", - "prodotto", - "profeta", - "progetto", - "promessa", - "pronto", - "proposta", - "proroga", - "prossimo", - "proteina", - "prova", - "prudenza", - "pubblico", - "pudore", - "pugilato", - "pulire", - "pulsante", - "puntare", - "pupazzo", - "puzzle", - "quaderno", - "qualcuno", - "quarzo", - "quercia", - "quintale", - "rabbia", - "racconto", - "radice", - "raffica", - "ragazza", - "ragione", - "rammento", - "ramo", - "rana", - "randagio", - "rapace", - "rapinare", - "rapporto", - "rasatura", - "ravioli", - "reagire", - "realista", - "reattore", - "reazione", - "recitare", - "recluso", - "record", - "recupero", - "redigere", - "regalare", - "regina", - "regola", - "relatore", - "reliquia", - "remare", - "rendere", - "reparto", - "resina", - "resto", - "rete", - "retorica", - "rettile", - "revocare", - "riaprire", - "ribadire", - "ribelle", - "ricambio", - "ricetta", - "richiamo", - "ricordo", - "ridurre", - "riempire", - "riferire", - "riflesso", - "righello", - "rilancio", - "rilevare", - "rilievo", - "rimanere", - "rimborso", - "rinforzo", - "rinuncia", - "riparo", - "ripetere", - "riposare", - "ripulire", - "risalita", - "riscatto", - "riserva", - "riso", - "rispetto", - "ritaglio", - "ritmo", - "ritorno", - "ritratto", - "rituale", - "riunione", - "riuscire", - "riva", - "robotica", - "rondine", - "rosa", - "rospo", - "rosso", - "rotonda", - "rotta", - "roulotte", - "rubare", - "rubrica", - "ruffiano", - "rumore", - "ruota", - "ruscello", - "sabbia", - "sacco", - "saggio", - "sale", - "salire", - "salmone", - "salto", - "salutare", - "salvia", - "sangue", - "sanzioni", - "sapere", - "sapienza", - "sarcasmo", - "sardine", - "sartoria", - "sbalzo", - "sbarcare", - "sberla", - "sborsare", - "scadenza", - "scafo", - "scala", - "scambio", - "scappare", - "scarpa", - "scatola", - "scelta", - "scena", - "sceriffo", - "scheggia", - "schiuma", - "sciarpa", - "scienza", - "scimmia", - "sciopero", - "scivolo", - "sclerare", - "scolpire", - "sconto", - "scopa", - "scordare", - "scossa", - "scrivere", - "scrupolo", - "scuderia", - "scultore", - "scuola", - "scusare", - "sdraiare", - "secolo", - "sedativo", - "sedere", - "sedia", - "segare", - "segreto", - "seguire", - "semaforo", - "seme", - "senape", - "seno", - "sentiero", - "separare", - "sepolcro", - "sequenza", - "serata", - "serpente", - "servizio", - "sesso", - "seta", - "settore", - "sfamare", - "sfera", - "sfidare", - "sfiorare", - "sfogare", - "sgabello", - "sicuro", - "siepe", - "sigaro", - "silenzio", - "silicone", - "simbiosi", - "simpatia", - "simulare", - "sinapsi", - "sindrome", - "sinergia", - "sinonimo", - "sintonia", - "sirena", - "siringa", - "sistema", - "sito", - "smalto", - "smentire", - "smontare", - "soccorso", - "socio", - "soffitto", - "software", - "soggetto", - "sogliola", - "sognare", - "soldi", - "sole", - "sollievo", - "solo", - "sommario", - "sondare", - "sonno", - "sorpresa", - "sorriso", - "sospiro", - "sostegno", - "sovrano", - "spaccare", - "spada", - "spagnolo", - "spalla", - "sparire", - "spavento", - "spazio", - "specchio", - "spedire", - "spegnere", - "spendere", - "speranza", - "spessore", - "spezzare", - "spiaggia", - "spiccare", - "spiegare", - "spiffero", - "spingere", - "sponda", - "sporcare", - "spostare", - "spremuta", - "spugna", - "spumante", - "spuntare", - "squadra", - "squillo", - "staccare", - "stadio", - "stagione", - "stallone", - "stampa", - "stancare", - "starnuto", - "statura", - "stella", - "stendere", - "sterzo", - "stilista", - "stimolo", - "stinco", - "stiva", - "stoffa", - "storia", - "strada", - "stregone", - "striscia", - "studiare", - "stufa", - "stupendo", - "subire", - "successo", - "sudare", - "suono", - "superare", - "supporto", - "surfista", - "sussurro", - "svelto", - "svenire", - "sviluppo", - "svolta", - "svuotare", - "tabacco", - "tabella", - "tabu", - "tacchino", - "tacere", - "taglio", - "talento", - "tangente", - "tappeto", - "tartufo", - "tassello", - "tastiera", - "tavolo", - "tazza", - "teatro", - "tedesco", - "telaio", - "telefono", - "tema", - "temere", - "tempo", - "tendenza", - "tenebre", - "tensione", - "tentare", - "teologia", - "teorema", - "termica", - "terrazzo", - "teschio", - "tesi", - "tesoro", - "tessera", - "testa", - "thriller", - "tifoso", - "tigre", - "timbrare", - "timido", - "tinta", - "tirare", - "tisana", - "titano", - "titolo", - "toccare", - "togliere", - "topolino", - "torcia", - "torrente", - "tovaglia", - "traffico", - "tragitto", - "training", - "tramonto", - "transito", - "trapezio", - "trasloco", - "trattore", - "trazione", - "treccia", - "tregua", - "treno", - "triciclo", - "tridente", - "trilogia", - "tromba", - "troncare", - "trota", - "trovare", - "trucco", - "tubo", - "tulipano", - "tumulto", - "tunisia", - "tuono", - "turista", - "tuta", - "tutelare", - "tutore", - "ubriaco", - "uccello", - "udienza", - "udito", - "uffa", - "umanoide", - "umore", - "unghia", - "unguento", - "unicorno", - "unione", - "universo", - "uomo", - "uragano", - "uranio", - "urlare", - "uscire", - "utente", - "utilizzo", - "vacanza", - "vacca", - "vaglio", - "vagonata", - "valle", - "valore", - "valutare", - "valvola", - "vampiro", - "vaniglia", - "vanto", - "vapore", - "variante", - "vasca", - "vaselina", - "vassoio", - "vedere", - "vegetale", - "veglia", - "veicolo", - "vela", - "veleno", - "velivolo", - "velluto", - "vendere", - "venerare", - "venire", - "vento", - "veranda", - "verbo", - "verdura", - "vergine", - "verifica", - "vernice", - "vero", - "verruca", - "versare", - "vertebra", - "vescica", - "vespaio", - "vestito", - "vesuvio", - "veterano", - "vetro", - "vetta", - "viadotto", - "viaggio", - "vibrare", - "vicenda", - "vichingo", - "vietare", - "vigilare", - "vigneto", - "villa", - "vincere", - "violino", - "vipera", - "virgola", - "virtuoso", - "visita", - "vita", - "vitello", - "vittima", - "vivavoce", - "vivere", - "viziato", - "voglia", - "volare", - "volpe", - "volto", - "volume", - "vongole", - "voragine", - "vortice", - "votare", - "vulcano", - "vuotare", - "zabaione", - "zaffiro", - "zainetto", - "zampa", - "zanzara", - "zattera", - "zavorra", - "zenzero", - "zero", - "zingaro", - "zittire", - "zoccolo", - "zolfo", - "zombie", - "zucchero" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list created by Monero contributor Shrikez +// +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file italian.h + * + * \brief Italian word list and map. + */ + +#ifndef ITALIAN_H +#define ITALIAN_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Italian: public Base + { + public: + Italian(): Base("Italiano", "Italian", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "abbinare", + "abbonato", + "abisso", + "abitare", + "abominio", + "accadere", + "accesso", + "acciaio", + "accordo", + "accumulo", + "acido", + "acqua", + "acrobata", + "acustico", + "adattare", + "addetto", + "addio", + "addome", + "adeguato", + "aderire", + "adorare", + "adottare", + "adozione", + "adulto", + "aereo", + "aerobica", + "affare", + "affetto", + "affidare", + "affogato", + "affronto", + "africano", + "afrodite", + "agenzia", + "aggancio", + "aggeggio", + "aggiunta", + "agio", + "agire", + "agitare", + "aglio", + "agnello", + "agosto", + "aiutare", + "albero", + "albo", + "alce", + "alchimia", + "alcool", + "alfabeto", + "algebra", + "alimento", + "allarme", + "alleanza", + "allievo", + "alloggio", + "alluce", + "alpi", + "alterare", + "altro", + "aluminio", + "amante", + "amarezza", + "ambiente", + "ambrosia", + "america", + "amico", + "ammalare", + "ammirare", + "amnesia", + "amnistia", + "amore", + "ampliare", + "amputare", + "analisi", + "anamnesi", + "ananas", + "anarchia", + "anatra", + "anca", + "ancorato", + "andare", + "androide", + "aneddoto", + "anello", + "angelo", + "angolino", + "anguilla", + "anidride", + "anima", + "annegare", + "anno", + "annuncio", + "anomalia", + "antenna", + "anticipo", + "aperto", + "apostolo", + "appalto", + "appello", + "appiglio", + "applauso", + "appoggio", + "appurare", + "aprile", + "aquila", + "arabo", + "arachidi", + "aragosta", + "arancia", + "arbitrio", + "archivio", + "arco", + "argento", + "argilla", + "aria", + "ariete", + "arma", + "armonia", + "aroma", + "arrivare", + "arrosto", + "arsenale", + "arte", + "artiglio", + "asfalto", + "asfissia", + "asino", + "asparagi", + "aspirina", + "assalire", + "assegno", + "assolto", + "assurdo", + "asta", + "astratto", + "atlante", + "atletica", + "atomo", + "atropina", + "attacco", + "attesa", + "attico", + "atto", + "attrarre", + "auguri", + "aula", + "aumento", + "aurora", + "auspicio", + "autista", + "auto", + "autunno", + "avanzare", + "avarizia", + "avere", + "aviatore", + "avido", + "avorio", + "avvenire", + "avviso", + "avvocato", + "azienda", + "azione", + "azzardo", + "azzurro", + "babbuino", + "bacio", + "badante", + "baffi", + "bagaglio", + "bagliore", + "bagno", + "balcone", + "balena", + "ballare", + "balordo", + "balsamo", + "bambola", + "bancomat", + "banda", + "barato", + "barba", + "barista", + "barriera", + "basette", + "basilico", + "bassista", + "bastare", + "battello", + "bavaglio", + "beccare", + "beduino", + "bellezza", + "bene", + "benzina", + "berretto", + "bestia", + "bevitore", + "bianco", + "bibbia", + "biberon", + "bibita", + "bici", + "bidone", + "bilancia", + "biliardo", + "binario", + "binocolo", + "biologia", + "biondina", + "biopsia", + "biossido", + "birbante", + "birra", + "biscotto", + "bisogno", + "bistecca", + "bivio", + "blindare", + "bloccare", + "bocca", + "bollire", + "bombola", + "bonifico", + "borghese", + "borsa", + "bottino", + "botulino", + "braccio", + "bradipo", + "branco", + "bravo", + "bresaola", + "bretelle", + "brevetto", + "briciola", + "brigante", + "brillare", + "brindare", + "brivido", + "broccoli", + "brontolo", + "bruciare", + "brufolo", + "bucare", + "buddista", + "budino", + "bufera", + "buffo", + "bugiardo", + "buio", + "buono", + "burrone", + "bussola", + "bustina", + "buttare", + "cabernet", + "cabina", + "cacao", + "cacciare", + "cactus", + "cadavere", + "caffe", + "calamari", + "calcio", + "caldaia", + "calmare", + "calunnia", + "calvario", + "calzone", + "cambiare", + "camera", + "camion", + "cammello", + "campana", + "canarino", + "cancello", + "candore", + "cane", + "canguro", + "cannone", + "canoa", + "cantare", + "canzone", + "caos", + "capanna", + "capello", + "capire", + "capo", + "capperi", + "capra", + "capsula", + "caraffa", + "carbone", + "carciofo", + "cardigan", + "carenza", + "caricare", + "carota", + "carrello", + "carta", + "casa", + "cascare", + "caserma", + "cashmere", + "casino", + "cassetta", + "castello", + "catalogo", + "catena", + "catorcio", + "cattivo", + "causa", + "cauzione", + "cavallo", + "caverna", + "caviglia", + "cavo", + "cazzotto", + "celibato", + "cemento", + "cenare", + "centrale", + "ceramica", + "cercare", + "ceretta", + "cerniera", + "certezza", + "cervello", + "cessione", + "cestino", + "cetriolo", + "chiave", + "chiedere", + "chilo", + "chimera", + "chiodo", + "chirurgo", + "chitarra", + "chiudere", + "ciabatta", + "ciao", + "cibo", + "ciccia", + "cicerone", + "ciclone", + "cicogna", + "cielo", + "cifra", + "cigno", + "ciliegia", + "cimitero", + "cinema", + "cinque", + "cintura", + "ciondolo", + "ciotola", + "cipolla", + "cippato", + "circuito", + "cisterna", + "citofono", + "ciuccio", + "civetta", + "civico", + "clausola", + "cliente", + "clima", + "clinica", + "cobra", + "coccole", + "cocktail", + "cocomero", + "codice", + "coesione", + "cogliere", + "cognome", + "colla", + "colomba", + "colpire", + "coltello", + "comando", + "comitato", + "commedia", + "comodino", + "compagna", + "comune", + "concerto", + "condotto", + "conforto", + "congiura", + "coniglio", + "consegna", + "conto", + "convegno", + "coperta", + "copia", + "coprire", + "corazza", + "corda", + "corleone", + "cornice", + "corona", + "corpo", + "corrente", + "corsa", + "cortesia", + "corvo", + "coso", + "costume", + "cotone", + "cottura", + "cozza", + "crampo", + "cratere", + "cravatta", + "creare", + "credere", + "crema", + "crescere", + "crimine", + "criterio", + "croce", + "crollare", + "cronaca", + "crostata", + "croupier", + "cubetto", + "cucciolo", + "cucina", + "cultura", + "cuoco", + "cuore", + "cupido", + "cupola", + "cura", + "curva", + "cuscino", + "custode", + "danzare", + "data", + "decennio", + "decidere", + "decollo", + "dedicare", + "dedurre", + "definire", + "delegare", + "delfino", + "delitto", + "demone", + "dentista", + "denuncia", + "deposito", + "derivare", + "deserto", + "designer", + "destino", + "detonare", + "dettagli", + "diagnosi", + "dialogo", + "diamante", + "diario", + "diavolo", + "dicembre", + "difesa", + "digerire", + "digitare", + "diluvio", + "dinamica", + "dipinto", + "diploma", + "diramare", + "dire", + "dirigere", + "dirupo", + "discesa", + "disdetta", + "disegno", + "disporre", + "dissenso", + "distacco", + "dito", + "ditta", + "diva", + "divenire", + "dividere", + "divorare", + "docente", + "dolcetto", + "dolore", + "domatore", + "domenica", + "dominare", + "donatore", + "donna", + "dorato", + "dormire", + "dorso", + "dosaggio", + "dottore", + "dovere", + "download", + "dragone", + "dramma", + "dubbio", + "dubitare", + "duetto", + "durata", + "ebbrezza", + "eccesso", + "eccitare", + "eclissi", + "economia", + "edera", + "edificio", + "editore", + "edizione", + "educare", + "effetto", + "egitto", + "egiziano", + "elastico", + "elefante", + "eleggere", + "elemento", + "elenco", + "elezione", + "elmetto", + "elogio", + "embrione", + "emergere", + "emettere", + "eminenza", + "emisfero", + "emozione", + "empatia", + "energia", + "enfasi", + "enigma", + "entrare", + "enzima", + "epidemia", + "epilogo", + "episodio", + "epoca", + "equivoco", + "erba", + "erede", + "eroe", + "erotico", + "errore", + "eruzione", + "esaltare", + "esame", + "esaudire", + "eseguire", + "esempio", + "esigere", + "esistere", + "esito", + "esperto", + "espresso", + "essere", + "estasi", + "esterno", + "estrarre", + "eterno", + "etica", + "euforico", + "europa", + "evacuare", + "evasione", + "evento", + "evidenza", + "evitare", + "evolvere", + "fabbrica", + "facciata", + "fagiano", + "fagotto", + "falco", + "fame", + "famiglia", + "fanale", + "fango", + "fantasia", + "farfalla", + "farmacia", + "faro", + "fase", + "fastidio", + "faticare", + "fatto", + "favola", + "febbre", + "femmina", + "femore", + "fenomeno", + "fermata", + "feromoni", + "ferrari", + "fessura", + "festa", + "fiaba", + "fiamma", + "fianco", + "fiat", + "fibbia", + "fidare", + "fieno", + "figa", + "figlio", + "figura", + "filetto", + "filmato", + "filosofo", + "filtrare", + "finanza", + "finestra", + "fingere", + "finire", + "finta", + "finzione", + "fiocco", + "fioraio", + "firewall", + "firmare", + "fisico", + "fissare", + "fittizio", + "fiume", + "flacone", + "flagello", + "flirtare", + "flusso", + "focaccia", + "foglio", + "fognario", + "follia", + "fonderia", + "fontana", + "forbici", + "forcella", + "foresta", + "forgiare", + "formare", + "fornace", + "foro", + "fortuna", + "forzare", + "fosforo", + "fotoni", + "fracasso", + "fragola", + "frantumi", + "fratello", + "frazione", + "freccia", + "freddo", + "frenare", + "fresco", + "friggere", + "frittata", + "frivolo", + "frizione", + "fronte", + "frullato", + "frumento", + "frusta", + "frutto", + "fucile", + "fuggire", + "fulmine", + "fumare", + "funzione", + "fuoco", + "furbizia", + "furgone", + "furia", + "furore", + "fusibile", + "fuso", + "futuro", + "gabbiano", + "galassia", + "gallina", + "gamba", + "gancio", + "garanzia", + "garofano", + "gasolio", + "gatto", + "gazebo", + "gazzetta", + "gelato", + "gemelli", + "generare", + "genitori", + "gennaio", + "geologia", + "germania", + "gestire", + "gettare", + "ghepardo", + "ghiaccio", + "giaccone", + "giaguaro", + "giallo", + "giappone", + "giardino", + "gigante", + "gioco", + "gioiello", + "giorno", + "giovane", + "giraffa", + "giudizio", + "giurare", + "giusto", + "globo", + "gloria", + "glucosio", + "gnocca", + "gocciola", + "godere", + "gomito", + "gomma", + "gonfiare", + "gorilla", + "governo", + "gradire", + "graffiti", + "granchio", + "grappolo", + "grasso", + "grattare", + "gridare", + "grissino", + "grondaia", + "grugnito", + "gruppo", + "guadagno", + "guaio", + "guancia", + "guardare", + "gufo", + "guidare", + "guscio", + "gusto", + "icona", + "idea", + "identico", + "idolo", + "idoneo", + "idrante", + "idrogeno", + "igiene", + "ignoto", + "imbarco", + "immagine", + "immobile", + "imparare", + "impedire", + "impianto", + "importo", + "impresa", + "impulso", + "incanto", + "incendio", + "incidere", + "incontro", + "incrocia", + "incubo", + "indagare", + "indice", + "indotto", + "infanzia", + "inferno", + "infinito", + "infranto", + "ingerire", + "inglese", + "ingoiare", + "ingresso", + "iniziare", + "innesco", + "insalata", + "inserire", + "insicuro", + "insonnia", + "insulto", + "interno", + "introiti", + "invasori", + "inverno", + "invito", + "invocare", + "ipnosi", + "ipocrita", + "ipotesi", + "ironia", + "irrigare", + "iscritto", + "isola", + "ispirare", + "isterico", + "istinto", + "istruire", + "italiano", + "jazz", + "labbra", + "labrador", + "ladro", + "lago", + "lamento", + "lampone", + "lancetta", + "lanterna", + "lapide", + "larva", + "lasagne", + "lasciare", + "lastra", + "latte", + "laurea", + "lavagna", + "lavorare", + "leccare", + "legare", + "leggere", + "lenzuolo", + "leone", + "lepre", + "letargo", + "lettera", + "levare", + "levitare", + "lezione", + "liberare", + "libidine", + "libro", + "licenza", + "lievito", + "limite", + "lince", + "lingua", + "liquore", + "lire", + "listino", + "litigare", + "litro", + "locale", + "lottare", + "lucciola", + "lucidare", + "luglio", + "luna", + "macchina", + "madama", + "madre", + "maestro", + "maggio", + "magico", + "maglione", + "magnolia", + "mago", + "maialino", + "maionese", + "malattia", + "male", + "malloppo", + "mancare", + "mandorla", + "mangiare", + "manico", + "manopola", + "mansarda", + "mantello", + "manubrio", + "manzo", + "mappa", + "mare", + "margine", + "marinaio", + "marmotta", + "marocco", + "martello", + "marzo", + "maschera", + "matrice", + "maturare", + "mazzetta", + "meandri", + "medaglia", + "medico", + "medusa", + "megafono", + "melone", + "membrana", + "menta", + "mercato", + "meritare", + "merluzzo", + "mese", + "mestiere", + "metafora", + "meteo", + "metodo", + "mettere", + "miele", + "miglio", + "miliardo", + "mimetica", + "minatore", + "minuto", + "miracolo", + "mirtillo", + "missile", + "mistero", + "misura", + "mito", + "mobile", + "moda", + "moderare", + "moglie", + "molecola", + "molle", + "momento", + "moneta", + "mongolia", + "monologo", + "montagna", + "morale", + "morbillo", + "mordere", + "mosaico", + "mosca", + "mostro", + "motivare", + "moto", + "mulino", + "mulo", + "muovere", + "muraglia", + "muscolo", + "museo", + "musica", + "mutande", + "nascere", + "nastro", + "natale", + "natura", + "nave", + "navigare", + "negare", + "negozio", + "nemico", + "nero", + "nervo", + "nessuno", + "nettare", + "neutroni", + "neve", + "nevicare", + "nicotina", + "nido", + "nipote", + "nocciola", + "noleggio", + "nome", + "nonno", + "norvegia", + "notare", + "notizia", + "nove", + "nucleo", + "nuda", + "nuotare", + "nutrire", + "obbligo", + "occhio", + "occupare", + "oceano", + "odissea", + "odore", + "offerta", + "officina", + "offrire", + "oggetto", + "oggi", + "olfatto", + "olio", + "oliva", + "ombelico", + "ombrello", + "omuncolo", + "ondata", + "onore", + "opera", + "opinione", + "opuscolo", + "opzione", + "orario", + "orbita", + "orchidea", + "ordine", + "orecchio", + "orgasmo", + "orgoglio", + "origine", + "orologio", + "oroscopo", + "orso", + "oscurare", + "ospedale", + "ospite", + "ossigeno", + "ostacolo", + "ostriche", + "ottenere", + "ottimo", + "ottobre", + "ovest", + "pacco", + "pace", + "pacifico", + "padella", + "pagare", + "pagina", + "pagnotta", + "palazzo", + "palestra", + "palpebre", + "pancetta", + "panfilo", + "panino", + "pannello", + "panorama", + "papa", + "paperino", + "paradiso", + "parcella", + "parente", + "parlare", + "parodia", + "parrucca", + "partire", + "passare", + "pasta", + "patata", + "patente", + "patogeno", + "patriota", + "pausa", + "pazienza", + "peccare", + "pecora", + "pedalare", + "pelare", + "pena", + "pendenza", + "penisola", + "pennello", + "pensare", + "pentirsi", + "percorso", + "perdono", + "perfetto", + "perizoma", + "perla", + "permesso", + "persona", + "pesare", + "pesce", + "peso", + "petardo", + "petrolio", + "pezzo", + "piacere", + "pianeta", + "piastra", + "piatto", + "piazza", + "piccolo", + "piede", + "piegare", + "pietra", + "pigiama", + "pigliare", + "pigrizia", + "pilastro", + "pilota", + "pinguino", + "pioggia", + "piombo", + "pionieri", + "piovra", + "pipa", + "pirata", + "pirolisi", + "piscina", + "pisolino", + "pista", + "pitone", + "piumino", + "pizza", + "plastica", + "platino", + "poesia", + "poiana", + "polaroid", + "polenta", + "polimero", + "pollo", + "polmone", + "polpetta", + "poltrona", + "pomodoro", + "pompa", + "popolo", + "porco", + "porta", + "porzione", + "possesso", + "postino", + "potassio", + "potere", + "poverino", + "pranzo", + "prato", + "prefisso", + "prelievo", + "premio", + "prendere", + "prestare", + "pretesa", + "prezzo", + "primario", + "privacy", + "problema", + "processo", + "prodotto", + "profeta", + "progetto", + "promessa", + "pronto", + "proposta", + "proroga", + "prossimo", + "proteina", + "prova", + "prudenza", + "pubblico", + "pudore", + "pugilato", + "pulire", + "pulsante", + "puntare", + "pupazzo", + "puzzle", + "quaderno", + "qualcuno", + "quarzo", + "quercia", + "quintale", + "rabbia", + "racconto", + "radice", + "raffica", + "ragazza", + "ragione", + "rammento", + "ramo", + "rana", + "randagio", + "rapace", + "rapinare", + "rapporto", + "rasatura", + "ravioli", + "reagire", + "realista", + "reattore", + "reazione", + "recitare", + "recluso", + "record", + "recupero", + "redigere", + "regalare", + "regina", + "regola", + "relatore", + "reliquia", + "remare", + "rendere", + "reparto", + "resina", + "resto", + "rete", + "retorica", + "rettile", + "revocare", + "riaprire", + "ribadire", + "ribelle", + "ricambio", + "ricetta", + "richiamo", + "ricordo", + "ridurre", + "riempire", + "riferire", + "riflesso", + "righello", + "rilancio", + "rilevare", + "rilievo", + "rimanere", + "rimborso", + "rinforzo", + "rinuncia", + "riparo", + "ripetere", + "riposare", + "ripulire", + "risalita", + "riscatto", + "riserva", + "riso", + "rispetto", + "ritaglio", + "ritmo", + "ritorno", + "ritratto", + "rituale", + "riunione", + "riuscire", + "riva", + "robotica", + "rondine", + "rosa", + "rospo", + "rosso", + "rotonda", + "rotta", + "roulotte", + "rubare", + "rubrica", + "ruffiano", + "rumore", + "ruota", + "ruscello", + "sabbia", + "sacco", + "saggio", + "sale", + "salire", + "salmone", + "salto", + "salutare", + "salvia", + "sangue", + "sanzioni", + "sapere", + "sapienza", + "sarcasmo", + "sardine", + "sartoria", + "sbalzo", + "sbarcare", + "sberla", + "sborsare", + "scadenza", + "scafo", + "scala", + "scambio", + "scappare", + "scarpa", + "scatola", + "scelta", + "scena", + "sceriffo", + "scheggia", + "schiuma", + "sciarpa", + "scienza", + "scimmia", + "sciopero", + "scivolo", + "sclerare", + "scolpire", + "sconto", + "scopa", + "scordare", + "scossa", + "scrivere", + "scrupolo", + "scuderia", + "scultore", + "scuola", + "scusare", + "sdraiare", + "secolo", + "sedativo", + "sedere", + "sedia", + "segare", + "segreto", + "seguire", + "semaforo", + "seme", + "senape", + "seno", + "sentiero", + "separare", + "sepolcro", + "sequenza", + "serata", + "serpente", + "servizio", + "sesso", + "seta", + "settore", + "sfamare", + "sfera", + "sfidare", + "sfiorare", + "sfogare", + "sgabello", + "sicuro", + "siepe", + "sigaro", + "silenzio", + "silicone", + "simbiosi", + "simpatia", + "simulare", + "sinapsi", + "sindrome", + "sinergia", + "sinonimo", + "sintonia", + "sirena", + "siringa", + "sistema", + "sito", + "smalto", + "smentire", + "smontare", + "soccorso", + "socio", + "soffitto", + "software", + "soggetto", + "sogliola", + "sognare", + "soldi", + "sole", + "sollievo", + "solo", + "sommario", + "sondare", + "sonno", + "sorpresa", + "sorriso", + "sospiro", + "sostegno", + "sovrano", + "spaccare", + "spada", + "spagnolo", + "spalla", + "sparire", + "spavento", + "spazio", + "specchio", + "spedire", + "spegnere", + "spendere", + "speranza", + "spessore", + "spezzare", + "spiaggia", + "spiccare", + "spiegare", + "spiffero", + "spingere", + "sponda", + "sporcare", + "spostare", + "spremuta", + "spugna", + "spumante", + "spuntare", + "squadra", + "squillo", + "staccare", + "stadio", + "stagione", + "stallone", + "stampa", + "stancare", + "starnuto", + "statura", + "stella", + "stendere", + "sterzo", + "stilista", + "stimolo", + "stinco", + "stiva", + "stoffa", + "storia", + "strada", + "stregone", + "striscia", + "studiare", + "stufa", + "stupendo", + "subire", + "successo", + "sudare", + "suono", + "superare", + "supporto", + "surfista", + "sussurro", + "svelto", + "svenire", + "sviluppo", + "svolta", + "svuotare", + "tabacco", + "tabella", + "tabu", + "tacchino", + "tacere", + "taglio", + "talento", + "tangente", + "tappeto", + "tartufo", + "tassello", + "tastiera", + "tavolo", + "tazza", + "teatro", + "tedesco", + "telaio", + "telefono", + "tema", + "temere", + "tempo", + "tendenza", + "tenebre", + "tensione", + "tentare", + "teologia", + "teorema", + "termica", + "terrazzo", + "teschio", + "tesi", + "tesoro", + "tessera", + "testa", + "thriller", + "tifoso", + "tigre", + "timbrare", + "timido", + "tinta", + "tirare", + "tisana", + "titano", + "titolo", + "toccare", + "togliere", + "topolino", + "torcia", + "torrente", + "tovaglia", + "traffico", + "tragitto", + "training", + "tramonto", + "transito", + "trapezio", + "trasloco", + "trattore", + "trazione", + "treccia", + "tregua", + "treno", + "triciclo", + "tridente", + "trilogia", + "tromba", + "troncare", + "trota", + "trovare", + "trucco", + "tubo", + "tulipano", + "tumulto", + "tunisia", + "tuono", + "turista", + "tuta", + "tutelare", + "tutore", + "ubriaco", + "uccello", + "udienza", + "udito", + "uffa", + "umanoide", + "umore", + "unghia", + "unguento", + "unicorno", + "unione", + "universo", + "uomo", + "uragano", + "uranio", + "urlare", + "uscire", + "utente", + "utilizzo", + "vacanza", + "vacca", + "vaglio", + "vagonata", + "valle", + "valore", + "valutare", + "valvola", + "vampiro", + "vaniglia", + "vanto", + "vapore", + "variante", + "vasca", + "vaselina", + "vassoio", + "vedere", + "vegetale", + "veglia", + "veicolo", + "vela", + "veleno", + "velivolo", + "velluto", + "vendere", + "venerare", + "venire", + "vento", + "veranda", + "verbo", + "verdura", + "vergine", + "verifica", + "vernice", + "vero", + "verruca", + "versare", + "vertebra", + "vescica", + "vespaio", + "vestito", + "vesuvio", + "veterano", + "vetro", + "vetta", + "viadotto", + "viaggio", + "vibrare", + "vicenda", + "vichingo", + "vietare", + "vigilare", + "vigneto", + "villa", + "vincere", + "violino", + "vipera", + "virgola", + "virtuoso", + "visita", + "vita", + "vitello", + "vittima", + "vivavoce", + "vivere", + "viziato", + "voglia", + "volare", + "volpe", + "volto", + "volume", + "vongole", + "voragine", + "vortice", + "votare", + "vulcano", + "vuotare", + "zabaione", + "zaffiro", + "zainetto", + "zampa", + "zanzara", + "zattera", + "zavorra", + "zenzero", + "zero", + "zingaro", + "zittire", + "zoccolo", + "zolfo", + "zombie", + "zucchero" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/japanese.h b/src/mnemonics/japanese.h index 6213c4976..bef134a18 100644 --- a/src/mnemonics/japanese.h +++ b/src/mnemonics/japanese.h @@ -1,1711 +1,1711 @@ -// Word list originally created by dabura667 and released under The MIT License (MIT) -// -// The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file japanese.h - * - * \brief Japanese word list and map. - */ - -#ifndef JAPANESE_H -#define JAPANESE_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Japanese: public Base - { - public: - Japanese(): Base("日本語", "Japanese", {}, 3) - { - static constexpr const char * const words[NWORDS] = - { - "あいこくしん", - "あいさつ", - "あいだ", - "あおぞら", - "あかちゃん", - "あきる", - "あけがた", - "あける", - "あこがれる", - "あさい", - "あさひ", - "あしあと", - "あじわう", - "あずかる", - "あずき", - "あそぶ", - "あたえる", - "あたためる", - "あたりまえ", - "あたる", - "あつい", - "あつかう", - "あっしゅく", - "あつまり", - "あつめる", - "あてな", - "あてはまる", - "あひる", - "あぶら", - "あぶる", - "あふれる", - "あまい", - "あまど", - "あまやかす", - "あまり", - "あみもの", - "あめりか", - "あやまる", - "あゆむ", - "あらいぐま", - "あらし", - "あらすじ", - "あらためる", - "あらゆる", - "あらわす", - "ありがとう", - "あわせる", - "あわてる", - "あんい", - "あんがい", - "あんこ", - "あんぜん", - "あんてい", - "あんない", - "あんまり", - "いいだす", - "いおん", - "いがい", - "いがく", - "いきおい", - "いきなり", - "いきもの", - "いきる", - "いくじ", - "いくぶん", - "いけばな", - "いけん", - "いこう", - "いこく", - "いこつ", - "いさましい", - "いさん", - "いしき", - "いじゅう", - "いじょう", - "いじわる", - "いずみ", - "いずれ", - "いせい", - "いせえび", - "いせかい", - "いせき", - "いぜん", - "いそうろう", - "いそがしい", - "いだい", - "いだく", - "いたずら", - "いたみ", - "いたりあ", - "いちおう", - "いちじ", - "いちど", - "いちば", - "いちぶ", - "いちりゅう", - "いつか", - "いっしゅん", - "いっせい", - "いっそう", - "いったん", - "いっち", - "いってい", - "いっぽう", - "いてざ", - "いてん", - "いどう", - "いとこ", - "いない", - "いなか", - "いねむり", - "いのち", - "いのる", - "いはつ", - "いばる", - "いはん", - "いびき", - "いひん", - "いふく", - "いへん", - "いほう", - "いみん", - "いもうと", - "いもたれ", - "いもり", - "いやがる", - "いやす", - "いよかん", - "いよく", - "いらい", - "いらすと", - "いりぐち", - "いりょう", - "いれい", - "いれもの", - "いれる", - "いろえんぴつ", - "いわい", - "いわう", - "いわかん", - "いわば", - "いわゆる", - "いんげんまめ", - "いんさつ", - "いんしょう", - "いんよう", - "うえき", - "うえる", - "うおざ", - "うがい", - "うかぶ", - "うかべる", - "うきわ", - "うくらいな", - "うくれれ", - "うけたまわる", - "うけつけ", - "うけとる", - "うけもつ", - "うける", - "うごかす", - "うごく", - "うこん", - "うさぎ", - "うしなう", - "うしろがみ", - "うすい", - "うすぎ", - "うすぐらい", - "うすめる", - "うせつ", - "うちあわせ", - "うちがわ", - "うちき", - "うちゅう", - "うっかり", - "うつくしい", - "うったえる", - "うつる", - "うどん", - "うなぎ", - "うなじ", - "うなずく", - "うなる", - "うねる", - "うのう", - "うぶげ", - "うぶごえ", - "うまれる", - "うめる", - "うもう", - "うやまう", - "うよく", - "うらがえす", - "うらぐち", - "うらない", - "うりあげ", - "うりきれ", - "うるさい", - "うれしい", - "うれゆき", - "うれる", - "うろこ", - "うわき", - "うわさ", - "うんこう", - "うんちん", - "うんてん", - "うんどう", - "えいえん", - "えいが", - "えいきょう", - "えいご", - "えいせい", - "えいぶん", - "えいよう", - "えいわ", - "えおり", - "えがお", - "えがく", - "えきたい", - "えくせる", - "えしゃく", - "えすて", - "えつらん", - "えのぐ", - "えほうまき", - "えほん", - "えまき", - "えもじ", - "えもの", - "えらい", - "えらぶ", - "えりあ", - "えんえん", - "えんかい", - "えんぎ", - "えんげき", - "えんしゅう", - "えんぜつ", - "えんそく", - "えんちょう", - "えんとつ", - "おいかける", - "おいこす", - "おいしい", - "おいつく", - "おうえん", - "おうさま", - "おうじ", - "おうせつ", - "おうたい", - "おうふく", - "おうべい", - "おうよう", - "おえる", - "おおい", - "おおう", - "おおどおり", - "おおや", - "おおよそ", - "おかえり", - "おかず", - "おがむ", - "おかわり", - "おぎなう", - "おきる", - "おくさま", - "おくじょう", - "おくりがな", - "おくる", - "おくれる", - "おこす", - "おこなう", - "おこる", - "おさえる", - "おさない", - "おさめる", - "おしいれ", - "おしえる", - "おじぎ", - "おじさん", - "おしゃれ", - "おそらく", - "おそわる", - "おたがい", - "おたく", - "おだやか", - "おちつく", - "おっと", - "おつり", - "おでかけ", - "おとしもの", - "おとなしい", - "おどり", - "おどろかす", - "おばさん", - "おまいり", - "おめでとう", - "おもいで", - "おもう", - "おもたい", - "おもちゃ", - "おやつ", - "おやゆび", - "およぼす", - "おらんだ", - "おろす", - "おんがく", - "おんけい", - "おんしゃ", - "おんせん", - "おんだん", - "おんちゅう", - "おんどけい", - "かあつ", - "かいが", - "がいき", - "がいけん", - "がいこう", - "かいさつ", - "かいしゃ", - "かいすいよく", - "かいぜん", - "かいぞうど", - "かいつう", - "かいてん", - "かいとう", - "かいふく", - "がいへき", - "かいほう", - "かいよう", - "がいらい", - "かいわ", - "かえる", - "かおり", - "かかえる", - "かがく", - "かがし", - "かがみ", - "かくご", - "かくとく", - "かざる", - "がぞう", - "かたい", - "かたち", - "がちょう", - "がっきゅう", - "がっこう", - "がっさん", - "がっしょう", - "かなざわし", - "かのう", - "がはく", - "かぶか", - "かほう", - "かほご", - "かまう", - "かまぼこ", - "かめれおん", - "かゆい", - "かようび", - "からい", - "かるい", - "かろう", - "かわく", - "かわら", - "がんか", - "かんけい", - "かんこう", - "かんしゃ", - "かんそう", - "かんたん", - "かんち", - "がんばる", - "きあい", - "きあつ", - "きいろ", - "ぎいん", - "きうい", - "きうん", - "きえる", - "きおう", - "きおく", - "きおち", - "きおん", - "きかい", - "きかく", - "きかんしゃ", - "ききて", - "きくばり", - "きくらげ", - "きけんせい", - "きこう", - "きこえる", - "きこく", - "きさい", - "きさく", - "きさま", - "きさらぎ", - "ぎじかがく", - "ぎしき", - "ぎじたいけん", - "ぎじにってい", - "ぎじゅつしゃ", - "きすう", - "きせい", - "きせき", - "きせつ", - "きそう", - "きぞく", - "きぞん", - "きたえる", - "きちょう", - "きつえん", - "ぎっちり", - "きつつき", - "きつね", - "きてい", - "きどう", - "きどく", - "きない", - "きなが", - "きなこ", - "きぬごし", - "きねん", - "きのう", - "きのした", - "きはく", - "きびしい", - "きひん", - "きふく", - "きぶん", - "きぼう", - "きほん", - "きまる", - "きみつ", - "きむずかしい", - "きめる", - "きもだめし", - "きもち", - "きもの", - "きゃく", - "きやく", - "ぎゅうにく", - "きよう", - "きょうりゅう", - "きらい", - "きらく", - "きりん", - "きれい", - "きれつ", - "きろく", - "ぎろん", - "きわめる", - "ぎんいろ", - "きんかくじ", - "きんじょ", - "きんようび", - "ぐあい", - "くいず", - "くうかん", - "くうき", - "くうぐん", - "くうこう", - "ぐうせい", - "くうそう", - "ぐうたら", - "くうふく", - "くうぼ", - "くかん", - "くきょう", - "くげん", - "ぐこう", - "くさい", - "くさき", - "くさばな", - "くさる", - "くしゃみ", - "くしょう", - "くすのき", - "くすりゆび", - "くせげ", - "くせん", - "ぐたいてき", - "くださる", - "くたびれる", - "くちこみ", - "くちさき", - "くつした", - "ぐっすり", - "くつろぐ", - "くとうてん", - "くどく", - "くなん", - "くねくね", - "くのう", - "くふう", - "くみあわせ", - "くみたてる", - "くめる", - "くやくしょ", - "くらす", - "くらべる", - "くるま", - "くれる", - "くろう", - "くわしい", - "ぐんかん", - "ぐんしょく", - "ぐんたい", - "ぐんて", - "けあな", - "けいかく", - "けいけん", - "けいこ", - "けいさつ", - "げいじゅつ", - "けいたい", - "げいのうじん", - "けいれき", - "けいろ", - "けおとす", - "けおりもの", - "げきか", - "げきげん", - "げきだん", - "げきちん", - "げきとつ", - "げきは", - "げきやく", - "げこう", - "げこくじょう", - "げざい", - "けさき", - "げざん", - "けしき", - "けしごむ", - "けしょう", - "げすと", - "けたば", - "けちゃっぷ", - "けちらす", - "けつあつ", - "けつい", - "けつえき", - "けっこん", - "けつじょ", - "けっせき", - "けってい", - "けつまつ", - "げつようび", - "げつれい", - "けつろん", - "げどく", - "けとばす", - "けとる", - "けなげ", - "けなす", - "けなみ", - "けぬき", - "げねつ", - "けねん", - "けはい", - "げひん", - "けぶかい", - "げぼく", - "けまり", - "けみかる", - "けむし", - "けむり", - "けもの", - "けらい", - "けろけろ", - "けわしい", - "けんい", - "けんえつ", - "けんお", - "けんか", - "げんき", - "けんげん", - "けんこう", - "けんさく", - "けんしゅう", - "けんすう", - "げんそう", - "けんちく", - "けんてい", - "けんとう", - "けんない", - "けんにん", - "げんぶつ", - "けんま", - "けんみん", - "けんめい", - "けんらん", - "けんり", - "こあくま", - "こいぬ", - "こいびと", - "ごうい", - "こうえん", - "こうおん", - "こうかん", - "ごうきゅう", - "ごうけい", - "こうこう", - "こうさい", - "こうじ", - "こうすい", - "ごうせい", - "こうそく", - "こうたい", - "こうちゃ", - "こうつう", - "こうてい", - "こうどう", - "こうない", - "こうはい", - "ごうほう", - "ごうまん", - "こうもく", - "こうりつ", - "こえる", - "こおり", - "ごかい", - "ごがつ", - "ごかん", - "こくご", - "こくさい", - "こくとう", - "こくない", - "こくはく", - "こぐま", - "こけい", - "こける", - "ここのか", - "こころ", - "こさめ", - "こしつ", - "こすう", - "こせい", - "こせき", - "こぜん", - "こそだて", - "こたい", - "こたえる", - "こたつ", - "こちょう", - "こっか", - "こつこつ", - "こつばん", - "こつぶ", - "こてい", - "こてん", - "ことがら", - "ことし", - "ことば", - "ことり", - "こなごな", - "こねこね", - "このまま", - "このみ", - "このよ", - "ごはん", - "こひつじ", - "こふう", - "こふん", - "こぼれる", - "ごまあぶら", - "こまかい", - "ごますり", - "こまつな", - "こまる", - "こむぎこ", - "こもじ", - "こもち", - "こもの", - "こもん", - "こやく", - "こやま", - "こゆう", - "こゆび", - "こよい", - "こよう", - "こりる", - "これくしょん", - "ころっけ", - "こわもて", - "こわれる", - "こんいん", - "こんかい", - "こんき", - "こんしゅう", - "こんすい", - "こんだて", - "こんとん", - "こんなん", - "こんびに", - "こんぽん", - "こんまけ", - "こんや", - "こんれい", - "こんわく", - "ざいえき", - "さいかい", - "さいきん", - "ざいげん", - "ざいこ", - "さいしょ", - "さいせい", - "ざいたく", - "ざいちゅう", - "さいてき", - "ざいりょう", - "さうな", - "さかいし", - "さがす", - "さかな", - "さかみち", - "さがる", - "さぎょう", - "さくし", - "さくひん", - "さくら", - "さこく", - "さこつ", - "さずかる", - "ざせき", - "さたん", - "さつえい", - "ざつおん", - "ざっか", - "ざつがく", - "さっきょく", - "ざっし", - "さつじん", - "ざっそう", - "さつたば", - "さつまいも", - "さてい", - "さといも", - "さとう", - "さとおや", - "さとし", - "さとる", - "さのう", - "さばく", - "さびしい", - "さべつ", - "さほう", - "さほど", - "さます", - "さみしい", - "さみだれ", - "さむけ", - "さめる", - "さやえんどう", - "さゆう", - "さよう", - "さよく", - "さらだ", - "ざるそば", - "さわやか", - "さわる", - "さんいん", - "さんか", - "さんきゃく", - "さんこう", - "さんさい", - "ざんしょ", - "さんすう", - "さんせい", - "さんそ", - "さんち", - "さんま", - "さんみ", - "さんらん", - "しあい", - "しあげ", - "しあさって", - "しあわせ", - "しいく", - "しいん", - "しうち", - "しえい", - "しおけ", - "しかい", - "しかく", - "じかん", - "しごと", - "しすう", - "じだい", - "したうけ", - "したぎ", - "したて", - "したみ", - "しちょう", - "しちりん", - "しっかり", - "しつじ", - "しつもん", - "してい", - "してき", - "してつ", - "じてん", - "じどう", - "しなぎれ", - "しなもの", - "しなん", - "しねま", - "しねん", - "しのぐ", - "しのぶ", - "しはい", - "しばかり", - "しはつ", - "しはらい", - "しはん", - "しひょう", - "しふく", - "じぶん", - "しへい", - "しほう", - "しほん", - "しまう", - "しまる", - "しみん", - "しむける", - "じむしょ", - "しめい", - "しめる", - "しもん", - "しゃいん", - "しゃうん", - "しゃおん", - "じゃがいも", - "しやくしょ", - "しゃくほう", - "しゃけん", - "しゃこ", - "しゃざい", - "しゃしん", - "しゃせん", - "しゃそう", - "しゃたい", - "しゃちょう", - "しゃっきん", - "じゃま", - "しゃりん", - "しゃれい", - "じゆう", - "じゅうしょ", - "しゅくはく", - "じゅしん", - "しゅっせき", - "しゅみ", - "しゅらば", - "じゅんばん", - "しょうかい", - "しょくたく", - "しょっけん", - "しょどう", - "しょもつ", - "しらせる", - "しらべる", - "しんか", - "しんこう", - "じんじゃ", - "しんせいじ", - "しんちく", - "しんりん", - "すあげ", - "すあし", - "すあな", - "ずあん", - "すいえい", - "すいか", - "すいとう", - "ずいぶん", - "すいようび", - "すうがく", - "すうじつ", - "すうせん", - "すおどり", - "すきま", - "すくう", - "すくない", - "すける", - "すごい", - "すこし", - "ずさん", - "すずしい", - "すすむ", - "すすめる", - "すっかり", - "ずっしり", - "ずっと", - "すてき", - "すてる", - "すねる", - "すのこ", - "すはだ", - "すばらしい", - "ずひょう", - "ずぶぬれ", - "すぶり", - "すふれ", - "すべて", - "すべる", - "ずほう", - "すぼん", - "すまい", - "すめし", - "すもう", - "すやき", - "すらすら", - "するめ", - "すれちがう", - "すろっと", - "すわる", - "すんぜん", - "すんぽう", - "せあぶら", - "せいかつ", - "せいげん", - "せいじ", - "せいよう", - "せおう", - "せかいかん", - "せきにん", - "せきむ", - "せきゆ", - "せきらんうん", - "せけん", - "せこう", - "せすじ", - "せたい", - "せたけ", - "せっかく", - "せっきゃく", - "ぜっく", - "せっけん", - "せっこつ", - "せっさたくま", - "せつぞく", - "せつだん", - "せつでん", - "せっぱん", - "せつび", - "せつぶん", - "せつめい", - "せつりつ", - "せなか", - "せのび", - "せはば", - "せびろ", - "せぼね", - "せまい", - "せまる", - "せめる", - "せもたれ", - "せりふ", - "ぜんあく", - "せんい", - "せんえい", - "せんか", - "せんきょ", - "せんく", - "せんげん", - "ぜんご", - "せんさい", - "せんしゅ", - "せんすい", - "せんせい", - "せんぞ", - "せんたく", - "せんちょう", - "せんてい", - "せんとう", - "せんぬき", - "せんねん", - "せんぱい", - "ぜんぶ", - "ぜんぽう", - "せんむ", - "せんめんじょ", - "せんもん", - "せんやく", - "せんゆう", - "せんよう", - "ぜんら", - "ぜんりゃく", - "せんれい", - "せんろ", - "そあく", - "そいとげる", - "そいね", - "そうがんきょう", - "そうき", - "そうご", - "そうしん", - "そうだん", - "そうなん", - "そうび", - "そうめん", - "そうり", - "そえもの", - "そえん", - "そがい", - "そげき", - "そこう", - "そこそこ", - "そざい", - "そしな", - "そせい", - "そせん", - "そそぐ", - "そだてる", - "そつう", - "そつえん", - "そっかん", - "そつぎょう", - "そっけつ", - "そっこう", - "そっせん", - "そっと", - "そとがわ", - "そとづら", - "そなえる", - "そなた", - "そふぼ", - "そぼく", - "そぼろ", - "そまつ", - "そまる", - "そむく", - "そむりえ", - "そめる", - "そもそも", - "そよかぜ", - "そらまめ", - "そろう", - "そんかい", - "そんけい", - "そんざい", - "そんしつ", - "そんぞく", - "そんちょう", - "ぞんび", - "ぞんぶん", - "そんみん", - "たあい", - "たいいん", - "たいうん", - "たいえき", - "たいおう", - "だいがく", - "たいき", - "たいぐう", - "たいけん", - "たいこ", - "たいざい", - "だいじょうぶ", - "だいすき", - "たいせつ", - "たいそう", - "だいたい", - "たいちょう", - "たいてい", - "だいどころ", - "たいない", - "たいねつ", - "たいのう", - "たいはん", - "だいひょう", - "たいふう", - "たいへん", - "たいほ", - "たいまつばな", - "たいみんぐ", - "たいむ", - "たいめん", - "たいやき", - "たいよう", - "たいら", - "たいりょく", - "たいる", - "たいわん", - "たうえ", - "たえる", - "たおす", - "たおる", - "たおれる", - "たかい", - "たかね", - "たきび", - "たくさん", - "たこく", - "たこやき", - "たさい", - "たしざん", - "だじゃれ", - "たすける", - "たずさわる", - "たそがれ", - "たたかう", - "たたく", - "ただしい", - "たたみ", - "たちばな", - "だっかい", - "だっきゃく", - "だっこ", - "だっしゅつ", - "だったい", - "たてる", - "たとえる", - "たなばた", - "たにん", - "たぬき", - "たのしみ", - "たはつ", - "たぶん", - "たべる", - "たぼう", - "たまご", - "たまる", - "だむる", - "ためいき", - "ためす", - "ためる", - "たもつ", - "たやすい", - "たよる", - "たらす", - "たりきほんがん", - "たりょう", - "たりる", - "たると", - "たれる", - "たれんと", - "たろっと", - "たわむれる", - "だんあつ", - "たんい", - "たんおん", - "たんか", - "たんき", - "たんけん", - "たんご", - "たんさん", - "たんじょうび", - "だんせい", - "たんそく", - "たんたい", - "だんち", - "たんてい", - "たんとう", - "だんな", - "たんにん", - "だんねつ", - "たんのう", - "たんぴん", - "だんぼう", - "たんまつ", - "たんめい", - "だんれつ", - "だんろ", - "だんわ", - "ちあい", - "ちあん", - "ちいき", - "ちいさい", - "ちえん", - "ちかい", - "ちから", - "ちきゅう", - "ちきん", - "ちけいず", - "ちけん", - "ちこく", - "ちさい", - "ちしき", - "ちしりょう", - "ちせい", - "ちそう", - "ちたい", - "ちたん", - "ちちおや", - "ちつじょ", - "ちてき", - "ちてん", - "ちぬき", - "ちぬり", - "ちのう", - "ちひょう", - "ちへいせん", - "ちほう", - "ちまた", - "ちみつ", - "ちみどろ", - "ちめいど", - "ちゃんこなべ", - "ちゅうい", - "ちゆりょく", - "ちょうし", - "ちょさくけん", - "ちらし", - "ちらみ", - "ちりがみ", - "ちりょう", - "ちるど", - "ちわわ", - "ちんたい", - "ちんもく", - "ついか", - "ついたち", - "つうか", - "つうじょう", - "つうはん", - "つうわ", - "つかう", - "つかれる", - "つくね", - "つくる", - "つけね", - "つける", - "つごう", - "つたえる", - "つづく", - "つつじ", - "つつむ", - "つとめる", - "つながる", - "つなみ", - "つねづね", - "つのる", - "つぶす", - "つまらない", - "つまる", - "つみき", - "つめたい", - "つもり", - "つもる", - "つよい", - "つるぼ", - "つるみく", - "つわもの", - "つわり", - "てあし", - "てあて", - "てあみ", - "ていおん", - "ていか", - "ていき", - "ていけい", - "ていこく", - "ていさつ", - "ていし", - "ていせい", - "ていたい", - "ていど", - "ていねい", - "ていひょう", - "ていへん", - "ていぼう", - "てうち", - "ておくれ", - "てきとう", - "てくび", - "でこぼこ", - "てさぎょう", - "てさげ", - "てすり", - "てそう", - "てちがい", - "てちょう", - "てつがく", - "てつづき", - "でっぱ", - "てつぼう", - "てつや", - "でぬかえ", - "てぬき", - "てぬぐい", - "てのひら", - "てはい", - "てぶくろ", - "てふだ", - "てほどき", - "てほん", - "てまえ", - "てまきずし", - "てみじか", - "てみやげ", - "てらす", - "てれび", - "てわけ", - "てわたし", - "でんあつ", - "てんいん", - "てんかい", - "てんき", - "てんぐ", - "てんけん", - "てんごく", - "てんさい", - "てんし", - "てんすう", - "でんち", - "てんてき", - "てんとう", - "てんない", - "てんぷら", - "てんぼうだい", - "てんめつ", - "てんらんかい", - "でんりょく", - "でんわ", - "どあい", - "といれ", - "どうかん", - "とうきゅう", - "どうぐ", - "とうし", - "とうむぎ", - "とおい", - "とおか", - "とおく", - "とおす", - "とおる", - "とかい", - "とかす", - "ときおり", - "ときどき", - "とくい", - "とくしゅう", - "とくてん", - "とくに", - "とくべつ", - "とけい", - "とける", - "とこや", - "とさか", - "としょかん", - "とそう", - "とたん", - "とちゅう", - "とっきゅう", - "とっくん", - "とつぜん", - "とつにゅう", - "とどける", - "ととのえる", - "とない", - "となえる", - "となり", - "とのさま", - "とばす", - "どぶがわ", - "とほう", - "とまる", - "とめる", - "ともだち", - "ともる", - "どようび", - "とらえる", - "とんかつ", - "どんぶり", - "ないかく", - "ないこう", - "ないしょ", - "ないす", - "ないせん", - "ないそう", - "なおす", - "ながい", - "なくす", - "なげる", - "なこうど", - "なさけ", - "なたでここ", - "なっとう", - "なつやすみ", - "ななおし", - "なにごと", - "なにもの", - "なにわ", - "なのか", - "なふだ", - "なまいき", - "なまえ", - "なまみ", - "なみだ", - "なめらか", - "なめる", - "なやむ", - "ならう", - "ならび", - "ならぶ", - "なれる", - "なわとび", - "なわばり", - "にあう", - "にいがた", - "にうけ", - "におい", - "にかい", - "にがて", - "にきび", - "にくしみ", - "にくまん", - "にげる", - "にさんかたんそ", - "にしき", - "にせもの", - "にちじょう", - "にちようび", - "にっか", - "にっき", - "にっけい", - "にっこう", - "にっさん", - "にっしょく", - "にっすう", - "にっせき", - "にってい", - "になう", - "にほん", - "にまめ", - "にもつ", - "にやり", - "にゅういん", - "にりんしゃ", - "にわとり", - "にんい", - "にんか", - "にんき", - "にんげん", - "にんしき", - "にんずう", - "にんそう", - "にんたい", - "にんち", - "にんてい", - "にんにく", - "にんぷ", - "にんまり", - "にんむ", - "にんめい", - "にんよう", - "ぬいくぎ", - "ぬかす", - "ぬぐいとる", - "ぬぐう", - "ぬくもり", - "ぬすむ", - "ぬまえび", - "ぬめり", - "ぬらす", - "ぬんちゃく", - "ねあげ", - "ねいき", - "ねいる", - "ねいろ", - "ねぐせ", - "ねくたい", - "ねくら", - "ねこぜ", - "ねこむ", - "ねさげ", - "ねすごす", - "ねそべる", - "ねだん", - "ねつい", - "ねっしん", - "ねつぞう", - "ねったいぎょ", - "ねぶそく", - "ねふだ", - "ねぼう", - "ねほりはほり", - "ねまき", - "ねまわし", - "ねみみ", - "ねむい", - "ねむたい", - "ねもと", - "ねらう", - "ねわざ", - "ねんいり", - "ねんおし", - "ねんかん", - "ねんきん", - "ねんぐ", - "ねんざ", - "ねんし", - "ねんちゃく", - "ねんど", - "ねんぴ", - "ねんぶつ", - "ねんまつ", - "ねんりょう", - "ねんれい", - "のいず", - "のおづま", - "のがす", - "のきなみ", - "のこぎり", - "のこす", - "のこる", - "のせる", - "のぞく", - "のぞむ", - "のたまう", - "のちほど", - "のっく", - "のばす", - "のはら", - "のべる", - "のぼる", - "のみもの", - "のやま", - "のらいぬ", - "のらねこ", - "のりもの", - "のりゆき", - "のれん", - "のんき", - "ばあい", - "はあく", - "ばあさん", - "ばいか", - "ばいく", - "はいけん", - "はいご", - "はいしん", - "はいすい", - "はいせん", - "はいそう", - "はいち", - "ばいばい", - "はいれつ", - "はえる", - "はおる", - "はかい", - "ばかり", - "はかる", - "はくしゅ", - "はけん", - "はこぶ", - "はさみ", - "はさん", - "はしご", - "ばしょ", - "はしる", - "はせる", - "ぱそこん", - "はそん", - "はたん", - "はちみつ", - "はつおん", - "はっかく", - "はづき", - "はっきり", - "はっくつ", - "はっけん", - "はっこう", - "はっさん", - "はっしん", - "はったつ", - "はっちゅう", - "はってん", - "はっぴょう", - "はっぽう", - "はなす", - "はなび", - "はにかむ", - "はぶらし", - "はみがき", - "はむかう", - "はめつ", - "はやい", - "はやし", - "はらう", - "はろうぃん", - "はわい", - "はんい", - "はんえい", - "はんおん", - "はんかく", - "はんきょう", - "ばんぐみ", - "はんこ", - "はんしゃ", - "はんすう", - "はんだん", - "ぱんち", - "ぱんつ", - "はんてい", - "はんとし", - "はんのう", - "はんぱ", - "はんぶん", - "はんぺん", - "はんぼうき", - "はんめい", - "はんらん", - "はんろん", - "ひいき", - "ひうん", - "ひえる", - "ひかく", - "ひかり", - "ひかる", - "ひかん", - "ひくい", - "ひけつ", - "ひこうき", - "ひこく", - "ひさい", - "ひさしぶり", - "ひさん", - "びじゅつかん", - "ひしょ" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list originally created by dabura667 and released under The MIT License (MIT) +// +// The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file japanese.h + * + * \brief Japanese word list and map. + */ + +#ifndef JAPANESE_H +#define JAPANESE_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Japanese: public Base + { + public: + Japanese(): Base("日本語", "Japanese", {}, 3) + { + static constexpr const char * const words[NWORDS] = + { + "あいこくしん", + "あいさつ", + "あいだ", + "あおぞら", + "あかちゃん", + "あきる", + "あけがた", + "あける", + "あこがれる", + "あさい", + "あさひ", + "あしあと", + "あじわう", + "あずかる", + "あずき", + "あそぶ", + "あたえる", + "あたためる", + "あたりまえ", + "あたる", + "あつい", + "あつかう", + "あっしゅく", + "あつまり", + "あつめる", + "あてな", + "あてはまる", + "あひる", + "あぶら", + "あぶる", + "あふれる", + "あまい", + "あまど", + "あまやかす", + "あまり", + "あみもの", + "あめりか", + "あやまる", + "あゆむ", + "あらいぐま", + "あらし", + "あらすじ", + "あらためる", + "あらゆる", + "あらわす", + "ありがとう", + "あわせる", + "あわてる", + "あんい", + "あんがい", + "あんこ", + "あんぜん", + "あんてい", + "あんない", + "あんまり", + "いいだす", + "いおん", + "いがい", + "いがく", + "いきおい", + "いきなり", + "いきもの", + "いきる", + "いくじ", + "いくぶん", + "いけばな", + "いけん", + "いこう", + "いこく", + "いこつ", + "いさましい", + "いさん", + "いしき", + "いじゅう", + "いじょう", + "いじわる", + "いずみ", + "いずれ", + "いせい", + "いせえび", + "いせかい", + "いせき", + "いぜん", + "いそうろう", + "いそがしい", + "いだい", + "いだく", + "いたずら", + "いたみ", + "いたりあ", + "いちおう", + "いちじ", + "いちど", + "いちば", + "いちぶ", + "いちりゅう", + "いつか", + "いっしゅん", + "いっせい", + "いっそう", + "いったん", + "いっち", + "いってい", + "いっぽう", + "いてざ", + "いてん", + "いどう", + "いとこ", + "いない", + "いなか", + "いねむり", + "いのち", + "いのる", + "いはつ", + "いばる", + "いはん", + "いびき", + "いひん", + "いふく", + "いへん", + "いほう", + "いみん", + "いもうと", + "いもたれ", + "いもり", + "いやがる", + "いやす", + "いよかん", + "いよく", + "いらい", + "いらすと", + "いりぐち", + "いりょう", + "いれい", + "いれもの", + "いれる", + "いろえんぴつ", + "いわい", + "いわう", + "いわかん", + "いわば", + "いわゆる", + "いんげんまめ", + "いんさつ", + "いんしょう", + "いんよう", + "うえき", + "うえる", + "うおざ", + "うがい", + "うかぶ", + "うかべる", + "うきわ", + "うくらいな", + "うくれれ", + "うけたまわる", + "うけつけ", + "うけとる", + "うけもつ", + "うける", + "うごかす", + "うごく", + "うこん", + "うさぎ", + "うしなう", + "うしろがみ", + "うすい", + "うすぎ", + "うすぐらい", + "うすめる", + "うせつ", + "うちあわせ", + "うちがわ", + "うちき", + "うちゅう", + "うっかり", + "うつくしい", + "うったえる", + "うつる", + "うどん", + "うなぎ", + "うなじ", + "うなずく", + "うなる", + "うねる", + "うのう", + "うぶげ", + "うぶごえ", + "うまれる", + "うめる", + "うもう", + "うやまう", + "うよく", + "うらがえす", + "うらぐち", + "うらない", + "うりあげ", + "うりきれ", + "うるさい", + "うれしい", + "うれゆき", + "うれる", + "うろこ", + "うわき", + "うわさ", + "うんこう", + "うんちん", + "うんてん", + "うんどう", + "えいえん", + "えいが", + "えいきょう", + "えいご", + "えいせい", + "えいぶん", + "えいよう", + "えいわ", + "えおり", + "えがお", + "えがく", + "えきたい", + "えくせる", + "えしゃく", + "えすて", + "えつらん", + "えのぐ", + "えほうまき", + "えほん", + "えまき", + "えもじ", + "えもの", + "えらい", + "えらぶ", + "えりあ", + "えんえん", + "えんかい", + "えんぎ", + "えんげき", + "えんしゅう", + "えんぜつ", + "えんそく", + "えんちょう", + "えんとつ", + "おいかける", + "おいこす", + "おいしい", + "おいつく", + "おうえん", + "おうさま", + "おうじ", + "おうせつ", + "おうたい", + "おうふく", + "おうべい", + "おうよう", + "おえる", + "おおい", + "おおう", + "おおどおり", + "おおや", + "おおよそ", + "おかえり", + "おかず", + "おがむ", + "おかわり", + "おぎなう", + "おきる", + "おくさま", + "おくじょう", + "おくりがな", + "おくる", + "おくれる", + "おこす", + "おこなう", + "おこる", + "おさえる", + "おさない", + "おさめる", + "おしいれ", + "おしえる", + "おじぎ", + "おじさん", + "おしゃれ", + "おそらく", + "おそわる", + "おたがい", + "おたく", + "おだやか", + "おちつく", + "おっと", + "おつり", + "おでかけ", + "おとしもの", + "おとなしい", + "おどり", + "おどろかす", + "おばさん", + "おまいり", + "おめでとう", + "おもいで", + "おもう", + "おもたい", + "おもちゃ", + "おやつ", + "おやゆび", + "およぼす", + "おらんだ", + "おろす", + "おんがく", + "おんけい", + "おんしゃ", + "おんせん", + "おんだん", + "おんちゅう", + "おんどけい", + "かあつ", + "かいが", + "がいき", + "がいけん", + "がいこう", + "かいさつ", + "かいしゃ", + "かいすいよく", + "かいぜん", + "かいぞうど", + "かいつう", + "かいてん", + "かいとう", + "かいふく", + "がいへき", + "かいほう", + "かいよう", + "がいらい", + "かいわ", + "かえる", + "かおり", + "かかえる", + "かがく", + "かがし", + "かがみ", + "かくご", + "かくとく", + "かざる", + "がぞう", + "かたい", + "かたち", + "がちょう", + "がっきゅう", + "がっこう", + "がっさん", + "がっしょう", + "かなざわし", + "かのう", + "がはく", + "かぶか", + "かほう", + "かほご", + "かまう", + "かまぼこ", + "かめれおん", + "かゆい", + "かようび", + "からい", + "かるい", + "かろう", + "かわく", + "かわら", + "がんか", + "かんけい", + "かんこう", + "かんしゃ", + "かんそう", + "かんたん", + "かんち", + "がんばる", + "きあい", + "きあつ", + "きいろ", + "ぎいん", + "きうい", + "きうん", + "きえる", + "きおう", + "きおく", + "きおち", + "きおん", + "きかい", + "きかく", + "きかんしゃ", + "ききて", + "きくばり", + "きくらげ", + "きけんせい", + "きこう", + "きこえる", + "きこく", + "きさい", + "きさく", + "きさま", + "きさらぎ", + "ぎじかがく", + "ぎしき", + "ぎじたいけん", + "ぎじにってい", + "ぎじゅつしゃ", + "きすう", + "きせい", + "きせき", + "きせつ", + "きそう", + "きぞく", + "きぞん", + "きたえる", + "きちょう", + "きつえん", + "ぎっちり", + "きつつき", + "きつね", + "きてい", + "きどう", + "きどく", + "きない", + "きなが", + "きなこ", + "きぬごし", + "きねん", + "きのう", + "きのした", + "きはく", + "きびしい", + "きひん", + "きふく", + "きぶん", + "きぼう", + "きほん", + "きまる", + "きみつ", + "きむずかしい", + "きめる", + "きもだめし", + "きもち", + "きもの", + "きゃく", + "きやく", + "ぎゅうにく", + "きよう", + "きょうりゅう", + "きらい", + "きらく", + "きりん", + "きれい", + "きれつ", + "きろく", + "ぎろん", + "きわめる", + "ぎんいろ", + "きんかくじ", + "きんじょ", + "きんようび", + "ぐあい", + "くいず", + "くうかん", + "くうき", + "くうぐん", + "くうこう", + "ぐうせい", + "くうそう", + "ぐうたら", + "くうふく", + "くうぼ", + "くかん", + "くきょう", + "くげん", + "ぐこう", + "くさい", + "くさき", + "くさばな", + "くさる", + "くしゃみ", + "くしょう", + "くすのき", + "くすりゆび", + "くせげ", + "くせん", + "ぐたいてき", + "くださる", + "くたびれる", + "くちこみ", + "くちさき", + "くつした", + "ぐっすり", + "くつろぐ", + "くとうてん", + "くどく", + "くなん", + "くねくね", + "くのう", + "くふう", + "くみあわせ", + "くみたてる", + "くめる", + "くやくしょ", + "くらす", + "くらべる", + "くるま", + "くれる", + "くろう", + "くわしい", + "ぐんかん", + "ぐんしょく", + "ぐんたい", + "ぐんて", + "けあな", + "けいかく", + "けいけん", + "けいこ", + "けいさつ", + "げいじゅつ", + "けいたい", + "げいのうじん", + "けいれき", + "けいろ", + "けおとす", + "けおりもの", + "げきか", + "げきげん", + "げきだん", + "げきちん", + "げきとつ", + "げきは", + "げきやく", + "げこう", + "げこくじょう", + "げざい", + "けさき", + "げざん", + "けしき", + "けしごむ", + "けしょう", + "げすと", + "けたば", + "けちゃっぷ", + "けちらす", + "けつあつ", + "けつい", + "けつえき", + "けっこん", + "けつじょ", + "けっせき", + "けってい", + "けつまつ", + "げつようび", + "げつれい", + "けつろん", + "げどく", + "けとばす", + "けとる", + "けなげ", + "けなす", + "けなみ", + "けぬき", + "げねつ", + "けねん", + "けはい", + "げひん", + "けぶかい", + "げぼく", + "けまり", + "けみかる", + "けむし", + "けむり", + "けもの", + "けらい", + "けろけろ", + "けわしい", + "けんい", + "けんえつ", + "けんお", + "けんか", + "げんき", + "けんげん", + "けんこう", + "けんさく", + "けんしゅう", + "けんすう", + "げんそう", + "けんちく", + "けんてい", + "けんとう", + "けんない", + "けんにん", + "げんぶつ", + "けんま", + "けんみん", + "けんめい", + "けんらん", + "けんり", + "こあくま", + "こいぬ", + "こいびと", + "ごうい", + "こうえん", + "こうおん", + "こうかん", + "ごうきゅう", + "ごうけい", + "こうこう", + "こうさい", + "こうじ", + "こうすい", + "ごうせい", + "こうそく", + "こうたい", + "こうちゃ", + "こうつう", + "こうてい", + "こうどう", + "こうない", + "こうはい", + "ごうほう", + "ごうまん", + "こうもく", + "こうりつ", + "こえる", + "こおり", + "ごかい", + "ごがつ", + "ごかん", + "こくご", + "こくさい", + "こくとう", + "こくない", + "こくはく", + "こぐま", + "こけい", + "こける", + "ここのか", + "こころ", + "こさめ", + "こしつ", + "こすう", + "こせい", + "こせき", + "こぜん", + "こそだて", + "こたい", + "こたえる", + "こたつ", + "こちょう", + "こっか", + "こつこつ", + "こつばん", + "こつぶ", + "こてい", + "こてん", + "ことがら", + "ことし", + "ことば", + "ことり", + "こなごな", + "こねこね", + "このまま", + "このみ", + "このよ", + "ごはん", + "こひつじ", + "こふう", + "こふん", + "こぼれる", + "ごまあぶら", + "こまかい", + "ごますり", + "こまつな", + "こまる", + "こむぎこ", + "こもじ", + "こもち", + "こもの", + "こもん", + "こやく", + "こやま", + "こゆう", + "こゆび", + "こよい", + "こよう", + "こりる", + "これくしょん", + "ころっけ", + "こわもて", + "こわれる", + "こんいん", + "こんかい", + "こんき", + "こんしゅう", + "こんすい", + "こんだて", + "こんとん", + "こんなん", + "こんびに", + "こんぽん", + "こんまけ", + "こんや", + "こんれい", + "こんわく", + "ざいえき", + "さいかい", + "さいきん", + "ざいげん", + "ざいこ", + "さいしょ", + "さいせい", + "ざいたく", + "ざいちゅう", + "さいてき", + "ざいりょう", + "さうな", + "さかいし", + "さがす", + "さかな", + "さかみち", + "さがる", + "さぎょう", + "さくし", + "さくひん", + "さくら", + "さこく", + "さこつ", + "さずかる", + "ざせき", + "さたん", + "さつえい", + "ざつおん", + "ざっか", + "ざつがく", + "さっきょく", + "ざっし", + "さつじん", + "ざっそう", + "さつたば", + "さつまいも", + "さてい", + "さといも", + "さとう", + "さとおや", + "さとし", + "さとる", + "さのう", + "さばく", + "さびしい", + "さべつ", + "さほう", + "さほど", + "さます", + "さみしい", + "さみだれ", + "さむけ", + "さめる", + "さやえんどう", + "さゆう", + "さよう", + "さよく", + "さらだ", + "ざるそば", + "さわやか", + "さわる", + "さんいん", + "さんか", + "さんきゃく", + "さんこう", + "さんさい", + "ざんしょ", + "さんすう", + "さんせい", + "さんそ", + "さんち", + "さんま", + "さんみ", + "さんらん", + "しあい", + "しあげ", + "しあさって", + "しあわせ", + "しいく", + "しいん", + "しうち", + "しえい", + "しおけ", + "しかい", + "しかく", + "じかん", + "しごと", + "しすう", + "じだい", + "したうけ", + "したぎ", + "したて", + "したみ", + "しちょう", + "しちりん", + "しっかり", + "しつじ", + "しつもん", + "してい", + "してき", + "してつ", + "じてん", + "じどう", + "しなぎれ", + "しなもの", + "しなん", + "しねま", + "しねん", + "しのぐ", + "しのぶ", + "しはい", + "しばかり", + "しはつ", + "しはらい", + "しはん", + "しひょう", + "しふく", + "じぶん", + "しへい", + "しほう", + "しほん", + "しまう", + "しまる", + "しみん", + "しむける", + "じむしょ", + "しめい", + "しめる", + "しもん", + "しゃいん", + "しゃうん", + "しゃおん", + "じゃがいも", + "しやくしょ", + "しゃくほう", + "しゃけん", + "しゃこ", + "しゃざい", + "しゃしん", + "しゃせん", + "しゃそう", + "しゃたい", + "しゃちょう", + "しゃっきん", + "じゃま", + "しゃりん", + "しゃれい", + "じゆう", + "じゅうしょ", + "しゅくはく", + "じゅしん", + "しゅっせき", + "しゅみ", + "しゅらば", + "じゅんばん", + "しょうかい", + "しょくたく", + "しょっけん", + "しょどう", + "しょもつ", + "しらせる", + "しらべる", + "しんか", + "しんこう", + "じんじゃ", + "しんせいじ", + "しんちく", + "しんりん", + "すあげ", + "すあし", + "すあな", + "ずあん", + "すいえい", + "すいか", + "すいとう", + "ずいぶん", + "すいようび", + "すうがく", + "すうじつ", + "すうせん", + "すおどり", + "すきま", + "すくう", + "すくない", + "すける", + "すごい", + "すこし", + "ずさん", + "すずしい", + "すすむ", + "すすめる", + "すっかり", + "ずっしり", + "ずっと", + "すてき", + "すてる", + "すねる", + "すのこ", + "すはだ", + "すばらしい", + "ずひょう", + "ずぶぬれ", + "すぶり", + "すふれ", + "すべて", + "すべる", + "ずほう", + "すぼん", + "すまい", + "すめし", + "すもう", + "すやき", + "すらすら", + "するめ", + "すれちがう", + "すろっと", + "すわる", + "すんぜん", + "すんぽう", + "せあぶら", + "せいかつ", + "せいげん", + "せいじ", + "せいよう", + "せおう", + "せかいかん", + "せきにん", + "せきむ", + "せきゆ", + "せきらんうん", + "せけん", + "せこう", + "せすじ", + "せたい", + "せたけ", + "せっかく", + "せっきゃく", + "ぜっく", + "せっけん", + "せっこつ", + "せっさたくま", + "せつぞく", + "せつだん", + "せつでん", + "せっぱん", + "せつび", + "せつぶん", + "せつめい", + "せつりつ", + "せなか", + "せのび", + "せはば", + "せびろ", + "せぼね", + "せまい", + "せまる", + "せめる", + "せもたれ", + "せりふ", + "ぜんあく", + "せんい", + "せんえい", + "せんか", + "せんきょ", + "せんく", + "せんげん", + "ぜんご", + "せんさい", + "せんしゅ", + "せんすい", + "せんせい", + "せんぞ", + "せんたく", + "せんちょう", + "せんてい", + "せんとう", + "せんぬき", + "せんねん", + "せんぱい", + "ぜんぶ", + "ぜんぽう", + "せんむ", + "せんめんじょ", + "せんもん", + "せんやく", + "せんゆう", + "せんよう", + "ぜんら", + "ぜんりゃく", + "せんれい", + "せんろ", + "そあく", + "そいとげる", + "そいね", + "そうがんきょう", + "そうき", + "そうご", + "そうしん", + "そうだん", + "そうなん", + "そうび", + "そうめん", + "そうり", + "そえもの", + "そえん", + "そがい", + "そげき", + "そこう", + "そこそこ", + "そざい", + "そしな", + "そせい", + "そせん", + "そそぐ", + "そだてる", + "そつう", + "そつえん", + "そっかん", + "そつぎょう", + "そっけつ", + "そっこう", + "そっせん", + "そっと", + "そとがわ", + "そとづら", + "そなえる", + "そなた", + "そふぼ", + "そぼく", + "そぼろ", + "そまつ", + "そまる", + "そむく", + "そむりえ", + "そめる", + "そもそも", + "そよかぜ", + "そらまめ", + "そろう", + "そんかい", + "そんけい", + "そんざい", + "そんしつ", + "そんぞく", + "そんちょう", + "ぞんび", + "ぞんぶん", + "そんみん", + "たあい", + "たいいん", + "たいうん", + "たいえき", + "たいおう", + "だいがく", + "たいき", + "たいぐう", + "たいけん", + "たいこ", + "たいざい", + "だいじょうぶ", + "だいすき", + "たいせつ", + "たいそう", + "だいたい", + "たいちょう", + "たいてい", + "だいどころ", + "たいない", + "たいねつ", + "たいのう", + "たいはん", + "だいひょう", + "たいふう", + "たいへん", + "たいほ", + "たいまつばな", + "たいみんぐ", + "たいむ", + "たいめん", + "たいやき", + "たいよう", + "たいら", + "たいりょく", + "たいる", + "たいわん", + "たうえ", + "たえる", + "たおす", + "たおる", + "たおれる", + "たかい", + "たかね", + "たきび", + "たくさん", + "たこく", + "たこやき", + "たさい", + "たしざん", + "だじゃれ", + "たすける", + "たずさわる", + "たそがれ", + "たたかう", + "たたく", + "ただしい", + "たたみ", + "たちばな", + "だっかい", + "だっきゃく", + "だっこ", + "だっしゅつ", + "だったい", + "たてる", + "たとえる", + "たなばた", + "たにん", + "たぬき", + "たのしみ", + "たはつ", + "たぶん", + "たべる", + "たぼう", + "たまご", + "たまる", + "だむる", + "ためいき", + "ためす", + "ためる", + "たもつ", + "たやすい", + "たよる", + "たらす", + "たりきほんがん", + "たりょう", + "たりる", + "たると", + "たれる", + "たれんと", + "たろっと", + "たわむれる", + "だんあつ", + "たんい", + "たんおん", + "たんか", + "たんき", + "たんけん", + "たんご", + "たんさん", + "たんじょうび", + "だんせい", + "たんそく", + "たんたい", + "だんち", + "たんてい", + "たんとう", + "だんな", + "たんにん", + "だんねつ", + "たんのう", + "たんぴん", + "だんぼう", + "たんまつ", + "たんめい", + "だんれつ", + "だんろ", + "だんわ", + "ちあい", + "ちあん", + "ちいき", + "ちいさい", + "ちえん", + "ちかい", + "ちから", + "ちきゅう", + "ちきん", + "ちけいず", + "ちけん", + "ちこく", + "ちさい", + "ちしき", + "ちしりょう", + "ちせい", + "ちそう", + "ちたい", + "ちたん", + "ちちおや", + "ちつじょ", + "ちてき", + "ちてん", + "ちぬき", + "ちぬり", + "ちのう", + "ちひょう", + "ちへいせん", + "ちほう", + "ちまた", + "ちみつ", + "ちみどろ", + "ちめいど", + "ちゃんこなべ", + "ちゅうい", + "ちゆりょく", + "ちょうし", + "ちょさくけん", + "ちらし", + "ちらみ", + "ちりがみ", + "ちりょう", + "ちるど", + "ちわわ", + "ちんたい", + "ちんもく", + "ついか", + "ついたち", + "つうか", + "つうじょう", + "つうはん", + "つうわ", + "つかう", + "つかれる", + "つくね", + "つくる", + "つけね", + "つける", + "つごう", + "つたえる", + "つづく", + "つつじ", + "つつむ", + "つとめる", + "つながる", + "つなみ", + "つねづね", + "つのる", + "つぶす", + "つまらない", + "つまる", + "つみき", + "つめたい", + "つもり", + "つもる", + "つよい", + "つるぼ", + "つるみく", + "つわもの", + "つわり", + "てあし", + "てあて", + "てあみ", + "ていおん", + "ていか", + "ていき", + "ていけい", + "ていこく", + "ていさつ", + "ていし", + "ていせい", + "ていたい", + "ていど", + "ていねい", + "ていひょう", + "ていへん", + "ていぼう", + "てうち", + "ておくれ", + "てきとう", + "てくび", + "でこぼこ", + "てさぎょう", + "てさげ", + "てすり", + "てそう", + "てちがい", + "てちょう", + "てつがく", + "てつづき", + "でっぱ", + "てつぼう", + "てつや", + "でぬかえ", + "てぬき", + "てぬぐい", + "てのひら", + "てはい", + "てぶくろ", + "てふだ", + "てほどき", + "てほん", + "てまえ", + "てまきずし", + "てみじか", + "てみやげ", + "てらす", + "てれび", + "てわけ", + "てわたし", + "でんあつ", + "てんいん", + "てんかい", + "てんき", + "てんぐ", + "てんけん", + "てんごく", + "てんさい", + "てんし", + "てんすう", + "でんち", + "てんてき", + "てんとう", + "てんない", + "てんぷら", + "てんぼうだい", + "てんめつ", + "てんらんかい", + "でんりょく", + "でんわ", + "どあい", + "といれ", + "どうかん", + "とうきゅう", + "どうぐ", + "とうし", + "とうむぎ", + "とおい", + "とおか", + "とおく", + "とおす", + "とおる", + "とかい", + "とかす", + "ときおり", + "ときどき", + "とくい", + "とくしゅう", + "とくてん", + "とくに", + "とくべつ", + "とけい", + "とける", + "とこや", + "とさか", + "としょかん", + "とそう", + "とたん", + "とちゅう", + "とっきゅう", + "とっくん", + "とつぜん", + "とつにゅう", + "とどける", + "ととのえる", + "とない", + "となえる", + "となり", + "とのさま", + "とばす", + "どぶがわ", + "とほう", + "とまる", + "とめる", + "ともだち", + "ともる", + "どようび", + "とらえる", + "とんかつ", + "どんぶり", + "ないかく", + "ないこう", + "ないしょ", + "ないす", + "ないせん", + "ないそう", + "なおす", + "ながい", + "なくす", + "なげる", + "なこうど", + "なさけ", + "なたでここ", + "なっとう", + "なつやすみ", + "ななおし", + "なにごと", + "なにもの", + "なにわ", + "なのか", + "なふだ", + "なまいき", + "なまえ", + "なまみ", + "なみだ", + "なめらか", + "なめる", + "なやむ", + "ならう", + "ならび", + "ならぶ", + "なれる", + "なわとび", + "なわばり", + "にあう", + "にいがた", + "にうけ", + "におい", + "にかい", + "にがて", + "にきび", + "にくしみ", + "にくまん", + "にげる", + "にさんかたんそ", + "にしき", + "にせもの", + "にちじょう", + "にちようび", + "にっか", + "にっき", + "にっけい", + "にっこう", + "にっさん", + "にっしょく", + "にっすう", + "にっせき", + "にってい", + "になう", + "にほん", + "にまめ", + "にもつ", + "にやり", + "にゅういん", + "にりんしゃ", + "にわとり", + "にんい", + "にんか", + "にんき", + "にんげん", + "にんしき", + "にんずう", + "にんそう", + "にんたい", + "にんち", + "にんてい", + "にんにく", + "にんぷ", + "にんまり", + "にんむ", + "にんめい", + "にんよう", + "ぬいくぎ", + "ぬかす", + "ぬぐいとる", + "ぬぐう", + "ぬくもり", + "ぬすむ", + "ぬまえび", + "ぬめり", + "ぬらす", + "ぬんちゃく", + "ねあげ", + "ねいき", + "ねいる", + "ねいろ", + "ねぐせ", + "ねくたい", + "ねくら", + "ねこぜ", + "ねこむ", + "ねさげ", + "ねすごす", + "ねそべる", + "ねだん", + "ねつい", + "ねっしん", + "ねつぞう", + "ねったいぎょ", + "ねぶそく", + "ねふだ", + "ねぼう", + "ねほりはほり", + "ねまき", + "ねまわし", + "ねみみ", + "ねむい", + "ねむたい", + "ねもと", + "ねらう", + "ねわざ", + "ねんいり", + "ねんおし", + "ねんかん", + "ねんきん", + "ねんぐ", + "ねんざ", + "ねんし", + "ねんちゃく", + "ねんど", + "ねんぴ", + "ねんぶつ", + "ねんまつ", + "ねんりょう", + "ねんれい", + "のいず", + "のおづま", + "のがす", + "のきなみ", + "のこぎり", + "のこす", + "のこる", + "のせる", + "のぞく", + "のぞむ", + "のたまう", + "のちほど", + "のっく", + "のばす", + "のはら", + "のべる", + "のぼる", + "のみもの", + "のやま", + "のらいぬ", + "のらねこ", + "のりもの", + "のりゆき", + "のれん", + "のんき", + "ばあい", + "はあく", + "ばあさん", + "ばいか", + "ばいく", + "はいけん", + "はいご", + "はいしん", + "はいすい", + "はいせん", + "はいそう", + "はいち", + "ばいばい", + "はいれつ", + "はえる", + "はおる", + "はかい", + "ばかり", + "はかる", + "はくしゅ", + "はけん", + "はこぶ", + "はさみ", + "はさん", + "はしご", + "ばしょ", + "はしる", + "はせる", + "ぱそこん", + "はそん", + "はたん", + "はちみつ", + "はつおん", + "はっかく", + "はづき", + "はっきり", + "はっくつ", + "はっけん", + "はっこう", + "はっさん", + "はっしん", + "はったつ", + "はっちゅう", + "はってん", + "はっぴょう", + "はっぽう", + "はなす", + "はなび", + "はにかむ", + "はぶらし", + "はみがき", + "はむかう", + "はめつ", + "はやい", + "はやし", + "はらう", + "はろうぃん", + "はわい", + "はんい", + "はんえい", + "はんおん", + "はんかく", + "はんきょう", + "ばんぐみ", + "はんこ", + "はんしゃ", + "はんすう", + "はんだん", + "ぱんち", + "ぱんつ", + "はんてい", + "はんとし", + "はんのう", + "はんぱ", + "はんぶん", + "はんぺん", + "はんぼうき", + "はんめい", + "はんらん", + "はんろん", + "ひいき", + "ひうん", + "ひえる", + "ひかく", + "ひかり", + "ひかる", + "ひかん", + "ひくい", + "ひけつ", + "ひこうき", + "ひこく", + "ひさい", + "ひさしぶり", + "ひさん", + "びじゅつかん", + "ひしょ" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/language_base.h b/src/mnemonics/language_base.h index 4ff6b7a4e..720deaa33 100644 --- a/src/mnemonics/language_base.h +++ b/src/mnemonics/language_base.h @@ -1,286 +1,287 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file language_base.h - * - * \brief Language Base class for Polymorphism. - */ - -#ifndef LANGUAGE_BASE_H -#define LANGUAGE_BASE_H - -#include -#include -#include -#include "epee/misc_log_ex.h" - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - /*! - * \brief Returns a string made of (at most) the first count characters in s. - * Assumes well formedness. No check is made for this. - * \param s The string from which to return the first count characters. - * \param count How many characters to return. - * \return A string consisting of the first count characters in s. - */ - template - inline T utf8prefix(const T &s, size_t count) - { - T prefix = ""; - size_t avail = s.size(); - const char *ptr = s.data(); - while (count-- && avail--) - { - prefix += *ptr++; - while (avail && ((*ptr) & 0xc0) == 0x80) - { - prefix += *ptr++; - --avail; - } - } - return prefix; - } - - template - inline T utf8canonical(const T &s) - { - T sc = ""; - size_t avail = s.size(); - const char *ptr = s.data(); - wint_t cp = 0; - int bytes = 1; - char wbuf[8], *wptr; - while (avail--) - { - if ((*ptr & 0x80) == 0) - { - cp = *ptr++; - bytes = 1; - } - else if ((*ptr & 0xe0) == 0xc0) - { - if (avail < 1) - throw std::runtime_error("Invalid UTF-8"); - cp = (*ptr++ & 0x1f) << 6; - cp |= *ptr++ & 0x3f; - --avail; - bytes = 2; - } - else if ((*ptr & 0xf0) == 0xe0) - { - if (avail < 2) - throw std::runtime_error("Invalid UTF-8"); - cp = (*ptr++ & 0xf) << 12; - cp |= (*ptr++ & 0x3f) << 6; - cp |= *ptr++ & 0x3f; - avail -= 2; - bytes = 3; - } - else if ((*ptr & 0xf8) == 0xf0) - { - if (avail < 3) - throw std::runtime_error("Invalid UTF-8"); - cp = (*ptr++ & 0x7) << 18; - cp |= (*ptr++ & 0x3f) << 12; - cp |= (*ptr++ & 0x3f) << 6; - cp |= *ptr++ & 0x3f; - avail -= 3; - bytes = 4; - } - else - throw std::runtime_error("Invalid UTF-8"); - - cp = std::towlower(cp); - wptr = wbuf; - switch (bytes) - { - case 1: *wptr++ = cp; break; - case 2: *wptr++ = 0xc0 | (cp >> 6); *wptr++ = 0x80 | (cp & 0x3f); break; - case 3: *wptr++ = 0xe0 | (cp >> 12); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; - case 4: *wptr++ = 0xf0 | (cp >> 18); *wptr += 0x80 | ((cp >> 12) & 0x3f); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; - default: throw std::runtime_error("Invalid UTF-8"); - } - *wptr = 0; - sc += T(wbuf, bytes); - cp = 0; - bytes = 1; - } - return sc; - } - - struct WordHash - { - std::size_t operator()(const epee::wipeable_string &s) const - { - return std::hash{}(utf8canonical(s)); - } - }; - - struct WordEqual - { - bool operator()(const epee::wipeable_string &s0, const epee::wipeable_string &s1) const - { - const epee::wipeable_string s0c = utf8canonical(s0); - const epee::wipeable_string s1c = utf8canonical(s1); - return s0c == s1c; - } - }; - - /*! - * \class Base - * \brief A base language class which all languages have to inherit from for - * Polymorphism. - */ - class Base - { - protected: - enum { - ALLOW_SHORT_WORDS = 1<<0, - ALLOW_DUPLICATE_PREFIXES = 1<<1, - }; - enum { - NWORDS = 1626 - }; - std::vector word_list; /*!< A pointer to the array of words */ - std::unordered_map word_map; /*!< hash table to find word's index */ - std::unordered_map trimmed_word_map; /*!< hash table to find word's trimmed index */ - std::string language_name; /*!< Name of language */ - std::string english_language_name; /*!< Name of language */ - uint32_t unique_prefix_length; /*!< Number of unique starting characters to trim the wordlist to when matching */ - /*! - * \brief Populates the word maps after the list is ready. - */ - void populate_maps(uint32_t flags = 0) - { - int ii; - std::vector::const_iterator it; - if (word_list.size () != NWORDS) - throw std::runtime_error("Wrong word list length for " + language_name); - for (it = word_list.begin(), ii = 0; it != word_list.end(); it++, ii++) - { - word_map[*it] = ii; - if ((*it).size() < unique_prefix_length) - { - if (flags & ALLOW_SHORT_WORDS) - MWARNING(language_name << " word '" << *it << "' is shorter than its prefix length, " << unique_prefix_length); - else - throw std::runtime_error("Too short word in " + language_name + " word list: " + *it); - } - epee::wipeable_string trimmed; - if (it->length() > unique_prefix_length) - { - trimmed = utf8prefix(*it, unique_prefix_length); - } - else - { - trimmed = *it; - } - if (trimmed_word_map.find(trimmed) != trimmed_word_map.end()) - { - if (flags & ALLOW_DUPLICATE_PREFIXES) - MWARNING("Duplicate prefix in " << language_name << " word list: " << std::string(trimmed.data(), trimmed.size())); - else - throw std::runtime_error("Duplicate prefix in " + language_name + " word list: " + std::string(trimmed.data(), trimmed.size())); - } - trimmed_word_map[trimmed] = ii; - } - } - public: - Base(const char *language_name, const char *english_language_name, const std::vector &words, uint32_t prefix_length): - word_list(words), - unique_prefix_length(prefix_length), - language_name(language_name), - english_language_name(english_language_name) - { - } - virtual ~Base() - { - } - void set_words(const char * const words[]) - { - word_list.resize(NWORDS); - for (size_t i = 0; i < NWORDS; ++i) - word_list[i] = words[i]; - } - /*! - * \brief Returns a pointer to the word list. - * \return A pointer to the word list. - */ - const std::vector& get_word_list() const - { - return word_list; - } - /*! - * \brief Returns a pointer to the word map. - * \return A pointer to the word map. - */ - const std::unordered_map& get_word_map() const - { - return word_map; - } - /*! - * \brief Returns a pointer to the trimmed word map. - * \return A pointer to the trimmed word map. - */ - const std::unordered_map& get_trimmed_word_map() const - { - return trimmed_word_map; - } - /*! - * \brief Returns the name of the language. - * \return Name of the language. - */ - const std::string &get_language_name() const - { - return language_name; - } - /*! - * \brief Returns the name of the language in English. - * \return Name of the language. - */ - const std::string &get_english_language_name() const - { - return english_language_name; - } - /*! - * \brief Returns the number of unique starting characters to be used for matching. - * \return Number of unique starting characters. - */ - uint32_t get_unique_prefix_length() const - { - return unique_prefix_length; - } - }; -} - -#endif +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file language_base.h + * + * \brief Language Base class for Polymorphism. + */ + +#ifndef LANGUAGE_BASE_H +#define LANGUAGE_BASE_H + +#include +#include +#include +#include "logging/oxen_logger.h" + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + /*! + * \brief Returns a string made of (at most) the first count characters in s. + * Assumes well formedness. No check is made for this. + * \param s The string from which to return the first count characters. + * \param count How many characters to return. + * \return A string consisting of the first count characters in s. + */ + template + inline T utf8prefix(const T &s, size_t count) + { + T prefix = ""; + size_t avail = s.size(); + const char *ptr = s.data(); + while (count-- && avail--) + { + prefix += *ptr++; + while (avail && ((*ptr) & 0xc0) == 0x80) + { + prefix += *ptr++; + --avail; + } + } + return prefix; + } + + template + inline T utf8canonical(const T &s) + { + T sc = ""; + size_t avail = s.size(); + const char *ptr = s.data(); + wint_t cp = 0; + int bytes = 1; + char wbuf[8], *wptr; + while (avail--) + { + if ((*ptr & 0x80) == 0) + { + cp = *ptr++; + bytes = 1; + } + else if ((*ptr & 0xe0) == 0xc0) + { + if (avail < 1) + throw std::runtime_error("Invalid UTF-8"); + cp = (*ptr++ & 0x1f) << 6; + cp |= *ptr++ & 0x3f; + --avail; + bytes = 2; + } + else if ((*ptr & 0xf0) == 0xe0) + { + if (avail < 2) + throw std::runtime_error("Invalid UTF-8"); + cp = (*ptr++ & 0xf) << 12; + cp |= (*ptr++ & 0x3f) << 6; + cp |= *ptr++ & 0x3f; + avail -= 2; + bytes = 3; + } + else if ((*ptr & 0xf8) == 0xf0) + { + if (avail < 3) + throw std::runtime_error("Invalid UTF-8"); + cp = (*ptr++ & 0x7) << 18; + cp |= (*ptr++ & 0x3f) << 12; + cp |= (*ptr++ & 0x3f) << 6; + cp |= *ptr++ & 0x3f; + avail -= 3; + bytes = 4; + } + else + throw std::runtime_error("Invalid UTF-8"); + + cp = std::towlower(cp); + wptr = wbuf; + switch (bytes) + { + case 1: *wptr++ = cp; break; + case 2: *wptr++ = 0xc0 | (cp >> 6); *wptr++ = 0x80 | (cp & 0x3f); break; + case 3: *wptr++ = 0xe0 | (cp >> 12); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; + case 4: *wptr++ = 0xf0 | (cp >> 18); *wptr += 0x80 | ((cp >> 12) & 0x3f); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; + default: throw std::runtime_error("Invalid UTF-8"); + } + *wptr = 0; + sc += T(wbuf, bytes); + cp = 0; + bytes = 1; + } + return sc; + } + + struct WordHash + { + std::size_t operator()(const epee::wipeable_string &s) const + { + return std::hash{}(utf8canonical(s)); + } + }; + + struct WordEqual + { + bool operator()(const epee::wipeable_string &s0, const epee::wipeable_string &s1) const + { + const epee::wipeable_string s0c = utf8canonical(s0); + const epee::wipeable_string s1c = utf8canonical(s1); + return s0c == s1c; + } + }; + + /*! + * \class Base + * \brief A base language class which all languages have to inherit from for + * Polymorphism. + */ + class Base + { + protected: + enum { + ALLOW_SHORT_WORDS = 1<<0, + ALLOW_DUPLICATE_PREFIXES = 1<<1, + }; + enum { + NWORDS = 1626 + }; + std::vector word_list; /*!< A pointer to the array of words */ + std::unordered_map word_map; /*!< hash table to find word's index */ + std::unordered_map trimmed_word_map; /*!< hash table to find word's trimmed index */ + std::string language_name; /*!< Name of language */ + std::string english_language_name; /*!< Name of language */ + uint32_t unique_prefix_length; /*!< Number of unique starting characters to trim the wordlist to when matching */ + /*! + * \brief Populates the word maps after the list is ready. + */ + void populate_maps(uint32_t flags = 0) + { + auto logcat = oxen::log::Cat("global"); + int ii; + std::vector::const_iterator it; + if (word_list.size () != NWORDS) + throw std::runtime_error("Wrong word list length for " + language_name); + for (it = word_list.begin(), ii = 0; it != word_list.end(); it++, ii++) + { + word_map[*it] = ii; + if ((*it).size() < unique_prefix_length) + { + if (flags & ALLOW_SHORT_WORDS) + oxen::log::debug(logcat, "{} word '{}' is shorter than its prefix length, {}", language_name, *it, unique_prefix_length); + else + throw std::runtime_error("Too short word in " + language_name + " word list: " + *it); + } + epee::wipeable_string trimmed; + if (it->length() > unique_prefix_length) + { + trimmed = utf8prefix(*it, unique_prefix_length); + } + else + { + trimmed = *it; + } + if (trimmed_word_map.find(trimmed) != trimmed_word_map.end()) + { + if (flags & ALLOW_DUPLICATE_PREFIXES) + oxen::log::warning(logcat, "Duplicate prefix in {} word list: {}", language_name, std::string(trimmed.data(), trimmed.size())); + else + throw std::runtime_error("Duplicate prefix in " + language_name + " word list: " + std::string(trimmed.data(), trimmed.size())); + } + trimmed_word_map[trimmed] = ii; + } + } + public: + Base(const char *language_name, const char *english_language_name, const std::vector &words, uint32_t prefix_length): + word_list(words), + unique_prefix_length(prefix_length), + language_name(language_name), + english_language_name(english_language_name) + { + } + virtual ~Base() + { + } + void set_words(const char * const words[]) + { + word_list.resize(NWORDS); + for (size_t i = 0; i < NWORDS; ++i) + word_list[i] = words[i]; + } + /*! + * \brief Returns a pointer to the word list. + * \return A pointer to the word list. + */ + const std::vector& get_word_list() const + { + return word_list; + } + /*! + * \brief Returns a pointer to the word map. + * \return A pointer to the word map. + */ + const std::unordered_map& get_word_map() const + { + return word_map; + } + /*! + * \brief Returns a pointer to the trimmed word map. + * \return A pointer to the trimmed word map. + */ + const std::unordered_map& get_trimmed_word_map() const + { + return trimmed_word_map; + } + /*! + * \brief Returns the name of the language. + * \return Name of the language. + */ + const std::string &get_language_name() const + { + return language_name; + } + /*! + * \brief Returns the name of the language in English. + * \return Name of the language. + */ + const std::string &get_english_language_name() const + { + return english_language_name; + } + /*! + * \brief Returns the number of unique starting characters to be used for matching. + * \return Number of unique starting characters. + */ + uint32_t get_unique_prefix_length() const + { + return unique_prefix_length; + } + }; +} + +#endif diff --git a/src/mnemonics/lojban.h b/src/mnemonics/lojban.h index b6baf46c4..f8dbf4a1a 100644 --- a/src/mnemonics/lojban.h +++ b/src/mnemonics/lojban.h @@ -1,1696 +1,1696 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file lojban.h - * - * \brief New Lojban word list and map. - */ - -/* - * Word list authored by: sorpaas - * Sources: - * lo gimste jo'u lo ma'oste (https://guskant.github.io/lojbo/gismu-cmavo.html) - * N-grams of Lojban corpus (https://mw.lojban.org/papri/N-grams_of_Lojban_corpus) - */ - -#ifndef LOJBAN_H -#define LOJBAN_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Lojban: public Base - { - public: - Lojban(): Base("Lojban", "Lojban", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "backi", - "bacru", - "badna", - "badri", - "bajra", - "bakfu", - "bakni", - "bakri", - "baktu", - "balji", - "balni", - "balre", - "balvi", - "bambu", - "bancu", - "bandu", - "banfi", - "bangu", - "banli", - "banro", - "banxa", - "banzu", - "bapli", - "barda", - "bargu", - "barja", - "barna", - "bartu", - "basfa", - "basna", - "basti", - "batci", - "batke", - "bavmi", - "baxso", - "bebna", - "bekpi", - "bemro", - "bende", - "bengo", - "benji", - "benre", - "benzo", - "bergu", - "bersa", - "berti", - "besna", - "besto", - "betfu", - "betri", - "bevri", - "bidju", - "bifce", - "bikla", - "bilga", - "bilma", - "bilni", - "bindo", - "binra", - "binxo", - "birje", - "birka", - "birti", - "bisli", - "bitmu", - "bitni", - "blabi", - "blaci", - "blanu", - "bliku", - "bloti", - "bolci", - "bongu", - "boske", - "botpi", - "boxfo", - "boxna", - "bradi", - "brano", - "bratu", - "brazo", - "bredi", - "bridi", - "brife", - "briju", - "brito", - "brivo", - "broda", - "bruna", - "budjo", - "bukpu", - "bumru", - "bunda", - "bunre", - "burcu", - "burna", - "cabna", - "cabra", - "cacra", - "cadga", - "cadzu", - "cafne", - "cagna", - "cakla", - "calku", - "calse", - "canci", - "cando", - "cange", - "canja", - "canko", - "canlu", - "canpa", - "canre", - "canti", - "carce", - "carfu", - "carmi", - "carna", - "cartu", - "carvi", - "casnu", - "catke", - "catlu", - "catni", - "catra", - "caxno", - "cecla", - "cecmu", - "cedra", - "cenba", - "censa", - "centi", - "cerda", - "cerni", - "certu", - "cevni", - "cfale", - "cfari", - "cfika", - "cfila", - "cfine", - "cfipu", - "ciblu", - "cicna", - "cidja", - "cidni", - "cidro", - "cifnu", - "cigla", - "cikna", - "cikre", - "ciksi", - "cilce", - "cilfu", - "cilmo", - "cilre", - "cilta", - "cimde", - "cimni", - "cinba", - "cindu", - "cinfo", - "cinje", - "cinki", - "cinla", - "cinmo", - "cinri", - "cinse", - "cinta", - "cinza", - "cipni", - "cipra", - "cirko", - "cirla", - "ciska", - "cisma", - "cisni", - "ciste", - "citka", - "citno", - "citri", - "citsi", - "civla", - "cizra", - "ckabu", - "ckafi", - "ckaji", - "ckana", - "ckape", - "ckasu", - "ckeji", - "ckiku", - "ckilu", - "ckini", - "ckire", - "ckule", - "ckunu", - "cladu", - "clani", - "claxu", - "cletu", - "clika", - "clinu", - "clira", - "clite", - "cliva", - "clupa", - "cmaci", - "cmalu", - "cmana", - "cmavo", - "cmene", - "cmeta", - "cmevo", - "cmila", - "cmima", - "cmoni", - "cnano", - "cnebo", - "cnemu", - "cnici", - "cnino", - "cnisa", - "cnita", - "cokcu", - "condi", - "conka", - "corci", - "cortu", - "cpacu", - "cpana", - "cpare", - "cpedu", - "cpina", - "cradi", - "crane", - "creka", - "crepu", - "cribe", - "crida", - "crino", - "cripu", - "crisa", - "critu", - "ctaru", - "ctebi", - "cteki", - "ctile", - "ctino", - "ctuca", - "cukla", - "cukre", - "cukta", - "culno", - "cumki", - "cumla", - "cunmi", - "cunso", - "cuntu", - "cupra", - "curmi", - "curnu", - "curve", - "cusku", - "cusna", - "cutci", - "cutne", - "cuxna", - "dacru", - "dacti", - "dadjo", - "dakfu", - "dakli", - "damba", - "damri", - "dandu", - "danfu", - "danlu", - "danmo", - "danre", - "dansu", - "danti", - "daplu", - "dapma", - "darca", - "dargu", - "darlu", - "darno", - "darsi", - "darxi", - "daski", - "dasni", - "daspo", - "dasri", - "datka", - "datni", - "datro", - "decti", - "degji", - "dejni", - "dekpu", - "dekto", - "delno", - "dembi", - "denci", - "denmi", - "denpa", - "dertu", - "derxi", - "desku", - "detri", - "dicma", - "dicra", - "didni", - "digno", - "dikca", - "diklo", - "dikni", - "dilcu", - "dilma", - "dilnu", - "dimna", - "dindi", - "dinju", - "dinko", - "dinso", - "dirba", - "dirce", - "dirgo", - "disko", - "ditcu", - "divzi", - "dizlo", - "djacu", - "djedi", - "djica", - "djine", - "djuno", - "donri", - "dotco", - "draci", - "drani", - "drata", - "drudi", - "dugri", - "dukse", - "dukti", - "dunda", - "dunja", - "dunku", - "dunli", - "dunra", - "dutso", - "dzena", - "dzipo", - "facki", - "fadni", - "fagri", - "falnu", - "famti", - "fancu", - "fange", - "fanmo", - "fanri", - "fanta", - "fanva", - "fanza", - "fapro", - "farka", - "farlu", - "farna", - "farvi", - "fasnu", - "fatci", - "fatne", - "fatri", - "febvi", - "fegli", - "femti", - "fendi", - "fengu", - "fenki", - "fenra", - "fenso", - "fepni", - "fepri", - "ferti", - "festi", - "fetsi", - "figre", - "filso", - "finpe", - "finti", - "firca", - "fisli", - "fizbu", - "flaci", - "flalu", - "flani", - "flecu", - "flese", - "fliba", - "flira", - "foldi", - "fonmo", - "fonxa", - "forca", - "forse", - "fraso", - "frati", - "fraxu", - "frica", - "friko", - "frili", - "frinu", - "friti", - "frumu", - "fukpi", - "fulta", - "funca", - "fusra", - "fuzme", - "gacri", - "gadri", - "galfi", - "galtu", - "galxe", - "ganlo", - "ganra", - "ganse", - "ganti", - "ganxo", - "ganzu", - "gapci", - "gapru", - "garna", - "gasnu", - "gaspo", - "gasta", - "genja", - "gento", - "genxu", - "gerku", - "gerna", - "gidva", - "gigdo", - "ginka", - "girzu", - "gismu", - "glare", - "gleki", - "gletu", - "glico", - "glife", - "glosa", - "gluta", - "gocti", - "gomsi", - "gotro", - "gradu", - "grafu", - "grake", - "grana", - "grasu", - "grava", - "greku", - "grusi", - "grute", - "gubni", - "gugde", - "gugle", - "gumri", - "gundi", - "gunka", - "gunma", - "gunro", - "gunse", - "gunta", - "gurni", - "guska", - "gusni", - "gusta", - "gutci", - "gutra", - "guzme", - "jabre", - "jadni", - "jakne", - "jalge", - "jalna", - "jalra", - "jamfu", - "jamna", - "janbe", - "janco", - "janli", - "jansu", - "janta", - "jarbu", - "jarco", - "jarki", - "jaspu", - "jatna", - "javni", - "jbama", - "jbari", - "jbena", - "jbera", - "jbini", - "jdari", - "jdice", - "jdika", - "jdima", - "jdini", - "jduli", - "jecta", - "jeftu", - "jegvo", - "jelca", - "jemna", - "jenca", - "jendu", - "jenmi", - "jensi", - "jerna", - "jersi", - "jerxo", - "jesni", - "jetce", - "jetnu", - "jgalu", - "jganu", - "jgari", - "jgena", - "jgina", - "jgira", - "jgita", - "jibni", - "jibri", - "jicla", - "jicmu", - "jijnu", - "jikca", - "jikfi", - "jikni", - "jikru", - "jilka", - "jilra", - "jimca", - "jimpe", - "jimte", - "jinci", - "jinda", - "jinga", - "jinku", - "jinme", - "jinru", - "jinsa", - "jinto", - "jinvi", - "jinzi", - "jipci", - "jipno", - "jirna", - "jisra", - "jitfa", - "jitro", - "jivbu", - "jivna", - "jmaji", - "jmifa", - "jmina", - "jmive", - "jonse", - "jordo", - "jorne", - "jubme", - "judri", - "jufra", - "jukni", - "jukpa", - "julne", - "julro", - "jundi", - "jungo", - "junla", - "junri", - "junta", - "jurme", - "jursa", - "jutsi", - "juxre", - "jvinu", - "jviso", - "kabri", - "kacma", - "kadno", - "kafke", - "kagni", - "kajde", - "kajna", - "kakne", - "kakpa", - "kalci", - "kalri", - "kalsa", - "kalte", - "kamju", - "kamni", - "kampu", - "kamre", - "kanba", - "kancu", - "kandi", - "kanji", - "kanla", - "kanpe", - "kanro", - "kansa", - "kantu", - "kanxe", - "karbi", - "karce", - "karda", - "kargu", - "karli", - "karni", - "katci", - "katna", - "kavbu", - "kazra", - "kecti", - "kekli", - "kelci", - "kelvo", - "kenka", - "kenra", - "kensa", - "kerfa", - "kerlo", - "kesri", - "ketco", - "ketsu", - "kevna", - "kibro", - "kicne", - "kijno", - "kilto", - "kinda", - "kinli", - "kisto", - "klaji", - "klaku", - "klama", - "klani", - "klesi", - "kliki", - "klina", - "kliru", - "kliti", - "klupe", - "kluza", - "kobli", - "kogno", - "kojna", - "kokso", - "kolme", - "komcu", - "konju", - "korbi", - "korcu", - "korka", - "korvo", - "kosmu", - "kosta", - "krali", - "kramu", - "krasi", - "krati", - "krefu", - "krici", - "krili", - "krinu", - "krixa", - "kruca", - "kruji", - "kruvi", - "kubli", - "kucli", - "kufra", - "kukte", - "kulnu", - "kumfa", - "kumte", - "kunra", - "kunti", - "kurfa", - "kurji", - "kurki", - "kuspe", - "kusru", - "labno", - "lacni", - "lacpu", - "lacri", - "ladru", - "lafti", - "lakne", - "lakse", - "laldo", - "lalxu", - "lamji", - "lanbi", - "lanci", - "landa", - "lanka", - "lanli", - "lanme", - "lante", - "lanxe", - "lanzu", - "larcu", - "larva", - "lasna", - "lastu", - "latmo", - "latna", - "lazni", - "lebna", - "lelxe", - "lenga", - "lenjo", - "lenku", - "lerci", - "lerfu", - "libjo", - "lidne", - "lifri", - "lijda", - "limfa", - "limna", - "lince", - "lindi", - "linga", - "linji", - "linsi", - "linto", - "lisri", - "liste", - "litce", - "litki", - "litru", - "livga", - "livla", - "logji", - "loglo", - "lojbo", - "loldi", - "lorxu", - "lubno", - "lujvo", - "luksi", - "lumci", - "lunbe", - "lunra", - "lunsa", - "luska", - "lusto", - "mabla", - "mabru", - "macnu", - "majga", - "makcu", - "makfa", - "maksi", - "malsi", - "mamta", - "manci", - "manfo", - "mango", - "manku", - "manri", - "mansa", - "manti", - "mapku", - "mapni", - "mapra", - "mapti", - "marbi", - "marce", - "marde", - "margu", - "marji", - "marna", - "marxa", - "masno", - "masti", - "matci", - "matli", - "matne", - "matra", - "mavji", - "maxri", - "mebri", - "megdo", - "mekso", - "melbi", - "meljo", - "melmi", - "menli", - "menre", - "mensi", - "mentu", - "merko", - "merli", - "metfo", - "mexno", - "midju", - "mifra", - "mikce", - "mikri", - "milti", - "milxe", - "minde", - "minji", - "minli", - "minra", - "mintu", - "mipri", - "mirli", - "misno", - "misro", - "mitre", - "mixre", - "mlana", - "mlatu", - "mleca", - "mledi", - "mluni", - "mogle", - "mokca", - "moklu", - "molki", - "molro", - "morji", - "morko", - "morna", - "morsi", - "mosra", - "mraji", - "mrilu", - "mruli", - "mucti", - "mudri", - "mugle", - "mukti", - "mulno", - "munje", - "mupli", - "murse", - "murta", - "muslo", - "mutce", - "muvdu", - "muzga", - "nabmi", - "nakni", - "nalci", - "namcu", - "nanba", - "nanca", - "nandu", - "nanla", - "nanmu", - "nanvi", - "narge", - "narju", - "natfe", - "natmi", - "natsi", - "navni", - "naxle", - "nazbi", - "nejni", - "nelci", - "nenri", - "nerde", - "nibli", - "nicfa", - "nicte", - "nikle", - "nilce", - "nimre", - "ninja", - "ninmu", - "nirna", - "nitcu", - "nivji", - "nixli", - "nobli", - "norgo", - "notci", - "nudle", - "nukni", - "nunmu", - "nupre", - "nurma", - "nusna", - "nutka", - "nutli", - "nuzba", - "nuzlo", - "pacna", - "pagbu", - "pagre", - "pajni", - "palci", - "palku", - "palma", - "palne", - "palpi", - "palta", - "pambe", - "pamga", - "panci", - "pandi", - "panje", - "panka", - "panlo", - "panpi", - "panra", - "pante", - "panzi", - "papri", - "parbi", - "pardu", - "parji", - "pastu", - "patfu", - "patlu", - "patxu", - "paznu", - "pelji", - "pelxu", - "pemci", - "penbi", - "pencu", - "pendo", - "penmi", - "pensi", - "pentu", - "perli", - "pesxu", - "petso", - "pevna", - "pezli", - "picti", - "pijne", - "pikci", - "pikta", - "pilda", - "pilji", - "pilka", - "pilno", - "pimlu", - "pinca", - "pindi", - "pinfu", - "pinji", - "pinka", - "pinsi", - "pinta", - "pinxe", - "pipno", - "pixra", - "plana", - "platu", - "pleji", - "plibu", - "plini", - "plipe", - "plise", - "plita", - "plixa", - "pluja", - "pluka", - "pluta", - "pocli", - "polje", - "polno", - "ponjo", - "ponse", - "poplu", - "porpi", - "porsi", - "porto", - "prali", - "prami", - "prane", - "preja", - "prenu", - "preri", - "preti", - "prije", - "prina", - "pritu", - "proga", - "prosa", - "pruce", - "pruni", - "pruri", - "pruxi", - "pulce", - "pulji", - "pulni", - "punji", - "punli", - "pupsu", - "purci", - "purdi", - "purmo", - "racli", - "ractu", - "radno", - "rafsi", - "ragbi", - "ragve", - "rakle", - "rakso", - "raktu", - "ralci", - "ralju", - "ralte", - "randa", - "rango", - "ranji", - "ranmi", - "ransu", - "ranti", - "ranxi", - "rapli", - "rarna", - "ratcu", - "ratni", - "rebla", - "rectu", - "rekto", - "remna", - "renro", - "renvi", - "respa", - "rexsa", - "ricfu", - "rigni", - "rijno", - "rilti", - "rimni", - "rinci", - "rindo", - "rinju", - "rinka", - "rinsa", - "rirci", - "rirni", - "rirxe", - "rismi", - "risna", - "ritli", - "rivbi", - "rokci", - "romge", - "romlo", - "ronte", - "ropno", - "rorci", - "rotsu", - "rozgu", - "ruble", - "rufsu", - "runme", - "runta", - "rupnu", - "rusko", - "rutni", - "sabji", - "sabnu", - "sacki", - "saclu", - "sadjo", - "sakci", - "sakli", - "sakta", - "salci", - "salpo", - "salri", - "salta", - "samcu", - "sampu", - "sanbu", - "sance", - "sanga", - "sanji", - "sanli", - "sanmi", - "sanso", - "santa", - "sarcu", - "sarji", - "sarlu", - "sarni", - "sarxe", - "saske", - "satci", - "satre", - "savru", - "sazri", - "sefsi", - "sefta", - "sekre", - "selci", - "selfu", - "semto", - "senci", - "sengi", - "senpi", - "senta", - "senva", - "sepli", - "serti", - "sesre", - "setca", - "sevzi", - "sfani", - "sfasa", - "sfofa", - "sfubu", - "sibli", - "siclu", - "sicni", - "sicpi", - "sidbo", - "sidju", - "sigja", - "sigma", - "sikta", - "silka", - "silna", - "simlu", - "simsa", - "simxu", - "since", - "sinma", - "sinso", - "sinxa", - "sipna", - "sirji", - "sirxo", - "sisku", - "sisti", - "sitna", - "sivni", - "skaci", - "skami", - "skapi", - "skari", - "skicu", - "skiji", - "skina", - "skori", - "skoto", - "skuba", - "skuro", - "slabu", - "slaka", - "slami", - "slanu", - "slari", - "slasi", - "sligu", - "slilu", - "sliri", - "slovo", - "sluji", - "sluni", - "smacu", - "smadi", - "smaji", - "smaka", - "smani", - "smela", - "smoka", - "smuci", - "smuni", - "smusu", - "snada", - "snanu", - "snidu", - "snime", - "snipa", - "snuji", - "snura", - "snuti", - "sobde", - "sodna", - "sodva", - "softo", - "solji", - "solri", - "sombo", - "sonci", - "sorcu", - "sorgu", - "sorni", - "sorta", - "sovda", - "spaji", - "spali", - "spano", - "spati", - "speni", - "spero", - "spisa", - "spita", - "spofu", - "spoja", - "spuda", - "sputu", - "sraji", - "sraku", - "sralo", - "srana", - "srasu", - "srera", - "srito", - "sruma", - "sruri", - "stace", - "stagi", - "staku", - "stali", - "stani", - "stapa", - "stasu", - "stati", - "steba", - "steci", - "stedu", - "stela", - "stero", - "stici", - "stidi", - "stika", - "stizu", - "stodi", - "stuna", - "stura", - "stuzi", - "sucta", - "sudga", - "sufti", - "suksa", - "sumji", - "sumne", - "sumti", - "sunga", - "sunla", - "surla", - "sutra", - "tabno", - "tabra", - "tadji", - "tadni", - "tagji", - "taksi", - "talsa", - "tamca", - "tamji", - "tamne", - "tanbo", - "tance", - "tanjo", - "tanko", - "tanru", - "tansi", - "tanxe", - "tapla", - "tarbi", - "tarci", - "tarla", - "tarmi", - "tarti", - "taske", - "tasmi", - "tasta", - "tatpi", - "tatru", - "tavla", - "taxfu", - "tcaci", - "tcadu", - "tcana", - "tcati", - "tcaxe", - "tcena", - "tcese", - "tcica", - "tcidu", - "tcika", - "tcila", - "tcima", - "tcini", - "tcita", - "temci", - "temse", - "tende", - "tenfa", - "tengu", - "terdi", - "terpa", - "terto", - "tifri", - "tigni", - "tigra", - "tikpa", - "tilju", - "tinbe", - "tinci", - "tinsa", - "tirna", - "tirse", - "tirxu", - "tisna", - "titla", - "tivni", - "tixnu", - "toknu", - "toldi", - "tonga", - "tordu", - "torni", - "torso", - "traji", - "trano", - "trati", - "trene", - "tricu", - "trina", - "trixe", - "troci", - "tsaba", - "tsali", - "tsani", - "tsapi", - "tsiju", - "tsina", - "tsuku", - "tubnu", - "tubra", - "tugni", - "tujli", - "tumla", - "tunba", - "tunka", - "tunlo", - "tunta", - "tuple", - "turko", - "turni", - "tutci", - "tutle", - "tutra", - "vacri", - "vajni", - "valsi", - "vamji", - "vamtu", - "vanbi", - "vanci", - "vanju", - "vasru", - "vasxu", - "vecnu", - "vedli", - "venfu", - "vensa", - "vente", - "vepre", - "verba", - "vibna", - "vidni", - "vidru", - "vifne", - "vikmi", - "viknu", - "vimcu", - "vindu", - "vinji", - "vinta", - "vipsi", - "virnu", - "viska", - "vitci", - "vitke", - "vitno", - "vlagi", - "vlile", - "vlina", - "vlipa", - "vofli", - "voksa", - "volve", - "vorme", - "vraga", - "vreji", - "vreta", - "vrici", - "vrude", - "vrusi", - "vubla", - "vujnu", - "vukna", - "vukro", - "xabju", - "xadba", - "xadji", - "xadni", - "xagji", - "xagri", - "xajmi", - "xaksu", - "xalbo", - "xalka", - "xalni", - "xamgu", - "xampo", - "xamsi", - "xance", - "xango", - "xanka", - "xanri", - "xansa", - "xanto", - "xarci", - "xarju", - "xarnu", - "xasli", - "xasne", - "xatra", - "xatsi", - "xazdo", - "xebni", - "xebro", - "xecto", - "xedja", - "xekri", - "xelso", - "xendo", - "xenru", - "xexso", - "xigzo", - "xindo", - "xinmo", - "xirma", - "xislu", - "xispo", - "xlali", - "xlura", - "xorbo", - "xorlo", - "xotli", - "xrabo", - "xrani", - "xriso", - "xrotu", - "xruba", - "xruki", - "xrula", - "xruti", - "xukmi", - "xulta", - "xunre", - "xurdo", - "xusra", - "xutla", - "zabna", - "zajba", - "zalvi", - "zanru", - "zarci", - "zargu", - "zasni", - "zasti", - "zbabu", - "zbani", - "zbasu", - "zbepi", - "zdani", - "zdile", - "zekri", - "zenba", - "zepti", - "zetro", - "zevla", - "zgadi", - "zgana", - "zgike", - "zifre", - "zinki", - "zirpu", - "zivle", - "zmadu", - "zmiku", - "zucna", - "zukte", - "zumri", - "zungi", - "zunle", - "zunti", - "zutse", - "zvati", - "zviki", - "jbobau", - "jbopre", - "karsna", - "cabdei", - "zunsna", - "gendra", - "glibau", - "nintadni", - "pavyseljirna", - "vlaste", - "selbri", - "latro'a", - "zdakemkulgu'a", - "mriste", - "selsku", - "fu'ivla", - "tolmo'i", - "snavei", - "xagmau", - "retsku", - "ckupau", - "skudji", - "smudra", - "prulamdei", - "vokta'a", - "tinju'i", - "jefyfa'o", - "bavlamdei", - "kinzga", - "jbocre", - "jbovla", - "xauzma", - "selkei", - "xuncku", - "spusku", - "jbogu'e", - "pampe'o", - "bripre", - "jbosnu", - "zi'evla", - "gimste", - "tolzdi", - "velski", - "samselpla", - "cnegau", - "velcki", - "selja'e", - "fasybau", - "zanfri", - "reisku", - "favgau", - "jbota'a", - "rejgau", - "malgli", - "zilkai", - "keidji", - "tersu'i", - "jbofi'e", - "cnima'o", - "mulgau", - "ningau", - "ponbau", - "mrobi'o", - "rarbau", - "zmanei", - "famyma'o", - "vacysai", - "jetmlu", - "jbonunsla", - "nunpe'i", - "fa'orma'o", - "crezenzu'e", - "jbojbe", - "cmicu'a", - "zilcmi", - "tolcando", - "zukcfu", - "depybu'i", - "mencre", - "matmau", - "nunctu", - "selma'o", - "titnanba", - "naldra", - "jvajvo", - "nunsnu", - "nerkla", - "cimjvo", - "muvgau", - "zipcpi", - "runbau", - "faumlu", - "terbri", - "balcu'e", - "dragau", - "smuvelcki", - "piksku", - "selpli", - "bregau", - "zvafa'i", - "ci'izra", - "noltruti'u", - "samtci", - "snaxa'a", - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file lojban.h + * + * \brief New Lojban word list and map. + */ + +/* + * Word list authored by: sorpaas + * Sources: + * lo gimste jo'u lo ma'oste (https://guskant.github.io/lojbo/gismu-cmavo.html) + * N-grams of Lojban corpus (https://mw.lojban.org/papri/N-grams_of_Lojban_corpus) + */ + +#ifndef LOJBAN_H +#define LOJBAN_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Lojban: public Base + { + public: + Lojban(): Base("Lojban", "Lojban", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "backi", + "bacru", + "badna", + "badri", + "bajra", + "bakfu", + "bakni", + "bakri", + "baktu", + "balji", + "balni", + "balre", + "balvi", + "bambu", + "bancu", + "bandu", + "banfi", + "bangu", + "banli", + "banro", + "banxa", + "banzu", + "bapli", + "barda", + "bargu", + "barja", + "barna", + "bartu", + "basfa", + "basna", + "basti", + "batci", + "batke", + "bavmi", + "baxso", + "bebna", + "bekpi", + "bemro", + "bende", + "bengo", + "benji", + "benre", + "benzo", + "bergu", + "bersa", + "berti", + "besna", + "besto", + "betfu", + "betri", + "bevri", + "bidju", + "bifce", + "bikla", + "bilga", + "bilma", + "bilni", + "bindo", + "binra", + "binxo", + "birje", + "birka", + "birti", + "bisli", + "bitmu", + "bitni", + "blabi", + "blaci", + "blanu", + "bliku", + "bloti", + "bolci", + "bongu", + "boske", + "botpi", + "boxfo", + "boxna", + "bradi", + "brano", + "bratu", + "brazo", + "bredi", + "bridi", + "brife", + "briju", + "brito", + "brivo", + "broda", + "bruna", + "budjo", + "bukpu", + "bumru", + "bunda", + "bunre", + "burcu", + "burna", + "cabna", + "cabra", + "cacra", + "cadga", + "cadzu", + "cafne", + "cagna", + "cakla", + "calku", + "calse", + "canci", + "cando", + "cange", + "canja", + "canko", + "canlu", + "canpa", + "canre", + "canti", + "carce", + "carfu", + "carmi", + "carna", + "cartu", + "carvi", + "casnu", + "catke", + "catlu", + "catni", + "catra", + "caxno", + "cecla", + "cecmu", + "cedra", + "cenba", + "censa", + "centi", + "cerda", + "cerni", + "certu", + "cevni", + "cfale", + "cfari", + "cfika", + "cfila", + "cfine", + "cfipu", + "ciblu", + "cicna", + "cidja", + "cidni", + "cidro", + "cifnu", + "cigla", + "cikna", + "cikre", + "ciksi", + "cilce", + "cilfu", + "cilmo", + "cilre", + "cilta", + "cimde", + "cimni", + "cinba", + "cindu", + "cinfo", + "cinje", + "cinki", + "cinla", + "cinmo", + "cinri", + "cinse", + "cinta", + "cinza", + "cipni", + "cipra", + "cirko", + "cirla", + "ciska", + "cisma", + "cisni", + "ciste", + "citka", + "citno", + "citri", + "citsi", + "civla", + "cizra", + "ckabu", + "ckafi", + "ckaji", + "ckana", + "ckape", + "ckasu", + "ckeji", + "ckiku", + "ckilu", + "ckini", + "ckire", + "ckule", + "ckunu", + "cladu", + "clani", + "claxu", + "cletu", + "clika", + "clinu", + "clira", + "clite", + "cliva", + "clupa", + "cmaci", + "cmalu", + "cmana", + "cmavo", + "cmene", + "cmeta", + "cmevo", + "cmila", + "cmima", + "cmoni", + "cnano", + "cnebo", + "cnemu", + "cnici", + "cnino", + "cnisa", + "cnita", + "cokcu", + "condi", + "conka", + "corci", + "cortu", + "cpacu", + "cpana", + "cpare", + "cpedu", + "cpina", + "cradi", + "crane", + "creka", + "crepu", + "cribe", + "crida", + "crino", + "cripu", + "crisa", + "critu", + "ctaru", + "ctebi", + "cteki", + "ctile", + "ctino", + "ctuca", + "cukla", + "cukre", + "cukta", + "culno", + "cumki", + "cumla", + "cunmi", + "cunso", + "cuntu", + "cupra", + "curmi", + "curnu", + "curve", + "cusku", + "cusna", + "cutci", + "cutne", + "cuxna", + "dacru", + "dacti", + "dadjo", + "dakfu", + "dakli", + "damba", + "damri", + "dandu", + "danfu", + "danlu", + "danmo", + "danre", + "dansu", + "danti", + "daplu", + "dapma", + "darca", + "dargu", + "darlu", + "darno", + "darsi", + "darxi", + "daski", + "dasni", + "daspo", + "dasri", + "datka", + "datni", + "datro", + "decti", + "degji", + "dejni", + "dekpu", + "dekto", + "delno", + "dembi", + "denci", + "denmi", + "denpa", + "dertu", + "derxi", + "desku", + "detri", + "dicma", + "dicra", + "didni", + "digno", + "dikca", + "diklo", + "dikni", + "dilcu", + "dilma", + "dilnu", + "dimna", + "dindi", + "dinju", + "dinko", + "dinso", + "dirba", + "dirce", + "dirgo", + "disko", + "ditcu", + "divzi", + "dizlo", + "djacu", + "djedi", + "djica", + "djine", + "djuno", + "donri", + "dotco", + "draci", + "drani", + "drata", + "drudi", + "dugri", + "dukse", + "dukti", + "dunda", + "dunja", + "dunku", + "dunli", + "dunra", + "dutso", + "dzena", + "dzipo", + "facki", + "fadni", + "fagri", + "falnu", + "famti", + "fancu", + "fange", + "fanmo", + "fanri", + "fanta", + "fanva", + "fanza", + "fapro", + "farka", + "farlu", + "farna", + "farvi", + "fasnu", + "fatci", + "fatne", + "fatri", + "febvi", + "fegli", + "femti", + "fendi", + "fengu", + "fenki", + "fenra", + "fenso", + "fepni", + "fepri", + "ferti", + "festi", + "fetsi", + "figre", + "filso", + "finpe", + "finti", + "firca", + "fisli", + "fizbu", + "flaci", + "flalu", + "flani", + "flecu", + "flese", + "fliba", + "flira", + "foldi", + "fonmo", + "fonxa", + "forca", + "forse", + "fraso", + "frati", + "fraxu", + "frica", + "friko", + "frili", + "frinu", + "friti", + "frumu", + "fukpi", + "fulta", + "funca", + "fusra", + "fuzme", + "gacri", + "gadri", + "galfi", + "galtu", + "galxe", + "ganlo", + "ganra", + "ganse", + "ganti", + "ganxo", + "ganzu", + "gapci", + "gapru", + "garna", + "gasnu", + "gaspo", + "gasta", + "genja", + "gento", + "genxu", + "gerku", + "gerna", + "gidva", + "gigdo", + "ginka", + "girzu", + "gismu", + "glare", + "gleki", + "gletu", + "glico", + "glife", + "glosa", + "gluta", + "gocti", + "gomsi", + "gotro", + "gradu", + "grafu", + "grake", + "grana", + "grasu", + "grava", + "greku", + "grusi", + "grute", + "gubni", + "gugde", + "gugle", + "gumri", + "gundi", + "gunka", + "gunma", + "gunro", + "gunse", + "gunta", + "gurni", + "guska", + "gusni", + "gusta", + "gutci", + "gutra", + "guzme", + "jabre", + "jadni", + "jakne", + "jalge", + "jalna", + "jalra", + "jamfu", + "jamna", + "janbe", + "janco", + "janli", + "jansu", + "janta", + "jarbu", + "jarco", + "jarki", + "jaspu", + "jatna", + "javni", + "jbama", + "jbari", + "jbena", + "jbera", + "jbini", + "jdari", + "jdice", + "jdika", + "jdima", + "jdini", + "jduli", + "jecta", + "jeftu", + "jegvo", + "jelca", + "jemna", + "jenca", + "jendu", + "jenmi", + "jensi", + "jerna", + "jersi", + "jerxo", + "jesni", + "jetce", + "jetnu", + "jgalu", + "jganu", + "jgari", + "jgena", + "jgina", + "jgira", + "jgita", + "jibni", + "jibri", + "jicla", + "jicmu", + "jijnu", + "jikca", + "jikfi", + "jikni", + "jikru", + "jilka", + "jilra", + "jimca", + "jimpe", + "jimte", + "jinci", + "jinda", + "jinga", + "jinku", + "jinme", + "jinru", + "jinsa", + "jinto", + "jinvi", + "jinzi", + "jipci", + "jipno", + "jirna", + "jisra", + "jitfa", + "jitro", + "jivbu", + "jivna", + "jmaji", + "jmifa", + "jmina", + "jmive", + "jonse", + "jordo", + "jorne", + "jubme", + "judri", + "jufra", + "jukni", + "jukpa", + "julne", + "julro", + "jundi", + "jungo", + "junla", + "junri", + "junta", + "jurme", + "jursa", + "jutsi", + "juxre", + "jvinu", + "jviso", + "kabri", + "kacma", + "kadno", + "kafke", + "kagni", + "kajde", + "kajna", + "kakne", + "kakpa", + "kalci", + "kalri", + "kalsa", + "kalte", + "kamju", + "kamni", + "kampu", + "kamre", + "kanba", + "kancu", + "kandi", + "kanji", + "kanla", + "kanpe", + "kanro", + "kansa", + "kantu", + "kanxe", + "karbi", + "karce", + "karda", + "kargu", + "karli", + "karni", + "katci", + "katna", + "kavbu", + "kazra", + "kecti", + "kekli", + "kelci", + "kelvo", + "kenka", + "kenra", + "kensa", + "kerfa", + "kerlo", + "kesri", + "ketco", + "ketsu", + "kevna", + "kibro", + "kicne", + "kijno", + "kilto", + "kinda", + "kinli", + "kisto", + "klaji", + "klaku", + "klama", + "klani", + "klesi", + "kliki", + "klina", + "kliru", + "kliti", + "klupe", + "kluza", + "kobli", + "kogno", + "kojna", + "kokso", + "kolme", + "komcu", + "konju", + "korbi", + "korcu", + "korka", + "korvo", + "kosmu", + "kosta", + "krali", + "kramu", + "krasi", + "krati", + "krefu", + "krici", + "krili", + "krinu", + "krixa", + "kruca", + "kruji", + "kruvi", + "kubli", + "kucli", + "kufra", + "kukte", + "kulnu", + "kumfa", + "kumte", + "kunra", + "kunti", + "kurfa", + "kurji", + "kurki", + "kuspe", + "kusru", + "labno", + "lacni", + "lacpu", + "lacri", + "ladru", + "lafti", + "lakne", + "lakse", + "laldo", + "lalxu", + "lamji", + "lanbi", + "lanci", + "landa", + "lanka", + "lanli", + "lanme", + "lante", + "lanxe", + "lanzu", + "larcu", + "larva", + "lasna", + "lastu", + "latmo", + "latna", + "lazni", + "lebna", + "lelxe", + "lenga", + "lenjo", + "lenku", + "lerci", + "lerfu", + "libjo", + "lidne", + "lifri", + "lijda", + "limfa", + "limna", + "lince", + "lindi", + "linga", + "linji", + "linsi", + "linto", + "lisri", + "liste", + "litce", + "litki", + "litru", + "livga", + "livla", + "logji", + "loglo", + "lojbo", + "loldi", + "lorxu", + "lubno", + "lujvo", + "luksi", + "lumci", + "lunbe", + "lunra", + "lunsa", + "luska", + "lusto", + "mabla", + "mabru", + "macnu", + "majga", + "makcu", + "makfa", + "maksi", + "malsi", + "mamta", + "manci", + "manfo", + "mango", + "manku", + "manri", + "mansa", + "manti", + "mapku", + "mapni", + "mapra", + "mapti", + "marbi", + "marce", + "marde", + "margu", + "marji", + "marna", + "marxa", + "masno", + "masti", + "matci", + "matli", + "matne", + "matra", + "mavji", + "maxri", + "mebri", + "megdo", + "mekso", + "melbi", + "meljo", + "melmi", + "menli", + "menre", + "mensi", + "mentu", + "merko", + "merli", + "metfo", + "mexno", + "midju", + "mifra", + "mikce", + "mikri", + "milti", + "milxe", + "minde", + "minji", + "minli", + "minra", + "mintu", + "mipri", + "mirli", + "misno", + "misro", + "mitre", + "mixre", + "mlana", + "mlatu", + "mleca", + "mledi", + "mluni", + "mogle", + "mokca", + "moklu", + "molki", + "molro", + "morji", + "morko", + "morna", + "morsi", + "mosra", + "mraji", + "mrilu", + "mruli", + "mucti", + "mudri", + "mugle", + "mukti", + "mulno", + "munje", + "mupli", + "murse", + "murta", + "muslo", + "mutce", + "muvdu", + "muzga", + "nabmi", + "nakni", + "nalci", + "namcu", + "nanba", + "nanca", + "nandu", + "nanla", + "nanmu", + "nanvi", + "narge", + "narju", + "natfe", + "natmi", + "natsi", + "navni", + "naxle", + "nazbi", + "nejni", + "nelci", + "nenri", + "nerde", + "nibli", + "nicfa", + "nicte", + "nikle", + "nilce", + "nimre", + "ninja", + "ninmu", + "nirna", + "nitcu", + "nivji", + "nixli", + "nobli", + "norgo", + "notci", + "nudle", + "nukni", + "nunmu", + "nupre", + "nurma", + "nusna", + "nutka", + "nutli", + "nuzba", + "nuzlo", + "pacna", + "pagbu", + "pagre", + "pajni", + "palci", + "palku", + "palma", + "palne", + "palpi", + "palta", + "pambe", + "pamga", + "panci", + "pandi", + "panje", + "panka", + "panlo", + "panpi", + "panra", + "pante", + "panzi", + "papri", + "parbi", + "pardu", + "parji", + "pastu", + "patfu", + "patlu", + "patxu", + "paznu", + "pelji", + "pelxu", + "pemci", + "penbi", + "pencu", + "pendo", + "penmi", + "pensi", + "pentu", + "perli", + "pesxu", + "petso", + "pevna", + "pezli", + "picti", + "pijne", + "pikci", + "pikta", + "pilda", + "pilji", + "pilka", + "pilno", + "pimlu", + "pinca", + "pindi", + "pinfu", + "pinji", + "pinka", + "pinsi", + "pinta", + "pinxe", + "pipno", + "pixra", + "plana", + "platu", + "pleji", + "plibu", + "plini", + "plipe", + "plise", + "plita", + "plixa", + "pluja", + "pluka", + "pluta", + "pocli", + "polje", + "polno", + "ponjo", + "ponse", + "poplu", + "porpi", + "porsi", + "porto", + "prali", + "prami", + "prane", + "preja", + "prenu", + "preri", + "preti", + "prije", + "prina", + "pritu", + "proga", + "prosa", + "pruce", + "pruni", + "pruri", + "pruxi", + "pulce", + "pulji", + "pulni", + "punji", + "punli", + "pupsu", + "purci", + "purdi", + "purmo", + "racli", + "ractu", + "radno", + "rafsi", + "ragbi", + "ragve", + "rakle", + "rakso", + "raktu", + "ralci", + "ralju", + "ralte", + "randa", + "rango", + "ranji", + "ranmi", + "ransu", + "ranti", + "ranxi", + "rapli", + "rarna", + "ratcu", + "ratni", + "rebla", + "rectu", + "rekto", + "remna", + "renro", + "renvi", + "respa", + "rexsa", + "ricfu", + "rigni", + "rijno", + "rilti", + "rimni", + "rinci", + "rindo", + "rinju", + "rinka", + "rinsa", + "rirci", + "rirni", + "rirxe", + "rismi", + "risna", + "ritli", + "rivbi", + "rokci", + "romge", + "romlo", + "ronte", + "ropno", + "rorci", + "rotsu", + "rozgu", + "ruble", + "rufsu", + "runme", + "runta", + "rupnu", + "rusko", + "rutni", + "sabji", + "sabnu", + "sacki", + "saclu", + "sadjo", + "sakci", + "sakli", + "sakta", + "salci", + "salpo", + "salri", + "salta", + "samcu", + "sampu", + "sanbu", + "sance", + "sanga", + "sanji", + "sanli", + "sanmi", + "sanso", + "santa", + "sarcu", + "sarji", + "sarlu", + "sarni", + "sarxe", + "saske", + "satci", + "satre", + "savru", + "sazri", + "sefsi", + "sefta", + "sekre", + "selci", + "selfu", + "semto", + "senci", + "sengi", + "senpi", + "senta", + "senva", + "sepli", + "serti", + "sesre", + "setca", + "sevzi", + "sfani", + "sfasa", + "sfofa", + "sfubu", + "sibli", + "siclu", + "sicni", + "sicpi", + "sidbo", + "sidju", + "sigja", + "sigma", + "sikta", + "silka", + "silna", + "simlu", + "simsa", + "simxu", + "since", + "sinma", + "sinso", + "sinxa", + "sipna", + "sirji", + "sirxo", + "sisku", + "sisti", + "sitna", + "sivni", + "skaci", + "skami", + "skapi", + "skari", + "skicu", + "skiji", + "skina", + "skori", + "skoto", + "skuba", + "skuro", + "slabu", + "slaka", + "slami", + "slanu", + "slari", + "slasi", + "sligu", + "slilu", + "sliri", + "slovo", + "sluji", + "sluni", + "smacu", + "smadi", + "smaji", + "smaka", + "smani", + "smela", + "smoka", + "smuci", + "smuni", + "smusu", + "snada", + "snanu", + "snidu", + "snime", + "snipa", + "snuji", + "snura", + "snuti", + "sobde", + "sodna", + "sodva", + "softo", + "solji", + "solri", + "sombo", + "sonci", + "sorcu", + "sorgu", + "sorni", + "sorta", + "sovda", + "spaji", + "spali", + "spano", + "spati", + "speni", + "spero", + "spisa", + "spita", + "spofu", + "spoja", + "spuda", + "sputu", + "sraji", + "sraku", + "sralo", + "srana", + "srasu", + "srera", + "srito", + "sruma", + "sruri", + "stace", + "stagi", + "staku", + "stali", + "stani", + "stapa", + "stasu", + "stati", + "steba", + "steci", + "stedu", + "stela", + "stero", + "stici", + "stidi", + "stika", + "stizu", + "stodi", + "stuna", + "stura", + "stuzi", + "sucta", + "sudga", + "sufti", + "suksa", + "sumji", + "sumne", + "sumti", + "sunga", + "sunla", + "surla", + "sutra", + "tabno", + "tabra", + "tadji", + "tadni", + "tagji", + "taksi", + "talsa", + "tamca", + "tamji", + "tamne", + "tanbo", + "tance", + "tanjo", + "tanko", + "tanru", + "tansi", + "tanxe", + "tapla", + "tarbi", + "tarci", + "tarla", + "tarmi", + "tarti", + "taske", + "tasmi", + "tasta", + "tatpi", + "tatru", + "tavla", + "taxfu", + "tcaci", + "tcadu", + "tcana", + "tcati", + "tcaxe", + "tcena", + "tcese", + "tcica", + "tcidu", + "tcika", + "tcila", + "tcima", + "tcini", + "tcita", + "temci", + "temse", + "tende", + "tenfa", + "tengu", + "terdi", + "terpa", + "terto", + "tifri", + "tigni", + "tigra", + "tikpa", + "tilju", + "tinbe", + "tinci", + "tinsa", + "tirna", + "tirse", + "tirxu", + "tisna", + "titla", + "tivni", + "tixnu", + "toknu", + "toldi", + "tonga", + "tordu", + "torni", + "torso", + "traji", + "trano", + "trati", + "trene", + "tricu", + "trina", + "trixe", + "troci", + "tsaba", + "tsali", + "tsani", + "tsapi", + "tsiju", + "tsina", + "tsuku", + "tubnu", + "tubra", + "tugni", + "tujli", + "tumla", + "tunba", + "tunka", + "tunlo", + "tunta", + "tuple", + "turko", + "turni", + "tutci", + "tutle", + "tutra", + "vacri", + "vajni", + "valsi", + "vamji", + "vamtu", + "vanbi", + "vanci", + "vanju", + "vasru", + "vasxu", + "vecnu", + "vedli", + "venfu", + "vensa", + "vente", + "vepre", + "verba", + "vibna", + "vidni", + "vidru", + "vifne", + "vikmi", + "viknu", + "vimcu", + "vindu", + "vinji", + "vinta", + "vipsi", + "virnu", + "viska", + "vitci", + "vitke", + "vitno", + "vlagi", + "vlile", + "vlina", + "vlipa", + "vofli", + "voksa", + "volve", + "vorme", + "vraga", + "vreji", + "vreta", + "vrici", + "vrude", + "vrusi", + "vubla", + "vujnu", + "vukna", + "vukro", + "xabju", + "xadba", + "xadji", + "xadni", + "xagji", + "xagri", + "xajmi", + "xaksu", + "xalbo", + "xalka", + "xalni", + "xamgu", + "xampo", + "xamsi", + "xance", + "xango", + "xanka", + "xanri", + "xansa", + "xanto", + "xarci", + "xarju", + "xarnu", + "xasli", + "xasne", + "xatra", + "xatsi", + "xazdo", + "xebni", + "xebro", + "xecto", + "xedja", + "xekri", + "xelso", + "xendo", + "xenru", + "xexso", + "xigzo", + "xindo", + "xinmo", + "xirma", + "xislu", + "xispo", + "xlali", + "xlura", + "xorbo", + "xorlo", + "xotli", + "xrabo", + "xrani", + "xriso", + "xrotu", + "xruba", + "xruki", + "xrula", + "xruti", + "xukmi", + "xulta", + "xunre", + "xurdo", + "xusra", + "xutla", + "zabna", + "zajba", + "zalvi", + "zanru", + "zarci", + "zargu", + "zasni", + "zasti", + "zbabu", + "zbani", + "zbasu", + "zbepi", + "zdani", + "zdile", + "zekri", + "zenba", + "zepti", + "zetro", + "zevla", + "zgadi", + "zgana", + "zgike", + "zifre", + "zinki", + "zirpu", + "zivle", + "zmadu", + "zmiku", + "zucna", + "zukte", + "zumri", + "zungi", + "zunle", + "zunti", + "zutse", + "zvati", + "zviki", + "jbobau", + "jbopre", + "karsna", + "cabdei", + "zunsna", + "gendra", + "glibau", + "nintadni", + "pavyseljirna", + "vlaste", + "selbri", + "latro'a", + "zdakemkulgu'a", + "mriste", + "selsku", + "fu'ivla", + "tolmo'i", + "snavei", + "xagmau", + "retsku", + "ckupau", + "skudji", + "smudra", + "prulamdei", + "vokta'a", + "tinju'i", + "jefyfa'o", + "bavlamdei", + "kinzga", + "jbocre", + "jbovla", + "xauzma", + "selkei", + "xuncku", + "spusku", + "jbogu'e", + "pampe'o", + "bripre", + "jbosnu", + "zi'evla", + "gimste", + "tolzdi", + "velski", + "samselpla", + "cnegau", + "velcki", + "selja'e", + "fasybau", + "zanfri", + "reisku", + "favgau", + "jbota'a", + "rejgau", + "malgli", + "zilkai", + "keidji", + "tersu'i", + "jbofi'e", + "cnima'o", + "mulgau", + "ningau", + "ponbau", + "mrobi'o", + "rarbau", + "zmanei", + "famyma'o", + "vacysai", + "jetmlu", + "jbonunsla", + "nunpe'i", + "fa'orma'o", + "crezenzu'e", + "jbojbe", + "cmicu'a", + "zilcmi", + "tolcando", + "zukcfu", + "depybu'i", + "mencre", + "matmau", + "nunctu", + "selma'o", + "titnanba", + "naldra", + "jvajvo", + "nunsnu", + "nerkla", + "cimjvo", + "muvgau", + "zipcpi", + "runbau", + "faumlu", + "terbri", + "balcu'e", + "dragau", + "smuvelcki", + "piksku", + "selpli", + "bregau", + "zvafa'i", + "ci'izra", + "noltruti'u", + "samtci", + "snaxa'a", + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/portuguese.h b/src/mnemonics/portuguese.h index dbc51fb2a..73b01133e 100644 --- a/src/mnemonics/portuguese.h +++ b/src/mnemonics/portuguese.h @@ -1,1712 +1,1712 @@ -// Word list originally created by dabura667 and released under The MIT License (MIT) -// -// The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file portuguese.h - * - * \brief Portuguese word list and map. - */ - -#ifndef PORTUGUESE_H -#define PORTUGUESE_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Portuguese: public Base - { - public: - Portuguese(): Base("Português", "Portuguese", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "abaular", - "abdominal", - "abeto", - "abissinio", - "abjeto", - "ablucao", - "abnegar", - "abotoar", - "abrutalhar", - "absurdo", - "abutre", - "acautelar", - "accessorios", - "acetona", - "achocolatado", - "acirrar", - "acne", - "acovardar", - "acrostico", - "actinomicete", - "acustico", - "adaptavel", - "adeus", - "adivinho", - "adjunto", - "admoestar", - "adnominal", - "adotivo", - "adquirir", - "adriatico", - "adsorcao", - "adutora", - "advogar", - "aerossol", - "afazeres", - "afetuoso", - "afixo", - "afluir", - "afortunar", - "afrouxar", - "aftosa", - "afunilar", - "agentes", - "agito", - "aglutinar", - "aiatola", - "aimore", - "aino", - "aipo", - "airoso", - "ajeitar", - "ajoelhar", - "ajudante", - "ajuste", - "alazao", - "albumina", - "alcunha", - "alegria", - "alexandre", - "alforriar", - "alguns", - "alhures", - "alivio", - "almoxarife", - "alotropico", - "alpiste", - "alquimista", - "alsaciano", - "altura", - "aluviao", - "alvura", - "amazonico", - "ambulatorio", - "ametodico", - "amizades", - "amniotico", - "amovivel", - "amurada", - "anatomico", - "ancorar", - "anexo", - "anfora", - "aniversario", - "anjo", - "anotar", - "ansioso", - "anturio", - "anuviar", - "anverso", - "anzol", - "aonde", - "apaziguar", - "apito", - "aplicavel", - "apoteotico", - "aprimorar", - "aprumo", - "apto", - "apuros", - "aquoso", - "arauto", - "arbusto", - "arduo", - "aresta", - "arfar", - "arguto", - "aritmetico", - "arlequim", - "armisticio", - "aromatizar", - "arpoar", - "arquivo", - "arrumar", - "arsenio", - "arturiano", - "aruaque", - "arvores", - "asbesto", - "ascorbico", - "aspirina", - "asqueroso", - "assustar", - "astuto", - "atazanar", - "ativo", - "atletismo", - "atmosferico", - "atormentar", - "atroz", - "aturdir", - "audivel", - "auferir", - "augusto", - "aula", - "aumento", - "aurora", - "autuar", - "avatar", - "avexar", - "avizinhar", - "avolumar", - "avulso", - "axiomatico", - "azerbaijano", - "azimute", - "azoto", - "azulejo", - "bacteriologista", - "badulaque", - "baforada", - "baixote", - "bajular", - "balzaquiana", - "bambuzal", - "banzo", - "baoba", - "baqueta", - "barulho", - "bastonete", - "batuta", - "bauxita", - "bavaro", - "bazuca", - "bcrepuscular", - "beato", - "beduino", - "begonia", - "behaviorista", - "beisebol", - "belzebu", - "bemol", - "benzido", - "beocio", - "bequer", - "berro", - "besuntar", - "betume", - "bexiga", - "bezerro", - "biatlon", - "biboca", - "bicuspide", - "bidirecional", - "bienio", - "bifurcar", - "bigorna", - "bijuteria", - "bimotor", - "binormal", - "bioxido", - "bipolarizacao", - "biquini", - "birutice", - "bisturi", - "bituca", - "biunivoco", - "bivalve", - "bizarro", - "blasfemo", - "blenorreia", - "blindar", - "bloqueio", - "blusao", - "boazuda", - "bofete", - "bojudo", - "bolso", - "bombordo", - "bonzo", - "botina", - "boquiaberto", - "bostoniano", - "botulismo", - "bourbon", - "bovino", - "boximane", - "bravura", - "brevidade", - "britar", - "broxar", - "bruno", - "bruxuleio", - "bubonico", - "bucolico", - "buda", - "budista", - "bueiro", - "buffer", - "bugre", - "bujao", - "bumerangue", - "burundines", - "busto", - "butique", - "buzios", - "caatinga", - "cabuqui", - "cacunda", - "cafuzo", - "cajueiro", - "camurca", - "canudo", - "caquizeiro", - "carvoeiro", - "casulo", - "catuaba", - "cauterizar", - "cebolinha", - "cedula", - "ceifeiro", - "celulose", - "cerzir", - "cesto", - "cetro", - "ceus", - "cevar", - "chavena", - "cheroqui", - "chita", - "chovido", - "chuvoso", - "ciatico", - "cibernetico", - "cicuta", - "cidreira", - "cientistas", - "cifrar", - "cigarro", - "cilio", - "cimo", - "cinzento", - "cioso", - "cipriota", - "cirurgico", - "cisto", - "citrico", - "ciumento", - "civismo", - "clavicula", - "clero", - "clitoris", - "cluster", - "coaxial", - "cobrir", - "cocota", - "codorniz", - "coexistir", - "cogumelo", - "coito", - "colusao", - "compaixao", - "comutativo", - "contentamento", - "convulsivo", - "coordenativa", - "coquetel", - "correto", - "corvo", - "costureiro", - "cotovia", - "covil", - "cozinheiro", - "cretino", - "cristo", - "crivo", - "crotalo", - "cruzes", - "cubo", - "cucuia", - "cueiro", - "cuidar", - "cujo", - "cultural", - "cunilingua", - "cupula", - "curvo", - "custoso", - "cutucar", - "czarismo", - "dablio", - "dacota", - "dados", - "daguerreotipo", - "daiquiri", - "daltonismo", - "damista", - "dantesco", - "daquilo", - "darwinista", - "dasein", - "dativo", - "deao", - "debutantes", - "decurso", - "deduzir", - "defunto", - "degustar", - "dejeto", - "deltoide", - "demover", - "denunciar", - "deputado", - "deque", - "dervixe", - "desvirtuar", - "deturpar", - "deuteronomio", - "devoto", - "dextrose", - "dezoito", - "diatribe", - "dicotomico", - "didatico", - "dietista", - "difuso", - "digressao", - "diluvio", - "diminuto", - "dinheiro", - "dinossauro", - "dioxido", - "diplomatico", - "dique", - "dirimivel", - "disturbio", - "diurno", - "divulgar", - "dizivel", - "doar", - "dobro", - "docura", - "dodoi", - "doer", - "dogue", - "doloso", - "domo", - "donzela", - "doping", - "dorsal", - "dossie", - "dote", - "doutro", - "doze", - "dravidico", - "dreno", - "driver", - "dropes", - "druso", - "dubnio", - "ducto", - "dueto", - "dulija", - "dundum", - "duodeno", - "duquesa", - "durou", - "duvidoso", - "duzia", - "ebano", - "ebrio", - "eburneo", - "echarpe", - "eclusa", - "ecossistema", - "ectoplasma", - "ecumenismo", - "eczema", - "eden", - "editorial", - "edredom", - "edulcorar", - "efetuar", - "efigie", - "efluvio", - "egiptologo", - "egresso", - "egua", - "einsteiniano", - "eira", - "eivar", - "eixos", - "ejetar", - "elastomero", - "eldorado", - "elixir", - "elmo", - "eloquente", - "elucidativo", - "emaranhar", - "embutir", - "emerito", - "emfa", - "emitir", - "emotivo", - "empuxo", - "emulsao", - "enamorar", - "encurvar", - "enduro", - "enevoar", - "enfurnar", - "enguico", - "enho", - "enigmista", - "enlutar", - "enormidade", - "enpreendimento", - "enquanto", - "enriquecer", - "enrugar", - "entusiastico", - "enunciar", - "envolvimento", - "enxuto", - "enzimatico", - "eolico", - "epiteto", - "epoxi", - "epura", - "equivoco", - "erario", - "erbio", - "ereto", - "erguido", - "erisipela", - "ermo", - "erotizar", - "erros", - "erupcao", - "ervilha", - "esburacar", - "escutar", - "esfuziante", - "esguio", - "esloveno", - "esmurrar", - "esoterismo", - "esperanca", - "espirito", - "espurio", - "essencialmente", - "esturricar", - "esvoacar", - "etario", - "eterno", - "etiquetar", - "etnologo", - "etos", - "etrusco", - "euclidiano", - "euforico", - "eugenico", - "eunuco", - "europio", - "eustaquio", - "eutanasia", - "evasivo", - "eventualidade", - "evitavel", - "evoluir", - "exaustor", - "excursionista", - "exercito", - "exfoliado", - "exito", - "exotico", - "expurgo", - "exsudar", - "extrusora", - "exumar", - "fabuloso", - "facultativo", - "fado", - "fagulha", - "faixas", - "fajuto", - "faltoso", - "famoso", - "fanzine", - "fapesp", - "faquir", - "fartura", - "fastio", - "faturista", - "fausto", - "favorito", - "faxineira", - "fazer", - "fealdade", - "febril", - "fecundo", - "fedorento", - "feerico", - "feixe", - "felicidade", - "felpudo", - "feltro", - "femur", - "fenotipo", - "fervura", - "festivo", - "feto", - "feudo", - "fevereiro", - "fezinha", - "fiasco", - "fibra", - "ficticio", - "fiduciario", - "fiesp", - "fifa", - "figurino", - "fijiano", - "filtro", - "finura", - "fiorde", - "fiquei", - "firula", - "fissurar", - "fitoteca", - "fivela", - "fixo", - "flavio", - "flexor", - "flibusteiro", - "flotilha", - "fluxograma", - "fobos", - "foco", - "fofura", - "foguista", - "foie", - "foliculo", - "fominha", - "fonte", - "forum", - "fosso", - "fotossintese", - "foxtrote", - "fraudulento", - "frevo", - "frivolo", - "frouxo", - "frutose", - "fuba", - "fucsia", - "fugitivo", - "fuinha", - "fujao", - "fulustreco", - "fumo", - "funileiro", - "furunculo", - "fustigar", - "futurologo", - "fuxico", - "fuzue", - "gabriel", - "gado", - "gaelico", - "gafieira", - "gaguejo", - "gaivota", - "gajo", - "galvanoplastico", - "gamo", - "ganso", - "garrucha", - "gastronomo", - "gatuno", - "gaussiano", - "gaviao", - "gaxeta", - "gazeteiro", - "gear", - "geiser", - "geminiano", - "generoso", - "genuino", - "geossinclinal", - "gerundio", - "gestual", - "getulista", - "gibi", - "gigolo", - "gilete", - "ginseng", - "giroscopio", - "glaucio", - "glacial", - "gleba", - "glifo", - "glote", - "glutonia", - "gnostico", - "goela", - "gogo", - "goitaca", - "golpista", - "gomo", - "gonzo", - "gorro", - "gostou", - "goticula", - "gourmet", - "governo", - "gozo", - "graxo", - "grevista", - "grito", - "grotesco", - "gruta", - "guaxinim", - "gude", - "gueto", - "guizo", - "guloso", - "gume", - "guru", - "gustativo", - "grelhado", - "gutural", - "habitue", - "haitiano", - "halterofilista", - "hamburguer", - "hanseniase", - "happening", - "harpista", - "hastear", - "haveres", - "hebreu", - "hectometro", - "hedonista", - "hegira", - "helena", - "helminto", - "hemorroidas", - "henrique", - "heptassilabo", - "hertziano", - "hesitar", - "heterossexual", - "heuristico", - "hexagono", - "hiato", - "hibrido", - "hidrostatico", - "hieroglifo", - "hifenizar", - "higienizar", - "hilario", - "himen", - "hino", - "hippie", - "hirsuto", - "historiografia", - "hitlerista", - "hodometro", - "hoje", - "holograma", - "homus", - "honroso", - "hoquei", - "horto", - "hostilizar", - "hotentote", - "huguenote", - "humilde", - "huno", - "hurra", - "hutu", - "iaia", - "ialorixa", - "iambico", - "iansa", - "iaque", - "iara", - "iatista", - "iberico", - "ibis", - "icar", - "iceberg", - "icosagono", - "idade", - "ideologo", - "idiotice", - "idoso", - "iemenita", - "iene", - "igarape", - "iglu", - "ignorar", - "igreja", - "iguaria", - "iidiche", - "ilativo", - "iletrado", - "ilharga", - "ilimitado", - "ilogismo", - "ilustrissimo", - "imaturo", - "imbuzeiro", - "imerso", - "imitavel", - "imovel", - "imputar", - "imutavel", - "inaveriguavel", - "incutir", - "induzir", - "inextricavel", - "infusao", - "ingua", - "inhame", - "iniquo", - "injusto", - "inning", - "inoxidavel", - "inquisitorial", - "insustentavel", - "intumescimento", - "inutilizavel", - "invulneravel", - "inzoneiro", - "iodo", - "iogurte", - "ioio", - "ionosfera", - "ioruba", - "iota", - "ipsilon", - "irascivel", - "iris", - "irlandes", - "irmaos", - "iroques", - "irrupcao", - "isca", - "isento", - "islandes", - "isotopo", - "isqueiro", - "israelita", - "isso", - "isto", - "iterbio", - "itinerario", - "itrio", - "iuane", - "iugoslavo", - "jabuticabeira", - "jacutinga", - "jade", - "jagunco", - "jainista", - "jaleco", - "jambo", - "jantarada", - "japones", - "jaqueta", - "jarro", - "jasmim", - "jato", - "jaula", - "javel", - "jazz", - "jegue", - "jeitoso", - "jejum", - "jenipapo", - "jeova", - "jequitiba", - "jersei", - "jesus", - "jetom", - "jiboia", - "jihad", - "jilo", - "jingle", - "jipe", - "jocoso", - "joelho", - "joguete", - "joio", - "jojoba", - "jorro", - "jota", - "joule", - "joviano", - "jubiloso", - "judoca", - "jugular", - "juizo", - "jujuba", - "juliano", - "jumento", - "junto", - "jururu", - "justo", - "juta", - "juventude", - "labutar", - "laguna", - "laico", - "lajota", - "lanterninha", - "lapso", - "laquear", - "lastro", - "lauto", - "lavrar", - "laxativo", - "lazer", - "leasing", - "lebre", - "lecionar", - "ledo", - "leguminoso", - "leitura", - "lele", - "lemure", - "lento", - "leonardo", - "leopardo", - "lepton", - "leque", - "leste", - "letreiro", - "leucocito", - "levitico", - "lexicologo", - "lhama", - "lhufas", - "liame", - "licoroso", - "lidocaina", - "liliputiano", - "limusine", - "linotipo", - "lipoproteina", - "liquidos", - "lirismo", - "lisura", - "liturgico", - "livros", - "lixo", - "lobulo", - "locutor", - "lodo", - "logro", - "lojista", - "lombriga", - "lontra", - "loop", - "loquaz", - "lorota", - "losango", - "lotus", - "louvor", - "luar", - "lubrificavel", - "lucros", - "lugubre", - "luis", - "luminoso", - "luneta", - "lustroso", - "luto", - "luvas", - "luxuriante", - "luzeiro", - "maduro", - "maestro", - "mafioso", - "magro", - "maiuscula", - "majoritario", - "malvisto", - "mamute", - "manutencao", - "mapoteca", - "maquinista", - "marzipa", - "masturbar", - "matuto", - "mausoleu", - "mavioso", - "maxixe", - "mazurca", - "meandro", - "mecha", - "medusa", - "mefistofelico", - "megera", - "meirinho", - "melro", - "memorizar", - "menu", - "mequetrefe", - "mertiolate", - "mestria", - "metroviario", - "mexilhao", - "mezanino", - "miau", - "microssegundo", - "midia", - "migratorio", - "mimosa", - "minuto", - "miosotis", - "mirtilo", - "misturar", - "mitzvah", - "miudos", - "mixuruca", - "mnemonico", - "moagem", - "mobilizar", - "modulo", - "moer", - "mofo", - "mogno", - "moita", - "molusco", - "monumento", - "moqueca", - "morubixaba", - "mostruario", - "motriz", - "mouse", - "movivel", - "mozarela", - "muarra", - "muculmano", - "mudo", - "mugir", - "muitos", - "mumunha", - "munir", - "muon", - "muquira", - "murros", - "musselina", - "nacoes", - "nado", - "naftalina", - "nago", - "naipe", - "naja", - "nalgum", - "namoro", - "nanquim", - "napolitano", - "naquilo", - "nascimento", - "nautilo", - "navios", - "nazista", - "nebuloso", - "nectarina", - "nefrologo", - "negus", - "nelore", - "nenufar", - "nepotismo", - "nervura", - "neste", - "netuno", - "neutron", - "nevoeiro", - "newtoniano", - "nexo", - "nhenhenhem", - "nhoque", - "nigeriano", - "niilista", - "ninho", - "niobio", - "niponico", - "niquelar", - "nirvana", - "nisto", - "nitroglicerina", - "nivoso", - "nobreza", - "nocivo", - "noel", - "nogueira", - "noivo", - "nojo", - "nominativo", - "nonuplo", - "noruegues", - "nostalgico", - "noturno", - "nouveau", - "nuanca", - "nublar", - "nucleotideo", - "nudista", - "nulo", - "numismatico", - "nunquinha", - "nupcias", - "nutritivo", - "nuvens", - "oasis", - "obcecar", - "obeso", - "obituario", - "objetos", - "oblongo", - "obnoxio", - "obrigatorio", - "obstruir", - "obtuso", - "obus", - "obvio", - "ocaso", - "occipital", - "oceanografo", - "ocioso", - "oclusivo", - "ocorrer", - "ocre", - "octogono", - "odalisca", - "odisseia", - "odorifico", - "oersted", - "oeste", - "ofertar", - "ofidio", - "oftalmologo", - "ogiva", - "ogum", - "oigale", - "oitavo", - "oitocentos", - "ojeriza", - "olaria", - "oleoso", - "olfato", - "olhos", - "oliveira", - "olmo", - "olor", - "olvidavel", - "ombudsman", - "omeleteira", - "omitir", - "omoplata", - "onanismo", - "ondular", - "oneroso", - "onomatopeico", - "ontologico", - "onus", - "onze", - "opalescente", - "opcional", - "operistico", - "opio", - "oposto", - "oprobrio", - "optometrista", - "opusculo", - "oratorio", - "orbital", - "orcar", - "orfao", - "orixa", - "orla", - "ornitologo", - "orquidea", - "ortorrombico", - "orvalho", - "osculo", - "osmotico", - "ossudo", - "ostrogodo", - "otario", - "otite", - "ouro", - "ousar", - "outubro", - "ouvir", - "ovario", - "overnight", - "oviparo", - "ovni", - "ovoviviparo", - "ovulo", - "oxala", - "oxente", - "oxiuro", - "oxossi", - "ozonizar", - "paciente", - "pactuar", - "padronizar", - "paete", - "pagodeiro", - "paixao", - "pajem", - "paludismo", - "pampas", - "panturrilha", - "papudo", - "paquistanes", - "pastoso", - "patua", - "paulo", - "pauzinhos", - "pavoroso", - "paxa", - "pazes", - "peao", - "pecuniario", - "pedunculo", - "pegaso", - "peixinho", - "pejorativo", - "pelvis", - "penuria", - "pequno", - "petunia", - "pezada", - "piauiense", - "pictorico", - "pierro", - "pigmeu", - "pijama", - "pilulas", - "pimpolho", - "pintura", - "piorar", - "pipocar", - "piqueteiro", - "pirulito", - "pistoleiro", - "pituitaria", - "pivotar", - "pixote", - "pizzaria", - "plistoceno", - "plotar", - "pluviometrico", - "pneumonico", - "poco", - "podridao", - "poetisa", - "pogrom", - "pois", - "polvorosa", - "pomposo", - "ponderado", - "pontudo", - "populoso", - "poquer", - "porvir", - "posudo", - "potro", - "pouso", - "povoar", - "prazo", - "prezar", - "privilegios", - "proximo", - "prussiano", - "pseudopode", - "psoriase", - "pterossauros", - "ptialina", - "ptolemaico", - "pudor", - "pueril", - "pufe", - "pugilista", - "puir", - "pujante", - "pulverizar", - "pumba", - "punk", - "purulento", - "pustula", - "putsch", - "puxe", - "quatrocentos", - "quetzal", - "quixotesco", - "quotizavel", - "rabujice", - "racista", - "radonio", - "rafia", - "ragu", - "rajado", - "ralo", - "rampeiro", - "ranzinza", - "raptor", - "raquitismo", - "raro", - "rasurar", - "ratoeira", - "ravioli", - "razoavel", - "reavivar", - "rebuscar", - "recusavel", - "reduzivel", - "reexposicao", - "refutavel", - "regurgitar", - "reivindicavel", - "rejuvenescimento", - "relva", - "remuneravel", - "renunciar", - "reorientar", - "repuxo", - "requisito", - "resumo", - "returno", - "reutilizar", - "revolvido", - "rezonear", - "riacho", - "ribossomo", - "ricota", - "ridiculo", - "rifle", - "rigoroso", - "rijo", - "rimel", - "rins", - "rios", - "riqueza", - "respeito", - "rissole", - "ritualistico", - "rivalizar", - "rixa", - "robusto", - "rococo", - "rodoviario", - "roer", - "rogo", - "rojao", - "rolo", - "rompimento", - "ronronar", - "roqueiro", - "rorqual", - "rosto", - "rotundo", - "rouxinol", - "roxo", - "royal", - "ruas", - "rucula", - "rudimentos", - "ruela", - "rufo", - "rugoso", - "ruivo", - "rule", - "rumoroso", - "runico", - "ruptura", - "rural", - "rustico", - "rutilar", - "saariano", - "sabujo", - "sacudir", - "sadomasoquista", - "safra", - "sagui", - "sais", - "samurai", - "santuario", - "sapo", - "saquear", - "sartriano", - "saturno", - "saude", - "sauva", - "saveiro", - "saxofonista", - "sazonal", - "scherzo", - "script", - "seara", - "seborreia", - "secura", - "seduzir", - "sefardim", - "seguro", - "seja", - "selvas", - "sempre", - "senzala", - "sepultura", - "sequoia", - "sestercio", - "setuplo", - "seus", - "seviciar", - "sezonismo", - "shalom", - "siames", - "sibilante", - "sicrano", - "sidra", - "sifilitico", - "signos", - "silvo", - "simultaneo", - "sinusite", - "sionista", - "sirio", - "sisudo", - "situar", - "sivan", - "slide", - "slogan", - "soar", - "sobrio", - "socratico", - "sodomizar", - "soerguer", - "software", - "sogro", - "soja", - "solver", - "somente", - "sonso", - "sopro", - "soquete", - "sorveteiro", - "sossego", - "soturno", - "sousafone", - "sovinice", - "sozinho", - "suavizar", - "subverter", - "sucursal", - "sudoriparo", - "sufragio", - "sugestoes", - "suite", - "sujo", - "sultao", - "sumula", - "suntuoso", - "suor", - "supurar", - "suruba", - "susto", - "suturar", - "suvenir", - "tabuleta", - "taco", - "tadjique", - "tafeta", - "tagarelice", - "taitiano", - "talvez", - "tampouco", - "tanzaniano", - "taoista", - "tapume", - "taquion", - "tarugo", - "tascar", - "tatuar", - "tautologico", - "tavola", - "taxionomista", - "tchecoslovaco", - "teatrologo", - "tectonismo", - "tedioso", - "teflon", - "tegumento", - "teixo", - "telurio", - "temporas", - "tenue", - "teosofico", - "tepido", - "tequila", - "terrorista", - "testosterona", - "tetrico", - "teutonico", - "teve", - "texugo", - "tiara", - "tibia", - "tiete", - "tifoide", - "tigresa", - "tijolo", - "tilintar", - "timpano", - "tintureiro", - "tiquete", - "tiroteio", - "tisico", - "titulos", - "tive", - "toar", - "toboga", - "tofu", - "togoles", - "toicinho", - "tolueno", - "tomografo", - "tontura", - "toponimo", - "toquio", - "torvelinho", - "tostar", - "toto", - "touro", - "toxina", - "trazer", - "trezentos", - "trivialidade", - "trovoar", - "truta", - "tuaregue", - "tubular", - "tucano", - "tudo", - "tufo", - "tuiste", - "tulipa", - "tumultuoso", - "tunisino", - "tupiniquim", - "turvo", - "tutu", - "ucraniano", - "udenista", - "ufanista", - "ufologo", - "ugaritico", - "uiste", - "uivo", - "ulceroso", - "ulema", - "ultravioleta", - "umbilical", - "umero", - "umido", - "umlaut", - "unanimidade", - "unesco", - "ungulado", - "unheiro", - "univoco", - "untuoso", - "urano", - "urbano", - "urdir", - "uretra", - "urgente", - "urinol", - "urna", - "urologo", - "urro", - "ursulina", - "urtiga", - "urupe", - "usavel", - "usbeque", - "usei", - "usineiro", - "usurpar", - "utero", - "utilizar", - "utopico", - "uvular", - "uxoricidio", - "vacuo", - "vadio", - "vaguear", - "vaivem", - "valvula", - "vampiro", - "vantajoso", - "vaporoso", - "vaquinha", - "varziano", - "vasto", - "vaticinio", - "vaudeville", - "vazio", - "veado", - "vedico", - "veemente", - "vegetativo", - "veio", - "veja", - "veludo", - "venusiano", - "verdade", - "verve", - "vestuario", - "vetusto", - "vexatorio", - "vezes", - "viavel", - "vibratorio", - "victor", - "vicunha", - "vidros", - "vietnamita", - "vigoroso", - "vilipendiar", - "vime", - "vintem", - "violoncelo", - "viquingue", - "virus", - "visualizar", - "vituperio", - "viuvo", - "vivo", - "vizir", - "voar", - "vociferar", - "vodu", - "vogar", - "voile", - "volver", - "vomito", - "vontade", - "vortice", - "vosso", - "voto", - "vovozinha", - "voyeuse", - "vozes", - "vulva", - "vupt", - "western", - "xadrez", - "xale", - "xampu", - "xango", - "xarope", - "xaual", - "xavante", - "xaxim", - "xenonio", - "xepa", - "xerox", - "xicara", - "xifopago", - "xiita", - "xilogravura", - "xinxim", - "xistoso", - "xixi", - "xodo", - "xogum", - "xucro", - "zabumba", - "zagueiro", - "zambiano", - "zanzar", - "zarpar", - "zebu", - "zefiro", - "zeloso", - "zenite", - "zumbi" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list originally created by dabura667 and released under The MIT License (MIT) +// +// The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file portuguese.h + * + * \brief Portuguese word list and map. + */ + +#ifndef PORTUGUESE_H +#define PORTUGUESE_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Portuguese: public Base + { + public: + Portuguese(): Base("Português", "Portuguese", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "abaular", + "abdominal", + "abeto", + "abissinio", + "abjeto", + "ablucao", + "abnegar", + "abotoar", + "abrutalhar", + "absurdo", + "abutre", + "acautelar", + "accessorios", + "acetona", + "achocolatado", + "acirrar", + "acne", + "acovardar", + "acrostico", + "actinomicete", + "acustico", + "adaptavel", + "adeus", + "adivinho", + "adjunto", + "admoestar", + "adnominal", + "adotivo", + "adquirir", + "adriatico", + "adsorcao", + "adutora", + "advogar", + "aerossol", + "afazeres", + "afetuoso", + "afixo", + "afluir", + "afortunar", + "afrouxar", + "aftosa", + "afunilar", + "agentes", + "agito", + "aglutinar", + "aiatola", + "aimore", + "aino", + "aipo", + "airoso", + "ajeitar", + "ajoelhar", + "ajudante", + "ajuste", + "alazao", + "albumina", + "alcunha", + "alegria", + "alexandre", + "alforriar", + "alguns", + "alhures", + "alivio", + "almoxarife", + "alotropico", + "alpiste", + "alquimista", + "alsaciano", + "altura", + "aluviao", + "alvura", + "amazonico", + "ambulatorio", + "ametodico", + "amizades", + "amniotico", + "amovivel", + "amurada", + "anatomico", + "ancorar", + "anexo", + "anfora", + "aniversario", + "anjo", + "anotar", + "ansioso", + "anturio", + "anuviar", + "anverso", + "anzol", + "aonde", + "apaziguar", + "apito", + "aplicavel", + "apoteotico", + "aprimorar", + "aprumo", + "apto", + "apuros", + "aquoso", + "arauto", + "arbusto", + "arduo", + "aresta", + "arfar", + "arguto", + "aritmetico", + "arlequim", + "armisticio", + "aromatizar", + "arpoar", + "arquivo", + "arrumar", + "arsenio", + "arturiano", + "aruaque", + "arvores", + "asbesto", + "ascorbico", + "aspirina", + "asqueroso", + "assustar", + "astuto", + "atazanar", + "ativo", + "atletismo", + "atmosferico", + "atormentar", + "atroz", + "aturdir", + "audivel", + "auferir", + "augusto", + "aula", + "aumento", + "aurora", + "autuar", + "avatar", + "avexar", + "avizinhar", + "avolumar", + "avulso", + "axiomatico", + "azerbaijano", + "azimute", + "azoto", + "azulejo", + "bacteriologista", + "badulaque", + "baforada", + "baixote", + "bajular", + "balzaquiana", + "bambuzal", + "banzo", + "baoba", + "baqueta", + "barulho", + "bastonete", + "batuta", + "bauxita", + "bavaro", + "bazuca", + "bcrepuscular", + "beato", + "beduino", + "begonia", + "behaviorista", + "beisebol", + "belzebu", + "bemol", + "benzido", + "beocio", + "bequer", + "berro", + "besuntar", + "betume", + "bexiga", + "bezerro", + "biatlon", + "biboca", + "bicuspide", + "bidirecional", + "bienio", + "bifurcar", + "bigorna", + "bijuteria", + "bimotor", + "binormal", + "bioxido", + "bipolarizacao", + "biquini", + "birutice", + "bisturi", + "bituca", + "biunivoco", + "bivalve", + "bizarro", + "blasfemo", + "blenorreia", + "blindar", + "bloqueio", + "blusao", + "boazuda", + "bofete", + "bojudo", + "bolso", + "bombordo", + "bonzo", + "botina", + "boquiaberto", + "bostoniano", + "botulismo", + "bourbon", + "bovino", + "boximane", + "bravura", + "brevidade", + "britar", + "broxar", + "bruno", + "bruxuleio", + "bubonico", + "bucolico", + "buda", + "budista", + "bueiro", + "buffer", + "bugre", + "bujao", + "bumerangue", + "burundines", + "busto", + "butique", + "buzios", + "caatinga", + "cabuqui", + "cacunda", + "cafuzo", + "cajueiro", + "camurca", + "canudo", + "caquizeiro", + "carvoeiro", + "casulo", + "catuaba", + "cauterizar", + "cebolinha", + "cedula", + "ceifeiro", + "celulose", + "cerzir", + "cesto", + "cetro", + "ceus", + "cevar", + "chavena", + "cheroqui", + "chita", + "chovido", + "chuvoso", + "ciatico", + "cibernetico", + "cicuta", + "cidreira", + "cientistas", + "cifrar", + "cigarro", + "cilio", + "cimo", + "cinzento", + "cioso", + "cipriota", + "cirurgico", + "cisto", + "citrico", + "ciumento", + "civismo", + "clavicula", + "clero", + "clitoris", + "cluster", + "coaxial", + "cobrir", + "cocota", + "codorniz", + "coexistir", + "cogumelo", + "coito", + "colusao", + "compaixao", + "comutativo", + "contentamento", + "convulsivo", + "coordenativa", + "coquetel", + "correto", + "corvo", + "costureiro", + "cotovia", + "covil", + "cozinheiro", + "cretino", + "cristo", + "crivo", + "crotalo", + "cruzes", + "cubo", + "cucuia", + "cueiro", + "cuidar", + "cujo", + "cultural", + "cunilingua", + "cupula", + "curvo", + "custoso", + "cutucar", + "czarismo", + "dablio", + "dacota", + "dados", + "daguerreotipo", + "daiquiri", + "daltonismo", + "damista", + "dantesco", + "daquilo", + "darwinista", + "dasein", + "dativo", + "deao", + "debutantes", + "decurso", + "deduzir", + "defunto", + "degustar", + "dejeto", + "deltoide", + "demover", + "denunciar", + "deputado", + "deque", + "dervixe", + "desvirtuar", + "deturpar", + "deuteronomio", + "devoto", + "dextrose", + "dezoito", + "diatribe", + "dicotomico", + "didatico", + "dietista", + "difuso", + "digressao", + "diluvio", + "diminuto", + "dinheiro", + "dinossauro", + "dioxido", + "diplomatico", + "dique", + "dirimivel", + "disturbio", + "diurno", + "divulgar", + "dizivel", + "doar", + "dobro", + "docura", + "dodoi", + "doer", + "dogue", + "doloso", + "domo", + "donzela", + "doping", + "dorsal", + "dossie", + "dote", + "doutro", + "doze", + "dravidico", + "dreno", + "driver", + "dropes", + "druso", + "dubnio", + "ducto", + "dueto", + "dulija", + "dundum", + "duodeno", + "duquesa", + "durou", + "duvidoso", + "duzia", + "ebano", + "ebrio", + "eburneo", + "echarpe", + "eclusa", + "ecossistema", + "ectoplasma", + "ecumenismo", + "eczema", + "eden", + "editorial", + "edredom", + "edulcorar", + "efetuar", + "efigie", + "efluvio", + "egiptologo", + "egresso", + "egua", + "einsteiniano", + "eira", + "eivar", + "eixos", + "ejetar", + "elastomero", + "eldorado", + "elixir", + "elmo", + "eloquente", + "elucidativo", + "emaranhar", + "embutir", + "emerito", + "emfa", + "emitir", + "emotivo", + "empuxo", + "emulsao", + "enamorar", + "encurvar", + "enduro", + "enevoar", + "enfurnar", + "enguico", + "enho", + "enigmista", + "enlutar", + "enormidade", + "enpreendimento", + "enquanto", + "enriquecer", + "enrugar", + "entusiastico", + "enunciar", + "envolvimento", + "enxuto", + "enzimatico", + "eolico", + "epiteto", + "epoxi", + "epura", + "equivoco", + "erario", + "erbio", + "ereto", + "erguido", + "erisipela", + "ermo", + "erotizar", + "erros", + "erupcao", + "ervilha", + "esburacar", + "escutar", + "esfuziante", + "esguio", + "esloveno", + "esmurrar", + "esoterismo", + "esperanca", + "espirito", + "espurio", + "essencialmente", + "esturricar", + "esvoacar", + "etario", + "eterno", + "etiquetar", + "etnologo", + "etos", + "etrusco", + "euclidiano", + "euforico", + "eugenico", + "eunuco", + "europio", + "eustaquio", + "eutanasia", + "evasivo", + "eventualidade", + "evitavel", + "evoluir", + "exaustor", + "excursionista", + "exercito", + "exfoliado", + "exito", + "exotico", + "expurgo", + "exsudar", + "extrusora", + "exumar", + "fabuloso", + "facultativo", + "fado", + "fagulha", + "faixas", + "fajuto", + "faltoso", + "famoso", + "fanzine", + "fapesp", + "faquir", + "fartura", + "fastio", + "faturista", + "fausto", + "favorito", + "faxineira", + "fazer", + "fealdade", + "febril", + "fecundo", + "fedorento", + "feerico", + "feixe", + "felicidade", + "felpudo", + "feltro", + "femur", + "fenotipo", + "fervura", + "festivo", + "feto", + "feudo", + "fevereiro", + "fezinha", + "fiasco", + "fibra", + "ficticio", + "fiduciario", + "fiesp", + "fifa", + "figurino", + "fijiano", + "filtro", + "finura", + "fiorde", + "fiquei", + "firula", + "fissurar", + "fitoteca", + "fivela", + "fixo", + "flavio", + "flexor", + "flibusteiro", + "flotilha", + "fluxograma", + "fobos", + "foco", + "fofura", + "foguista", + "foie", + "foliculo", + "fominha", + "fonte", + "forum", + "fosso", + "fotossintese", + "foxtrote", + "fraudulento", + "frevo", + "frivolo", + "frouxo", + "frutose", + "fuba", + "fucsia", + "fugitivo", + "fuinha", + "fujao", + "fulustreco", + "fumo", + "funileiro", + "furunculo", + "fustigar", + "futurologo", + "fuxico", + "fuzue", + "gabriel", + "gado", + "gaelico", + "gafieira", + "gaguejo", + "gaivota", + "gajo", + "galvanoplastico", + "gamo", + "ganso", + "garrucha", + "gastronomo", + "gatuno", + "gaussiano", + "gaviao", + "gaxeta", + "gazeteiro", + "gear", + "geiser", + "geminiano", + "generoso", + "genuino", + "geossinclinal", + "gerundio", + "gestual", + "getulista", + "gibi", + "gigolo", + "gilete", + "ginseng", + "giroscopio", + "glaucio", + "glacial", + "gleba", + "glifo", + "glote", + "glutonia", + "gnostico", + "goela", + "gogo", + "goitaca", + "golpista", + "gomo", + "gonzo", + "gorro", + "gostou", + "goticula", + "gourmet", + "governo", + "gozo", + "graxo", + "grevista", + "grito", + "grotesco", + "gruta", + "guaxinim", + "gude", + "gueto", + "guizo", + "guloso", + "gume", + "guru", + "gustativo", + "grelhado", + "gutural", + "habitue", + "haitiano", + "halterofilista", + "hamburguer", + "hanseniase", + "happening", + "harpista", + "hastear", + "haveres", + "hebreu", + "hectometro", + "hedonista", + "hegira", + "helena", + "helminto", + "hemorroidas", + "henrique", + "heptassilabo", + "hertziano", + "hesitar", + "heterossexual", + "heuristico", + "hexagono", + "hiato", + "hibrido", + "hidrostatico", + "hieroglifo", + "hifenizar", + "higienizar", + "hilario", + "himen", + "hino", + "hippie", + "hirsuto", + "historiografia", + "hitlerista", + "hodometro", + "hoje", + "holograma", + "homus", + "honroso", + "hoquei", + "horto", + "hostilizar", + "hotentote", + "huguenote", + "humilde", + "huno", + "hurra", + "hutu", + "iaia", + "ialorixa", + "iambico", + "iansa", + "iaque", + "iara", + "iatista", + "iberico", + "ibis", + "icar", + "iceberg", + "icosagono", + "idade", + "ideologo", + "idiotice", + "idoso", + "iemenita", + "iene", + "igarape", + "iglu", + "ignorar", + "igreja", + "iguaria", + "iidiche", + "ilativo", + "iletrado", + "ilharga", + "ilimitado", + "ilogismo", + "ilustrissimo", + "imaturo", + "imbuzeiro", + "imerso", + "imitavel", + "imovel", + "imputar", + "imutavel", + "inaveriguavel", + "incutir", + "induzir", + "inextricavel", + "infusao", + "ingua", + "inhame", + "iniquo", + "injusto", + "inning", + "inoxidavel", + "inquisitorial", + "insustentavel", + "intumescimento", + "inutilizavel", + "invulneravel", + "inzoneiro", + "iodo", + "iogurte", + "ioio", + "ionosfera", + "ioruba", + "iota", + "ipsilon", + "irascivel", + "iris", + "irlandes", + "irmaos", + "iroques", + "irrupcao", + "isca", + "isento", + "islandes", + "isotopo", + "isqueiro", + "israelita", + "isso", + "isto", + "iterbio", + "itinerario", + "itrio", + "iuane", + "iugoslavo", + "jabuticabeira", + "jacutinga", + "jade", + "jagunco", + "jainista", + "jaleco", + "jambo", + "jantarada", + "japones", + "jaqueta", + "jarro", + "jasmim", + "jato", + "jaula", + "javel", + "jazz", + "jegue", + "jeitoso", + "jejum", + "jenipapo", + "jeova", + "jequitiba", + "jersei", + "jesus", + "jetom", + "jiboia", + "jihad", + "jilo", + "jingle", + "jipe", + "jocoso", + "joelho", + "joguete", + "joio", + "jojoba", + "jorro", + "jota", + "joule", + "joviano", + "jubiloso", + "judoca", + "jugular", + "juizo", + "jujuba", + "juliano", + "jumento", + "junto", + "jururu", + "justo", + "juta", + "juventude", + "labutar", + "laguna", + "laico", + "lajota", + "lanterninha", + "lapso", + "laquear", + "lastro", + "lauto", + "lavrar", + "laxativo", + "lazer", + "leasing", + "lebre", + "lecionar", + "ledo", + "leguminoso", + "leitura", + "lele", + "lemure", + "lento", + "leonardo", + "leopardo", + "lepton", + "leque", + "leste", + "letreiro", + "leucocito", + "levitico", + "lexicologo", + "lhama", + "lhufas", + "liame", + "licoroso", + "lidocaina", + "liliputiano", + "limusine", + "linotipo", + "lipoproteina", + "liquidos", + "lirismo", + "lisura", + "liturgico", + "livros", + "lixo", + "lobulo", + "locutor", + "lodo", + "logro", + "lojista", + "lombriga", + "lontra", + "loop", + "loquaz", + "lorota", + "losango", + "lotus", + "louvor", + "luar", + "lubrificavel", + "lucros", + "lugubre", + "luis", + "luminoso", + "luneta", + "lustroso", + "luto", + "luvas", + "luxuriante", + "luzeiro", + "maduro", + "maestro", + "mafioso", + "magro", + "maiuscula", + "majoritario", + "malvisto", + "mamute", + "manutencao", + "mapoteca", + "maquinista", + "marzipa", + "masturbar", + "matuto", + "mausoleu", + "mavioso", + "maxixe", + "mazurca", + "meandro", + "mecha", + "medusa", + "mefistofelico", + "megera", + "meirinho", + "melro", + "memorizar", + "menu", + "mequetrefe", + "mertiolate", + "mestria", + "metroviario", + "mexilhao", + "mezanino", + "miau", + "microssegundo", + "midia", + "migratorio", + "mimosa", + "minuto", + "miosotis", + "mirtilo", + "misturar", + "mitzvah", + "miudos", + "mixuruca", + "mnemonico", + "moagem", + "mobilizar", + "modulo", + "moer", + "mofo", + "mogno", + "moita", + "molusco", + "monumento", + "moqueca", + "morubixaba", + "mostruario", + "motriz", + "mouse", + "movivel", + "mozarela", + "muarra", + "muculmano", + "mudo", + "mugir", + "muitos", + "mumunha", + "munir", + "muon", + "muquira", + "murros", + "musselina", + "nacoes", + "nado", + "naftalina", + "nago", + "naipe", + "naja", + "nalgum", + "namoro", + "nanquim", + "napolitano", + "naquilo", + "nascimento", + "nautilo", + "navios", + "nazista", + "nebuloso", + "nectarina", + "nefrologo", + "negus", + "nelore", + "nenufar", + "nepotismo", + "nervura", + "neste", + "netuno", + "neutron", + "nevoeiro", + "newtoniano", + "nexo", + "nhenhenhem", + "nhoque", + "nigeriano", + "niilista", + "ninho", + "niobio", + "niponico", + "niquelar", + "nirvana", + "nisto", + "nitroglicerina", + "nivoso", + "nobreza", + "nocivo", + "noel", + "nogueira", + "noivo", + "nojo", + "nominativo", + "nonuplo", + "noruegues", + "nostalgico", + "noturno", + "nouveau", + "nuanca", + "nublar", + "nucleotideo", + "nudista", + "nulo", + "numismatico", + "nunquinha", + "nupcias", + "nutritivo", + "nuvens", + "oasis", + "obcecar", + "obeso", + "obituario", + "objetos", + "oblongo", + "obnoxio", + "obrigatorio", + "obstruir", + "obtuso", + "obus", + "obvio", + "ocaso", + "occipital", + "oceanografo", + "ocioso", + "oclusivo", + "ocorrer", + "ocre", + "octogono", + "odalisca", + "odisseia", + "odorifico", + "oersted", + "oeste", + "ofertar", + "ofidio", + "oftalmologo", + "ogiva", + "ogum", + "oigale", + "oitavo", + "oitocentos", + "ojeriza", + "olaria", + "oleoso", + "olfato", + "olhos", + "oliveira", + "olmo", + "olor", + "olvidavel", + "ombudsman", + "omeleteira", + "omitir", + "omoplata", + "onanismo", + "ondular", + "oneroso", + "onomatopeico", + "ontologico", + "onus", + "onze", + "opalescente", + "opcional", + "operistico", + "opio", + "oposto", + "oprobrio", + "optometrista", + "opusculo", + "oratorio", + "orbital", + "orcar", + "orfao", + "orixa", + "orla", + "ornitologo", + "orquidea", + "ortorrombico", + "orvalho", + "osculo", + "osmotico", + "ossudo", + "ostrogodo", + "otario", + "otite", + "ouro", + "ousar", + "outubro", + "ouvir", + "ovario", + "overnight", + "oviparo", + "ovni", + "ovoviviparo", + "ovulo", + "oxala", + "oxente", + "oxiuro", + "oxossi", + "ozonizar", + "paciente", + "pactuar", + "padronizar", + "paete", + "pagodeiro", + "paixao", + "pajem", + "paludismo", + "pampas", + "panturrilha", + "papudo", + "paquistanes", + "pastoso", + "patua", + "paulo", + "pauzinhos", + "pavoroso", + "paxa", + "pazes", + "peao", + "pecuniario", + "pedunculo", + "pegaso", + "peixinho", + "pejorativo", + "pelvis", + "penuria", + "pequno", + "petunia", + "pezada", + "piauiense", + "pictorico", + "pierro", + "pigmeu", + "pijama", + "pilulas", + "pimpolho", + "pintura", + "piorar", + "pipocar", + "piqueteiro", + "pirulito", + "pistoleiro", + "pituitaria", + "pivotar", + "pixote", + "pizzaria", + "plistoceno", + "plotar", + "pluviometrico", + "pneumonico", + "poco", + "podridao", + "poetisa", + "pogrom", + "pois", + "polvorosa", + "pomposo", + "ponderado", + "pontudo", + "populoso", + "poquer", + "porvir", + "posudo", + "potro", + "pouso", + "povoar", + "prazo", + "prezar", + "privilegios", + "proximo", + "prussiano", + "pseudopode", + "psoriase", + "pterossauros", + "ptialina", + "ptolemaico", + "pudor", + "pueril", + "pufe", + "pugilista", + "puir", + "pujante", + "pulverizar", + "pumba", + "punk", + "purulento", + "pustula", + "putsch", + "puxe", + "quatrocentos", + "quetzal", + "quixotesco", + "quotizavel", + "rabujice", + "racista", + "radonio", + "rafia", + "ragu", + "rajado", + "ralo", + "rampeiro", + "ranzinza", + "raptor", + "raquitismo", + "raro", + "rasurar", + "ratoeira", + "ravioli", + "razoavel", + "reavivar", + "rebuscar", + "recusavel", + "reduzivel", + "reexposicao", + "refutavel", + "regurgitar", + "reivindicavel", + "rejuvenescimento", + "relva", + "remuneravel", + "renunciar", + "reorientar", + "repuxo", + "requisito", + "resumo", + "returno", + "reutilizar", + "revolvido", + "rezonear", + "riacho", + "ribossomo", + "ricota", + "ridiculo", + "rifle", + "rigoroso", + "rijo", + "rimel", + "rins", + "rios", + "riqueza", + "respeito", + "rissole", + "ritualistico", + "rivalizar", + "rixa", + "robusto", + "rococo", + "rodoviario", + "roer", + "rogo", + "rojao", + "rolo", + "rompimento", + "ronronar", + "roqueiro", + "rorqual", + "rosto", + "rotundo", + "rouxinol", + "roxo", + "royal", + "ruas", + "rucula", + "rudimentos", + "ruela", + "rufo", + "rugoso", + "ruivo", + "rule", + "rumoroso", + "runico", + "ruptura", + "rural", + "rustico", + "rutilar", + "saariano", + "sabujo", + "sacudir", + "sadomasoquista", + "safra", + "sagui", + "sais", + "samurai", + "santuario", + "sapo", + "saquear", + "sartriano", + "saturno", + "saude", + "sauva", + "saveiro", + "saxofonista", + "sazonal", + "scherzo", + "script", + "seara", + "seborreia", + "secura", + "seduzir", + "sefardim", + "seguro", + "seja", + "selvas", + "sempre", + "senzala", + "sepultura", + "sequoia", + "sestercio", + "setuplo", + "seus", + "seviciar", + "sezonismo", + "shalom", + "siames", + "sibilante", + "sicrano", + "sidra", + "sifilitico", + "signos", + "silvo", + "simultaneo", + "sinusite", + "sionista", + "sirio", + "sisudo", + "situar", + "sivan", + "slide", + "slogan", + "soar", + "sobrio", + "socratico", + "sodomizar", + "soerguer", + "software", + "sogro", + "soja", + "solver", + "somente", + "sonso", + "sopro", + "soquete", + "sorveteiro", + "sossego", + "soturno", + "sousafone", + "sovinice", + "sozinho", + "suavizar", + "subverter", + "sucursal", + "sudoriparo", + "sufragio", + "sugestoes", + "suite", + "sujo", + "sultao", + "sumula", + "suntuoso", + "suor", + "supurar", + "suruba", + "susto", + "suturar", + "suvenir", + "tabuleta", + "taco", + "tadjique", + "tafeta", + "tagarelice", + "taitiano", + "talvez", + "tampouco", + "tanzaniano", + "taoista", + "tapume", + "taquion", + "tarugo", + "tascar", + "tatuar", + "tautologico", + "tavola", + "taxionomista", + "tchecoslovaco", + "teatrologo", + "tectonismo", + "tedioso", + "teflon", + "tegumento", + "teixo", + "telurio", + "temporas", + "tenue", + "teosofico", + "tepido", + "tequila", + "terrorista", + "testosterona", + "tetrico", + "teutonico", + "teve", + "texugo", + "tiara", + "tibia", + "tiete", + "tifoide", + "tigresa", + "tijolo", + "tilintar", + "timpano", + "tintureiro", + "tiquete", + "tiroteio", + "tisico", + "titulos", + "tive", + "toar", + "toboga", + "tofu", + "togoles", + "toicinho", + "tolueno", + "tomografo", + "tontura", + "toponimo", + "toquio", + "torvelinho", + "tostar", + "toto", + "touro", + "toxina", + "trazer", + "trezentos", + "trivialidade", + "trovoar", + "truta", + "tuaregue", + "tubular", + "tucano", + "tudo", + "tufo", + "tuiste", + "tulipa", + "tumultuoso", + "tunisino", + "tupiniquim", + "turvo", + "tutu", + "ucraniano", + "udenista", + "ufanista", + "ufologo", + "ugaritico", + "uiste", + "uivo", + "ulceroso", + "ulema", + "ultravioleta", + "umbilical", + "umero", + "umido", + "umlaut", + "unanimidade", + "unesco", + "ungulado", + "unheiro", + "univoco", + "untuoso", + "urano", + "urbano", + "urdir", + "uretra", + "urgente", + "urinol", + "urna", + "urologo", + "urro", + "ursulina", + "urtiga", + "urupe", + "usavel", + "usbeque", + "usei", + "usineiro", + "usurpar", + "utero", + "utilizar", + "utopico", + "uvular", + "uxoricidio", + "vacuo", + "vadio", + "vaguear", + "vaivem", + "valvula", + "vampiro", + "vantajoso", + "vaporoso", + "vaquinha", + "varziano", + "vasto", + "vaticinio", + "vaudeville", + "vazio", + "veado", + "vedico", + "veemente", + "vegetativo", + "veio", + "veja", + "veludo", + "venusiano", + "verdade", + "verve", + "vestuario", + "vetusto", + "vexatorio", + "vezes", + "viavel", + "vibratorio", + "victor", + "vicunha", + "vidros", + "vietnamita", + "vigoroso", + "vilipendiar", + "vime", + "vintem", + "violoncelo", + "viquingue", + "virus", + "visualizar", + "vituperio", + "viuvo", + "vivo", + "vizir", + "voar", + "vociferar", + "vodu", + "vogar", + "voile", + "volver", + "vomito", + "vontade", + "vortice", + "vosso", + "voto", + "vovozinha", + "voyeuse", + "vozes", + "vulva", + "vupt", + "western", + "xadrez", + "xale", + "xampu", + "xango", + "xarope", + "xaual", + "xavante", + "xaxim", + "xenonio", + "xepa", + "xerox", + "xicara", + "xifopago", + "xiita", + "xilogravura", + "xinxim", + "xistoso", + "xixi", + "xodo", + "xogum", + "xucro", + "zabumba", + "zagueiro", + "zambiano", + "zanzar", + "zarpar", + "zebu", + "zefiro", + "zeloso", + "zenite", + "zumbi" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/russian.h b/src/mnemonics/russian.h index d36942a9b..7dfd3a98d 100644 --- a/src/mnemonics/russian.h +++ b/src/mnemonics/russian.h @@ -1,1691 +1,1691 @@ -// Word list created by Monero contributor sammy007 -// -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file russian.h - * - * \brief Russian word list and map. - */ - -#ifndef RUSSIAN_H -#define RUSSIAN_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Russian: public Base - { - public: - Russian(): Base("русский язык", "Russian", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "абажур", - "абзац", - "абонент", - "абрикос", - "абсурд", - "авангард", - "август", - "авиация", - "авоська", - "автор", - "агат", - "агент", - "агитатор", - "агнец", - "агония", - "агрегат", - "адвокат", - "адмирал", - "адрес", - "ажиотаж", - "азарт", - "азбука", - "азот", - "аист", - "айсберг", - "академия", - "аквариум", - "аккорд", - "акробат", - "аксиома", - "актер", - "акула", - "акция", - "алгоритм", - "алебарда", - "аллея", - "алмаз", - "алтарь", - "алфавит", - "алхимик", - "алый", - "альбом", - "алюминий", - "амбар", - "аметист", - "амнезия", - "ампула", - "амфора", - "анализ", - "ангел", - "анекдот", - "анимация", - "анкета", - "аномалия", - "ансамбль", - "антенна", - "апатия", - "апельсин", - "апофеоз", - "аппарат", - "апрель", - "аптека", - "арабский", - "арбуз", - "аргумент", - "арест", - "ария", - "арка", - "армия", - "аромат", - "арсенал", - "артист", - "архив", - "аршин", - "асбест", - "аскетизм", - "аспект", - "ассорти", - "астроном", - "асфальт", - "атака", - "ателье", - "атлас", - "атом", - "атрибут", - "аудитор", - "аукцион", - "аура", - "афера", - "афиша", - "ахинея", - "ацетон", - "аэропорт", - "бабушка", - "багаж", - "бадья", - "база", - "баклажан", - "балкон", - "бампер", - "банк", - "барон", - "бассейн", - "батарея", - "бахрома", - "башня", - "баян", - "бегство", - "бедро", - "бездна", - "бекон", - "белый", - "бензин", - "берег", - "беседа", - "бетонный", - "биатлон", - "библия", - "бивень", - "бигуди", - "бидон", - "бизнес", - "бикини", - "билет", - "бинокль", - "биология", - "биржа", - "бисер", - "битва", - "бицепс", - "благо", - "бледный", - "близкий", - "блок", - "блуждать", - "блюдо", - "бляха", - "бобер", - "богатый", - "бодрый", - "боевой", - "бокал", - "большой", - "борьба", - "босой", - "ботинок", - "боцман", - "бочка", - "боярин", - "брать", - "бревно", - "бригада", - "бросать", - "брызги", - "брюки", - "бублик", - "бугор", - "будущее", - "буква", - "бульвар", - "бумага", - "бунт", - "бурный", - "бусы", - "бутылка", - "буфет", - "бухта", - "бушлат", - "бывалый", - "быль", - "быстрый", - "быть", - "бюджет", - "бюро", - "бюст", - "вагон", - "важный", - "ваза", - "вакцина", - "валюта", - "вампир", - "ванная", - "вариант", - "вассал", - "вата", - "вафля", - "вахта", - "вдова", - "вдыхать", - "ведущий", - "веер", - "вежливый", - "везти", - "веко", - "великий", - "вена", - "верить", - "веселый", - "ветер", - "вечер", - "вешать", - "вещь", - "веяние", - "взаимный", - "взбучка", - "взвод", - "взгляд", - "вздыхать", - "взлетать", - "взмах", - "взнос", - "взор", - "взрыв", - "взывать", - "взятка", - "вибрация", - "визит", - "вилка", - "вино", - "вирус", - "висеть", - "витрина", - "вихрь", - "вишневый", - "включать", - "вкус", - "власть", - "влечь", - "влияние", - "влюблять", - "внешний", - "внимание", - "внук", - "внятный", - "вода", - "воевать", - "вождь", - "воздух", - "войти", - "вокзал", - "волос", - "вопрос", - "ворота", - "восток", - "впадать", - "впускать", - "врач", - "время", - "вручать", - "всадник", - "всеобщий", - "вспышка", - "встреча", - "вторник", - "вулкан", - "вурдалак", - "входить", - "въезд", - "выбор", - "вывод", - "выгодный", - "выделять", - "выезжать", - "выживать", - "вызывать", - "выигрыш", - "вылезать", - "выносить", - "выпивать", - "высокий", - "выходить", - "вычет", - "вышка", - "выяснять", - "вязать", - "вялый", - "гавань", - "гадать", - "газета", - "гаишник", - "галстук", - "гамма", - "гарантия", - "гастроли", - "гвардия", - "гвоздь", - "гектар", - "гель", - "генерал", - "геолог", - "герой", - "гешефт", - "гибель", - "гигант", - "гильза", - "гимн", - "гипотеза", - "гитара", - "глаз", - "глина", - "глоток", - "глубокий", - "глыба", - "глядеть", - "гнать", - "гнев", - "гнить", - "гном", - "гнуть", - "говорить", - "годовой", - "голова", - "гонка", - "город", - "гость", - "готовый", - "граница", - "грех", - "гриб", - "громкий", - "группа", - "грызть", - "грязный", - "губа", - "гудеть", - "гулять", - "гуманный", - "густой", - "гуща", - "давать", - "далекий", - "дама", - "данные", - "дарить", - "дать", - "дача", - "дверь", - "движение", - "двор", - "дебют", - "девушка", - "дедушка", - "дежурный", - "дезертир", - "действие", - "декабрь", - "дело", - "демократ", - "день", - "депутат", - "держать", - "десяток", - "детский", - "дефицит", - "дешевый", - "деятель", - "джаз", - "джинсы", - "джунгли", - "диалог", - "диван", - "диета", - "дизайн", - "дикий", - "динамика", - "диплом", - "директор", - "диск", - "дитя", - "дичь", - "длинный", - "дневник", - "добрый", - "доверие", - "договор", - "дождь", - "доза", - "документ", - "должен", - "домашний", - "допрос", - "дорога", - "доход", - "доцент", - "дочь", - "дощатый", - "драка", - "древний", - "дрожать", - "друг", - "дрянь", - "дубовый", - "дуга", - "дудка", - "дукат", - "дуло", - "думать", - "дупло", - "дурак", - "дуть", - "духи", - "душа", - "дуэт", - "дымить", - "дыня", - "дыра", - "дыханье", - "дышать", - "дьявол", - "дюжина", - "дюйм", - "дюна", - "дядя", - "дятел", - "егерь", - "единый", - "едкий", - "ежевика", - "ежик", - "езда", - "елка", - "емкость", - "ерунда", - "ехать", - "жадный", - "жажда", - "жалеть", - "жанр", - "жара", - "жать", - "жгучий", - "ждать", - "жевать", - "желание", - "жемчуг", - "женщина", - "жертва", - "жесткий", - "жечь", - "живой", - "жидкость", - "жизнь", - "жилье", - "жирный", - "житель", - "журнал", - "жюри", - "забывать", - "завод", - "загадка", - "задача", - "зажечь", - "зайти", - "закон", - "замечать", - "занимать", - "западный", - "зарплата", - "засыпать", - "затрата", - "захват", - "зацепка", - "зачет", - "защита", - "заявка", - "звать", - "звезда", - "звонить", - "звук", - "здание", - "здешний", - "здоровье", - "зебра", - "зевать", - "зеленый", - "земля", - "зенит", - "зеркало", - "зефир", - "зигзаг", - "зима", - "зиять", - "злак", - "злой", - "змея", - "знать", - "зной", - "зодчий", - "золотой", - "зомби", - "зона", - "зоопарк", - "зоркий", - "зрачок", - "зрение", - "зритель", - "зубной", - "зыбкий", - "зять", - "игла", - "иголка", - "играть", - "идея", - "идиот", - "идол", - "идти", - "иерархия", - "избрать", - "известие", - "изгонять", - "издание", - "излагать", - "изменять", - "износ", - "изоляция", - "изрядный", - "изучать", - "изымать", - "изящный", - "икона", - "икра", - "иллюзия", - "имбирь", - "иметь", - "имидж", - "иммунный", - "империя", - "инвестор", - "индивид", - "инерция", - "инженер", - "иномарка", - "институт", - "интерес", - "инфекция", - "инцидент", - "ипподром", - "ирис", - "ирония", - "искать", - "история", - "исходить", - "исчезать", - "итог", - "июль", - "июнь", - "кабинет", - "кавалер", - "кадр", - "казарма", - "кайф", - "кактус", - "калитка", - "камень", - "канал", - "капитан", - "картина", - "касса", - "катер", - "кафе", - "качество", - "каша", - "каюта", - "квартира", - "квинтет", - "квота", - "кедр", - "кекс", - "кенгуру", - "кепка", - "керосин", - "кетчуп", - "кефир", - "кибитка", - "кивнуть", - "кидать", - "километр", - "кино", - "киоск", - "кипеть", - "кирпич", - "кисть", - "китаец", - "класс", - "клетка", - "клиент", - "клоун", - "клуб", - "клык", - "ключ", - "клятва", - "книга", - "кнопка", - "кнут", - "князь", - "кобура", - "ковер", - "коготь", - "кодекс", - "кожа", - "козел", - "койка", - "коктейль", - "колено", - "компания", - "конец", - "копейка", - "короткий", - "костюм", - "котел", - "кофе", - "кошка", - "красный", - "кресло", - "кричать", - "кровь", - "крупный", - "крыша", - "крючок", - "кубок", - "кувшин", - "кудрявый", - "кузов", - "кукла", - "культура", - "кумир", - "купить", - "курс", - "кусок", - "кухня", - "куча", - "кушать", - "кювет", - "лабиринт", - "лавка", - "лагерь", - "ладонь", - "лазерный", - "лайнер", - "лакей", - "лампа", - "ландшафт", - "лапа", - "ларек", - "ласковый", - "лауреат", - "лачуга", - "лаять", - "лгать", - "лебедь", - "левый", - "легкий", - "ледяной", - "лежать", - "лекция", - "лента", - "лепесток", - "лесной", - "лето", - "лечь", - "леший", - "лживый", - "либерал", - "ливень", - "лига", - "лидер", - "ликовать", - "лиловый", - "лимон", - "линия", - "липа", - "лирика", - "лист", - "литр", - "лифт", - "лихой", - "лицо", - "личный", - "лишний", - "лобовой", - "ловить", - "логика", - "лодка", - "ложка", - "лозунг", - "локоть", - "ломать", - "лоно", - "лопата", - "лорд", - "лось", - "лоток", - "лохматый", - "лошадь", - "лужа", - "лукавый", - "луна", - "лупить", - "лучший", - "лыжный", - "лысый", - "львиный", - "льгота", - "льдина", - "любить", - "людской", - "люстра", - "лютый", - "лягушка", - "магазин", - "мадам", - "мазать", - "майор", - "максимум", - "мальчик", - "манера", - "март", - "масса", - "мать", - "мафия", - "махать", - "мачта", - "машина", - "маэстро", - "маяк", - "мгла", - "мебель", - "медведь", - "мелкий", - "мемуары", - "менять", - "мера", - "место", - "метод", - "механизм", - "мечтать", - "мешать", - "миграция", - "мизинец", - "микрофон", - "миллион", - "минута", - "мировой", - "миссия", - "митинг", - "мишень", - "младший", - "мнение", - "мнимый", - "могила", - "модель", - "мозг", - "мойка", - "мокрый", - "молодой", - "момент", - "монах", - "море", - "мост", - "мотор", - "мохнатый", - "мочь", - "мошенник", - "мощный", - "мрачный", - "мстить", - "мудрый", - "мужчина", - "музыка", - "мука", - "мумия", - "мундир", - "муравей", - "мусор", - "мутный", - "муфта", - "муха", - "мучить", - "мушкетер", - "мыло", - "мысль", - "мыть", - "мычать", - "мышь", - "мэтр", - "мюзикл", - "мягкий", - "мякиш", - "мясо", - "мятый", - "мячик", - "набор", - "навык", - "нагрузка", - "надежда", - "наемный", - "нажать", - "называть", - "наивный", - "накрыть", - "налог", - "намерен", - "наносить", - "написать", - "народ", - "натура", - "наука", - "нация", - "начать", - "небо", - "невеста", - "негодяй", - "неделя", - "нежный", - "незнание", - "нелепый", - "немалый", - "неправда", - "нервный", - "нести", - "нефть", - "нехватка", - "нечистый", - "неясный", - "нива", - "нижний", - "низкий", - "никель", - "нирвана", - "нить", - "ничья", - "ниша", - "нищий", - "новый", - "нога", - "ножницы", - "ноздря", - "ноль", - "номер", - "норма", - "нота", - "ночь", - "ноша", - "ноябрь", - "нрав", - "нужный", - "нутро", - "нынешний", - "нырнуть", - "ныть", - "нюанс", - "нюхать", - "няня", - "оазис", - "обаяние", - "обвинять", - "обгонять", - "обещать", - "обжигать", - "обзор", - "обида", - "область", - "обмен", - "обнимать", - "оборона", - "образ", - "обучение", - "обходить", - "обширный", - "общий", - "объект", - "обычный", - "обязать", - "овальный", - "овес", - "овощи", - "овраг", - "овца", - "овчарка", - "огненный", - "огонь", - "огромный", - "огурец", - "одежда", - "одинокий", - "одобрить", - "ожидать", - "ожог", - "озарение", - "озеро", - "означать", - "оказать", - "океан", - "оклад", - "окно", - "округ", - "октябрь", - "окурок", - "олень", - "опасный", - "операция", - "описать", - "оплата", - "опора", - "оппонент", - "опрос", - "оптимизм", - "опускать", - "опыт", - "орать", - "орбита", - "орган", - "орден", - "орел", - "оригинал", - "оркестр", - "орнамент", - "оружие", - "осадок", - "освещать", - "осень", - "осина", - "осколок", - "осмотр", - "основной", - "особый", - "осуждать", - "отбор", - "отвечать", - "отдать", - "отец", - "отзыв", - "открытие", - "отмечать", - "относить", - "отпуск", - "отрасль", - "отставка", - "оттенок", - "отходить", - "отчет", - "отъезд", - "офицер", - "охапка", - "охота", - "охрана", - "оценка", - "очаг", - "очередь", - "очищать", - "очки", - "ошейник", - "ошибка", - "ощущение", - "павильон", - "падать", - "паек", - "пакет", - "палец", - "память", - "панель", - "папка", - "партия", - "паспорт", - "патрон", - "пауза", - "пафос", - "пахнуть", - "пациент", - "пачка", - "пашня", - "певец", - "педагог", - "пейзаж", - "пельмень", - "пенсия", - "пепел", - "период", - "песня", - "петля", - "пехота", - "печать", - "пешеход", - "пещера", - "пианист", - "пиво", - "пиджак", - "пиковый", - "пилот", - "пионер", - "пирог", - "писать", - "пить", - "пицца", - "пишущий", - "пища", - "план", - "плечо", - "плита", - "плохой", - "плыть", - "плюс", - "пляж", - "победа", - "повод", - "погода", - "подумать", - "поехать", - "пожимать", - "позиция", - "поиск", - "покой", - "получать", - "помнить", - "пони", - "поощрять", - "попадать", - "порядок", - "пост", - "поток", - "похожий", - "поцелуй", - "почва", - "пощечина", - "поэт", - "пояснить", - "право", - "предмет", - "проблема", - "пруд", - "прыгать", - "прямой", - "психолог", - "птица", - "публика", - "пугать", - "пудра", - "пузырь", - "пуля", - "пункт", - "пурга", - "пустой", - "путь", - "пухлый", - "пучок", - "пушистый", - "пчела", - "пшеница", - "пыль", - "пытка", - "пыхтеть", - "пышный", - "пьеса", - "пьяный", - "пятно", - "работа", - "равный", - "радость", - "развитие", - "район", - "ракета", - "рамка", - "ранний", - "рапорт", - "рассказ", - "раунд", - "рация", - "рвать", - "реальный", - "ребенок", - "реветь", - "регион", - "редакция", - "реестр", - "режим", - "резкий", - "рейтинг", - "река", - "религия", - "ремонт", - "рента", - "реплика", - "ресурс", - "реформа", - "рецепт", - "речь", - "решение", - "ржавый", - "рисунок", - "ритм", - "рифма", - "робкий", - "ровный", - "рогатый", - "родитель", - "рождение", - "розовый", - "роковой", - "роль", - "роман", - "ронять", - "рост", - "рота", - "роща", - "рояль", - "рубль", - "ругать", - "руда", - "ружье", - "руины", - "рука", - "руль", - "румяный", - "русский", - "ручка", - "рыба", - "рывок", - "рыдать", - "рыжий", - "рынок", - "рысь", - "рыть", - "рыхлый", - "рыцарь", - "рычаг", - "рюкзак", - "рюмка", - "рябой", - "рядовой", - "сабля", - "садовый", - "сажать", - "салон", - "самолет", - "сани", - "сапог", - "сарай", - "сатира", - "сауна", - "сахар", - "сбегать", - "сбивать", - "сбор", - "сбыт", - "свадьба", - "свет", - "свидание", - "свобода", - "связь", - "сгорать", - "сдвигать", - "сеанс", - "северный", - "сегмент", - "седой", - "сезон", - "сейф", - "секунда", - "сельский", - "семья", - "сентябрь", - "сердце", - "сеть", - "сечение", - "сеять", - "сигнал", - "сидеть", - "сизый", - "сила", - "символ", - "синий", - "сирота", - "система", - "ситуация", - "сиять", - "сказать", - "скважина", - "скелет", - "скидка", - "склад", - "скорый", - "скрывать", - "скучный", - "слава", - "слеза", - "слияние", - "слово", - "случай", - "слышать", - "слюна", - "смех", - "смирение", - "смотреть", - "смутный", - "смысл", - "смятение", - "снаряд", - "снег", - "снижение", - "сносить", - "снять", - "событие", - "совет", - "согласие", - "сожалеть", - "сойти", - "сокол", - "солнце", - "сомнение", - "сонный", - "сообщать", - "соперник", - "сорт", - "состав", - "сотня", - "соус", - "социолог", - "сочинять", - "союз", - "спать", - "спешить", - "спина", - "сплошной", - "способ", - "спутник", - "средство", - "срок", - "срывать", - "стать", - "ствол", - "стена", - "стихи", - "сторона", - "страна", - "студент", - "стыд", - "субъект", - "сувенир", - "сугроб", - "судьба", - "суета", - "суждение", - "сукно", - "сулить", - "сумма", - "сунуть", - "супруг", - "суровый", - "сустав", - "суть", - "сухой", - "суша", - "существо", - "сфера", - "схема", - "сцена", - "счастье", - "счет", - "считать", - "сшивать", - "съезд", - "сынок", - "сыпать", - "сырье", - "сытый", - "сыщик", - "сюжет", - "сюрприз", - "таблица", - "таежный", - "таинство", - "тайна", - "такси", - "талант", - "таможня", - "танец", - "тарелка", - "таскать", - "тахта", - "тачка", - "таять", - "тварь", - "твердый", - "творить", - "театр", - "тезис", - "текст", - "тело", - "тема", - "тень", - "теория", - "теплый", - "терять", - "тесный", - "тетя", - "техника", - "течение", - "тигр", - "типичный", - "тираж", - "титул", - "тихий", - "тишина", - "ткань", - "товарищ", - "толпа", - "тонкий", - "топливо", - "торговля", - "тоска", - "точка", - "тощий", - "традиция", - "тревога", - "трибуна", - "трогать", - "труд", - "трюк", - "тряпка", - "туалет", - "тугой", - "туловище", - "туман", - "тундра", - "тупой", - "турнир", - "тусклый", - "туфля", - "туча", - "туша", - "тыкать", - "тысяча", - "тьма", - "тюльпан", - "тюрьма", - "тяга", - "тяжелый", - "тянуть", - "убеждать", - "убирать", - "убогий", - "убыток", - "уважение", - "уверять", - "увлекать", - "угнать", - "угол", - "угроза", - "удар", - "удивлять", - "удобный", - "уезд", - "ужас", - "ужин", - "узел", - "узкий", - "узнавать", - "узор", - "уйма", - "уклон", - "укол", - "уксус", - "улетать", - "улица", - "улучшать", - "улыбка", - "уметь", - "умиление", - "умный", - "умолять", - "умысел", - "унижать", - "уносить", - "уныние", - "упасть", - "уплата", - "упор", - "упрекать", - "упускать", - "уран", - "урна", - "уровень", - "усадьба", - "усердие", - "усилие", - "ускорять", - "условие", - "усмешка", - "уснуть", - "успеть", - "усыпать", - "утешать", - "утка", - "уточнять", - "утро", - "утюг", - "уходить", - "уцелеть", - "участие", - "ученый", - "учитель", - "ушко", - "ущерб", - "уютный", - "уяснять", - "фабрика", - "фаворит", - "фаза", - "файл", - "факт", - "фамилия", - "фантазия", - "фара", - "фасад", - "февраль", - "фельдшер", - "феномен", - "ферма", - "фигура", - "физика", - "фильм", - "финал", - "фирма", - "фишка", - "флаг", - "флейта", - "флот", - "фокус", - "фольклор", - "фонд", - "форма", - "фото", - "фраза", - "фреска", - "фронт", - "фрукт", - "функция", - "фуражка", - "футбол", - "фыркать", - "халат", - "хамство", - "хаос", - "характер", - "хата", - "хватать", - "хвост", - "хижина", - "хилый", - "химия", - "хирург", - "хитрый", - "хищник", - "хлам", - "хлеб", - "хлопать", - "хмурый", - "ходить", - "хозяин", - "хоккей", - "холодный", - "хороший", - "хотеть", - "хохотать", - "храм", - "хрен", - "хриплый", - "хроника", - "хрупкий", - "художник", - "хулиган", - "хутор", - "царь", - "цвет", - "цель", - "цемент", - "центр", - "цепь", - "церковь", - "цикл", - "цилиндр", - "циничный", - "цирк", - "цистерна", - "цитата", - "цифра", - "цыпленок", - "чадо", - "чайник", - "часть", - "чашка", - "человек", - "чемодан", - "чепуха", - "черный", - "честь", - "четкий", - "чехол", - "чиновник", - "число", - "читать", - "членство", - "чреватый", - "чтение", - "чувство", - "чугунный", - "чудо", - "чужой", - "чукча", - "чулок", - "чума", - "чуткий", - "чучело", - "чушь", - "шаблон", - "шагать", - "шайка", - "шакал", - "шалаш", - "шампунь", - "шанс", - "шапка", - "шарик", - "шасси", - "шатер", - "шахта", - "шашлык", - "швейный", - "швырять", - "шевелить", - "шедевр", - "шейка", - "шелковый", - "шептать", - "шерсть", - "шестерка", - "шикарный", - "шинель", - "шипеть", - "широкий", - "шить", - "шишка", - "шкаф", - "школа", - "шкура", - "шланг", - "шлем", - "шлюпка", - "шляпа", - "шнур", - "шоколад", - "шорох", - "шоссе", - "шофер", - "шпага", - "шпион", - "шприц", - "шрам", - "шрифт", - "штаб", - "штора", - "штраф", - "штука", - "штык", - "шуба", - "шуметь", - "шуршать", - "шутка", - "щадить", - "щедрый", - "щека", - "щель", - "щенок", - "щепка", - "щетка", - "щука", - "эволюция", - "эгоизм", - "экзамен", - "экипаж", - "экономия", - "экран", - "эксперт", - "элемент", - "элита", - "эмблема", - "эмигрант", - "эмоция", - "энергия", - "эпизод", - "эпоха", - "эскиз", - "эссе", - "эстрада", - "этап", - "этика", - "этюд", - "эфир", - "эффект", - "эшелон", - "юбилей", - "юбка", - "южный", - "юмор", - "юноша", - "юрист", - "яблоко", - "явление", - "ягода", - "ядерный", - "ядовитый", - "ядро", - "язва", - "язык", - "яйцо", - "якорь", - "январь", - "японец", - "яркий", - "ярмарка", - "ярость", - "ярус", - "ясный", - "яхта", - "ячейка", - "ящик" - }; - set_words(words); - populate_maps(); - } - }; -} - -#endif +// Word list created by Monero contributor sammy007 +// +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file russian.h + * + * \brief Russian word list and map. + */ + +#ifndef RUSSIAN_H +#define RUSSIAN_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Russian: public Base + { + public: + Russian(): Base("русский язык", "Russian", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "абажур", + "абзац", + "абонент", + "абрикос", + "абсурд", + "авангард", + "август", + "авиация", + "авоська", + "автор", + "агат", + "агент", + "агитатор", + "агнец", + "агония", + "агрегат", + "адвокат", + "адмирал", + "адрес", + "ажиотаж", + "азарт", + "азбука", + "азот", + "аист", + "айсберг", + "академия", + "аквариум", + "аккорд", + "акробат", + "аксиома", + "актер", + "акула", + "акция", + "алгоритм", + "алебарда", + "аллея", + "алмаз", + "алтарь", + "алфавит", + "алхимик", + "алый", + "альбом", + "алюминий", + "амбар", + "аметист", + "амнезия", + "ампула", + "амфора", + "анализ", + "ангел", + "анекдот", + "анимация", + "анкета", + "аномалия", + "ансамбль", + "антенна", + "апатия", + "апельсин", + "апофеоз", + "аппарат", + "апрель", + "аптека", + "арабский", + "арбуз", + "аргумент", + "арест", + "ария", + "арка", + "армия", + "аромат", + "арсенал", + "артист", + "архив", + "аршин", + "асбест", + "аскетизм", + "аспект", + "ассорти", + "астроном", + "асфальт", + "атака", + "ателье", + "атлас", + "атом", + "атрибут", + "аудитор", + "аукцион", + "аура", + "афера", + "афиша", + "ахинея", + "ацетон", + "аэропорт", + "бабушка", + "багаж", + "бадья", + "база", + "баклажан", + "балкон", + "бампер", + "банк", + "барон", + "бассейн", + "батарея", + "бахрома", + "башня", + "баян", + "бегство", + "бедро", + "бездна", + "бекон", + "белый", + "бензин", + "берег", + "беседа", + "бетонный", + "биатлон", + "библия", + "бивень", + "бигуди", + "бидон", + "бизнес", + "бикини", + "билет", + "бинокль", + "биология", + "биржа", + "бисер", + "битва", + "бицепс", + "благо", + "бледный", + "близкий", + "блок", + "блуждать", + "блюдо", + "бляха", + "бобер", + "богатый", + "бодрый", + "боевой", + "бокал", + "большой", + "борьба", + "босой", + "ботинок", + "боцман", + "бочка", + "боярин", + "брать", + "бревно", + "бригада", + "бросать", + "брызги", + "брюки", + "бублик", + "бугор", + "будущее", + "буква", + "бульвар", + "бумага", + "бунт", + "бурный", + "бусы", + "бутылка", + "буфет", + "бухта", + "бушлат", + "бывалый", + "быль", + "быстрый", + "быть", + "бюджет", + "бюро", + "бюст", + "вагон", + "важный", + "ваза", + "вакцина", + "валюта", + "вампир", + "ванная", + "вариант", + "вассал", + "вата", + "вафля", + "вахта", + "вдова", + "вдыхать", + "ведущий", + "веер", + "вежливый", + "везти", + "веко", + "великий", + "вена", + "верить", + "веселый", + "ветер", + "вечер", + "вешать", + "вещь", + "веяние", + "взаимный", + "взбучка", + "взвод", + "взгляд", + "вздыхать", + "взлетать", + "взмах", + "взнос", + "взор", + "взрыв", + "взывать", + "взятка", + "вибрация", + "визит", + "вилка", + "вино", + "вирус", + "висеть", + "витрина", + "вихрь", + "вишневый", + "включать", + "вкус", + "власть", + "влечь", + "влияние", + "влюблять", + "внешний", + "внимание", + "внук", + "внятный", + "вода", + "воевать", + "вождь", + "воздух", + "войти", + "вокзал", + "волос", + "вопрос", + "ворота", + "восток", + "впадать", + "впускать", + "врач", + "время", + "вручать", + "всадник", + "всеобщий", + "вспышка", + "встреча", + "вторник", + "вулкан", + "вурдалак", + "входить", + "въезд", + "выбор", + "вывод", + "выгодный", + "выделять", + "выезжать", + "выживать", + "вызывать", + "выигрыш", + "вылезать", + "выносить", + "выпивать", + "высокий", + "выходить", + "вычет", + "вышка", + "выяснять", + "вязать", + "вялый", + "гавань", + "гадать", + "газета", + "гаишник", + "галстук", + "гамма", + "гарантия", + "гастроли", + "гвардия", + "гвоздь", + "гектар", + "гель", + "генерал", + "геолог", + "герой", + "гешефт", + "гибель", + "гигант", + "гильза", + "гимн", + "гипотеза", + "гитара", + "глаз", + "глина", + "глоток", + "глубокий", + "глыба", + "глядеть", + "гнать", + "гнев", + "гнить", + "гном", + "гнуть", + "говорить", + "годовой", + "голова", + "гонка", + "город", + "гость", + "готовый", + "граница", + "грех", + "гриб", + "громкий", + "группа", + "грызть", + "грязный", + "губа", + "гудеть", + "гулять", + "гуманный", + "густой", + "гуща", + "давать", + "далекий", + "дама", + "данные", + "дарить", + "дать", + "дача", + "дверь", + "движение", + "двор", + "дебют", + "девушка", + "дедушка", + "дежурный", + "дезертир", + "действие", + "декабрь", + "дело", + "демократ", + "день", + "депутат", + "держать", + "десяток", + "детский", + "дефицит", + "дешевый", + "деятель", + "джаз", + "джинсы", + "джунгли", + "диалог", + "диван", + "диета", + "дизайн", + "дикий", + "динамика", + "диплом", + "директор", + "диск", + "дитя", + "дичь", + "длинный", + "дневник", + "добрый", + "доверие", + "договор", + "дождь", + "доза", + "документ", + "должен", + "домашний", + "допрос", + "дорога", + "доход", + "доцент", + "дочь", + "дощатый", + "драка", + "древний", + "дрожать", + "друг", + "дрянь", + "дубовый", + "дуга", + "дудка", + "дукат", + "дуло", + "думать", + "дупло", + "дурак", + "дуть", + "духи", + "душа", + "дуэт", + "дымить", + "дыня", + "дыра", + "дыханье", + "дышать", + "дьявол", + "дюжина", + "дюйм", + "дюна", + "дядя", + "дятел", + "егерь", + "единый", + "едкий", + "ежевика", + "ежик", + "езда", + "елка", + "емкость", + "ерунда", + "ехать", + "жадный", + "жажда", + "жалеть", + "жанр", + "жара", + "жать", + "жгучий", + "ждать", + "жевать", + "желание", + "жемчуг", + "женщина", + "жертва", + "жесткий", + "жечь", + "живой", + "жидкость", + "жизнь", + "жилье", + "жирный", + "житель", + "журнал", + "жюри", + "забывать", + "завод", + "загадка", + "задача", + "зажечь", + "зайти", + "закон", + "замечать", + "занимать", + "западный", + "зарплата", + "засыпать", + "затрата", + "захват", + "зацепка", + "зачет", + "защита", + "заявка", + "звать", + "звезда", + "звонить", + "звук", + "здание", + "здешний", + "здоровье", + "зебра", + "зевать", + "зеленый", + "земля", + "зенит", + "зеркало", + "зефир", + "зигзаг", + "зима", + "зиять", + "злак", + "злой", + "змея", + "знать", + "зной", + "зодчий", + "золотой", + "зомби", + "зона", + "зоопарк", + "зоркий", + "зрачок", + "зрение", + "зритель", + "зубной", + "зыбкий", + "зять", + "игла", + "иголка", + "играть", + "идея", + "идиот", + "идол", + "идти", + "иерархия", + "избрать", + "известие", + "изгонять", + "издание", + "излагать", + "изменять", + "износ", + "изоляция", + "изрядный", + "изучать", + "изымать", + "изящный", + "икона", + "икра", + "иллюзия", + "имбирь", + "иметь", + "имидж", + "иммунный", + "империя", + "инвестор", + "индивид", + "инерция", + "инженер", + "иномарка", + "институт", + "интерес", + "инфекция", + "инцидент", + "ипподром", + "ирис", + "ирония", + "искать", + "история", + "исходить", + "исчезать", + "итог", + "июль", + "июнь", + "кабинет", + "кавалер", + "кадр", + "казарма", + "кайф", + "кактус", + "калитка", + "камень", + "канал", + "капитан", + "картина", + "касса", + "катер", + "кафе", + "качество", + "каша", + "каюта", + "квартира", + "квинтет", + "квота", + "кедр", + "кекс", + "кенгуру", + "кепка", + "керосин", + "кетчуп", + "кефир", + "кибитка", + "кивнуть", + "кидать", + "километр", + "кино", + "киоск", + "кипеть", + "кирпич", + "кисть", + "китаец", + "класс", + "клетка", + "клиент", + "клоун", + "клуб", + "клык", + "ключ", + "клятва", + "книга", + "кнопка", + "кнут", + "князь", + "кобура", + "ковер", + "коготь", + "кодекс", + "кожа", + "козел", + "койка", + "коктейль", + "колено", + "компания", + "конец", + "копейка", + "короткий", + "костюм", + "котел", + "кофе", + "кошка", + "красный", + "кресло", + "кричать", + "кровь", + "крупный", + "крыша", + "крючок", + "кубок", + "кувшин", + "кудрявый", + "кузов", + "кукла", + "культура", + "кумир", + "купить", + "курс", + "кусок", + "кухня", + "куча", + "кушать", + "кювет", + "лабиринт", + "лавка", + "лагерь", + "ладонь", + "лазерный", + "лайнер", + "лакей", + "лампа", + "ландшафт", + "лапа", + "ларек", + "ласковый", + "лауреат", + "лачуга", + "лаять", + "лгать", + "лебедь", + "левый", + "легкий", + "ледяной", + "лежать", + "лекция", + "лента", + "лепесток", + "лесной", + "лето", + "лечь", + "леший", + "лживый", + "либерал", + "ливень", + "лига", + "лидер", + "ликовать", + "лиловый", + "лимон", + "линия", + "липа", + "лирика", + "лист", + "литр", + "лифт", + "лихой", + "лицо", + "личный", + "лишний", + "лобовой", + "ловить", + "логика", + "лодка", + "ложка", + "лозунг", + "локоть", + "ломать", + "лоно", + "лопата", + "лорд", + "лось", + "лоток", + "лохматый", + "лошадь", + "лужа", + "лукавый", + "луна", + "лупить", + "лучший", + "лыжный", + "лысый", + "львиный", + "льгота", + "льдина", + "любить", + "людской", + "люстра", + "лютый", + "лягушка", + "магазин", + "мадам", + "мазать", + "майор", + "максимум", + "мальчик", + "манера", + "март", + "масса", + "мать", + "мафия", + "махать", + "мачта", + "машина", + "маэстро", + "маяк", + "мгла", + "мебель", + "медведь", + "мелкий", + "мемуары", + "менять", + "мера", + "место", + "метод", + "механизм", + "мечтать", + "мешать", + "миграция", + "мизинец", + "микрофон", + "миллион", + "минута", + "мировой", + "миссия", + "митинг", + "мишень", + "младший", + "мнение", + "мнимый", + "могила", + "модель", + "мозг", + "мойка", + "мокрый", + "молодой", + "момент", + "монах", + "море", + "мост", + "мотор", + "мохнатый", + "мочь", + "мошенник", + "мощный", + "мрачный", + "мстить", + "мудрый", + "мужчина", + "музыка", + "мука", + "мумия", + "мундир", + "муравей", + "мусор", + "мутный", + "муфта", + "муха", + "мучить", + "мушкетер", + "мыло", + "мысль", + "мыть", + "мычать", + "мышь", + "мэтр", + "мюзикл", + "мягкий", + "мякиш", + "мясо", + "мятый", + "мячик", + "набор", + "навык", + "нагрузка", + "надежда", + "наемный", + "нажать", + "называть", + "наивный", + "накрыть", + "налог", + "намерен", + "наносить", + "написать", + "народ", + "натура", + "наука", + "нация", + "начать", + "небо", + "невеста", + "негодяй", + "неделя", + "нежный", + "незнание", + "нелепый", + "немалый", + "неправда", + "нервный", + "нести", + "нефть", + "нехватка", + "нечистый", + "неясный", + "нива", + "нижний", + "низкий", + "никель", + "нирвана", + "нить", + "ничья", + "ниша", + "нищий", + "новый", + "нога", + "ножницы", + "ноздря", + "ноль", + "номер", + "норма", + "нота", + "ночь", + "ноша", + "ноябрь", + "нрав", + "нужный", + "нутро", + "нынешний", + "нырнуть", + "ныть", + "нюанс", + "нюхать", + "няня", + "оазис", + "обаяние", + "обвинять", + "обгонять", + "обещать", + "обжигать", + "обзор", + "обида", + "область", + "обмен", + "обнимать", + "оборона", + "образ", + "обучение", + "обходить", + "обширный", + "общий", + "объект", + "обычный", + "обязать", + "овальный", + "овес", + "овощи", + "овраг", + "овца", + "овчарка", + "огненный", + "огонь", + "огромный", + "огурец", + "одежда", + "одинокий", + "одобрить", + "ожидать", + "ожог", + "озарение", + "озеро", + "означать", + "оказать", + "океан", + "оклад", + "окно", + "округ", + "октябрь", + "окурок", + "олень", + "опасный", + "операция", + "описать", + "оплата", + "опора", + "оппонент", + "опрос", + "оптимизм", + "опускать", + "опыт", + "орать", + "орбита", + "орган", + "орден", + "орел", + "оригинал", + "оркестр", + "орнамент", + "оружие", + "осадок", + "освещать", + "осень", + "осина", + "осколок", + "осмотр", + "основной", + "особый", + "осуждать", + "отбор", + "отвечать", + "отдать", + "отец", + "отзыв", + "открытие", + "отмечать", + "относить", + "отпуск", + "отрасль", + "отставка", + "оттенок", + "отходить", + "отчет", + "отъезд", + "офицер", + "охапка", + "охота", + "охрана", + "оценка", + "очаг", + "очередь", + "очищать", + "очки", + "ошейник", + "ошибка", + "ощущение", + "павильон", + "падать", + "паек", + "пакет", + "палец", + "память", + "панель", + "папка", + "партия", + "паспорт", + "патрон", + "пауза", + "пафос", + "пахнуть", + "пациент", + "пачка", + "пашня", + "певец", + "педагог", + "пейзаж", + "пельмень", + "пенсия", + "пепел", + "период", + "песня", + "петля", + "пехота", + "печать", + "пешеход", + "пещера", + "пианист", + "пиво", + "пиджак", + "пиковый", + "пилот", + "пионер", + "пирог", + "писать", + "пить", + "пицца", + "пишущий", + "пища", + "план", + "плечо", + "плита", + "плохой", + "плыть", + "плюс", + "пляж", + "победа", + "повод", + "погода", + "подумать", + "поехать", + "пожимать", + "позиция", + "поиск", + "покой", + "получать", + "помнить", + "пони", + "поощрять", + "попадать", + "порядок", + "пост", + "поток", + "похожий", + "поцелуй", + "почва", + "пощечина", + "поэт", + "пояснить", + "право", + "предмет", + "проблема", + "пруд", + "прыгать", + "прямой", + "психолог", + "птица", + "публика", + "пугать", + "пудра", + "пузырь", + "пуля", + "пункт", + "пурга", + "пустой", + "путь", + "пухлый", + "пучок", + "пушистый", + "пчела", + "пшеница", + "пыль", + "пытка", + "пыхтеть", + "пышный", + "пьеса", + "пьяный", + "пятно", + "работа", + "равный", + "радость", + "развитие", + "район", + "ракета", + "рамка", + "ранний", + "рапорт", + "рассказ", + "раунд", + "рация", + "рвать", + "реальный", + "ребенок", + "реветь", + "регион", + "редакция", + "реестр", + "режим", + "резкий", + "рейтинг", + "река", + "религия", + "ремонт", + "рента", + "реплика", + "ресурс", + "реформа", + "рецепт", + "речь", + "решение", + "ржавый", + "рисунок", + "ритм", + "рифма", + "робкий", + "ровный", + "рогатый", + "родитель", + "рождение", + "розовый", + "роковой", + "роль", + "роман", + "ронять", + "рост", + "рота", + "роща", + "рояль", + "рубль", + "ругать", + "руда", + "ружье", + "руины", + "рука", + "руль", + "румяный", + "русский", + "ручка", + "рыба", + "рывок", + "рыдать", + "рыжий", + "рынок", + "рысь", + "рыть", + "рыхлый", + "рыцарь", + "рычаг", + "рюкзак", + "рюмка", + "рябой", + "рядовой", + "сабля", + "садовый", + "сажать", + "салон", + "самолет", + "сани", + "сапог", + "сарай", + "сатира", + "сауна", + "сахар", + "сбегать", + "сбивать", + "сбор", + "сбыт", + "свадьба", + "свет", + "свидание", + "свобода", + "связь", + "сгорать", + "сдвигать", + "сеанс", + "северный", + "сегмент", + "седой", + "сезон", + "сейф", + "секунда", + "сельский", + "семья", + "сентябрь", + "сердце", + "сеть", + "сечение", + "сеять", + "сигнал", + "сидеть", + "сизый", + "сила", + "символ", + "синий", + "сирота", + "система", + "ситуация", + "сиять", + "сказать", + "скважина", + "скелет", + "скидка", + "склад", + "скорый", + "скрывать", + "скучный", + "слава", + "слеза", + "слияние", + "слово", + "случай", + "слышать", + "слюна", + "смех", + "смирение", + "смотреть", + "смутный", + "смысл", + "смятение", + "снаряд", + "снег", + "снижение", + "сносить", + "снять", + "событие", + "совет", + "согласие", + "сожалеть", + "сойти", + "сокол", + "солнце", + "сомнение", + "сонный", + "сообщать", + "соперник", + "сорт", + "состав", + "сотня", + "соус", + "социолог", + "сочинять", + "союз", + "спать", + "спешить", + "спина", + "сплошной", + "способ", + "спутник", + "средство", + "срок", + "срывать", + "стать", + "ствол", + "стена", + "стихи", + "сторона", + "страна", + "студент", + "стыд", + "субъект", + "сувенир", + "сугроб", + "судьба", + "суета", + "суждение", + "сукно", + "сулить", + "сумма", + "сунуть", + "супруг", + "суровый", + "сустав", + "суть", + "сухой", + "суша", + "существо", + "сфера", + "схема", + "сцена", + "счастье", + "счет", + "считать", + "сшивать", + "съезд", + "сынок", + "сыпать", + "сырье", + "сытый", + "сыщик", + "сюжет", + "сюрприз", + "таблица", + "таежный", + "таинство", + "тайна", + "такси", + "талант", + "таможня", + "танец", + "тарелка", + "таскать", + "тахта", + "тачка", + "таять", + "тварь", + "твердый", + "творить", + "театр", + "тезис", + "текст", + "тело", + "тема", + "тень", + "теория", + "теплый", + "терять", + "тесный", + "тетя", + "техника", + "течение", + "тигр", + "типичный", + "тираж", + "титул", + "тихий", + "тишина", + "ткань", + "товарищ", + "толпа", + "тонкий", + "топливо", + "торговля", + "тоска", + "точка", + "тощий", + "традиция", + "тревога", + "трибуна", + "трогать", + "труд", + "трюк", + "тряпка", + "туалет", + "тугой", + "туловище", + "туман", + "тундра", + "тупой", + "турнир", + "тусклый", + "туфля", + "туча", + "туша", + "тыкать", + "тысяча", + "тьма", + "тюльпан", + "тюрьма", + "тяга", + "тяжелый", + "тянуть", + "убеждать", + "убирать", + "убогий", + "убыток", + "уважение", + "уверять", + "увлекать", + "угнать", + "угол", + "угроза", + "удар", + "удивлять", + "удобный", + "уезд", + "ужас", + "ужин", + "узел", + "узкий", + "узнавать", + "узор", + "уйма", + "уклон", + "укол", + "уксус", + "улетать", + "улица", + "улучшать", + "улыбка", + "уметь", + "умиление", + "умный", + "умолять", + "умысел", + "унижать", + "уносить", + "уныние", + "упасть", + "уплата", + "упор", + "упрекать", + "упускать", + "уран", + "урна", + "уровень", + "усадьба", + "усердие", + "усилие", + "ускорять", + "условие", + "усмешка", + "уснуть", + "успеть", + "усыпать", + "утешать", + "утка", + "уточнять", + "утро", + "утюг", + "уходить", + "уцелеть", + "участие", + "ученый", + "учитель", + "ушко", + "ущерб", + "уютный", + "уяснять", + "фабрика", + "фаворит", + "фаза", + "файл", + "факт", + "фамилия", + "фантазия", + "фара", + "фасад", + "февраль", + "фельдшер", + "феномен", + "ферма", + "фигура", + "физика", + "фильм", + "финал", + "фирма", + "фишка", + "флаг", + "флейта", + "флот", + "фокус", + "фольклор", + "фонд", + "форма", + "фото", + "фраза", + "фреска", + "фронт", + "фрукт", + "функция", + "фуражка", + "футбол", + "фыркать", + "халат", + "хамство", + "хаос", + "характер", + "хата", + "хватать", + "хвост", + "хижина", + "хилый", + "химия", + "хирург", + "хитрый", + "хищник", + "хлам", + "хлеб", + "хлопать", + "хмурый", + "ходить", + "хозяин", + "хоккей", + "холодный", + "хороший", + "хотеть", + "хохотать", + "храм", + "хрен", + "хриплый", + "хроника", + "хрупкий", + "художник", + "хулиган", + "хутор", + "царь", + "цвет", + "цель", + "цемент", + "центр", + "цепь", + "церковь", + "цикл", + "цилиндр", + "циничный", + "цирк", + "цистерна", + "цитата", + "цифра", + "цыпленок", + "чадо", + "чайник", + "часть", + "чашка", + "человек", + "чемодан", + "чепуха", + "черный", + "честь", + "четкий", + "чехол", + "чиновник", + "число", + "читать", + "членство", + "чреватый", + "чтение", + "чувство", + "чугунный", + "чудо", + "чужой", + "чукча", + "чулок", + "чума", + "чуткий", + "чучело", + "чушь", + "шаблон", + "шагать", + "шайка", + "шакал", + "шалаш", + "шампунь", + "шанс", + "шапка", + "шарик", + "шасси", + "шатер", + "шахта", + "шашлык", + "швейный", + "швырять", + "шевелить", + "шедевр", + "шейка", + "шелковый", + "шептать", + "шерсть", + "шестерка", + "шикарный", + "шинель", + "шипеть", + "широкий", + "шить", + "шишка", + "шкаф", + "школа", + "шкура", + "шланг", + "шлем", + "шлюпка", + "шляпа", + "шнур", + "шоколад", + "шорох", + "шоссе", + "шофер", + "шпага", + "шпион", + "шприц", + "шрам", + "шрифт", + "штаб", + "штора", + "штраф", + "штука", + "штык", + "шуба", + "шуметь", + "шуршать", + "шутка", + "щадить", + "щедрый", + "щека", + "щель", + "щенок", + "щепка", + "щетка", + "щука", + "эволюция", + "эгоизм", + "экзамен", + "экипаж", + "экономия", + "экран", + "эксперт", + "элемент", + "элита", + "эмблема", + "эмигрант", + "эмоция", + "энергия", + "эпизод", + "эпоха", + "эскиз", + "эссе", + "эстрада", + "этап", + "этика", + "этюд", + "эфир", + "эффект", + "эшелон", + "юбилей", + "юбка", + "южный", + "юмор", + "юноша", + "юрист", + "яблоко", + "явление", + "ягода", + "ядерный", + "ядовитый", + "ядро", + "язва", + "язык", + "яйцо", + "якорь", + "январь", + "японец", + "яркий", + "ярмарка", + "ярость", + "ярус", + "ясный", + "яхта", + "ячейка", + "ящик" + }; + set_words(words); + populate_maps(); + } + }; +} + +#endif diff --git a/src/mnemonics/singleton.h b/src/mnemonics/singleton.h index ffe3fe4de..f03b1aca0 100644 --- a/src/mnemonics/singleton.h +++ b/src/mnemonics/singleton.h @@ -1,62 +1,62 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file singleton.h - * - * \brief A singleton helper class based on template. - */ - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - /*! - * \class Singleton - * - * \brief Single helper class. - * - * Do Language::Singleton::instance() to create a singleton instance - * of `YourClass`. - */ - template - class Singleton - { - Singleton() {} - Singleton(Singleton &s) = delete; - Singleton& operator=(const Singleton&) = delete; - public: - static T* instance() - { - static T* obj = new T; - return obj; - } - }; -} +// Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file singleton.h + * + * \brief A singleton helper class based on template. + */ + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + /*! + * \class Singleton + * + * \brief Single helper class. + * + * Do Language::Singleton::instance() to create a singleton instance + * of `YourClass`. + */ + template + class Singleton + { + Singleton() {} + Singleton(Singleton &s) = delete; + Singleton& operator=(const Singleton&) = delete; + public: + static T* instance() + { + static T* obj = new T; + return obj; + } + }; +} diff --git a/src/mnemonics/spanish.h b/src/mnemonics/spanish.h index a05485775..2a82c9b92 100644 --- a/src/mnemonics/spanish.h +++ b/src/mnemonics/spanish.h @@ -1,1712 +1,1712 @@ -// Word list originally created by dabura667 and released under The MIT License (MIT) -// -// The MIT License (MIT) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// -// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. - -/*! - * \file spanish.h - * - * \brief Spanish word list and map. - */ - -#ifndef SPANISH_H -#define SPANISH_H - -#include -#include -#include "language_base.h" -#include - -/*! - * \namespace Language - * \brief Mnemonic language related namespace. - */ -namespace Language -{ - class Spanish: public Base - { - public: - Spanish(): Base("Español", "Spanish", {}, 4) - { - static constexpr const char * const words[NWORDS] = - { - "ábaco", - "abdomen", - "abeja", - "abierto", - "abogado", - "abono", - "aborto", - "abrazo", - "abrir", - "abuelo", - "abuso", - "acabar", - "academia", - "acceso", - "acción", - "aceite", - "acelga", - "acento", - "aceptar", - "ácido", - "aclarar", - "acné", - "acoger", - "acoso", - "activo", - "acto", - "actriz", - "actuar", - "acudir", - "acuerdo", - "acusar", - "adicto", - "admitir", - "adoptar", - "adorno", - "aduana", - "adulto", - "aéreo", - "afectar", - "afición", - "afinar", - "afirmar", - "ágil", - "agitar", - "agonía", - "agosto", - "agotar", - "agregar", - "agrio", - "agua", - "agudo", - "águila", - "aguja", - "ahogo", - "ahorro", - "aire", - "aislar", - "ajedrez", - "ajeno", - "ajuste", - "alacrán", - "alambre", - "alarma", - "alba", - "álbum", - "alcalde", - "aldea", - "alegre", - "alejar", - "alerta", - "aleta", - "alfiler", - "alga", - "algodón", - "aliado", - "aliento", - "alivio", - "alma", - "almeja", - "almíbar", - "altar", - "alteza", - "altivo", - "alto", - "altura", - "alumno", - "alzar", - "amable", - "amante", - "amapola", - "amargo", - "amasar", - "ámbar", - "ámbito", - "ameno", - "amigo", - "amistad", - "amor", - "amparo", - "amplio", - "ancho", - "anciano", - "ancla", - "andar", - "andén", - "anemia", - "ángulo", - "anillo", - "ánimo", - "anís", - "anotar", - "antena", - "antiguo", - "antojo", - "anual", - "anular", - "anuncio", - "añadir", - "añejo", - "año", - "apagar", - "aparato", - "apetito", - "apio", - "aplicar", - "apodo", - "aporte", - "apoyo", - "aprender", - "aprobar", - "apuesta", - "apuro", - "arado", - "araña", - "arar", - "árbitro", - "árbol", - "arbusto", - "archivo", - "arco", - "arder", - "ardilla", - "arduo", - "área", - "árido", - "aries", - "armonía", - "arnés", - "aroma", - "arpa", - "arpón", - "arreglo", - "arroz", - "arruga", - "arte", - "artista", - "asa", - "asado", - "asalto", - "ascenso", - "asegurar", - "aseo", - "asesor", - "asiento", - "asilo", - "asistir", - "asno", - "asombro", - "áspero", - "astilla", - "astro", - "astuto", - "asumir", - "asunto", - "atajo", - "ataque", - "atar", - "atento", - "ateo", - "ático", - "atleta", - "átomo", - "atraer", - "atroz", - "atún", - "audaz", - "audio", - "auge", - "aula", - "aumento", - "ausente", - "autor", - "aval", - "avance", - "avaro", - "ave", - "avellana", - "avena", - "avestruz", - "avión", - "aviso", - "ayer", - "ayuda", - "ayuno", - "azafrán", - "azar", - "azote", - "azúcar", - "azufre", - "azul", - "baba", - "babor", - "bache", - "bahía", - "baile", - "bajar", - "balanza", - "balcón", - "balde", - "bambú", - "banco", - "banda", - "baño", - "barba", - "barco", - "barniz", - "barro", - "báscula", - "bastón", - "basura", - "batalla", - "batería", - "batir", - "batuta", - "baúl", - "bazar", - "bebé", - "bebida", - "bello", - "besar", - "beso", - "bestia", - "bicho", - "bien", - "bingo", - "blanco", - "bloque", - "blusa", - "boa", - "bobina", - "bobo", - "boca", - "bocina", - "boda", - "bodega", - "boina", - "bola", - "bolero", - "bolsa", - "bomba", - "bondad", - "bonito", - "bono", - "bonsái", - "borde", - "borrar", - "bosque", - "bote", - "botín", - "bóveda", - "bozal", - "bravo", - "brazo", - "brecha", - "breve", - "brillo", - "brinco", - "brisa", - "broca", - "broma", - "bronce", - "brote", - "bruja", - "brusco", - "bruto", - "buceo", - "bucle", - "bueno", - "buey", - "bufanda", - "bufón", - "búho", - "buitre", - "bulto", - "burbuja", - "burla", - "burro", - "buscar", - "butaca", - "buzón", - "caballo", - "cabeza", - "cabina", - "cabra", - "cacao", - "cadáver", - "cadena", - "caer", - "café", - "caída", - "caimán", - "caja", - "cajón", - "cal", - "calamar", - "calcio", - "caldo", - "calidad", - "calle", - "calma", - "calor", - "calvo", - "cama", - "cambio", - "camello", - "camino", - "campo", - "cáncer", - "candil", - "canela", - "canguro", - "canica", - "canto", - "caña", - "cañón", - "caoba", - "caos", - "capaz", - "capitán", - "capote", - "captar", - "capucha", - "cara", - "carbón", - "cárcel", - "careta", - "carga", - "cariño", - "carne", - "carpeta", - "carro", - "carta", - "casa", - "casco", - "casero", - "caspa", - "castor", - "catorce", - "catre", - "caudal", - "causa", - "cazo", - "cebolla", - "ceder", - "cedro", - "celda", - "célebre", - "celoso", - "célula", - "cemento", - "ceniza", - "centro", - "cerca", - "cerdo", - "cereza", - "cero", - "cerrar", - "certeza", - "césped", - "cetro", - "chacal", - "chaleco", - "champú", - "chancla", - "chapa", - "charla", - "chico", - "chiste", - "chivo", - "choque", - "choza", - "chuleta", - "chupar", - "ciclón", - "ciego", - "cielo", - "cien", - "cierto", - "cifra", - "cigarro", - "cima", - "cinco", - "cine", - "cinta", - "ciprés", - "circo", - "ciruela", - "cisne", - "cita", - "ciudad", - "clamor", - "clan", - "claro", - "clase", - "clave", - "cliente", - "clima", - "clínica", - "cobre", - "cocción", - "cochino", - "cocina", - "coco", - "código", - "codo", - "cofre", - "coger", - "cohete", - "cojín", - "cojo", - "cola", - "colcha", - "colegio", - "colgar", - "colina", - "collar", - "colmo", - "columna", - "combate", - "comer", - "comida", - "cómodo", - "compra", - "conde", - "conejo", - "conga", - "conocer", - "consejo", - "contar", - "copa", - "copia", - "corazón", - "corbata", - "corcho", - "cordón", - "corona", - "correr", - "coser", - "cosmos", - "costa", - "cráneo", - "cráter", - "crear", - "crecer", - "creído", - "crema", - "cría", - "crimen", - "cripta", - "crisis", - "cromo", - "crónica", - "croqueta", - "crudo", - "cruz", - "cuadro", - "cuarto", - "cuatro", - "cubo", - "cubrir", - "cuchara", - "cuello", - "cuento", - "cuerda", - "cuesta", - "cueva", - "cuidar", - "culebra", - "culpa", - "culto", - "cumbre", - "cumplir", - "cuna", - "cuneta", - "cuota", - "cupón", - "cúpula", - "curar", - "curioso", - "curso", - "curva", - "cutis", - "dama", - "danza", - "dar", - "dardo", - "dátil", - "deber", - "débil", - "década", - "decir", - "dedo", - "defensa", - "definir", - "dejar", - "delfín", - "delgado", - "delito", - "demora", - "denso", - "dental", - "deporte", - "derecho", - "derrota", - "desayuno", - "deseo", - "desfile", - "desnudo", - "destino", - "desvío", - "detalle", - "detener", - "deuda", - "día", - "diablo", - "diadema", - "diamante", - "diana", - "diario", - "dibujo", - "dictar", - "diente", - "dieta", - "diez", - "difícil", - "digno", - "dilema", - "diluir", - "dinero", - "directo", - "dirigir", - "disco", - "diseño", - "disfraz", - "diva", - "divino", - "doble", - "doce", - "dolor", - "domingo", - "don", - "donar", - "dorado", - "dormir", - "dorso", - "dos", - "dosis", - "dragón", - "droga", - "ducha", - "duda", - "duelo", - "dueño", - "dulce", - "dúo", - "duque", - "durar", - "dureza", - "duro", - "ébano", - "ebrio", - "echar", - "eco", - "ecuador", - "edad", - "edición", - "edificio", - "editor", - "educar", - "efecto", - "eficaz", - "eje", - "ejemplo", - "elefante", - "elegir", - "elemento", - "elevar", - "elipse", - "élite", - "elixir", - "elogio", - "eludir", - "embudo", - "emitir", - "emoción", - "empate", - "empeño", - "empleo", - "empresa", - "enano", - "encargo", - "enchufe", - "encía", - "enemigo", - "enero", - "enfado", - "enfermo", - "engaño", - "enigma", - "enlace", - "enorme", - "enredo", - "ensayo", - "enseñar", - "entero", - "entrar", - "envase", - "envío", - "época", - "equipo", - "erizo", - "escala", - "escena", - "escolar", - "escribir", - "escudo", - "esencia", - "esfera", - "esfuerzo", - "espada", - "espejo", - "espía", - "esposa", - "espuma", - "esquí", - "estar", - "este", - "estilo", - "estufa", - "etapa", - "eterno", - "ética", - "etnia", - "evadir", - "evaluar", - "evento", - "evitar", - "exacto", - "examen", - "exceso", - "excusa", - "exento", - "exigir", - "exilio", - "existir", - "éxito", - "experto", - "explicar", - "exponer", - "extremo", - "fábrica", - "fábula", - "fachada", - "fácil", - "factor", - "faena", - "faja", - "falda", - "fallo", - "falso", - "faltar", - "fama", - "familia", - "famoso", - "faraón", - "farmacia", - "farol", - "farsa", - "fase", - "fatiga", - "fauna", - "favor", - "fax", - "febrero", - "fecha", - "feliz", - "feo", - "feria", - "feroz", - "fértil", - "fervor", - "festín", - "fiable", - "fianza", - "fiar", - "fibra", - "ficción", - "ficha", - "fideo", - "fiebre", - "fiel", - "fiera", - "fiesta", - "figura", - "fijar", - "fijo", - "fila", - "filete", - "filial", - "filtro", - "fin", - "finca", - "fingir", - "finito", - "firma", - "flaco", - "flauta", - "flecha", - "flor", - "flota", - "fluir", - "flujo", - "flúor", - "fobia", - "foca", - "fogata", - "fogón", - "folio", - "folleto", - "fondo", - "forma", - "forro", - "fortuna", - "forzar", - "fosa", - "foto", - "fracaso", - "frágil", - "franja", - "frase", - "fraude", - "freír", - "freno", - "fresa", - "frío", - "frito", - "fruta", - "fuego", - "fuente", - "fuerza", - "fuga", - "fumar", - "función", - "funda", - "furgón", - "furia", - "fusil", - "fútbol", - "futuro", - "gacela", - "gafas", - "gaita", - "gajo", - "gala", - "galería", - "gallo", - "gamba", - "ganar", - "gancho", - "ganga", - "ganso", - "garaje", - "garza", - "gasolina", - "gastar", - "gato", - "gavilán", - "gemelo", - "gemir", - "gen", - "género", - "genio", - "gente", - "geranio", - "gerente", - "germen", - "gesto", - "gigante", - "gimnasio", - "girar", - "giro", - "glaciar", - "globo", - "gloria", - "gol", - "golfo", - "goloso", - "golpe", - "goma", - "gordo", - "gorila", - "gorra", - "gota", - "goteo", - "gozar", - "grada", - "gráfico", - "grano", - "grasa", - "gratis", - "grave", - "grieta", - "grillo", - "gripe", - "gris", - "grito", - "grosor", - "grúa", - "grueso", - "grumo", - "grupo", - "guante", - "guapo", - "guardia", - "guerra", - "guía", - "guiño", - "guion", - "guiso", - "guitarra", - "gusano", - "gustar", - "haber", - "hábil", - "hablar", - "hacer", - "hacha", - "hada", - "hallar", - "hamaca", - "harina", - "haz", - "hazaña", - "hebilla", - "hebra", - "hecho", - "helado", - "helio", - "hembra", - "herir", - "hermano", - "héroe", - "hervir", - "hielo", - "hierro", - "hígado", - "higiene", - "hijo", - "himno", - "historia", - "hocico", - "hogar", - "hoguera", - "hoja", - "hombre", - "hongo", - "honor", - "honra", - "hora", - "hormiga", - "horno", - "hostil", - "hoyo", - "hueco", - "huelga", - "huerta", - "hueso", - "huevo", - "huida", - "huir", - "humano", - "húmedo", - "humilde", - "humo", - "hundir", - "huracán", - "hurto", - "icono", - "ideal", - "idioma", - "ídolo", - "iglesia", - "iglú", - "igual", - "ilegal", - "ilusión", - "imagen", - "imán", - "imitar", - "impar", - "imperio", - "imponer", - "impulso", - "incapaz", - "índice", - "inerte", - "infiel", - "informe", - "ingenio", - "inicio", - "inmenso", - "inmune", - "innato", - "insecto", - "instante", - "interés", - "íntimo", - "intuir", - "inútil", - "invierno", - "ira", - "iris", - "ironía", - "isla", - "islote", - "jabalí", - "jabón", - "jamón", - "jarabe", - "jardín", - "jarra", - "jaula", - "jazmín", - "jefe", - "jeringa", - "jinete", - "jornada", - "joroba", - "joven", - "joya", - "juerga", - "jueves", - "juez", - "jugador", - "jugo", - "juguete", - "juicio", - "junco", - "jungla", - "junio", - "juntar", - "júpiter", - "jurar", - "justo", - "juvenil", - "juzgar", - "kilo", - "koala", - "labio", - "lacio", - "lacra", - "lado", - "ladrón", - "lagarto", - "lágrima", - "laguna", - "laico", - "lamer", - "lámina", - "lámpara", - "lana", - "lancha", - "langosta", - "lanza", - "lápiz", - "largo", - "larva", - "lástima", - "lata", - "látex", - "latir", - "laurel", - "lavar", - "lazo", - "leal", - "lección", - "leche", - "lector", - "leer", - "legión", - "legumbre", - "lejano", - "lengua", - "lento", - "leña", - "león", - "leopardo", - "lesión", - "letal", - "letra", - "leve", - "leyenda", - "libertad", - "libro", - "licor", - "líder", - "lidiar", - "lienzo", - "liga", - "ligero", - "lima", - "límite", - "limón", - "limpio", - "lince", - "lindo", - "línea", - "lingote", - "lino", - "linterna", - "líquido", - "liso", - "lista", - "litera", - "litio", - "litro", - "llaga", - "llama", - "llanto", - "llave", - "llegar", - "llenar", - "llevar", - "llorar", - "llover", - "lluvia", - "lobo", - "loción", - "loco", - "locura", - "lógica", - "logro", - "lombriz", - "lomo", - "lonja", - "lote", - "lucha", - "lucir", - "lugar", - "lujo", - "luna", - "lunes", - "lupa", - "lustro", - "luto", - "luz", - "maceta", - "macho", - "madera", - "madre", - "maduro", - "maestro", - "mafia", - "magia", - "mago", - "maíz", - "maldad", - "maleta", - "malla", - "malo", - "mamá", - "mambo", - "mamut", - "manco", - "mando", - "manejar", - "manga", - "maniquí", - "manjar", - "mano", - "manso", - "manta", - "mañana", - "mapa", - "máquina", - "mar", - "marco", - "marea", - "marfil", - "margen", - "marido", - "mármol", - "marrón", - "martes", - "marzo", - "masa", - "máscara", - "masivo", - "matar", - "materia", - "matiz", - "matriz", - "máximo", - "mayor", - "mazorca", - "mecha", - "medalla", - "medio", - "médula", - "mejilla", - "mejor", - "melena", - "melón", - "memoria", - "menor", - "mensaje", - "mente", - "menú", - "mercado", - "merengue", - "mérito", - "mes", - "mesón", - "meta", - "meter", - "método", - "metro", - "mezcla", - "miedo", - "miel", - "miembro", - "miga", - "mil", - "milagro", - "militar", - "millón", - "mimo", - "mina", - "minero", - "mínimo", - "minuto", - "miope", - "mirar", - "misa", - "miseria", - "misil", - "mismo", - "mitad", - "mito", - "mochila", - "moción", - "moda", - "modelo", - "moho", - "mojar", - "molde", - "moler", - "molino", - "momento", - "momia", - "monarca", - "moneda", - "monja", - "monto", - "moño", - "morada", - "morder", - "moreno", - "morir", - "morro", - "morsa", - "mortal", - "mosca", - "mostrar", - "motivo", - "mover", - "móvil", - "mozo", - "mucho", - "mudar", - "mueble", - "muela", - "muerte", - "muestra", - "mugre", - "mujer", - "mula", - "muleta", - "multa", - "mundo", - "muñeca", - "mural", - "muro", - "músculo", - "museo", - "musgo", - "música", - "muslo", - "nácar", - "nación", - "nadar", - "naipe", - "naranja", - "nariz", - "narrar", - "nasal", - "natal", - "nativo", - "natural", - "náusea", - "naval", - "nave", - "navidad", - "necio", - "néctar", - "negar", - "negocio", - "negro", - "neón", - "nervio", - "neto", - "neutro", - "nevar", - "nevera", - "nicho", - "nido", - "niebla", - "nieto", - "niñez", - "niño", - "nítido", - "nivel", - "nobleza", - "noche", - "nómina", - "noria", - "norma", - "norte", - "nota", - "noticia", - "novato", - "novela", - "novio", - "nube", - "nuca", - "núcleo", - "nudillo", - "nudo", - "nuera", - "nueve", - "nuez", - "nulo", - "número", - "nutria", - "oasis", - "obeso", - "obispo", - "objeto", - "obra", - "obrero", - "observar", - "obtener", - "obvio", - "oca", - "ocaso", - "océano", - "ochenta", - "ocho", - "ocio", - "ocre", - "octavo", - "octubre", - "oculto", - "ocupar", - "ocurrir", - "odiar", - "odio", - "odisea", - "oeste", - "ofensa", - "oferta", - "oficio", - "ofrecer", - "ogro", - "oído", - "oír", - "ojo", - "ola", - "oleada", - "olfato", - "olivo", - "olla", - "olmo", - "olor", - "olvido", - "ombligo", - "onda", - "onza", - "opaco", - "opción", - "ópera", - "opinar", - "oponer", - "optar", - "óptica", - "opuesto", - "oración", - "orador", - "oral", - "órbita", - "orca", - "orden", - "oreja", - "órgano", - "orgía", - "orgullo", - "oriente", - "origen", - "orilla", - "oro", - "orquesta", - "oruga", - "osadía", - "oscuro", - "osezno", - "oso", - "ostra", - "otoño", - "otro", - "oveja", - "óvulo", - "óxido", - "oxígeno", - "oyente", - "ozono", - "pacto", - "padre", - "paella", - "página", - "pago", - "país", - "pájaro", - "palabra", - "palco", - "paleta", - "pálido", - "palma", - "paloma", - "palpar", - "pan", - "panal", - "pánico", - "pantera", - "pañuelo", - "papá", - "papel", - "papilla", - "paquete", - "parar", - "parcela", - "pared", - "parir", - "paro", - "párpado", - "parque", - "párrafo", - "parte", - "pasar", - "paseo", - "pasión", - "paso", - "pasta", - "pata", - "patio", - "patria", - "pausa", - "pauta", - "pavo", - "payaso", - "peatón", - "pecado", - "pecera", - "pecho", - "pedal", - "pedir", - "pegar", - "peine", - "pelar", - "peldaño", - "pelea", - "peligro", - "pellejo", - "pelo", - "peluca", - "pena", - "pensar", - "peñón", - "peón", - "peor", - "pepino", - "pequeño", - "pera", - "percha", - "perder", - "pereza", - "perfil", - "perico", - "perla", - "permiso", - "perro", - "persona", - "pesa", - "pesca", - "pésimo", - "pestaña", - "pétalo", - "petróleo", - "pez", - "pezuña", - "picar", - "pichón", - "pie", - "piedra", - "pierna", - "pieza", - "pijama", - "pilar", - "piloto", - "pimienta", - "pino", - "pintor", - "pinza", - "piña", - "piojo", - "pipa", - "pirata", - "pisar", - "piscina", - "piso", - "pista", - "pitón", - "pizca", - "placa", - "plan", - "plata", - "playa", - "plaza", - "pleito", - "pleno", - "plomo", - "pluma", - "plural", - "pobre", - "poco", - "poder", - "podio", - "poema", - "poesía", - "poeta", - "polen", - "policía", - "pollo", - "polvo", - "pomada", - "pomelo", - "pomo", - "pompa", - "poner", - "porción", - "portal", - "posada", - "poseer", - "posible", - "poste", - "potencia", - "potro", - "pozo", - "prado", - "precoz", - "pregunta", - "premio", - "prensa", - "preso", - "previo", - "primo", - "príncipe", - "prisión", - "privar", - "proa", - "probar", - "proceso", - "producto", - "proeza", - "profesor", - "programa", - "prole", - "promesa", - "pronto", - "propio", - "próximo", - "prueba", - "público", - "puchero", - "pudor", - "pueblo", - "puerta", - "puesto", - "pulga", - "pulir", - "pulmón", - "pulpo", - "pulso", - "puma", - "punto", - "puñal", - "puño", - "pupa", - "pupila", - "puré", - "quedar", - "queja", - "quemar", - "querer", - "queso", - "quieto", - "química", - "quince", - "quitar", - "rábano", - "rabia", - "rabo", - "ración", - "radical", - "raíz", - "rama", - "rampa", - "rancho", - "rango", - "rapaz", - "rápido", - "rapto", - "rasgo", - "raspa", - "rato", - "rayo", - "raza", - "razón", - "reacción", - "realidad", - "rebaño", - "rebote", - "recaer", - "receta", - "rechazo", - "recoger", - "recreo", - "recto", - "recurso", - "red", - "redondo", - "reducir", - "reflejo", - "reforma", - "refrán", - "refugio", - "regalo", - "regir", - "regla", - "regreso", - "rehén", - "reino", - "reír", - "reja", - "relato", - "relevo", - "relieve", - "relleno", - "reloj", - "remar", - "remedio", - "remo", - "rencor", - "rendir", - "renta", - "reparto", - "repetir", - "reposo", - "reptil", - "res", - "rescate", - "resina", - "respeto", - "resto", - "resumen", - "retiro", - "retorno", - "retrato", - "reunir", - "revés", - "revista", - "rey", - "rezar", - "rico", - "riego", - "rienda", - "riesgo", - "rifa", - "rígido", - "rigor", - "rincón", - "riñón", - "río", - "riqueza", - "risa", - "ritmo", - "rito" - }; - set_words(words); - populate_maps(ALLOW_SHORT_WORDS); - } - }; -} - -#endif +// Word list originally created by dabura667 and released under The MIT License (MIT) +// +// The MIT License (MIT) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// Code surrounding the word list is Copyright (c) 2014-2019, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +/*! + * \file spanish.h + * + * \brief Spanish word list and map. + */ + +#ifndef SPANISH_H +#define SPANISH_H + +#include +#include +#include "language_base.h" +#include + +/*! + * \namespace Language + * \brief Mnemonic language related namespace. + */ +namespace Language +{ + class Spanish: public Base + { + public: + Spanish(): Base("Español", "Spanish", {}, 4) + { + static constexpr const char * const words[NWORDS] = + { + "ábaco", + "abdomen", + "abeja", + "abierto", + "abogado", + "abono", + "aborto", + "abrazo", + "abrir", + "abuelo", + "abuso", + "acabar", + "academia", + "acceso", + "acción", + "aceite", + "acelga", + "acento", + "aceptar", + "ácido", + "aclarar", + "acné", + "acoger", + "acoso", + "activo", + "acto", + "actriz", + "actuar", + "acudir", + "acuerdo", + "acusar", + "adicto", + "admitir", + "adoptar", + "adorno", + "aduana", + "adulto", + "aéreo", + "afectar", + "afición", + "afinar", + "afirmar", + "ágil", + "agitar", + "agonía", + "agosto", + "agotar", + "agregar", + "agrio", + "agua", + "agudo", + "águila", + "aguja", + "ahogo", + "ahorro", + "aire", + "aislar", + "ajedrez", + "ajeno", + "ajuste", + "alacrán", + "alambre", + "alarma", + "alba", + "álbum", + "alcalde", + "aldea", + "alegre", + "alejar", + "alerta", + "aleta", + "alfiler", + "alga", + "algodón", + "aliado", + "aliento", + "alivio", + "alma", + "almeja", + "almíbar", + "altar", + "alteza", + "altivo", + "alto", + "altura", + "alumno", + "alzar", + "amable", + "amante", + "amapola", + "amargo", + "amasar", + "ámbar", + "ámbito", + "ameno", + "amigo", + "amistad", + "amor", + "amparo", + "amplio", + "ancho", + "anciano", + "ancla", + "andar", + "andén", + "anemia", + "ángulo", + "anillo", + "ánimo", + "anís", + "anotar", + "antena", + "antiguo", + "antojo", + "anual", + "anular", + "anuncio", + "añadir", + "añejo", + "año", + "apagar", + "aparato", + "apetito", + "apio", + "aplicar", + "apodo", + "aporte", + "apoyo", + "aprender", + "aprobar", + "apuesta", + "apuro", + "arado", + "araña", + "arar", + "árbitro", + "árbol", + "arbusto", + "archivo", + "arco", + "arder", + "ardilla", + "arduo", + "área", + "árido", + "aries", + "armonía", + "arnés", + "aroma", + "arpa", + "arpón", + "arreglo", + "arroz", + "arruga", + "arte", + "artista", + "asa", + "asado", + "asalto", + "ascenso", + "asegurar", + "aseo", + "asesor", + "asiento", + "asilo", + "asistir", + "asno", + "asombro", + "áspero", + "astilla", + "astro", + "astuto", + "asumir", + "asunto", + "atajo", + "ataque", + "atar", + "atento", + "ateo", + "ático", + "atleta", + "átomo", + "atraer", + "atroz", + "atún", + "audaz", + "audio", + "auge", + "aula", + "aumento", + "ausente", + "autor", + "aval", + "avance", + "avaro", + "ave", + "avellana", + "avena", + "avestruz", + "avión", + "aviso", + "ayer", + "ayuda", + "ayuno", + "azafrán", + "azar", + "azote", + "azúcar", + "azufre", + "azul", + "baba", + "babor", + "bache", + "bahía", + "baile", + "bajar", + "balanza", + "balcón", + "balde", + "bambú", + "banco", + "banda", + "baño", + "barba", + "barco", + "barniz", + "barro", + "báscula", + "bastón", + "basura", + "batalla", + "batería", + "batir", + "batuta", + "baúl", + "bazar", + "bebé", + "bebida", + "bello", + "besar", + "beso", + "bestia", + "bicho", + "bien", + "bingo", + "blanco", + "bloque", + "blusa", + "boa", + "bobina", + "bobo", + "boca", + "bocina", + "boda", + "bodega", + "boina", + "bola", + "bolero", + "bolsa", + "bomba", + "bondad", + "bonito", + "bono", + "bonsái", + "borde", + "borrar", + "bosque", + "bote", + "botín", + "bóveda", + "bozal", + "bravo", + "brazo", + "brecha", + "breve", + "brillo", + "brinco", + "brisa", + "broca", + "broma", + "bronce", + "brote", + "bruja", + "brusco", + "bruto", + "buceo", + "bucle", + "bueno", + "buey", + "bufanda", + "bufón", + "búho", + "buitre", + "bulto", + "burbuja", + "burla", + "burro", + "buscar", + "butaca", + "buzón", + "caballo", + "cabeza", + "cabina", + "cabra", + "cacao", + "cadáver", + "cadena", + "caer", + "café", + "caída", + "caimán", + "caja", + "cajón", + "cal", + "calamar", + "calcio", + "caldo", + "calidad", + "calle", + "calma", + "calor", + "calvo", + "cama", + "cambio", + "camello", + "camino", + "campo", + "cáncer", + "candil", + "canela", + "canguro", + "canica", + "canto", + "caña", + "cañón", + "caoba", + "caos", + "capaz", + "capitán", + "capote", + "captar", + "capucha", + "cara", + "carbón", + "cárcel", + "careta", + "carga", + "cariño", + "carne", + "carpeta", + "carro", + "carta", + "casa", + "casco", + "casero", + "caspa", + "castor", + "catorce", + "catre", + "caudal", + "causa", + "cazo", + "cebolla", + "ceder", + "cedro", + "celda", + "célebre", + "celoso", + "célula", + "cemento", + "ceniza", + "centro", + "cerca", + "cerdo", + "cereza", + "cero", + "cerrar", + "certeza", + "césped", + "cetro", + "chacal", + "chaleco", + "champú", + "chancla", + "chapa", + "charla", + "chico", + "chiste", + "chivo", + "choque", + "choza", + "chuleta", + "chupar", + "ciclón", + "ciego", + "cielo", + "cien", + "cierto", + "cifra", + "cigarro", + "cima", + "cinco", + "cine", + "cinta", + "ciprés", + "circo", + "ciruela", + "cisne", + "cita", + "ciudad", + "clamor", + "clan", + "claro", + "clase", + "clave", + "cliente", + "clima", + "clínica", + "cobre", + "cocción", + "cochino", + "cocina", + "coco", + "código", + "codo", + "cofre", + "coger", + "cohete", + "cojín", + "cojo", + "cola", + "colcha", + "colegio", + "colgar", + "colina", + "collar", + "colmo", + "columna", + "combate", + "comer", + "comida", + "cómodo", + "compra", + "conde", + "conejo", + "conga", + "conocer", + "consejo", + "contar", + "copa", + "copia", + "corazón", + "corbata", + "corcho", + "cordón", + "corona", + "correr", + "coser", + "cosmos", + "costa", + "cráneo", + "cráter", + "crear", + "crecer", + "creído", + "crema", + "cría", + "crimen", + "cripta", + "crisis", + "cromo", + "crónica", + "croqueta", + "crudo", + "cruz", + "cuadro", + "cuarto", + "cuatro", + "cubo", + "cubrir", + "cuchara", + "cuello", + "cuento", + "cuerda", + "cuesta", + "cueva", + "cuidar", + "culebra", + "culpa", + "culto", + "cumbre", + "cumplir", + "cuna", + "cuneta", + "cuota", + "cupón", + "cúpula", + "curar", + "curioso", + "curso", + "curva", + "cutis", + "dama", + "danza", + "dar", + "dardo", + "dátil", + "deber", + "débil", + "década", + "decir", + "dedo", + "defensa", + "definir", + "dejar", + "delfín", + "delgado", + "delito", + "demora", + "denso", + "dental", + "deporte", + "derecho", + "derrota", + "desayuno", + "deseo", + "desfile", + "desnudo", + "destino", + "desvío", + "detalle", + "detener", + "deuda", + "día", + "diablo", + "diadema", + "diamante", + "diana", + "diario", + "dibujo", + "dictar", + "diente", + "dieta", + "diez", + "difícil", + "digno", + "dilema", + "diluir", + "dinero", + "directo", + "dirigir", + "disco", + "diseño", + "disfraz", + "diva", + "divino", + "doble", + "doce", + "dolor", + "domingo", + "don", + "donar", + "dorado", + "dormir", + "dorso", + "dos", + "dosis", + "dragón", + "droga", + "ducha", + "duda", + "duelo", + "dueño", + "dulce", + "dúo", + "duque", + "durar", + "dureza", + "duro", + "ébano", + "ebrio", + "echar", + "eco", + "ecuador", + "edad", + "edición", + "edificio", + "editor", + "educar", + "efecto", + "eficaz", + "eje", + "ejemplo", + "elefante", + "elegir", + "elemento", + "elevar", + "elipse", + "élite", + "elixir", + "elogio", + "eludir", + "embudo", + "emitir", + "emoción", + "empate", + "empeño", + "empleo", + "empresa", + "enano", + "encargo", + "enchufe", + "encía", + "enemigo", + "enero", + "enfado", + "enfermo", + "engaño", + "enigma", + "enlace", + "enorme", + "enredo", + "ensayo", + "enseñar", + "entero", + "entrar", + "envase", + "envío", + "época", + "equipo", + "erizo", + "escala", + "escena", + "escolar", + "escribir", + "escudo", + "esencia", + "esfera", + "esfuerzo", + "espada", + "espejo", + "espía", + "esposa", + "espuma", + "esquí", + "estar", + "este", + "estilo", + "estufa", + "etapa", + "eterno", + "ética", + "etnia", + "evadir", + "evaluar", + "evento", + "evitar", + "exacto", + "examen", + "exceso", + "excusa", + "exento", + "exigir", + "exilio", + "existir", + "éxito", + "experto", + "explicar", + "exponer", + "extremo", + "fábrica", + "fábula", + "fachada", + "fácil", + "factor", + "faena", + "faja", + "falda", + "fallo", + "falso", + "faltar", + "fama", + "familia", + "famoso", + "faraón", + "farmacia", + "farol", + "farsa", + "fase", + "fatiga", + "fauna", + "favor", + "fax", + "febrero", + "fecha", + "feliz", + "feo", + "feria", + "feroz", + "fértil", + "fervor", + "festín", + "fiable", + "fianza", + "fiar", + "fibra", + "ficción", + "ficha", + "fideo", + "fiebre", + "fiel", + "fiera", + "fiesta", + "figura", + "fijar", + "fijo", + "fila", + "filete", + "filial", + "filtro", + "fin", + "finca", + "fingir", + "finito", + "firma", + "flaco", + "flauta", + "flecha", + "flor", + "flota", + "fluir", + "flujo", + "flúor", + "fobia", + "foca", + "fogata", + "fogón", + "folio", + "folleto", + "fondo", + "forma", + "forro", + "fortuna", + "forzar", + "fosa", + "foto", + "fracaso", + "frágil", + "franja", + "frase", + "fraude", + "freír", + "freno", + "fresa", + "frío", + "frito", + "fruta", + "fuego", + "fuente", + "fuerza", + "fuga", + "fumar", + "función", + "funda", + "furgón", + "furia", + "fusil", + "fútbol", + "futuro", + "gacela", + "gafas", + "gaita", + "gajo", + "gala", + "galería", + "gallo", + "gamba", + "ganar", + "gancho", + "ganga", + "ganso", + "garaje", + "garza", + "gasolina", + "gastar", + "gato", + "gavilán", + "gemelo", + "gemir", + "gen", + "género", + "genio", + "gente", + "geranio", + "gerente", + "germen", + "gesto", + "gigante", + "gimnasio", + "girar", + "giro", + "glaciar", + "globo", + "gloria", + "gol", + "golfo", + "goloso", + "golpe", + "goma", + "gordo", + "gorila", + "gorra", + "gota", + "goteo", + "gozar", + "grada", + "gráfico", + "grano", + "grasa", + "gratis", + "grave", + "grieta", + "grillo", + "gripe", + "gris", + "grito", + "grosor", + "grúa", + "grueso", + "grumo", + "grupo", + "guante", + "guapo", + "guardia", + "guerra", + "guía", + "guiño", + "guion", + "guiso", + "guitarra", + "gusano", + "gustar", + "haber", + "hábil", + "hablar", + "hacer", + "hacha", + "hada", + "hallar", + "hamaca", + "harina", + "haz", + "hazaña", + "hebilla", + "hebra", + "hecho", + "helado", + "helio", + "hembra", + "herir", + "hermano", + "héroe", + "hervir", + "hielo", + "hierro", + "hígado", + "higiene", + "hijo", + "himno", + "historia", + "hocico", + "hogar", + "hoguera", + "hoja", + "hombre", + "hongo", + "honor", + "honra", + "hora", + "hormiga", + "horno", + "hostil", + "hoyo", + "hueco", + "huelga", + "huerta", + "hueso", + "huevo", + "huida", + "huir", + "humano", + "húmedo", + "humilde", + "humo", + "hundir", + "huracán", + "hurto", + "icono", + "ideal", + "idioma", + "ídolo", + "iglesia", + "iglú", + "igual", + "ilegal", + "ilusión", + "imagen", + "imán", + "imitar", + "impar", + "imperio", + "imponer", + "impulso", + "incapaz", + "índice", + "inerte", + "infiel", + "informe", + "ingenio", + "inicio", + "inmenso", + "inmune", + "innato", + "insecto", + "instante", + "interés", + "íntimo", + "intuir", + "inútil", + "invierno", + "ira", + "iris", + "ironía", + "isla", + "islote", + "jabalí", + "jabón", + "jamón", + "jarabe", + "jardín", + "jarra", + "jaula", + "jazmín", + "jefe", + "jeringa", + "jinete", + "jornada", + "joroba", + "joven", + "joya", + "juerga", + "jueves", + "juez", + "jugador", + "jugo", + "juguete", + "juicio", + "junco", + "jungla", + "junio", + "juntar", + "júpiter", + "jurar", + "justo", + "juvenil", + "juzgar", + "kilo", + "koala", + "labio", + "lacio", + "lacra", + "lado", + "ladrón", + "lagarto", + "lágrima", + "laguna", + "laico", + "lamer", + "lámina", + "lámpara", + "lana", + "lancha", + "langosta", + "lanza", + "lápiz", + "largo", + "larva", + "lástima", + "lata", + "látex", + "latir", + "laurel", + "lavar", + "lazo", + "leal", + "lección", + "leche", + "lector", + "leer", + "legión", + "legumbre", + "lejano", + "lengua", + "lento", + "leña", + "león", + "leopardo", + "lesión", + "letal", + "letra", + "leve", + "leyenda", + "libertad", + "libro", + "licor", + "líder", + "lidiar", + "lienzo", + "liga", + "ligero", + "lima", + "límite", + "limón", + "limpio", + "lince", + "lindo", + "línea", + "lingote", + "lino", + "linterna", + "líquido", + "liso", + "lista", + "litera", + "litio", + "litro", + "llaga", + "llama", + "llanto", + "llave", + "llegar", + "llenar", + "llevar", + "llorar", + "llover", + "lluvia", + "lobo", + "loción", + "loco", + "locura", + "lógica", + "logro", + "lombriz", + "lomo", + "lonja", + "lote", + "lucha", + "lucir", + "lugar", + "lujo", + "luna", + "lunes", + "lupa", + "lustro", + "luto", + "luz", + "maceta", + "macho", + "madera", + "madre", + "maduro", + "maestro", + "mafia", + "magia", + "mago", + "maíz", + "maldad", + "maleta", + "malla", + "malo", + "mamá", + "mambo", + "mamut", + "manco", + "mando", + "manejar", + "manga", + "maniquí", + "manjar", + "mano", + "manso", + "manta", + "mañana", + "mapa", + "máquina", + "mar", + "marco", + "marea", + "marfil", + "margen", + "marido", + "mármol", + "marrón", + "martes", + "marzo", + "masa", + "máscara", + "masivo", + "matar", + "materia", + "matiz", + "matriz", + "máximo", + "mayor", + "mazorca", + "mecha", + "medalla", + "medio", + "médula", + "mejilla", + "mejor", + "melena", + "melón", + "memoria", + "menor", + "mensaje", + "mente", + "menú", + "mercado", + "merengue", + "mérito", + "mes", + "mesón", + "meta", + "meter", + "método", + "metro", + "mezcla", + "miedo", + "miel", + "miembro", + "miga", + "mil", + "milagro", + "militar", + "millón", + "mimo", + "mina", + "minero", + "mínimo", + "minuto", + "miope", + "mirar", + "misa", + "miseria", + "misil", + "mismo", + "mitad", + "mito", + "mochila", + "moción", + "moda", + "modelo", + "moho", + "mojar", + "molde", + "moler", + "molino", + "momento", + "momia", + "monarca", + "moneda", + "monja", + "monto", + "moño", + "morada", + "morder", + "moreno", + "morir", + "morro", + "morsa", + "mortal", + "mosca", + "mostrar", + "motivo", + "mover", + "móvil", + "mozo", + "mucho", + "mudar", + "mueble", + "muela", + "muerte", + "muestra", + "mugre", + "mujer", + "mula", + "muleta", + "multa", + "mundo", + "muñeca", + "mural", + "muro", + "músculo", + "museo", + "musgo", + "música", + "muslo", + "nácar", + "nación", + "nadar", + "naipe", + "naranja", + "nariz", + "narrar", + "nasal", + "natal", + "nativo", + "natural", + "náusea", + "naval", + "nave", + "navidad", + "necio", + "néctar", + "negar", + "negocio", + "negro", + "neón", + "nervio", + "neto", + "neutro", + "nevar", + "nevera", + "nicho", + "nido", + "niebla", + "nieto", + "niñez", + "niño", + "nítido", + "nivel", + "nobleza", + "noche", + "nómina", + "noria", + "norma", + "norte", + "nota", + "noticia", + "novato", + "novela", + "novio", + "nube", + "nuca", + "núcleo", + "nudillo", + "nudo", + "nuera", + "nueve", + "nuez", + "nulo", + "número", + "nutria", + "oasis", + "obeso", + "obispo", + "objeto", + "obra", + "obrero", + "observar", + "obtener", + "obvio", + "oca", + "ocaso", + "océano", + "ochenta", + "ocho", + "ocio", + "ocre", + "octavo", + "octubre", + "oculto", + "ocupar", + "ocurrir", + "odiar", + "odio", + "odisea", + "oeste", + "ofensa", + "oferta", + "oficio", + "ofrecer", + "ogro", + "oído", + "oír", + "ojo", + "ola", + "oleada", + "olfato", + "olivo", + "olla", + "olmo", + "olor", + "olvido", + "ombligo", + "onda", + "onza", + "opaco", + "opción", + "ópera", + "opinar", + "oponer", + "optar", + "óptica", + "opuesto", + "oración", + "orador", + "oral", + "órbita", + "orca", + "orden", + "oreja", + "órgano", + "orgía", + "orgullo", + "oriente", + "origen", + "orilla", + "oro", + "orquesta", + "oruga", + "osadía", + "oscuro", + "osezno", + "oso", + "ostra", + "otoño", + "otro", + "oveja", + "óvulo", + "óxido", + "oxígeno", + "oyente", + "ozono", + "pacto", + "padre", + "paella", + "página", + "pago", + "país", + "pájaro", + "palabra", + "palco", + "paleta", + "pálido", + "palma", + "paloma", + "palpar", + "pan", + "panal", + "pánico", + "pantera", + "pañuelo", + "papá", + "papel", + "papilla", + "paquete", + "parar", + "parcela", + "pared", + "parir", + "paro", + "párpado", + "parque", + "párrafo", + "parte", + "pasar", + "paseo", + "pasión", + "paso", + "pasta", + "pata", + "patio", + "patria", + "pausa", + "pauta", + "pavo", + "payaso", + "peatón", + "pecado", + "pecera", + "pecho", + "pedal", + "pedir", + "pegar", + "peine", + "pelar", + "peldaño", + "pelea", + "peligro", + "pellejo", + "pelo", + "peluca", + "pena", + "pensar", + "peñón", + "peón", + "peor", + "pepino", + "pequeño", + "pera", + "percha", + "perder", + "pereza", + "perfil", + "perico", + "perla", + "permiso", + "perro", + "persona", + "pesa", + "pesca", + "pésimo", + "pestaña", + "pétalo", + "petróleo", + "pez", + "pezuña", + "picar", + "pichón", + "pie", + "piedra", + "pierna", + "pieza", + "pijama", + "pilar", + "piloto", + "pimienta", + "pino", + "pintor", + "pinza", + "piña", + "piojo", + "pipa", + "pirata", + "pisar", + "piscina", + "piso", + "pista", + "pitón", + "pizca", + "placa", + "plan", + "plata", + "playa", + "plaza", + "pleito", + "pleno", + "plomo", + "pluma", + "plural", + "pobre", + "poco", + "poder", + "podio", + "poema", + "poesía", + "poeta", + "polen", + "policía", + "pollo", + "polvo", + "pomada", + "pomelo", + "pomo", + "pompa", + "poner", + "porción", + "portal", + "posada", + "poseer", + "posible", + "poste", + "potencia", + "potro", + "pozo", + "prado", + "precoz", + "pregunta", + "premio", + "prensa", + "preso", + "previo", + "primo", + "príncipe", + "prisión", + "privar", + "proa", + "probar", + "proceso", + "producto", + "proeza", + "profesor", + "programa", + "prole", + "promesa", + "pronto", + "propio", + "próximo", + "prueba", + "público", + "puchero", + "pudor", + "pueblo", + "puerta", + "puesto", + "pulga", + "pulir", + "pulmón", + "pulpo", + "pulso", + "puma", + "punto", + "puñal", + "puño", + "pupa", + "pupila", + "puré", + "quedar", + "queja", + "quemar", + "querer", + "queso", + "quieto", + "química", + "quince", + "quitar", + "rábano", + "rabia", + "rabo", + "ración", + "radical", + "raíz", + "rama", + "rampa", + "rancho", + "rango", + "rapaz", + "rápido", + "rapto", + "rasgo", + "raspa", + "rato", + "rayo", + "raza", + "razón", + "reacción", + "realidad", + "rebaño", + "rebote", + "recaer", + "receta", + "rechazo", + "recoger", + "recreo", + "recto", + "recurso", + "red", + "redondo", + "reducir", + "reflejo", + "reforma", + "refrán", + "refugio", + "regalo", + "regir", + "regla", + "regreso", + "rehén", + "reino", + "reír", + "reja", + "relato", + "relevo", + "relieve", + "relleno", + "reloj", + "remar", + "remedio", + "remo", + "rencor", + "rendir", + "renta", + "reparto", + "repetir", + "reposo", + "reptil", + "res", + "rescate", + "resina", + "respeto", + "resto", + "resumen", + "retiro", + "retorno", + "retrato", + "reunir", + "revés", + "revista", + "rey", + "rezar", + "rico", + "riego", + "rienda", + "riesgo", + "rifa", + "rígido", + "rigor", + "rincón", + "riñón", + "río", + "riqueza", + "risa", + "ritmo", + "rito" + }; + set_words(words); + populate_maps(ALLOW_SHORT_WORDS); + } + }; +} + +#endif diff --git a/src/multisig/CMakeLists.txt b/src/multisig/CMakeLists.txt index 9ddd4664e..34434eb24 100644 --- a/src/multisig/CMakeLists.txt +++ b/src/multisig/CMakeLists.txt @@ -35,4 +35,5 @@ target_link_libraries(multisig ringct cryptonote_basic common + logging extra) diff --git a/src/multisig/multisig.cpp b/src/multisig/multisig.cpp index 6514a8d19..d6b786f34 100644 --- a/src/multisig/multisig.cpp +++ b/src/multisig/multisig.cpp @@ -35,13 +35,13 @@ #include "multisig.h" #include "cryptonote_config.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "multisig" - using namespace std; namespace cryptonote { + + static auto logcat = oxen::log::Cat("multisig"); + //----------------------------------------------------------------- crypto::secret_key get_multisig_blinded_secret_key(const crypto::secret_key &key) { diff --git a/src/net/CMakeLists.txt b/src/net/CMakeLists.txt index eb665ba82..3f6358535 100644 --- a/src/net/CMakeLists.txt +++ b/src/net/CMakeLists.txt @@ -39,4 +39,5 @@ target_link_libraries(net PRIVATE common epee extra + logging ) diff --git a/src/net/epee_network_address_hack.cpp b/src/net/epee_network_address_hack.cpp index 564dc088e..0d7879d93 100644 --- a/src/net/epee_network_address_hack.cpp +++ b/src/net/epee_network_address_hack.cpp @@ -1,4 +1,5 @@ #include "epee/net/net_utils_base.h" +#include "logging/oxen_logger.h" #include "epee/storages/portable_storage.h" #include "tor_address.h" #include "i2p_address.h" @@ -12,6 +13,8 @@ namespace epee { namespace net_utils { +static auto logcat = oxen::log::Cat("global"); + KV_SERIALIZE_MAP_CODE_BEGIN(network_address) std::uint8_t type = static_cast(is_store ? this_ref.get_type_id() : address_type::invalid); if (!epee::serialization::perform_serialize(type, stg, parent_section, "type")) @@ -28,7 +31,7 @@ KV_SERIALIZE_MAP_CODE_BEGIN(network_address) case address_type::i2p: return this_ref.template serialize_addr(stg, parent_section); default: - MERROR("Unsupported network address type: " << (unsigned)type); + oxen::log::error(logcat, "Unsupported network address type: {}", (unsigned)type); return false; } KV_SERIALIZE_MAP_CODE_END() diff --git a/src/p2p/CMakeLists.txt b/src/p2p/CMakeLists.txt index 6720cf7a7..d17143d47 100644 --- a/src/p2p/CMakeLists.txt +++ b/src/p2p/CMakeLists.txt @@ -44,4 +44,5 @@ target_link_libraries(p2p filesystem Boost::serialization SQLiteCpp + logging extra) diff --git a/src/p2p/net_node.cpp b/src/p2p/net_node.cpp index 37b2fbff7..b744523e4 100644 --- a/src/p2p/net_node.cpp +++ b/src/p2p/net_node.cpp @@ -71,9 +71,7 @@ namespace expect address = T::make(value); if (!address) { - MERROR( - "Failed to parse " << T::get_zone() << " address \"" << value << "\": " << address.error().message() - ); + oxen::log::error("Failed to parse " << T::get_zone() << " address \"" << value << "\": " << address.error().message()); return {}; } return {std::move(*address)}; @@ -93,7 +91,7 @@ namespace set = client->set_connect_command(remote.as()); break; default: - MERROR("Unsupported network address in socks_connect"); + oxen::log::error(globallogcat, "Unsupported network address in socks_connect"); return false; } @@ -189,14 +187,14 @@ namespace nodetool set_proxy.max_connections = get_max_connections(*it); if (set_proxy.max_connections == 0) { - MERROR("Invalid max connections given to --" << arg_tx_proxy.name); + oxen::log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); return std::nullopt; } ++it; } if (it != pieces.end()) { - MERROR("Too many ',' characters given to --" << arg_tx_proxy.name); + oxen::log::error(globallogcat, "Too many ',' characters given to --{}", arg_tx_proxy.name); return std::nullopt; } @@ -209,7 +207,7 @@ namespace nodetool set_proxy.zone = epee::net_utils::zone::i2p; break; default: - MERROR("Invalid network for --" << arg_tx_proxy.name); + oxen::log::error(globallogcat, "Invalid network for --{}", arg_tx_proxy.name); return std::nullopt; } @@ -217,7 +215,7 @@ namespace nodetool std::uint16_t port = 0; if (!epee::string_tools::parse_peer_from_string(ip, port, proxy) || port == 0) { - MERROR("Invalid ipv4:port given for --" << arg_tx_proxy.name); + oxen::log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_tx_proxy.name); return std::nullopt; } set_proxy.address = ip::tcp::endpoint{ip::address_v4{oxenc::host_to_big(ip)}, port}; @@ -251,7 +249,7 @@ namespace nodetool set_inbound.max_connections = get_max_connections(pieces[2]); if (set_inbound.max_connections == 0) { - MERROR("Invalid max connections given to --" << arg_tx_proxy.name); + oxen::log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); return std::nullopt; } } @@ -268,7 +266,7 @@ namespace nodetool set_inbound.default_remote = net::i2p_address::unknown(); break; default: - MERROR("Invalid inbound address (" << address << ") for --" << arg_anonymous_inbound.name << ": " << (our_address ? "invalid type" : our_address.error().message())); + oxen::log::error(globallogcat, "Invalid inbound address ({}) for --{}: {}", address, arg_anonymous_inbound.name, (our_address ? "invalid type" : our_address.error().message())); return std::nullopt; } @@ -280,7 +278,7 @@ namespace nodetool std::uint16_t port = 0; if (!epee::string_tools::parse_peer_from_string(ip, port, bind)) { - MERROR("Invalid ipv4:port given for --" << arg_anonymous_inbound.name); + oxen::log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_anonymous_inbound.name); return std::nullopt; } set_inbound.local_ip = bind.substr(0, colon); @@ -305,7 +303,7 @@ namespace nodetool if (address.get_zone() == epee::net_utils::zone::public_) return false; - MWARNING("Filtered command (#" << command << ") to/from " << address.str()); + oxen::log::warning(globallogcat, "Filtered command (#{}) to/from {}", command, address.str()); return true; } @@ -342,7 +340,7 @@ namespace nodetool { if (socks_connect_timeout < std::chrono::steady_clock::now() - start) { - MERROR("Timeout on socks connect (" << proxy << " to " << remote.str() << ")"); + oxen::log::error(globallogcat, "Timeout on socks connect ({} to {})", proxy.address().to_string(), remote.str()); return std::nullopt; } @@ -356,7 +354,7 @@ namespace nodetool if (!result.first) return {std::move(result.second)}; - MERROR("Failed to make socks connection to " << remote.str() << " (via " << proxy << "): " << result.first.message()); + oxen::log::error(globallogcat, "Failed to make socks connection to {} (via {}): {}", remote.str(), proxy.address().to_string(), result.first.message()); } catch (const std::future_error&) {} diff --git a/src/p2p/net_node.h b/src/p2p/net_node.h index ed46b6b28..26b34a27e 100644 --- a/src/p2p/net_node.h +++ b/src/p2p/net_node.h @@ -40,9 +40,11 @@ #include #include #include +#include #include "cryptonote_config.h" #include "cryptonote_protocol/levin_notify.h" +#include "cryptonote_basic/connection_context.h" #include "epee/warnings.h" #include "epee/net/abstract_tcp_server2.h" #include "epee/net/levin_protocol_handler.h" @@ -367,11 +369,11 @@ namespace nodetool bool check_incoming_connections(); void kill() { ///< will be called e.g. from deinit() - MINFO("Killing the net_node"); + oxen::log::info(globallogcat, "Killing the net_node"); is_closing = true; if(mPeersLoggerThread) mPeersLoggerThread->join(); // make sure the thread finishes - MINFO("Joined extra background net_node threads"); + oxen::log::info(globallogcat, "Joined extra background net_node threads"); } //debug functions diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index cd21c7d11..77644ab19 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -40,6 +40,8 @@ #include #include #include +#include +#include #include "cryptonote_config.h" #include "version.h" @@ -56,11 +58,8 @@ #include "epee/storages/levin_abstract_invoke2.h" #include "cryptonote_core/cryptonote_core.h" #include "net/parse.h" - #include - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "net.p2p" +#include "net_node.h" #define NET_MAKE_IP(b1,b2,b3,b4) ((LPARAM)(((DWORD)(b1)<<24)+((DWORD)(b2)<<16)+((DWORD)(b3)<<8)+((DWORD)(b4)))) @@ -68,6 +67,8 @@ namespace nodetool { + static auto logcat = oxen::log::Cat("net.p2p"); + template node_server::~node_server() { @@ -166,7 +167,7 @@ namespace nodetool if (now >= it->second) { m_blocked_hosts.erase(it); - MCLOG_CYAN(el::Level::Info, "global", "Host " << address.host_str() << " unblocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked.", address.host_str())); it = m_blocked_hosts.end(); } else @@ -187,7 +188,7 @@ namespace nodetool if (now >= it->second) { it = m_blocked_subnets.erase(it); - MCLOG_CYAN(el::Level::Info, "global", "Subnet " << it->first.host_str() << " unblocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} unblocked", it->first.host_str())); continue; } if (it->first.matches(ipv4_address)) @@ -240,7 +241,7 @@ namespace nodetool conns.clear(); } - MCLOG_CYAN(el::Level::Info, "global", "Host " << addr.host_str() << " blocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} blocked", addr.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -252,7 +253,7 @@ namespace nodetool if (i == m_blocked_hosts.end()) return false; m_blocked_hosts.erase(i); - MCLOG_CYAN(el::Level::Info, "global", "Host " << address.host_str() << " unblocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked", address.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -292,7 +293,7 @@ namespace nodetool conns.clear(); } - MCLOG_CYAN(el::Level::Info, "global", "Subnet " << subnet.host_str() << " blocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} blocked.", subnet.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -304,7 +305,7 @@ namespace nodetool if (i == m_blocked_subnets.end()) return false; m_blocked_subnets.erase(i); - MCLOG_CYAN(el::Level::Info, "global", "Subnet " << subnet.host_str() << " unblocked."); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {}", subnet.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -316,7 +317,7 @@ namespace nodetool std::lock_guard lock{m_host_fails_score_lock}; uint64_t fails = ++m_host_fails_score[address.host_str()]; - MDEBUG("Host " << address.host_str() << " fail score=" << fails); + oxen::log::debug(logcat, "Host {} fail score={}", address.host_str(), fails); if(fails > cryptonote::p2p::IP_FAILS_BEFORE_BLOCK) { auto it = m_host_fails_score.find(address.host_str()); @@ -447,7 +448,7 @@ namespace nodetool network_zone& zone = add_zone(proxy.zone); if (zone.m_connect != nullptr) { - MERROR("Listed --" << arg_tx_proxy.name << " twice with " << proxy.zone); + oxen::log::error(logcat, "Listed --{} twice", arg_tx_proxy.name); return false; } zone.m_connect = &socks_connect; @@ -475,7 +476,7 @@ namespace nodetool { if (zone.second.m_connect == nullptr) { - MERROR("Set outgoing peer for " << zone.first << " but did not set --" << arg_tx_proxy.name); + oxen::log::error(logcat, "Set outgoing peer for zone but did not set --{}", arg_tx_proxy.name); return false; } } @@ -491,13 +492,13 @@ namespace nodetool if (!zone.m_bind_ip.empty()) { - MERROR("Listed --" << arg_anonymous_inbound.name << " twice with " << inbound.our_address.get_zone() << " network"); + oxen::log::error(logcat, "Listed--{} twice", arg_anonymous_inbound.name); return false; } if (zone.m_connect == nullptr && tx_relay_zones <= 1) { - MERROR("Listed --" << arg_anonymous_inbound.name << " without listing any --" << arg_tx_proxy.name << ". The latter is necessary for sending local txes over anonymity networks"); + oxen::log::error(logcat, "Listed --{} without listing any --{}. The latter is necessary for sending local txes over anonymity networks", arg_anonymous_inbound.name, arg_tx_proxy.name); return false; } @@ -540,7 +541,7 @@ namespace nodetool port = std::to_string(default_port); } - MINFO("Resolving node address: host=" << host << ", port=" << port); + oxen::log::info(logcat, "Resolving node address: host={}, port={}", host, port); io_service io_srv; ip::tcp::resolver resolver(io_srv); @@ -557,13 +558,13 @@ namespace nodetool { epee::net_utils::network_address na{epee::net_utils::ipv4_network_address{boost::asio::detail::socket_ops::host_to_network_long(endpoint.address().to_v4().to_ulong()), endpoint.port()}}; seed_nodes.push_back(na); - MINFO("Added node: " << na.str()); + oxen::log::info(logcat, "Added node: {}", na.str()); } else { epee::net_utils::network_address na{epee::net_utils::ipv6_network_address{endpoint.address().to_v6(), endpoint.port()}}; seed_nodes.push_back(na); - MINFO("Added node: " << na.str()); + oxen::log::info(logcat, "Added node: {}", na.str()); } } return true; @@ -699,27 +700,32 @@ namespace nodetool std::string ipv6_addr = ""; std::string ipv6_port = ""; zone.second.m_net_server.set_connection_filter(this); - MINFO("Binding (IPv4) on " << zone.second.m_bind_ip << ":" << zone.second.m_port); + oxen::log::info(logcat, "Binding (IPv4) on {}:{}", zone.second.m_bind_ip, zone.second.m_port); if (!zone.second.m_bind_ipv6_address.empty() && m_use_ipv6) { ipv6_addr = zone.second.m_bind_ipv6_address; ipv6_port = zone.second.m_port_ipv6; - MINFO("Binding (IPv6) on " << zone.second.m_bind_ipv6_address << ":" << zone.second.m_port_ipv6); + oxen::log::info(logcat, "Binding (IPv6) on {}:{}", zone.second.m_bind_ipv6_address, zone.second.m_port_ipv6); + } + try { + res = zone.second.m_net_server.init_server(zone.second.m_port, zone.second.m_bind_ip, ipv6_port, ipv6_addr, m_use_ipv6, m_require_ipv4); + CHECK_AND_ASSERT_MES(res, false, "Failed to bind server"); + } catch (const std::exception& e) { + oxen::log::error(logcat, "{}", e.what()); + res = false; } - res = zone.second.m_net_server.init_server(zone.second.m_port, zone.second.m_bind_ip, ipv6_port, ipv6_addr, m_use_ipv6, m_require_ipv4); - CHECK_AND_ASSERT_MES(res, false, "Failed to bind server"); } } m_listening_port = public_zone.m_net_server.get_binded_port(); - MLOG_GREEN(el::Level::Info, "Net service bound (IPv4) to " << public_zone.m_bind_ip << ":" << m_listening_port); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv4) to {}:{}", public_zone.m_bind_ip, m_listening_port)); if (m_use_ipv6) { m_listening_port_ipv6 = public_zone.m_net_server.get_binded_port_ipv6(); - MLOG_GREEN(el::Level::Info, "Net service bound (IPv6) to " << public_zone.m_bind_ipv6_address << ":" << m_listening_port_ipv6); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv6) to {}:{}", public_zone.m_bind_ipv6_address, m_listening_port_ipv6)); } if(m_external_port) - MDEBUG("External port defined as " << m_external_port); + oxen::log::debug(logcat, "External port defined as {}", m_external_port); return res; } @@ -736,7 +742,7 @@ namespace nodetool // creating thread to log number of connections mPeersLoggerThread.emplace([&]() { - MDEBUG("Thread monitor number of peers - start"); + oxen::log::debug(logcat, "Thread monitor number of peers - start"); const network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_); while (!is_closing && !public_zone.m_net_server.is_stop_signal_sent()) { // main loop of thread @@ -765,7 +771,7 @@ namespace nodetool } std::this_thread::sleep_for(1s); } // main loop of thread - MDEBUG("Thread monitor number of peers - done"); + oxen::log::debug(logcat, "Thread monitor number of peers - done"); }); // lambda network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_); @@ -775,13 +781,13 @@ namespace nodetool //here you can set worker threads count int thrds_count = 10; //go to loop - MINFO("Run net_service loop( " << thrds_count << " threads)..."); + oxen::log::info(logcat, "Run net_service loop( {} threads)...", thrds_count); if(!public_zone.m_net_server.run_server(thrds_count, true)) { - LOG_ERROR("Failed to run net tcp server!"); + oxen::log::error(logcat, "Failed to run net tcp server!"); } - MINFO("net_service loop stopped."); + oxen::log::info(logcat, "net_service loop stopped."); return true; } //----------------------------------------------------------------------------------- @@ -815,7 +821,7 @@ namespace nodetool std::error_code ec; if (fs::create_directories(m_config_folder); ec) { - MWARNING("Failed to create data directory " << m_config_folder); + oxen::log::warning(logcat, "Failed to create data directory {}", m_config_folder); return false; } @@ -826,7 +832,7 @@ namespace nodetool const auto state_file_path = m_config_folder / cryptonote::P2P_NET_DATA_FILENAME; if (!m_peerlist_storage.store(state_file_path, active)) { - MWARNING("Failed to save config to file " << state_file_path); + oxen::log::warning(logcat, "Failed to save config to file {}", state_file_path); return false; } CATCH_ENTRY_L0("node_server::store", false); @@ -836,10 +842,10 @@ namespace nodetool template bool node_server::send_stop_signal() { - MDEBUG("[node] sending stop signal"); + oxen::log::debug(logcat, "[node] sending stop signal"); for (auto& zone : m_network_zones) zone.second.m_net_server.send_stop_signal(); - MDEBUG("[node] Stop signal sent"); + oxen::log::debug(logcat, "[node] Stop signal sent"); for (auto& zone : m_network_zones) { @@ -879,7 +885,7 @@ namespace nodetool if(code < 0) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE invoke failed. (" << code << ", " << epee::levin::get_err_descr(code) << ")"); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE invoke failed. ({},{})", context, code, epee::levin::get_err_descr(code)); if (code == LEVIN_ERROR_CONNECTION_TIMEDOUT || code == LEVIN_ERROR_CONNECTION_DESTROYED) timeout = true; return; @@ -887,13 +893,13 @@ namespace nodetool if(rsp.node_data.network_id != m_network_id) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE Failed, wrong network! (" << rsp.node_data.network_id << "), closing connection."); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE Failed, wrong network! ({}), closing connection.", context, boost::lexical_cast(rsp.node_data.network_id)); return; } if(!handle_remote_peerlist(rsp.local_peerlist_new, context)) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE: failed to handle_remote_peerlist(...), closing connection."); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE: failed to handle_remote_peerlist(...), closing connection.", context); add_host_fail(context.m_remote_address); return; } @@ -902,7 +908,7 @@ namespace nodetool { if(!m_payload_handler.process_payload_sync_data(std::move(rsp.payload_data), context, true)) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE invoked, but process_payload_sync_data returned false, dropping connection."); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE invoked, but process_payload_sync_data returned false, dropping connection.", context); hsh_result = false; return; } @@ -914,15 +920,15 @@ namespace nodetool // move if(rsp.node_data.peer_id == zone.m_config.m_peer_id) { - LOG_DEBUG_CC(context, "Connection to self detected, dropping connection"); + oxen::log::debug(logcat, "{}Connection to self detected, dropping connection", context); hsh_result = false; return; } - LOG_INFO_CC(context, "New connection handshaked, pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed)); - LOG_DEBUG_CC(context, " COMMAND_HANDSHAKE INVOKED OK"); + oxen::log::info(logcat, "{}New connection handshaked, pruning seed {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed)); + oxen::log::debug(logcat, "{} COMMAND_HANDSHAKE INVOKED OK", context); }else { - LOG_DEBUG_CC(context, " COMMAND_HANDSHAKE(AND CLOSE) INVOKED OK"); + oxen::log::debug(logcat, "{} COMMAND_HANDSHAKE(AND CLOSE) INVOKED OK", context); } context_ = context; }, std::chrono::milliseconds{cryptonote::p2p::DEFAULT_HANDSHAKE_INVOKE_TIMEOUT}); @@ -934,7 +940,7 @@ namespace nodetool if(!hsh_result) { - LOG_WARNING_CC(context_, "COMMAND_HANDSHAKE Failed"); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE Failed", context_); if (!timeout) zone.m_net_server.get_config_object().close(context_.m_connection_id); } @@ -957,13 +963,13 @@ namespace nodetool context.m_in_timedsync = false; if(code < 0) { - LOG_WARNING_CC(context, "COMMAND_TIMED_SYNC invoke failed. (" << code << ", " << epee::levin::get_err_descr(code) << ")"); + oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC invoke failed. ({}, {})", context, code, epee::levin::get_err_descr(code)); return; } if(!handle_remote_peerlist(rsp.local_peerlist_new, context)) { - LOG_WARNING_CC(context, "COMMAND_TIMED_SYNC: failed to handle_remote_peerlist(...), closing connection."); + oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC: failed to handle_remote_peerlist(...), closing connection.", context); m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().close(context.m_connection_id ); add_host_fail(context.m_remote_address); } @@ -977,7 +983,7 @@ namespace nodetool if(!r) { - LOG_WARNING_CC(context_, "COMMAND_TIMED_SYNC Failed"); + oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC Failed", context_); return false; } return true; @@ -992,7 +998,7 @@ namespace nodetool size_t x = crypto::rand()%(max_index+1); size_t res = (x*x*x)/(max_index*max_index); //parabola \/ - MDEBUG("Random connection index=" << res << "(x="<< x << ", max_index=" << max_index << ")"); + oxen::log::debug(logcat, "Random connection index={}(x={}, max_index={})", res, x, max_index); return res; } //----------------------------------------------------------------------------------- @@ -1066,15 +1072,6 @@ namespace nodetool return connected; } -#define LOG_PRINT_CC_PRIORITY_NODE(priority, con, msg) \ - do { \ - if (priority) {\ - LOG_INFO_CC(con, "[priority]" << msg); \ - } else {\ - LOG_INFO_CC(con, msg); \ - } \ - } while(0) - template bool node_server::try_to_connect_and_handshake_with_new_peer(const epee::net_utils::network_address& na, bool just_take_peerlist, uint64_t last_seen_stamp, PeerType peer_type, uint64_t first_seen_stamp) { @@ -1094,16 +1091,15 @@ namespace nodetool } - MDEBUG("Connecting to " << na.str() << "(peer_type=" << peer_type << ", last_seen: " - << (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never") - << ")..."); + oxen::log::debug(logcat, "Connecting to {}(peer_type={}, last_seen: {})...", na.str(), peer_type, (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); auto con = zone.m_connect(zone, na); if(!con) { - bool is_priority = is_priority_node(na); - LOG_PRINT_CC_PRIORITY_NODE(is_priority, bool(con), "Connect failed to " << na.str() - /*<< ", try " << try_count*/); + if (is_priority_node(na)) + oxen::log::info(logcat, "{}[priority] Connect failed to {}", bool(con), na.str()); + else + oxen::log::info(logcat, "{} Connect failed to {}", bool(con), na.str()); record_addr_failed(na); return false; } @@ -1115,9 +1111,10 @@ namespace nodetool if(!res) { bool is_priority = is_priority_node(na); - LOG_PRINT_CC_PRIORITY_NODE(is_priority, *con, "Failed to HANDSHAKE with peer " - << na.str() - /*<< ", try " << try_count*/); + if (is_priority_node(na)) + oxen::log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); + else + oxen::log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); record_addr_failed(na); return false; } @@ -1125,7 +1122,7 @@ namespace nodetool if(just_take_peerlist) { zone.m_net_server.get_config_object().close(con->m_connection_id); - LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK AND CLOSED."); + oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); return true; } @@ -1147,7 +1144,7 @@ namespace nodetool zone.m_peerlist.append_with_peer_anchor(ape); zone.m_notifier.new_out_connection(); - LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK."); + oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK.", *con ); return true; } @@ -1158,15 +1155,14 @@ namespace nodetool if (zone.m_connect == nullptr) return false; - LOG_PRINT_L1("Connecting to " << na.str() << "(last_seen: " - << (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never") - << ")..."); + oxen::log::info(logcat, "Connecting to {}(last_seen: {})...", na.str(), (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); auto con = zone.m_connect(zone, na); if (!con) { - bool is_priority = is_priority_node(na); - - LOG_PRINT_CC_PRIORITY_NODE(is_priority, p2p_connection_context{}, "Connect failed to " << na.str()); + if (is_priority_node(na)) + oxen::log::info(logcat, "{}[priority]Connect failed to {}", p2p_connection_context{}, na.str()); + else + oxen::log::info(logcat, "{}Connect failed to {}", p2p_connection_context{}, na.str()); record_addr_failed(na); return false; @@ -1176,22 +1172,21 @@ namespace nodetool peerid_type pi{}; const bool res = do_handshake_with_peer(pi, *con, true); if (!res) { - bool is_priority = is_priority_node(na); - - LOG_PRINT_CC_PRIORITY_NODE(is_priority, *con, "Failed to HANDSHAKE with peer " << na.str()); + if (is_priority_node(na)) + oxen::log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); + else + oxen::log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); record_addr_failed(na); return false; } zone.m_net_server.get_config_object().close(con->m_connection_id); - LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK AND CLOSED."); + oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); return true; } -#undef LOG_PRINT_CC_PRIORITY_NODE - //----------------------------------------------------------------------------------- template void node_server::record_addr_failed(const epee::net_utils::network_address& addr) @@ -1222,10 +1217,10 @@ namespace nodetool bool node_server::make_new_connection_from_anchor_peerlist(const std::vector& anchor_peerlist) { for (const auto& pe: anchor_peerlist) { - MDEBUG("Considering connecting (out) to anchor peer: " << peerid_to_string(pe.id) << " " << pe.adr.str()); + oxen::log::debug(logcat, "Considering connecting (out) to anchor peer: {} {}", peerid_to_string(pe.id), pe.adr.str()); if(is_peer_used(pe)) { - MDEBUG("Peer is used"); + oxen::log::debug(logcat, "Peer is used"); continue; } @@ -1237,12 +1232,10 @@ namespace nodetool continue; } - MDEBUG("Selected peer: " << peerid_to_string(pe.id) << " " << pe.adr.str() - << "[peer_type=" << anchor - << "] first_seen: " << epee::misc_utils::get_time_interval_string(time(NULL) - pe.first_seen)); + oxen::log::debug(logcat, "Selected peer: {} {} first_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::misc_utils::get_time_interval_string(time(NULL) - pe.first_seen)); if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, 0, anchor, pe.first_seen)) { - MDEBUG("Handshake failed"); + oxen::log::debug(logcat, "Handshake failed"); continue; } @@ -1312,11 +1305,11 @@ namespace nodetool if (skipped == 0 || !filtered.empty()) break; if (skipped) - MINFO("Skipping " << skipped << " possible peers as they share a class B with existing peers"); + oxen::log::info(logcat, "Skipping {} possible peers as they share a class B with existing peers", skipped); } if (filtered.empty()) { - MDEBUG("No available peer in " << (use_white_list ? "white" : "gray") << " list filtered by " << next_needed_pruning_stripe); + oxen::log::debug(logcat, "No available peer in {} list filtered by {}", (use_white_list ? "white" : "gray"), next_needed_pruning_stripe); return false; } if (use_white_list) @@ -1333,7 +1326,7 @@ namespace nodetool peerlist_entry pe; if (zone.m_peerlist.get_white_peer_by_index(pe, filtered[i]) && pe.adr == na) { - MDEBUG("Reusing stripe " << next_needed_pruning_stripe << " peer " << pe.adr.str()); + oxen::log::debug(logcat, "Reusing stripe {} peer {}", next_needed_pruning_stripe, pe.adr.str()); random_index = i; break; } @@ -1358,12 +1351,10 @@ namespace nodetool ++try_count; - MDEBUG("Considering connecting (out) to " << (use_white_list ? "white" : "gray") << " list peer: " << - peerid_to_string(pe.id) << " " << pe.adr.str() << ", pruning seed " << epee::string_tools::to_string_hex(pe.pruning_seed) << - " (stripe " << next_needed_pruning_stripe << " needed)"); + oxen::log::debug(logcat, "Considering connecting (out) to {} list peer: {} {}, pruning seed {} (stripe {} needed)", (use_white_list ? "white" : "gray"), peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), next_needed_pruning_stripe); if(is_peer_used(pe)) { - MDEBUG("Peer is used"); + oxen::log::debug(logcat, "Peer is used"); continue; } @@ -1373,13 +1364,10 @@ namespace nodetool if(is_addr_recently_failed(pe.adr)) continue; - MDEBUG("Selected peer: " << peerid_to_string(pe.id) << " " << pe.adr.str() - << ", pruning seed " << epee::string_tools::to_string_hex(pe.pruning_seed) << " " - << "[peer_list=" << (use_white_list ? white : gray) - << "] last_seen: " << (pe.last_seen ? epee::misc_utils::get_time_interval_string(time(NULL) - pe.last_seen) : "never")); + oxen::log::debug(logcat, "Selected peer: {} {}, pruning seed {} [peer_list={}] last_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), (use_white_list ? white : gray), (pe.last_seen ? epee::misc_utils::get_time_interval_string(time(NULL) - pe.last_seen) : "never")); if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, pe.last_seen, use_white_list ? white : gray)) { - MDEBUG("Handshake failed"); + oxen::log::debug(logcat, "Handshake failed"); continue; } @@ -1398,10 +1386,10 @@ namespace nodetool { for (const auto& full_addr : get_seed_nodes()) { - MDEBUG("Seed node: " << full_addr); + oxen::log::debug(logcat, "Seed node: {}", full_addr); append_net_address(m_seed_nodes, full_addr, cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT); } - MDEBUG("Number of seed nodes: " << m_seed_nodes.size()); + oxen::log::debug(logcat, "Number of seed nodes: {}", m_seed_nodes.size()); m_seed_nodes_initialized = true; } } @@ -1430,7 +1418,7 @@ namespace nodetool { if (!m_fallback_seed_nodes_added.test_and_set()) { - MWARNING("Failed to connect to any of seed peers, trying fallback seeds"); + oxen::log::warning(logcat, "Failed to connect to any of seed peers, trying fallback seeds"); current_index = m_seed_nodes.size() - 1; { shlock.unlock(); @@ -1438,7 +1426,7 @@ namespace nodetool std::unique_lock lock{m_seed_nodes_mutex}; for (const auto &peer: get_seed_nodes(m_nettype)) { - MDEBUG("Fallback seed node: " << peer); + oxen::log::debug(logcat, "Fallback seed node: {}", peer); append_net_address(m_seed_nodes, peer, cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT); } } @@ -1446,7 +1434,7 @@ namespace nodetool } if (current_index == m_seed_nodes.size() - 1) { - MWARNING("No fallback seeds, continuing without seeds"); + oxen::log::warning(logcat, "No fallback seeds, continuing without seeds"); break; } // continue for another few cycles @@ -1454,7 +1442,7 @@ namespace nodetool else { if (!is_connected_to_at_least_one_seed_node) - MWARNING("Failed to connect to any of seed peers, continuing without seeds"); + oxen::log::warning(logcat, "Failed to connect to any of seed peers, continuing without seeds"); break; } } @@ -1528,7 +1516,7 @@ namespace nodetool if (start_conn_count == get_public_outgoing_connections_count() && start_conn_count < m_network_zones.at(zone_type::public_).m_config.m_net_config.max_out_connection_count) { - MINFO("Failed to connect to any, trying seeds"); + oxen::log::info(logcat, "Failed to connect to any, trying seeds"); if (!connect_to_seed()) return false; } @@ -1555,7 +1543,7 @@ namespace nodetool if(zone.m_net_server.is_stop_signal_sent()) return false; - MDEBUG("Making expected connection, type " << peer_type << ", " << conn_count << "/" << expected_connections << " connections"); + oxen::log::debug(logcat, "Making expected connection, type {}, {}/{} connections", peer_type, conn_count, expected_connections); if (peer_type == anchor && !make_new_connection_from_anchor_peerlist(apl)) { return false; @@ -1689,12 +1677,11 @@ namespace nodetool { if (m_hide_my_port || public_zone->second.m_config.m_net_config.max_in_connection_count == 0) { - MGINFO("Incoming connections disabled, enable them for full connectivity"); + oxen::log::info(logcat, "Incoming connections disabled, enable them for full connectivity"); } else { - const el::Level level = el::Level::Warning; - MCLOG_RED(level, "global", "No incoming connections - check firewalls/routers allow port " << get_this_peer_port()); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "No incoming connections - check firewalls/routers allow port {}", get_this_peer_port())); } } return true; @@ -1708,7 +1695,7 @@ namespace nodetool // This really should be spaced out, i.e. the 60s sync timing should apply per peer, not // globally. - MDEBUG("STARTED PEERLIST IDLE HANDSHAKE"); + oxen::log::debug(logcat, "STARTED PEERLIST IDLE HANDSHAKE"); typedef std::list > local_connects_type; local_connects_type cncts; for(auto& zone : m_network_zones) @@ -1726,7 +1713,7 @@ namespace nodetool std::for_each(cncts.begin(), cncts.end(), [&](const auto& vl){ do_peer_timed_sync(vl.first, vl.second); }); - MDEBUG("FINISHED PEERLIST IDLE HANDSHAKE"); + oxen::log::debug(logcat, "FINISHED PEERLIST IDLE HANDSHAKE"); return true; } //----------------------------------------------------------------------------------- @@ -1752,7 +1739,7 @@ namespace nodetool ignore = true; if (ignore) { - MDEBUG("Ignoring " << be.adr.str()); + oxen::log::debug(logcat, "Ignoring {}", be.adr.str()); std::swap(local_peerlist[i], local_peerlist[local_peerlist.size() - 1]); local_peerlist.resize(local_peerlist.size() - 1); --i; @@ -1778,13 +1765,13 @@ namespace nodetool { if(peer.adr.get_zone() != zone) { - MWARNING(context << " sent peerlist from another zone, dropping"); + oxen::log::warning(logcat, "{} sent peerlist from another zone, dropping", context); return false; } } - LOG_DEBUG_CC(context, "REMOTE PEERLIST: remote peerlist size=" << peerlist_.size()); - LOG_TRACE_CC(context, "REMOTE PEERLIST: \n" << print_peerlist_to_string(peerlist_)); + oxen::log::debug(logcat, "{}REMOTE PEERLIST: remote peerlist size={}", context, peerlist_.size()); + oxen::log::trace(logcat, "{}REMOTE PEERLIST: \n{}", context, "REMOTE PEERLIST: \n", print_peerlist_to_string(peerlist_)); return m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.merge_peerlist(peerlist_, [this](const peerlist_entry &pe) { return !is_addr_recently_failed(pe.adr); }); } //----------------------------------------------------------------------------------- @@ -1824,7 +1811,7 @@ namespace nodetool { if (zone == m_network_zones.end()) { - MWARNING("Unable to relay all messages, " << c_id.first << " not available"); + oxen::log::warning(logcat, "Unable to relay all messages, zone not available"); return false; } if (c_id.first <= zone->first) @@ -1975,7 +1962,7 @@ namespace nodetool { if(ec) { - LOG_WARNING_CC(ping_context, "back ping connect failed to " << address.str()); + oxen::log::warning(logcat, "{}back ping connect failed to {}", ping_context, address.str()); return false; } COMMAND_PING::request req{}; @@ -1996,14 +1983,14 @@ namespace nodetool { if(code <= 0) { - LOG_WARNING_CC(ping_context, "Failed to invoke COMMAND_PING to " << address.str() << "(" << code << ", " << epee::levin::get_err_descr(code) << ")"); + oxen::log::warning(logcat, "{}Failed to invoke COMMAND_PING to {}({}, {})", ping_context, address.str(), code, epee::levin::get_err_descr(code)); return; } network_zone& zone = m_network_zones.at(address.get_zone()); if(rsp.status != COMMAND_PING::OK_RESPONSE || pr != rsp.peer_id) { - LOG_WARNING_CC(ping_context, "back ping invoke wrong response \"" << rsp.status << "\" from" << address.str() << ", hsh_peer_id=" << pr_ << ", rsp.peer_id=" << peerid_to_string(rsp.peer_id)); + oxen::log::warning(logcat, "{}{}\" from{}, hsh_peer_id={}, rsp.peer_id={}", ping_context, "back ping invoke wrong response \"", rsp.status, address.str(), pr_, peerid_to_string(rsp.peer_id)); zone.m_net_server.get_config_object().close(ping_context.m_connection_id); return; } @@ -2013,7 +2000,7 @@ namespace nodetool if(!inv_call_res) { - LOG_WARNING_CC(ping_context, "back ping invoke failed to " << address.str()); + oxen::log::warning(logcat, "{}{}", ping_context, "back ping invoke failed to ", address.str()); zone.m_net_server.get_config_object().close(ping_context.m_connection_id); return false; } @@ -2021,7 +2008,7 @@ namespace nodetool }, zone.m_bind_ip); if(!r) { - LOG_WARNING_CC(context, "Failed to call connect_async, network error."); + oxen::log::warning(logcat, "{}Failed to call connect_async, network error.", context); } return r; } @@ -2031,7 +2018,7 @@ namespace nodetool { if(!m_payload_handler.process_payload_sync_data(std::move(arg.payload_data), context, false)) { - LOG_WARNING_CC(context, "Failed to process_payload_sync_data(), dropping connection"); + oxen::log::warning(logcat, "{}Failed to process_payload_sync_data(), dropping connection", context); drop_connection(context); return 1; } @@ -2064,7 +2051,7 @@ namespace nodetool if(!context.m_is_income && zone.m_our_address.get_zone() == zone_type) rsp.local_peerlist_new.push_back(peerlist_entry{zone.m_our_address, zone.m_config.m_peer_id, std::time(nullptr)}); - LOG_DEBUG_CC(context, "COMMAND_TIMED_SYNC"); + oxen::log::debug(logcat, "{}COMMAND_TIMED_SYNC", context); return 1; } //----------------------------------------------------------------------------------- @@ -2074,7 +2061,7 @@ namespace nodetool if(arg.node_data.network_id != m_network_id) { - LOG_INFO_CC(context, "WRONG NETWORK AGENT CONNECTED! id=" << arg.node_data.network_id); + oxen::log::info(logcat, "{}{}", context, "WRONG NETWORK AGENT CONNECTED! id=", boost::lexical_cast(arg.node_data.network_id)); drop_connection(context); add_host_fail(context.m_remote_address); return 1; @@ -2082,7 +2069,7 @@ namespace nodetool if(!context.m_is_income) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came not from incoming connection"); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came not from incoming connection", context); drop_connection(context); add_host_fail(context.m_remote_address); return 1; @@ -2090,7 +2077,7 @@ namespace nodetool if(context.peer_id) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came, but seems that connection already have associated peer_id (double COMMAND_HANDSHAKE?)"); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but seems that connection already have associated peer_id (double COMMAND_HANDSHAKE?)", context); drop_connection(context); return 1; } @@ -2101,28 +2088,28 @@ namespace nodetool // and pass in a tor connection's peer id, and deduce the two are the same if you reject it if(arg.node_data.peer_id == zone.m_config.m_peer_id) { - LOG_DEBUG_CC(context, "Connection to self detected, dropping connection"); + oxen::log::debug(logcat, "{}Connection to self detected, dropping connection", context); drop_connection(context); return 1; } if (zone.m_current_number_of_in_peers >= zone.m_config.m_net_config.max_in_connection_count) // in peers limit { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came, but already have max incoming connections, so dropping this one."); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but already have max incoming connections, so dropping this one.", context); drop_connection(context); return 1; } if(!m_payload_handler.process_payload_sync_data(std::move(arg.payload_data), context, true)) { - LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came, but process_payload_sync_data returned false, dropping connection."); + oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but process_payload_sync_data returned false, dropping connection.", context); drop_connection(context); return 1; } if(has_too_many_connections(context.m_remote_address)) { - LOG_PRINT_CCONTEXT_L1("CONNECTION FROM " << context.m_remote_address.host_str() << " REFUSED, too many connections from the same address"); + oxen::log::info(logcat, "CONNECTION FROM {} REFUSED, too many connections from the same address", context.m_remote_address.host_str()); drop_connection(context); return 1; } @@ -2157,7 +2144,7 @@ namespace nodetool pe.id = peer_id_l; pe.pruning_seed = context.m_pruning_seed; this->m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.append_with_peer_white(pe); - LOG_DEBUG_CC(context, "PING SUCCESS " << context.m_remote_address.host_str() << ":" << port_l); + oxen::log::debug(logcat, "{}PING SUCCESS {}:{}", context, context.m_remote_address.host_str(), port_l); }); } @@ -2167,14 +2154,14 @@ namespace nodetool context.sent_addresses.insert(e.adr); get_local_node_data(rsp.node_data, zone); m_payload_handler.get_payload_sync_data(rsp.payload_data); - LOG_DEBUG_CC(context, "COMMAND_HANDSHAKE"); + oxen::log::debug(logcat, "{}COMMAND_HANDSHAKE", context); return 1; } //----------------------------------------------------------------------------------- template int node_server::handle_ping(int command, COMMAND_PING::request& arg, COMMAND_PING::response& rsp, p2p_connection_context& context) { - LOG_DEBUG_CC(context, "COMMAND_PING"); + oxen::log::debug(logcat, "{}COMMAND_PING", context); rsp.status = COMMAND_PING::OK_RESPONSE; rsp.peer_id = m_network_zones.at(context.m_remote_address.get_zone()).m_config.m_peer_id; return 1; @@ -2187,14 +2174,14 @@ namespace nodetool std::vector pl_gray; for (auto& zone : m_network_zones) zone.second.m_peerlist.get_peerlist(pl_gray, pl_white); - MINFO("\nPeerlist white:\n" << print_peerlist_to_string(pl_white) << "\nPeerlist gray:\n" << print_peerlist_to_string(pl_gray) ); + oxen::log::info(logcat, "\nPeerlist white:\n{}\nPeerlist gray:\n{}", print_peerlist_to_string(pl_white), print_peerlist_to_string(pl_gray)); return true; } //----------------------------------------------------------------------------------- template bool node_server::log_connections() { - MINFO("Connections: \r\n" << print_connections_container() ); + oxen::log::info(logcat, "Connections: \r\n{}", print_connections_container()); return true; } //----------------------------------------------------------------------------------- @@ -2221,7 +2208,7 @@ namespace nodetool template void node_server::on_connection_new(p2p_connection_context& context) { - MINFO("["<< epee::net_utils::print_connection_context(context) << "] NEW CONNECTION"); + oxen::log::info(logcat, "[{}] NEW CONNECTION", epee::net_utils::print_connection_context(context)); } //----------------------------------------------------------------------------------- template @@ -2237,7 +2224,7 @@ namespace nodetool m_payload_handler.on_connection_close(context); - MINFO("["<< epee::net_utils::print_connection_context(context) << "] CLOSE CONNECTION"); + oxen::log::info(logcat, "[{}] CLOSE CONNECTION", epee::net_utils::print_connection_context(context)); } template @@ -2361,7 +2348,7 @@ namespace nodetool return true; } epee::net_utils::connection >::set_tos_flag(flag); - MDEBUG("Set ToS flag " << flag); + oxen::log::debug(logcat, "Set ToS flag {}", flag); return true; } @@ -2375,7 +2362,7 @@ namespace nodetool } epee::net_utils::connection >::set_rate_up_limit( limit ); - MINFO("Set limit-up to " << limit << " kB/s"); + oxen::log::info(logcat, "Set limit-up to {} kB/s", limit); return true; } @@ -2387,7 +2374,7 @@ namespace nodetool limit=cryptonote::p2p::DEFAULT_LIMIT_RATE_DOWN; } epee::net_utils::connection >::set_rate_down_limit( limit ); - MINFO("Set limit-down to " << limit << " kB/s"); + oxen::log::info(logcat, "Set limit-down to {} kB/s", limit); return true; } @@ -2409,11 +2396,11 @@ namespace nodetool } if(!this->islimitup) { epee::net_utils::connection >::set_rate_up_limit(limit_up); - MINFO("Set limit-up to " << limit_up << " kB/s"); + oxen::log::info(logcat, "Set limit-up to {} kB/s", limit_up); } if(!this->islimitdown) { epee::net_utils::connection >::set_rate_down_limit(limit_down); - MINFO("Set limit-down to " << limit_down << " kB/s"); + oxen::log::info(logcat, "Set limit-down to {} kB/s", limit_down); } return true; @@ -2466,12 +2453,12 @@ namespace nodetool if (!check_connection_and_handshake_with_peer(pe.adr, pe.last_seen)) { zone.second.m_peerlist.remove_from_peer_gray(pe); - LOG_PRINT_L2("PEER EVICTED FROM GRAY PEER LIST: address: " << pe.adr.host_str() << " Peer ID: " << peerid_to_string(pe.id)); + oxen::log::debug(logcat, "PEER EVICTED FROM GRAY PEER LIST: address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); } else { zone.second.m_peerlist.set_peer_just_seen(pe.id, pe.adr, pe.pruning_seed); - LOG_PRINT_L2("PEER PROMOTED TO WHITE PEER LIST IP address: " << pe.adr.host_str() << " Peer ID: " << peerid_to_string(pe.id)); + oxen::log::debug(logcat, "PEER PROMOTED TO WHITE PEER LIST IP address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); } } return true; @@ -2485,7 +2472,7 @@ namespace nodetool return; const uint32_t index = stripe - 1; std::lock_guard lock{m_used_stripe_peers_mutex}; - MINFO("adding stripe " << stripe << " peer: " << context.m_remote_address.str()); + oxen::log::info(logcat, "adding stripe {} peer: {}", stripe, context.m_remote_address.str()); std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(), [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }); m_used_stripe_peers[index].push_back(context.m_remote_address); @@ -2499,7 +2486,7 @@ namespace nodetool return; const uint32_t index = stripe - 1; std::lock_guard lock{m_used_stripe_peers_mutex}; - MINFO("removing stripe " << stripe << " peer: " << context.m_remote_address.str()); + oxen::log::info(logcat, "removing stripe {} peer: {}", stripe, context.m_remote_address.str()); std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(), [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }); } @@ -2508,7 +2495,7 @@ namespace nodetool void node_server::clear_used_stripe_peers() { std::lock_guard lock{m_used_stripe_peers_mutex}; - MINFO("clearing used stripe peers"); + oxen::log::info(logcat, "clearing used stripe peers"); for (auto &e: m_used_stripe_peers) e.clear(); } diff --git a/src/p2p/net_peerlist.cpp b/src/p2p/net_peerlist.cpp index f50b86943..8890952dc 100644 --- a/src/p2p/net_peerlist.cpp +++ b/src/p2p/net_peerlist.cpp @@ -41,6 +41,7 @@ #include "net_peerlist_boost_serialization.h" #include "common/fs.h" +#include "logging/oxen_logger.h" namespace nodetool @@ -212,7 +213,7 @@ namespace nodetool // This is different from the `return std::nullopt` cases above. Those // cases could fail due to bad file permissions, so a shutdown is // likely more appropriate. - MWARNING("Failed to load p2p config file, falling back to default config"); + oxen::log::warning(globallogcat, "Failed to load p2p config file, falling back to default config"); out.emplace(); } } diff --git a/src/ringct/CMakeLists.txt b/src/ringct/CMakeLists.txt index 935b32033..4065dbc35 100644 --- a/src/ringct/CMakeLists.txt +++ b/src/ringct/CMakeLists.txt @@ -38,6 +38,7 @@ target_link_libraries(ringct_basic PUBLIC common PRIVATE + logging extra) add_library(ringct @@ -49,4 +50,5 @@ target_link_libraries(ringct cryptonote_basic device PRIVATE + logging extra) diff --git a/src/ringct/bulletproofs.cc b/src/ringct/bulletproofs.cc index 57625b238..0e80d41a5 100644 --- a/src/ringct/bulletproofs.cc +++ b/src/ringct/bulletproofs.cc @@ -31,8 +31,8 @@ #include #include "epee/misc_log_ex.h" +#include #include "epee/span.h" -#include "common/perf_timer.h" #include "common/varint.h" #include "cryptonote_config.h" extern "C" @@ -43,25 +43,16 @@ extern "C" #include "multiexp.h" #include "bulletproofs.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "bulletproofs" - //#define DEBUG_BP -#if 0 -#define PERF_TIMER_START_BP(x) PERF_TIMER_START_UNIT(x, 1000000) -#define PERF_TIMER_STOP_BP(x) PERF_TIMER_STOP(x) -#else -#define PERF_TIMER_START_BP(x) ((void)0) -#define PERF_TIMER_STOP_BP(x) ((void)0) -#endif - #define STRAUS_SIZE_LIMIT 232 #define PIPPENGER_SIZE_LIMIT 0 namespace rct { +static auto logcat = oxen::log::Cat("bulletproofs"); + static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b); static rct::keyV vector_powers(const rct::key &x, size_t n); static rct::keyV vector_dup(const rct::key &x, size_t n); @@ -132,12 +123,12 @@ static void init_exponents() straus_HiGi_cache = straus_init_cache(data, STRAUS_SIZE_LIMIT); pippenger_HiGi_cache = pippenger_init_cache(data, 0, PIPPENGER_SIZE_LIMIT); - MINFO("Hi/Gi cache size: " << (sizeof(Hi)+sizeof(Gi))/1024 << " kB"); - MINFO("Hi_p3/Gi_p3 cache size: " << (sizeof(Hi_p3)+sizeof(Gi_p3))/1024 << " kB"); - MINFO("Straus cache size: " << straus_get_cache_size(straus_HiGi_cache)/1024 << " kB"); - MINFO("Pippenger cache size: " << pippenger_get_cache_size(pippenger_HiGi_cache)/1024 << " kB"); + //MINFO("Hi/Gi cache size: " << (sizeof(Hi)+sizeof(Gi))/1024 << " kB"); + //MINFO("Hi_p3/Gi_p3 cache size: " << (sizeof(Hi_p3)+sizeof(Gi_p3))/1024 << " kB"); + //MINFO("Straus cache size: " << straus_get_cache_size(straus_HiGi_cache)/1024 << " kB"); + //MINFO("Pippenger cache size: " << pippenger_get_cache_size(pippenger_HiGi_cache)/1024 << " kB"); size_t cache_size = (sizeof(Hi)+sizeof(Hi_p3))*2 + straus_get_cache_size(straus_HiGi_cache) + pippenger_get_cache_size(pippenger_HiGi_cache); - MINFO("Total cache size: " << cache_size/1024 << "kB"); + //MINFO("Total cache size: " << cache_size/1024 << "kB"); init_done = true; } @@ -496,8 +487,6 @@ Bulletproof bulletproof_PROVE(const rct::keyV &sv, const rct::keyV &gamma) init_exponents(); - PERF_TIMER_UNIT(PROVE, 1000000); - constexpr size_t logN = 6; // log2(64) constexpr size_t N = 1< 0; ) @@ -541,7 +527,6 @@ Bulletproof bulletproof_PROVE(const rct::keyV &sv, const rct::keyV &gamma) } } } - PERF_TIMER_STOP_BP(PROVE_aLaR); // DEBUG: Test to ensure this recovers the value #ifdef DEBUG_BP @@ -566,7 +551,6 @@ Bulletproof bulletproof_PROVE(const rct::keyV &sv, const rct::keyV &gamma) try_again: rct::key hash_cache = rct::hash_to_scalar(V); - PERF_TIMER_START_BP(PROVE_step1); // PAPER LINES 43-44 rct::key alpha = rct::skGen(); rct::key ve = vector_exponent(aL8, aR8); @@ -586,15 +570,13 @@ try_again: rct::key y = hash_cache_mash(hash_cache, A, S); if (y == rct::zero()) { - PERF_TIMER_STOP_BP(PROVE_step1); - MINFO("y is 0, trying again"); + //MINFO("y is 0, trying again"); goto try_again; } rct::key z = hash_cache = rct::hash_to_scalar(y); if (z == rct::zero()) { - PERF_TIMER_STOP_BP(PROVE_step1); - MINFO("z is 0, trying again"); + //MINFO("z is 0, trying again"); goto try_again; } @@ -628,9 +610,7 @@ try_again: sc_add(t1.bytes, t1_1.bytes, t1_2.bytes); rct::key t2 = inner_product(l1, r1); - PERF_TIMER_STOP_BP(PROVE_step1); - PERF_TIMER_START_BP(PROVE_step2); // PAPER LINES 52-53 rct::key tau1 = rct::skGen(), tau2 = rct::skGen(); @@ -649,8 +629,7 @@ try_again: rct::key x = hash_cache_mash(hash_cache, z, T1, T2); if (x == rct::zero()) { - PERF_TIMER_STOP_BP(PROVE_step2); - MINFO("x is 0, trying again"); + //MINFO("x is 0, trying again"); goto try_again; } @@ -673,9 +652,7 @@ try_again: l = vector_add(l, vector_scalar(l1, x)); rct::keyV r = r0; r = vector_add(r, vector_scalar(r1, x)); - PERF_TIMER_STOP_BP(PROVE_step2); - PERF_TIMER_START_BP(PROVE_step3); rct::key t = inner_product(l, r); // DEBUG: Test if the l and r vectors match the polynomial forms @@ -691,8 +668,7 @@ try_again: rct::key x_ip = hash_cache_mash(hash_cache, x, taux, mu, t); if (x_ip == rct::zero()) { - PERF_TIMER_STOP_BP(PROVE_step3); - MINFO("x_ip is 0, trying again"); + //MINFO("x_ip is 0, trying again"); goto try_again; } @@ -719,9 +695,7 @@ try_again: rct::keyV R(logMN); int round = 0; rct::keyV w(logMN); // this is the challenge x in the inner product protocol - PERF_TIMER_STOP_BP(PROVE_step3); - PERF_TIMER_START_BP(PROVE_step4); const rct::keyV *scale = &yinvpow; while (nprime > 1) { @@ -729,25 +703,20 @@ try_again: nprime /= 2; // PAPER LINES 21-22 - PERF_TIMER_START_BP(PROVE_inner_product); rct::key cL = inner_product(slice(aprime, 0, nprime), slice(bprime, nprime, bprime.size())); rct::key cR = inner_product(slice(aprime, nprime, aprime.size()), slice(bprime, 0, nprime)); - PERF_TIMER_STOP_BP(PROVE_inner_product); // PAPER LINES 23-24 - PERF_TIMER_START_BP(PROVE_LR); sc_mul(tmp.bytes, cL.bytes, x_ip.bytes); L[round] = cross_vector_exponent8(nprime, Gprime, nprime, Hprime, 0, aprime, 0, bprime, nprime, scale, &ge_p3_H, &tmp); sc_mul(tmp.bytes, cR.bytes, x_ip.bytes); R[round] = cross_vector_exponent8(nprime, Gprime, 0, Hprime, nprime, aprime, nprime, bprime, 0, scale, &ge_p3_H, &tmp); - PERF_TIMER_STOP_BP(PROVE_LR); // PAPER LINES 25-27 w[round] = hash_cache_mash(hash_cache, L[round], R[round]); if (w[round] == rct::zero()) { - PERF_TIMER_STOP_BP(PROVE_step4); - MINFO("w[round] is 0, trying again"); + //MINFO("w[round] is 0, trying again"); goto try_again; } @@ -755,22 +724,17 @@ try_again: const rct::key winv = invert(w[round]); if (nprime > 1) { - PERF_TIMER_START_BP(PROVE_hadamard2); hadamard_fold(Gprime, NULL, winv, w[round]); hadamard_fold(Hprime, scale, w[round], winv); - PERF_TIMER_STOP_BP(PROVE_hadamard2); } // PAPER LINES 33-34 - PERF_TIMER_START_BP(PROVE_prime); aprime = vector_add(vector_scalar(slice(aprime, 0, nprime), w[round]), vector_scalar(slice(aprime, nprime, aprime.size()), winv)); bprime = vector_add(vector_scalar(slice(bprime, 0, nprime), winv), vector_scalar(slice(bprime, nprime, bprime.size()), w[round])); - PERF_TIMER_STOP_BP(PROVE_prime); scale = NULL; ++round; } - PERF_TIMER_STOP_BP(PROVE_step4); return Bulletproof(std::move(V), A, S, T1, T2, taux, mu, std::move(L), std::move(R), aprime[0], bprime[0], t); } @@ -780,7 +744,6 @@ Bulletproof bulletproof_PROVE(const std::vector &v, const rct::keyV &g CHECK_AND_ASSERT_THROW_MES(v.size() == gamma.size(), "Incompatible sizes of v and gamma"); // vG + gammaH - PERF_TIMER_START_BP(PROVE_v); rct::keyV sv(v.size()); for (size_t i = 0; i < v.size(); ++i) { @@ -794,7 +757,6 @@ Bulletproof bulletproof_PROVE(const std::vector &v, const rct::keyV &g sv[i].bytes[6] = (v[i] >> 48) & 255; sv[i].bytes[7] = (v[i] >> 56) & 255; } - PERF_TIMER_STOP_BP(PROVE_v); return bulletproof_PROVE(sv, gamma); } @@ -813,7 +775,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) { init_exponents(); - PERF_TIMER_START_BP(VERIFY); const size_t logN = 6; const size_t N = 1 << logN; @@ -846,7 +807,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) nV += proof.V.size(); // Reconstruct the challenges - PERF_TIMER_START_BP(VERIFY_start); proof_data.resize(proof_data.size() + 1); proof_data_t &pd = proof_data.back(); rct::key hash_cache = rct::hash_to_scalar(proof.V); @@ -858,7 +818,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) CHECK_AND_ASSERT_MES(!(pd.x == rct::zero()), false, "x == 0"); pd.x_ip = hash_cache_mash(hash_cache, pd.x, proof.taux, proof.mu, proof.t); CHECK_AND_ASSERT_MES(!(pd.x_ip == rct::zero()), false, "x_ip == 0"); - PERF_TIMER_STOP_BP(VERIFY_start); size_t M; for (pd.logM = 0; (M = 1< &proofs) const size_t rounds = pd.logM+logN; CHECK_AND_ASSERT_MES(rounds > 0, false, "Zero rounds"); - PERF_TIMER_START_BP(VERIFY_line_21_22); // The inner product challenges are computed per round pd.w.resize(rounds); for (size_t i = 0; i < rounds; ++i) @@ -876,7 +834,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) pd.w[i] = hash_cache_mash(hash_cache, proof.L[i], proof.R[i]); CHECK_AND_ASSERT_MES(!(pd.w[i] == rct::zero()), false, "w[i] == 0"); } - PERF_TIMER_STOP_BP(VERIFY_line_21_22); pd.inv_offset = inv_offset; for (size_t i = 0; i < rounds; ++i) @@ -893,9 +850,7 @@ bool bulletproof_VERIFY(const std::vector &proofs) multiexp_data.reserve(nV + (2 * (max_logM + logN) + 4) * proofs.size() + 2 * maxMN); multiexp_data.resize(2 * maxMN); - PERF_TIMER_START_BP(VERIFY_line_24_25_invert); const std::vector inverses = invert(to_invert); - PERF_TIMER_STOP_BP(VERIFY_line_24_25_invert); // setup weighted aggregates rct::key z1 = rct::zero(); @@ -929,7 +884,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) rct::scalarmult8(proof8_S, proof.S); rct::scalarmult8(proof8_A, proof.A); - PERF_TIMER_START_BP(VERIFY_line_61); sc_mulsub(m_y0.bytes, proof.taux.bytes, weight_y.bytes, m_y0.bytes); const rct::keyV zpow = vector_powers(pd.z, M+3); @@ -942,9 +896,7 @@ bool bulletproof_VERIFY(const std::vector &proofs) CHECK_AND_ASSERT_MES(j+2 < zpow.size(), false, "invalid zpow index"); sc_mulsub(k.bytes, zpow[j+2].bytes, ip12.bytes, k.bytes); } - PERF_TIMER_STOP_BP(VERIFY_line_61); - PERF_TIMER_START_BP(VERIFY_line_61rl_new); sc_muladd(tmp.bytes, pd.z.bytes, ip1y.bytes, k.bytes); sc_sub(tmp.bytes, proof.t.bytes, tmp.bytes); sc_muladd(y1.bytes, tmp.bytes, weight_y.bytes, y1.bytes); @@ -959,19 +911,15 @@ bool bulletproof_VERIFY(const std::vector &proofs) sc_mul(xsq.bytes, pd.x.bytes, pd.x.bytes); sc_mul(tmp.bytes, xsq.bytes, weight_y.bytes); multiexp_data.emplace_back(tmp, proof8_T2); - PERF_TIMER_STOP_BP(VERIFY_line_61rl_new); - PERF_TIMER_START_BP(VERIFY_line_62); multiexp_data.emplace_back(weight_z, proof8_A); sc_mul(tmp.bytes, pd.x.bytes, weight_z.bytes); multiexp_data.emplace_back(tmp, proof8_S); - PERF_TIMER_STOP_BP(VERIFY_line_62); // Compute the number of rounds for the inner product const size_t rounds = pd.logM+logN; CHECK_AND_ASSERT_MES(rounds > 0, false, "Zero rounds"); - PERF_TIMER_START_BP(VERIFY_line_24_25); // Compute the curvepoints from G[i] and H[i] rct::key yinvpow = rct::identity(); rct::key ypow = rct::identity(); @@ -980,7 +928,6 @@ bool bulletproof_VERIFY(const std::vector &proofs) const rct::key yinv = inverses[pd.inv_offset + rounds]; // precalc - PERF_TIMER_START_BP(VERIFY_line_24_25_precalc); w_cache.resize(1< &proofs) sc_mul(w_cache[s-1].bytes, w_cache[s/2].bytes, winv[j].bytes); } } - PERF_TIMER_STOP_BP(VERIFY_line_24_25_precalc); for (size_t i = 0; i < MN; ++i) { @@ -1038,9 +984,7 @@ bool bulletproof_VERIFY(const std::vector &proofs) } } - PERF_TIMER_STOP_BP(VERIFY_line_24_25); - PERF_TIMER_START_BP(VERIFY_line_26_new); sc_muladd(z1.bytes, proof.mu.bytes, weight_z.bytes, z1.bytes); for (size_t i = 0; i < rounds; ++i) { @@ -1054,11 +998,9 @@ bool bulletproof_VERIFY(const std::vector &proofs) sc_mulsub(tmp.bytes, proof.a.bytes, proof.b.bytes, proof.t.bytes); sc_mul(tmp.bytes, tmp.bytes, pd.x_ip.bytes); sc_muladd(z3.bytes, tmp.bytes, weight_z.bytes, z3.bytes); - PERF_TIMER_STOP_BP(VERIFY_line_26_new); } // now check all proofs at once - PERF_TIMER_START_BP(VERIFY_step2_check); sc_sub(tmp.bytes, m_y0.bytes, z1.bytes); multiexp_data.emplace_back(tmp, rct::G); sc_sub(tmp.bytes, z3.bytes, y1.bytes); @@ -1070,13 +1012,10 @@ bool bulletproof_VERIFY(const std::vector &proofs) } if (!(multiexp(multiexp_data, 2 * maxMN) == rct::identity())) { - PERF_TIMER_STOP_BP(VERIFY_step2_check); - MERROR("Verification failure"); + //MERROR("Verification failure"); return false; } - PERF_TIMER_STOP_BP(VERIFY_step2_check); - PERF_TIMER_STOP_BP(VERIFY); return true; } diff --git a/src/ringct/fmt.h b/src/ringct/fmt.h new file mode 100644 index 000000000..b5d408dfb --- /dev/null +++ b/src/ringct/fmt.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022, The Oxen Foundation +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 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. +// +// 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. +// +// 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. + +#pragma once + +#include "rctTypes.h" + +template <> +struct fmt::formatter : fmt::formatter { + auto format(rct::key k, format_context& ctx) { + return formatter::format( + fmt::format("<{}>", tools::type_to_hex(k)), ctx); + } +}; diff --git a/src/ringct/multiexp.cc b/src/ringct/multiexp.cc index e54cd2e03..5263acacd 100644 --- a/src/ringct/multiexp.cc +++ b/src/ringct/multiexp.cc @@ -29,7 +29,7 @@ // Adapted from Python code by Sarang Noether #include "epee/misc_log_ex.h" -#include "common/perf_timer.h" +#include extern "C" { #include "crypto/crypto-ops.h" @@ -38,12 +38,6 @@ extern "C" #include "rctOps.h" #include "multiexp.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "multiexp" - -//#define MULTIEXP_PERF(x) x -#define MULTIEXP_PERF(x) - #define RAW_MEMORY_BLOCK //#define ALTERNATE_LAYOUT //#define TRACK_STRAUS_ZERO_IDENTITY @@ -101,6 +95,8 @@ extern "C" namespace rct { +static auto logcat = oxen::log::Cat("multiexp"); + static inline bool operator<(const rct::key &k0, const rct::key&k1) { for (int n = 31; n >= 0; --n) @@ -156,8 +152,6 @@ static inline void add(ge_p3 &p3, const ge_p3 &other) rct::key bos_coster_heap_conv(std::vector data) { - MULTIEXP_PERF(PERF_TIMER_START_UNIT(bos_coster, 1000000)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(setup, 1000000)); size_t points = data.size(); CHECK_AND_ASSERT_THROW_MES(points > 1, "Not enough points"); std::vector heap(points); @@ -166,37 +160,24 @@ rct::key bos_coster_heap_conv(std::vector data) auto Comp = [&](size_t e0, size_t e1) { return data[e0].scalar < data[e1].scalar; }; std::make_heap(heap.begin(), heap.end(), Comp); - MULTIEXP_PERF(PERF_TIMER_STOP(setup)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(loop, 1000000)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(pop, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(pop)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(add, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(add)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(sub, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(sub)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(push, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(push)); while (heap.size() > 1) { - MULTIEXP_PERF(PERF_TIMER_RESUME(pop)); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index1 = heap.back(); heap.pop_back(); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index2 = heap.back(); heap.pop_back(); - MULTIEXP_PERF(PERF_TIMER_PAUSE(pop)); - MULTIEXP_PERF(PERF_TIMER_RESUME(add)); ge_cached cached; ge_p3_to_cached(&cached, &data[index1].point); ge_p1p1 p1; ge_add(&p1, &data[index2].point, &cached); ge_p1p1_to_p3(&data[index2].point, &p1); - MULTIEXP_PERF(PERF_TIMER_PAUSE(add)); - MULTIEXP_PERF(PERF_TIMER_RESUME(sub)); sc_sub(data[index1].scalar.bytes, data[index1].scalar.bytes, data[index2].scalar.bytes); - MULTIEXP_PERF(PERF_TIMER_PAUSE(sub)); - MULTIEXP_PERF(PERF_TIMER_RESUME(push)); if (!(data[index1].scalar == rct::zero())) { heap.push_back(index1); @@ -205,15 +186,8 @@ rct::key bos_coster_heap_conv(std::vector data) heap.push_back(index2); std::push_heap(heap.begin(), heap.end(), Comp); - MULTIEXP_PERF(PERF_TIMER_PAUSE(push)); } - MULTIEXP_PERF(PERF_TIMER_STOP(push)); - MULTIEXP_PERF(PERF_TIMER_STOP(sub)); - MULTIEXP_PERF(PERF_TIMER_STOP(add)); - MULTIEXP_PERF(PERF_TIMER_STOP(pop)); - MULTIEXP_PERF(PERF_TIMER_STOP(loop)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(end, 1000000)); //return rct::scalarmultKey(data[index1].point, data[index1].scalar); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index1 = heap.back(); @@ -227,8 +201,6 @@ rct::key bos_coster_heap_conv(std::vector data) rct::key bos_coster_heap_conv_robust(std::vector data) { - MULTIEXP_PERF(PERF_TIMER_START_UNIT(bos_coster, 1000000)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(setup, 1000000)); size_t points = data.size(); CHECK_AND_ASSERT_THROW_MES(points > 0, "Not enough points"); std::vector heap; @@ -256,30 +228,20 @@ rct::key bos_coster_heap_conv_robust(std::vector data) return res; } - MULTIEXP_PERF(PERF_TIMER_STOP(setup)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(loop, 1000000)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(pop, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(pop)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(div, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(div)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(add, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(add)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(sub, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(sub)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(push, 1000000)); MULTIEXP_PERF(PERF_TIMER_PAUSE(push)); while (heap.size() > 1) { - MULTIEXP_PERF(PERF_TIMER_RESUME(pop)); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index1 = heap.back(); heap.pop_back(); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index2 = heap.back(); heap.pop_back(); - MULTIEXP_PERF(PERF_TIMER_PAUSE(pop)); ge_cached cached; ge_p1p1 p1; ge_p2 p2; - MULTIEXP_PERF(PERF_TIMER_RESUME(div)); while (1) { rct::key s1_2 = div2(data[index1].scalar); @@ -298,19 +260,13 @@ rct::key bos_coster_heap_conv_robust(std::vector data) ge_p2_dbl(&p1, &p2); ge_p1p1_to_p3(&data[index1].point, &p1); } - MULTIEXP_PERF(PERF_TIMER_PAUSE(div)); - MULTIEXP_PERF(PERF_TIMER_RESUME(add)); ge_p3_to_cached(&cached, &data[index1].point); ge_add(&p1, &data[index2].point, &cached); ge_p1p1_to_p3(&data[index2].point, &p1); - MULTIEXP_PERF(PERF_TIMER_PAUSE(add)); - MULTIEXP_PERF(PERF_TIMER_RESUME(sub)); sc_sub(data[index1].scalar.bytes, data[index1].scalar.bytes, data[index2].scalar.bytes); - MULTIEXP_PERF(PERF_TIMER_PAUSE(sub)); - MULTIEXP_PERF(PERF_TIMER_RESUME(push)); if (!(data[index1].scalar == rct::zero())) { heap.push_back(index1); @@ -319,15 +275,8 @@ rct::key bos_coster_heap_conv_robust(std::vector data) heap.push_back(index2); std::push_heap(heap.begin(), heap.end(), Comp); - MULTIEXP_PERF(PERF_TIMER_PAUSE(push)); } - MULTIEXP_PERF(PERF_TIMER_STOP(push)); - MULTIEXP_PERF(PERF_TIMER_STOP(sub)); - MULTIEXP_PERF(PERF_TIMER_STOP(add)); - MULTIEXP_PERF(PERF_TIMER_STOP(pop)); - MULTIEXP_PERF(PERF_TIMER_STOP(loop)); - MULTIEXP_PERF(PERF_TIMER_START_UNIT(end, 1000000)); //return rct::scalarmultKey(data[index1].point, data[index1].scalar); std::pop_heap(heap.begin(), heap.end(), Comp); size_t index1 = heap.back(); @@ -368,7 +317,6 @@ struct straus_cached_data std::shared_ptr straus_init_cache(const std::vector &data, size_t N) { - MULTIEXP_PERF(PERF_TIMER_START_UNIT(multiples, 1000000)); if (N == 0) N = data.size(); CHECK_AND_ASSERT_THROW_MES(N <= data.size(), "Bad cache base data"); @@ -426,7 +374,6 @@ std::shared_ptr straus_init_cache(const std::vector &cache) rct::key straus(const std::vector &data, const std::shared_ptr &cache, size_t STEP) { CHECK_AND_ASSERT_THROW_MES(cache == NULL || cache->size >= data.size(), "Cache is too small"); - MULTIEXP_PERF(PERF_TIMER_UNIT(straus, 1000000)); STEP = STEP ? STEP : 192; - MULTIEXP_PERF(PERF_TIMER_START_UNIT(setup, 1000000)); static constexpr unsigned int mask = (1< local_cache = cache == NULL ? straus_init_cache(data) : cache; ge_cached cached; @@ -457,14 +402,11 @@ rct::key straus(const std::vector &data, const std::shared_ptr skip(data.size()); for (size_t i = 0; i < data.size(); ++i) skip[i] = data[i].scalar == rct::zero() || ge_p3_is_point_at_infinity(&data[i].point); - MULTIEXP_PERF(PERF_TIMER_STOP(skip)); #endif - MULTIEXP_PERF(PERF_TIMER_START_UNIT(digits, 1000000)); #if STRAUS_C==4 std::unique_ptr digits{new uint8_t[64 * data.size()]}; #else @@ -496,7 +438,6 @@ rct::key straus(const std::vector &data, const std::shared_ptr &data, const std::shared_ptr pippenger_init_cache(const std::vector &data, size_t start_offset, size_t N) { - MULTIEXP_PERF(PERF_TIMER_START_UNIT(pippenger_init_cache, 1000000)); CHECK_AND_ASSERT_THROW_MES(start_offset <= data.size(), "Bad cache base data"); if (N == 0) N = data.size() - start_offset; @@ -596,7 +535,6 @@ std::shared_ptr pippenger_init_cache(const std::vectorcached[i], &data[i+start_offset].point); - MULTIEXP_PERF(PERF_TIMER_STOP(pippenger_init_cache)); return cache; } diff --git a/src/ringct/rctOps.cpp b/src/ringct/rctOps.cpp index b595bb600..5c943f6c5 100644 --- a/src/ringct/rctOps.cpp +++ b/src/ringct/rctOps.cpp @@ -30,15 +30,13 @@ #include #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "rctOps.h" using namespace crypto; using namespace std; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "ringct" - -#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}} +#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {oxen::log::warning(oxen::log::Cat("ringct"), message); throw std::runtime_error(message);}} struct zero_commitment { uint64_t amount; rct::key commitment; }; static const zero_commitment zero_commitments[] = { diff --git a/src/ringct/rctSigs.cpp b/src/ringct/rctSigs.cpp index f716cabb6..ce642f073 100644 --- a/src/ringct/rctSigs.cpp +++ b/src/ringct/rctSigs.cpp @@ -29,7 +29,6 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "epee/misc_log_ex.h" -#include "common/perf_timer.h" #include "common/threadpool.h" #include "common/util.h" #include "rctSigs.h" @@ -37,13 +36,11 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "cryptonote_config.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "ringct" - -#define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}} namespace { + static auto logcat = oxen::log::Cat("ringct"); + rct::Bulletproof make_dummy_bulletproof(const std::vector &outamounts, rct::keyV &C, rct::keyV &masks) { const size_t n_outs = outamounts.size(); @@ -124,8 +121,11 @@ namespace rct { bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) { ge_p3 P1_p3[64], P2_p3[64]; for (size_t i = 0 ; i < 64 ; ++i) { - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed"); - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed"); + if (ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) != 0 || ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) != 0) + { + oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + return false; + } } return verifyBorromean(bb, P1_p3, P2_p3); } @@ -372,7 +372,6 @@ namespace rct { bool verRange(const key & C, const rangeSig & as) { try { - PERF_TIMER(verRange); ge_p3 CiH[64], asCi[64]; int i = 0; ge_p3 Ctmp_p3 = ge_p3_identity; @@ -383,9 +382,17 @@ namespace rct { ge_cached cached; ge_p3 p3; ge_p1p1 p1; - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, H2[i].bytes) == 0, false, "point conv failed"); + if (ge_frombytes_vartime(&p3, H2[i].bytes) != 0) + { + oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + return false; + } ge_p3_to_cached(&cached, &p3); - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) == 0, false, "point conv failed"); + if (ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) != 0) + { + oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + return false; + } ge_sub(&p1, &asCi[i], &cached); ge_p3_to_cached(&cached, &asCi[i]); ge_p1p1_to_p3(&CiH[i], &p1); @@ -507,7 +514,6 @@ namespace rct { //Ver: // verifies the above sig is created corretly bool verRctMG(const mgSig &mg, const ctkeyM & pubs, const ctkeyV & outPk, const key &txnFeeKey, const key &message) { - PERF_TIMER(verRctMG); //setup vars size_t cols = pubs.size(); CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs"); @@ -548,7 +554,6 @@ namespace rct { bool verRctMGSimple(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C) { try { - PERF_TIMER(verRctMGSimple); //setup vars size_t rows = 1; size_t cols = pubs.size(); @@ -557,7 +562,11 @@ namespace rct { size_t i; keyM M(cols, tmp); ge_p3 Cp3; - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&Cp3, C.bytes) == 0, false, "point conv failed"); + if (ge_frombytes_vartime(&Cp3, C.bytes) != 0) + { + oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + return false; + } ge_cached Ccached; ge_p3_to_cached(&Ccached, &Cp3); ge_p1p1 p1; @@ -565,7 +574,11 @@ namespace rct { for (i = 0; i < cols; i++) { M[i][0] = pubs[i].dest; ge_p3 p3; - CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, pubs[i].mask.bytes) == 0, false, "point conv failed"); + if (ge_frombytes_vartime(&p3, pubs[i].mask.bytes) != 0) + { + oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + return false; + } ge_sub(&p1, &p3, &Ccached); ge_p1p1_to_p3(&p3, &p1); ge_p3_tobytes(M[i][1].bytes, &p3); @@ -579,7 +592,6 @@ namespace rct { bool verRctCLSAGSimple(const key &message, const clsag &sig, const ctkeyV & pubs, const key & C_offset) { try { - PERF_TIMER(verRctCLSAGSimple); const size_t n = pubs.size(); // Check data @@ -895,7 +907,6 @@ namespace rct { // uses the attached ecdh info to find the amounts represented by each output commitment // must know the destination private key to find the correct amount, else will return a random number bool verRct(const rctSig & rv, bool semantics) { - PERF_TIMER(verRct); CHECK_AND_ASSERT_MES(rv.type == RCTType::Full, false, "verRct called on non-full rctSig"); if (semantics) { @@ -922,7 +933,7 @@ namespace rct { for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - LOG_PRINT_L1("Range proof verified failed for proof " << i); + oxen::log::info(logcat, "Range proof verified failed for proof {}", i); return false; } } @@ -935,7 +946,7 @@ namespace rct { DP("mg sig verified?"); DP(mgVerd); if (!mgVerd) { - LOG_PRINT_L1("MG signature verification failed"); + oxen::log::info(logcat, "MG signature verification failed"); return false; } } @@ -944,12 +955,12 @@ namespace rct { } catch (const std::exception &e) { - LOG_PRINT_L1("Error in verRct: " << e.what()); + oxen::log::info(logcat, "Error in verRct: {}", e.what()); return false; } catch (...) { - LOG_PRINT_L1("Error in verRct, but not an actual exception"); + oxen::log::info(logcat, "Error in verRct, but not an actual exception"); return false; } } @@ -959,7 +970,6 @@ namespace rct { bool verRctSemanticsSimple(const std::vector & rvv) { try { - PERF_TIMER(verRctSemanticsSimple); tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; @@ -1022,7 +1032,7 @@ namespace rct { //check pseudoOuts vs Outs.. if (!equalKeys(sumPseudoOuts, sumOutpks)) { - LOG_PRINT_L1("Sum check failed"); + oxen::log::info(logcat, "Sum check failed"); return false; } @@ -1040,14 +1050,14 @@ namespace rct { } if (!proofs.empty() && !verBulletproof(proofs)) { - LOG_PRINT_L1("Aggregate range proof verified failed"); + oxen::log::info(logcat, "Aggregate range proof verified failed"); return false; } waiter.wait(&tpool); for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - LOG_PRINT_L1("Range proof verified failed for proof " << i); + oxen::log::info(logcat, "Range proof verified failed for proof {}", i); return false; } } @@ -1057,12 +1067,12 @@ namespace rct { // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { - LOG_PRINT_L1("Error in verRctSemanticsSimple: " << e.what()); + oxen::log::info(logcat, "Error in verRctSemanticsSimple: {}", e.what()); return false; } catch (...) { - LOG_PRINT_L1("Error in verRctSemanticsSimple, but not an actual exception"); + oxen::log::info(logcat, "Error in verRctSemanticsSimple, but not an actual exception"); return false; } } @@ -1077,7 +1087,6 @@ namespace rct { bool verRctNonSemanticsSimple(const rctSig & rv) { try { - PERF_TIMER(verRctNonSemanticsSimple); CHECK_AND_ASSERT_MES(rct::is_rct_simple(rv.type), false, "verRctNonSemanticsSimple called on non simple rctSig"); const bool bulletproof = is_rct_bulletproof(rv.type); @@ -1111,7 +1120,7 @@ namespace rct { for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - LOG_PRINT_L1("verRctMGSimple/verRctCLSAGSimple failed for input " << i); + oxen::log::info(logcat, "verRctMGSimple/verRctCLSAGSimple failed for input {}", i); return false; } } @@ -1121,12 +1130,12 @@ namespace rct { // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { - LOG_PRINT_L1("Error in verRctNonSemanticsSimple: " << e.what()); + oxen::log::info(logcat, "Error in verRctNonSemanticsSimple: {}", e.what()); return false; } catch (...) { - LOG_PRINT_L1("Error in verRctNonSemanticsSimple, but not an actual exception"); + oxen::log::info(logcat, "Error in verRctNonSemanticsSimple, but not an actual exception"); return false; } } diff --git a/src/ringct/rctTypes.cpp b/src/ringct/rctTypes.cpp index a1aba0676..9f0f2680d 100644 --- a/src/ringct/rctTypes.cpp +++ b/src/ringct/rctTypes.cpp @@ -32,14 +32,15 @@ #include "cryptonote_config.h" #include "rctTypes.h" #include "epee/int-util.h" +#include + using namespace crypto; using namespace std; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "ringct" - namespace rct { + static auto logcat = oxen::log::Cat("ringct"); + //dp //Debug printing for the above types //Actually use DP(value) and #define DBG diff --git a/src/ringct/rctTypes.h b/src/ringct/rctTypes.h index fff31542c..98d3c8362 100644 --- a/src/ringct/rctTypes.h +++ b/src/ringct/rctTypes.h @@ -47,7 +47,6 @@ extern "C" { #include "serialization/variant.h" #include "common/util.h" - //Define this flag when debugging to get additional info on the console #ifdef DBG #define DP(x) dp(x) @@ -577,7 +576,6 @@ inline std::ostream &operator <<(std::ostream &o, const rct::key &v) { } } - namespace std { template<> struct hash { std::size_t operator()(const rct::key &k) const { return reinterpret_cast(k); } }; diff --git a/src/rpc/CMakeLists.txt b/src/rpc/CMakeLists.txt index 91896fc07..48ab0e456 100644 --- a/src/rpc/CMakeLists.txt +++ b/src/rpc/CMakeLists.txt @@ -55,6 +55,7 @@ target_link_libraries(rpc_commands nlohmann_json::nlohmann_json PRIVATE cryptonote_protocol + logging extra) target_link_libraries(rpc @@ -69,6 +70,7 @@ target_link_libraries(rpc Boost::thread Boost::program_options SQLiteCpp + logging extra) target_link_libraries(daemon_rpc_server @@ -78,6 +80,7 @@ target_link_libraries(daemon_rpc_server rpc Boost::thread SQLiteCpp + logging extra) target_link_libraries(rpc_http_client @@ -86,4 +89,5 @@ target_link_libraries(rpc_http_client cpr::cpr nlohmann_json::nlohmann_json PRIVATE + logging extra) diff --git a/src/rpc/common/CMakeLists.txt b/src/rpc/common/CMakeLists.txt index 2c2e52e92..a7dfd1ded 100644 --- a/src/rpc/common/CMakeLists.txt +++ b/src/rpc/common/CMakeLists.txt @@ -12,5 +12,6 @@ target_link_libraries(rpc_common uWebSockets nlohmann_json::nlohmann_json oxenmq::oxenmq + logging PRIVATE extra) diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index f73ab9bb3..5c1661d37 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -55,7 +55,6 @@ #include "common/command_line.h" #include "common/oxen.h" #include "common/sha256sum.h" -#include "common/perf_timer.h" #include "common/random.h" #include "common/hex.h" #include "cryptonote_basic/cryptonote_format_utils.h" @@ -71,15 +70,15 @@ #include "rpc/common/json_bt.h" #include "rpc/common/rpc_command.h" #include - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon.rpc" +#include namespace cryptonote::rpc { using nlohmann::json; using oxen::json_to_bt; + static auto logcat = oxen::log::Cat("daemon.rpc"); + namespace { template @@ -172,7 +171,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_HEIGHT& get_height, rpc_context context) { - PERF_TIMER(on_get_height); auto [height, hash] = m_core.get_blockchain_top(); ++height; // block height to chain height @@ -191,7 +189,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_INFO& info, rpc_context context) { - PERF_TIMER(on_get_info); auto [top_height, top_hash] = m_core.get_blockchain_top(); @@ -295,7 +292,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_NET_STATS& get_net_stats, rpc_context context) { - PERF_TIMER(on_get_net_stats); get_net_stats.response["start_time"] = m_core.get_start_time(); { std::lock_guard lock{epee::net_utils::network_throttle_manager::m_lock_get_global_throttle_in}; @@ -327,7 +323,6 @@ namespace cryptonote::rpc { { GET_BLOCKS_BIN::response res{}; - PERF_TIMER(on_get_blocks); std::vector, std::vector > > > bs; if(!m_core.find_blockchain_supplement(req.start_height, req.block_ids, bs, res.current_height, res.start_height, req.prune, !req.no_miner_tx, GET_BLOCKS_BIN::MAX_COUNT)) @@ -371,7 +366,7 @@ namespace cryptonote::rpc { } } - MDEBUG("on_get_blocks: " << bs.size() << " blocks, " << ntxes << " txes, size " << size); + oxen::log::debug(logcat, "on_get_blocks: {} blocks, {} txes, size {}", bs.size(), ntxes, size); res.status = STATUS_OK; return res; } @@ -379,7 +374,6 @@ namespace cryptonote::rpc { { GET_ALT_BLOCKS_HASHES_BIN::response res{}; - PERF_TIMER(on_get_alt_blocks_hashes); std::vector blks; if(!m_core.get_alternative_blocks(blks)) @@ -395,7 +389,7 @@ namespace cryptonote::rpc { res.blks_hashes.push_back(tools::type_to_hex(get_block_hash(blk))); } - MDEBUG("on_get_alt_blocks_hashes: " << blks.size() << " blocks " ); + oxen::log::debug(logcat, "on_get_alt_blocks_hashes: {} blocks ", blks.size()); res.status = STATUS_OK; return res; } @@ -404,8 +398,6 @@ namespace cryptonote::rpc { { GET_BLOCKS_BY_HEIGHT_BIN::response res{}; - PERF_TIMER(on_get_blocks_by_height); - res.status = "Failed"; res.blocks.clear(); res.blocks.reserve(req.heights.size()); @@ -436,8 +428,6 @@ namespace cryptonote::rpc { { GET_HASHES_BIN::response res{}; - PERF_TIMER(on_get_hashes); - res.start_height = req.start_height; if(!m_core.get_blockchain_storage().find_blockchain_supplement(req.block_ids, res.m_block_ids, res.start_height, res.current_height, false)) { @@ -453,8 +443,6 @@ namespace cryptonote::rpc { { GET_OUTPUTS_BIN::response res{}; - PERF_TIMER(on_get_outs_bin); - if (!context.admin && req.outputs.size() > GET_OUTPUTS_BIN::MAX_COUNT) res.status = "Too many outs requested"; else if (m_core.get_outs(req, res)) @@ -467,7 +455,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_OUTPUTS& get_outputs, rpc_context context) { - PERF_TIMER(on_get_outs); if (!context.admin && get_outputs.request.output_indices.size() > GET_OUTPUTS::MAX_COUNT) { get_outputs.response["status"] = "Too many outs requested"; return; @@ -526,7 +513,6 @@ namespace cryptonote::rpc { { GET_TX_GLOBAL_OUTPUTS_INDEXES_BIN::response res{}; - PERF_TIMER(on_get_indexes); bool r = m_core.get_tx_outputs_gindexs(req.txid, res.o_indexes); if(!r) { @@ -534,7 +520,7 @@ namespace cryptonote::rpc { return res; } res.status = STATUS_OK; - LOG_PRINT_L2("GET_TX_GLOBAL_OUTPUTS_INDEXES: [" << res.o_indexes.size() << "]"); + oxen::log::debug(logcat, "GET_TX_GLOBAL_OUTPUTS_INDEXES: [{}]", res.o_indexes.size()); return res; } @@ -748,7 +734,7 @@ namespace cryptonote::rpc { transaction tx; if (!parse_and_validate_tx_from_blob(*bd, tx)) { - MERROR("Failed to parse tx from txpool"); + oxen::log::error(logcat, "Failed to parse tx from txpool"); // continue return true; } @@ -794,7 +780,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_TRANSACTIONS& get, rpc_context context) { - PERF_TIMER(on_get_transactions); std::unordered_set missed_txs; using split_tx = std::tuple; std::vector txs; @@ -804,7 +789,7 @@ namespace cryptonote::rpc { get.response["status"] = STATUS_FAILED; return; } - LOG_PRINT_L2("Found " << txs.size() << "/" << get.request.tx_hashes.size() << " transactions on the blockchain"); + oxen::log::debug(logcat, "Found {}/{} transactions on the blockchain", txs.size(), get.request.tx_hashes.size()); } // try the pool for any missing txes @@ -855,7 +840,7 @@ namespace cryptonote::rpc { } txs = std::move(sorted_txs); get.response_hex["missed_tx"] = missed_txs; // non-plural here intentional to not break existing clients - LOG_PRINT_L2("Found " << found_in_pool.size() << "/" << get.request.tx_hashes.size() << " transactions in the pool"); + oxen::log::debug(logcat, "Found {}/{} transactions in the pool", found_in_pool.size(), get.request.tx_hashes.size()); } else if (get.request.memory_pool) { txs.reserve(pool_txs.size()); std::transform(pool_txs.begin(), pool_txs.end(), std::back_inserter(txs), split_mempool_tx); @@ -869,7 +854,7 @@ namespace cryptonote::rpc { } } } catch (const std::exception& e) { - MERROR(e.what()); + oxen::log::error(logcat, e.what()); get.response["status"] = "Failed: "s + e.what(); return; } @@ -997,13 +982,12 @@ namespace cryptonote::rpc { } } - LOG_PRINT_L2(get.response["txs"].size() << " transactions found, " << missed_txs.size() << " not found"); + oxen::log::debug(logcat, "{} transactions found, {} not found", get.response["txs"].size(), missed_txs.size()); get.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(IS_KEY_IMAGE_SPENT& spent, rpc_context context) { - PERF_TIMER(on_is_key_image_spent); spent.response["status"] = STATUS_FAILED; std::vector blockchain_spent; @@ -1019,7 +1003,7 @@ namespace cryptonote::rpc { try { kis = get_pool_kis(m_core); } catch (const std::exception& e) { - MERROR("Failed to get pool key images: " << e.what()); + oxen::log::error(logcat, "Failed to get pool key images: {}", e.what()); return; } } @@ -1034,7 +1018,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SUBMIT_TRANSACTION& tx, rpc_context context) { - PERF_TIMER(on_submit_transaction); if (!check_core_ready()) { tx.response["status"] = STATUS_BUSY; return; @@ -1079,7 +1062,7 @@ namespace cryptonote::rpc { { tx.response["status"] = STATUS_FAILED; auto reason = print_tx_verification_context(tvc); - LOG_PRINT_L0("[on_send_raw_tx]: " << (tvc.m_verifivation_failed ? "tx verification failed" : "Failed to process tx") << reason); + oxen::log::warning(logcat, "[on_send_raw_tx]: {} {}", (tvc.m_verifivation_failed ? "tx verification failed" : "Failed to process tx"), reason); tx.response["reason"] = std::move(reason); tx.response["reason_codes"] = tx_verification_failure_codes(tvc); return; @@ -1097,7 +1080,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(START_MINING& start_mining, rpc_context context) { - PERF_TIMER(on_start_mining); //CHECK_CORE_READY(); if(!check_core_ready()){ start_mining.response["status"] = STATUS_BUSY; @@ -1107,12 +1089,12 @@ namespace cryptonote::rpc { cryptonote::address_parse_info info; if(!get_account_address_from_str(info, m_core.get_nettype(), start_mining.request.miner_address)) { start_mining.response["status"] = "Failed, invalid address"; - LOG_PRINT_L0(start_mining.response["status"]); + oxen::log::warning(logcat, start_mining.response["status"]); return; } if (info.is_subaddress) { start_mining.response["status"] = "Mining to subaddress isn't supported yet"; - LOG_PRINT_L0(start_mining.response["status"]); + oxen::log::warning(logcat, start_mining.response["status"]); return; } @@ -1126,7 +1108,7 @@ namespace cryptonote::rpc { // then we fail and log that. if (start_mining.request.threads_count > max_concurrency_count) { start_mining.response["status"] = "Failed, too many threads relative to CPU cores."; - LOG_PRINT_L0(start_mining.response["status"]); + oxen::log::warning(logcat, start_mining.response["status"]); return; } @@ -1140,7 +1122,7 @@ namespace cryptonote::rpc { if(!miner.start(info.address, start_mining.request.threads_count, start_mining.request.num_blocks, start_mining.request.slow_mining)) { start_mining.response["status"] = "Failed, mining not started"; - LOG_PRINT_L0(start_mining.response["status"]); + oxen::log::warning(logcat, start_mining.response["status"]); return; } @@ -1149,18 +1131,17 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(STOP_MINING& stop_mining, rpc_context context) { - PERF_TIMER(on_stop_mining); cryptonote::miner &miner= m_core.get_miner(); if(!miner.is_mining()) { stop_mining.response["status"] = "Mining never started"; - LOG_PRINT_L0(stop_mining.response["status"]); + oxen::log::warning(logcat, stop_mining.response["status"]); return; } if(!miner.stop()) { stop_mining.response["status"] = "Failed, mining not stopped"; - LOG_PRINT_L0(stop_mining.response["status"]); + oxen::log::warning(logcat, stop_mining.response["status"]); return; } @@ -1169,8 +1150,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(MINING_STATUS& mining_status, rpc_context context) { - PERF_TIMER(on_mining_status); - const miner& lMiner = m_core.get_miner(); mining_status.response["active"] = lMiner.is_mining(); mining_status.response["block_target"] = tools::to_seconds(TARGET_BLOCK_TIME); @@ -1195,11 +1174,10 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SAVE_BC& save_bc, rpc_context context) { - PERF_TIMER(on_save_bc); if( !m_core.get_blockchain_storage().store_blockchain() ) { save_bc.response["status"] = "Error while storing blockchain"; - LOG_PRINT_L0(save_bc.response["status"]); + oxen::log::warning(logcat, save_bc.response["status"]); return; } save_bc.response["status"] = STATUS_OK; @@ -1220,9 +1198,7 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_PEER_LIST& pl, rpc_context context) { - PERF_TIMER(on_get_peer_list); std::vector white_list, gray_list; - if (pl.request.public_only) m_p2p.get_public_peerlist(gray_list, white_list); else @@ -1236,21 +1212,20 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SET_LOG_LEVEL& set_log_level, rpc_context context) { - PERF_TIMER(on_set_log_level); if (set_log_level.request.level < 0 || set_log_level.request.level > 4) { set_log_level.response["status"] = "Error: log level not valid"; return; } - mlog_set_log_level(set_log_level.request.level); + auto log_level = oxen::logging::parse_level(set_log_level.request.level); + if (log_level.has_value()) + oxen::log::reset_level(*log_level); set_log_level.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SET_LOG_CATEGORIES& set_log_categories, rpc_context context) { - PERF_TIMER(on_set_log_categories); - mlog_set_log(set_log_categories.request.categories.c_str()); - set_log_categories.response["categories"] = mlog_get_categories(); + oxen::logging::process_categories_string(set_log_categories.request.categories.c_str()); set_log_categories.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ @@ -1258,7 +1233,6 @@ namespace cryptonote::rpc { { GET_TRANSACTION_POOL_HASHES_BIN::response res{}; - PERF_TIMER(on_get_transaction_pool_hashes); std::vector tx_pool_hashes; m_core.get_pool().get_transaction_hashes(tx_pool_hashes, context.admin, req.blinked_txs_only); @@ -1269,7 +1243,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_TRANSACTION_POOL_HASHES& get_transaction_pool_hashes, rpc_context context) { - PERF_TIMER(on_get_transaction_pool_hashes); std::vector tx_hashes; m_core.get_pool().get_transaction_hashes(tx_hashes, context.admin); get_transaction_pool_hashes.response_hex["tx_hashes"] = tx_hashes; @@ -1278,7 +1251,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_TRANSACTION_POOL_STATS& stats, rpc_context context) { - PERF_TIMER(on_get_transaction_pool_stats); auto txpool = m_core.get_pool().get_transaction_stats(stats.request.include_unrelayed); json pool_stats{ {"bytes_total", txpool.bytes_total}, @@ -1305,12 +1277,10 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(STOP_DAEMON& stop_daemon, rpc_context context) { - PERF_TIMER(on_stop_daemon); m_p2p.send_stop_signal(); stop_daemon.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ - // // Oxen // @@ -1318,7 +1288,6 @@ namespace cryptonote::rpc { { GET_OUTPUT_BLACKLIST_BIN::response res{}; - PERF_TIMER(on_get_output_blacklist_bin); try { m_core.get_output_blacklist(res.blacklist); @@ -1335,20 +1304,17 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BLOCK_COUNT& get, rpc_context context) { - PERF_TIMER(on_getblockcount); get.response["count"] = m_core.get_current_blockchain_height(); get.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BLOCK_HASH& get, rpc_context context) { - PERF_TIMER(on_getblockhash); auto curr_height = m_core.get_current_blockchain_height(); for (auto h : get.request.heights) { if (h >= curr_height) throw rpc_error{ERROR_TOO_BIG_HEIGHT, "Requested block height: " + tools::int_to_string(h) + " greater than current top block height: " + tools::int_to_string(curr_height - 1)}; - get.response_hex[tools::int_to_string(h)] = m_core.get_block_id_by_height(h); } get.response["status"] = STATUS_OK; @@ -1366,7 +1332,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::fill_block_header_response(const block& blk, bool orphan_status, uint64_t height, const crypto::hash& hash, block_header_response& response, bool fill_pow_hash, bool get_tx_hashes) { - PERF_TIMER(fill_block_header_response); response.major_version = static_cast(blk.major_version); response.minor_version = blk.minor_version; response.timestamp = blk.timestamp; @@ -1396,13 +1361,9 @@ namespace cryptonote::rpc { response.tx_hashes.push_back(tools::type_to_hex(tx_hash)); } } - //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_LAST_BLOCK_HEADER& get_last_block_header, rpc_context context) { - - PERF_TIMER(on_get_last_block_header); - if(!check_core_ready()) { get_last_block_header.response["status"] = STATUS_BUSY; @@ -1426,9 +1387,6 @@ namespace cryptonote::rpc { void core_rpc_server::invoke(GET_BLOCK_HEADER_BY_HASH& get_block_header_by_hash, rpc_context context) { - - PERF_TIMER(on_get_block_header_by_hash); - auto get = [this, &get_block_header_by_hash, admin=context.admin](const std::string &hash, block_header_response &block_header) { crypto::hash block_hash; if (!tools::hex_to_type(hash, block_hash)) @@ -1462,7 +1420,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BLOCK_HEADERS_RANGE& get_block_headers_range, rpc_context context) { - PERF_TIMER(on_get_block_headers_range); const uint64_t bc_height = m_core.get_current_blockchain_height(); uint64_t start_height = get_block_headers_range.request.start_height; uint64_t end_height = get_block_headers_range.request.end_height; @@ -1491,7 +1448,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BLOCK_HEADER_BY_HEIGHT& get_block_header_by_height, rpc_context context) { - PERF_TIMER(on_get_block_header_by_height); auto get = [this, curr_height=m_core.get_current_blockchain_height(), pow=get_block_header_by_height.request.fill_pow_hash && context.admin, tx_hashes=get_block_header_by_height.request.get_tx_hashes] (uint64_t height, block_header_response& bhr) { if (height >= curr_height) @@ -1524,7 +1480,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BLOCK& get_block, rpc_context context) { - PERF_TIMER(on_get_block); block blk; uint64_t block_height; bool orphan = false; @@ -1593,7 +1548,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_CONNECTIONS& get_connections, rpc_context context) { - PERF_TIMER(on_get_connections); auto& c = get_connections.response["connections"]; c = json::array(); for (auto& ci : m_p2p.get_payload_object().get_connections()) @@ -1603,8 +1557,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(HARD_FORK_INFO& hfinfo, rpc_context context) { - PERF_TIMER(on_hard_fork_info); - const auto& blockchain = m_core.get_blockchain_storage(); auto version = hfinfo.request.version > 0 ? static_cast(hfinfo.request.version) : @@ -1622,8 +1574,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GETBANS& get_bans, rpc_context context) { - PERF_TIMER(on_get_bans); - auto now = time(nullptr); std::map blocked_hosts = m_p2p.get_blocked_hosts(); for (std::map::const_iterator i = blocked_hosts.begin(); i != blocked_hosts.end(); ++i) @@ -1657,8 +1607,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(BANNED& banned, rpc_context context) { - PERF_TIMER(on_banned); - auto na_parsed = net::get_network_address(banned.request.address, 0); if (!na_parsed) throw rpc_error{ERROR_WRONG_PARAM, "Unsupported host type"}; @@ -1681,10 +1629,7 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SETBANS& set_bans, rpc_context context) { - PERF_TIMER(on_set_bans); - epee::net_utils::network_address na; - // try subnet first if (!set_bans.request.host.empty()) { @@ -1723,8 +1668,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(FLUSH_TRANSACTION_POOL& flush_transaction_pool, rpc_context context) { - PERF_TIMER(on_flush_txpool); - bool failed = false; std::vector txids; if (flush_transaction_pool.request.txids.empty()) @@ -1763,8 +1706,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_OUTPUT_HISTOGRAM& get_output_histogram, rpc_context context) { - PERF_TIMER(on_get_output_histogram); - if (!context.admin && get_output_histogram.request.recent_cutoff > 0 && get_output_histogram.request.recent_cutoff < (uint64_t)time(NULL) - OUTPUT_HISTOGRAM_RECENT_CUTOFF_RESTRICTION) { get_output_histogram.response["status"] = "Recent cutoff is too old"; @@ -1804,7 +1745,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_VERSION& version, rpc_context context) { - PERF_TIMER(on_get_version); version.response["version"] = pack_version(VERSION); version.response["status"] = STATUS_OK; } @@ -1843,7 +1783,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_COINBASE_TX_SUM& get_coinbase_tx_sum, rpc_context context) { - PERF_TIMER(on_get_coinbase_tx_sum); if (auto sums = m_core.get_coinbase_tx_sum(get_coinbase_tx_sum.request.height, get_coinbase_tx_sum.request.count)) { std::tie(get_coinbase_tx_sum.response["emission_amount"], get_coinbase_tx_sum.response["fee_amount"], get_coinbase_tx_sum.response["burn_amount"]) = *sums; get_coinbase_tx_sum.response["status"] = STATUS_OK; @@ -1854,7 +1793,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_BASE_FEE_ESTIMATE& get_base_fee_estimate, rpc_context context) { - PERF_TIMER(on_get_base_fee_estimate); auto fees = m_core.get_blockchain_storage().get_dynamic_base_fee_estimate(get_base_fee_estimate.request.grace_blocks); get_base_fee_estimate.response["fee_per_byte"] = fees.first; get_base_fee_estimate.response["fee_per_output"] = fees.second; @@ -1868,7 +1806,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_ALTERNATE_CHAINS& get_alternate_chains, rpc_context context) { - PERF_TIMER(on_get_alternate_chains); try { std::vector chains; @@ -1901,8 +1838,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_LIMIT& limit, rpc_context context) { - PERF_TIMER(on_get_limit); - limit.response = { {"limit_down", epee::net_utils::connection_basic::get_rate_down_limit()}, {"limit_up", epee::net_utils::connection_basic::get_rate_up_limit()}, @@ -1911,8 +1846,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SET_LIMIT& limit, rpc_context context) { - PERF_TIMER(on_set_limit); - // -1 = reset to default // 0 = do not modify if (limit.request.limit_down != 0) @@ -1931,7 +1864,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(OUT_PEERS& out_peers, rpc_context context) { - PERF_TIMER(on_out_peers); if (out_peers.request.set) m_p2p.change_max_out_public_peers(out_peers.request.out_peers); out_peers.response["status"] = STATUS_OK; @@ -1939,7 +1871,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(IN_PEERS& in_peers, rpc_context context) { - PERF_TIMER(on_in_peers); if (in_peers.request.set) m_p2p.change_max_in_public_peers(in_peers.request.in_peers); in_peers.response["status"] = STATUS_OK; @@ -1947,8 +1878,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(POP_BLOCKS& pop_blocks, rpc_context context) { - PERF_TIMER(on_pop_blocks); - m_core.get_blockchain_storage().pop_blocks(pop_blocks.request.nblocks); pop_blocks.response["height"] = m_core.get_current_blockchain_height(); @@ -1957,8 +1886,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(RELAY_TX& relay_tx, rpc_context context) { - PERF_TIMER(on_relay_tx); - std::string status = ""; for (const auto& txid_hex: relay_tx.request.txids) { @@ -1994,8 +1921,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(SYNC_INFO& sync, rpc_context context) { - PERF_TIMER(on_sync_info); - auto [top_height, top_hash] = m_core.get_blockchain_top(); sync.response["height"] = top_height + 1; // turn top block height into blockchain height if (auto target_height = m_core.get_target_blockchain_height(); target_height > top_height + 1) @@ -2022,7 +1947,6 @@ namespace cryptonote::rpc { return true; }); sync.response["overview"] = block_queue.get_overview(top_height + 1); - sync.response["status"] = STATUS_OK; } @@ -2141,8 +2065,6 @@ namespace cryptonote::rpc { GET_OUTPUT_DISTRIBUTION::response core_rpc_server::invoke(GET_OUTPUT_DISTRIBUTION::request&& req, rpc_context context, bool binary) { GET_OUTPUT_DISTRIBUTION::response res{}; - - PERF_TIMER(on_get_output_distribution); try { // 0 is placeholder for the whole chain @@ -2179,7 +2101,6 @@ namespace cryptonote::rpc { { GET_OUTPUT_DISTRIBUTION_BIN::response res{}; - PERF_TIMER(on_get_output_distribution_bin); if (!req.binary) { @@ -2212,8 +2133,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_QUORUM_STATE& get_quorum_state, rpc_context context) { - PERF_TIMER(on_get_quorum_state); - uint8_t quorum_type = get_quorum_state.request.quorum_type; if (quorum_type >= tools::enum_count && @@ -2368,8 +2287,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_SERVICE_NODE_REGISTRATION_CMD_RAW& get_service_node_registration_cmd_raw, rpc_context context) { - PERF_TIMER(on_get_service_node_registration_cmd_raw); - if (!m_core.service_node()) throw rpc_error{ERROR_WRONG_PARAM, "Daemon has not been started in service node mode, please relaunch with --service-node flag."}; @@ -2393,8 +2310,6 @@ namespace cryptonote::rpc { { GET_SERVICE_NODE_REGISTRATION_CMD::response res{}; - PERF_TIMER(on_get_service_node_registration_cmd); - std::vector args; std::optional height = m_core.get_current_blockchain_height(); @@ -2406,7 +2321,7 @@ namespace cryptonote::rpc { args.emplace_back(std::to_string(service_nodes::percent_to_basis_points(req.operator_cut))); } catch(const std::exception &e) { res.status = "Invalid value: "s + e.what(); - MERROR(res.status); + oxen::log::error(logcat, res.status); return res; } } @@ -2431,7 +2346,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_SERVICE_NODE_BLACKLISTED_KEY_IMAGES& get_service_node_blacklisted_key_images, rpc_context context) { - PERF_TIMER(on_get_service_node_blacklisted_key_images); auto &blacklist = m_core.get_service_node_blacklisted_key_images(); get_service_node_blacklisted_key_images.response["status"] = STATUS_OK; @@ -2441,7 +2355,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_SERVICE_KEYS& get_service_keys, rpc_context context) { - PERF_TIMER(on_get_service_node_key); const auto& keys = m_core.get_service_keys(); if (keys.pub) get_service_keys.response["service_node_pubkey"] = tools::type_to_hex(keys.pub); @@ -2453,7 +2366,6 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_SERVICE_PRIVKEYS& get_service_privkeys, rpc_context context) { - PERF_TIMER(on_get_service_node_key); const auto& keys = m_core.get_service_keys(); if (keys.key != crypto::null_skey) get_service_privkeys.response["service_node_privkey"] = tools::type_to_hex(keys.key.data); @@ -2739,20 +2651,20 @@ namespace cryptonote::rpc { status = fmt::format("Outdated {}. Current: {}.{}.{} Required: {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2], required[0], required[1], required[2]); - MERROR(status); + oxen::log::error(logcat, status); } else if (!ed25519_pubkey.empty() // TODO: once lokinet & ss are always sending this we can remove this empty bypass && ed25519_pubkey != our_ed25519_pubkey) { status = fmt::format("Invalid {} pubkey: expected {}, received {}", name, our_ed25519_pubkey, ed25519_pubkey); - MERROR(status); + oxen::log::error(logcat, status); } else { auto now = std::time(nullptr); auto old = update.exchange(now); bool significant = std::chrono::seconds{now - old} > lifetime; // Print loudly for the first ping after startup/expiry auto msg = fmt::format("Received ping from {} {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2]); if (significant) - MGINFO_GREEN(msg); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), msg)); else - MDEBUG(msg); + oxen::log::debug(logcat, msg); success(significant); status = STATUS_OK; } @@ -2790,9 +2702,7 @@ namespace cryptonote::rpc { //------------------------------------------------------------------------------------------------------------------------------ void core_rpc_server::invoke(GET_STAKING_REQUIREMENT& get_staking_requirement, rpc_context context) { - PERF_TIMER(on_get_staking_requirement); get_staking_requirement.response["height"] = get_staking_requirement.request.height > 0 ? get_staking_requirement.request.height : m_core.get_current_blockchain_height(); - get_staking_requirement.response["staking_requirement"] = service_nodes::get_staking_requirement(nettype(), get_staking_requirement.request.height); get_staking_requirement.response["status"] = STATUS_OK; return; @@ -2878,7 +2788,7 @@ namespace cryptonote::rpc { blobs.clear(); if (!db.get_transactions_blobs(block.second.tx_hashes, blobs)) { - MERROR("Could not query block at requested height: " << cryptonote::get_block_height(block.second)); + oxen::log::error(logcat, "Could not query block at requested height: {}", cryptonote::get_block_height(block.second)); continue; } const auto hard_fork_version = block.second.major_version; @@ -2887,7 +2797,7 @@ namespace cryptonote::rpc { cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(blob, tx)) { - MERROR("tx could not be validated from blob, possibly corrupt blockchain"); + oxen::log::error(logcat, "tx could not be validated from blob, possibly corrupt blockchain"); continue; } if (tx.type == cryptonote::txtype::state_change) @@ -2895,7 +2805,7 @@ namespace cryptonote::rpc { cryptonote::tx_extra_service_node_state_change state_change; if (!cryptonote::get_service_node_state_change_from_tx_extra(tx.extra, state_change, hard_fork_version)) { - LOG_ERROR("Could not get state change from tx, possibly corrupt tx, hf_version "<< static_cast(hard_fork_version)); + oxen::log::error(logcat, "Could not get state change from tx, possibly corrupt tx, hf_version {}", static_cast(hard_fork_version)); continue; } @@ -2917,7 +2827,7 @@ namespace cryptonote::rpc { break; default: - MERROR("Unhandled state in on_get_service_nodes_state_changes"); + oxen::log::error(logcat, "Unhandled state in on_get_service_nodes_state_changes"); break; } } @@ -2941,7 +2851,7 @@ namespace cryptonote::rpc { { crypto::public_key pubkey; if (!tools::hex_to_type(report_peer_status.request.pubkey, pubkey)) { - MERROR("Could not parse public key: " << report_peer_status.request.pubkey); + oxen::log::error(logcat, "Could not parse public key: {}", report_peer_status.request.pubkey); throw rpc_error{ERROR_WRONG_PARAM, "Could not parse public key"}; } diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index f870eed02..938c84acf 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -61,7 +61,6 @@ #include "cryptonote_core/service_node_voting.h" #include "cryptonote_core/service_node_list.h" #include "common/varint.h" -#include "common/perf_timer.h" #include "common/meta.h" #include "common/hex.h" #include "checkpoints/checkpoints.h" diff --git a/src/rpc/http_client.cpp b/src/rpc/http_client.cpp index 5da56c75e..265417277 100644 --- a/src/rpc/http_client.cpp +++ b/src/rpc/http_client.cpp @@ -5,12 +5,14 @@ #include #include #include +#include "logging/oxen_logger.h" +#include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "rpc.http_client" namespace cryptonote::rpc { + static auto logcat = oxen::log::Cat("rpc.http_client"); + http_client_connect_error::http_client_connect_error(const cpr::Error& err, const std::string& prefix) : http_client_error{prefix + err.message}, code{err.code} @@ -169,7 +171,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea { std::shared_lock plock{params_mutex}; std::chrono::steady_clock::time_point start; - if (LOG_ENABLED(Debug)) + if (OXEN_LOG_ENABLED(debug)) start = std::chrono::steady_clock::now(); auto url = base_url + uri; @@ -202,7 +204,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea new_ssl_opts->SetOption(client_cert->second); } if (!verify_https) { - MWARNING("HTTPS certificate verification disabled; this connection is not secure"); + oxen::log::warning(logcat, "HTTPS certificate verification disabled; this connection is not secure"); new_ssl_opts->SetOption(cpr::ssl::VerifyHost(false)); new_ssl_opts->SetOption(cpr::ssl::VerifyPeer(false)); new_ssl_opts->SetOption(cpr::ssl::VerifyStatus(false)); @@ -222,7 +224,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea if (new_proxy) session.SetProxies(*std::move(new_proxy)); if (new_ssl_opts) session.SetSslOptions(*new_ssl_opts); - MDEBUG("Submitting post request to " << url); + oxen::log::debug(logcat, "Submitting post request to {}", url.str()); session.SetUrl(url); session.SetHeader(header); session.SetBody(std::move(body)); @@ -230,10 +232,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea res = session.Post(); } - MDEBUG(url << ": " << - (res.error.code != cpr::ErrorCode::OK ? res.error.message : res.status_line) << - ", sent " << res.uploaded_bytes << " bytes, received " << res.downloaded_bytes << " bytes in " << - tools::friendly_duration(std::chrono::steady_clock::now() - start)); + oxen::log::debug(logcat, "{}: {}, sent {} bytes, received {} bytes in {}", url.str(), (res.error.code != cpr::ErrorCode::OK ? res.error.message : res.status_line), res.uploaded_bytes, res.downloaded_bytes, tools::friendly_duration(std::chrono::steady_clock::now() - start)); bytes_sent += res.uploaded_bytes; bytes_received += res.downloaded_bytes; diff --git a/src/rpc/http_client.h b/src/rpc/http_client.h index 04aca255c..59a7f435e 100644 --- a/src/rpc/http_client.h +++ b/src/rpc/http_client.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include diff --git a/src/rpc/http_server.cpp b/src/rpc/http_server.cpp index a0b9d8b02..144c8edb6 100644 --- a/src/rpc/http_server.cpp +++ b/src/rpc/http_server.cpp @@ -12,11 +12,10 @@ #include "rpc/common/rpc_args.h" #include "version.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon.rpc" - namespace cryptonote::rpc { + static auto logcat = oxen::log::Cat("daemon.rpc"); + const command_line::arg_descriptor> http_server::arg_rpc_public{ "rpc-public", "Specifies an IP:PORT to listen on for public (restricted) RPC requests; can be specified multiple times." @@ -164,7 +163,7 @@ namespace cryptonote::rpc { void http_server::create_rpc_endpoints(uWS::App& http) { auto access_denied = [this](HttpResponse* res, HttpRequest* req) { - MINFO("Forbidden HTTP request for restricted endpoint " << req->getMethod() << " " << req->getUrl()); + oxen::log::info(logcat, "Forbidden HTTP request for restricted endpoint {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_FORBIDDEN); }; @@ -191,7 +190,7 @@ namespace cryptonote::rpc { http.any("/*", [this](HttpResponse* res, HttpRequest* req) { if (m_login && !check_auth(*req, *res)) return; - MINFO("Invalid HTTP request for " << req->getMethod() << " " << req->getUrl()); + oxen::log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_NOT_FOUND); }); } @@ -280,7 +279,7 @@ namespace cryptonote::rpc { if (std::string_view{data.uri}.substr(1) == rpc::GET_TRANSACTION_POOL_HASHES_BIN::names()[0]) return invoke_txpool_hashes_bin(std::move(dataptr)); - const bool time_logging = LOG_ENABLED(Debug); + const bool time_logging = OXEN_LOG_ENABLED(debug); std::chrono::steady_clock::time_point start; if (time_logging) start = std::chrono::steady_clock::now(); @@ -302,19 +301,19 @@ namespace cryptonote::rpc { json_error = 0; } catch (const parse_error& e) { // This isn't really WARNable as it's the client fault; log at info level instead. - MINFO("HTTP RPC request '" << data.uri << "' called with invalid/unparseable data: " << e.what()); + oxen::log::info(logcat, "HTTP RPC request '{}' called with invalid/unparseable data: {}", data.uri, e.what()); json_error = -32602; http_message = "Unable to parse request: "s + e.what(); json_message = "Invalid params"; } catch (const rpc_error& e) { - MWARNING("HTTP RPC request '" << data.uri << "' failed with: " << e.what()); + oxen::log::warning(logcat, "HTTP RPC request '{}' failed with: {}", data.uri, e.what()); json_error = e.code; json_message = e.message; http_message = e.message; } catch (const std::exception& e) { - MWARNING("HTTP RPC request '" << data.uri << "' raised an exception: " << e.what()); + oxen::log::warning(logcat, "HTTP RPC request '{}' raised an exception: {}", data.uri, e.what()); } catch (...) { - MWARNING("HTTP RPC request '" << data.uri << "' raised an unknown exception"); + oxen::log::warning(logcat, "HTTP RPC request '{}' raised an unknown exception", data.uri); } if (json_error != 0) { @@ -330,8 +329,8 @@ namespace cryptonote::rpc { std::string call_duration; if (time_logging) call_duration = " in " + tools::friendly_duration(std::chrono::steady_clock::now() - start); - if (LOG_ENABLED(Info)) - MINFO("HTTP RPC " << data.uri << " [" << data.request.context.remote << "] OK (" << result.size() << " bytes)" << call_duration); + if (OXEN_LOG_ENABLED(info)) + oxen::log::info(logcat, "HTTP RPC {} [{}] OK ({} bytes){}", data.uri, data.request.context.remote, result.size(), call_duration); queue_response(std::move(dataptr), std::move(result)); } @@ -372,12 +371,12 @@ namespace cryptonote::rpc { if (req.tx_pool_checksum == checksum) { // Hashes match, which means we need to defer this request until later. std::lock_guard lock{long_poll_mutex}; - MTRACE("Deferring long poll request from " << data->request.context.remote << ": long polling requested and remote's checksum matches current pool (" << checksum << ")"); + oxen::log::trace(logcat, "Deferring long poll request from {}: long polling requested and remote's checksum matches current pool ({})", data->request.context.remote, checksum); long_pollers.emplace_back(std::move(data), std::chrono::steady_clock::now() + GET_TRANSACTION_POOL_HASHES_BIN::long_poll_timeout); return; } - MTRACE("Ignoring long poll request from " << data->request.context.remote << ": pool hash mismatch (remote: " << req.tx_pool_checksum << ", local: " << checksum << ")"); + oxen::log::trace(logcat, "Ignoring long poll request from {}: pool hash mismatch (remote: {}, local: {})", data->request.context.remote, req.tx_pool_checksum, checksum); } // Either not a long poll request or checksum didn't match @@ -391,7 +390,7 @@ namespace cryptonote::rpc { if (long_pollers.empty()) return; - MDEBUG("TX pool changed; sending tx pool to " << long_pollers.size() << " pending long poll connections"); + oxen::log::debug(logcat, "TX pool changed; sending tx pool to {} pending long poll connections", long_pollers.size()); std::optional body_public, body_admin; @@ -405,7 +404,7 @@ namespace cryptonote::rpc { pool.get_transaction_hashes(pool_hashes, data.request.context.admin, true /*include_only_blinked*/); body = pool_hashes_response(std::move(pool_hashes)); } - MTRACE("Sending deferred long poll pool update to " << data.request.context.remote); + oxen::log::trace(logcat, "Sending deferred long poll pool update to {}", data.request.context.remote); queue_response(std::move(dataptr), *body); } long_pollers.clear(); @@ -434,7 +433,7 @@ namespace cryptonote::rpc { { if (it->second < now) { - MTRACE("Sending long poll timeout to " << it->first->request.context.remote); + oxen::log::trace(logcat, "Sending long poll timeout to {}", it->first->request.context.remote); queue_response(std::move(it->first), long_poll_timeout_body); it = long_pollers.erase(it); count++; @@ -444,9 +443,9 @@ namespace cryptonote::rpc { } if (count > 0) - MDEBUG("Timed out " << count << " long poll connections"); + oxen::log::debug(logcat, "Timed out {} long poll connections", count); else - MTRACE("None of " << long_pollers.size() << " established long poll connections reached timeout"); + oxen::log::trace(logcat, "None of {} established long poll connections reached timeout", long_pollers.size()); } } // anonymous namespace @@ -463,7 +462,7 @@ namespace cryptonote::rpc { request.context.source = rpc_source::http; request.context.remote = get_remote_address(res); handle_cors(req, data->extra_headers); - MTRACE("Received " << req.getMethod() << " " << req.getUrl() << " request from " << request.context.remote); + oxen::log::trace(logcat, "Received {} {} request from {}", req.getMethod(), req.getUrl(), request.context.remote); res.onAborted([data] { data->aborted = true; }); res.onData([data=std::move(data)](std::string_view d, bool done) mutable { @@ -514,7 +513,7 @@ namespace cryptonote::rpc { try { method = &jsonrpc["method"].get_ref(); } catch (const std::exception& e) { - MINFO("Invalid JSON RPC request from " << data->request.context.remote << ": no 'method' in request"); + oxen::log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", data->request.context.remote); return data->jsonrpc_error_response(data->res, -32600, "Invalid Request", data->jsonrpc_id); } @@ -522,17 +521,17 @@ namespace cryptonote::rpc { it != rpc_commands.end() && !it->second->is_binary) data->call = it->second.get(); else { - MINFO("Invalid JSON RPC request from " << data->request.context.remote << ": method '" << *method << "' is invalid"); + oxen::log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", data->request.context.remote, *method); return data->jsonrpc_error_response(data->res, -32601, "Method not found", data->jsonrpc_id); } if (restricted && !data->call->is_public) { - MWARNING("Invalid JSON RPC request from " << data->request.context.remote << ": method '" << *method << "' is restricted"); + oxen::log::warning(logcat, "Invalid JSON RPC request from {}: method '{}' is restricted", data->request.context.remote, *method); return data->jsonrpc_error_response(data->res, 403, "Forbidden; this command is not available over public RPC", data->jsonrpc_id); } - MDEBUG("Incoming JSON RPC request for " << *method << " from " << data->request.context.remote); + oxen::log::debug(logcat, "Incoming JSON RPC request for {} from {}", *method, data->request.context.remote); if (auto it = jsonrpc.find("params"); it != jsonrpc.end()) data->request.body = *it; @@ -572,7 +571,7 @@ namespace cryptonote::rpc { if (!m_sent_shutdown) { - MTRACE("initiating shutdown"); + oxen::log::trace(logcat, "initiating shutdown"); if (!m_sent_startup) { m_startup_promise.set_value(false); @@ -581,7 +580,7 @@ namespace cryptonote::rpc { else if (!m_listen_socks.empty()) { loop_defer([this] { - MTRACE("closing " << m_listen_socks.size() << " listening sockets"); + oxen::log::trace(logcat, "closing {} listening sockets", m_listen_socks.size()); for (auto* s : m_listen_socks) us_listen_socket_close(/*ssl=*/false, s); m_listen_socks.clear(); @@ -590,7 +589,7 @@ namespace cryptonote::rpc { { // Destroy any pending long poll connections as well - MTRACE("closing pending long poll requests"); + oxen::log::trace(logcat, "closing pending long poll requests"); std::lock_guard lock{long_poll_mutex}; for (auto it = long_pollers.begin(); it != long_pollers.end(); ) { @@ -606,10 +605,10 @@ namespace cryptonote::rpc { m_sent_shutdown = true; } - MTRACE("joining rpc thread"); + oxen::log::trace(logcat, "joining rpc thread"); if (join) m_rpc_thread.join(); - MTRACE("done shutdown"); + oxen::log::trace(logcat, "done shutdown"); } http_server::~http_server() diff --git a/src/rpc/lmq_server.cpp b/src/rpc/lmq_server.cpp index b28ee7722..b1024d7de 100644 --- a/src/rpc/lmq_server.cpp +++ b/src/rpc/lmq_server.cpp @@ -5,18 +5,18 @@ #include "oxenmq/oxenmq.h" #include #include "oxenc/bt.h" +#include "oxenmq/fmt.h" // FIXME: Rename this to omq_server.{h,cpp} -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "daemon.rpc" - namespace cryptonote { namespace rpc { using oxenmq::AuthLevel; namespace { +static auto logcat = oxen::log::Cat("daemon.rpc"); + // TODO: all of this --lmq-blah options really should be renamed to --omq-blah, but then we *also* // need some sort of backwards compatibility shim, and that is a nuissance. @@ -112,21 +112,21 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog // the quorumnet listener set up in cryptonote_core). for (const auto &addr : command_line::get_arg(vm, arg_omq_public)) { check_omq_listen_addr(addr); - MGINFO("LMQ listening on " << addr << " (public unencrypted)"); + oxen::log::info(logcat, "LMQ listening on {} (public unencrypted)", addr); omq.listen_plain(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::basic); }); } for (const auto &addr : command_line::get_arg(vm, arg_omq_curve_public)) { check_omq_listen_addr(addr); - MGINFO("LMQ listening on " << addr << " (public curve)"); + oxen::log::info(logcat, "LMQ listening on {} (public curve)", addr); omq.listen_curve(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::basic); }); } for (const auto &addr : command_line::get_arg(vm, arg_omq_curve)) { check_omq_listen_addr(addr); - MGINFO("LMQ listening on " << addr << " (curve restricted)"); + oxen::log::info(logcat, "LMQ listening on {} (curve restricted)", addr); omq.listen_curve(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::denied); }); } @@ -148,7 +148,7 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog } for (const auto &addr : locals) { check_omq_listen_addr(addr); - MGINFO("LMQ listening on " << addr << " (unauthenticated local admin)"); + oxen::log::info(logcat, "OMQ listening on {} (unauthenticated local admin)", addr); omq.listen_plain(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::admin); }); } @@ -227,19 +227,17 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog // warnings that get generated deep inside epee, for example when passing a string or // number instead of a JSON object. If you want to find some, `grep number2 epee` (for // real). - MINFO("LMQ RPC request '" << (call.is_public ? "rpc." : "admin.") << name << "' called with invalid/unparseable data: " << e.what()); + oxen::log::info(logcat, "LMQ RPC request '{}{}' called with invalid/unparseable data: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); m.send_reply(LMQ_BAD_REQUEST, "Unable to parse request: "s + e.what()); return; } catch (const rpc_error& e) { - MWARNING("LMQ RPC request '" << (call.is_public ? "rpc." : "admin.") << name << "' failed with: " << e.what()); + oxen::log::warning(logcat, "LMQ RPC request '{}{}' failed with: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); m.send_reply(LMQ_ERROR, e.what()); return; } catch (const std::exception& e) { - MWARNING("LMQ RPC request '" << (call.is_public ? "rpc." : "admin.") << name << "' " - "raised an exception: " << e.what()); + oxen::log::warning(logcat, "LMQ RPC request '{}{}' raised an exception: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); } catch (...) { - MWARNING("LMQ RPC request '" << (call.is_public ? "rpc." : "admin.") << name << "' " - "raised an unknown exception"); + oxen::log::warning(logcat, "LMQ RPC request '{}{}' raised an unknown exception", (call.is_public ? "rpc." : "admin."), name); } // Don't include the exception message in case it contains something that we don't want go // back to the user. If we want to support it eventually we could add some sort of @@ -302,7 +300,7 @@ static void send_notifies(Mutex& mutex, Subs& subs, const char* desc, Call call) for (auto& conn : remove) { auto it = subs.find(conn); if (it != subs.end() && it->second.expiry < now /* recheck: client might have resubscribed in between locks */) { - MDEBUG("Removing " << conn << " from " << desc << " subscriptions: subscription timed out"); + oxen::log::debug(logcat, "Removing {} from {} subscriptions: subscription timed out", conn, desc); subs.erase(it); } } @@ -536,13 +534,13 @@ void omq_rpc::on_mempool_sub_request(oxenmq::Message& m) if (!result.second) { result.first->second.expiry = expiry; if (result.first->second.type == sub_type) { - MTRACE("Renewed mempool subscription request from conn id " << m.conn << " @ " << m.remote); + oxen::log::trace(logcat, "Renewed mempool subscription request from conn id {}@{}", m.conn, m.remote); m.send_reply("ALREADY"); return; } result.first->second.type = sub_type; } - MDEBUG("New " << (sub_type == mempool_sub_type::blink ? "blink" : "all") << " mempool subscription request from conn " << m.conn << " @ " << m.remote); + oxen::log::debug(logcat, "New {} mempool subscription request from conn {}@{}", (sub_type == mempool_sub_type::blink ? "blink" : "all"), m.conn, m.remote); m.send_reply("OK"); } } @@ -565,10 +563,10 @@ void omq_rpc::on_block_sub_request(oxenmq::Message& m) auto result = block_subs_.emplace(m.conn, block_sub{expiry}); if (!result.second) { result.first->second.expiry = expiry; - MTRACE("Renewed block subscription request from conn id " << m.conn << " @ " << m.remote); + oxen::log::trace(logcat, "Renewed block subscription request from conn id {}@{}", m.conn, m.remote); m.send_reply("ALREADY"); } else { - MDEBUG("New block subscription request from conn " << m.conn << " @ " << m.remote); + oxen::log::debug(logcat, "New block subscription request from conn {}@{}", m.conn, m.remote); m.send_reply("OK"); } } diff --git a/src/simplewallet/CMakeLists.txt b/src/simplewallet/CMakeLists.txt index fa1c35c73..12477977b 100644 --- a/src/simplewallet/CMakeLists.txt +++ b/src/simplewallet/CMakeLists.txt @@ -41,4 +41,5 @@ target_link_libraries(simplewallet filesystem icu Boost::thread + logging extra) diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index d602428dc..60239ccd2 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -56,6 +56,7 @@ #include #include #include +#include #include "epee/console_handler.h" #include "common/i18n.h" #include "common/command_line.h" @@ -96,11 +97,6 @@ namespace po = boost::program_options; namespace string_tools = epee::string_tools; using sw = cryptonote::simple_wallet; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.simplewallet" - -#define EXTENDED_LOGS_FILE "wallet_details.log" - #define OUTPUT_EXPORT_FILE_MAGIC "Loki output export\003" #define LOCK_IDLE_SCOPE() \ @@ -127,6 +123,9 @@ using sw = cryptonote::simple_wallet; namespace { + + static auto logcat = oxen::log::Cat("wallet.simplewallet"); + const auto arg_wallet_file = wallet_args::arg_wallet_file(); const command_line::arg_descriptor arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to "), ""}; const command_line::arg_descriptor arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to "), ""}; @@ -293,7 +292,7 @@ namespace auto pwd_container = tools::password_container::prompt(false, prompt, false); if (!pwd_container) { - MERROR("Failed to read secure line"); + oxen::log::error(logcat, "Failed to read secure line"); return ""; } @@ -342,22 +341,22 @@ namespace tools::scoped_message_writer success_msg_writer(bool color = false) { - return tools::scoped_message_writer(color ? epee::console_color_green : epee::console_color_default, false, std::string{}, el::Level::Info); + return tools::scoped_message_writer(color ? fmt::terminal_color::green : fmt::terminal_color::white, std::string{}, spdlog::level::info); } - tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false) + tools::scoped_message_writer message_writer(fmt::terminal_color color = fmt::terminal_color::white) { - return tools::scoped_message_writer(color, bright); + return tools::scoped_message_writer(color); } tools::scoped_message_writer fail_msg_writer() { - return tools::scoped_message_writer(epee::console_color_red, true, sw::tr("Error: "), el::Level::Error); + return tools::scoped_message_writer(fmt::terminal_color::red, sw::tr("Error: "), spdlog::level::err); } tools::scoped_message_writer warn_msg_writer() { - return tools::scoped_message_writer(epee::console_color_red, true, sw::tr("Warning: "), el::Level::Error); + return tools::scoped_message_writer(fmt::terminal_color::red, sw::tr("Warning: "), spdlog::level::warn); } bool parse_bool(const std::string& s, bool& result) @@ -453,7 +452,7 @@ namespace } catch (const tools::error::wallet_rpc_error& e) { - LOG_ERROR("RPC error: " << e.to_string()); + oxen::log::error(logcat, "RPC error: {}", e.to_string()); fail_msg_writer() << sw::tr("RPC error: ") << e.what(); } catch (const tools::error::get_outs_error &e) @@ -462,26 +461,22 @@ namespace } catch (const tools::error::not_enough_unlocked_money& e) { - LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") % - print_money(e.available()) % - print_money(e.tx_amount())); + oxen::log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::not_enough_money& e) { - LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") % - print_money(e.available()) % - print_money(e.tx_amount())); + oxen::log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::tx_not_possible& e) { - LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") % - print_money(e.available()) % - print_money(e.tx_amount() + e.fee()) % - print_money(e.tx_amount()) % + oxen::log::warning(logcat, "not enough money to transfer, available only {}, transaction amount {} = {} + {} (fee)", + print_money(e.available()), + print_money(e.tx_amount() + e.fee()), + print_money(e.tx_amount()), print_money(e.fee())); fail_msg_writer() << sw::tr("Failed to find a way to create transactions. This is usually due to dust which is so small it cannot pay for itself in fees, or trying to send more money than the unlocked balance, or not leaving enough for fees"); warn_of_possible_attack = false; @@ -525,23 +520,23 @@ namespace } catch (const tools::error::transfer_error& e) { - LOG_ERROR("unknown transfer error: " << e.to_string()); + oxen::log::error(logcat, "unknown transfer error: {}", e.to_string()); fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what(); } catch (const tools::error::multisig_export_needed& e) { - LOG_ERROR("Multisig error: " << e.to_string()); + oxen::log::error(logcat, "Multisig error: {}", e.to_string()); fail_msg_writer() << sw::tr("Multisig error: ") << e.what(); warn_of_possible_attack = false; } catch (const tools::error::wallet_internal_error& e) { - LOG_ERROR("internal error: " << e.to_string()); + oxen::log::error(logcat, "internal error: {}", e.to_string()); fail_msg_writer() << sw::tr("internal error: ") << e.what(); } catch (const std::exception& e) { - LOG_ERROR("unexpected error: " << e.what()); + oxen::log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << sw::tr("unexpected error: ") << e.what(); } @@ -1187,7 +1182,7 @@ bool simple_wallet::export_multisig_main(const std::vector &args EN } catch (const std::exception &e) { - LOG_ERROR("Error exporting multisig info: " << e.what()); + oxen::log::error(logcat, "Error exporting multisig info: {}", e.what()); fail_msg_writer() << tr("Error exporting multisig info: ") << e.what(); return false; } @@ -1493,7 +1488,7 @@ bool simple_wallet::submit_multisig_main(const std::vector &args EN } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return false; } @@ -1567,12 +1562,12 @@ bool simple_wallet::export_raw_multisig(const std::vector &args) } catch (const std::exception& e) { - LOG_ERROR("unexpected error: " << e.what()); + oxen::log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { - LOG_ERROR("Unknown error"); + oxen::log::error(logcat, "Unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -2121,13 +2116,13 @@ bool simple_wallet::cold_sign_tx(const std::vector& { std::vector tx_aux; - message_writer(epee::console_color_white, false) << tr("Please confirm the transaction on the device"); + message_writer(fmt::terminal_color::white) << tr("Please confirm the transaction on the device"); m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux); if (accept_func && !accept_func(exported_txs)) { - MERROR("Transactions rejected by callback"); + oxen::log::error(logcat, "Transactions rejected by callback"); return false; } @@ -2512,7 +2507,7 @@ bool simple_wallet::set_device_name(const std::vector &args/* = std } } catch(const std::exception & e){ - MWARNING("Device reconnect failed: " << e.what()); + oxen::log::warning(logcat, "Device reconnect failed: {}", e.what()); fail_msg_writer() << tr("Device reconnect failed: ") << e.what(); } @@ -3243,29 +3238,21 @@ bool simple_wallet::set_log(const std::vector &args) } if(!args.empty()) { - uint16_t level = 0; - if(epee::string_tools::get_xtype_from_string(level, args[0])) - { - if(4 < level) - { - fail_msg_writer() << boost::format(tr("wrong number range, use: %s")) % USAGE_SET_LOG; - return true; - } - mlog_set_log_level(level); - } - else - { - mlog_set_log(args[0].c_str()); + auto log_level = oxen::logging::parse_level(args[0]); + if (log_level.has_value()) + oxen::log::reset_level(*log_level); + else { + oxen::logging::process_categories_string(args[0]); } } - success_msg_writer() << "New log categories: " << mlog_get_categories(); + success_msg_writer() << "Log categories updated"; return true; } //---------------------------------------------------------------------------------------------------- bool simple_wallet::ask_wallet_create_if_needed() { - LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started"); + oxen::log::trace(logcat, "simple_wallet::ask_wallet_create_if_needed() started"); fs::path wallet_path; std::string confirm_creation; bool wallet_name_valid = false; @@ -3273,7 +3260,7 @@ bool simple_wallet::ask_wallet_create_if_needed() bool wallet_file_exists; do{ - LOG_PRINT_L3("User asked to specify wallet file name."); + oxen::log::trace(logcat, "User asked to specify wallet file name."); wallet_path = fs::u8path(input_line( tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n" "Wallet file name (or Ctrl-C to quit)" : @@ -3282,7 +3269,7 @@ bool simple_wallet::ask_wallet_create_if_needed() )); if(std::cin.eof()) { - LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); + oxen::log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } if(wallet_path.empty()) @@ -3293,9 +3280,8 @@ bool simple_wallet::ask_wallet_create_if_needed() else { tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists); - LOG_PRINT_L3("wallet_path: " << wallet_path); - LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha - << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); + oxen::log::trace(logcat, "wallet_path: {}", wallet_path); + oxen::log::trace(logcat, "keys_file_exists: {} wallet_file_exists: {}", keys_file_exists, wallet_file_exists); if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring)) { @@ -3329,7 +3315,7 @@ bool simple_wallet::ask_wallet_create_if_needed() confirm_creation = input_line(prompt, true); if(std::cin.eof()) { - LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); + oxen::log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } ok = command_line::is_yes(confirm_creation); @@ -3344,7 +3330,7 @@ bool simple_wallet::ask_wallet_create_if_needed() } } while(!wallet_name_valid); - LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()"); + oxen::log::error(logcat, "Failed out of do-while loop in ask_wallet_create_if_needed()"); return false; } @@ -3422,7 +3408,7 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) if (auto deprecations = tools::wallet2::has_deprecated_options(vm); !deprecations.empty()) { for (auto msg : deprecations) - message_writer(epee::console_color_red, true) << tr("Warning: option is deprecated and will be removed in the future: ") << msg; + message_writer(fmt::terminal_color::red) << tr("Warning: option is deprecated and will be removed in the future: ") << msg; } const bool testnet = tools::wallet2::has_testnet_option(vm); @@ -4000,13 +3986,13 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) if (!m_wallet->is_trusted_daemon()) { - message_writer(epee::console_color_yellow, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str(); - message_writer(epee::console_color_yellow, true) << tr("Using a third party daemon can be detrimental to your security and privacy"); + message_writer(fmt::terminal_color::yellow) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str(); + message_writer(fmt::terminal_color::yellow) << tr("Using a third party daemon can be detrimental to your security and privacy"); bool ssl = false; if (m_wallet->check_connection(nullptr, &ssl) && !ssl) - message_writer(epee::console_color_yellow, true) << tr("Using your own without SSL exposes your RPC traffic to monitoring"); - message_writer(epee::console_color_yellow, true) << tr("You are strongly encouraged to connect to the Oxen network using your own daemon"); - message_writer(epee::console_color_yellow, true) << tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon"); + message_writer(fmt::terminal_color::yellow) << tr("Using your own without SSL exposes your RPC traffic to monitoring"); + message_writer(fmt::terminal_color::yellow) << tr("You are strongly encouraged to connect to the Oxen network using your own daemon"); + message_writer(fmt::terminal_color::yellow) << tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon"); message_writer(); nlohmann::json res; @@ -4017,7 +4003,7 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) } std::string err = interpret_rpc_response(true, res["status"]); if (err.empty() && res["untrusted"].get()) - message_writer(epee::console_color_yellow, true) << tr("Moreover, a daemon is also less secure when running in bootstrap mode"); + message_writer(fmt::terminal_color::yellow) << tr("Moreover, a daemon is also less secure when running in bootstrap mode"); } if (m_wallet->get_ring_database().empty()) @@ -4026,7 +4012,7 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) m_wallet->callback(this); if (welcome) - message_writer(epee::console_color_yellow, true) << tr("If you are new to Oxen, type \"welcome\" for a brief overview."); + message_writer(fmt::terminal_color::yellow) << tr("If you are new to Oxen, type \"welcome\" for a brief overview."); m_last_activity_time = time(NULL); return true; @@ -4214,7 +4200,7 @@ std::optional simple_wallet::new_wallet(const boost::prog if (was_deprecated_wallet) { // The user had used an older version of the wallet with old style mnemonics. - message_writer(epee::console_color_green, false) << "\n" << tr("You had been using " + message_writer(fmt::terminal_color::green) << "\n" << tr("You had been using " "a deprecated version of the wallet. Please use the new seed that we provide.\n"); } mnemonic_language = get_mnemonic_language(); @@ -4230,7 +4216,7 @@ std::optional simple_wallet::new_wallet(const boost::prog try { recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file); - message_writer(epee::console_color_white, true) << tr("Generated new wallet: ") + message_writer(fmt::terminal_color::white) << tr("Generated new wallet: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); rdln::suspend_readline pause_readline; std::cout << tr("View key: "); @@ -4304,7 +4290,7 @@ std::optional simple_wallet::new_wallet(const boost::prog { m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file); } - message_writer(epee::console_color_white, true) << tr("Generated new wallet: ") + message_writer(fmt::terminal_color::white) << tr("Generated new wallet: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } catch (const std::exception& e) @@ -4350,14 +4336,14 @@ std::optional simple_wallet::new_device_wallet(const boos if (!command_line::is_arg_defaulted(vm, arg_create_hwdev_txt)) create_hwdev_txt = command_line::get_arg(vm, arg_create_hwdev_txt); m_wallet->device_derivation_path(device_derivation_path); - message_writer(epee::console_color_white, true) << tr("Connecting to hardware device"); + message_writer(fmt::terminal_color::white) << tr("Connecting to hardware device"); message_writer() << tr("Your hardware device will ask for permission to export your wallet view key.\n" "This is optional, but will significantly improve wallet syncing speed. Your\n" "spend key (needed to spend funds) does not leave the device."); m_wallet->restore_from_device( m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file, - std::move(create_hwdev_txt), [](const std::string& msg) { message_writer(epee::console_color_green, true) << msg; }); - message_writer(epee::console_color_white, true) << tr("Finished setting up wallet from hw device"); + std::move(create_hwdev_txt), [](const std::string& msg) { message_writer(fmt::terminal_color::green) << msg; }); + message_writer(fmt::terminal_color::white) << tr("Finished setting up wallet from hw device"); } catch (const std::exception& e) { @@ -4411,7 +4397,7 @@ std::optional simple_wallet::new_wallet(const boost::prog fail_msg_writer() << tr("failed to generate new mutlisig wallet"); return {}; } - message_writer(epee::console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total + message_writer(fmt::terminal_color::white) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); } catch (const std::exception& e) @@ -4463,10 +4449,10 @@ std::optional simple_wallet::open_wallet(const boost::pro prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str(); else prefix = tr("Opened wallet"); - message_writer(epee::console_color_green, true) << + message_writer(fmt::terminal_color::green) << prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype()); if (m_wallet->get_account().get_device().is_hardware_device()) { - message_writer(epee::console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name(); + message_writer(fmt::terminal_color::white) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name(); } // If the wallet file is deprecated, we should ask for mnemonic language again and store // everything in the new format. @@ -4480,7 +4466,7 @@ std::optional simple_wallet::open_wallet(const boost::pro } if (is_deterministic) { - message_writer(epee::console_color_green, false) << "\n" << tr("You had been using " + message_writer(fmt::terminal_color::green) << "\n" << tr("You had been using " "a deprecated version of the wallet. Please proceed to upgrade your wallet.\n"); std::string mnemonic_language = get_mnemonic_language(); if (mnemonic_language.empty()) @@ -4495,7 +4481,7 @@ std::optional simple_wallet::open_wallet(const boost::pro } else { - message_writer(epee::console_color_green, false) << "\n" << tr("You had been using " + message_writer(fmt::terminal_color::green) << "\n" << tr("You had been using " "a deprecated version of the wallet. Your wallet file format is being upgraded now.\n"); m_wallet->rewrite(m_wallet_file, password); } @@ -4722,7 +4708,7 @@ bool simple_wallet::set_daemon(const std::vector& args) } else if (is_local) { - MINFO(tr("Daemon is local, assuming trusted")); + oxen::log::info(logcat, tr("Daemon is local, assuming trusted")); m_wallet->set_trusted_daemon(true); } success_msg_writer() << "Daemon set to " << daemon_url << ", " << tr(m_wallet->is_trusted_daemon() ? "trusted" : "untrusted"); @@ -4766,7 +4752,7 @@ void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, if (m_locked) return; { - auto m = message_writer(epee::console_color_green, false); + auto m = message_writer(fmt::terminal_color::green); m << "\r"; if (height == 0 && blink) m << tr("Blink, "); @@ -4803,7 +4789,7 @@ void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, crypto::hash payment_id = crypto::null_hash; if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) - message_writer(epee::console_color_red, false) << + message_writer(fmt::terminal_color::red) << tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead."); } if (unlock_time && !cryptonote::is_coinbase(tx)) @@ -4825,7 +4811,7 @@ void simple_wallet::on_money_spent(uint64_t height, const crypto::hash &txid, co { if (m_locked) return; - message_writer(epee::console_color_magenta, false) << "\r" << + message_writer(fmt::terminal_color::magenta) << "\r" << tr("Height ") << height << ", " << tr("txid ") << txid << ", " << tr("spent ") << print_money(amount) << ", " << @@ -4856,7 +4842,7 @@ std::optional simple_wallet::on_get_password(const char * m_password_asked_on_height = m_wallet->get_blockchain_current_height(); m_password_asked_on_checksum = tx_pool_checksum; - message_writer(epee::console_color_red, false) << boost::format(tr("Password needed %s")) % reason; + message_writer(fmt::terminal_color::red) << boost::format(tr("Password needed %s")) % reason; m_cmd_binder.print_prompt(); } return std::nullopt; @@ -4869,7 +4855,7 @@ std::optional simple_wallet::on_get_password(const char * auto pwd_container = tools::password_container::prompt(false, msg.c_str()); if (!pwd_container) { - MERROR("Failed to read password"); + oxen::log::error(logcat, "Failed to read password"); return std::nullopt; } @@ -4878,7 +4864,7 @@ std::optional simple_wallet::on_get_password(const char * //---------------------------------------------------------------------------------------------------- void simple_wallet::on_device_button_request(uint64_t code) { - message_writer(epee::console_color_white, false) << tr("Device requires attention"); + message_writer(fmt::terminal_color::white) << tr("Device requires attention"); } //---------------------------------------------------------------------------------------------------- std::optional simple_wallet::on_device_pin_request() @@ -4896,7 +4882,7 @@ std::optional simple_wallet::on_device_passphrase_request std::string accepted = input_line(tr( "Device asks for passphrase. Do you want to enter the passphrase on device (Y) (or on the host (N))?")); if (std::cin.eof() || command_line::is_yes(accepted)) { - message_writer(epee::console_color_white, true) << tr("Please enter the device passphrase on the device"); + message_writer(fmt::terminal_color::white) << tr("Please enter the device passphrase on the device"); return std::nullopt; } } @@ -4916,7 +4902,7 @@ void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_ const uint64_t dh = m_wallet->get_daemon_blockchain_height(err); if (err.empty() && rfbh > dh) { - message_writer(epee::console_color_yellow, false) << tr("The wallet's refresh-from-block-height setting is higher than the daemon's height: this may mean your wallet will skip over transactions"); + message_writer(fmt::terminal_color::yellow) << tr("The wallet's refresh-from-block-height setting is higher than the daemon's height: this may mean your wallet will skip over transactions"); } // Key image sync after the first refresh @@ -4933,7 +4919,7 @@ void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_ std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): ")); if (std::cin.eof() || !command_line::is_yes(accepted)) { - message_writer(epee::console_color_red, false) << tr("hw_key_images_sync skipped. Run command manually before a transfer."); + message_writer(fmt::terminal_color::red) << tr("hw_key_images_sync skipped. Run command manually before a transfer."); return; } @@ -5002,27 +4988,27 @@ bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bo } catch (const tools::error::wallet_rpc_error& e) { - LOG_ERROR("RPC error: " << e.to_string()); + oxen::log::error(logcat, "RPC error: {}", e.to_string()); ss << tr("RPC error: ") << e.what(); } catch (const tools::error::refresh_error& e) { - LOG_ERROR("refresh error: " << e.to_string()); + oxen::log::error(logcat, "refresh error: {}", e.to_string()); ss << tr("refresh error: ") << e.what(); } catch (const tools::error::wallet_internal_error& e) { - LOG_ERROR("internal error: " << e.to_string()); + oxen::log::error(logcat, "internal error: {}", e.to_string()); ss << tr("internal error: ") << e.what(); } catch (const std::exception& e) { - LOG_ERROR("unexpected error: " << e.what()); + oxen::log::error(logcat, "unexpected error: {}", e.what()); ss << tr("unexpected error: ") << e.what(); } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); ss << tr("unknown error"); } @@ -5230,7 +5216,7 @@ bool simple_wallet::show_incoming_transfers(const std::vector& args const std::pair line = show_outputs_line(heights, blockchain_height, idx); extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second; } - message_writer(td.m_spent ? epee::console_color_magenta : epee::console_color_green, false) << + message_writer(td.m_spent ? fmt::terminal_color::magenta : fmt::terminal_color::green) << boost::format("%21s%8s%12s%8s%16u%68s%16u%s") % print_money(td.amount()) % (td.m_spent ? tr("T") : tr("F")) % @@ -5374,17 +5360,17 @@ bool simple_wallet::rescan_spent(const std::vector &args) } catch (const tools::error::wallet_rpc_error& e) { - LOG_ERROR("RPC error: " << e.to_string()); + oxen::log::error(logcat, "RPC error: {}", e.to_string()); fail_msg_writer() << tr("RPC error: ") << e.what(); } catch (const std::exception& e) { - LOG_ERROR("unexpected error: " << e.what()); + oxen::log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -5814,7 +5800,7 @@ bool simple_wallet::confirm_and_send_tx(std::vector &args_) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -6217,7 +6203,7 @@ bool simple_wallet::stake(const std::vector &args_) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } } @@ -6286,7 +6272,7 @@ bool simple_wallet::request_stake_unlock(const std::vector &args_) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -6702,7 +6688,7 @@ bool simple_wallet::ons_buy_mapping(std::vector args) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -6781,7 +6767,7 @@ bool simple_wallet::ons_renew_mapping(std::vector args) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -6837,7 +6823,7 @@ bool simple_wallet::ons_update_mapping(std::vector args) auto enc_hex = response[0]["encrypted_value"].get(); if (!oxenc::is_hex(enc_hex) || enc_hex.size() > 2*ons::mapping_value::BUFFER_SIZE) { - LOG_ERROR("invalid ONS data returned from oxend"); + oxen::log::error(logcat, "invalid ONS data returned from oxend"); fail_msg_writer() << tr("invalid ONS data returned from oxend"); return true; } @@ -6909,7 +6895,7 @@ bool simple_wallet::ons_update_mapping(std::vector args) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -7304,7 +7290,7 @@ bool simple_wallet::sweep_unmixable(const std::vector &args_) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -7427,7 +7413,7 @@ bool simple_wallet::sweep_main_internal(sweep_type_t sweep_type, std::vector &args_) } catch (...) { - LOG_ERROR("unknown error"); + oxen::log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -8011,7 +7997,7 @@ bool simple_wallet::submit_transfer(const std::vector &args_) } catch (...) { - LOG_ERROR("Unknown error"); + oxen::log::error(logcat, "Unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -8625,11 +8611,11 @@ bool simple_wallet::show_transfers(const std::vector &args_) rdln::suspend_readline pause_readline; - auto color = epee::console_color_white; + auto color = fmt::terminal_color::white; auto formatter = boost::format("%8.8s %6.6s %8.8s %12.12s %16.16s %20.20s %64s %16s %14.14s %s %s - %s"); - message_writer(color, true) << formatter + message_writer(color) << formatter % "Height" % "Type" % "Locked" @@ -8650,19 +8636,19 @@ bool simple_wallet::show_transfers(const std::vector &args_) { switch (transfer.pay_type) { - case wallet::pay_type::in: color = epee::console_color_green; break; - case wallet::pay_type::out: color = epee::console_color_yellow; break; - case wallet::pay_type::miner: color = epee::console_color_cyan; break; - case wallet::pay_type::governance: color = epee::console_color_cyan; break; - case wallet::pay_type::stake: color = epee::console_color_blue; break; - case wallet::pay_type::ons: color = epee::console_color_blue; break; - case wallet::pay_type::service_node: color = epee::console_color_cyan; break; - default: color = epee::console_color_magenta; break; + case wallet::pay_type::in: color = fmt::terminal_color::green; break; + case wallet::pay_type::out: color = fmt::terminal_color::yellow; break; + case wallet::pay_type::miner: color = fmt::terminal_color::cyan; break; + case wallet::pay_type::governance: color = fmt::terminal_color::cyan; break; + case wallet::pay_type::stake: color = fmt::terminal_color::blue; break; + case wallet::pay_type::ons: color = fmt::terminal_color::blue; break; + case wallet::pay_type::service_node: color = fmt::terminal_color::cyan; break; + default: color = fmt::terminal_color::magenta; break; } } if (transfer.type == "failed") - color = epee::console_color_red; + color = fmt::terminal_color::red; std::string destinations = "-"; if (!transfer.destinations.empty()) @@ -8691,7 +8677,7 @@ bool simple_wallet::show_transfers(const std::vector &args_) std::transform(transfer.subaddr_indices.begin(), transfer.subaddr_indices.end(), std::back_inserter(subaddr_minors), [](const auto& index) { return index.minor; }); - message_writer(color, false) << formatter + message_writer(color) << formatter % (transfer.type.size() ? transfer.type : (transfer.height == 0 && transfer.blink_mempool) ? "blink" : std::to_string(transfer.height)) % wallet::pay_type_string(transfer.pay_type) % transfer.lock_msg @@ -9089,7 +9075,7 @@ bool simple_wallet::run() } }); - message_writer(epee::console_color_green, false) << "Background refresh thread started"; + message_writer(fmt::terminal_color::green) << "Background refresh thread started"; return m_cmd_binder.run_handling([this]() {return get_prompt(); }, ""); } @@ -9866,7 +9852,7 @@ bool simple_wallet::export_key_images(const std::vector &args) } catch (const std::exception &e) { - LOG_ERROR("Error exporting key images: " << e.what()); + oxen::log::error(logcat, "Error exporting key images: {}", e.what()); fail_msg_writer() << "Error exporting key images: " << e.what(); return true; } @@ -9933,7 +9919,7 @@ bool simple_wallet::hw_key_images_sync(const std::vector &args) void simple_wallet::key_images_sync_intern(){ try { - message_writer(epee::console_color_white, false) << tr("Please confirm the key image sync on the device"); + message_writer(fmt::terminal_color::white) << tr("Please confirm the key image sync on the device"); uint64_t spent = 0, unspent = 0; uint64_t height = m_wallet->cold_key_image_sync(spent, unspent); @@ -10023,7 +10009,7 @@ bool simple_wallet::export_outputs(const std::vector &args) } catch (const std::exception &e) { - LOG_ERROR("Error exporting outputs: " << e.what()); + oxen::log::error(logcat, "Error exporting outputs: {}", e.what()); fail_msg_writer() << "Error exporting outputs: " << e.what(); return true; } @@ -10344,7 +10330,7 @@ int main(int argc, char* argv[]) desc_params, hidden_params, positional_options, - [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; }, + [](const std::string &s){ tools::scoped_message_writer(fmt::terminal_color::white) << s; }, "oxen-wallet-cli.log" ); diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index 970e038bd..485597b25 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -55,15 +55,14 @@ #include "common/password.h" #include "crypto/crypto.h" // for definition of crypto::secret_key -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.simplewallet" - /*! * \namespace cryptonote * \brief Holds cryptonote related classes and helpers. */ namespace cryptonote { + static auto logcat = oxen::log::Cat("wallet.simplewallet"); + enum class Transfer { Normal, Locked @@ -398,7 +397,7 @@ namespace cryptonote } else { - LOG_ERROR("Failed to get current blockchain height: " << err); + oxen::log::error(logcat, "Failed to get current blockchain height: {}", err); } } diff --git a/src/sqlitedb/CMakeLists.txt b/src/sqlitedb/CMakeLists.txt index f674d7eaf..d4bf0736e 100644 --- a/src/sqlitedb/CMakeLists.txt +++ b/src/sqlitedb/CMakeLists.txt @@ -9,5 +9,6 @@ target_link_libraries(sqlitedb common PRIVATE SQLite::SQLite3 + logging fmt::fmt extra) diff --git a/src/sqlitedb/database.cpp b/src/sqlitedb/database.cpp index d07ccd3d0..06ce0a7d7 100644 --- a/src/sqlitedb/database.cpp +++ b/src/sqlitedb/database.cpp @@ -5,6 +5,7 @@ namespace db { + static auto logcat = oxen::log::Cat("db.sqlite"); std::string multi_in_query(std::string_view prefix, size_t count, std::string_view suffix) { @@ -45,20 +46,20 @@ namespace db { // Don't fail on these because we can still work even if they fail if (int rc = db.tryExec("PRAGMA journal_mode = WAL"); rc != SQLITE_OK) - MERROR("Failed to set journal mode to WAL: {}" << sqlite3_errstr(rc)); + oxen::log::error(logcat, "Failed to set journal mode to WAL: {}{}", sqlite3_errstr(rc)); if (int rc = db.tryExec("PRAGMA synchronous = NORMAL"); rc != SQLITE_OK) - MERROR("Failed to set synchronous mode to NORMAL: {}" << sqlite3_errstr(rc)); + oxen::log::error(logcat, "Failed to set synchronous mode to NORMAL: {}{}", sqlite3_errstr(rc)); - if (int rc = db.tryExec("PRAGMA foreign_keys = ON"); - rc != SQLITE_OK) { - auto m = fmt::format("Failed to enable foreign keys constraints: {}", sqlite3_errstr(rc)); - MERROR(m); - throw std::runtime_error{m}; + if (int rc = db.tryExec("PRAGMA foreign_keys = ON"); rc != SQLITE_OK) + { + oxen::log::error(logcat, "Failed to enable foreign keys constraints: {}", sqlite3_errstr(rc)); + throw std::runtime_error{"Foreign key constrains required"}; } int fk_enabled = db.execAndGet("PRAGMA foreign_keys").getInt(); - if (fk_enabled != 1) { - MERROR("Failed to enable foreign key constraints; perhaps this sqlite3 is compiled without it?"); + if (fk_enabled != 1) + { + oxen::log::error(logcat, "Failed to enable foreign key constraints; perhaps this sqlite3 is compiled without it?"); throw std::runtime_error{"Foreign key support is required"}; } diff --git a/src/sqlitedb/database.hpp b/src/sqlitedb/database.hpp index 630908cec..79b68f53a 100644 --- a/src/sqlitedb/database.hpp +++ b/src/sqlitedb/database.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include "logging/oxen_logger.h" #include @@ -138,7 +139,7 @@ namespace db { if (result) { - MERROR("Expected single-row result, got multiple rows from {}" << st.getQuery()); + oxen::log::error(oxen::log::Cat("db.sqlite"), "Expected single-row result, got multiple rows from {}", st.getQuery()); throw std::runtime_error{"DB error: expected single-row result, got multiple rows"}; } result = get(st); @@ -157,7 +158,7 @@ namespace db auto maybe_result = exec_and_maybe_get(st, bind...); if (!maybe_result) { - MERROR("Expected single-row result, got no rows from {}" << st.getQuery()); + oxen::log::error(oxen::log::Cat("db.sqlite"), "Expected single-row result, got no rows from {}", st.getQuery()); throw std::runtime_error{"DB error: expected single-row result, got no rows"}; } return *std::move(maybe_result); diff --git a/src/wallet/CMakeLists.txt b/src/wallet/CMakeLists.txt index a2fb7e89e..772e48284 100644 --- a/src/wallet/CMakeLists.txt +++ b/src/wallet/CMakeLists.txt @@ -60,6 +60,7 @@ target_link_libraries(wallet Boost::serialization filesystem Boost::thread + logging PRIVATE extra) @@ -78,6 +79,7 @@ target_link_libraries(wallet_rpc_server wallet daemonizer Boost::program_options + logging extra) diff --git a/src/wallet/api/CMakeLists.txt b/src/wallet/api/CMakeLists.txt index 9b6db68d0..3d1d8a4b6 100644 --- a/src/wallet/api/CMakeLists.txt +++ b/src/wallet/api/CMakeLists.txt @@ -137,7 +137,6 @@ if (STATIC AND BUILD_STATIC_DEPS) CURL::libcurl oxenmq::oxenmq lmdb - easylogging randomx uSockets cpr diff --git a/src/wallet/api/address_book.cpp b/src/wallet/api/address_book.cpp index 00ce99162..cd29a1452 100644 --- a/src/wallet/api/address_book.cpp +++ b/src/wallet/api/address_book.cpp @@ -70,7 +70,7 @@ bool AddressBookImpl::addRow(const std::string &dst_addr, const std::string &des EXPORT void AddressBookImpl::refresh() { - LOG_PRINT_L2("Refreshing addressbook"); + oxen::log::debug(logcat, "Refreshing addressbook"); clearRows(); @@ -93,7 +93,7 @@ void AddressBookImpl::refresh() EXPORT bool AddressBookImpl::deleteRow(std::size_t rowId) { - LOG_PRINT_L2("Deleting address book row " << rowId); + oxen::log::debug(logcat, "Deleting address book row {}", rowId); bool r = m_wallet->wallet()->delete_address_book_row(rowId); if (r) refresh(); diff --git a/src/wallet/api/pending_transaction.cpp b/src/wallet/api/pending_transaction.cpp index 9a23ee3c7..b4ea73e21 100644 --- a/src/wallet/api/pending_transaction.cpp +++ b/src/wallet/api/pending_transaction.cpp @@ -83,7 +83,7 @@ EXPORT bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, bool blink) { - LOG_PRINT_L3("m_pending_tx size: " << m_pending_tx.size()); + oxen::log::trace(logcat, "m_pending_tx size: {}", m_pending_tx.size()); auto filename = fs::u8path(filename_); @@ -93,7 +93,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, if (!filename.empty()) { if (std::error_code ec_ignore; fs::exists(filename, ec_ignore) && !overwrite){ m_status = {Status_Error, tr("Attempting to save transaction to file, but specified file(s) exist. Exiting to not risk overwriting. File:") + filename.u8string()}; - LOG_ERROR(m_status.second); + oxen::log::error(m_status.second); return false; } bool r = w->save_tx(m_pending_tx, filename); @@ -147,7 +147,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, m_status = {Status_Error, std::string(tr("Unknown exception: ")) + e.what()}; } catch (...) { m_status = {Status_Error, tr("Unhandled exception")}; - LOG_ERROR(m_status.second); + oxen::log::error(m_status.second); } return good(); diff --git a/src/wallet/api/stake_unlock_result.cpp b/src/wallet/api/stake_unlock_result.cpp index d7af1f92e..1489230c5 100644 --- a/src/wallet/api/stake_unlock_result.cpp +++ b/src/wallet/api/stake_unlock_result.cpp @@ -13,7 +13,7 @@ StakeUnlockResultImpl::StakeUnlockResultImpl(WalletImpl& w, tools::wallet2::requ EXPORT StakeUnlockResultImpl::~StakeUnlockResultImpl() { - LOG_PRINT_L3("Stake Unlock Result Deleted"); + oxen::log::trace(logcat, "Stake Unlock Result Deleted"); } //---------------------------------------------------------------------------------------------------- diff --git a/src/wallet/api/subaddress.cpp b/src/wallet/api/subaddress.cpp index 44fa23723..93ee81b17 100644 --- a/src/wallet/api/subaddress.cpp +++ b/src/wallet/api/subaddress.cpp @@ -60,14 +60,14 @@ void SubaddressImpl::setLabel(uint32_t accountIndex, uint32_t addressIndex, cons } catch (const std::exception& e) { - LOG_ERROR("setLabel: " << e.what()); + oxen::log::error(logcat, "setLabel: {}", e.what()); } } EXPORT void SubaddressImpl::refresh(uint32_t accountIndex) { - LOG_PRINT_L2("Refreshing subaddress"); + oxen::log::debug(logcat, "Refreshing subaddress"); clearRows(); auto w = m_wallet->wallet(); diff --git a/src/wallet/api/subaddress_account.cpp b/src/wallet/api/subaddress_account.cpp index 67922a34c..6152f2213 100644 --- a/src/wallet/api/subaddress_account.cpp +++ b/src/wallet/api/subaddress_account.cpp @@ -60,7 +60,7 @@ void SubaddressAccountImpl::setLabel(uint32_t accountIndex, const std::string &l EXPORT void SubaddressAccountImpl::refresh() { - LOG_PRINT_L2("Refreshing subaddress account"); + oxen::log::debug(logcat, "Refreshing subaddress account"); clearRows(); auto w = m_wallet->wallet(); diff --git a/src/wallet/api/transaction_history.cpp b/src/wallet/api/transaction_history.cpp index 9eb924631..7ce8d364b 100644 --- a/src/wallet/api/transaction_history.cpp +++ b/src/wallet/api/transaction_history.cpp @@ -259,7 +259,7 @@ void TransactionHistoryImpl::refresh() ti->m_is_stake = pd.m_type == wallet::pay_type::stake; m_history.push_back(ti); - LOG_PRINT_L1(__FUNCTION__ << ": Unconfirmed payment found " << pd.m_amount); + oxen::log::info(logcat, "{}: Unconfirmed payment found {}", __FUNCTION__, pd.m_amount); } } diff --git a/src/wallet/api/unsigned_transaction.cpp b/src/wallet/api/unsigned_transaction.cpp index e4df814c7..b8951507a 100644 --- a/src/wallet/api/unsigned_transaction.cpp +++ b/src/wallet/api/unsigned_transaction.cpp @@ -55,7 +55,7 @@ UnsignedTransactionImpl::UnsignedTransactionImpl(WalletImpl &wallet) EXPORT UnsignedTransactionImpl::~UnsignedTransactionImpl() { - LOG_PRINT_L3("Unsigned tx deleted"); + oxen::log::trace(logcat, "Unsigned tx deleted"); } EXPORT @@ -288,7 +288,7 @@ std::vector UnsignedTransactionImpl::recipientAddress() const std::vector result; for (const auto &utx: m_unsigned_tx_set.txes) { if (utx.dests.empty()) { - MERROR("empty destinations, skipped"); + oxen::log::error(logcat, "empty destinations, skipped"); continue; } result.push_back(cryptonote::get_account_address_as_str(m_wallet.m_wallet_ptr->nettype(), utx.dests[0].is_subaddress, utx.dests[0].addr)); diff --git a/src/wallet/api/utils.cpp b/src/wallet/api/utils.cpp index b9502a89c..542a1f194 100644 --- a/src/wallet/api/utils.cpp +++ b/src/wallet/api/utils.cpp @@ -41,7 +41,7 @@ bool isAddressLocal(const std::string &address) try { return tools::is_local_address(address); } catch (const std::exception &e) { - MERROR("error: " << e.what()); + oxen::log::error(logcat, "error: {}", e.what()); return false; } } diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index 9dca92fd9..6cd48ed87 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -45,6 +45,7 @@ #include "common_defines.h" #include "common/util.h" #include "common/fs.h" +#include "logging/oxen_logger.h" #include "mnemonics/electrum-words.h" #include "mnemonics/english.h" @@ -55,11 +56,10 @@ using namespace cryptonote; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "WalletAPI" - namespace Wallet { + static auto logcat = oxen::log::Cat("WalletAPI"); + namespace { static const int DEFAULT_REFRESH_INTERVAL_MILLIS = 1000 * 10; // limit maximum refresh interval as one minute @@ -143,7 +143,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback // created or the restore height specified when wallet was recovered // if(height >= m_wallet->m_wallet_ptr->get_refresh_from_block_height() || height % 1000 == 0) { - // LOG_PRINT_L3(__FUNCTION__ << ": new block. height: " << height); + // oxen::log::trace(logcat, "{}: new block. height: {}", __FUNCTION__, height); if (m_listener) { m_listener->newBlock(height); } @@ -155,7 +155,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { std::string tx_hash = tools::type_to_hex(txid); - LOG_PRINT_L3(__FUNCTION__ << ": money received." << (blink ? "blink: " : "height: ") << height + oxen::log::trace(logcat, "{}: money received.{}{}", __FUNCTION__, (blink ? "blink: " : "height: "), height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -172,7 +172,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback std::string tx_hash = tools::type_to_hex(txid); - LOG_PRINT_L3(__FUNCTION__ << ": unconfirmed money received. height: " << height + oxen::log::trace(logcat, "{}: unconfirmed money received. height: {}", __FUNCTION__, height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -193,7 +193,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { // TODO; std::string tx_hash = tools::type_to_hex(txid); - LOG_PRINT_L3(__FUNCTION__ << ": money spent. height: " << height + oxen::log::trace(logcat, "{}: money spent. height: {}", __FUNCTION__, height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -416,22 +416,22 @@ void Wallet::init(const char *argv0, const char *default_log_base_name, const st EXPORT void Wallet::debug(const std::string &category, const std::string &str) { - MCDEBUG(category.empty() ? OXEN_DEFAULT_LOG_CATEGORY : category.c_str(), str); + oxen::log::debug(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT void Wallet::info(const std::string &category, const std::string &str) { - MCINFO(category.empty() ? OXEN_DEFAULT_LOG_CATEGORY : category.c_str(), str); + oxen::log::info(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT void Wallet::warning(const std::string &category, const std::string &str) { - MCWARNING(category.empty() ? OXEN_DEFAULT_LOG_CATEGORY : category.c_str(), str); + oxen::log::warning(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT void Wallet::error(const std::string &category, const std::string &str) { - MCERROR(category.empty() ? OXEN_DEFAULT_LOG_CATEGORY : category.c_str(), str); + oxenlog::error(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } ///////////////////////// WalletImpl implementation //////////////////////// @@ -481,7 +481,7 @@ EXPORT WalletImpl::~WalletImpl() { - LOG_PRINT_L1(__FUNCTION__); + oxen::log::info(__FUNCTION__); m_wallet_ptr->callback(nullptr); // Stop refresh and long poll threads stopRefresh(); @@ -496,7 +496,7 @@ WalletImpl::~WalletImpl() m_wallet2Callback->getListener()->onSetWallet(nullptr); } - LOG_PRINT_L1(__FUNCTION__ << " finished"); + oxen::log::info(logcat, "{} finished", __FUNCTION__); } EXPORT @@ -510,15 +510,15 @@ bool WalletImpl::create(std::string_view path_, const std::string &password, con bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - LOG_PRINT_L3("wallet_path: " << path); - LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha + oxen::log::trace(logcat, "wallet_path: {}", path); + oxen::log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting."; - LOG_ERROR(error); + oxen::log::error(error); setStatusCritical(error); return false; } @@ -531,7 +531,7 @@ bool WalletImpl::create(std::string_view path_, const std::string &password, con m_password = password; clearStatus(); } catch (const std::exception &e) { - LOG_ERROR("Error creating wallet: " << e.what()); + oxen::log::error(logcat, "Error creating wallet: {}", e.what()); setStatusCritical(e.what()); return false; } @@ -553,14 +553,14 @@ bool WalletImpl::createWatchOnly(std::string_view path_, const std::string &pass bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - LOG_PRINT_L3("wallet_path: " << path); - LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha + oxen::log::trace(logcat, "wallet_path: {}", path); + oxen::log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate view only wallet, but specified file(s) exist. Exiting to not risk overwriting."; - LOG_ERROR(error); + oxen::log::error(error); setStatusError(error); return false; } @@ -599,7 +599,7 @@ bool WalletImpl::createWatchOnly(std::string_view path_, const std::string &pass view_wallet->import_key_images(key_images.second, key_images.first, spent, unspent, false); clearStatus(); } catch (const std::exception &e) { - LOG_ERROR("Error creating view only wallet: " << e.what()); + oxen::log::error(logcat, "Error creating view only wallet: {}", e.what()); setStatusError(e.what()); return false; } @@ -680,16 +680,16 @@ bool WalletImpl::recoverFromKeysWithPassword(std::string_view path_, auto w = wallet(); if (has_spendkey && has_viewkey) { w->generate(path, password, info.address, spendkey, viewkey); - LOG_PRINT_L1("Generated new wallet from spend key and view key"); + oxen::log::info(logcat, "Generated new wallet from spend key and view key"); } if(!has_spendkey && has_viewkey) { w->generate(path, password, info.address, viewkey); - LOG_PRINT_L1("Generated new view only wallet from keys"); + oxen::log::info(logcat, "Generated new view only wallet from keys"); } if(has_spendkey && !has_viewkey) { w->generate(path, password, spendkey, true, false); setSeedLanguage(language); - LOG_PRINT_L1("Generated deterministic wallet from spend key with seed language: " + language); + oxen::log::info(logcat, "Generated deterministic wallet from spend key with seed language: " + language); } } @@ -711,7 +711,7 @@ bool WalletImpl::recoverFromDevice(std::string_view path_, const std::string &pa try { w->restore_from_device(path, password, device_name); - LOG_PRINT_L1("Generated new wallet from device: " + device_name); + oxen::log::info(logcat, "Generated new wallet from device: " + device_name); } catch (const std::exception& e) { setStatusError(std::string(tr("failed to generate new wallet: ")) + e.what()); @@ -749,7 +749,7 @@ bool WalletImpl::open(std::string_view path_, const std::string &password) m_password = password; } catch (const std::exception &e) { - LOG_ERROR("Error opening wallet: " << e.what()); + oxen::log::error(logcat, "Error opening wallet: {}", e.what()); setStatusCritical(e.what()); } return good(); @@ -761,7 +761,7 @@ bool WalletImpl::recover(std::string_view path_, const std::string &password, co auto path = fs::u8path(path_); clearStatus(); if (seed.empty()) { - LOG_ERROR("Electrum seed is empty"); + oxen::log::error(logcat, "Electrum seed is empty"); setStatusError(tr("Electrum seed is empty")); return false; } @@ -798,7 +798,7 @@ bool WalletImpl::close(bool store) { bool result = false; - LOG_PRINT_L1("closing wallet..."); + oxen::log::info(logcat, "closing wallet..."); try { auto w = wallet(); if (store) { @@ -807,18 +807,18 @@ bool WalletImpl::close(bool store) if (status().first != Status_Critical) w->store(); else - LOG_ERROR("Status_Critical - not saving wallet"); - LOG_PRINT_L1("wallet::store done"); + oxen::log::error(logcat, "Status_Critical - not saving wallet"); + oxen::log::info(logcat, "wallet::store done"); } - LOG_PRINT_L1("Calling wallet::stop..."); + oxen::log::info(logcat, "Calling wallet::stop..."); w->stop(); - LOG_PRINT_L1("wallet::stop done"); + oxen::log::info(logcat, "wallet::stop done"); w->deinit(); result = true; clearStatus(); } catch (const std::exception &e) { setStatusCritical(e.what()); - LOG_ERROR("Error closing wallet: " << e.what()); + oxen::log::error(logcat, "Error closing wallet: {}", e.what()); } return result; } @@ -961,7 +961,7 @@ bool WalletImpl::store(std::string_view path_) wallet()->store_to(path, m_password); } } catch (const std::exception &e) { - LOG_ERROR("Error saving wallet: " << e.what()); + oxen::log::error(logcat, "Error saving wallet: {}", e.what()); setStatusError(e.what()); return false; } @@ -1019,7 +1019,7 @@ bool WalletImpl::lightWalletImportWalletRequest(std::string &payment_id, uint64_ } catch (const std::exception &e) { - LOG_ERROR("Error sending import wallet request: " << e.what()); + oxen::log::error(logcat, "Error sending import wallet request: {}", e.what()); setStatusError(e.what()); return false; } @@ -1139,7 +1139,7 @@ uint64_t WalletImpl::daemonBlockChainHeight() const std::string err; uint64_t result = w->get_daemon_blockchain_height(err); if (!err.empty()) { - LOG_ERROR(__FUNCTION__ << ": " << err); + oxen::log::error(logcat, "{}: {}", __FUNCTION__, err); result = 0; setStatusError(err); } else { @@ -1165,7 +1165,7 @@ uint64_t WalletImpl::daemonBlockChainTargetHeight() const std::string err; uint64_t result = w->get_daemon_blockchain_target_height(err); if (!err.empty()) { - LOG_ERROR(__FUNCTION__ << ": " << err); + oxen::log::error(logcat, "{}: {}", __FUNCTION__, err); result = 0; setStatusError(err); } else { @@ -1205,7 +1205,7 @@ bool WalletImpl::refresh() EXPORT void WalletImpl::refreshAsync() { - LOG_PRINT_L3(__FUNCTION__ << ": Refreshing asynchronously.."); + oxen::log::trace(logcat, "{}: Refreshing asynchronously..", __FUNCTION__); clearStatus(); m_refreshCV.notify_one(); } @@ -1236,7 +1236,7 @@ EXPORT void WalletImpl::setAutoRefreshInterval(int millis) { if (millis > MAX_REFRESH_INTERVAL_MILLIS) { - LOG_ERROR(__FUNCTION__<< ": invalid refresh interval " << millis + oxen::log::error(logcat, "{}: invalid refresh interval {}", __FUNCTION__, millis << " ms, maximum allowed is " << MAX_REFRESH_INTERVAL_MILLIS << " ms"); m_refreshIntervalMillis = MAX_REFRESH_INTERVAL_MILLIS; } else { @@ -1313,7 +1313,7 @@ bool WalletImpl::exportKeyImages(std::string_view filename_) } catch (const std::exception &e) { - LOG_ERROR("Error exporting key images: " << e.what()); + oxen::log::error(logcat, "Error exporting key images: {}", e.what()); setStatusError(e.what()); return false; } @@ -1332,12 +1332,12 @@ bool WalletImpl::importKeyImages(std::string_view filename_) { uint64_t spent = 0, unspent = 0; uint64_t height = wallet()->import_key_images_from_file(filename, spent, unspent); - LOG_PRINT_L2("Signed key images imported to height " << height << ", " + oxen::log::debug(logcat, "Signed key images imported to height {}, ", height << print_money(spent) << " spent, " << print_money(unspent) << " unspent"); } catch (const std::exception &e) { - LOG_ERROR("Error exporting key images: " << e.what()); + oxen::log::error(logcat, "Error exporting key images: {}", e.what()); setStatusError(std::string(tr("Failed to import key images: ")) + e.what()); return false; } @@ -1374,7 +1374,7 @@ std::string WalletImpl::getSubaddressLabel(uint32_t accountIndex, uint32_t addre } catch (const std::exception &e) { - LOG_ERROR("Error getting subaddress label: " << e.what()); + oxen::log::error(logcat, "Error getting subaddress label: {}", e.what()); setStatusError(std::string(tr("Failed to get subaddress label: ")) + e.what()); return ""; } @@ -1388,7 +1388,7 @@ void WalletImpl::setSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex } catch (const std::exception &e) { - LOG_ERROR("Error setting subaddress label: " << e.what()); + oxen::log::error(logcat, "Error setting subaddress label: {}", e.what()); setStatusError(std::string(tr("Failed to set subaddress label: ")) + e.what()); } } @@ -1411,7 +1411,7 @@ std::string WalletImpl::getMultisigInfo() const { clearStatus(); return wallet()->get_multisig_info(); } catch (const std::exception& e) { - LOG_ERROR("Error on generating multisig info: " << e.what()); + oxen::log::error(logcat, "Error on generating multisig info: {}", e.what()); setStatusError(std::string(tr("Failed to get multisig info: ")) + e.what()); } @@ -1429,7 +1429,7 @@ std::string WalletImpl::makeMultisig(const std::vector& info, uint3 return w->make_multisig(epee::wipeable_string(m_password), info, threshold); } catch (const std::exception& e) { - LOG_ERROR("Error on making multisig wallet: " << e.what()); + oxen::log::error(logcat, "Error on making multisig wallet: {}", e.what()); setStatusError(std::string(tr("Failed to make multisig: ")) + e.what()); } @@ -1445,7 +1445,7 @@ std::string WalletImpl::exchangeMultisigKeys(const std::vector &inf return w->exchange_multisig_keys(epee::wipeable_string(m_password), info); } catch (const std::exception& e) { - LOG_ERROR("Error on exchanging multisig keys: " << e.what()); + oxen::log::error(logcat, "Error on exchanging multisig keys: {}", e.what()); setStatusError(std::string(tr("Failed to make multisig: ")) + e.what()); } @@ -1465,7 +1465,7 @@ bool WalletImpl::finalizeMultisig(const std::vector& extraMultisigI setStatusError(tr("Failed to finalize multisig wallet creation")); } catch (const std::exception& e) { - LOG_ERROR("Error on finalizing multisig wallet creation: " << e.what()); + oxen::log::error(logcat, "Error on finalizing multisig wallet creation: {}", e.what()); setStatusError(std::string(tr("Failed to finalize multisig wallet creation: ")) + e.what()); } @@ -1483,7 +1483,7 @@ bool WalletImpl::exportMultisigImages(std::string& images) { images = oxenc::to_hex(blob); return true; } catch (const std::exception& e) { - LOG_ERROR("Error on exporting multisig images: " << e.what()); + oxen::log::error(logcat, "Error on exporting multisig images: {}", e.what()); setStatusError(std::string(tr("Failed to export multisig images: ")) + e.what()); } @@ -1502,7 +1502,7 @@ size_t WalletImpl::importMultisigImages(const std::vector& images) for (const auto& image: images) { if (!oxenc::is_hex(image)) { - LOG_ERROR("Failed to parse imported multisig images"); + oxen::log::error(logcat, "Failed to parse imported multisig images"); setStatusError(tr("Failed to parse imported multisig images")); return 0; } @@ -1512,7 +1512,7 @@ size_t WalletImpl::importMultisigImages(const std::vector& images) return w->import_multisig(blobs); } catch (const std::exception& e) { - LOG_ERROR("Error on importing multisig images: " << e.what()); + oxen::log::error(logcat, "Error on importing multisig images: {}", e.what()); setStatusError(std::string(tr("Failed to import multisig images: ")) + e.what()); } @@ -1528,7 +1528,7 @@ bool WalletImpl::hasMultisigPartialKeyImages() const { return w->has_multisig_partial_key_images(); } catch (const std::exception& e) { - LOG_ERROR("Error on checking for partial multisig key images: " << e.what()); + oxen::log::error(logcat, "Error on checking for partial multisig key images: {}", e.what()); setStatusError(std::string(tr("Failed to check for partial multisig key images: ")) + e.what()); } @@ -1555,7 +1555,7 @@ PendingTransaction* WalletImpl::restoreMultisigTransaction(const std::string& si return ptx; } catch (std::exception& e) { - LOG_ERROR("Error on restoring multisig transaction: " << e.what()); + oxen::log::error(logcat, "Error on restoring multisig transaction: {}", e.what()); setStatusError(std::string(tr("Failed to restore multisig transaction: ")) + e.what()); } @@ -2272,14 +2272,14 @@ bool WalletImpl::setStatus(int status, std::string message) const EXPORT void WalletImpl::refreshThreadFunc() { - LOG_PRINT_L3(__FUNCTION__ << ": starting refresh thread"); + oxen::log::trace(logcat, "{}: starting refresh thread", __FUNCTION__); while (true) { std::unique_lock lock{m_refreshMutex}; if (m_refreshThreadDone) { break; } - LOG_PRINT_L3(__FUNCTION__ << ": waiting for refresh..."); + oxen::log::trace(logcat, "{}: waiting for refresh...", __FUNCTION__); // if auto refresh enabled, we wait for the "m_refreshIntervalSeconds" interval. // if not - we wait forever if (std::chrono::milliseconds max_delay{m_refreshIntervalMillis.load()}; @@ -2289,17 +2289,17 @@ void WalletImpl::refreshThreadFunc() m_refreshCV.wait(lock); } - LOG_PRINT_L3(__FUNCTION__ << ": refresh lock acquired..."); - LOG_PRINT_L3(__FUNCTION__ << ": m_refreshEnabled: " << m_refreshEnabled); + oxen::log::trace(logcat, "{}: refresh lock acquired...", __FUNCTION__); + oxen::log::trace(logcat, "{}: m_refreshEnabled: {}", __FUNCTION__, m_refreshEnabled); auto st = status(); - LOG_PRINT_L3(__FUNCTION__ << ": m_status: " << st.first << ": " << st.second); - LOG_PRINT_L3(__FUNCTION__ << ": m_refreshShouldRescan: " << m_refreshShouldRescan); + oxen::log::trace(logcat, "{}: m_status: {}: {}", __FUNCTION__, st.first, st.second); + oxen::log::trace(logcat, "{}: m_refreshShouldRescan: {}", __FUNCTION__, m_refreshShouldRescan); if (m_refreshEnabled) { - LOG_PRINT_L3(__FUNCTION__ << ": refreshing..."); + oxen::log::trace(logcat, "{}: refreshing...", __FUNCTION__); doRefresh(); } } - LOG_PRINT_L3(__FUNCTION__ << ": refresh thread stopped"); + oxen::log::trace(logcat, "{}: refresh thread stopped", __FUNCTION__); } EXPORT @@ -2310,7 +2310,7 @@ void WalletImpl::doRefresh() std::lock_guard guard{m_refreshMutex2}; do { try { - LOG_PRINT_L3(__FUNCTION__ << ": doRefresh, rescan = "<find_and_save_rings(false); } else { - LOG_PRINT_L3(__FUNCTION__ << ": skipping refresh - daemon is not synced"); + oxen::log::trace(logcat, "{}: skipping refresh - daemon is not synced", __FUNCTION__); } } catch (const std::exception &e) { setStatusError(e.what()); @@ -2352,7 +2352,7 @@ EXPORT void WalletImpl::startRefresh() { if (!m_refreshEnabled) { - LOG_PRINT_L2(__FUNCTION__ << ": refresh started/resumed..."); + oxen::log::debug(logcat, "{}: refresh started/resumed...", __FUNCTION__); m_refreshEnabled = true; m_refreshCV.notify_one(); } @@ -2374,7 +2374,7 @@ void WalletImpl::stopRefresh() EXPORT void WalletImpl::pauseRefresh() { - LOG_PRINT_L2(__FUNCTION__ << ": refresh paused..."); + oxen::log::debug(logcat, "{}: refresh paused...", __FUNCTION__); // TODO synchronize access if (!m_refreshThreadDone) { m_refreshEnabled = false; @@ -2420,12 +2420,12 @@ bool WalletImpl::doInit(const std::string &daemon_address, uint64_t upper_transa // If daemon isn't synced a calculated block height will be used instead //TODO: Handle light wallet scenario where block height = 0. if (isNewWallet() && daemonSynced()) { - LOG_PRINT_L2(__FUNCTION__ << ":New Wallet - fast refresh until " << daemonBlockChainHeight()); + oxen::log::debug(logcat, "{}:New Wallet - fast refresh until {}", __FUNCTION__, daemonBlockChainHeight()); w->set_refresh_from_block_height(daemonBlockChainHeight()); } if (m_rebuildWalletCache) - LOG_PRINT_L2(__FUNCTION__ << ": Rebuilding wallet cache, fast refresh until block " << w->get_refresh_from_block_height()); + oxen::log::debug(logcat, "{}: Rebuilding wallet cache, fast refresh until block {}", __FUNCTION__, w->get_refresh_from_block_height()); if (Utils::isAddressLocal(daemon_address)) { this->setTrustedDaemon(true); @@ -2460,7 +2460,7 @@ bool WalletImpl::rescanSpent() try { wallet()->rescan_spent(); } catch (const std::exception &e) { - LOG_ERROR(__FUNCTION__ << " error: " << e.what()); + oxen::log::error(logcat, "{} error: {}", __FUNCTION__, e.what()); setStatusError(e.what()); return false; } @@ -2680,7 +2680,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (!tools::hex_to_type(sn_key_str, sn_key)) { error_msg = "Failed to parse service node pubkey"; - LOG_ERROR(error_msg); + oxen::log::error(error_msg); transaction->setError(error_msg); return transaction; } @@ -2689,7 +2689,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (stake_result.status != tools::wallet2::stake_result_status::success) { error_msg = "Failed to create a stake transaction: " + stake_result.msg; - LOG_ERROR(error_msg); + oxen::log::error(error_msg); transaction->setError(error_msg); return transaction; } diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 96fb58ced..3c70e76e6 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -39,11 +39,10 @@ #include "version.h" #include "common/fs.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "WalletAPI" - namespace Wallet { + static auto logcat = oxen::log::Cat("WalletAPI"); + EXPORT Wallet* WalletManagerImpl::createWallet(std::string_view path, const std::string &password, const std::string &language, NetworkType nettype, uint64_t kdf_rounds) @@ -191,13 +190,13 @@ std::vector WalletManagerImpl::findWallets(std::string_view path_) continue; auto filename = p.path(); - LOG_PRINT_L3("Checking filename: " << filename); + oxen::log::trace(logcat, "Checking filename: {}", filename); if (filename.extension() == ".keys") { // if keys file found, checking if there's wallet file itself filename.replace_extension(); if (fs::exists(filename)) { - LOG_PRINT_L3("Found wallet: " << filename); + oxen::log::trace(logcat, "Found wallet: {}", filename); result.push_back(filename.u8string()); } } diff --git a/src/wallet/message_store.cpp b/src/wallet/message_store.cpp index 6a7d76243..d374651c6 100644 --- a/src/wallet/message_store.cpp +++ b/src/wallet/message_store.cpp @@ -40,12 +40,9 @@ #include "common/file.h" #include "epee/string_tools.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.mms" - namespace mms { + static auto logcat = oxen::log::Cat("wallet.mms"); message_store::message_store() { @@ -442,7 +439,7 @@ bool message_store::get_signer_index_by_monero_address(const cryptonote::account return true; } } - MWARNING("No authorized signer with Monero address " << account_address_to_string(monero_address)); + oxen::log::warning(logcat, "No authorized signer with Monero address {}", account_address_to_string(monero_address)); return false; } @@ -457,7 +454,7 @@ bool message_store::get_signer_index_by_label(const std::string label, uint32_t return true; } } - MWARNING("No authorized signer with label " << label); + oxen::log::warning(logcat, "No authorized signer with label {}", label); return false; } @@ -540,7 +537,7 @@ size_t message_store::add_message(const multisig_wallet_state &state, // Save for every new message right away (at least while in beta) save(state); - MINFO(boost::format("Added %s message %s for signer %s of type %s") + oxen::log::info(boost::format("Added %s message %s for signer %s of type %s") % message_direction_to_string(direction) % m.id % signer_index % message_type_to_string(type)); return m_messages.size() - 1; } @@ -556,7 +553,7 @@ bool message_store::get_message_index_by_id(uint32_t id, size_t &index) const return true; } } - MWARNING("No message found with an id of " << id); + oxen::log::warning(logcat, "No message found with an id of {}", id); return false; } @@ -722,7 +719,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: { // Simply do nothing if the file is not there; allows e.g. easy recovery // from problems with the MMS by deleting the file - MINFO("No message store file found: " << filename); + oxen::log::info(logcat, "No message store file found: {}", filename); return; } @@ -740,7 +737,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: } catch (const std::exception &e) { - MERROR("MMS file " << filename << " has bad structure : " << e.what()); + oxen::log::error(logcat, "MMS file {} has bad structure : {}", filename, e.what()); THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename); } @@ -759,7 +756,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: } catch (const std::exception &e) { - MERROR("MMS file " << filename << " has bad structure: " << e.what()); + oxen::log::error(logcat, "MMS file {} has bad structure: {}", filename, e.what()); THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename); } diff --git a/src/wallet/message_store.h b/src/wallet/message_store.h index a0ce83c10..8ee5fc09b 100644 --- a/src/wallet/message_store.h +++ b/src/wallet/message_store.h @@ -49,13 +49,13 @@ #include "common/fs.h" #include "message_transporter.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.mms" #define AUTO_CONFIG_TOKEN_BYTES 4 #define AUTO_CONFIG_TOKEN_PREFIX "mms" namespace mms { + static auto logcat = oxen::log::Cat("wallet.mms"); + enum class message_type { key_set, diff --git a/src/wallet/message_transporter.cpp b/src/wallet/message_transporter.cpp index 5e065d7d7..557ff4b2f 100644 --- a/src/wallet/message_transporter.cpp +++ b/src/wallet/message_transporter.cpp @@ -32,8 +32,6 @@ #include #include -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.mms" #define PYBITMESSAGE_DEFAULT_API_PORT 8442 using namespace std::literals; @@ -41,6 +39,8 @@ using namespace std::literals; namespace mms { + static auto logcat = oxen::log::Cat("wallet.mms"); + namespace bitmessage_rpc { @@ -113,7 +113,7 @@ bool message_transporter::receive_messages(const std::vector &desti bitmessage_rpc::inbox_messages_response bitmessage_res; if (!epee::serialization::load_t_from_json(bitmessage_res, json)) { - MERROR("Failed to deserialize messages"); + oxen::log::error(logcat, "Failed to deserialize messages"); return true; } size_t size = bitmessage_res.inboxMessages.size(); @@ -148,7 +148,7 @@ bool message_transporter::receive_messages(const std::vector &desti } catch(const std::exception& e) { - MERROR("Failed to deserialize message: " << e.what()); + oxen::log::error(logcat, "Failed to deserialize message: {}", e.what()); } } } @@ -235,7 +235,7 @@ void message_transporter::post_request(const std::string &request, std::string & auto res = m_http_client.post("", request, {{"Content-Type", "application/xml; charset=utf-8"}}); answer = res.text; } catch (const std::exception& e) { - LOG_ERROR("POST request to Bitmessage failed: " << e.what()); + oxen::log::error(logcat, "POST request to Bitmessage failed: {}", e.what()); THROW_WALLET_EXCEPTION(tools::error::no_connection_to_bitmessage, m_http_client.get_base_url()); } diff --git a/src/wallet/node_rpc_proxy.cpp b/src/wallet/node_rpc_proxy.cpp index f7172a95d..36e1b1fdd 100644 --- a/src/wallet/node_rpc_proxy.cpp +++ b/src/wallet/node_rpc_proxy.cpp @@ -38,6 +38,8 @@ using namespace std::literals; namespace tools { +static auto logcat = oxen::log::Cat("node_rpc_proxy"); + static constexpr std::chrono::seconds rpc_timeout{30}; NodeRPCProxy::NodeRPCProxy(rpc::http_client& http_client) @@ -227,7 +229,7 @@ bool NodeRPCProxy::get_fee_quantization_mask(uint64_t &fee_quantization_mask) co fee_quantization_mask = m_fee_quantization_mask; if (fee_quantization_mask == 0) { - MERROR("Fee quantization mask is 0, forcing to 1"); + oxen::log::error(logcat, "Fee quantization mask is 0, forcing to 1"); fee_quantization_mask = 1; } return true; diff --git a/src/wallet/node_rpc_proxy.h b/src/wallet/node_rpc_proxy.h index b6b8c8998..a77cdc8c1 100644 --- a/src/wallet/node_rpc_proxy.h +++ b/src/wallet/node_rpc_proxy.h @@ -80,12 +80,12 @@ private: try { result = m_http_client.json_rpc(RPC::names().front(), req); } catch (const std::exception& e) { - MERROR(e.what()); + oxen::log::error(globallogcat, e.what()); throw; } if (result.status != cryptonote::rpc::STATUS_OK) { std::string error = "Request for " + std::string{RPC::names().front()} + " failed: " + (result.status == cryptonote::rpc::STATUS_BUSY ? "daemon is busy" : result.status); - MERROR(error); + oxen::log::error(globallogcat, error); throw std::runtime_error{error}; } diff --git a/src/wallet/ringdb.cpp b/src/wallet/ringdb.cpp index 219a80f38..33d1b94c7 100644 --- a/src/wallet/ringdb.cpp +++ b/src/wallet/ringdb.cpp @@ -33,12 +33,12 @@ #include "wallet_errors.h" #include "ringdb.h" #include "cryptonote_config.h" - -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.ringdb" +#include #define V1TAG ((uint64_t)798237759845202) +static auto logcat = oxen::log::Cat("wallet.ringdb"); + static const char zerokey[8] = {0}; static const MDB_val zerokeyval = { sizeof(zerokey), (void *)zerokey }; @@ -179,14 +179,14 @@ static int resize_env(MDB_env *env, const fs::path& db_path, size_t needed) auto si = fs::space(db_path); if(si.available < needed) { - MERROR("!! WARNING: Insufficient free space to extend database !!: " << (si.available / 1000000) << " MB available"); + oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); return ENOSPC; } } catch(...) { // print something but proceed. - MWARNING("Unable to query free disk space."); + oxen::log::warning(logcat, "Unable to query free disk space."); } mapsize += needed; @@ -212,7 +212,7 @@ ringdb::ringdb(fs::path fn_, const std::string &genesis) : filename_{std::move(f std::error_code ec; if (fs::create_directories(filename_, ec); ec) - MWARNING("Failed to create ringdb directory " << filename_ << ": " << ec.message()); + oxen::log::warning(logcat, "Failed to create ringdb directory {}: {}", filename_, ec.message()); dbr = mdb_env_create(&env); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr))); @@ -314,7 +314,7 @@ bool ringdb::remove_rings(const crypto::chacha_key &chacha_key, const std::vecto continue; THROW_WALLET_EXCEPTION_IF(data.mv_size <= 0, tools::error::wallet_internal_error, "Invalid ring data size"); - MDEBUG("Removing ring data for key image " << key_image); + oxen::log::debug(logcat, "Removing ring data for key image {}", key_image); dbr = mdb_del(txn, dbi_rings, &key, NULL); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to remove ring to database: " + std::string(mdb_strerror(dbr))); } @@ -374,10 +374,10 @@ bool ringdb::get_ring(const crypto::chacha_key &chacha_key, const crypto::key_im data_plaintext = decrypt(std::string((const char*)data.mv_data, data.mv_size), key_image, chacha_key, 0); outs = decompress_ring(data_plaintext, 0); } - MDEBUG("Found ring for key image " << key_image << ":"); - MDEBUG("Relative: " << tools::join(" ", outs)); + oxen::log::debug(logcat, "Found ring for key image {}:", key_image); + oxen::log::debug(logcat, "Relative: {}", tools::join(" ", outs)); outs = cryptonote::relative_output_offsets_to_absolute(outs); - MDEBUG("Absolute: " << tools::join(" ", outs)); + oxen::log::debug(logcat, "Absolute: {}", tools::join(" ", outs)); dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn getting ring from database: " + std::string(mdb_strerror(dbr))); @@ -437,13 +437,13 @@ bool ringdb::blackball_worker(const std::vector> & switch (op) { case BLACKBALL_BLACKBALL: - MDEBUG("Marking output " << output.first << "/" << output.second << " as spent"); + oxen::log::debug(logcat, "Marking output {}/{} as spent", output.first, output.second); dbr = mdb_cursor_put(cursor, &key, &data, MDB_NODUPDATA); if (dbr == MDB_KEYEXIST) dbr = 0; break; case BLACKBALL_UNBLACKBALL: - MDEBUG("Marking output " << output.first << "/" << output.second << " as unspent"); + oxen::log::debug(logcat, "Marking output {}/{} as unspent", output.first, output.second); dbr = mdb_cursor_get(cursor, &key, &data, MDB_GET_BOTH); if (dbr == 0) dbr = mdb_cursor_del(cursor, 0); diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 3ee1b6eea..e1b5cf271 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -73,9 +73,9 @@ #include "common/base58.h" #include "common/combinator.h" #include "common/notify.h" -#include "common/perf_timer.h" #include "common/hex.h" #include "ringct/rctSigs.h" +#include "ringct/fmt.h" #include "ringdb.h" #include "device/device_cold.hpp" #ifdef DEVICE_TREZOR_READY @@ -86,6 +86,9 @@ #include "cryptonote_core/service_node_rules.h" #include "common/oxen.h" #include "oxen_economy.h" +#include "logging/oxen_logger.h" +#include +#include extern "C" { @@ -101,9 +104,8 @@ extern "C" using namespace crypto; using namespace cryptonote; -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.wallet2" namespace { + static auto logcat = oxen::log::Cat("wallet.wallet2"); constexpr std::string_view UNSIGNED_TX_PREFIX = "Loki unsigned tx set\004"sv; constexpr std::string_view SIGNED_TX_PREFIX = "Loki signed tx set\004"sv; @@ -389,7 +391,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl command_line::get_arg(vm, opts.daemon_login), false, [password_prompter](bool verify) { if (!password_prompter) { - MERROR("Password needed without prompt function"); + oxen::log::error(logcat, "Password needed without prompt function"); return std::optional(); } return password_prompter("Daemon client password", verify); @@ -441,7 +443,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl if (!command_line::is_arg_defaulted(vm, opts.trusted_daemon) || !command_line::is_arg_defaulted(vm, opts.untrusted_daemon)) trusted_daemon = command_line::get_arg(vm, opts.trusted_daemon) && !command_line::get_arg(vm, opts.untrusted_daemon); else if (trusted_daemon) - MINFO(tools::wallet2::tr("Daemon is local, assuming trusted")); + oxen::log::info(logcat, tools::wallet2::tr("Daemon is local, assuming trusted")); auto wallet = std::make_unique(nettype, kdf_rounds, unattended); wallet->init(std::move(daemon_address), std::move(login), std::move(proxy), 0, trusted_daemon); @@ -477,7 +479,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl } catch (const std::exception &e) { - MERROR("Failed to parse tx notify spec"); + oxen::log::error(logcat, "Failed to parse tx notify spec"); } return wallet; @@ -790,7 +792,7 @@ size_t estimate_rct_tx_size(int n_inputs, int mixin, int n_outputs, size_t extra // txnFee size += 4; - LOG_PRINT_L2("estimated bulletproof rct tx size for " << n_inputs << " inputs with ring size " << (mixin+1) << " and " << n_outputs << " outputs: " << size << " (" << ((32 * n_inputs/*+1*/) + 2 * 32 * (mixin+1) * n_inputs + 32 * n_outputs) << " saved)"); + oxen::log::debug(logcat, "estimated bulletproof rct tx size for {} inputs with ring size {} and {} outputs: {} ({} saved)", n_inputs, (mixin+1), n_outputs, size, ((32 * n_inputs/*+1*/) + 2 * 32 * (mixin+1) * n_inputs + 32 * n_outputs)); return size; } @@ -806,7 +808,7 @@ uint64_t estimate_tx_weight(int n_inputs, int mixin, int n_outputs, size_t extra uint64_t nlr = 2 * (6 + log_padded_outputs); const uint64_t bp_size = 32 * (9 + nlr); const uint64_t bp_clawback = (bp_base * (1<::max(); // bad pick - MTRACE("Picking 1/" << n_rct << " in block " << index); + oxen::log::trace(logcat, "Picking 1/{} in block {}", n_rct, index); return first_rct + crypto::rand_idx(n_rct); }; @@ -1010,7 +1012,7 @@ wallet_keys_unlocker::~wallet_keys_unlocker() std::lock_guard lock{lockers_mutex}; if (lockers == 0) { - MERROR("There are no lockers in wallet_keys_unlocker dtor"); + oxen::log::error(logcat, "There are no lockers in wallet_keys_unlocker dtor"); return; } --lockers; @@ -1020,7 +1022,7 @@ wallet_keys_unlocker::~wallet_keys_unlocker() } catch (...) { - MERROR("Failed to re-encrypt wallet keys"); + oxen::log::error(logcat, "Failed to re-encrypt wallet keys"); // do not propagate through dtor, we'd crash } } @@ -1258,7 +1260,7 @@ bool wallet2::set_daemon(std::string daemon_address, std::optional auto [proto, host, port, uri] = rpc::http_client::parse_url(daemon_address); localhost = tools::is_local_address(host); } catch (const rpc::http_client_error& e) { - MWARNING("Invalid daemon URL: "s + e.what()); + oxen::log::warning(logcat, "Invalid daemon URL: "s + e.what()); return false; } @@ -1285,7 +1287,7 @@ bool wallet2::set_daemon(std::string daemon_address, std::optional m_node_rpc_proxy.invalidate(); std::string url = m_http_client.get_base_url(); - MINFO("set daemon to " << (url.empty() ? "(none, offline)" : url)); + oxen::log::info(logcat, "set daemon to {}", (url.empty() ? "(none, offline)" : url)); { std::lock_guard lock{default_daemon_address_mutex}; default_daemon_address = std::move(url); @@ -1413,13 +1415,13 @@ bool wallet2::reconnect_device() hwdev.set_callback(get_device_callback()); r = hwdev.init(); if (!r){ - MERROR("Could not init device"); + oxen::log::error(logcat, "Could not init device"); return false; } r = hwdev.connect(); if (!r){ - MERROR("Could not connect to the device"); + oxen::log::error(logcat, "Could not connect to the device"); return false; } @@ -1543,7 +1545,7 @@ std::string wallet2::get_subaddress_label(const cryptonote::subaddress_index& in { if (index.major >= m_subaddress_labels.size() || index.minor >= m_subaddress_labels[index.major].size()) { - MERROR("Subaddress label doesn't exist"); + oxen::log::error(logcat, "Subaddress label doesn't exist"); return ""; } return m_subaddress_labels[index.major][index.minor]; @@ -1578,7 +1580,7 @@ void wallet2::set_spent(size_t idx, uint64_t height) { CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); transfer_details &td = m_transfers[idx]; - LOG_PRINT_L2("Setting SPENT at " << height << ": ki " << td.m_key_image << ", amount " << print_money(td.m_amount)); + oxen::log::debug(logcat, "Setting SPENT at {}: ki {}, amount {}", height, td.m_key_image, print_money(td.m_amount)); td.m_spent = true; td.m_spent_height = height; } @@ -1587,7 +1589,7 @@ void wallet2::set_unspent(size_t idx) { CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); transfer_details &td = m_transfers[idx]; - LOG_PRINT_L2("Setting UNSPENT: ki " << td.m_key_image << ", amount " << print_money(td.m_amount)); + oxen::log::debug(logcat, "Setting UNSPENT: ki {}, amount {}", td.m_key_image, print_money(td.m_amount)); td.m_spent = false; td.m_spent_height = 0; } @@ -1671,7 +1673,7 @@ void wallet2::check_acc_out_precomp(const tx_out &o, const crypto::key_derivatio if (!std::holds_alternative(o.target)) { tx_scan_info.error = true; - LOG_ERROR("wrong type id in transaction out"); + oxen::log::error(logcat, "wrong type id in transaction out"); return; } tx_scan_info.received = is_out_to_acc_precomp(m_subaddresses, var::get(o.target).key, derivation, additional_derivations, i, hwdev); @@ -1729,13 +1731,13 @@ static uint64_t decodeRct(const rct::rctSig & rv, const crypto::key_derivation & case rct::RCTType::Full: return rct::decodeRct(rv, rct::sk2rct(scalar1), i, mask, hwdev); default: - LOG_ERROR(__func__ << ": Unsupported rct type: " << (int)rv.type); + oxen::log::error(logcat, "{}: Unsupported rct type: {}", __func__, (int)rv.type); return 0; } } catch (const std::exception &e) { - LOG_ERROR("Failed to decode input " << i); + oxen::log::error(logcat, "Failed to decode input {}", i); return 0; } } @@ -1789,7 +1791,7 @@ void wallet2::scan_output(const cryptonote::transaction &tx, bool miner_tx, cons if (tx_scan_info.money_transfered == 0) { - MERROR("Invalid output amount, skipping"); + oxen::log::error(logcat, "Invalid output amount, skipping"); tx_scan_info.error = true; return; } @@ -1821,7 +1823,7 @@ void wallet2::cache_tx_data(const cryptonote::transaction& tx, const crypto::has if(!parse_tx_extra(tx.extra, tx_cache_data.tx_extra_fields)) { // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key - LOG_PRINT_L0("Transaction extra has unsupported format: " << txid); + oxen::log::warning(logcat, "Transaction extra has unsupported format: {}", txid); if (tx_cache_data.tx_extra_fields.empty()) return; } @@ -1859,7 +1861,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (!tx.is_transfer() || tx.version <= txversion::v1) return; - PERF_TIMER(process_new_transaction); + oxen::log::trace(logcat, "PROC NEW TX {}", txid); // In this function, tx (probably) only contains the base information // (that is, the prunable stuff may or may not be included) confirmed_transfer_details* just_confirmed = nullptr; @@ -1881,7 +1883,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if(!parse_tx_extra(tx.extra, local_tx_extra_fields)) { // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key - LOG_PRINT_L0("Transaction extra has unsupported format: " << txid); + oxen::log::warning(logcat, "Transaction extra has unsupported format: {}", txid); } } const auto& tx_extra_fields = tx_cache_data.tx_extra_fields.empty() ? local_tx_extra_fields : tx_cache_data.tx_extra_fields; @@ -1921,7 +1923,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if (pk_index > 1) break; - LOG_PRINT_L0("Public key wasn't found in the transaction extra. Skipping transaction " << txid); + oxen::log::warning(logcat, "Public key wasn't found in the transaction extra. Skipping transaction {}", txid); if (m_callback) m_callback->on_skip_transaction(height, txid, tx); break; @@ -1950,7 +1952,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote hwdev.set_mode(hw::device::mode::TRANSACTION_PARSE); if (!hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation)) { - MWARNING("Failed to generate key derivation from tx pubkey in " << txid << ", skipping"); + oxen::log::warning(logcat, "Failed to generate key derivation from tx pubkey in {}, skipping", txid); static_assert(sizeof(derivation) == sizeof(rct::key), "Mismatched sizes of key_derivation and rct::key"); memcpy(&derivation, rct::identity().bytes, sizeof(derivation)); } @@ -1965,7 +1967,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote additional_derivations.push_back({}); if (!hwdev.generate_key_derivation(additional_tx_pub_keys.data[i], keys.m_view_secret_key, additional_derivations.back())) { - MWARNING("Failed to generate key derivation from additional tx pubkey in " << txid << ", skipping"); + oxen::log::warning(logcat, "Failed to generate key derivation from additional tx pubkey in {}, skipping", txid); memcpy(&additional_derivations.back(), rct::identity().bytes, sizeof(crypto::key_derivation)); } } @@ -2135,7 +2137,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (m_multisig_rescan_info && m_multisig_rescan_info->front().size() >= m_transfers.size()) update_multisig_rescan_info(*m_multisig_rescan_k, *m_multisig_rescan_info, m_transfers.size() - 1); } - LOG_PRINT_L0("Received money: " << print_money(td.amount()) << ", with tx: " << txid); + oxen::log::warning(logcat, "Received money: {}, with tx: {}", print_money(td.amount()), txid); if (m_callback) m_callback->on_money_received(height, txid, tx, td.m_amount, td.m_subaddr_index, td.m_tx.unlock_time, blink); } @@ -2158,10 +2160,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if (transfer.amount() > tx_scan_info[o].amount) { - LOG_ERROR("Public key " << tools::type_to_hex(kit->first) - << " from received " << print_money(tx_scan_info[o].amount) << " output already exists with " - << (transfer.m_spent ? "spent" : "unspent") << " " - << print_money(transfer.amount()) << " in tx " << transfer.m_txid << ", received output ignored"); + oxen::log::error(logcat, "Public key {} from received {} output already exists with {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspend"), print_money(transfer.amount()), transfer.m_txid); } if (transfer.m_unmined_blink) @@ -2170,9 +2169,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote THROW_WALLET_EXCEPTION_IF(transfer.amount() != tx_scan_info[o].amount, error::wallet_internal_error, "A blink should credit the amount exactly as we recorded it when it arrived in the mempool"); THROW_WALLET_EXCEPTION_IF(transfer.m_spent, error::wallet_internal_error, "Blink can not be spent before it is mined, this should never happen"); - MINFO("Public key " << tools::type_to_hex(kit->first) - << " of blink tx " << transfer.m_txid << " (for " << print_money(tx_scan_info[o].amount) << ")" - << " status updated: now mined in block " << height); + oxen::log::info(logcat, "Public key {} of blink tx {} (for {}) status updated: now mined in block {}", tools::type_to_hex(kit->first), transfer.m_txid, print_money(tx_scan_info[o].amount), height); // We previous had this as a blink, but now it's been mined so update the tx status with the height and output index transfer.m_block_height = height; @@ -2195,10 +2192,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else if (transfer.m_spent || transfer.amount() >= tx_scan_info[o].amount) { - LOG_ERROR("Public key " << tools::type_to_hex(kit->first) - << " from received " << print_money(tx_scan_info[o].amount) << " output already exists with " - << (transfer.m_spent ? "spent" : "unspent") << " " - << print_money(transfer.amount()) << " in tx " << transfer.m_txid << ", received output ignored"); + oxen::log::error(logcat, "Public key {} from received {} output already exists with {} {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspent"), print_money(transfer.amount()), transfer.m_txid); auto iter = std::find_if( tx_money_got_in_outs.begin(), @@ -2216,9 +2210,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else { - LOG_ERROR("Public key " << tools::type_to_hex(kit->first) - << " from received " << print_money(tx_scan_info[o].amount) << " output already exists with " - << print_money(transfer.amount()) << ", replacing with new output"); + oxen::log::error(logcat, "Public key {} from received {} output already exists with {}, replacing with new output", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), print_money(transfer.amount())); // The new larger output replaced a previous smaller one auto unlock_time_it = pk_to_unlock_times.find(kit->first); @@ -2313,7 +2305,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote THROW_WALLET_EXCEPTION_IF(transfer.get_public_key() != tx_scan_info[o].in_ephemeral.pub, error::wallet_internal_error, "Inconsistent public keys"); THROW_WALLET_EXCEPTION_IF(transfer.m_spent, error::wallet_internal_error, "Inconsistent spent status"); - LOG_PRINT_L0("Received money: " << print_money(transfer.amount()) << ", with tx: " << txid); + oxen::log::warning(logcat, "Received money: {}, with tx: {}", print_money(transfer.amount()), txid); if (m_callback) m_callback->on_money_received(height, txid, tx, transfer.m_amount, transfer.m_subaddr_index, transfer.m_tx.unlock_time, blink); } @@ -2342,8 +2334,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if(amount != td.amount()) { - MERROR("Inconsistent amount in tx input: got " << print_money(amount) << - ", expected " << print_money(td.amount())); + oxen::log::error(logcat, "Inconsistent amount in tx input: got {}, expected {}", print_money(amount), print_money(td.amount())); // this means: // 1) the same output pub key was used as destination multiple times, // 2) the wallet set the highest amount among them to transfer_details::m_amount, and @@ -2357,12 +2348,12 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } tx_money_spent_in_ins += amount; if (subaddr_account && *subaddr_account != td.m_subaddr_index.major) - LOG_ERROR("spent funds are from different subaddress accounts; count of incoming/outgoing payments will be incorrect"); + oxen::log::error(logcat, "spent funds are from different subaddress accounts; count of incoming/outgoing payments will be incorrect"); subaddr_account = td.m_subaddr_index.major; subaddr_indices.insert(td.m_subaddr_index.minor); if (!pool) { - LOG_PRINT_L0("Spent money: " << print_money(amount) << ", with tx: " << txid); + oxen::log::warning(logcat, "Spent money: {}, with tx: {}", print_money(amount), txid); set_spent(it->second, height); if (m_callback) m_callback->on_money_spent(height, txid, tx, amount, tx, td.m_subaddr_index); @@ -2371,7 +2362,6 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (!pool && m_track_uses) { - PERF_TIMER(track_uses); const uint64_t amount = in_to_key.amount; std::vector offsets = cryptonote::relative_output_offsets_to_absolute(in_to_key.key_offsets); if (output_tracker_cache) @@ -2446,17 +2436,17 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { // We got a payment ID to go with this tx - LOG_PRINT_L2("Found encrypted payment ID: " << payment_id8); - MINFO("Consider using subaddresses instead of encrypted payment IDs"); + oxen::log::debug(logcat, "Found encrypted payment ID: {}", payment_id8); + oxen::log::info(logcat, "Consider using subaddresses instead of encrypted payment IDs"); if (tx_pub_key != null_pkey) { if (!m_account.get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_account.get_keys().m_view_secret_key)) { - LOG_PRINT_L0("Failed to decrypt payment ID: " << payment_id8); + oxen::log::warning(logcat, "Failed to decrypt payment ID: {}", payment_id8); } else { - LOG_PRINT_L2("Decrypted payment ID: " << payment_id8); + oxen::log::debug(logcat, "Decrypted payment ID: {}", payment_id8); // put the 64 bit decrypted payment id in the first 8 bytes memcpy(payment_id.data, payment_id8.data, 8); // rest is already 0, but guard against code changes above @@ -2465,7 +2455,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else { - LOG_PRINT_L1("No public key found in tx, unable to decrypt payment id"); + oxen::log::info(logcat, "No public key found in tx, unable to decrypt payment id"); } } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) @@ -2473,14 +2463,14 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote bool ignore = block_version >= IGNORE_LONG_PAYMENT_ID_FROM_BLOCK_VERSION; if (ignore) { - LOG_PRINT_L2("Found unencrypted payment ID in tx " << txid << " (ignored)"); - MWARNING("Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); + oxen::log::debug(logcat, "Found unencrypted payment ID in tx {} (ignored)", txid); + oxen::log::warning(logcat, "Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); payment_id = crypto::null_hash; } else { - LOG_PRINT_L2("Found unencrypted payment ID: " << payment_id); - MWARNING("Found unencrypted payment ID: these are bad for privacy, consider using subaddresses instead"); + oxen::log::debug(logcat, "Found unencrypted payment ID: {}", payment_id); + oxen::log::warning(logcat, "Found unencrypted payment ID: these are bad for privacy, consider using subaddresses instead"); } } } @@ -2494,11 +2484,10 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (total_received_1 != total_received_2) { - const el::Level level = el::Level::Warning; - MCLOG_RED(level, "global", "**********************************************************************"); - MCLOG_RED(level, "global", "Consistency failure in amounts received"); - MCLOG_RED(level, "global", "Check transaction " << txid); - MCLOG_RED(level, "global", "**********************************************************************"); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Consistency failure in amounts received")); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Check transaction {}", txid)); + oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); exit(1); return; } @@ -2525,7 +2514,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else m_payments.emplace(payment_id, payment); - LOG_PRINT_L2("Payment found in " << (pool ? blink ? "blink pool" : "pool" : "block") << ": " << payment_id << " / " << payment.m_tx_hash << " / " << payment.m_amount); + oxen::log::debug(logcat, "Payment found in {}: {} / {} / {}", (pool ? blink ? "blink pool" : "pool" : "block"), payment_id, payment.m_tx_hash, payment.m_amount); } // if it's a pool tx and we already had it, don't notify again @@ -2597,7 +2586,7 @@ wallet2::confirmed_transfer_details* wallet2::process_unconfirmed(const crypto:: } catch (...) { // can fail if the tx has unexpected input types - LOG_PRINT_L0("Failed to add outgoing transaction to confirmed transaction map"); + oxen::log::warning(logcat, "Failed to add outgoing transaction to confirmed transaction map"); } } m_unconfirmed_txs.erase(unconf_it); @@ -2686,13 +2675,19 @@ void wallet2::process_new_blockchain_entry(const cryptonote::block& b, const cry m_last_block_reward = cryptonote::get_outs_money_amount(b.miner_tx); if (height > 0 && ((height % 2000) == 0)) - LOG_PRINT_L0("Blockchain sync progress: " << bl_id << ", height " << height); + oxen::log::warning(logcat, "Blockchain sync progress: {}, height {}", bl_id, height); + + oxen::log::debug(logcat, "Processed block: {}, height {}, {}({}/{})", + bl_id, + height, + tools::friendly_duration(miner_tx_handle_time_duration + txs_handle_time_duration), + tools::friendly_duration(miner_tx_handle_time_duration), + tools::friendly_duration(txs_handle_time_duration)); - LOG_PRINT_L2("Processed block: " << bl_id << ", height " << height << ", " << tools::friendly_duration(miner_tx_handle_time_duration + txs_handle_time_duration) << "(" << tools::friendly_duration(miner_tx_handle_time_duration) << "/" << tools::friendly_duration(txs_handle_time_duration) <<")ms"); }else { if (!(height % 128)) - LOG_PRINT_L2( "Skipped block by timestamp, height: " << height << ", block time " << b.timestamp << ", account time " << m_account.get_createtime()); + oxen::log::debug(logcat, "Skipped block by timestamp, height: {}, block time {}, account time {}", height, b.timestamp, m_account.get_createtime()); } m_blockchain.push_back(bl_id); m_cached_height++; @@ -2745,7 +2740,7 @@ void wallet2::pull_blocks(uint64_t start_height, uint64_t& blocks_start_height, cryptonote::rpc::GET_BLOCKS_BIN::response res{}; req.block_ids = short_chain_history; - MDEBUG("Pulling blocks: start_height " << start_height); + oxen::log::debug(logcat, "Pulling blocks: start_height {}", start_height); req.prune = true; req.start_height = start_height; @@ -2763,8 +2758,7 @@ void wallet2::pull_blocks(uint64_t start_height, uint64_t& blocks_start_height, o_indices = std::move(res.output_indices); current_height = res.current_height; - MDEBUG("Pulled blocks: blocks_start_height " << blocks_start_height << ", count " << blocks.size() - << ", height " << blocks_start_height + blocks.size() << ", node height " << res.current_height); + oxen::log::debug(logcat, "Pulled blocks: blocks_start_height {}, count {}, height {}, node height {}", blocks_start_height, blocks.size(), blocks_start_height + blocks.size(), res.current_height); } //---------------------------------------------------------------------------------------------------- void wallet2::pull_hashes(uint64_t start_height, uint64_t &blocks_start_height, const std::list &short_chain_history, std::vector &hashes) @@ -2829,7 +2823,7 @@ void wallet2::process_parsed_blocks(uint64_t start_height, const std::vector &tx_hashe auto pit = uit++; if (!found) { - MDEBUG("Removing " << txid << " from unconfirmed payments, not found in pool"); + oxen::log::debug(logcat, "Removing {} from unconfirmed payments, not found in pool", txid); m_unconfirmed_payments.erase(pit); if (m_callback) m_callback->on_pool_tx_removed(txid); @@ -3062,10 +3056,10 @@ bool wallet2::long_poll_pool_state() res = m_long_poll_client.binary(GET_TRANSACTION_POOL_HASHES_BIN::names()[0], req); } catch (const std::exception& e) { if (m_long_poll_disabled) - MDEBUG("Long poll request cancelled"); + oxen::log::debug(logcat, "Long poll request cancelled"); else { - MWARNING("Long poll request failed: " << e.what()); + oxen::log::warning(logcat, "Long poll request failed: {}", e.what()); std::this_thread::sleep_for(error_sleep); } throw; @@ -3073,7 +3067,7 @@ bool wallet2::long_poll_pool_state() if (res.status == rpc::STATUS_TX_LONG_POLL_TIMED_OUT) { - MINFO("Long poll replied with no pool change"); + oxen::log::debug(logcat, "Long poll replied with no pool change"); return false; } @@ -3112,7 +3106,7 @@ static std::vector hashes_to_hex(It begin, It end) std::vector wallet2::get_pool_state(bool refreshed) { std::vector process_txs; - MTRACE("get_pool_state: take hashes from cache"); + oxen::log::trace(logcat, "get_pool_state: take hashes from cache"); std::vector blink_hashes, pool_hashes; { // We make two requests here: one for all pool txes, and then (assuming there are any) a second @@ -3123,7 +3117,7 @@ std::vector wallet2::get_pool_state(bool refreshed) THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status == rpc::STATUS_BUSY, error::daemon_busy, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status != rpc::STATUS_OK, error::get_tx_pool_error); - MTRACE("get_pool_state got full pool"); + oxen::log::trace(logcat, "get_pool_state got full pool"); pool_hashes = std::move(res.tx_hashes); // NOTE: Only request blinked transactions, normal transactions will appear @@ -3136,7 +3130,7 @@ std::vector wallet2::get_pool_state(bool refreshed) THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status == rpc::STATUS_BUSY, error::daemon_busy, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status != rpc::STATUS_OK, error::get_tx_pool_error); - MTRACE("get_pool_state got blinks"); + oxen::log::trace(logcat, "get_pool_state got blinks"); blink_hashes = std::move(res.tx_hashes); } @@ -3165,12 +3159,12 @@ std::vector wallet2::get_pool_state(bool refreshed) // we're sure we've seen the blockchain state first) if (pit->second.m_state == wallet2::unconfirmed_transfer_details::pending) { - LOG_PRINT_L1("Pending txid " << txid << " not in pool, marking as not in pool"); + oxen::log::info(logcat, "Pending txid {} not in pool, marking as not in pool", txid); pit->second.m_state = wallet2::unconfirmed_transfer_details::pending_not_in_pool; } else if (pit->second.m_state == wallet2::unconfirmed_transfer_details::pending_not_in_pool && refreshed) { - LOG_PRINT_L1("Pending txid " << txid << " not in pool, marking as failed"); + oxen::log::info(logcat, "Pending txid {} not in pool, marking as failed", txid); pit->second.m_state = wallet2::unconfirmed_transfer_details::failed; // the inputs aren't spent anymore, since the tx failed @@ -3183,7 +3177,7 @@ std::vector wallet2::get_pool_state(bool refreshed) const transfer_details &td = m_transfers[i]; if (td.m_key_image == tx_in_to_key->k_image) { - LOG_PRINT_L1("Resetting spent status for output " << vini << ": " << td.m_key_image); + oxen::log::info(logcat, "Resetting spent status for output {}: {}", vini, td.m_key_image); set_unspent(i); break; } @@ -3193,7 +3187,7 @@ std::vector wallet2::get_pool_state(bool refreshed) } } } - MTRACE("get_pool_state done first loop"); + oxen::log::trace(logcat, "get_pool_state done first loop"); // remove pool txes to us that aren't in the pool anymore // but only if we just refreshed, so that the tx can go in @@ -3202,7 +3196,7 @@ std::vector wallet2::get_pool_state(bool refreshed) if (refreshed) remove_obsolete_pool_txs(pool_hashes); - MTRACE("get_pool_state done second loop"); + oxen::log::trace(logcat, "get_pool_state done second loop"); // gather txids of new blink txes to us. We just ignore non-blinks here (we pick them up when they // get mined into a block). @@ -3223,13 +3217,13 @@ std::vector wallet2::get_pool_state(bool refreshed) // if it's for us, we want to keep track of whether we saw a double spend, so don't bail out if (!txid_found_in_up) { - LOG_PRINT_L2("Already seen " << txid << ", and not for us, skipped"); + oxen::log::debug(logcat, "Already seen {}, and not for us, skipped", txid); continue; } } if (!txid_found_in_up) { - LOG_PRINT_L1("Found new pool tx: " << txid); + oxen::log::info(logcat, "Found new pool tx: {}", txid); bool found = false; for (const auto &i: m_unconfirmed_txs) { @@ -3258,7 +3252,7 @@ std::vector wallet2::get_pool_state(bool refreshed) } else { - LOG_PRINT_L1("We sent that one"); + oxen::log::info(logcat, "We sent that one"); } } } @@ -3278,7 +3272,7 @@ std::vector wallet2::get_pool_state(bool refreshed) }; auto res = m_http_client.json_rpc("get_transactions", get_transactions_params); } catch (const std::exception& e) { - LOG_PRINT_L0("Failed to retrieve transactions: " << e.what()); + oxen::log::warning(logcat, "Failed to retrieve transactions: {}", e.what()); return process_txs; } for (const auto &tx_entry: res["txs"]) @@ -3299,21 +3293,21 @@ std::vector wallet2::get_pool_state(bool refreshed) } else { - MERROR("Got txid " << tx_hash << " which we did not ask for"); + oxen::log::error(logcat, "Got txid {} which we did not ask for", tx_hash); } } else { - LOG_PRINT_L0("Failed to parse transaction from daemon"); + oxen::log::warning(logcat, "Failed to parse transaction from daemon"); } } else { - LOG_PRINT_L1("Transaction from daemon was in pool, but is no more"); + oxen::log::info(logcat, "Transaction from daemon was in pool, but is no more"); } } } - MTRACE("get_pool_state end"); + oxen::log::trace(logcat, "get_pool_state end"); return process_txs; } //---------------------------------------------------------------------------------------------------- @@ -3359,7 +3353,7 @@ void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, return; if (blocks_start_height < m_blockchain.offset()) { - MERROR("Blocks start before blockchain offset: " << blocks_start_height << " " << m_blockchain.offset()); + oxen::log::error(logcat, "Blocks start before blockchain offset: {} {}", blocks_start_height, m_blockchain.offset()); return; } current_index = blocks_start_height; @@ -3377,7 +3371,7 @@ void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, if(current_index >= m_blockchain.size()) { if (!(current_index % 1024)) - LOG_PRINT_L2( "Skipped block by height: " << current_index); + oxen::log::debug(logcat, "Skipped block by height: {}", current_index); m_blockchain.push_back(bl_id); m_cached_height++; @@ -3546,7 +3540,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (const tools::error::out_of_hashchain_bounds_error&) { - MINFO("Daemon claims next refresh block is out of hash chain bounds, resetting hash chain"); + oxen::log::info(logcat, "Daemon claims next refresh block is out of hash chain bounds, resetting hash chain"); uint64_t stop_height = m_blockchain.offset(); std::vector tip(m_blockchain.size() - m_blockchain.offset()); for (size_t i = m_blockchain.offset(); i < m_blockchain.size(); ++i) @@ -3571,7 +3565,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (const std::exception &e) { - MERROR("Error parsing blocks: " << e.what()); + oxen::log::error(logcat, "Error parsing blocks: {}", e.what()); error = true; } blocks_fetched += added_blocks; @@ -3613,7 +3607,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo waiter.wait(&tpool); if(try_count < 3) { - LOG_PRINT_L1("Another try pull_blocks (try_count=" << try_count << ")..."); + oxen::log::info(logcat, "Another try pull_blocks (try_count={})...", try_count); first = true; start_height = 0; blocks.clear(); @@ -3624,7 +3618,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } else { - LOG_ERROR("pull_blocks failed, try_count=" << try_count); + oxen::log::error(logcat, "pull_blocks failed, try_count={}", try_count); throw; } } @@ -3644,14 +3638,14 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (...) { - LOG_PRINT_L1("Failed to check pending transactions"); + oxen::log::info(logcat, "Failed to check pending transactions"); } refresh_batching_cache(); m_first_refresh_done = true; - LOG_PRINT_L1("Refresh done, blocks received: " << blocks_fetched << ", balance (all accounts): " << print_money(balance_all(false)) << ", unlocked: " << print_money(unlocked_balance_all(false))); + oxen::log::info(logcat, "Refresh done, blocks received: {}, balance (all accounts): {}, unlocked: {}", blocks_fetched, print_money(balance_all(false)), print_money(unlocked_balance_all(false))); } //---------------------------------------------------------------------------------------------------- bool wallet2::refresh(bool trusted_daemon, uint64_t & blocks_fetched, bool& received_money, bool& ok) @@ -3676,10 +3670,10 @@ bool wallet2::get_rct_distribution(uint64_t &start_height, std::vector if (rpc_version < rpc::version_t{1, 19}) { - MWARNING("Daemon is too old, not requesting rct distribution"); + oxen::log::warning(logcat, "Daemon is too old, not requesting rct distribution"); return false; } - MDEBUG("Daemon is recent enough, requesting rct distribution"); + oxen::log::debug(logcat, "Daemon is recent enough, requesting rct distribution"); cryptonote::rpc::GET_OUTPUT_DISTRIBUTION_BIN::request req{}; cryptonote::rpc::GET_OUTPUT_DISTRIBUTION_BIN::response res{}; @@ -3691,27 +3685,27 @@ bool wallet2::get_rct_distribution(uint64_t &start_height, std::vector bool r = invoke_http(req, res); if (!r) { - MWARNING("Failed to request output distribution: no connection to daemon"); + oxen::log::warning(logcat, "Failed to request output distribution: no connection to daemon"); return false; } if (res.status == rpc::STATUS_BUSY) { - MWARNING("Failed to request output distribution: daemon is busy"); + oxen::log::warning(logcat, "Failed to request output distribution: daemon is busy"); return false; } if (res.status != rpc::STATUS_OK) { - MWARNING("Failed to request output distribution: " << res.status); + oxen::log::warning(logcat, "Failed to request output distribution: {}", res.status); return false; } if (res.distributions.size() != 1) { - MWARNING("Failed to request output distribution: not the expected single result"); + oxen::log::warning(logcat, "Failed to request output distribution: not the expected single result"); return false; } if (res.distributions[0].amount != 0) { - MWARNING("Failed to request output distribution: results are not for amount 0"); + oxen::log::warning(logcat, "Failed to request output distribution: results are not for amount 0"); return false; } for (size_t i = 1; i < res.distributions[0].data.distribution.size(); ++i) @@ -3730,16 +3724,17 @@ bool wallet2::get_output_blacklist(std::vector &blacklist) } if (rpc_version < rpc::version_t{2, 3}) { - MWARNING("Daemon is too old, not requesting output blacklist"); + oxen::log::warning(logcat, "Daemon is too old, not requesting output blacklist"); return false; } - MDEBUG("Daemon is recent enough, requesting output blacklist"); + oxen::log::debug(logcat, "Daemon is recent enough, requesting output blacklist"); try { auto res = m_http_client.json_rpc("get_output_blacklist", {}); blacklist = std::move(res["blacklist"].get>()); } catch (...) { - MWARNING("Failed to request output blacklist: no connection to daemon"); + oxen::log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); + oxen::log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); return false; } @@ -3748,7 +3743,7 @@ bool wallet2::get_output_blacklist(std::vector &blacklist) //---------------------------------------------------------------------------------------------------- void wallet2::detach_blockchain(uint64_t height, std::map, size_t> *output_tracker_cache) { - LOG_PRINT_L0("Detaching blockchain on height " << height); + oxen::log::warning(logcat, "Detaching blockchain on height {}", height); // size 1 2 3 4 5 6 7 8 9 // block 0 1 2 3 4 5 6 7 8 @@ -3763,7 +3758,7 @@ void wallet2::detach_blockchain(uint64_t height, std::map= height) { - LOG_PRINT_L1("Resetting spent/frozen status for output " << i << ": " << td.m_key_image); + oxen::log::info(logcat, "Resetting spent/frozen status for output {}: {}", i, td.m_key_image); set_unspent(i); thaw(i); } @@ -3819,7 +3814,7 @@ void wallet2::detach_blockchain(uint64_t height, std::map wallet2::get_keys_file_data(const epee::w try { multisig_signers = serialization::dump_binary(m_multisig_signers); } catch (const std::exception& e) { - LOG_ERROR("failed to serialize wallet multisig signers: " << e.what()); + oxen::log::error(logcat, "failed to serialize wallet multisig signers: {}", e.what()); return std::nullopt; } value.SetString(multisig_signers.c_str(), multisig_signers.length()); @@ -3979,7 +3974,7 @@ std::optional wallet2::get_keys_file_data(const epee::w try { multisig_derivations = serialization::dump_binary(m_multisig_derivations); } catch (const std::exception& e) { - LOG_ERROR("failed to serialize wallet multisig derivations"); + oxen::log::error(logcat, "failed to serialize wallet multisig derivations"); return std::nullopt; } value.SetString(multisig_derivations.c_str(), multisig_derivations.length()); @@ -4159,7 +4154,7 @@ bool wallet2::load_keys(const fs::path& keys_file_name, const epee::wipeable_str if (!saved_ret) { // just moan a bit, but not fatal - MERROR("Error saving keys file with encrypted keys, not fatal"); + oxen::log::error(logcat, "Error saving keys file with encrypted keys, not fatal"); } if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) decrypt_keys(*keys_to_encrypt); @@ -4235,12 +4230,12 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json.HasMember("key_data")) { - LOG_ERROR("Field key_data not found in JSON"); + oxen::log::error(logcat, "Field key_data not found in JSON"); return false; } if (!json["key_data"].IsString()) { - LOG_ERROR("Field key_data found in JSON, but not String"); + oxen::log::error(logcat, "Field key_data found in JSON, but not String"); return false; } const char *field_key_data = json["key_data"].GetString(); @@ -4269,12 +4264,12 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json.HasMember("multisig_signers")) { - LOG_ERROR("Field multisig_signers not found in JSON"); + oxen::log::error(logcat, "Field multisig_signers not found in JSON"); return false; } if (!json["multisig_signers"].IsString()) { - LOG_ERROR("Field multisig_signers found in JSON, but not String"); + oxen::log::error(logcat, "Field multisig_signers found in JSON, but not String"); return false; } const char *field_multisig_signers = json["multisig_signers"].GetString(); @@ -4282,7 +4277,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st try { serialization::parse_binary(multisig_signers, m_multisig_signers); } catch (const std::exception& e) { - LOG_ERROR("Field multisig_signers found in JSON, but failed to parse: " << e.what()); + oxen::log::error(logcat, "Field multisig_signers found in JSON, but failed to parse: {}", e.what()); return false; } @@ -4291,7 +4286,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json["multisig_derivations"].IsString()) { - LOG_ERROR("Field multisig_derivations found in JSON, but not String"); + oxen::log::error(logcat, "Field multisig_derivations found in JSON, but not String"); return false; } const char *field_multisig_derivations = json["multisig_derivations"].GetString(); @@ -4299,7 +4294,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st try { serialization::parse_binary(multisig_derivations, m_multisig_derivations); } catch (const std::exception& e) { - LOG_ERROR("Field multisig_derivations found in JSON, but failed to parse: " << e.what()); + oxen::log::error(logcat, "Field multisig_derivations found in JSON, but failed to parse: {}", e.what()); return false; } } @@ -4342,7 +4337,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st if (field_refresh_type == RefreshFull || field_refresh_type == RefreshOptimizeCoinbase || field_refresh_type == RefreshNoCoinbase) m_refresh_type = (RefreshType)field_refresh_type; else - LOG_PRINT_L0("Unknown refresh-type value (" << field_refresh_type << "), using default"); + oxen::log::warning(logcat, "Unknown refresh-type value ({}), using default", field_refresh_type); } GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, refresh_height, uint64_t, Uint64, false, 0); m_refresh_from_block_height = field_refresh_height; @@ -4418,7 +4413,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st bool ok = get_account_address_from_str(info, m_nettype, field_original_address); if (!ok) { - LOG_ERROR("Failed to parse original_address from JSON"); + oxen::log::error(logcat, "Failed to parse original_address from JSON"); return false; } m_original_address = info.address; @@ -4426,7 +4421,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st ok = tools::hex_to_type(field_original_view_secret_key, m_original_view_secret_key); if (!ok) { - LOG_ERROR("Failed to parse original_view_secret_key from JSON"); + oxen::log::error(logcat, "Failed to parse original_view_secret_key from JSON"); return false; } } @@ -4445,7 +4440,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st bool r = epee::serialization::load_t_from_binary(m_account, account_data); THROW_WALLET_EXCEPTION_IF(!r, error::invalid_password); if (m_key_device_type == hw::device::type::LEDGER || m_key_device_type == hw::device::type::TREZOR) { - LOG_PRINT_L0("Account on device. Initing device..."); + oxen::log::warning(logcat, "Account on device. Initing device..."); hw::device &hwdev = lookup_device(m_device_name); THROW_WALLET_EXCEPTION_IF(!hwdev.set_name(m_device_name), error::wallet_internal_error, "Could not set device name " + m_device_name); hwdev.set_network_type(m_nettype); @@ -4461,7 +4456,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st "Device wallet does not match wallet address. " "Device address: " + cryptonote::get_account_address_as_str(m_nettype, false, device_account_public_address) + ", wallet address: " + m_account.get_public_address_str(m_nettype)); - LOG_PRINT_L0("Device initialized..."); + oxen::log::warning(logcat, "Device initialized..."); } else if (key_on_device()) { THROW_WALLET_EXCEPTION(error::wallet_internal_error, "hardware device not supported"); } @@ -4627,7 +4622,7 @@ void wallet2::create_keys_file(const fs::path &wallet_, bool watch_only, const e auto addrfile = m_wallet_file; addrfile += ".address.txt"; r = tools::dump_file(addrfile, m_account.get_public_address_str(m_nettype)); - if(!r) MERROR("String with address text not saved"); + if(!r) oxen::log::error(logcat, "String with address text not saved"); } } } @@ -4975,7 +4970,7 @@ void wallet2::restore_from_device(const fs::path& wallet_, const epee::wipeable_ hwdev_filename += ".hwdev.txt"; std::string hwdev_text = hwdev_label.value_or(""); if (!tools::dump_file(hwdev_filename, hwdev_text)) - MERROR("failed to write .hwdev.txt comment file"); + oxen::log::error(logcat, "failed to write .hwdev.txt comment file"); if (progress_callback) progress_callback(tr("Setting up account and subaddresses")); setup_new_blockchain(); @@ -5037,7 +5032,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, if (threshold == spend_keys.size() + 1) { // In N / N case we only need to do one round and calculate secret multisig keys and new secret spend key - MINFO("Creating spend key..."); + oxen::log::info(logcat, "Creating spend key..."); // Calculates all multisig keys and spend key cryptonote::generate_multisig_N_N(get_account().get_keys(), spend_keys, multisig_keys, spend_skey, spend_pkey); @@ -5061,7 +5056,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, // We need an extra step, so we package all the composite public keys // we know about, and make a signed string out of them - MINFO("Creating spend key..."); + oxen::log::info(logcat, "Creating spend key..."); // Calculating set of our secret multisig keys as follows: mi = H(Mi), // where mi - secret multisig key, Mi - others' participants public multisig key @@ -5079,7 +5074,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, else { // M / N case - MINFO("Preparing keys for next exchange round..."); + oxen::log::info(logcat, "Preparing keys for next exchange round..."); // Preparing data for middle round - packing new public multisig keys to exchage with others. extra_multisig_info = pack_multisignature_keys(derivations, m_account.get_keys().m_spend_secret_key); @@ -5100,10 +5095,10 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, } clear(); - MINFO("Creating view key..."); + oxen::log::info(logcat, "Creating view key..."); crypto::secret_key view_skey = cryptonote::generate_multisig_view_secret_key(get_account().get_keys().m_view_secret_key, view_keys); - MINFO("Creating multisig address..."); + oxen::log::info(logcat, "Creating multisig address..."); CHECK_AND_ASSERT_THROW_MES(m_account.make_multisig(view_skey, rct::rct2sk(spend_skey), rct::rct2pk(spend_pkey), multisig_keys), "Failed to create multisig wallet due to bad keys"); memwipe(&spend_skey, sizeof(rct::key)); @@ -5221,7 +5216,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor if (fs::exists(addrfile)) { r = tools::dump_file(addrfile, m_account.get_public_address_str(m_nettype)); - if(!r) MERROR("String with address text not saved"); + if(!r) oxen::log::error(logcat, "String with address text not saved"); } } @@ -5247,7 +5242,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor if (m_multisig_rounds_passed == multisig_rounds_required(m_multisig_signers.size(), m_multisig_threshold) - 2) // next round is last { // Next round is last therefore we are performing secret spend establishment round as described above. - MINFO("Creating spend key..."); + oxen::log::info(logcat, "Creating spend key..."); // Calculating our secret multisig keys by hashing our public multisig keys. auto multisig_keys = cryptonote::calculate_multisig_keys(std::vector(new_derivations.begin(), new_derivations.end())); @@ -5262,7 +5257,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor else { // This is just middle round - MINFO("Preparing keys for next exchange round..."); + oxen::log::info(logcat, "Preparing keys for next exchange round..."); extra_multisig_info = pack_multisignature_keys(new_derivations, m_account.get_keys().m_spend_secret_key); m_multisig_derivations = new_derivations; } @@ -5299,7 +5294,7 @@ void wallet2::unpack_multisig_info(const std::vector& info, { if (rct::sk2rct(secret_keys[i]) == rct::sk2rct(secret_keys[j])) { - MDEBUG("Duplicate key found, ignoring"); + oxen::log::debug(logcat, "Duplicate key found, ignoring"); secret_keys[j] = secret_keys.back(); public_keys[j] = public_keys.back(); secret_keys.pop_back(); @@ -5316,7 +5311,7 @@ void wallet2::unpack_multisig_info(const std::vector& info, { if (secret_keys[i] == local_skey) { - MDEBUG("Local key is present, ignoring"); + oxen::log::debug(logcat, "Local key is present, ignoring"); secret_keys[i] = secret_keys.back(); public_keys[i] = public_keys.back(); secret_keys.pop_back(); @@ -5347,17 +5342,17 @@ bool wallet2::finalize_multisig(const epee::wipeable_string &password, const std uint32_t threshold, total; if (!multisig(&ready, &threshold, &total)) { - MERROR("This is not a multisig wallet"); + oxen::log::error(logcat, "This is not a multisig wallet"); return false; } if (ready) { - MERROR("This multisig wallet is already finalized"); + oxen::log::error(logcat, "This multisig wallet is already finalized"); return false; } if (threshold + 1 != total) { - MERROR("finalize_multisig should only be used for N-1/N wallets, use exchange_multisig_keys instead"); + oxen::log::error(logcat, "finalize_multisig should only be used for N-1/N wallets, use exchange_multisig_keys instead"); return false; } exchange_multisig_keys(password, pkeys, signers); @@ -5387,7 +5382,7 @@ bool wallet2::finalize_multisig(const epee::wipeable_string &password, const std std::vector signers; if (!unpack_extra_multisig_info(info, signers, public_keys)) { - MERROR("Bad multisig info"); + oxen::log::error(logcat, "Bad multisig info"); return false; } @@ -5417,18 +5412,18 @@ bool wallet2::verify_multisig_info(const std::string &data, crypto::secret_key & { if (!tools::starts_with(data, MULTISIG_MAGIC)) { - MERROR("Multisig info header check error"); + oxen::log::error(logcat, "Multisig info header check error"); return false; } std::string decoded; if (!tools::base58::decode(data.substr(MULTISIG_MAGIC.size()), decoded)) { - MERROR("Multisig info decoding error"); + oxen::log::error(logcat, "Multisig info decoding error"); return false; } if (decoded.size() != sizeof(crypto::secret_key) + sizeof(crypto::public_key) + sizeof(crypto::signature)) { - MERROR("Multisig info is corrupt"); + oxen::log::error(logcat, "Multisig info is corrupt"); return false; } @@ -5443,7 +5438,7 @@ bool wallet2::verify_multisig_info(const std::string &data, crypto::secret_key & crypto::cn_fast_hash(decoded.data(), decoded.size() - sizeof(signature), hash); if (!crypto::check_signature(hash, pkey, signature)) { - MERROR("Multisig info signature is invalid"); + oxen::log::error(logcat, "Multisig info signature is invalid"); return false; } @@ -5454,23 +5449,23 @@ bool wallet2::verify_extra_multisig_info(const std::string &data, std::unordered { if (!tools::starts_with(data, MULTISIG_EXTRA_INFO_MAGIC)) { - MERROR("Multisig info header check error"); + oxen::log::error(logcat, "Multisig info header check error"); return false; } std::string decoded; if (!tools::base58::decode(data.substr(MULTISIG_EXTRA_INFO_MAGIC.size()), decoded)) { - MERROR("Multisig info decoding error"); + oxen::log::error(logcat, "Multisig info decoding error"); return false; } if (decoded.size() < sizeof(crypto::public_key) + sizeof(crypto::signature)) { - MERROR("Multisig info is corrupt"); + oxen::log::error(logcat, "Multisig info is corrupt"); return false; } if ((decoded.size() - (sizeof(crypto::public_key) + sizeof(crypto::signature))) % sizeof(crypto::public_key)) { - MERROR("Multisig info is corrupt"); + oxen::log::error(logcat, "Multisig info is corrupt"); return false; } @@ -5484,7 +5479,7 @@ bool wallet2::verify_extra_multisig_info(const std::string &data, std::unordered crypto::cn_fast_hash(decoded.data(), decoded.size() - sizeof(signature), hash); if (!crypto::check_signature(hash, signer, signature)) { - MERROR("Multisig info signature is invalid"); + oxen::log::error(logcat, "Multisig info signature is invalid"); return false; } @@ -5675,7 +5670,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor { THROW_WALLET_EXCEPTION_IF(true, error::file_read_error, m_keys_file); } - LOG_PRINT_L0("Loaded wallet keys file, with public address: " << m_account.get_public_address_str(m_nettype)); + oxen::log::warning(logcat, "Loaded wallet keys file, with public address: {}", m_account.get_public_address_str(m_nettype)); lock_keys_file(); } else if (!load_keys_buf(keys_buf, password)) @@ -5689,7 +5684,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor //try to load wallet file. but even if we failed, it is not big problem if (use_fs && (!fs::exists(m_wallet_file, e) || e)) { - LOG_PRINT_L0("file not found: " << m_wallet_file << ", starting with empty blockchain"); + oxen::log::warning(logcat, "file not found: {}, starting with empty blockchain", m_wallet_file); m_account_public_address = m_account.get_keys().m_account_address; } else if (use_fs || !cache_buf.empty()) @@ -5706,7 +5701,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor // try to read it as an encrypted cache try { - LOG_PRINT_L1("Trying to decrypt cache data"); + oxen::log::info(logcat, "Trying to decrypt cache data"); try { serialization::parse_binary(use_fs ? cache_file_buf : cache_buf, cache_file_data); @@ -5747,7 +5742,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - LOG_PRINT_L0("Failed to open portable binary, trying unportable"); + oxen::log::warning(logcat, "Failed to open portable binary, trying unportable"); auto unportable = m_wallet_file; unportable += ".unportable"; if (use_fs) fs::copy_file(m_wallet_file, unportable, fs::copy_options::overwrite_existing); @@ -5761,7 +5756,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - LOG_PRINT_L1("Failed to load encrypted cache, trying unencrypted"); + oxen::log::info(logcat, "Failed to load encrypted cache, trying unencrypted"); try { std::stringstream iss; iss << cache_file_buf; @@ -5770,7 +5765,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - LOG_PRINT_L0("Failed to open portable binary, trying unportable"); + oxen::log::warning(logcat, "Failed to open portable binary, trying unportable"); auto unportable = m_wallet_file; unportable += ".unportable"; if (use_fs) fs::copy_file(m_wallet_file, unportable, fs::copy_options::overwrite_existing); @@ -5818,7 +5813,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (const std::exception &e) { - MERROR("Failed to save rings, will try again next time"); + oxen::log::error(logcat, "Failed to save rings, will try again next time"); } #ifdef WALLET_ENABLE_MMS @@ -5829,7 +5824,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (const std::exception &e) { - MERROR("Failed to initialize MMS, it will be unusable"); + oxen::log::error(logcat, "Failed to initialize MMS, it will be unusable"); } #endif } @@ -5845,7 +5840,7 @@ void wallet2::trim_hashchain() if (!m_blockchain.empty() && m_blockchain.size() == m_blockchain.offset()) { - MINFO("Fixing empty hashchain"); + oxen::log::info(logcat, "Fixing empty hashchain"); nlohmann::json req_params{ {"height", m_blockchain.size() - 1} }; @@ -5859,19 +5854,19 @@ void wallet2::trim_hashchain() } else { - MERROR("Failed to request block header from daemon, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); + oxen::log::error(logcat, "Failed to request block header from daemon, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); } } catch (const std::exception &e) { - MERROR("Failed to request block header from daemon when requesting get_block_header_by_height, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); + oxen::log::error(logcat, "Failed to request block header from daemon when requesting get_block_header_by_height, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); } } if (height > 0 && m_blockchain.size() > height) { --height; - MDEBUG("trimming to " << height << ", offset " << m_blockchain.offset()); + oxen::log::debug(logcat, "trimming to {}, offset {}", height, m_blockchain.offset()); m_blockchain.trim(height); } m_cached_height = m_blockchain.size(); @@ -5941,18 +5936,18 @@ void wallet2::store_to(const fs::path &path, const epee::wipeable_string &passwo THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_wallet_file); // remove old address file if (!fs::remove(old_address_file, ec)) - LOG_ERROR("error removing file: " << old_address_file << ": " << ec.message()); + oxen::log::error(logcat, "error removing file: {}: {}", old_address_file, ec.message()); } // remove old wallet file if (!fs::remove(old_file, ec)) - LOG_ERROR("error removing file: " << old_file << ": " << ec.message()); + oxen::log::error(logcat, "error removing file: {}: {}", old_file, ec.message()); // remove old keys file if (!fs::remove(old_keys_file, ec)) - LOG_ERROR("error removing file: " << old_keys_file << ": " << ec.message()); + oxen::log::error(logcat, "error removing file: {}: {}", old_keys_file, ec.message()); #ifdef WALLET_ENABLE_MMS // remove old message store file if (fs::exists(m_mms_file, ec) && !fs::remove(m_mms_file, ec)) - LOG_ERROR("error removing file: " << m_mms_file << ": " << ec.message()); + oxen::log::error(logcat, "error removing file: {}: {}", m_mms_file, ec.message()); #endif } else { // save to new file @@ -6307,8 +6302,7 @@ void wallet2::get_transfers(get_transfers_args_t args, std::vector> pending_or_failed; std::list> pool; - MDEBUG("Getting transfers of type(s) " << (args.in ? "in " : "") << (args.out ? "out " : "") << (args.pending ? "pending " : "") << (args.failed ? "failed " : "") - << (args.pool ? "pool " : "") << " for heights in [" << args.min_height << "," << args.max_height << "]"); + oxen::log::debug(logcat, "Getting transfers of type(s) {}{}{}{}{} for heights in[{},{}]", (args.in ? "in " : ""), (args.out ? "out " : ""), (args.pending ? "pending " : ""), (args.failed ? "failed " : ""), (args.pool ? "pool " : ""), args.min_height, args.max_height); size_t size = 0; if (args.in) @@ -6407,7 +6401,7 @@ std::string wallet2::transfers_to_csv(const std::vector& running_balance -= transfer.amount + transfer.fee; break; default: - MERROR("Warning: Unhandled pay type, this is most likely a developer error, please report it to the Oxen developers."); + oxen::log::error(logcat, "Warning: Unhandled pay type, this is most likely a developer error, please report it to the Oxen developers."); break; } @@ -6526,12 +6520,12 @@ std::optional wallet2::resolve_address(std::string address, uint64_ { info = std::move(*addr_info); result = true; - LOG_PRINT_L2("Resolved ONS name: "<< address << " to address: " << get_account_address_as_str(m_nettype, info.is_subaddress, info.address)); + oxen::log::debug(logcat, "Resolved ONS name: {} to address: {}", address, get_account_address_as_str(m_nettype, info.is_subaddress, info.address)); } } } else { - LOG_PRINT_L2("Invalid address format, could not resolve " << address); + oxen::log::debug(logcat, "Invalid address format, could not resolve {}", address); } } @@ -6560,7 +6554,7 @@ void wallet2::rescan_spent() for (size_t start_offset = 0; start_offset < m_transfers.size(); start_offset += chunk_size) { const size_t n_outputs = std::min(chunk_size, m_transfers.size() - start_offset); - MDEBUG("Calling is_key_image_spent on " << start_offset << " - " << (start_offset + n_outputs - 1) << ", out of " << m_transfers.size()); + oxen::log::debug(logcat, "Calling is_key_image_spent on {} - {}, out of {}", start_offset, (start_offset + n_outputs - 1), m_transfers.size()); std::vector key_images; key_images.reserve(n_outputs); for (size_t n = start_offset; n < start_offset + n_outputs; ++n) @@ -6589,13 +6583,13 @@ void wallet2::rescan_spent() { if (td.m_spent) { - LOG_PRINT_L0("Marking output " << i << "(" << td.m_key_image << ") as unspent, it was marked as spent"); + oxen::log::warning(logcat, "Marking output {}({}) as unspent, it was marked as spent", i, td.m_key_image); set_unspent(i); td.m_spent_height = 0; } else { - LOG_PRINT_L0("Marking output " << i << "(" << td.m_key_image << ") as spent, it was marked as unspent"); + oxen::log::warning(logcat, "Marking output {}({}) as spent, it was marked as unspent", i, td.m_key_image); set_spent(i, td.m_spent_height); // unknown height, if this gets reorged, it might still be missed } @@ -6666,7 +6660,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, if (!success) { // We'll already have a log message printed containing the request failure reason - LOG_PRINT_L1("Failed to query service node for blacklisted transfers, assuming transfer not blacklisted"); + oxen::log::info(logcat, "Failed to query service node for blacklisted transfers, assuming transfer not blacklisted"); return true; } @@ -6675,7 +6669,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, crypto::key_image check_image; if(!tools::hex_to_type(entry["key_image"].get(), check_image)) { - MERROR("Failed to parse hex representation of key image: " << entry["key_image"]); + oxen::log::error(logcat, "Failed to parse hex representation of key image: {}", entry["key_image"]); break; } @@ -6690,7 +6684,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, auto [success, service_nodes_states] = m_node_rpc_proxy.get_contributed_service_nodes(primary_address); if (!success) { - LOG_PRINT_L1("Failed to query service node for locked transfers, assuming transfer not locked"); + oxen::log::info(logcat, "Failed to query service node for locked transfers, assuming transfer not locked"); return true; } @@ -6706,7 +6700,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, crypto::key_image check_image; if(!tools::hex_to_type(contribution["key_image"].get(), check_image)) { - MERROR("Failed to parse hex representation of key image: " << contribution["key_image"]); + oxen::log::error(logcat, "Failed to parse hex representation of key image: {}", contribution["key_image"]); break; } @@ -6919,7 +6913,7 @@ crypto::hash wallet2::get_payment_id(const pending_tx &ptx) const { if (ptx.dests.empty()) { - MWARNING("Encrypted payment id found, but no destinations public key, cannot decrypt"); + oxen::log::warning(logcat, "Encrypted payment id found, but no destinations public key, cannot decrypt"); return crypto::null_hash; } if (m_account.get_device().decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key)) @@ -6998,7 +6992,7 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) m_additional_tx_keys.insert(std::make_pair(txid, ptx.additional_tx_keys)); } - LOG_PRINT_L2("transaction " << txid << " generated ok and sent to daemon, key_images: [" << ptx.key_images << "]"); + oxen::log::debug(logcat, "transaction {} generated ok and sent to daemon, key_images: [{}]", txid, ptx.key_images); for(size_t idx: ptx.selected_transfers) { @@ -7010,11 +7004,12 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) memwipe(m_transfers[idx].m_multisig_k.data(), m_transfers[idx].m_multisig_k.size() * sizeof(m_transfers[idx].m_multisig_k[0])); //fee includes dust if dust policy specified it. - LOG_PRINT_L1("Transaction successfully " << (blink ? "blinked. " : "sent. ") << txid - << "\nCommission: " << print_money(ptx.fee) << " (dust sent to dust addr: " << print_money((ptx.dust_added_to_fee ? 0 : ptx.dust)) << ")" - << "\nBalance: " << print_money(balance(ptx.construction_data.subaddr_account, false)) - << "\nUnlocked: " << print_money(unlocked_balance(ptx.construction_data.subaddr_account, false)) - << "\nPlease, wait for confirmation for your balance to be unlocked."); + oxen::log::info(logcat, "Transaction successfully {}{} \ + \nCommission: {} (dust sent to dust addr: {})\ + \nBalance: {} \ + \nUnlocked: {} \ + \nPlease, wait for confirmation for your balance to be unlocked.", + (blink ? "blinked. " : "sent. "), txid, print_money(ptx.fee), print_money((ptx.dust_added_to_fee ? 0 : ptx.dust)), print_money(balance(ptx.construction_data.subaddr_account, false)), print_money(unlocked_balance(ptx.construction_data.subaddr_account, false))); } void wallet2::commit_tx(std::vector& ptx_vector, bool blink) @@ -7027,7 +7022,7 @@ void wallet2::commit_tx(std::vector& ptx_vector, bool blink) //---------------------------------------------------------------------------------------------------- bool wallet2::save_tx(const std::vector& ptx_vector, const fs::path& filename) const { - LOG_PRINT_L0("saving " << ptx_vector.size() << " transactions"); + oxen::log::warning(logcat, "saving {} transactions", ptx_vector.size()); std::string ciphertext = dump_tx_to_str(ptx_vector); if (ciphertext.empty()) return false; @@ -7036,7 +7031,7 @@ bool wallet2::save_tx(const std::vector& ptx_vector, const fs::path& //---------------------------------------------------------------------------------------------------- std::string wallet2::dump_tx_to_str(const std::vector &ptx_vector) const { - LOG_PRINT_L0("saving " << ptx_vector.size() << " transactions"); + oxen::log::warning(logcat, "saving {} transactions", ptx_vector.size()); unsigned_tx_set txs; for (auto &tx: ptx_vector) { @@ -7058,7 +7053,7 @@ std::string wallet2::dump_tx_to_str(const std::vector &ptx_vector) c { return std::string(); } - LOG_PRINT_L2("Saving unsigned tx data: " << oss.str()); + oxen::log::debug(logcat, "Saving unsigned tx data: {}", oss.str()); std::string ciphertext = encrypt_with_view_secret_key(oss.str()); return std::string(UNSIGNED_TX_PREFIX) + ciphertext; } @@ -7067,14 +7062,14 @@ bool wallet2::load_unsigned_tx(const fs::path& unsigned_filename, unsigned_tx_se { if (std::error_code ec; !fs::exists(unsigned_filename, ec)) { - LOG_PRINT_L0("File " << unsigned_filename << " does not exist: " << ec.message()); + oxen::log::warning(logcat, "File {} does not exist: {}", unsigned_filename, ec.message()); return false; } std::string s; if (!tools::slurp_file(unsigned_filename, s)) { - LOG_PRINT_L0("Failed to load from " << unsigned_filename); + oxen::log::warning(logcat, "Failed to load from {}", unsigned_filename); return false; } @@ -7085,7 +7080,7 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex { if (!tools::starts_with(s, UNSIGNED_TX_PREFIX_NOVER)) { - LOG_PRINT_L0("Bad magic from unsigned tx"); + oxen::log::warning(logcat, "Bad magic from unsigned tx"); return false; } s.remove_prefix(UNSIGNED_TX_PREFIX_NOVER.size()); @@ -7102,7 +7097,7 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex } catch (...) { - LOG_PRINT_L0("Failed to parse data from unsigned tx"); + oxen::log::warning(logcat, "Failed to parse data from unsigned tx"); return false; } } @@ -7119,22 +7114,22 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex } catch (...) { - LOG_PRINT_L0("Failed to parse data from unsigned tx"); + oxen::log::warning(logcat, "Failed to parse data from unsigned tx"); return false; } } catch (const std::exception &e) { - LOG_PRINT_L0("Failed to decrypt unsigned tx: " << e.what()); + oxen::log::warning(logcat, "Failed to decrypt unsigned tx: {}", e.what()); return false; } } else { - LOG_PRINT_L0("Unsupported version in unsigned tx"); + oxen::log::warning(logcat, "Unsupported version in unsigned tx"); return false; } - LOG_PRINT_L1("Loaded tx unsigned data from binary: " << exported_txs.txes.size() << " transactions"); + oxen::log::info(logcat, "Loaded tx unsigned data from binary: {} transactions", exported_txs.txes.size()); return true; } @@ -7147,7 +7142,7 @@ bool wallet2::sign_tx(const fs::path& unsigned_filename, const fs::path& signed_ if (accept_func && !accept_func(exported_txs)) { - LOG_PRINT_L1("Transactions rejected by callback"); + oxen::log::info(logcat, "Transactions rejected by callback"); return false; } return sign_tx(exported_txs, signed_filename, txs, export_raw); @@ -7162,7 +7157,7 @@ bool wallet2::sign_tx(unsigned_tx_set &exported_txs, std::vector 1) raw_filename += "_" + std::to_string(i); if (!tools::dump_file(raw_filename, tx_as_hex)) { - LOG_PRINT_L0("Failed to save file to " << raw_filename); + oxen::log::warning(logcat, "Failed to save file to {}", raw_filename); return false; } } @@ -7326,7 +7321,7 @@ std::string wallet2::sign_tx_dump_to_str(unsigned_tx_set &exported_txs, std::vec bool r = sign_tx(exported_txs, ptx, signed_txes); if (!r) { - LOG_PRINT_L0("Failed to sign unsigned_tx_set"); + oxen::log::warning(logcat, "Failed to sign unsigned_tx_set"); return std::string(); } @@ -7341,7 +7336,7 @@ std::string wallet2::sign_tx_dump_to_str(unsigned_tx_set &exported_txs, std::vec { return std::string(); } - LOG_PRINT_L3("Saving signed tx data (with encryption): " << oss.str()); + oxen::log::trace(logcat, "Saving signed tx data (with encryption): {}", oss.str()); std::string ciphertext = encrypt_with_view_secret_key(oss.str()); return std::string(SIGNED_TX_PREFIX) + ciphertext; } @@ -7350,14 +7345,14 @@ bool wallet2::load_tx(const fs::path& signed_filename, std::vector txs_hashes; @@ -8014,7 +8008,7 @@ bool wallet2::find_and_save_rings(bool force) for (const auto& [txid, details]: payments) txs_hashes.push_back(txid); - MDEBUG("Found " << std::to_string(txs_hashes.size()) << " transactions"); + oxen::log::debug(logcat, "Found {} transactions", std::to_string(txs_hashes.size())); // get those transactions from the daemon auto it = txs_hashes.begin(); @@ -8027,7 +8021,7 @@ bool wallet2::find_and_save_rings(bool force) }; auto res = m_http_client.json_rpc("get_transactions", get_transactions_params); - MDEBUG("Scanning " << res["txs"].size() << " transactions"); + oxen::log::debug(logcat, "Scanning {} transactions", res["txs"].size()); for (size_t i = 0; i < res["txs"].size(); ++i, ++it) { const auto &tx_info = res["txs"][i]; @@ -8040,7 +8034,7 @@ bool wallet2::find_and_save_rings(bool force) } } - MINFO("Found and saved rings for " << txs_hashes.size() << " transactions"); + oxen::log::info(logcat, "Found and saved rings for {} transactions", txs_hashes.size()); m_ring_history_saved = true; return true; } @@ -8991,7 +8985,7 @@ bool wallet2::lock_keys_file() return true; if (m_keys_file_locker) { - MDEBUG(m_keys_file << " is already locked."); + oxen::log::debug(logcat, "{} is already locked.", m_keys_file); return false; } m_keys_file_locker.reset(new tools::file_locker(m_keys_file)); @@ -9004,7 +8998,7 @@ bool wallet2::unlock_keys_file() return true; if (!m_keys_file_locker) { - MDEBUG(m_keys_file << " is already unlocked."); + oxen::log::debug(logcat, "{} is already unlocked.", m_keys_file); return false; } m_keys_file_locker.reset(); @@ -9076,13 +9070,13 @@ bool wallet2::tx_add_fake_output(std::vector> void wallet2::get_outs(std::vector> &outs, const std::vector &selected_transfers, size_t fake_outputs_count, std::vector &rct_offsets, bool has_rct) { - LOG_PRINT_L2("fake_outputs_count: " << fake_outputs_count); + oxen::log::debug(logcat, "fake_outputs_count: {}", fake_outputs_count); outs.clear(); #ifdef ENABLE_LIGHT_WALLET @@ -9195,9 +9189,7 @@ void wallet2::get_outs(std::vector> std::sort(output_blacklist.begin(), output_blacklist.end()); if (output_blacklist.size() * 0.05 > (double)rct_offsets.size()) { - MWARNING("More than 5% of outputs are blacklisted (" - << output_blacklist.size() << "/" << rct_offsets.size() - << "), please notify the Oxen developers"); + oxen::log::warning(logcat, "More than 5% of outputs are blacklisted ({}/{}), please notify the Oxen developers", output_blacklist.size(), rct_offsets.size()); } nlohmann::json res; @@ -9264,7 +9256,7 @@ void wallet2::get_outs(std::vector> // we ask for more, to have spares if some outputs are still locked size_t base_requested_outputs_count = (size_t)((fake_outputs_count + 1) * 1.5 + 1); - LOG_PRINT_L2("base_requested_outputs_count: " << base_requested_outputs_count); + oxen::log::debug(logcat, "base_requested_outputs_count: {}", base_requested_outputs_count); // generate output indices to request rpc::GET_OUTPUTS_BIN::request req{}; @@ -9305,8 +9297,7 @@ void wallet2::get_outs(std::vector> { if (he["amount"].get() == amount) { - LOG_PRINT_L2("Found " << print_money(amount) << ": " << he["total_instances"] << " total, " - << he["unlocked_instances"] << " unlocked, " << he["recent_instances"] << " recent"); + oxen::log::debug(logcat, "Found {}: {} total, {} unlocked, {} recent", print_money(amount), he["total_instances"], he["unlocked_instances"], he["recent_instances"]); num_outs = he["unlocked_instances"].get(); num_recent_outs = he["recent_instances"].get(); break; @@ -9342,7 +9333,7 @@ void wallet2::get_outs(std::vector> if (use_histogram) { - LOG_PRINT_L1("" << num_outs << " unlocked outputs of size " << print_money(amount)); + oxen::log::info(logcat, "{} unlocked outputs of size {}", num_outs, print_money(amount)); THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, "histogram reports no unlocked outputs for " + std::to_string(amount) + ", not even ours"); THROW_WALLET_EXCEPTION_IF(num_recent_outs > num_outs, error::wallet_internal_error, @@ -9352,7 +9343,7 @@ void wallet2::get_outs(std::vector> { // the base offset of the first rct output in the first unlocked block (or the one to be if there's none) num_outs = rct_offsets[rct_offsets.size() - DEFAULT_TX_SPENDABLE_AGE]; - LOG_PRINT_L1("" << num_outs << " unlocked rct outputs"); + oxen::log::info(logcat, "{} unlocked rct outputs", num_outs); THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, "histogram reports no unlocked rct outputs, not even ours"); } @@ -9375,9 +9366,7 @@ void wallet2::get_outs(std::vector> if (td.m_global_output_index >= num_outs - num_recent_outs && recent_outputs_count > 0) --recent_outputs_count; // if the real out is recent, pick one less recent fake out } - LOG_PRINT_L1("Fake output makeup: " << requested_outputs_count << " requested: " << recent_outputs_count << " recent, " << - pre_fork_outputs_count << " pre-fork, " << post_fork_outputs_count << " post-fork, " << - (requested_outputs_count - recent_outputs_count - pre_fork_outputs_count - post_fork_outputs_count) << " full-chain"); + oxen::log::info(logcat, "Fake output makeup: {} requested: {} recent, {} pre-fork, {} post-fork, {} full-chain", requested_outputs_count, recent_outputs_count, pre_fork_outputs_count, post_fork_outputs_count, (requested_outputs_count - recent_outputs_count - pre_fork_outputs_count - post_fork_outputs_count)); uint64_t num_found = 0; @@ -9387,7 +9376,7 @@ void wallet2::get_outs(std::vector> std::vector ring; if (get_ring(get_ringdb_key(), td.m_key_image, ring)) { - MINFO("This output has a known ring, reusing (size " << ring.size() << ")"); + oxen::log::info(logcat, "This output has a known ring, reusing (size {})", ring.size()); THROW_WALLET_EXCEPTION_IF(ring.size() > fake_outputs_count + 1, error::wallet_internal_error, "An output in this transaction was previously spent on another chain with ring size " + std::to_string(ring.size()) + ", it cannot be spent now with ring size " + @@ -9395,22 +9384,22 @@ void wallet2::get_outs(std::vector> bool own_found = false; for (const auto &out: ring) { - MINFO("Ring has output " << out); + oxen::log::info(logcat, "Ring has output {}", out); if (out < num_outs) { - MINFO("Using it"); + oxen::log::info(logcat, "Using it"); get_outputs.push_back({amount, out}); ++num_found; seen_indices.emplace(out); if (out == td.m_global_output_index) { - MINFO("This is the real output"); + oxen::log::info(logcat, "This is the real output"); own_found = true; } } else { - MINFO("Ignoring output " << out << ", too recent"); + oxen::log::info(logcat, "Ignoring output {}, too recent", out); } } THROW_WALLET_EXCEPTION_IF(!own_found, error::wallet_internal_error, @@ -9436,7 +9425,7 @@ void wallet2::get_outs(std::vector> num_found = 1; seen_indices.emplace(td.m_global_output_index); get_outputs.push_back({amount, td.m_global_output_index}); - LOG_PRINT_L1("Selecting real output: " << td.m_global_output_index << " for " << print_money(amount)); + oxen::log::info(logcat, "Selecting real output: {} for {}", td.m_global_output_index, print_money(amount)); } std::unordered_map> picks; @@ -9444,8 +9433,7 @@ void wallet2::get_outs(std::vector> // while we still need more mixins uint64_t num_usable_outs = num_outs; bool allow_blackballed_or_blacklisted = false; - MDEBUG("Starting gamma picking with " << num_outs << ", num_usable_outs " << num_usable_outs - << ", requested_outputs_count " << requested_outputs_count); + oxen::log::debug(logcat, "Starting gamma picking with {}, num_usable_outs {}, requested_outputs_count {}", num_outs, num_usable_outs, requested_outputs_count); while (num_found < requested_outputs_count) { // if we've gone through every possible output, we've gotten all we can @@ -9457,7 +9445,7 @@ void wallet2::get_outs(std::vector> // outputs, we still need to reach the minimum ring size) if (allow_blackballed_or_blacklisted) break; - MINFO("Not enough output not marked as spent, we'll allow outputs marked as spent and outputs with known destinations and amounts"); + oxen::log::info(logcat, "Not enough output not marked as spent, we'll allow outputs marked as spent and outputs with known destinations and amounts"); allow_blackballed_or_blacklisted = true; num_usable_outs = num_outs; } @@ -9549,17 +9537,17 @@ void wallet2::get_outs(std::vector> picks[type].insert(i); get_outputs.push_back({amount, i}); ++num_found; - MDEBUG("picked " << i << ", " << num_found << " now picked"); + oxen::log::debug(logcat, "picked {}, {} now picked", i, num_found); } - if (LOG_ENABLED(Debug)) + if (OXEN_LOG_ENABLED(debug)) { for (const auto &pick: picks) { std::string outputs; for (const auto& out : pick.second) outputs += " " + std::to_string(out); - MDEBUG("picking " << pick.first << " outputs:" << outputs); + oxen::log::debug(logcat, "picking {} outputs:{}", pick.first, outputs); } } @@ -9578,19 +9566,19 @@ void wallet2::get_outs(std::vector> [](const auto& a, const auto& b) { return a.index < b.index; }); } - if (ELPP->vRegistry()->allowed(el::Level::Debug, OXEN_DEFAULT_LOG_CATEGORY)) + if (OXEN_LOG_ENABLED(debug)) { std::map> outs; for (const auto &i: get_outputs) outs[i.amount].insert(i.index); - if (LOG_ENABLED(Debug)) + if (OXEN_LOG_ENABLED(debug)) { for (const auto &o: outs) { std::string outputs; for (const auto& out : o.second) outputs += " " + std::to_string(out); - MDEBUG("asking for outputs with amount " << print_money(o.first) << ":" << outputs); + oxen::log::debug(logcat, "asking for outputs with amount {}:{}", print_money(o.first), outputs); } } } @@ -9692,7 +9680,7 @@ void wallet2::get_outs(std::vector> size_t i = base + o; if (get_outputs[i].index == out) { - LOG_PRINT_L2("Index " << i << "/" << requested_outputs_count << ": idx " << get_outputs[i].index << " (real " << td.m_global_output_index << "), unlocked " << got_outs[i].unlocked << ", key " << got_outs[i].key << " (from existing ring)"); + oxen::log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {} (from existing ring)", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); tx_add_fake_output(outs, get_outputs[i].index, got_outs[i].key, got_outs[i].mask, td.m_global_output_index, got_outs[i].unlocked); found = true; break; @@ -9713,11 +9701,11 @@ void wallet2::get_outs(std::vector> order[n] = n; std::shuffle(order.begin(), order.end(), crypto::random_device{}); - LOG_PRINT_L2("Looking for " << (fake_outputs_count+1) << " outputs of size " << print_money(td.is_rct() ? 0 : td.amount())); + oxen::log::debug(logcat, "Looking for {} outputs of size {}", (fake_outputs_count+1), print_money(td.is_rct() ? 0 : td.amount())); for (size_t o = 0; o < requested_outputs_count && outs.back().size() < fake_outputs_count + 1; ++o) { size_t i = base + order[o]; - LOG_PRINT_L2("Index " << i << "/" << requested_outputs_count << ": idx " << get_outputs[i].index << " (real " << td.m_global_output_index << "), unlocked " << got_outs[i].unlocked << ", key " << got_outs[i].key); + oxen::log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {}", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); tx_add_fake_output(outs, get_outputs[i].index, got_outs[i].key, got_outs[i].mask, td.m_global_output_index, got_outs[i].unlocked); } if (outs.back().size() < fake_outputs_count + 1) @@ -9756,7 +9744,7 @@ void wallet2::get_outs(std::vector> for (const auto &e: outs[i]) ring.push_back(std::get<0>(e)); if (!set_ring(td.m_key_image, ring, false)) - MERROR("Failed to set ring for " << td.m_key_image); + oxen::log::error(logcat, "Failed to set ring for {}", td.m_key_image); } } @@ -9769,8 +9757,8 @@ void wallet2::transfer_selected_rct(std::vector m_multisig_threshold) { @@ -9835,7 +9823,7 @@ void wallet2::transfer_selected_rct(std::vector sources; std::unordered_set used_L; @@ -9916,12 +9904,12 @@ void wallet2::transfer_selected_rct(std::vector splitted_dsts = dsts; @@ -9937,10 +9925,10 @@ void wallet2::transfer_selected_rct(std::vector additional_tx_keys; rct::multisig_out msout; - LOG_PRINT_L2("constructing tx"); + oxen::log::debug(logcat, "constructing tx"); auto sources_copy = sources; bool r = cryptonote::construct_tx_and_get_tx_key( m_account.get_keys(), @@ -9990,7 +9978,7 @@ void wallet2::transfer_selected_rct(std::vector bool { @@ -10070,7 +10058,7 @@ void wallet2::transfer_selected_rct(std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, uint32_t subaddr_account, const std::set &subaddr_indices) const @@ -10111,7 +10099,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui std::vector picks; float current_output_relatdness = 1.0f; - LOG_PRINT_L2("pick_preferred_rct_inputs: needed_money " << print_money(needed_money)); + oxen::log::debug(logcat, "pick_preferred_rct_inputs: needed_money {}", print_money(needed_money)); // try to find a rct input of enough size for (size_t i = 0; i < m_transfers.size(); ++i) @@ -10121,10 +10109,10 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui { if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); + oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } - LOG_PRINT_L2("We can use " << i << " alone: " << print_money(td.amount())); + oxen::log::debug(logcat, "We can use {} alone: {}", i, print_money(td.amount())); picks.push_back(i); return picks; } @@ -10141,16 +10129,16 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui { if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); + oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } - LOG_PRINT_L2("Considering input " << i << ", " << print_money(td.amount())); + oxen::log::debug(logcat, "Considering input {}, {}", i, print_money(td.amount())); for (size_t j = i + 1; j < m_transfers.size(); ++j) { const transfer_details& td2 = m_transfers[j]; if (td2.amount() > m_ignore_outputs_above || td2.amount() < m_ignore_outputs_below) { - MDEBUG("Ignoring output " << j << " of amount " << print_money(td2.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); + oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", j, print_money(td2.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } if (!is_spent(td2, false) && !td2.m_frozen && !td.m_key_image_partial && td2.is_rct() && td.amount() + td2.amount() >= needed_money && is_transfer_unlocked(td2) && td2.m_subaddr_index == td.m_subaddr_index) @@ -10159,7 +10147,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui // already found. If the same, don't update, and oldest suitable outputs // will be used in preference. float relatedness = get_output_relatedness(td, td2); - LOG_PRINT_L2(" with input " << j << ", " << print_money(td2.amount()) << ", relatedness " << relatedness); + oxen::log::debug(logcat, " with input {}, {}, relatedness {}", j, print_money(td2.amount()), relatedness); if (relatedness < current_output_relatdness) { // reset the current picks with those, and return them directly @@ -10168,7 +10156,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui picks.clear(); picks.push_back(i); picks.push_back(j); - LOG_PRINT_L0("we could use " << i << " and " << j); + oxen::log::warning(logcat, "we could use {} and {}", i, j); if (relatedness == 0.0f) return picks; current_output_relatdness = relatedness; @@ -10236,7 +10224,7 @@ static uint32_t get_count_above(const std::vector &tr #ifdef ENABLE_LIGHT_WALLET void wallet2::light_wallet_get_outs(std::vector> &outs, const std::vector &selected_transfers, size_t fake_outputs_count) { - MDEBUG("LIGHTWALLET - Getting random outs"); + oxen::log::debug(logcat, "LIGHTWALLET - Getting random outs"); light_rpc::GET_RANDOM_OUTS::request oreq{}; light_rpc::GET_RANDOM_OUTS::response ores{}; @@ -10260,10 +10248,10 @@ void wallet2::light_wallet_get_outs(std::vector order; @@ -10285,8 +10273,8 @@ void wallet2::light_wallet_get_outs(std::vector(a) < std::get<0>(b); }); // Print output order for(auto added_out: outs.back()) - MTRACE(std::get<0>(added_out)); + oxen::log::trace( std::get<0>(added_out)); } } bool wallet2::light_wallet_login(bool &new_address) { - MDEBUG("Light wallet login request"); + oxen::log::debug(logcat, "Light wallet login request"); m_light_wallet_connected = false; light_rpc::LOGIN::request request{}; light_rpc::LOGIN::response response{}; @@ -10350,9 +10338,9 @@ bool wallet2::light_wallet_login(bool &new_address) // MyMonero doesn't send any status message. OpenMonero does. m_light_wallet_connected = connected && (response.status.empty() || response.status == "success"); new_address = response.new_address; - MDEBUG("Status: " << response.status); - MDEBUG("Reason: " << response.reason); - MDEBUG("New wallet: " << response.new_address); + oxen::log::debug(logcat, "Status: {}", response.status); + oxen::log::debug(logcat, "Reason: {}", response.reason); + oxen::log::debug(logcat, "New wallet: {}", response.new_address); if(m_light_wallet_connected) { // Clear old data on successful login. @@ -10365,7 +10353,7 @@ bool wallet2::light_wallet_login(bool &new_address) bool wallet2::light_wallet_import_wallet_request(light_rpc::IMPORT_WALLET_REQUEST::response &response) { - MDEBUG("Light wallet import wallet request"); + oxen::log::debug(logcat, "Light wallet import wallet request"); light_rpc::IMPORT_WALLET_REQUEST::request oreq{}; oreq.address = get_account().get_public_address_str(m_nettype); oreq.view_key = tools::type_to_hex(get_account().get_keys().m_view_secret_key); @@ -10378,7 +10366,7 @@ bool wallet2::light_wallet_import_wallet_request(light_rpc::IMPORT_WALLET_REQUES void wallet2::light_wallet_get_unspent_outs() { - MDEBUG("Getting unspent outs"); + oxen::log::debug(logcat, "Getting unspent outs"); light_rpc::GET_UNSPENT_OUTS::request oreq{}; light_rpc::GET_UNSPENT_OUTS::response ores{}; @@ -10403,7 +10391,7 @@ void wallet2::light_wallet_get_unspent_outs() for(const auto &t: m_transfers) transfers_txs.emplace(t.m_txid,t.m_spent); - MDEBUG("FOUND " << ores.outputs.size() <<" outputs"); + oxen::log::debug(logcat, "FOUND {} outputs", ores.outputs.size()); // return if no outputs found if(ores.outputs.empty()) @@ -10427,11 +10415,11 @@ void wallet2::light_wallet_get_unspent_outs() THROW_WALLET_EXCEPTION_IF(ski.size() != 64 || !oxenc::is_hex(ski), error::wallet_internal_error, "Invalid key image"); tools::hex_to_type(ski, unspent_key_image); if(light_wallet_key_image_is_ours(unspent_key_image, tx_public_key, o.index)){ - MTRACE("Output " << o.public_key << " is spent. Key image: " << ski); + oxen::log::trace(logcat, "Output {} is spent. Key image: {}", o.public_key, ski); spent = true; break; } { - MTRACE("Unspent output found. " << o.public_key); + oxen::log::trace(logcat, "Unspent output found. {}", o.public_key); } } @@ -10508,11 +10496,11 @@ void wallet2::light_wallet_get_unspent_outs() bool valid_commit = (rct_commit == rct::commit(td.amount(), td.m_mask)); if(!valid_commit) { - MDEBUG("output index: " << o.global_index); - MDEBUG("mask: " + tools::type_to_hex(td.m_mask)); - MDEBUG("calculated commit: " + tools::type_to_hex(rct::commit(td.amount(), td.m_mask))); - MDEBUG("expected commit: " + tools::type_to_hex(rct_commit)); - MDEBUG("amount: " << td.amount()); + oxen::log::debug(logcat, "output index: {}", o.global_index); + oxen::log::debug(logcat, "mask: " + tools::type_to_hex(td.m_mask)); + oxen::log::debug(logcat, "calculated commit: " + tools::type_to_hex(rct::commit(td.amount(), td.m_mask))); + oxen::log::debug(logcat, "expected commit: " + tools::type_to_hex(rct_commit)); + oxen::log::debug(logcat, "amount: {}", td.amount()); } THROW_WALLET_EXCEPTION_IF(!valid_commit, error::wallet_internal_error, "Lightwallet: rct commit hash mismatch!"); } @@ -10532,7 +10520,7 @@ void wallet2::light_wallet_get_unspent_outs() bool wallet2::light_wallet_get_address_info(light_rpc::GET_ADDRESS_INFO::response &response) { - MTRACE(__FUNCTION__); + oxen::log::trace( __FUNCTION__); light_rpc::GET_ADDRESS_INFO::request request{}; @@ -10546,7 +10534,7 @@ bool wallet2::light_wallet_get_address_info(light_rpc::GET_ADDRESS_INFO::respons void wallet2::light_wallet_get_address_txs() { - MDEBUG("Refreshing light wallet"); + oxen::log::debug(logcat, "Refreshing light wallet"); light_rpc::GET_ADDRESS_TXS::request ireq{}; light_rpc::GET_ADDRESS_TXS::response ires{}; @@ -10707,7 +10695,7 @@ void wallet2::light_wallet_get_address_txs() { if(confirmed_tx->second.m_amount_in != amount_sent || confirmed_tx->second.m_amount_out != amount_sent) { - MDEBUG("Adjusting amount sent/received for tx: <" + t.hash + ">. Is tx sent to own wallet? " << print_money(amount_sent) << " != " << print_money(confirmed_tx->second.m_amount_in)); + oxen::log::debug(logcat, "Adjusting amount sent/received for tx: <" + t.hash + ">. Is tx sent to own wallet? {} != {}", print_money(amount_sent), print_money(confirmed_tx->second.m_amount_in)); confirmed_tx->second.m_amount_in = amount_sent; confirmed_tx->second.m_amount_out = amount_sent; confirmed_tx->second.m_change = 0; @@ -10914,7 +10902,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); + oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } const uint32_t index_minor = td.m_subaddr_index.minor; @@ -11019,7 +11007,7 @@ std::vector wallet2::create_transactions_2(std::vector(); @@ -11043,7 +11031,7 @@ std::vector wallet2::create_transactions_2(std::vector preferred_inputs; { // this is used to build a tx that's 1 or 2 inputs, and 1 or 2 outputs, which will get us a known fee. @@ -11053,7 +11041,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector 0) || adding_fee || !preferred_inputs.empty() || should_pick_a_second_output(txes.back().selected_transfers.size(), *unused_transfers_indices, *unused_dust_indices)) { TX &tx = txes.back(); - LOG_PRINT_L2("Start of loop with " << unused_transfers_indices->size() << " " << unused_dust_indices->size() << ", tx.dsts.size() " << tx.dsts.size()); - LOG_PRINT_L2("unused_transfers_indices: " << tools::join(" ", *unused_transfers_indices)); - LOG_PRINT_L2("unused_dust_indices: " << tools::join(" ", *unused_dust_indices)); - LOG_PRINT_L2("dsts size " << dsts.size() << ", first " << (dsts.empty() ? "-" : cryptonote::print_money(dsts[0].amount))); - LOG_PRINT_L2("adding_fee " << adding_fee); + oxen::log::debug(logcat, "Start of loop with {} {}, tx.dsts.size() {}", unused_transfers_indices->size(), unused_dust_indices->size(), tx.dsts.size()); + oxen::log::debug(logcat, "unused_transfers_indices: {}", tools::join(" ", *unused_transfers_indices)); + oxen::log::debug(logcat, "unused_dust_indices: {}", tools::join(" ", *unused_dust_indices)); + oxen::log::debug(logcat, "dsts size {}, first {}", dsts.size(), (dsts.empty() ? "-" : cryptonote::print_money(dsts[0].amount))); + oxen::log::debug(logcat, "adding_fee {}", adding_fee); // if we need to spend money and don't have any left, we fail if (unused_dust_indices->empty() && unused_transfers_indices->empty()) { - LOG_PRINT_L2("No more outputs to choose from"); + oxen::log::debug(logcat, "No more outputs to choose from"); THROW_WALLET_EXCEPTION_IF(1, error::tx_not_possible, unlocked_balance(subaddr_account, false), needed_money, accumulated_fee + needed_fee); } @@ -11128,7 +11116,7 @@ std::vector wallet2::create_transactions_2(std::vector= min_output_value) { if (get_count_above(m_transfers, *unused_transfers_indices, min_output_value) < min_output_count) { - LOG_PRINT_L2("Second output was not strictly needed, and we're running out of outputs above " << print_money(min_output_value) << ", not adding"); + oxen::log::debug(logcat, "Second output was not strictly needed, and we're running out of outputs above {}, not adding", print_money(min_output_value)); break; } } @@ -11138,7 +11126,7 @@ std::vector wallet2::create_transactions_2(std::vector SECOND_OUTPUT_RELATEDNESS_THRESHOLD) { - LOG_PRINT_L2("Second output was not strictly needed, and relatedness " << relatedness << ", not adding"); + oxen::log::debug(logcat, "Second output was not strictly needed, and relatedness {}, not adding", relatedness); break; } pop_if_present(*unused_transfers_indices, idx); @@ -11147,7 +11135,7 @@ std::vector wallet2::create_transactions_2(std::vectorempty() ? *unused_dust_indices : *unused_transfers_indices, tx.selected_transfers); const transfer_details &td = m_transfers[idx]; - LOG_PRINT_L2("Picking output " << idx << ", amount " << print_money(td.amount()) << ", ki " << td.m_key_image); + oxen::log::debug(logcat, "Picking output {}, amount {}, ki {}", idx, print_money(td.amount()), td.m_key_image); // add this output to the list to spend tx.selected_transfers.push_back(idx); @@ -11158,7 +11146,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector 0 && !dsts.empty() && estimate_tx_weight(tx.selected_transfers.size(), fake_outs_count, tx.dsts.size()+1, extra.size(), clsag) < tx_weight_target(upper_transaction_weight_limit)) { // we can partially fill that destination - LOG_PRINT_L2("We can partially pay " << get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr) << - " for " << print_money(available_amount) << "/" << print_money(dsts[0].amount)); + oxen::log::debug(logcat, "We can partially pay {} for {}/{}", get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr), print_money(available_amount), print_money(dsts[0].amount)); tx.add(dsts[0], available_amount, original_output_index, m_merge_destinations); dsts[0].amount -= available_amount; available_amount = 0; @@ -11186,8 +11172,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector available_for_fee && !dsts.empty() && dsts[0].amount > 0) { @@ -11243,9 +11226,7 @@ std::vector wallet2::create_transactions_2(std::vectoramount > needed_fee) { uint64_t new_paid_amount = i->amount /*+ test_ptx.fee*/ - needed_fee; - LOG_PRINT_L2("Adjusting amount paid to " << get_account_address_as_str(m_nettype, i->is_subaddress, i->addr) << " from " << - print_money(i->amount) << " to " << print_money(new_paid_amount) << " to accommodate " << - print_money(needed_fee) << " fee"); + oxen::log::debug(logcat, "Adjusting amount paid to {} from {} to {} to accomodate {} fee", get_account_address_as_str(m_nettype, i->is_subaddress, i->addr), print_money(i->amount), print_money(new_paid_amount), print_money(needed_fee)); dsts[0].amount += i->amount - new_paid_amount; i->amount = new_paid_amount; test_ptx.fee = needed_fee; @@ -11255,24 +11236,22 @@ std::vector wallet2::create_transactions_2(std::vector available_for_fee) { - LOG_PRINT_L2("We could not make a tx, switching to fee accumulation"); + oxen::log::debug(logcat, "We could not make a tx, switching to fee accumulation"); adding_fee = true; } else { - LOG_PRINT_L2("We made a tx, adjusting fee and saving it, we need " << print_money(needed_fee) << " and we have " << print_money(test_ptx.fee)); + oxen::log::debug(logcat, "We made a tx, adjusting fee and saving it, we need {} and we have {}", print_money(needed_fee), print_money(test_ptx.fee)); while (needed_fee > test_ptx.fee) { transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx, rct_config, tx_params); txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(test_ptx.tx, txBlob.size(), base_fee, fee_percent, fixed_fee, fee_quantization_mask); - LOG_PRINT_L2("Made an attempt at a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << - " fee and " << print_money(test_ptx.change_dts.amount) << " change"); + oxen::log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); } - LOG_PRINT_L2("Made a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << - " fee and " << print_money(test_ptx.change_dts.amount) << " change"); + oxen::log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); tx.tx = test_tx; tx.ptx = test_ptx; @@ -11284,7 +11263,7 @@ std::vector wallet2::create_transactions_2(std::vector &ptx_vector, std::vector dsts) const { - MDEBUG("sanity_check: " << ptx_vector.size() << " txes, " << dsts.size() << " destinations"); + oxen::log::debug(logcat, "sanity_check: {} txes, {} destinations", ptx_vector.size(), dsts.size()); hw::device &hwdev = m_account.get_device(); @@ -11392,7 +11367,7 @@ bool wallet2::sanity_check(const std::vector &ptx_vector, s } for (const auto &r: required) change -= r.second.first; - MDEBUG("Adding " << cryptonote::print_money(change) << " expected change"); + oxen::log::debug(logcat, "Adding {} expected change", cryptonote::print_money(change)); // for all txes that have actual change, check change is coming back to the sending wallet for (const pending_tx &ptx: ptx_vector) @@ -11426,7 +11401,7 @@ bool wallet2::sanity_check(const std::vector &ptx_vector, s std::stringstream ss; ss << "Total received by " << cryptonote::get_account_address_as_str(m_nettype, r.second.second, address) << ": " << cryptonote::print_money(total_received) << ", expected " << cryptonote::print_money(r.second.first); - MDEBUG(ss.str()); + oxen::log::debug(logcat, ss.str()); THROW_WALLET_EXCEPTION_IF(total_received < r.second.first, error::wallet_internal_error, ss.str()); } @@ -11474,7 +11449,7 @@ std::vector wallet2::create_transactions_all(uint64_t below std::advance(i, crypto::rand_idx(unused_transfer_dust_indices_per_subaddr.size())); unused_transfers_indices = i->second.first; unused_dust_indices = i->second.second; - LOG_PRINT_L2("Spending from subaddress index " << i->first); + oxen::log::debug(logcat, "Spending from subaddress index {}", i->first); } else { @@ -11482,7 +11457,7 @@ std::vector wallet2::create_transactions_all(uint64_t below { unused_transfers_indices.insert(unused_transfers_indices.end(), p.second.first.begin(), p.second.first.end()); unused_dust_indices.insert(unused_dust_indices.end(), p.second.second.begin(), p.second.second.end()); - LOG_PRINT_L2("Spending from subaddress index " << p.first); + oxen::log::debug(logcat, "Spending from subaddress index {}", p.first); } } @@ -11562,7 +11537,7 @@ std::vector wallet2::create_transactions_from(const crypton THROW_WALLET_EXCEPTION_IF(burn_percent > fee_percent, error::wallet_internal_error, "invalid burn fees: cannot burn more than the tx fee"); } - LOG_PRINT_L2("Starting with " << unused_transfers_indices.size() << " non-dust outputs and " << unused_dust_indices.size() << " dust outputs"); + oxen::log::debug(logcat, "Starting with {} non-dust outputs and {} dust outputs", unused_transfers_indices.size(), unused_dust_indices.size()); if (unused_dust_indices.empty() && unused_transfers_indices.empty()) return std::vector(); @@ -11598,7 +11573,7 @@ std::vector wallet2::create_transactions_from(const crypton : pop_best_value(unused_transfers_indices, tx.selected_transfers); const transfer_details &td = m_transfers[idx]; - LOG_PRINT_L2("Picking output " << idx << ", amount " << print_money(td.amount())); + oxen::log::debug(logcat, "Picking output {}, amount {}", idx, print_money(td.amount())); // add this output to the list to spend tx.selected_transfers.push_back(idx); @@ -11609,8 +11584,7 @@ std::vector wallet2::create_transactions_from(const crypton outs.clear(); // here, check if we need to sent tx and start a new one - LOG_PRINT_L2("Considering whether to create a tx now, " << tx.selected_transfers.size() << " inputs, tx limit " - << upper_transaction_weight_limit); + oxen::log::debug(logcat, "Considering whether to create a tx now, {} inputs, tx limit {}", tx.selected_transfers.size(), upper_transaction_weight_limit); const size_t estimated_rct_tx_weight = estimate_tx_weight(tx.selected_transfers.size(), fake_outs_count, tx.dsts.size() + 2, extra.size(), clsag); bool try_tx = (unused_dust_indices.empty() && unused_transfers_indices.empty()) || ( estimated_rct_tx_weight >= tx_weight_target(upper_transaction_weight_limit)); @@ -11625,8 +11599,7 @@ std::vector wallet2::create_transactions_from(const crypton for (size_t i = 0; i < ((outputs > 1) ? outputs - 1 : outputs); ++i) tx.dsts.push_back(tx_destination_entry(1, address, is_subaddress)); - LOG_PRINT_L2("Trying to create a tx now, with " << tx.dsts.size() << " destinations and " << - tx.selected_transfers.size() << " outputs"); + oxen::log::debug(logcat, "Trying to create a tx now, with {} destinations and {} outputs", tx.dsts.size(), tx.selected_transfers.size()); transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx, rct_config, oxen_tx_params); auto txBlob = t_serializable_object_to_blob(test_ptx.tx); @@ -11634,8 +11607,7 @@ std::vector wallet2::create_transactions_from(const crypton available_for_fee = test_ptx.fee + test_ptx.change_dts.amount; for (auto &dt: test_ptx.dests) available_for_fee += dt.amount; - LOG_PRINT_L2("Made a " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(available_for_fee) << " available for fee (" << - print_money(needed_fee) << " needed)"); + oxen::log::debug(logcat, "Made a {} tx, with {} available for fee ({} needed)", get_weight_string(test_ptx.tx, txBlob.size()), print_money(available_for_fee), print_money(needed_fee)); // add last output, missed for fee estimation if (outputs > 1) @@ -11644,7 +11616,7 @@ std::vector wallet2::create_transactions_from(const crypton THROW_WALLET_EXCEPTION_IF(needed_fee > available_for_fee, error::wallet_internal_error, "Transaction cannot pay for itself"); do { - LOG_PRINT_L2("We made a tx, adjusting fee and saving it"); + oxen::log::debug(logcat, "We made a tx, adjusting fee and saving it"); // distribute total transferred amount between outputs uint64_t amount_transferred = available_for_fee - needed_fee; uint64_t dt_amount = amount_transferred / outputs; @@ -11664,12 +11636,10 @@ std::vector wallet2::create_transactions_from(const crypton test_tx, test_ptx, rct_config, oxen_tx_params); txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(test_ptx.tx, txBlob.size(), base_fee, fee_percent, fixed_fee, fee_quantization_mask); - LOG_PRINT_L2("Made an attempt at a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << - " fee and " << print_money(test_ptx.change_dts.amount) << " change"); + oxen::log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); } while (needed_fee > test_ptx.fee); - LOG_PRINT_L2("Made a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << - " fee and " << print_money(test_ptx.change_dts.amount) << " change"); + oxen::log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); tx.tx = test_tx; tx.ptx = test_ptx; @@ -11680,14 +11650,13 @@ std::vector wallet2::create_transactions_from(const crypton accumulated_change += test_ptx.change_dts.amount; if (!unused_transfers_indices.empty() || !unused_dust_indices.empty()) { - LOG_PRINT_L2("We have more to pay, starting another tx"); + oxen::log::debug(logcat, "We have more to pay, starting another tx"); txes.push_back(TX()); } } } - LOG_PRINT_L1("Done creating " << txes.size() << " transactions, " << print_money(accumulated_fee) << - " total fee, " << print_money(accumulated_change) << " total change"); + oxen::log::info(logcat, "Done creating {} transactions, {} total fee, {} total change", txes.size(), print_money(accumulated_fee), print_money(accumulated_change)); hwdev.set_mode(hw::device::mode::TRANSACTION_CREATE_REAL); for (auto &tx : txes) @@ -11714,10 +11683,7 @@ std::vector wallet2::create_transactions_from(const crypton uint64_t tx_money = 0; for (size_t idx: tx.selected_transfers) tx_money += m_transfers[idx].amount(); - LOG_PRINT_L1(" Transaction " << (1+std::distance(txes.begin(), i)) << "/" << txes.size() << - " " << get_transaction_hash(tx.ptx.tx) << ": " << get_weight_string(tx.weight) << ", sending " << print_money(tx_money) << " in " << tx.selected_transfers.size() << - " outputs to " << tx.dsts.size() << " destination(s), including " << - print_money(tx.ptx.fee) << " fee, " << print_money(tx.ptx.change_dts.amount) << " change"); + oxen::log::info(logcat, " Transaction {}/{} {}: {}, sending {} in {} outputs to {} destinations(s), including {} fee, {} change", (1+std::distance(txes.begin(), i)), txes.size(), get_transaction_hash(tx.ptx.tx), get_weight_string(tx.weight), print_money(tx_money), tx.selected_transfers.size(), tx.dsts.size(), print_money(tx.ptx.fee), print_money(tx.ptx.change_dts.amount)); ptx_vector.push_back(tx.ptx); } @@ -11775,8 +11741,8 @@ void wallet2::cold_sign_tx(const std::vector& ptx_vector, signed_tx_ dev_cold->tx_sign(&wallet_shim, txs, exported_txs, aux_data); tx_device_aux = aux_data.tx_device_aux; - MDEBUG("Signed tx data from hw: " << exported_txs.ptx.size() << " transactions"); - for (auto &c_ptx: exported_txs.ptx) LOG_PRINT_L0(cryptonote::obj_to_json_str(c_ptx.tx)); + oxen::log::debug(logcat, "Signed tx data from hw: {} transactions", exported_txs.ptx.size()); + for (auto &c_ptx: exported_txs.ptx) oxen::log::warning(logcat, cryptonote::obj_to_json_str(c_ptx.tx)); } //---------------------------------------------------------------------------------------------------- uint64_t wallet2::cold_key_image_sync(uint64_t &spent, uint64_t &unspent) { @@ -11834,9 +11800,9 @@ bool wallet2::use_fork_rules(hf version, uint64_t early_blocks) const close_enough = true; if (close_enough) - LOG_PRINT_L2("Using v" << (unsigned)version << " rules"); + oxen::log::debug(logcat, "Using v{} rules", (unsigned)version); else - LOG_PRINT_L2("Not using v" << (unsigned)version << " rules"); + oxen::log::debug(logcat, "Not using v{} rules", (unsigned)version); return close_enough; } //---------------------------------------------------------------------------------------------------- @@ -12013,7 +11979,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s bool r = get_tx_key_cached(txid, tx_key, additional_tx_keys); if (r) { - MDEBUG("tx key cached for txid: " << txid); + oxen::log::debug(logcat, "tx key cached for txid: {}", txid); return true; } @@ -12028,7 +11994,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s const auto tx_data_it = m_tx_device.find(txid); if (tx_data_it == m_tx_device.end()) { - MDEBUG("Aux data not found for txid: " << txid); + oxen::log::debug(logcat, "Aux data not found for txid: {}", txid); return false; } @@ -12036,7 +12002,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); if (!dev_cold->is_get_tx_key_supported()) { - MDEBUG("get_tx_key not supported by the device"); + oxen::log::debug(logcat, "get_tx_key not supported by the device"); return false; } @@ -12071,7 +12037,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s dev_cold->get_tx_key(tx_keys, tx_key_data, m_account.get_keys().m_view_secret_key); if (tx_keys.empty()) { - MDEBUG("Empty tx keys for txid: " << txid); + oxen::log::debug(logcat, "Empty tx keys for txid: {}", txid); return false; } @@ -13000,7 +12966,7 @@ uint64_t wallet2::get_approximate_blockchain_height() const uint64_t approx_blockchain_height = netconf.HEIGHT_ESTIMATE_HEIGHT + (since_ts > 0 ? (uint64_t)since_ts / tools::to_seconds(TARGET_BLOCK_TIME) : 0) - BLOCKS_PER_DAY * 7; // subtract a week's worth of blocks to be conservative - LOG_PRINT_L2("Calculated blockchain height: " << approx_blockchain_height); + oxen::log::debug(logcat, "Calculated blockchain height: {}", approx_blockchain_height); return approx_blockchain_height; } @@ -13135,7 +13101,7 @@ void wallet2::set_account_tag(const std::set &account_indices, const s { THROW_WALLET_EXCEPTION_IF(account_index >= get_num_subaddress_accounts(), error::wallet_internal_error, "Account index out of bound"); if (m_account_tags.second[account_index] == tag) - MDEBUG("This tag is already assigned to this account"); + oxen::log::debug(logcat, "This tag is already assigned to this account"); else m_account_tags.second[account_index] = tag; } @@ -13178,19 +13144,19 @@ std::string wallet2::sign(std::string_view data, cryptonote::subaddress_index in bool wallet2::verify(std::string_view data, const cryptonote::account_public_address &address, std::string_view signature) { if (!tools::starts_with(signature, SIG_MAGIC)) { - LOG_PRINT_L0("Signature header check error"); + oxen::log::warning(logcat, "Signature header check error"); return false; } crypto::hash hash; crypto::cn_fast_hash(data.data(), data.size(), hash); std::string decoded; if (!tools::base58::decode(signature.substr(SIG_MAGIC.size()), decoded)) { - LOG_PRINT_L0("Signature decoding error"); + oxen::log::warning(logcat, "Signature decoding error"); return false; } crypto::signature s; if (sizeof(s) != decoded.size()) { - LOG_PRINT_L0("Signature decoding error"); + oxen::log::warning(logcat, "Signature decoding error"); return false; } memcpy(&s, decoded.data(), sizeof(s)); @@ -13214,19 +13180,19 @@ std::string wallet2::sign_multisig_participant(std::string_view data) const bool wallet2::verify_with_public_key(std::string_view data, const crypto::public_key &public_key, std::string_view signature) const { if (!tools::starts_with(signature, MULTISIG_SIGNATURE_MAGIC)) { - MERROR("Signature header check error"); + oxen::log::error(logcat, "Signature header check error"); return false; } crypto::hash hash; crypto::cn_fast_hash(data.data(), data.size(), hash); std::string decoded; if (!tools::base58::decode(signature.substr(MULTISIG_SIGNATURE_MAGIC.size()), decoded)) { - MERROR("Signature decoding error"); + oxen::log::error(logcat, "Signature decoding error"); return false; } crypto::signature s; if (sizeof(s) != decoded.size()) { - MERROR("Signature decoding error"); + oxen::log::error(logcat, "Signature decoding error"); return false; } memcpy(&s, decoded.data(), sizeof(s)); @@ -13309,7 +13275,6 @@ bool wallet2::export_key_images_to_file(const fs::path& filename, bool requested // [ ((transfer array offset*) (spend public key) (view public key) {(key image) (signature), ...}) ] // *The offset in the wallet's transfers this exported key image file contains. - PERF_TIMER(__FUNCTION__); std::pair>> ski = export_key_images(requested_only); const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; std::string data; @@ -13325,7 +13290,6 @@ bool wallet2::export_key_images_to_file(const fs::path& filename, bool requested } // encrypt data, keep magic plaintext - PERF_TIMER(export_key_images_encrypt); std::string ciphertext{KEY_IMAGE_EXPORT_FILE_MAGIC}; ciphertext += encrypt_with_view_secret_key(data); return tools::dump_file(filename, ciphertext); @@ -13334,7 +13298,6 @@ bool wallet2::export_key_images_to_file(const fs::path& filename, bool requested //---------------------------------------------------------------------------------------------------- std::pair>> wallet2::export_key_images(bool requested_only) const { - PERF_TIMER(export_key_images_raw); std::vector> ski; size_t offset = 0; @@ -13389,7 +13352,6 @@ std::pair>> uint64_t wallet2::import_key_images_from_file(const fs::path& filename, uint64_t& spent, uint64_t& unspent) { - PERF_TIMER(__FUNCTION__); std::string data; bool r = tools::slurp_file(filename, data); @@ -13402,7 +13364,6 @@ uint64_t wallet2::import_key_images_from_file(const fs::path& filename, uint64_t try { - PERF_TIMER(import_key_images_decrypt); data = decrypt_with_view_secret_key(std::string_view{data}.substr(KEY_IMAGE_EXPORT_FILE_MAGIC.size())).view(); } catch (const std::exception &e) @@ -13450,8 +13411,6 @@ uint64_t wallet2::import_key_images_from_file(const fs::path& filename, uint64_t //---------------------------------------------------------------------------------------------------- uint64_t wallet2::import_key_images(const std::vector> &signed_key_images, size_t offset, uint64_t &spent, uint64_t &unspent, bool check_spent) { - PERF_TIMER(import_key_images_lots); - THROW_WALLET_EXCEPTION_IF(offset > m_transfers.size(), error::wallet_internal_error, "Offset larger than known outputs"); THROW_WALLET_EXCEPTION_IF(signed_key_images.size() > m_transfers.size() - offset, error::wallet_internal_error, "The blockchain is out of date compared to the signed key images"); @@ -13466,7 +13425,6 @@ uint64_t wallet2::import_key_images(const std::vector key_images{}; key_images.reserve(signed_key_images.size()); - PERF_TIMER_START(import_key_images_A_validate_and_extract_key_images); for (size_t n = 0; n < signed_key_images.size(); ++n) { const transfer_details &td = m_transfers[n + offset]; @@ -13502,9 +13460,7 @@ uint64_t wallet2::import_key_images(const std::vector spent_key_images; - PERF_TIMER_START(import_key_images_C); for (const transfer_details &td: m_transfers) { for (const cryptonote::txin_v& in : td.m_tx.vin) @@ -13549,7 +13502,6 @@ uint64_t wallet2::import_key_images(const std::vectork_image, td.m_txid); } } - PERF_TIMER_STOP(import_key_images_C); // accumulate outputs before the updated data for(size_t i = 0; i < offset; ++i) @@ -13564,7 +13516,6 @@ uint64_t wallet2::import_key_images(const std::vectorsecond); } } - PERF_TIMER_STOP(import_key_images_D); - MDEBUG("Total: " << print_money(spent) << " spent, " << print_money(unspent) << " unspent"); + oxen::log::debug(logcat, "Total: {} spent, {} unspent", print_money(spent), print_money(unspent)); if (check_spent) { // query outgoing txes - PERF_TIMER_START(import_key_images_E); nlohmann::json get_transactions_params{ {"tx_hashes", hashes_to_hex(spent_txids.begin(), spent_txids.end())} }; auto gettxs_res = m_http_client.json_rpc("get_transactions", get_transactions_params); - PERF_TIMER_STOP(import_key_images_E); // process each outgoing tx - PERF_TIMER_START(import_key_images_F); auto spent_txid = spent_txids.begin(); hw::device &hwdev = m_account.get_device(); auto it = spent_txids.begin(); @@ -13674,12 +13620,12 @@ uint64_t wallet2::import_key_images(const std::vectorsecond, e["block_height"]); if (m_callback) m_callback->on_money_spent(e["block_height"], *spent_txid, spent_tx, amount, spent_tx, td.m_subaddr_index); if (subaddr_account != (uint32_t)-1 && subaddr_account != td.m_subaddr_index.major) - LOG_PRINT_L0("WARNING: This tx spends outputs received by different subaddress accounts, which isn't supposed to happen"); + oxen::log::warning(logcat, "WARNING: This tx spends outputs received by different subaddress accounts, which isn't supposed to happen"); subaddr_account = td.m_subaddr_index.major; subaddr_indices.insert(td.m_subaddr_index.minor); } @@ -13699,9 +13645,7 @@ uint64_t wallet2::import_key_images(const std::vector key_images, size_ { if (key_images.size() + offset > m_transfers.size()) { - LOG_PRINT_L1("More key images returned that we know outputs for"); + oxen::log::info(logcat, "More key images returned that we know outputs for"); return false; } for (size_t ki_idx = 0; ki_idx < key_images.size(); ++ki_idx) @@ -13736,7 +13679,7 @@ bool wallet2::import_key_images(std::vector key_images, size_ transfer_details &td = m_transfers[transfer_idx]; if (td.m_key_image_known && !td.m_key_image_partial && td.m_key_image != key_images[ki_idx]) - LOG_PRINT_L0("WARNING: imported key image differs from previously known key image at index " << ki_idx << ": trusting imported one"); + oxen::log::warning(logcat, "WARNING: imported key image differs from previously known key image at index {}: trusting imported one", ki_idx); td.m_key_image = key_images[ki_idx]; m_key_images[td.m_key_image] = transfer_idx; td.m_key_image_known = true; @@ -13819,7 +13762,6 @@ void wallet2::import_blockchain(const std::tuple> wallet2::export_outputs(bool all) const { - PERF_TIMER(export_outputs); std::vector outs; size_t offset = 0; @@ -13840,7 +13782,6 @@ std::pair> wallet2::export //---------------------------------------------------------------------------------------------------- std::string wallet2::export_outputs_to_str(bool all) const { - PERF_TIMER(export_outputs_to_str); std::stringstream oss; boost::archive::portable_binary_oarchive ar(oss); @@ -13852,7 +13793,6 @@ std::string wallet2::export_outputs_to_str(bool all) const header += tools::view_guts(keys.m_spend_public_key); header += tools::view_guts(keys.m_view_public_key); header += oss.str(); - PERF_TIMER(export_outputs_encryption); std::string ciphertext{OUTPUT_EXPORT_FILE_MAGIC}; ciphertext += encrypt_with_view_secret_key(header); return ciphertext; @@ -13860,7 +13800,6 @@ std::string wallet2::export_outputs_to_str(bool all) const //---------------------------------------------------------------------------------------------------- size_t wallet2::import_outputs(const std::pair> &outputs) { - PERF_TIMER(import_outputs); THROW_WALLET_EXCEPTION_IF(outputs.first > m_transfers.size(), error::wallet_internal_error, "Imported outputs omit more outputs that we know of"); @@ -13929,7 +13868,6 @@ size_t wallet2::import_outputs(const std::pair= m_transfers.size(), "Mismatched sizes of multisig_k and info"); - MDEBUG("update_multisig_rescan_info: updating index " << n); + oxen::log::debug(logcat, "update_multisig_rescan_info: updating index {}", n); transfer_details &td = m_transfers[n]; td.m_multisig_info.clear(); for (const auto &pi: info) @@ -14197,12 +14134,12 @@ size_t wallet2::import_multisig(std::vector blobs) error::wallet_internal_error, "Multisig info is for a different account"); if (get_multisig_signer_public_key() == signer) { - MINFO("Multisig info from this wallet ignored"); + oxen::log::info(logcat, "Multisig info from this wallet ignored"); continue; } if (seen.find(signer) != seen.end()) { - MINFO("Duplicate multisig info ignored"); + oxen::log::info(logcat, "Duplicate multisig info ignored"); continue; } seen.insert(signer); @@ -14214,7 +14151,7 @@ size_t wallet2::import_multisig(std::vector blobs) std::vector i; boost::archive::portable_binary_iarchive ar(iss); ar >> i; - MINFO(i.size() << " outputs found"); + oxen::log::info(logcat, "{} outputs found", i.size()); info.push_back(std::move(i)); } @@ -14263,7 +14200,7 @@ size_t wallet2::import_multisig(std::vector blobs) const transfer_details &td = m_transfers[n]; if (!td.m_key_image_partial) continue; - MINFO("Multisig info importing from block height " << td.m_block_height); + oxen::log::info(logcat, "Multisig info importing from block height {}", td.m_block_height); detach_blockchain(td.m_block_height); break; } diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index e45ae1f6d..8430078cc 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -54,6 +54,7 @@ #include "common/file.h" #include "crypto/chacha.h" #include "crypto/hash.h" +#include "crypto/fmt.h" #include "ringct/rctTypes.h" #include "ringct/rctOps.h" #include "checkpoints/checkpoints.h" @@ -92,9 +93,6 @@ #include "rpc/http_client.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.wallet2" - #define SUBADDRESS_LOOKAHEAD_MAJOR 50 #define SUBADDRESS_LOOKAHEAD_MINOR 200 @@ -1332,12 +1330,12 @@ private: if (throw_on_error) throw; else - MERROR("HTTP request failed: " << e.what()); + oxen::log::error(oxen::log::Cat("wallet.wallet2"), "HTTP request failed: {}", e.what()); } catch (...) { if (throw_on_error) throw; else - MERROR("HTTP request failed: unknown error"); + oxen::log::error(oxen::log::Cat("wallet.wallet2"), "HTTP request failed: unknown error"); } return false; } @@ -1945,7 +1943,7 @@ namespace boost::serialization is_long |= payment_id.data[i]; if (is_long) { - MWARNING("Long payment ID ignored on address book load"); + oxen::log::warning(oxen::log::Cat("wallet.wallet2"), "Long payment ID ignored on address book load"); x.m_payment_id = crypto::null_hash8; x.m_has_payment_id = false; } diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index d999aa35f..82bd25c47 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -29,20 +29,20 @@ #include "wallet/wallet_args.h" #include +#include #include "common/i18n.h" #include "common/util.h" #include "common/file.h" #include "epee/misc_log_ex.h" #include "epee/string_tools.h" #include "version.h" +#include "logging/oxen_logger.h" +#include #if defined(WIN32) #include #endif -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.wallet2" - // workaround for a suspected bug in pthread/kernel on MacOS X #ifdef __APPLE__ #define DEFAULT_MAX_CONCURRENCY 1 @@ -52,16 +52,17 @@ namespace { + static auto logcat = oxen::log::Cat("wallet.wallet2"); + class Print { public: - Print(const std::function &p, bool em = false): print(p), emphasis(em) {} - ~Print() { print(ss.str(), emphasis); } + Print(const std::function &p): print(p) {} + ~Print() { print(ss.str()); } template std::ostream &operator<<(const T &t) { ss << t; return ss; } private: - const std::function &print; + const std::function &print; std::stringstream ss; - bool emphasis; }; } @@ -89,7 +90,7 @@ namespace wallet_args boost::program_options::options_description desc_params, boost::program_options::options_description hidden_params, const boost::program_options::positional_options_description& positional_options, - const std::function &print, + const std::function &print, const char *default_log_name, bool log_to_console) @@ -100,8 +101,8 @@ namespace wallet_args #endif const command_line::arg_descriptor arg_log_level = {"log-level", "0-4 or categories", ""}; - const command_line::arg_descriptor arg_max_log_file_size = {"max-log-file-size", "Specify maximum log file size [B]", MAX_LOG_FILE_SIZE}; - const command_line::arg_descriptor arg_max_log_files = {"max-log-files", "Specify maximum number of rotated log files to be saved (no limit by setting to 0)", MAX_LOG_FILES}; + const command_line::arg_descriptor arg_max_log_file_size = {"max-log-file-size", "Specify maximum log file size [B]", 50}; + const command_line::arg_descriptor arg_max_log_files = {"max-log-files", "Specify maximum number of rotated log files to be saved (no limit by setting to 0)", 50}; const command_line::arg_descriptor arg_max_concurrency = {"max-concurrency", wallet_args::tr("Max number of threads to use for a parallel job"), DEFAULT_MAX_CONCURRENCY}; const command_line::arg_descriptor arg_log_file = {"log-file", wallet_args::tr("Specify log file"), ""}; const command_line::arg_descriptor arg_config_file = {"config-file", wallet_args::tr("Config file"), "", true}; @@ -167,7 +168,7 @@ namespace wallet_args } else { - MERROR(wallet_args::tr("Can't find config file ") << config); + oxen::log::error(logcat, "{}{}", wallet_args::tr("Can't find config file "), config); return false; } } @@ -185,17 +186,17 @@ namespace wallet_args if (!command_line::is_arg_defaulted(vm, arg_log_file)) log_path = command_line::get_arg(vm, arg_log_file); else - log_path = mlog_get_default_log_path(default_log_name); - mlog_configure(log_path, log_to_console, command_line::get_arg(vm, arg_max_log_file_size), command_line::get_arg(vm, arg_max_log_files)); - if (!command_line::is_arg_defaulted(vm, arg_log_level)) - { - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - } - else if (!log_to_console) - { - mlog_set_categories(""); + log_path = epee::string_tools::get_current_module_name() + ".log"; + oxen::log::Level log_level; + if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { + log_level = *level; + } else { + std::cerr << "Incorrect log level: " << command_line::get_arg(vm, arg_log_level).c_str() << std::endl; + throw std::runtime_error{"Incorrect log level"}; } + oxen::logging::init(log_path, log_level); + if (notice) Print(print) << notice << "\n"; @@ -205,15 +206,15 @@ namespace wallet_args Print(print) << "Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")"; if (!command_line::is_arg_defaulted(vm, arg_log_level)) - MINFO("Setting log level = " << command_line::get_arg(vm, arg_log_level)); + oxen::log::info(logcat, "Setting log level = {}", command_line::get_arg(vm, arg_log_level)); else { const char *logs = getenv("OXEN_LOGS"); - MINFO("Setting log levels = " << (logs ? logs : "")); + oxen::log::info(logcat, "Setting log levels = {}", (logs ? logs : "")); } - MINFO(wallet_args::tr("Logging to: ") << log_path); + //oxen::log::info(logcat, "{}{}", wallet_args::tr("Logging to: "), log_path); - Print(print) << boost::format(wallet_args::tr("Logging to %s")) % log_path; + //Print(print) << boost::format(wallet_args::tr("Logging to %s")) % log_path; const ssize_t lockable_memory = tools::get_lockable_memory(); if (lockable_memory >= 0 && lockable_memory < 256 * 4096) // 256 pages -> at least 256 secret keys and other such small/medium objects diff --git a/src/wallet/wallet_args.h b/src/wallet/wallet_args.h index 09ad90512..4af3d9a77 100644 --- a/src/wallet/wallet_args.h +++ b/src/wallet/wallet_args.h @@ -55,6 +55,6 @@ namespace wallet_args boost::program_options::options_description desc_params, boost::program_options::options_description hidden_params, const boost::program_options::positional_options_description& positional_options, - const std::function &print, + const std::function &print, const char *default_log_name, bool log_to_console = false); } diff --git a/src/wallet/wallet_errors.h b/src/wallet/wallet_errors.h index 855fe67fe..6a0855413 100644 --- a/src/wallet/wallet_errors.h +++ b/src/wallet/wallet_errors.h @@ -38,6 +38,7 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "cryptonote_core/cryptonote_tx_utils.h" #include "rpc/core_rpc_server_commands_defs.h" +#include "logging/oxen_logger.h" namespace tools @@ -883,7 +884,7 @@ namespace tools void throw_wallet_ex(std::string&& loc, TArgs&&... args) { TException e(std::move(loc), std::forward(args)...); - LOG_PRINT_L0(e.to_string()); + oxen::log::warning(globallogcat, e.to_string()); throw e; } } @@ -894,13 +895,13 @@ namespace tools #define THROW_WALLET_EXCEPTION(err_type, ...) \ do { \ - LOG_ERROR("THROW EXCEPTION: " << #err_type); \ + oxen::log::error(logcat, "THROW EXCEPTION: {}", #err_type); \ tools::error::throw_wallet_ex(std::string(__FILE__ ":" STRINGIZE(__LINE__)), ## __VA_ARGS__); \ } while(0) #define THROW_WALLET_EXCEPTION_IF(cond, err_type, ...) \ do { if (cond) \ { \ - LOG_ERROR(#cond << ". THROW EXCEPTION: " << #err_type); \ + oxen::log::error(logcat, "{}. THROW EXCEPTION: {}", #cond, #err_type); \ tools::error::throw_wallet_ex(std::string(__FILE__ ":" STRINGIZE(__LINE__)), ## __VA_ARGS__); \ } } while (0) diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 6ead0a177..3d667b8fd 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -36,6 +36,7 @@ #include #include #include +#include #include "wallet_rpc_server_error_codes.h" #include "wallet_rpc_server.h" @@ -57,14 +58,13 @@ #include "cryptonote_core/oxen_name_system.h" #include "serialization/boost_std_variant.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.rpc" - namespace rpc = cryptonote::rpc; using namespace tools::wallet_rpc; namespace { + static auto logcat = oxen::log::Cat("wallet.rpc"); + constexpr auto DEFAULT_AUTO_REFRESH_PERIOD = 20s; const command_line::arg_descriptor arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"}; @@ -80,7 +80,7 @@ namespace auto pwd_container = tools::password_container::prompt(verify, prompt); if (!pwd_container) { - MERROR("failed to read wallet password"); + oxen::log::error(logcat, "failed to read wallet password"); } return pwd_container; } @@ -196,7 +196,7 @@ namespace tools http.any("/*", [this](HttpResponse* res, HttpRequest* req) { if (m_login && !check_auth(*req, *res)) return; - MINFO("Invalid HTTP request for " << req->getMethod() << " " << req->getUrl()); + oxen::log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_NOT_FOUND); }); } @@ -231,23 +231,23 @@ namespace tools std::string method; if(!ps.get_value("method", method, nullptr)) { - MINFO("Invalid JSON RPC request from " << get_remote_address(res) << ": no 'method' in request"); + oxen::log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", get_remote_address(res)); return jsonrpc_error_response(res, -32600, "Invalid Request", id); } auto it = rpc_commands.find(method); if (it == rpc_commands.end()) { - MINFO("Invalid JSON RPC request from " << get_remote_address(res) << ": method '" << method << "' is invalid"); + oxen::log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", get_remote_address(res), method); return jsonrpc_error_response(res, -32601, "Method not found", id); } - MDEBUG("Incoming JSON RPC request for " << method << " from " << get_remote_address(res)); + oxen::log::debug(logcat, "Incoming JSON RPC request for {} from {}", method, get_remote_address(res)); const auto& [restricted, invoke_ptr] = it->second; // If it's a restricted command and we're in restricted mode then deny it if (restricted && m_restricted) { - MWARNING("JSON RPC request for restricted command " << method << " in restricted mode from " << get_remote_address(res)); + oxen::log::warning(logcat, "JSON RPC request for restricted command {} in restricted mode from {}", method, get_remote_address(res)); return jsonrpc_error_response(res, error_code::DENIED, method + " is not available in restricted mode.", {}); } @@ -400,7 +400,7 @@ namespace tools try { if (m_wallet) m_wallet->refresh(m_wallet->is_trusted_daemon()); } catch (const std::exception& ex) { - LOG_ERROR("Exception while refreshing: " << ex.what()); + oxen::log::error(logcat, "Exception while refreshing: {}", ex.what()); } m_last_auto_refresh_time = std::chrono::steady_clock::now(); @@ -411,8 +411,8 @@ namespace tools std::this_thread::sleep_for(250ms); } - MGINFO("Stopping wallet rpc server"); - MINFO("Shutting down listening HTTP RPC sockets"); + oxen::log::info(logcat, "Stopping wallet rpc server"); + oxen::log::info(logcat, "Shutting down listening HTTP RPC sockets"); // Stopped: close the sockets, cancel the long poll, and rejoin the threads for (auto* s : m_listen_socks) us_listen_socket_close(/*ssl=*/false, s); @@ -420,23 +420,23 @@ namespace tools stop_long_poll_thread(); - MDEBUG("Joining uws thread"); + oxen::log::debug(logcat, "Joining uws thread"); uws_thread.join(); - MGINFO("Storing wallet..."); + oxen::log::info(logcat, "Storing wallet..."); if (m_wallet) m_wallet->store(); - MGINFO("Wallet stopped."); + oxen::log::info(logcat, "Wallet stopped."); } void wallet_rpc_server::start_long_poll_thread() { assert(m_wallet); if (m_long_poll_thread.joinable() || m_long_poll_disabled) { - MDEBUG("Not starting long poll thread: " << (m_long_poll_thread.joinable() ? "already running" : "long polling disabled")); + oxen::log::debug(logcat, "Not starting long poll thread: {}", (m_long_poll_thread.joinable() ? "already running" : "long polling disabled")); return; } - MINFO("Starting long poll thread"); + oxen::log::info(logcat, "Starting long poll thread"); m_long_poll_thread = std::thread{[this] { for (;;) { @@ -464,10 +464,10 @@ namespace tools assert(m_wallet); if (!m_long_poll_thread.joinable()) { - MDEBUG("Not stopping long poll thread: not running"); + oxen::log::debug(logcat, "Not stopping long poll thread: not running"); return; } - MINFO("Stopping long poll thread"); + oxen::log::info(logcat, "Stopping long poll thread"); m_wallet->cancel_long_poll(); // Store this to revert it afterwards to its original state bool disabled_state = m_long_poll_disabled; @@ -482,14 +482,14 @@ namespace tools try { rpc_config = cryptonote::rpc_args::process(m_vm); } catch (const std::exception& e) { - MERROR("Failed to process rpc arguments: " << e.what()); + oxen::log::error(logcat, "Failed to process rpc arguments: {}", e.what()); return false; } const uint16_t port = command_line::get_arg(m_vm, arg_rpc_bind_port); if (!port) { - MERROR("Invalid port " << port << " specified"); + oxen::log::error(logcat, "Invalid port {} specified", port); return false; } @@ -510,7 +510,7 @@ namespace tools { if (!command_line::is_arg_defaulted(m_vm, wallet_args::arg_wallet_file())) { - MERROR(arg_wallet_dir.name << " and " << wallet_args::arg_wallet_file().name << " are incompatible, use only one of them"); + oxen::log::error(logcat, "{} and {} are incompatible, use only one of them", arg_wallet_dir.name, wallet_args::arg_wallet_file().name); return false; } m_wallet_dir = fs::u8path(command_line::get_arg(m_vm, arg_wallet_dir)); @@ -521,7 +521,7 @@ namespace tools fs::permissions(m_wallet_dir, fs::perms::owner_all, ec); else if (ec) { - LOG_ERROR(tr("Failed to create directory ") << m_wallet_dir << ": " << ec.message()); + oxen::log::error(logcat, "{}{}: {}", tr("Failed to create directory "), m_wallet_dir, ec.message()); return false; } } @@ -532,7 +532,7 @@ namespace tools if (rpc_config.login) { const cryptonote::rpc_args::descriptors arg{}; - LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg.rpc_login.name); + oxen::log::error(logcat, "{}{}{}{}", tr("Cannot specify --"), arg_disable_rpc_login.name, tr(" and --"), arg.rpc_login.name); return false; } m_login = std::nullopt; @@ -552,7 +552,7 @@ namespace tools rpc_login_file = tools::private_file::create(temp); if (!rpc_login_file.handle()) { - LOG_ERROR(tr("Failed to create file ") << temp << tr(". Check permissions or remove file")); + oxen::log::error(logcat, "{}{}{}", tr("Failed to create file "), temp, tr(". Check permissions or remove file")); return false; } std::fputs(m_login->username.c_str(), rpc_login_file.handle()); @@ -563,10 +563,10 @@ namespace tools std::fflush(rpc_login_file.handle()); if (std::ferror(rpc_login_file.handle())) { - LOG_ERROR(tr("Error writing to file ") << temp); + oxen::log::error(logcat, "{}{}", tr("Error writing to file "), temp); return false; } - LOG_PRINT_L0(tr("RPC username/password is stored in file ") << temp); + oxen::log::warning(logcat, "{}{}", tr("RPC username/password is stored in file "), temp); } else // chosen user/pass { @@ -590,17 +590,17 @@ namespace tools { if (m_wallet) { - MDEBUG(tools::wallet_rpc_server::tr("Closing wallet...")); + oxen::log::debug(logcat, tools::wallet_rpc_server::tr("Closing wallet...")); stop_long_poll_thread(); if (save_current) { - MDEBUG(tools::wallet_rpc_server::tr("Saving wallet...")); + oxen::log::debug(logcat, tools::wallet_rpc_server::tr("Saving wallet...")); m_wallet->store(); - MINFO(tools::wallet_rpc_server::tr("Wallet saved")); + oxen::log::info(logcat, tools::wallet_rpc_server::tr("Wallet saved")); } m_wallet->deinit(); m_wallet.reset(); - MINFO(tools::wallet_rpc_server::tr("Wallet closed")); + oxen::log::info(logcat, tools::wallet_rpc_server::tr("Wallet closed")); } } //------------------------------------------------------------------------------------------------------------------------------ @@ -1040,7 +1040,7 @@ namespace tools std::vector dsts; std::vector extra; - LOG_PRINT_L3("on_transfer starts"); + oxen::log::trace(logcat, "on_transfer starts"); require_open(); // validate the transfer requested and populate dsts & extra @@ -1087,9 +1087,9 @@ namespace tools throw wallet_rpc_error{error_code::HF_QUERY_FAILED, tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED}; cryptonote::oxen_construct_tx_params tx_params = tools::wallet2::construct_params(*hf_version, cryptonote::txtype::standard, priority); - LOG_PRINT_L2("on_transfer_split calling create_transactions_2"); + oxen::log::debug(logcat, "on_transfer_split calling create_transactions_2"); std::vector ptx_vector = m_wallet->create_transactions_2(dsts, cryptonote::TX_OUTPUT_DECOYS, req.unlock_time, priority, extra, req.account_index, req.subaddr_indices, tx_params); - LOG_PRINT_L2("on_transfer_split called create_transactions_2"); + oxen::log::debug(logcat, "on_transfer_split called create_transactions_2"); if (ptx_vector.empty()) throw wallet_rpc_error{error_code::TX_NOT_POSSIBLE, "No transaction created"}; @@ -2310,7 +2310,7 @@ namespace tools AUTO_REFRESH::response wallet_rpc_server::invoke(AUTO_REFRESH::request&& req) { m_auto_refresh_period = req.enable ? req.period ? std::chrono::seconds{req.period} : DEFAULT_AUTO_REFRESH_PERIOD : 0s; - MINFO("Auto refresh now " << (m_auto_refresh_period != 0s ? std::to_string(std::chrono::duration(m_auto_refresh_period).count()) + " seconds" : std::string("disabled"))); + oxen::log::info(logcat, "Auto refresh now {}", (m_auto_refresh_period != 0s ? std::to_string(std::chrono::duration(m_auto_refresh_period).count()) + " seconds" : std::string("disabled"))); return {}; } //------------------------------------------------------------------------------------------------------------------------------ @@ -2491,7 +2491,7 @@ namespace { if (m_wallet->verify_password(req.old_password)) { m_wallet->change_password(m_wallet->get_wallet_file(), req.old_password, req.new_password); - LOG_PRINT_L0("Wallet password changed."); + oxen::log::warning(logcat, "Wallet password changed."); } else throw wallet_rpc_error{error_code::INVALID_PASSWORD, "Invalid original password."}; @@ -2559,7 +2559,7 @@ namespace { wal->generate(wallet_file, std::move(rc.second).password(), info.address, viewkey, false); res.info = "Watch-only wallet has been generated successfully."; } - MINFO("Wallet has been generated.\n"); + oxen::log::info(logcat, "Wallet has been generated.\n"); } if (!wal) @@ -2641,7 +2641,7 @@ namespace { wal->set_seed_language(mnemonic_language); crypto::secret_key recovery_val = wal->generate(wallet_file, std::move(rc.second).password(), recovery_key, true, false, false); - MINFO("Wallet has been restored.\n"); + oxen::log::info(logcat, "Wallet has been restored.\n"); // // Convert the secret key back to seed epee::wipeable_string electrum_words; @@ -2940,15 +2940,16 @@ namespace { { if (req.level < 0 || req.level > 4) throw wallet_rpc_error{error_code::INVALID_LOG_LEVEL, "Error: log level not valid"}; - mlog_set_log_level(req.level); + auto log_level = oxen::logging::parse_level(req.level); + if (log_level.has_value()) + oxen::log::reset_level(*log_level); return {}; } //------------------------------------------------------------------------------------------------------------------------------ SET_LOG_CATEGORIES::response wallet_rpc_server::invoke(SET_LOG_CATEGORIES::request&& req) { - mlog_set_log(req.categories.c_str()); SET_LOG_CATEGORIES::response res{}; - res.categories = mlog_get_categories(); + oxen::logging::process_categories_string(req.categories.c_str()); return res; } //------------------------------------------------------------------------------------------------------------------------------ @@ -3290,7 +3291,7 @@ namespace { { if (rec["entry_index"].get() >= num_entries) { - MWARNING("Got back invalid entry_index " << rec["entry_index"] << " for a request for " << num_entries << " entries"); + oxen::log::warning(logcat, "Got back invalid entry_index {} for a request for {} entries", rec["entry_index"], num_entries); continue; } @@ -3313,7 +3314,7 @@ namespace { && value.decrypt(res_e.name, type)) res_e.value = value.to_readable_value(nettype, type); else - MWARNING("Failed to decrypt ONS value for " << res_e.name << (errmsg.empty() ? ""s : ": " + errmsg)); + oxen::log::warning(logcat, "Failed to decrypt ONS value for {}{}", res_e.name, (errmsg.empty() ? ""s : ": " + errmsg)); } } } @@ -3467,7 +3468,7 @@ namespace { if (wallet_file.empty() && from_json.empty()) throw std::logic_error{tr("Must specify --wallet-file or --generate-from-json or --wallet-dir")}; - LOG_PRINT_L0(tools::wallet_rpc_server::tr("Loading wallet...")); + oxen::log::warning(logcat, tools::wallet_rpc_server::tr("Loading wallet...")); if(!wallet_file.empty()) wal = tools::wallet2::make_from_file(m_vm, true, wallet_file, password_prompt).first; else @@ -3487,12 +3488,12 @@ namespace { // if we ^C during potentially length load/refresh, there's no server loop yet if (quit) { - MINFO(tools::wallet_rpc_server::tr("Saving wallet...")); + oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Saving wallet...")); wal->store(); - MINFO(tools::wallet_rpc_server::tr("Successfully saved")); + oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully saved")); throw std::runtime_error{tr("Wallet loading cancelled before initial refresh completed")}; } - MINFO(tools::wallet_rpc_server::tr("Successfully loaded")); + oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully loaded")); } return wal; } @@ -3506,7 +3507,7 @@ namespace { } catch (const std::exception& e) { - LOG_ERROR(tr("Wallet initialization failed: ") << e.what()); + oxen::log::error(logcat, "{}{}", tr("Wallet initialization failed: "), e.what()); return false; } @@ -3515,28 +3516,28 @@ namespace { bool r = init(); CHECK_AND_ASSERT_MES(r, false, tools::wallet_rpc_server::tr("Failed to initialize wallet RPC server")); tools::signal_handler::install([this](int) { - MWARNING("Shutting down..."); + oxen::log::warning(logcat, "Shutting down..."); m_stop = true; }); - LOG_PRINT_L0(tools::wallet_rpc_server::tr("Starting wallet RPC server")); + oxen::log::warning(globallogcat, tools::wallet_rpc_server::tr("Starting wallet RPC server")); try { run_loop(); } catch (const std::exception &e) { - LOG_ERROR(tools::wallet_rpc_server::tr("Failed to run wallet: ") << e.what()); + oxen::log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to run wallet: "), e.what()); return false; } - LOG_PRINT_L0(tools::wallet_rpc_server::tr("Stopped wallet RPC server")); + oxen::log::warning(globallogcat, tools::wallet_rpc_server::tr("Stopped wallet RPC server")); try { close_wallet(true); } catch (const std::exception& e) { - LOG_ERROR(tools::wallet_rpc_server::tr("Failed to save wallet: ") << e.what()); + oxen::log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to save wallet: "), e.what()); return false; } return true; @@ -3580,7 +3581,7 @@ int main(int argc, char **argv) tools::wallet_rpc_server::tr("This is the RPC oxen wallet. It needs to connect to a oxen\ndaemon to work correctly."), desc_params, hidden_params, po::positional_options_description(), - [](const std::string &s, bool emphasis){ epee::set_console_color(emphasis ? epee::console_color_white : epee::console_color_default, emphasis); std::cout << s << std::endl; if (emphasis) epee::reset_console_color(); }, + [](const std::string &s){}, "oxen-wallet-rpc.log", true ); diff --git a/src/wallet/wallet_rpc_server.h b/src/wallet/wallet_rpc_server.h index 887f70653..5d486289f 100644 --- a/src/wallet/wallet_rpc_server.h +++ b/src/wallet/wallet_rpc_server.h @@ -44,11 +44,10 @@ #include "wallet2.h" #include "rpc/common/http_server_base.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.rpc" - namespace tools { + static auto logcat = oxen::log::Cat("wallet.rpc"); + using HttpRequest = uWS::HttpRequest; using HttpResponse = uWS::HttpResponse; diff --git a/src/wallet/wallet_rpc_server_commands_defs.h b/src/wallet/wallet_rpc_server_commands_defs.h index 41e18298b..dccd80fb0 100644 --- a/src/wallet/wallet_rpc_server_commands_defs.h +++ b/src/wallet/wallet_rpc_server_commands_defs.h @@ -39,9 +39,6 @@ #include "common/meta.h" #include "common/oxen.h" -#undef OXEN_DEFAULT_LOG_CATEGORY -#define OXEN_DEFAULT_LOG_CATEGORY "wallet.rpc" - // When making *any* change here, bump minor // If the change is incompatible, then bump major and set minor to 0 // This ensures WALLET_RPC_VERSION always increases, that every change @@ -62,6 +59,8 @@ namespace tools::wallet_rpc { + static auto logcat = oxen::log::Cat("wallet.rpc"); + /// Base class that all wallet rpc commands inherit from struct RPC_COMMAND {}; diff --git a/src/wallet3/transaction_scanner.cpp b/src/wallet3/transaction_scanner.cpp index 08749e75a..1256e032f 100644 --- a/src/wallet3/transaction_scanner.cpp +++ b/src/wallet3/transaction_scanner.cpp @@ -9,6 +9,8 @@ namespace wallet { + static auto logcat = oxen::log::Cat("wallet.wallet3"); + std::vector TransactionScanner::scan_received( const BlockTX& tx, int64_t height, int64_t timestamp) @@ -19,9 +21,7 @@ namespace wallet if (tx_public_keys.empty()) { - LOG_PRINT_L0( - "TransactionScanner found no tx public keys in transaction with hash <" << tx.hash - << ">."); + oxen::log::warning(logcat, "TransactionScanner found no tx public keys in transaction with hash <{}>.", tx.hash); return {}; } if (tx.tx.vout.size() != tx.global_indices.size()) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index fd1947189..cce0e03da 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -93,7 +93,6 @@ set(enabled_tests difficulty block_weight hash - performance_tests core_proxy fuzz wallet3_tests diff --git a/tests/block_weight/CMakeLists.txt b/tests/block_weight/CMakeLists.txt index 198c4fa41..fd9219b9f 100644 --- a/tests/block_weight/CMakeLists.txt +++ b/tests/block_weight/CMakeLists.txt @@ -33,6 +33,7 @@ target_link_libraries(block_weight cryptonote_core blockchain_db SQLiteCpp + logging extra) add_test( diff --git a/tests/core_proxy/CMakeLists.txt b/tests/core_proxy/CMakeLists.txt index 5601a92ad..ae76dbfdf 100644 --- a/tests/core_proxy/CMakeLists.txt +++ b/tests/core_proxy/CMakeLists.txt @@ -38,6 +38,7 @@ target_link_libraries(core_proxy epee Boost::program_options SQLiteCpp + logging extra) set_property(TARGET core_proxy PROPERTY diff --git a/tests/core_proxy/core_proxy.cpp b/tests/core_proxy/core_proxy.cpp index b18c2de1d..9ae654bf4 100644 --- a/tests/core_proxy/core_proxy.cpp +++ b/tests/core_proxy/core_proxy.cpp @@ -73,8 +73,7 @@ int main(int argc, char* argv[]) epee::string_tools::set_module_name_and_folder(argv[0]); //set up logging options - mlog_configure(mlog_get_default_log_path("core_proxy.log"), true); - mlog_set_log_level(2); + oxen::logging::init("core_proxy.log", oxen::log::Level::debug); po::options_description desc("Allowed options"); @@ -92,8 +91,8 @@ int main(int argc, char* argv[]) if (!r) return 1; - MGINFO("Module folder: " << argv[0]); - MGINFO("Node starting ..."); + oxen::log::info(logcat, "Module folder: {}", argv[0]); + oxen::log::info(logcat, "Node starting ..."); //create objects and link them @@ -108,32 +107,32 @@ int main(int argc, char* argv[]) //initialize objects - MGINFO("Initializing p2p server..."); + oxen::log::info(logcat, "Initializing p2p server..."); bool res = p2psrv.init(vm); CHECK_AND_ASSERT_MES(res, 1, "Failed to initialize p2p server."); - MGINFO("P2p server initialized OK"); + oxen::log::info(logcat, "P2p server initialized OK"); - MGINFO("Initializing cryptonote protocol..."); + oxen::log::info(logcat, "Initializing cryptonote protocol..."); res = cprotocol.init(vm); CHECK_AND_ASSERT_MES(res, 1, "Failed to initialize cryptonote protocol."); - MGINFO("Cryptonote protocol initialized OK"); + oxen::log::info(logcat, "Cryptonote protocol initialized OK"); //initialize core here - MGINFO("Initializing proxy core..."); + oxen::log::info(logcat, "Initializing proxy core..."); res = pr_core.init(vm); CHECK_AND_ASSERT_MES(res, 1, "Failed to initialize core"); - MGINFO("Core initialized OK"); + oxen::log::info(logcat, "Core initialized OK"); - MGINFO("Starting p2p net loop..."); + oxen::log::info(logcat, "Starting p2p net loop..."); p2psrv.run(); - MGINFO("p2p net loop stopped"); + oxen::log::info(logcat, "p2p net loop stopped"); //deinitialize components - MGINFO("Deinitializing core..."); + oxen::log::info(logcat, "Deinitializing core..."); pr_core.deinit(); - MGINFO("Deinitializing cryptonote_protocol..."); + oxen::log::info(logcat, "Deinitializing cryptonote_protocol..."); cprotocol.deinit(); - MGINFO("Deinitializing p2p..."); + oxen::log::info(logcat, "Deinitializing p2p..."); p2psrv.deinit(); @@ -141,7 +140,7 @@ int main(int argc, char* argv[]) cprotocol.set_p2p_endpoint(NULL); - MGINFO("Node stopped."); + oxen::log::info(logcat, "Node stopped."); return 0; CATCH_ENTRY_L0("main", 1); diff --git a/tests/core_tests/CMakeLists.txt b/tests/core_tests/CMakeLists.txt index 99bc880e1..44e762a1c 100644 --- a/tests/core_tests/CMakeLists.txt +++ b/tests/core_tests/CMakeLists.txt @@ -58,6 +58,7 @@ target_link_libraries(core_tests wallet Boost::program_options SQLiteCpp + logging extra) set_property(TARGET core_tests PROPERTY diff --git a/tests/core_tests/block_validation.cpp b/tests/core_tests/block_validation.cpp index f09b41b96..428b78824 100644 --- a/tests/core_tests/block_validation.cpp +++ b/tests/core_tests/block_validation.cpp @@ -457,7 +457,7 @@ static bool construct_miner_tx_with_extra_output(cryptonote::transaction& tx, const auto hard_fork_version = hf::hf7; // NOTE(oxen): We know this test doesn't need the new block reward formula uint64_t block_reward, block_reward_unpenalized; if (!get_base_block_reward(0, 0, already_generated_coins, block_reward, block_reward_unpenalized, hf::hf7, 0)) { - LOG_PRINT_L0("Block is too big"); + oxen::log::warning(globallogcat, "Block is too big"); return false; } @@ -489,7 +489,7 @@ static bool construct_miner_tx_with_extra_output(cryptonote::transaction& tx, if (!get_deterministic_output_key( governance_wallet_address.address, gov_key, tx.vout.size(), out_eph_public_key)) { - MERROR("Failed to generate deterministic output key for governance wallet output creation"); + oxen::log::error(globallogcat, "Failed to generate deterministic output key for governance wallet output creation"); return false; } diff --git a/tests/core_tests/bulletproofs.cpp b/tests/core_tests/bulletproofs.cpp index 79705317e..0e0adfc71 100644 --- a/tests/core_tests/bulletproofs.cpp +++ b/tests/core_tests/bulletproofs.cpp @@ -207,7 +207,7 @@ bool gen_bp_tx_validation_base::generate_with(std::vector& eve if (pre_tx && !pre_tx(sources, destinations, n)) { - MDEBUG("pre_tx returned failure"); + oxen::log::debug(globallogcat, "pre_tx returned failure"); return false; } @@ -228,14 +228,14 @@ bool gen_bp_tx_validation_base::generate_with(std::vector& eve nullptr, /*multisig_out*/ tx_params)) { - MDEBUG("construct_tx_and_get_tx_key failure"); + oxen::log::debug(globallogcat, "construct_tx_and_get_tx_key failure"); return false; } rct_txes.push_back(tx); if (post_tx && !post_tx(rct_txes.back(), n)) { - MDEBUG("post_tx returned failure"); + oxen::log::debug(globallogcat, "post_tx returned failure"); return false; } @@ -258,7 +258,7 @@ bool gen_bp_tx_validation_base::generate_with(std::vector& eve tx_hash.data[i] = unif(rng); } starting_rct_tx_hashes.push_back(tx_hash); - LOG_PRINT_L0("Test tx: " << obj_to_json_str(rct_txes.back())); + oxen::log::warning(globallogcat, "Test tx: {}", obj_to_json_str(rct_txes.back())); uint64_t total_amount_encoded = 0; for (int o = 0; amounts_paid[o] != (uint64_t)-1; ++o) diff --git a/tests/core_tests/chaingen.cpp b/tests/core_tests/chaingen.cpp index e3d1955c3..2c57af838 100644 --- a/tests/core_tests/chaingen.cpp +++ b/tests/core_tests/chaingen.cpp @@ -61,6 +61,7 @@ #include "chaingen.h" #include "device/device.hpp" #include "crypto/crypto.h" +#include "fmt/color.h" extern "C" { @@ -1612,13 +1613,13 @@ uint64_t get_amount(const cryptonote::account_base& account, const cryptonote::t else if (tx.rct_signatures.type == rct::RCTType::Null) money_transferred = tx.vout[i].amount; else { - LOG_PRINT_L0(__func__ << ": Unsupported rct type: " << (int)tx.rct_signatures.type); + oxen::log::warning(globallogcat, "{}: Unsupported rct type: {}", __func__, (int)tx.rct_signatures.type); return 0; } } catch (const std::exception &e) { - LOG_PRINT_L0("Failed to decode input " << i << ": " << e.what()); + oxen::log::warning(globallogcat, "Failed to decode input {}: {}", i, e.what()); return 0; } @@ -2587,7 +2588,7 @@ bool test_chain_unit_base::verify(const std::string& cb_name, cryptonote::core& auto cb_it = m_callbacks.find(cb_name); if(cb_it == m_callbacks.end()) { - LOG_ERROR("Failed to find callback " << cb_name); + oxen::log::error(globallogcat, "Failed to find callback {}", cb_name); return false; } return cb_it->second(c, ev_index, events); diff --git a/tests/core_tests/chaingen.h b/tests/core_tests/chaingen.h index 9a457855d..cadbebe28 100644 --- a/tests/core_tests/chaingen.h +++ b/tests/core_tests/chaingen.h @@ -40,11 +40,13 @@ #include #include #include +#include #include "cryptonote_protocol/quorumnet.h" #include "common/boost_serialization_helper.h" #include "common/command_line.h" #include "common/threadpool.h" +#include "epee/misc_log_ex.h" #include "cryptonote_basic/account_boost_serialization.h" #include "cryptonote_basic/cryptonote_basic.h" @@ -649,8 +651,11 @@ public: opts.kept_by_block = m_txs_keeped_by_block; m_c.handle_incoming_tx(t_serializable_object_to_blob(tx), tvc, opts); bool tx_added = pool_size + 1 == m_c.get_pool().get_transactions_count(); - bool r = m_validator.check_tx_verification_context(tvc, tx_added, m_ev_index, tx); - CHECK_AND_NO_ASSERT_MES(r, false, "tx verification context check failed"); + if (!m_validator.check_tx_verification_context(tvc, tx_added, m_ev_index, tx)) + { + oxen::log::warning(globallogcat, "tx verification context check failed"); + return false; + } return true; } @@ -669,8 +674,11 @@ public: for (auto &i : parsed) tvcs.push_back(i.tvc); size_t tx_added = m_c.get_pool().get_transactions_count() - pool_size; - bool r = m_validator.check_tx_verification_context_array(tvcs, tx_added, m_ev_index, txs); - CHECK_AND_NO_ASSERT_MES(r, false, "tx verification context check failed"); + if (!m_validator.check_tx_verification_context_array(tvcs, tx_added, m_ev_index, txs)) + { + oxen::log::warning(globallogcat, "tx verification context check failed"); + return false; + } return true; } @@ -687,9 +695,12 @@ public: } else bvc.m_verifivation_failed = true; - bool r = m_validator.check_block_verification_context(bvc, m_ev_index, b); - CHECK_AND_NO_ASSERT_MES(r, false, "block verification context check failed"); - return r; + if (!m_validator.check_block_verification_context(bvc, m_ev_index, b)) + { + oxen::log::warning(globallogcat, "block verification context check failed"); + return false; + } + return true; } // TODO(oxen): Deprecate callback_entry for oxen_callback_entry, why don't you @@ -729,8 +740,11 @@ public: } catch (...) { blk = cryptonote::block(); } - bool r = m_validator.check_block_verification_context(bvc, m_ev_index, blk); - CHECK_AND_NO_ASSERT_MES(r, false, "block verification context check failed"); + if (!m_validator.check_block_verification_context(bvc, m_ev_index, blk)) + { + oxen::log::warning(globallogcat, "block verification context check failed"); + return false; + } return true; } @@ -753,8 +767,11 @@ public: tx = cryptonote::transaction(); } - bool r = m_validator.check_tx_verification_context(tvc, tx_added, m_ev_index, tx); - CHECK_AND_NO_ASSERT_MES(r, false, "transaction verification context check failed"); + if (!m_validator.check_tx_verification_context(tvc, tx_added, m_ev_index, tx)) + { + oxen::log::warning(globallogcat, "transaction verification context check failed"); + return false; + } return true; } @@ -766,7 +783,14 @@ public: log_event("oxen_blockchain_addable"); cryptonote::Blockchain &blockchain = m_c.get_blockchain_storage(); bool added = blockchain.update_checkpoint(entry.data); - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : "Failed to add checkpoint (no reason given)")); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else + oxen::log::warning(globallogcat, "Failed to add checkpoint (no reason given)"); + return false; + } return true; } @@ -774,8 +798,15 @@ public: { log_event("oxen_blockchain_addable"); cryptonote::vote_verification_context vvc = {}; - bool added = m_c.add_service_node_vote(entry.data, vvc); - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : "Failed to add service node vote (no reason given)")); + bool added = m_c.add_service_node_vote(entry.data, vvc); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else + oxen::log::warning(globallogcat, "Failed to add service node vote (no reason given)"); + return false; + } return true; } @@ -800,7 +831,14 @@ public: bvc.m_verifivation_failed = true; bool added = !bvc.m_verifivation_failed; - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : "Failed to add block with checkpoint (no reason given)")); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else + oxen::log::warning(globallogcat, "Failed to add block with checkpoint (no reason given)"); + return false; + } return true; } @@ -820,7 +858,14 @@ public: bvc.m_verifivation_failed = true; bool added = !bvc.m_verifivation_failed; - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : "Failed to add block (no reason given)")); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else + oxen::log::warning(globallogcat, "Failed to add block (no reason given)"); + return false; + } return true; } @@ -839,7 +884,14 @@ public: bvc.m_verifivation_failed = true; bool added = !bvc.m_verifivation_failed; - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : "Failed to add block (no reason given)")); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else + oxen::log::warning(globallogcat, "Failed to add block (no reason given)"); + return false; + } return true; } @@ -853,9 +905,17 @@ public: m_c.handle_incoming_tx(t_serializable_object_to_blob(entry.data.tx), tvc, opts); bool added = (pool_size + 1) == m_c.get_pool().get_transactions_count(); + if (added != entry.can_be_added_to_blockchain) + { + if (entry.fail_msg.size()) + oxen::log::warning(globallogcat, entry.fail_msg); + else if (entry.can_be_added_to_blockchain) + oxen::log::warning(globallogcat, "Failed to add transaction that should have been accepted"); + else + oxen::log::warning(globallogcat, "TX adding should have failed, but didn't"); + return false; + } - CHECK_AND_NO_ASSERT_MES(added == entry.can_be_added_to_blockchain, false, (entry.fail_msg.size() ? entry.fail_msg : - entry.can_be_added_to_blockchain ? "Failed to add transaction that should have been accepted" : "TX adding should have failed, but didn't")); return true; } @@ -869,15 +929,15 @@ public: bool operator()(const std::string &msg) const { log_event("event_msgevent_marker"); - MGINFO_MAGENTA(msg); + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::magenta), msg)); return true; } private: void log_event(const std::string& event_type) const { - if (LOG_ENABLED(Info)) - MGINFO_YELLOW("=== EVENT # " << m_ev_index << ": " << event_type); + if (globallogcat->should_log(oxen::log::Level::info)) + oxen::log::debug(globallogcat, fmt::format(fg(fmt::terminal_color::yellow), "=== EVENT # {}:{}", m_ev_index, event_type)); } }; //-------------------------------------------------------------------------- @@ -964,7 +1024,7 @@ inline bool do_replay_events_get_core(std::vector& events, cry cryptonote::test_options const *testing_options = (use_derived_hardforks) ? &derived_test_options : >o.test_options; if (!c.init(vm, testing_options)) { - MERROR("Failed to init core"); + oxen::log::error(globallogcat, "Failed to init core"); return false; } c.get_blockchain_storage().get_db().set_batch_transactions(true); @@ -979,7 +1039,7 @@ inline bool do_replay_file(const std::string& filename) std::vector events; if (!tools::unserialize_obj_from_file(events, filename)) { - MERROR("Failed to deserialize data from file: "); + oxen::log::error(globallogcat, "Failed to deserialize data from file: "); return false; } @@ -1141,24 +1201,24 @@ inline bool do_replay_file(const std::string& filename) #define PLAY(filename, generator_class) \ if(!do_replay_file(filename)) \ { \ - MERROR("Failed to pass test : " << #generator_class); \ + oxen::log::error(globallogcat, "Failed to pass test : {}", #generator_class); \ return 1; \ } #define CATCH_REPLAY(generator_class) \ - catch (const std::exception &ex) { MERROR(#generator_class << " generation failed: what=" << ex.what()); } \ - catch (...) { MERROR(#generator_class << " generation failed: generic exception"); } + catch (const std::exception &ex) { oxen::log::error(globallogcat, "{} generation failed: what={}", #generator_class, ex.what()); }\ + catch (...) { oxen::log::error(globallogcat, "{} generation failed: generic exception", #generator_class); } #define REPLAY_CORE(generator_class, generator_class_instance) \ { \ cryptonote::core core; \ if (generated && do_replay_events_get_core(events, &core, generator_class_instance)) \ { \ - MGINFO_GREEN("#TEST# Succeeded " << #generator_class); \ + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "#TEST# Succeeded {}", #generator_class));\ } \ else \ { \ - MERROR("#TEST# Failed " << #generator_class); \ + oxen::log::error(globallogcat, "#TEST# Failed {}", #generator_class); \ failed_tests.push_back(#generator_class); \ } \ core.deinit(); \ @@ -1169,11 +1229,11 @@ inline bool do_replay_file(const std::string& filename) if (generated && \ replay_events_through_core_plain(events, CORE, generator_class_instance, false /*reinit*/)) \ { \ - MGINFO_GREEN("#TEST# Succeeded " << #generator_class); \ + oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "#TEST# Succeeded {}", #generator_class));\ } \ else \ { \ - MERROR("#TEST# Failed " << #generator_class); \ + oxen::log::error(globallogcat, "{}{}", , "#TEST# Failed ", #generator_class); \ failed_tests.push_back(#generator_class); \ } \ } diff --git a/tests/core_tests/chaingen_main.cpp b/tests/core_tests/chaingen_main.cpp index e3b9590f6..71508083b 100644 --- a/tests/core_tests/chaingen_main.cpp +++ b/tests/core_tests/chaingen_main.cpp @@ -53,8 +53,6 @@ int main(int argc, char* argv[]) // Bypass tx version checks for core tests: cryptonote::hack::test_suite_permissive_txes = true; - //set up logging options - mlog_configure(mlog_get_default_log_path("core_tests.log"), true); po::options_description desc_options("Allowed options"); command_line::add_arg(desc_options, command_line::arg_help); @@ -78,10 +76,13 @@ int main(int argc, char* argv[]) return 0; } + auto log_level = oxen::log::Level::info; if (!command_line::is_arg_defaulted(vm, arg_log_level)) - mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); - else - mlog_set_log_level(0); + if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) + log_level = *level; + + //set up logging options + oxen::logging::init("core_tests.log", log_level); const std::string filter = command_line::get_arg(vm, arg_filter); @@ -315,20 +316,14 @@ int main(int argc, char* argv[]) GENERATE_AND_PLAY(gen_multisig_tx_valid_48_1_234_many_inputs); #endif - el::Level level = (failed_tests.empty() ? el::Level::Info : el::Level::Error); - if (!list_tests) - { - MLOG(level, "\nREPORT:"); - MLOG(level, " Test run: " << tests_count); - MLOG(level, " Failures: " << failed_tests.size()); - } + if (!list_tests && failed_tests.empty()) + oxen::log::info(globallogcat, "\nREPORT:\n Test run: {}\n Failures: {}", tests_count, failed_tests.size()); if (!failed_tests.empty()) { - MLOG(level, "FAILED TESTS:"); - for (auto &test_name : failed_tests) - { - MLOG(level, " " << test_name); - } + oxen::log::error(globallogcat, "\nREPORT:\n Test run: {}\n Failures: {}", tests_count, failed_tests.size()); + oxen::log::error(globallogcat, "Failed TESTS:"); + for (auto& test_name : failed_tests) + oxen::log::error(globallogcat, " {}", test_name); } } diff --git a/tests/core_tests/multisig.cpp b/tests/core_tests/multisig.cpp index 026f94d00..0d9084fd9 100644 --- a/tests/core_tests/multisig.cpp +++ b/tests/core_tests/multisig.cpp @@ -29,8 +29,6 @@ // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "ringct/rctSigs.h" -#include "cryptonote_basic/cryptonote_basic.h" -#include "cryptonote_core/uptime_proof.h" #include "multisig/multisig.h" #include "common/apply_permutation.h" #include "common/util.h" @@ -210,9 +208,9 @@ bool gen_multisig_tx_validation_base::generate_with(std::vector(blocks[n].miner_tx.vout[0].target).key; - MDEBUG("output_pub_key: " << output_pub_key); + //oxen::log::debug(logcat, "output_pub_key: {}", output_pub_key); } std::unordered_map subaddresses; @@ -251,19 +249,19 @@ bool gen_multisig_tx_validation_base::generate_with(std::vector(blocks[m].miner_tx.vout[0].target).key); - MDEBUG("using " << (m == n ? "real" : "fake") << " input " << ctkey.dest); + //oxen::log::debug(logcat, "using {} input {}", (m == n ? "real" : "fake"), ctkey.dest); ctkey.mask = rct::commit(blocks[m].miner_tx.vout[0].amount, rct::identity()); // since those are coinbases, the masks are known src.outputs.push_back(std::make_pair(m, ctkey)); } @@ -429,13 +427,13 @@ bool gen_multisig_tx_validation_base::generate_with(std::vector 0 && rewards_from_fee < tx_fee, "Block producer should receive a penalised tx fee less than " << cryptonote::print_money(tx_fee) << "received, " << cryptonote::print_money(rewards_from_fee) << ""); CHECK_TEST_CONDITION_MSG(top_block.miner_tx.vout[1].amount == unpenalized_reward, "Service Node should receive full reward " << unpenalized_reward); - MGINFO("rewards_from_fee: " << cryptonote::print_money(rewards_from_fee)); - MGINFO("tx_fee: " << cryptonote::print_money(tx_fee)); - MGINFO("unpenalized_amount: " << cryptonote::print_money(unpenalized_reward)); + oxen::log::info(globallogcat, "rewards_from_fee: {}", cryptonote::print_money(rewards_from_fee)); + oxen::log::info(globallogcat, "tx_fee: {}", cryptonote::print_money(tx_fee)); + oxen::log::info(globallogcat, "unpenalized_amount: {}", cryptonote::print_money(unpenalized_reward)); return true; }); return true; @@ -2810,7 +2810,7 @@ bool oxen_service_nodes_test_rollback::generate(std::vector& e crypto::public_key pk_b; if (!cryptonote::get_service_node_pubkey_from_tx_extra(reg_tx.data.tx.extra, pk_b)) { - MERROR("Could not get service node key from tx extra"); + oxen::log::error(globallogcat, "Could not get service node key from tx extra"); return false; } @@ -3730,7 +3730,7 @@ bool oxen_batch_sn_rewards_bad_address::generate(std::vector & crypto::public_key bob_deterministic_output_key{}; if (!cryptonote::get_deterministic_output_key(bob_address, txkey, 0, bob_deterministic_output_key)) { - MERROR("Failed to generate output one-time public key"); + oxen::log::error(globallogcat, "Failed to generate output one-time public key"); return false; } // Switch Alice as recipient of payment to Bob diff --git a/tests/core_tests/rct.cpp b/tests/core_tests/rct.cpp index f94d4f295..9d9e6c90e 100644 --- a/tests/core_tests/rct.cpp +++ b/tests/core_tests/rct.cpp @@ -238,7 +238,7 @@ bool gen_rct_tx_validation_base::generate_with_full(std::vector& events) con std::vector chain; map_hash2tx_t mtx; - bool r = find_block_chain(events, chain, mtx, get_block_hash(blk_i)); - CHECK_AND_NO_ASSERT_MES(r, false, "failed to call find_block_chain"); + if (!find_block_chain(events, chain, mtx, get_block_hash(blk_i))) + { + oxen::log::warning(globallogcat, "failed to call find_block_chain"); + return false; + } std::cout << i << ": " << get_balance(accounts[i], chain, mtx) << std::endl; } diff --git a/tests/core_tests/wallet_tools.cpp b/tests/core_tests/wallet_tools.cpp index 80560564b..66d446eee 100644 --- a/tests/core_tests/wallet_tools.cpp +++ b/tests/core_tests/wallet_tools.cpp @@ -108,11 +108,11 @@ bool wallet_tools::fill_tx_sources(tools::wallet2 * wallet, std::vector cur_height) continue; if (selected_idx.find((size_t)i) != selected_idx.end()){ - MERROR("Should not happen (selected_idx not found): " << i); + oxen::log::error(globallogcat, "Should not happen (selected_idx not found): {}", i); continue; } if (selected_kis.find(td.m_key_image) != selected_kis.end()){ - MERROR("Should not happen (selected KI): " << i << "ki: " << dump_keys(td.m_key_image.data)); + oxen::log::error(globallogcat, "Should not happen (selected KI): {} ki: {}", i, dump_keys(td.m_key_image.data)); continue; } @@ -131,11 +131,7 @@ bool wallet_tools::fill_tx_sources(tools::wallet2 * wallet, std::vector= FIRST_N_TRANSFERS) break; } @@ -230,7 +230,7 @@ bool transactions_flow_test(std::string& working_folder, while(w1.unlocked_balance(0, true) < amount_to_tx + TEST_FEE) { std::this_thread::sleep_for(1s); - LOG_PRINT_L0("not enough money, waiting for cashback or mining"); + oxen::log::warning(logcat, "not enough money, waiting for cashback or mining"); w1.refresh(true, blocks_fetched, received_money, ok); } @@ -245,11 +245,11 @@ bool transactions_flow_test(std::string& working_folder, if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { - LOG_PRINT_L0("failed to transfer money, tx: " << get_transaction_hash(tx) << ", refresh and try again" ); + oxen::log::warning(logcat, "failed to transfer money, tx: {}, refresh and try again", get_transaction_hash(tx)); w1.refresh(true, blocks_fetched, received_money, ok); if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { - LOG_PRINT_L0( "failed to transfer money, second chance. tx: " << get_transaction_hash(tx) << ", exit" ); + oxen::log::warning(logcat, "failed to transfer money, second chance. tx: {}, exit", get_transaction_hash(tx)); LOCAL_ASSERT(false); return false; } @@ -258,7 +258,7 @@ bool transactions_flow_test(std::string& working_folder, transfered_money += amount_to_tx; - LOG_PRINT_L0("transferred " << amount_to_tx << ", i=" << i ); + oxen::log::warning(logcat, "transferred {}, i={}", amount_to_tx, i); tx_test_entry& ent = txs[get_transaction_hash(tx)] = {}; ent.amount_transfered = amount_to_tx; ent.tx = tx; @@ -267,9 +267,9 @@ bool transactions_flow_test(std::string& working_folder, } - LOG_PRINT_L0( "waiting some new blocks..."); + oxen::log::warning(logcat, "waiting some new blocks..."); std::this_thread::sleep_for(TARGET_BLOCK_TIME*20*1s);//wait two blocks before sync on another wallet on another daemon - LOG_PRINT_L0( "refreshing..."); + oxen::log::warning(logcat, "refreshing..."); bool recvd_money = false; while(w2.refresh(true, blocks_fetched, recvd_money, ok) && ( (blocks_fetched && recvd_money) || !blocks_fetched ) ) { @@ -279,8 +279,8 @@ bool transactions_flow_test(std::string& working_folder, uint64_t money_2 = w2.balance(0, true); if(money_2 == transfered_money) { - MGINFO_GREEN("-----------------------FINISHING TRANSACTIONS FLOW TEST OK-----------------------"); - MGINFO_GREEN("transferred " << print_money(transfered_money) << " via " << i << " transactions" ); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "-----------------------FINISHING TRANSACTIONS FLOW TEST OK-----------------------"); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "transferred {} via {} transactions", print_money(transfered_money), i); return true; }else { @@ -297,13 +297,13 @@ bool transactions_flow_test(std::string& working_folder, { if(tx_pair.second.m_received_count != 1) { - MERROR("Transaction lost: " << get_transaction_hash(tx_pair.second.tx)); + oxen::log::error(logcat, "{}{}", , "Transaction lost: ", get_transaction_hash(tx_pair.second.tx)); } } - MERROR("-----------------------FINISHING TRANSACTIONS FLOW TEST FAILED-----------------------" ); - MERROR("income " << print_money(money_2) << " via " << i << " transactions, expected money = " << print_money(transfered_money) ); + oxen::log::error(logcat, "-----------------------FINISHING TRANSACTIONS FLOW TEST FAILED-----------------------" ); + oxen::log::error(logcat, "income {} via {} transactions, expected money = {}", print_money(money_2), i, print_money(transfered_money)); LOCAL_ASSERT(false); return false; } diff --git a/tests/fuzz/CMakeLists.txt b/tests/fuzz/CMakeLists.txt index af7aa15c6..0c21d2bdb 100644 --- a/tests/fuzz/CMakeLists.txt +++ b/tests/fuzz/CMakeLists.txt @@ -33,6 +33,7 @@ target_link_libraries(block_fuzz_tests p2p epee device + logging extra) set_property(TARGET block_fuzz_tests PROPERTY @@ -45,6 +46,7 @@ target_link_libraries(transaction_fuzz_tests p2p epee device + logging extra) set_property(TARGET transaction_fuzz_tests PROPERTY @@ -58,6 +60,7 @@ target_link_libraries(signature_fuzz_tests p2p epee device + logging extra) set_property(TARGET signature_fuzz_tests PROPERTY @@ -71,6 +74,7 @@ target_link_libraries(cold-outputs_fuzz_tests p2p epee device + logging extra) set_property(TARGET cold-outputs_fuzz_tests PROPERTY @@ -84,6 +88,7 @@ target_link_libraries(cold-transaction_fuzz_tests p2p epee device + logging extra) set_property(TARGET cold-transaction_fuzz_tests PROPERTY @@ -95,6 +100,7 @@ target_link_libraries(load-from-binary_fuzz_tests common epee Boost::program_options + logging extra) set_property(TARGET load-from-binary_fuzz_tests PROPERTY @@ -106,6 +112,7 @@ target_link_libraries(load-from-json_fuzz_tests common epee Boost::program_options + logging extra) set_property(TARGET load-from-json_fuzz_tests PROPERTY @@ -117,6 +124,7 @@ target_link_libraries(base58_fuzz_tests common epee Boost::program_options + logging extra) set_property(TARGET base58_fuzz_tests PROPERTY @@ -129,6 +137,7 @@ target_link_libraries(levin_fuzz_tests epee Boost::thread Boost::program_options + logging extra) set_property(TARGET levin_fuzz_tests PROPERTY @@ -141,6 +150,7 @@ target_link_libraries(bulletproof_fuzz_tests epee Boost::thread Boost::program_options + logging extra) set_property(TARGET bulletproof_fuzz_tests PROPERTY diff --git a/tests/fuzz/fuzzer.cpp b/tests/fuzz/fuzzer.cpp index 7bb580f32..4cb2d2ec0 100644 --- a/tests/fuzz/fuzzer.cpp +++ b/tests/fuzz/fuzzer.cpp @@ -28,6 +28,7 @@ #include #include "epee/string_tools.h" +#include "epee/misc_log_ex.h" #include "common/command_line.h" #include "common/util.h" #include "fuzzer.h" diff --git a/tests/hash/CMakeLists.txt b/tests/hash/CMakeLists.txt index c53b5a84f..af7505b01 100644 --- a/tests/hash/CMakeLists.txt +++ b/tests/hash/CMakeLists.txt @@ -32,6 +32,7 @@ target_link_libraries(hash-tests PRIVATE cryptonote_core common + logging extra) set_property(TARGET hash-tests PROPERTY diff --git a/tests/libwallet_api_tests/main.cpp b/tests/libwallet_api_tests/main.cpp index 07650a618..0b2e07553 100644 --- a/tests/libwallet_api_tests/main.cpp +++ b/tests/libwallet_api_tests/main.cpp @@ -233,8 +233,7 @@ TEST_F(WalletManagerTest, WalletManagerOpensWallet) TEST_F(WalletManagerTest, WalletMaxAmountAsString) { - LOG_PRINT_L3("max amount: " << Wallet::Wallet::displayAmount( - Wallet::Wallet::maximumAllowedAmount())); + oxen::log::trace(logcat, "max amount: {}", Wallet::Wallet::displayAmount( Wallet::Wallet::maximumAllowedAmount())); } @@ -256,11 +255,11 @@ void open_wallet_helper(Wallet::WalletManager *wmgr, Wallet::Wallet **wallet, co { if (mutex) mutex->lock(); - LOG_PRINT_L3("opening wallet in thread: " << boost::this_thread::get_id()); + oxen::log::trace(logcat, "opening wallet in thread: {}", boost::this_thread::get_id()); *wallet = wmgr->openWallet(WALLET_NAME, pass, Wallet::NetworkType::TESTNET); - LOG_PRINT_L3("wallet address: " << (*wallet)->mainAddress()); - LOG_PRINT_L3("wallet status: " << (*wallet)->status()); - LOG_PRINT_L3("closing wallet in thread: " << boost::this_thread::get_id()); + oxen::log::trace(logcat, "wallet address: {}", (*wallet)->mainAddress()); + oxen::log::trace(logcat, "wallet status: {}", (*wallet)->status()); + oxen::log::trace(logcat, "closing wallet in thread: {}", boost::this_thread::get_id()); if (mutex) mutex->unlock(); } diff --git a/tests/net_load_tests/CMakeLists.txt b/tests/net_load_tests/CMakeLists.txt index 569fc75bd..56bd0299b 100644 --- a/tests/net_load_tests/CMakeLists.txt +++ b/tests/net_load_tests/CMakeLists.txt @@ -35,6 +35,7 @@ target_link_libraries(net_load_tests_clt epee gtest Boost::thread + logging extra) add_executable(net_load_tests_srv @@ -45,6 +46,7 @@ target_link_libraries(net_load_tests_srv cryptonote_core epee gtest + logging extra) set_property(TARGET net_load_tests_clt net_load_tests_srv diff --git a/tests/net_load_tests/clt.cpp b/tests/net_load_tests/clt.cpp index 82dac0263..192609e49 100644 --- a/tests/net_load_tests/clt.cpp +++ b/tests/net_load_tests/clt.cpp @@ -39,6 +39,7 @@ #include "epee/misc_log_ex.h" #include "epee/storages/levin_abstract_invoke2.h" +#include "logging/oxen_logger.h" #include "common/util.h" #include "net_load_tests.h" @@ -207,7 +208,7 @@ namespace } else { - LOG_ERROR("Connection error: " << ec.message()); + oxen::log::error(globallogcat, "Connection error: {}", ec.message()); } conn_status.store(1, std::memory_order_seq_cst); })); @@ -304,7 +305,7 @@ namespace } else { - LOG_ERROR("Get server statistics error: " << code); + oxen::log::error(globallogcat, "Get server statistics error: {}", code); } req_status.store(0 < code ? 1 : -1, std::memory_order_seq_cst); })); @@ -355,8 +356,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for all open requests to complete EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&]{ return CONNECTION_COUNT + RESERVED_CONN_CNT <= m_commands_handler.new_connection_counter() + connection_opener.error_count(); })); - LOG_PRINT_L0("number of opened connections / fails (total): " << m_commands_handler.new_connection_counter() << - " / " << connection_opener.error_count() << " (" << (m_commands_handler.new_connection_counter() + connection_opener.error_count()) << ")"); + oxen::log::warning(globallogcat, "number of opened connections / fails (total): {} / {} ({})", m_commands_handler.new_connection_counter(), connection_opener.error_count(), (m_commands_handler.new_connection_counter() + connection_opener.error_count())); // Check ASSERT_GT(m_commands_handler.new_connection_counter(), RESERVED_CONN_CNT); @@ -373,8 +373,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for all opened connections to close EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&]{ return m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT <= m_commands_handler.close_connection_counter(); })); - LOG_PRINT_L0("number of opened / closed connections: " << m_tcp_server.get_config_object().get_connections_count() << - " / " << m_commands_handler.close_connection_counter()); + oxen::log::warning(globallogcat, "number of opened / closed connections: {} / {}", m_tcp_server.get_config_object().get_connections_count(), m_commands_handler.close_connection_counter()); // Check all connections are closed ASSERT_EQ(m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT, m_commands_handler.close_connection_counter()); @@ -383,7 +382,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for server to handle all open and close requests CMD_GET_STATISTICS::response srv_stat; busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status // It's OK, if server didn't close all opened connections, because of it could receive not all FIN packets @@ -395,7 +394,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for server to close rest connections busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status. All connections should be closed ASSERT_EQ(srv_stat.close_connection_counter, srv_stat.new_connection_counter - RESERVED_CONN_CNT); @@ -412,8 +411,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for all open requests to complete EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return CONNECTION_COUNT + RESERVED_CONN_CNT <= m_commands_handler.new_connection_counter() + connection_opener.error_count(); })); - LOG_PRINT_L0("number of opened connections / fails (total): " << m_commands_handler.new_connection_counter() << - " / " << connection_opener.error_count() << " (" << (m_commands_handler.new_connection_counter() + connection_opener.error_count()) << ")"); + oxen::log::warning(globallogcat, "number of opened connections / fails (total): {} / {} ({})", m_commands_handler.new_connection_counter(), connection_opener.error_count(), (m_commands_handler.new_connection_counter() + connection_opener.error_count())); // Check ASSERT_GT(m_commands_handler.new_connection_counter(), RESERVED_CONN_CNT); @@ -434,8 +432,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for all opened connections to close busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT <= m_commands_handler.close_connection_counter(); }); - LOG_PRINT_L0("number of opened / closed connections: " << m_tcp_server.get_config_object().get_connections_count() << - " / " << m_commands_handler.close_connection_counter()); + oxen::log::warning(globallogcat, "number of opened / closed connections: {} / {}", m_tcp_server.get_config_object().get_connections_count(), m_commands_handler.close_connection_counter()); // It's OK, if server didn't close all connections, because it could accept not all our connections ASSERT_LE(m_commands_handler.close_connection_counter(), m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT); @@ -443,7 +440,7 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ // Wait for server to handle all open and close requests busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status ASSERT_EQ(srv_stat.close_connection_counter, srv_stat.new_connection_counter - RESERVED_CONN_CNT); @@ -458,19 +455,18 @@ TEST_F(net_load_test_clt, a_lot_of_client_connections_and_connections_closed_by_ m_tcp_server.get_config_object(), [=](int code, const CMD_DATA_REQUEST::response& rsp, const test_connection_context&) { if (code <= 0) { - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST. code = " << code); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST. code = {}", code); } }); if (!r) - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST"); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST"); } return true; }); // Wait for all opened connections to close EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT <= m_commands_handler.close_connection_counter(); })); - LOG_PRINT_L0("number of opened / closed connections: " << m_tcp_server.get_config_object().get_connections_count() << - " / " << m_commands_handler.close_connection_counter()); + oxen::log::warning(globallogcat, "number of opened / closed connections: {} / {}", m_tcp_server.get_config_object().get_connections_count(), m_commands_handler.close_connection_counter()); // Check ASSERT_EQ(m_commands_handler.close_connection_counter(), m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT); @@ -489,8 +485,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_cli // Wait for all open requests to complete EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return CONNECTION_COUNT + RESERVED_CONN_CNT <= m_commands_handler.new_connection_counter() + connection_opener.error_count(); })); - LOG_PRINT_L0("number of opened connections / fails (total): " << m_commands_handler.new_connection_counter() << - " / " << connection_opener.error_count() << " (" << (m_commands_handler.new_connection_counter() + connection_opener.error_count()) << ")"); + oxen::log::warning(globallogcat, "number of opened connections / fails (total): {} / {} ({})", m_commands_handler.new_connection_counter(), connection_opener.error_count(), (m_commands_handler.new_connection_counter() + connection_opener.error_count())); // Check ASSERT_GT(m_commands_handler.new_connection_counter(), RESERVED_CONN_CNT); @@ -498,7 +493,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_cli // Wait for all close requests to complete EXPECT_TRUE(busy_wait_for(4 * DEFAULT_OPERATION_TIMEOUT, [&](){ return connection_opener.opened_connection_count() <= MAX_OPENED_CONN_COUNT; })); - LOG_PRINT_L0("actual number of opened connections: " << connection_opener.opened_connection_count()); + oxen::log::warning(globallogcat, "actual number of opened connections: {}", connection_opener.opened_connection_count()); // Check ASSERT_EQ(MAX_OPENED_CONN_COUNT, connection_opener.opened_connection_count()); @@ -507,7 +502,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_cli // Wait for all close requests to complete EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return m_commands_handler.new_connection_counter() <= m_commands_handler.close_connection_counter() + RESERVED_CONN_CNT; })); - LOG_PRINT_L0("actual number of opened connections: " << connection_opener.opened_connection_count()); + oxen::log::warning(globallogcat, "actual number of opened connections: {}", connection_opener.opened_connection_count()); ASSERT_EQ(m_commands_handler.new_connection_counter(), m_commands_handler.close_connection_counter() + RESERVED_CONN_CNT); ASSERT_EQ(0, connection_opener.opened_connection_count()); @@ -516,7 +511,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_cli // Wait for server to handle all open and close requests CMD_GET_STATISTICS::response srv_stat; busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status // It's OK, if server didn't close all opened connections, because of it could receive not all FIN packets @@ -528,7 +523,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_cli // Wait for server to close rest connections busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status. All connections should be closed ASSERT_EQ(srv_stat.close_connection_counter, srv_stat.new_connection_counter - RESERVED_CONN_CNT); @@ -561,9 +556,8 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_ser // Wait for all open requests to complete EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return CONNECTION_COUNT + RESERVED_CONN_CNT <= m_commands_handler.new_connection_counter() + connection_opener.error_count(); })); - LOG_PRINT_L0("number of opened connections / fails (total): " << m_commands_handler.new_connection_counter() << - " / " << connection_opener.error_count() << " (" << (m_commands_handler.new_connection_counter() + connection_opener.error_count()) << ")"); - LOG_PRINT_L0("actual number of opened connections: " << m_tcp_server.get_config_object().get_connections_count()); + oxen::log::warning(globallogcat, "number of opened connections / fails (total): {} / {} ({})", m_commands_handler.new_connection_counter(), connection_opener.error_count(), (m_commands_handler.new_connection_counter() + connection_opener.error_count())); + oxen::log::warning(globallogcat, "actual number of opened connections: {}", m_tcp_server.get_config_object().get_connections_count()); ASSERT_GT(m_commands_handler.new_connection_counter(), RESERVED_CONN_CNT); ASSERT_EQ(m_commands_handler.new_connection_counter() + connection_opener.error_count(), CONNECTION_COUNT + RESERVED_CONN_CNT); @@ -589,7 +583,7 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_ser // Wait for server to handle all open and close requests busy_wait_for_server_statistics(srv_stat, [](const CMD_GET_STATISTICS::response& stat) { return stat.new_connection_counter - RESERVED_CONN_CNT <= stat.close_connection_counter; }); - LOG_PRINT_L0("server statistics: " << srv_stat.to_string()); + oxen::log::warning(globallogcat, "server statistics: {}", srv_stat.to_string()); // Check server status ASSERT_EQ(srv_stat.close_connection_counter, srv_stat.new_connection_counter - RESERVED_CONN_CNT); @@ -604,19 +598,18 @@ TEST_F(net_load_test_clt, permament_open_and_close_and_connections_closed_by_ser m_tcp_server.get_config_object(), [=](int code, const CMD_DATA_REQUEST::response& rsp, const test_connection_context&) { if (code <= 0) { - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST. code = " << code); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST. code = {}", code); } }); if (!r) - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST"); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST"); } return true; }); // Wait for all opened connections to close EXPECT_TRUE(busy_wait_for(DEFAULT_OPERATION_TIMEOUT, [&](){ return m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT <= m_commands_handler.close_connection_counter(); })); - LOG_PRINT_L0("number of opened / closed connections: " << m_tcp_server.get_config_object().get_connections_count() << - " / " << m_commands_handler.close_connection_counter()); + oxen::log::warning(globallogcat, "number of opened / closed connections: {} / {}", m_tcp_server.get_config_object().get_connections_count(), m_commands_handler.close_connection_counter()); // Check ASSERT_EQ(m_commands_handler.close_connection_counter(), m_commands_handler.new_connection_counter() - RESERVED_CONN_CNT); @@ -629,7 +622,7 @@ int main(int argc, char** argv) tools::on_startup(); epee::debug::get_set_enable_assert(true, false); //set up logging options - mlog_configure(mlog_get_default_log_path("net_load_tests_clt.log"), true); + oxen::logging::init("net_load_tests_clt.log", oxen::log::Level::debug); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/tests/net_load_tests/net_load_tests.h b/tests/net_load_tests/net_load_tests.h index 11b03ae94..3db0ff30e 100644 --- a/tests/net_load_tests/net_load_tests.h +++ b/tests/net_load_tests/net_load_tests.h @@ -39,6 +39,7 @@ #include "epee/net/levin_protocol_handler_async.h" #include "epee/net/abstract_tcp_server2.h" #include "epee/serialization/keyvalue_serialization.h" +#include "ringct/fmt.h" #include "../unit_tests/unit_tests_utils.h" @@ -152,7 +153,7 @@ namespace net_load_tests size_t idx = m_next_opened_conn_idx.fetch_add(1, std::memory_order_relaxed); if (idx >= m_connections.size()) { - LOG_PRINT_L0("ERROR: connections overflow"); + oxen::log::warning(globallogcat, "ERROR: connections overflow"); exit(1); } m_connections[idx] = connection_id; @@ -176,17 +177,17 @@ namespace net_load_tests size_t idx = m_next_closed_conn_idx.fetch_add(1, std::memory_order_relaxed); if (m_next_opened_conn_idx.load(std::memory_order_relaxed) <= idx) { - LOG_PRINT_L0("Not enough opened connections"); + oxen::log::warning(globallogcat, "Not enough opened connections"); return false; } if (m_connections[idx].is_nil()) { - LOG_PRINT_L0("Connection isn't opened"); + oxen::log::warning(globallogcat, "Connection isn't opened"); return false; } if (!m_tcp_server.get_config_object().close(m_connections[idx])) { - LOG_PRINT_L0("Close connection error: " << m_connections[idx]); + oxen::log::warning(globallogcat, "Close connection error: {}", boost::lexical_cast(m_connections[idx])); if (!ignore_close_fails) { return false; diff --git a/tests/net_load_tests/srv.cpp b/tests/net_load_tests/srv.cpp index a6294e4cd..7f8683e10 100644 --- a/tests/net_load_tests/srv.cpp +++ b/tests/net_load_tests/srv.cpp @@ -34,13 +34,14 @@ #include "epee/misc_log_ex.h" #include "epee/storages/levin_abstract_invoke2.h" #include "common/util.h" +#include "logging/oxen_logger.h" #include "net_load_tests.h" using namespace net_load_tests; using namespace std::literals; -#define EXIT_ON_ERROR(cond) { if (!(cond)) { LOG_PRINT_L0("ERROR: " << #cond); exit(1); } else {} } +#define EXIT_ON_ERROR(cond) { if (!(cond)) { oxen::log::warning(globallogcat, "ERROR: {}", #cond); exit(1); } else {} } namespace { @@ -73,7 +74,7 @@ namespace std::unique_lock lock{m_open_close_test_mutex}; if (context.m_connection_id == m_open_close_test_conn_id) { - LOG_PRINT_L0("Stop open/close test"); + oxen::log::warning(globallogcat, "Stop open/close test"); m_open_close_test_conn_id = boost::uuids::nil_uuid(); m_open_close_test_helper.reset(0); } @@ -102,7 +103,7 @@ namespace rsp.opened_connections_count = m_tcp_server.get_config_object().get_connections_count(); rsp.new_connection_counter = new_connection_counter(); rsp.close_connection_counter = close_connection_counter(); - LOG_PRINT_L0("Statistics: " << rsp.to_string()); + oxen::log::warning(globallogcat, "Statistics: {}", rsp.to_string()); return 1; } @@ -119,7 +120,7 @@ namespace std::unique_lock lock{m_open_close_test_mutex}; if (0 == m_open_close_test_helper.get()) { - LOG_PRINT_L0("Start open/close test (" << req.open_request_target << ", " << req.max_opened_conn_count << ")"); + oxen::log::warning(globallogcat, "Start open/close test ({}, {})", req.open_request_target, req.max_opened_conn_count); m_open_close_test_conn_id = context.m_connection_id; m_open_close_test_helper.reset(new open_close_test_helper(m_tcp_server, req.open_request_target, req.max_opened_conn_count)); @@ -133,7 +134,7 @@ namespace int handle_shutdown(int command, const CMD_SHUTDOWN::request& req, test_connection_context& /*context*/) { - LOG_PRINT_L0("Got shutdown request. Shutting down..."); + oxen::log::warning(globallogcat, "Got shutdown request. Shutting down..."); m_tcp_server.send_stop_signal(); return 1; } @@ -151,11 +152,11 @@ namespace m_tcp_server.get_config_object(), [=](int code, const CMD_DATA_REQUEST::response& rsp, const test_connection_context&) { if (code <= 0) { - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST. code = " << code); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST. code = {}", code); } }); if (!r) - LOG_PRINT_L0("Failed to invoke CMD_DATA_REQUEST"); + oxen::log::warning(globallogcat, "Failed to invoke CMD_DATA_REQUEST"); } return true; }); @@ -166,7 +167,7 @@ namespace private: void close_connections(boost::uuids::uuid cmd_conn_id) { - LOG_PRINT_L0("Closing connections. Number of opened connections: " << m_tcp_server.get_config_object().get_connections_count()); + oxen::log::warning(globallogcat, "Closing connections. Number of opened connections: {}", m_tcp_server.get_config_object().get_connections_count()); size_t count = 0; bool r = m_tcp_server.get_config_object().foreach_connection([&](test_connection_context& ctx) { @@ -180,7 +181,7 @@ namespace } else { - LOG_PRINT_L0(count << " connection already closed"); + oxen::log::warning(globallogcat, "{} connection already closed", count); } } return true; @@ -199,7 +200,7 @@ namespace } else { - LOG_PRINT_L0("ERROR: " << ec.message() << ':' << ec.value()); + oxen::log::warning(globallogcat, "ERROR: {}:{}", ec.message(), ec.value()); } }); } @@ -219,7 +220,7 @@ int main(int argc, char** argv) TRY_ENTRY(); tools::on_startup(); //set up logging options - mlog_configure(mlog_get_default_log_path("net_load_tests_srv.log"), true); + oxen::logging::init("net_load_tests_srv.log", oxen::log::Level::debug); size_t thread_count = std::max(min_thread_count, std::thread::hardware_concurrency() / 2); diff --git a/tests/performance_tests/CMakeLists.txt b/tests/performance_tests/CMakeLists.txt index c7e8d7f37..d89c20d11 100644 --- a/tests/performance_tests/CMakeLists.txt +++ b/tests/performance_tests/CMakeLists.txt @@ -36,6 +36,7 @@ target_link_libraries(performance_tests common epee Boost::program_options + logging extra) set_property(TARGET performance_tests PROPERTY diff --git a/tests/performance_tests/main.cpp b/tests/performance_tests/main.cpp index 866e48049..24074bcce 100644 --- a/tests/performance_tests/main.cpp +++ b/tests/performance_tests/main.cpp @@ -68,7 +68,7 @@ int main(int argc, char** argv) set_process_affinity(1); set_thread_high_priority(); - mlog_configure(mlog_get_default_log_path("performance_tests.log"), true); + oxenlog::init("performance_tests.log", oxenlog::LogLevel::critical) po::options_description desc_options("Command line options"); const command_line::arg_descriptor arg_filter = { "filter", "Regular expression filter for which tests to run" }; diff --git a/tests/performance_tests/performance_tests.h b/tests/performance_tests/performance_tests.h index b4901c58e..790b9dcce 100644 --- a/tests/performance_tests/performance_tests.h +++ b/tests/performance_tests/performance_tests.h @@ -37,7 +37,7 @@ #include #include "epee/stats.h" -#include "common/perf_timer.h" +#include "spdlog/stopwatch.h" #include "timings.h" struct Params @@ -57,7 +57,7 @@ public: test_runner(const Params ¶ms) : m_elapsed(0s) , m_params(params) - , m_per_call_timers(T::loop_count * params.loop_multiplier, {true}) + , m_per_call_timers(T::loop_count * params.loop_multiplier) { } @@ -78,15 +78,14 @@ public: start = clock::now(); for (size_t i = 0; i < T::loop_count * m_params.loop_multiplier; ++i) { - if (m_params.stats) - m_per_call_timers[i].resume(); + auto call_start = clock::now(); if (!test.test()) return false; if (m_params.stats) - m_per_call_timers[i].pause(); + m_per_call_timers[i] = clock::now() - call_start; } m_elapsed = clock::now() - start; - m_stats.reset(new Stats(m_per_call_timers)); + m_stats.reset(new Stats, std::chrono::duration>(m_per_call_timers)); return true; } @@ -100,13 +99,13 @@ public: return m_elapsed / (T::loop_count * m_params.loop_multiplier); } - double get_min() const { return m_stats->get_min(); } - double get_max() const { return m_stats->get_max(); } - double get_mean() const { return m_stats->get_mean(); } - double get_median() const { return m_stats->get_median(); } - double get_stddev() const { return m_stats->get_standard_deviation(); } - double get_non_parametric_skew() const { return m_stats->get_non_parametric_skew(); } - std::vector get_quantiles(size_t n) const { return m_stats->get_quantiles(n); } + std::chrono::duration get_min() const { return m_stats->get_min(); } + std::chrono::duration get_max() const { return m_stats->get_max(); } + std::chrono::duration get_mean() const { return m_stats->get_mean(); } + std::chrono::duration get_median() const { return m_stats->get_median(); } + std::chrono::duration get_stddev() const { return m_stats->get_standard_deviation(); } + std::chrono::duration get_non_parametric_skew() const { return m_stats->get_non_parametric_skew(); } + std::vector> get_quantiles(size_t n) const { return m_stats->get_quantiles(n); } bool is_same_distribution(size_t npoints, double mean, double stddev) const { @@ -132,8 +131,8 @@ private: volatile uint64_t m_warm_up; /// m_elapsed; Params m_params; - std::vector m_per_call_timers; - std::unique_ptr> m_stats; + std::vector> m_per_call_timers; + std::unique_ptr, std::chrono::duration>> m_stats; }; std::string elapsed_str(std::chrono::duration seconds) @@ -180,12 +179,12 @@ void run_test(const std::string &filter, Params ¶ms, const char* test_name) std::cout << test_name << " (" << T::loop_count * params.loop_multiplier << " calls) - OK:"; } const auto quantiles = runner.get_quantiles(10); - double min = runner.get_min(); - double max = runner.get_max(); - double med = runner.get_median(); - double mean = runner.get_mean(); - double stddev = runner.get_stddev(); - double npskew = runner.get_non_parametric_skew(); + auto min = runner.get_min(); + auto max = runner.get_max(); + auto med = runner.get_median(); + auto mean = runner.get_mean(); + auto stddev = runner.get_stddev(); + auto npskew = runner.get_non_parametric_skew(); std::vector prev_instances = params.td.get(test_name); params.td.add(test_name, {time(NULL), runner.get_size(), min, max, mean, med, stddev, npskew, quantiles}); @@ -199,7 +198,7 @@ void run_test(const std::string &filter, Params ¶ms, const char* test_name) const TimingsDatabase::instance &prev_instance = prev_instances.back(); if (!runner.is_same_distribution(prev_instance.npoints, prev_instance.mean, prev_instance.stddev)) { - double pc = fabs(100. * (prev_instance.mean - runner.get_mean()) / prev_instance.mean); + auto pc = fabs(100. * (prev_instance.mean - runner.get_mean()) / prev_instance.mean); cmp = ", " + std::to_string(pc) + "% " + (mean > prev_instance.mean ? "slower" : "faster"); } cmp += " -- " + std::to_string(prev_instance.mean); diff --git a/tests/performance_tests/timings.cc b/tests/performance_tests/timings.cc index 6c0c16e5e..1bb00f3cb 100644 --- a/tests/performance_tests/timings.cc +++ b/tests/performance_tests/timings.cc @@ -33,7 +33,7 @@ bool TimingsDatabase::load() FILE *f = fopen(filename.c_str(), "r"); if (!f) { - MDEBUG("Failed to load timings file " << filename << ": " << strerror(errno)); + oxenlog::debug("Failed to load timings file {}: {}", filename, strerror(errno)); return false; } while (1) @@ -44,7 +44,7 @@ bool TimingsDatabase::load() char *tab = strchr(s, '\t'); if (!tab) { - MWARNING("Bad format: no tab found"); + oxenlog::warn("Bad format: no tab found"); continue; } const std::string name = std::string(s, tab - s); @@ -53,7 +53,7 @@ bool TimingsDatabase::load() if (fields_sv.size() != N_EXPECTED_FIELDS) { - MERROR("Bad format: wrong number of fields: got " << fields_sv.size() << " expected " << N_EXPECTED_FIELDS); + oxenlog::err("Bad format: wrong number of fields: got {} expected {}", fields_sv.size(), N_EXPECTED_FIELDS); continue; } // We need C strings for the below, so make copies @@ -91,7 +91,7 @@ bool TimingsDatabase::save() FILE *f = fopen(filename.c_str(), "w"); if (!f) { - MERROR("Failed to write to file " << filename << ": " << strerror(errno)); + MERROR("Failed to write to file {}: {}", filename, strerror(errno)); return false; } for (const auto &i: instances) diff --git a/tests/performance_tests/timings.h b/tests/performance_tests/timings.h index 490262cd4..1f4d72b5b 100644 --- a/tests/performance_tests/timings.h +++ b/tests/performance_tests/timings.h @@ -12,8 +12,8 @@ public: { time_t t; size_t npoints; - double min, max, mean, median, stddev, npskew; - std::vector deciles; + std::chrono::duration min, max, mean, median, stddev, npskew; + std::vector> deciles; }; public: diff --git a/tests/trezor/daemon.cpp b/tests/trezor/daemon.cpp index e9050df37..4ec452554 100644 --- a/tests/trezor/daemon.cpp +++ b/tests/trezor/daemon.cpp @@ -110,7 +110,7 @@ mock_daemon::~mock_daemon() } catch (...) { - MERROR("Failed to stop"); + oxen::log::error(logcat, "Failed to stop"); } } @@ -149,7 +149,7 @@ void mock_daemon::deinit() } catch (...) { - MERROR("Failed to deinitialize RPC server..."); + oxen::log::error(logcat, "Failed to deinitialize RPC server..."); } if (m_start_p2p) @@ -160,7 +160,7 @@ void mock_daemon::deinit() } catch (...) { - MERROR("Failed to deinitialize p2p..."); + oxen::log::error(logcat, "Failed to deinitialize p2p..."); } } @@ -171,7 +171,7 @@ void mock_daemon::deinit() } catch (...) { - MERROR("Failed to stop cryptonote protocol!"); + oxen::log::error(logcat, "Failed to stop cryptonote protocol!"); } m_deinitalized = true; @@ -198,7 +198,7 @@ void mock_daemon::try_init_and_run(std::optional initial_port) { set_ports(m_vm, initial_port.get()); load_params(m_vm); - MDEBUG("Ports changed, RPC: " << rpc_addr()); + oxen::log::debug(logcat, "Ports changed, RPC: {}", rpc_addr()); } try @@ -208,7 +208,7 @@ void mock_daemon::try_init_and_run(std::optional initial_port) } catch(const std::exception &e) { - MWARNING("Could not init and start, attempt: " << attempts << ", reason: " << e.what()); + oxen::log::warning(logcat, "Could not init and start, attempt: {}, reason: {}", attempts, e.what()); if (attempts + 1 >= max_attempts) { throw; @@ -247,16 +247,16 @@ bool mock_daemon::run_main() { if (!zmq_server.init_rpc("127.0.0.1", m_zmq_bind_port)) { - MERROR("Failed to add TCP Socket (127.0.0.1:" << m_zmq_bind_port << ") to ZMQ RPC Server"); + oxen::log::error(logcat, "{}{}) to ZMQ RPC Server", , "Failed to add TCP Socket (127.0.0.1:", m_zmq_bind_port); stop_rpc(); return false; } - MINFO("Starting ZMQ server..."); + oxen::log::info(logcat, "Starting ZMQ server..."); zmq_server.run(); - MINFO("ZMQ server started at 127.0.0.1: " << m_zmq_bind_port); + oxen::log::info(logcat, "ZMQ server started at 127.0.0.1: {}", m_zmq_bind_port); } if (m_start_p2p) @@ -277,12 +277,12 @@ bool mock_daemon::run_main() } catch (std::exception const & ex) { - MFATAL("Uncaught exception! " << ex.what()); + oxen::log::error(logcat, "Uncaught exception! {}", ex.what()); return false; } catch (...) { - MFATAL("Uncaught exception!"); + oxen::log::error(logcat, "Uncaught exception!"); return false; } } @@ -312,7 +312,7 @@ void mock_daemon::mine_blocks(size_t num_blocks, const std::string &miner_addres bool blocks_mined = false; const uint64_t start_height = get_height(); const auto mining_timeout = std::chrono::seconds(120); - MDEBUG("Current height before mining: " << start_height); + oxen::log::debug(logcat, "Current height before mining: {}", start_height); start_mining(miner_address); auto mining_started = std::chrono::system_clock::now(); @@ -323,7 +323,7 @@ void mock_daemon::mine_blocks(size_t num_blocks, const std::string &miner_addres if (cur_height - start_height >= num_blocks) { - MDEBUG("Cur blocks: " << cur_height << " start: " << start_height); + oxen::log::debug(logcat, "Cur blocks: {} start: {}", cur_height, start_height); blocks_mined = true; break; } diff --git a/tests/trezor/trezor_tests.cpp b/tests/trezor/trezor_tests.cpp index 96721e59b..dc86a050e 100644 --- a/tests/trezor/trezor_tests.cpp +++ b/tests/trezor/trezor_tests.cpp @@ -72,7 +72,7 @@ namespace try { \ setup_chain(core, trezor_base, chain_path, fix_chain, vm_core); \ } catch (const std::exception& ex) { \ - MERROR("Chain setup failed for " << NAME); \ + oxen::log::error(logcat, "{}{}", , "Chain setup failed for ", NAME); \ throw; \ } \ } while(0) @@ -137,8 +137,8 @@ int main(int argc, char* argv[]) const uint8_t initial_hf = (uint8_t)get_env_long("TEST_MIN_HF", 12); const uint8_t max_hf = (uint8_t)get_env_long("TEST_MAX_HF", cryptonote::feature::CLSAG); auto sync_test = get_env_long("TEST_KI_SYNC", 1); - MINFO("Test versions " << LOKI_RELEASE_NAME << "' (v" << LOKI_VERSION_FULL << ")"); - MINFO("Testing hardforks [" << (int)initial_hf << ", " << (int)max_hf << "], sync-test: " << sync_test); + oxen::log::info(logcat, "Test versions {}' (v{})", LOKI_RELEASE_NAME, LOKI_VERSION_FULL); + oxen::log::info(logcat, "Testing hardforks [{}, {}], sync-test: {}", (int)initial_hf, (int)max_hf, sync_test); cryptonote::core core_obj(nullptr); cryptonote::core * const core = &core_obj; @@ -169,7 +169,7 @@ int main(int argc, char* argv[]) } } - MDEBUG("Transaction tests for HF " << (int)hf); + oxen::log::debug(logcat, "Transaction tests for HF {}", (int)hf); trezor_base.set_hard_fork(hf); TREZOR_SETUP_CHAIN(std::string("HF") + std::to_string((int)hf)); @@ -207,15 +207,15 @@ int main(int argc, char* argv[]) core->deinit(); el::Level level = (failed_tests.empty() ? el::Level::Info : el::Level::Error); - MLOG(level, "\nREPORT:"); - MLOG(level, " Test run: " << tests_count); - MLOG(level, " Failures: " << failed_tests.size()); - if (!failed_tests.empty()) + if (failed_tests.empty()) + oxen::log::info(logcat, "\nREPORT:\n Test run: {}\n Failures: {}", tests_count, failed_tests.size()); + else { - MLOG(level, "FAILED TESTS:"); + oxen::log::error(logcat, "\nREPORT:\n Test run: {}\n Failures: {}", tests_count, failed_tests.size()); + oxen::log::error(logcat, "Failed TESTS:"); for (auto& test_name : failed_tests) { - MLOG(level, " " << test_name); + oxen::log::error(logcat, " {}", test_name) } } @@ -233,7 +233,7 @@ static void rollback_chain(cryptonote::core * core, const cryptonote::block & he crypto::hash head_hash = get_block_hash(head), cur_hash{}; uint64_t height = get_block_height(head), cur_height=0; - MDEBUG("Rollbacking to " << height << " to hash " << head_hash); + oxen::log::debug(logcat, "Rollbacking to {} to hash {}", height, head_hash); do { core->get_blockchain_top(cur_height, cur_hash); @@ -264,7 +264,7 @@ static bool unserialize_chain_from_file(std::vector& events, g } catch(...) { - MWARNING("Chain deserialization failed"); + oxen::log::warning(logcat, "Chain deserialization failed"); return false; } CATCH_ENTRY_L0("unserialize_chain_from_file", false); @@ -287,7 +287,7 @@ static bool serialize_chain_to_file(std::vector& events, gen_t } catch(...) { - MWARNING("Chain deserialization failed"); + oxen::log::warning(logcat, "Chain deserialization failed"); return false; } return false; @@ -335,7 +335,7 @@ static void setup_chain(cryptonote::core * core, gen_trezor_base & trezor_base, { if (!unserialize_chain_from_file(events, trezor_base, chain_path)) { - MERROR("Failed to deserialize data from file: " << chain_path); + oxen::log::error(logcat, "{}{}", , "Failed to deserialize data from file: ", chain_path); CHECK_AND_ASSERT_THROW_MES(fix_chain, "Chain load error"); } else { @@ -357,7 +357,7 @@ static void setup_chain(cryptonote::core * core, gen_trezor_base & trezor_base, trezor_base.update_trackers(events); if (!serialize_chain_to_file(events, trezor_base, chain_path)) { - MERROR("Failed to serialize data to file: " << chain_path); + oxen::log::error(logcat, "{}{}", , "Failed to serialize data to file: ", chain_path); } } } @@ -367,11 +367,11 @@ static void setup_chain(cryptonote::core * core, gen_trezor_base & trezor_base, trezor_base.fix_hf(events); if (generated && init_core_replay_events(events, core, vm_core)) { - MGINFO_GREEN("#TEST-chain-init# Succeeded "); + oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "#TEST-chain-init# Succeeded "); } else { - MERROR("#TEST-chain-init# Failed "); + oxen::log::error(logcat, "#TEST-chain-init# Failed "); throw std::runtime_error("Chain init error"); } } @@ -433,7 +433,7 @@ bool get_short_payment_id(crypto::hash8 &payment_id8, const tools::wallet2::pend { if (ptx.dests.empty()) { - MWARNING("Encrypted payment id found, but no destinations public key, cannot decrypt"); + oxen::log::warning(logcat, "Encrypted payment id found, but no destinations public key, cannot decrypt"); return false; } return hwdev.decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key); @@ -455,7 +455,7 @@ static tools::wallet2::tx_construction_data get_construction_data_with_decrypted set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); THROW_WALLET_EXCEPTION_IF(!add_extra_nonce_to_tx_extra(construction_data.extra, extra_nonce), tools::error::wallet_internal_error, "Failed to add decrypted payment id to tx extra"); - MDEBUG("Decrypted payment ID: " << payment_id); + oxen::log::debug(logcat, "Decrypted payment ID: {}", payment_id); } return construction_data; } @@ -747,7 +747,7 @@ bool gen_trezor_base::generate(std::vector& events) } events.push_back(blk_0); - MDEBUG("Gen+1 block has time: " << blk_0.timestamp << " blid: " << get_block_hash(blk_0)); + oxen::log::debug(logcat, "Gen+1 block has time: {} blid: {}", blk_0.timestamp, get_block_hash(blk_0)); // Generate some spendable funds on the Miner account REWIND_BLOCKS_N(events, blk_3, blk_0, m_miner_account, 40); @@ -773,7 +773,7 @@ bool gen_trezor_base::generate(std::vector& events) #error FIXME broken ADD_HARDFORK(m_hard_forks, CUR_HF, hardfork_height); add_hforks(events, m_hard_forks); - MDEBUG("Hardfork height: " << hardfork_height << " at block: " << get_block_hash(blk_4r)); + oxen::log::debug(logcat, "Hardfork height: {} at block: {}", hardfork_height, get_block_hash(blk_4r)); // RCT transactions, wallets have to be used, wallet init m_wl_alice.reset(new tools::wallet2(m_network_type, 1, true)); @@ -847,7 +847,7 @@ bool gen_trezor_base::generate(std::vector& events) construct_tx_to_key(tx_1, m_wl_alice.get(), m_bob_account, MK_COINS(1), sources, TREZOR_TEST_FEE, true, rct::RangeProofType::PaddedBulletproof, 1); events.push_back(tx_1); MAKE_NEXT_BLOCK_TX1_HF(events, blk_6, blk_5r, m_miner_account, tx_1, CUR_HF); - MDEBUG("Post 1st tsx: " << (num_blocks(events) - 1) << " at block: " << get_block_hash(blk_6)); + oxen::log::debug(logcat, "Post 1st tsx: {} at block: {}", (num_blocks(events) - 1), get_block_hash(blk_6)); // Simple transaction check resx = rct::verRctSemanticsSimple(tx_1.rct_signatures); @@ -858,8 +858,8 @@ bool gen_trezor_base::generate(std::vector& events) REWIND_BLOCKS_N_HF(events, blk_6r, blk_6, m_miner_account, 10, CUR_HF); wallet_tools::process_transactions(m_wl_alice.get(), events, blk_6, m_bt); wallet_tools::process_transactions(m_wl_bob.get(), events, blk_6, m_bt); - MDEBUG("Available funds on Alice: " << get_available_funds(m_wl_alice.get())); - MDEBUG("Available funds on Bob: " << get_available_funds(m_wl_bob.get())); + oxen::log::debug(logcat, "Available funds on Alice: {}", get_available_funds(m_wl_alice.get())); + oxen::log::debug(logcat, "Available funds on Bob: {}", get_available_funds(m_wl_bob.get())); m_head = blk_6r; m_events = events; @@ -920,8 +920,8 @@ void gen_trezor_base::load(std::vector& events) wallet_tools::process_transactions(m_wl_alice.get(), events, m_head, m_bt); wallet_tools::process_transactions(m_wl_bob.get(), events, m_head, m_bt); - MDEBUG("Available funds on Alice: " << get_available_funds(m_wl_alice.get())); - MDEBUG("Available funds on Bob: " << get_available_funds(m_wl_bob.get())); + oxen::log::debug(logcat, "Available funds on Alice: {}", get_available_funds(m_wl_alice.get())); + oxen::log::debug(logcat, "Available funds on Bob: {}", get_available_funds(m_wl_bob.get())); } void gen_trezor_base::rewind_blocks(std::vector& events, size_t rewind_n, uint8_t hf) @@ -930,7 +930,7 @@ void gen_trezor_base::rewind_blocks(std::vector& events, size_ REWIND_BLOCKS_N_HF(events, blk_new, m_head, m_miner_account, rewind_n, hf); m_head = blk_new; m_events = events; - MDEBUG("Blocks rewound: " << rewind_n << ", #blocks: " << num_blocks(events) << ", #events: " << events.size()); + oxen::log::debug(logcat, "Blocks rewound: {}, #blocks: {}, #events: {}", rewind_n, num_blocks(events), events.size()); wallet_tools::process_transactions(m_wl_alice.get(), events, m_head, m_bt); wallet_tools::process_transactions(m_wl_bob.get(), events, m_head, m_bt); @@ -951,7 +951,7 @@ void gen_trezor_base::fix_hf(std::vector& events) #error FIXME broken ADD_HARDFORK(m_hard_forks, hf_to_add, hardfork_height); add_top_hfork(events, m_hard_forks); - MDEBUG("Hardfork added at height: " << hardfork_height << ", from " << (int)current_hf << " to " << (int)hf_to_add); + oxen::log::debug(logcat, "Hardfork added at height: {}, from {} to {}", hardfork_height, (int)current_hf, (int)hf_to_add); rewind_blocks(events, 10, hf_to_add); } } @@ -1001,7 +1001,7 @@ void gen_trezor_base::add_transactions_to_events( } MAKE_NEXT_BLOCK_TX_LIST_HF(events, blk_new, m_head, m_miner_account, tx_list, tx_hf); - MDEBUG("New tsx: " << (num_blocks(events) - 1) << " at block: " << get_block_hash(blk_new)); + oxen::log::debug(logcat, "New tsx: {} at block: {}", (num_blocks(events) - 1), get_block_hash(blk_new)); m_head = blk_new; } @@ -1033,7 +1033,7 @@ void gen_trezor_base::test_trezor_tx(std::vector& events, std: aux_data.hard_fork = m_top_hard_fork; dev_cold->tx_sign(&wallet_shim, txs, exported_txs, aux_data); - MDEBUG("Signed tx data from hw: " << exported_txs.ptx.size() << " transactions, hf: " << (int)m_top_hard_fork << ", bpv: " << m_rct_config.bp_version); + oxen::log::debug(logcat, "Signed tx data from hw: {} transactions, hf: {}, bpv: {}", exported_txs.ptx.size(), (int)m_top_hard_fork, m_rct_config.bp_version); CHECK_AND_ASSERT_THROW_MES(exported_txs.ptx.size() == ptxs.size(), "Invalid transaction sizes"); for (size_t i = 0; i < exported_txs.ptx.size(); ++i){ @@ -1042,14 +1042,14 @@ void gen_trezor_base::test_trezor_tx(std::vector& events, std: expand_tsx(c_ptx.tx); // Simple TX tests, more complex are performed in the core. - MTRACE(cryptonote::obj_to_json_str(c_ptx.tx)); + oxen::log::trace(cryptonote::obj_to_json_str(c_ptx.tx)); bool resx = rct::verRctSemanticsSimple(c_ptx.tx.rct_signatures); bool resy = rct::verRctNonSemanticsSimple(c_ptx.tx.rct_signatures); CHECK_AND_ASSERT_THROW_MES(resx, "Trezor tx_1 semantics failed"); CHECK_AND_ASSERT_THROW_MES(resy, "Trezor tx_1 Nonsemantics failed"); tx_list.push_back(c_ptx.tx); - MDEBUG("Transaction: " << dump_data(c_ptx.tx)); + oxen::log::debug(logcat, "Transaction: {}", dump_data(c_ptx.tx)); } add_transactions_to_events(events, generator, tx_list); @@ -1190,7 +1190,7 @@ void gen_trezor_base::test_get_tx( if (!dev_cold->is_get_tx_key_supported()) { - MERROR("Get TX key is not supported by the connected Trezor"); + oxen::log::error(logcat, "Get TX key is not supported by the connected Trezor"); return; } @@ -1285,7 +1285,7 @@ void gen_trezor_base::set_hard_fork(uint8_t hf) test_trezor_tx(events, _dsts, _dsts_info, generator, vct_wallets(m_wl_alice.get(), m_wl_bob.get(), m_wl_eve.get())); \ return true -#define TREZOR_SKIP_IF_VERSION_LEQ(x) if (m_trezor->get_version() <= x) { MDEBUG("Test skipped"); return true; } +#define TREZOR_SKIP_IF_VERSION_LEQ(x) if (m_trezor->get_version() <= x) { oxen::log::debug(logcat, "Test skipped"); return true; } #define TREZOR_TEST_PAYMENT_ID "\xde\xad\xc0\xde\xde\xad\xc0\xde" tsx_builder * tsx_builder::sources(std::vector & sources, std::vector & selected_transfers) @@ -1593,7 +1593,7 @@ bool gen_trezor_live_refresh::generate(std::vector& events) CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); if (!dev_cold->is_live_refresh_supported()){ - MDEBUG("Trezor does not support live refresh"); + oxen::log::debug(logcat, "Trezor does not support live refresh"); return true; } @@ -1848,7 +1848,7 @@ wallet_api_tests::~wallet_api_tests() } catch(...) { - MERROR("Could not remove wallet directory"); + oxen::log::error(logcat, "Could not remove wallet directory"); } } @@ -1864,7 +1864,7 @@ bool wallet_api_tests::generate(std::vector& events) CHECK_AND_ASSERT_THROW_MES(w->init(daemon()->rpc_addr(), 0), "Wallet init fail"); CHECK_AND_ASSERT_THROW_MES(w->refresh(), "Refresh fail"); uint64_t balance = w->balance(0); - MDEBUG("Balance: " << balance); + oxen::log::debug(logcat, "Balance: {}", balance); CHECK_AND_ASSERT_THROW_MES(w->status() == Monero::PendingTransaction::Status_Ok, "Status nok, " << w->errorString()); auto addr = get_address(m_eve_account); diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 4f4dac570..1b8f4d496 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -105,6 +105,7 @@ target_link_libraries(unit_tests SQLiteCpp Boost::thread gtest + logging extra) set_property(TARGET unit_tests PROPERTY diff --git a/tests/unit_tests/blockchain_db.cpp b/tests/unit_tests/blockchain_db.cpp index f8e8ab547..55499f010 100644 --- a/tests/unit_tests/blockchain_db.cpp +++ b/tests/unit_tests/blockchain_db.cpp @@ -41,6 +41,7 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "common/fs.h" #include "common/hex.h" +#include "logging/oxen_logger.h" #include "random_path.h" @@ -49,7 +50,7 @@ using namespace cryptonote; #define ASSERT_HASH_EQ(a,b) ASSERT_EQ(tools::type_to_hex(a), tools::type_to_hex(b)) namespace { // anonymous namespace - + const std::vector t_blocks = { "0100d5adc49a053b8818b2b6023cd2d532c6774e164a8fcacd603651cb3ea0cb7f9340b28ec016b4bc4ca301aa0101ff6e08acbb2702eab03067870349139bee7eab2ca2e030a6bb73d4f68ab6a3b6ca937214054cdac0843d028bbe23b57ea9bae53f12da93bb57bf8a2e40598d9fccd10c2921576e987d93cd80b4891302468738e391f07c4f2b356f7957160968e0bfef6e907c3cee2d8c23cbf04b089680c6868f01025a0f41f063e195a966051e3a29e17130a9ce97d48f55285b9bb04bdd55a09ae78088aca3cf0202d0f26169290450fe17e08974789c3458910b4db18361cdc564f8f2d0bdd2cf568090cad2c60e02d6f3483ec45505cc3be841046c7a12bf953ac973939bc7b727e54258e1881d4d80e08d84ddcb0102dae6dfb16d3e28aaaf43e00170b90606b36f35f38f8a3dceb5ee18199dd8f17c80c0caf384a30202385d7e57a4daba4cdd9e550a92dcc188838386e7581f13f09de796cbed4716a42101c052492a077abf41996b50c1b2e67fd7288bcd8c55cdc657b4e22d0804371f6901beb76a82ea17400cd6d7f595f70e1667d2018ed8f5a78d1ce07484222618c3cd" diff --git a/tests/unit_tests/logging.cpp b/tests/unit_tests/logging.cpp index bee0b36a9..c67d951ef 100644 --- a/tests/unit_tests/logging.cpp +++ b/tests/unit_tests/logging.cpp @@ -31,6 +31,9 @@ #include "gtest/gtest.h" #include "common/file.h" #include "epee/misc_log_ex.h" +#include "logging/oxen_logger.h" +#include +#include #include "random_path.h" @@ -40,7 +43,19 @@ static void init() { fs::path p = random_tmp_file(); log_filename = p.string(); - mlog_configure(log_filename, false, 0); + + oxen::log::reset_level(oxen::log::Level::info); + try { + auto file_sink = std::make_shared(log_filename); + oxen::log::add_sink(std::move(file_sink)); + } catch (const spdlog::spdlog_ex& ex) { + oxen::log::error( + globallogcat, + "Failed to open {} for logging: {}. File logging disabled.", + log_filename, + ex.what()); + return; + } } static void cleanup() @@ -51,17 +66,9 @@ static void cleanup() #endif } -static size_t nlines(const std::string &str) -{ - size_t n = 0; - for (const char *ptr = str.c_str(); *ptr; ++ptr) - if (*ptr == '\n') - ++n; - return n; -} - static bool load_log_to_string(const std::string &filename, std::string &str) { + oxen::log::flush(); if (!tools::slurp_file(filename, str)) return false; for (const char *ptr = str.c_str(); *ptr; ++ptr) @@ -69,7 +76,7 @@ static bool load_log_to_string(const std::string &filename, std::string &str) if (*ptr == '\n') { std::string prefix = std::string(str.c_str(), ptr - str.c_str()); - if (prefix.find("New log categories:") != std::string::npos) + if (prefix.find("New log categories") != std::string::npos) { str = std::string(ptr + 1, strlen(ptr + 1)); break; @@ -81,25 +88,24 @@ static bool load_log_to_string(const std::string &filename, std::string &str) static void log() { - MFATAL("fatal"); - MERROR("error"); - MWARNING("warning"); - MINFO("info"); - MDEBUG("debug"); - MTRACE("trace"); + oxen::log::error(globallogcat, "fatal"); + oxen::log::error(globallogcat, "error"); + oxen::log::warning(globallogcat, "warning"); + oxen::log::info(globallogcat, "info"); + oxen::log::debug(globallogcat, "debug"); + oxen::log::trace(globallogcat, "trace"); - MCINFO("a.b.c.d", "a.b.c.d"); - MCINFO("a.b.c.e", "a.b.c.e"); - MCINFO("global", "global"); - MCINFO("x.y.z", "x.y.z"); - MCINFO("y.y.z", "y.y.z"); - MCINFO("x.y.x", "x.y.x"); + oxen::log::info(oxen::log::Cat("first"), "a.b.c.d"); + oxen::log::info(oxen::log::Cat("second"), "a.b.c.e"); + oxen::log::info(oxen::log::Cat("third"), "x.y.z"); + oxen::log::info(oxen::log::Cat("forth"), "y.y.z"); + oxen::log::info(oxen::log::Cat("fifth"), "x.y.x"); } TEST(logging, no_logs) { init(); - mlog_set_categories(""); + oxen::logging::process_categories_string("*:critical"); log(); std::string str; ASSERT_TRUE(load_log_to_string(log_filename, str)); @@ -124,7 +130,7 @@ TEST(logging, default) TEST(logging, all) { init(); - mlog_set_categories("*:TRACE"); + oxen::logging::process_categories_string("*:trace"); log(); std::string str; ASSERT_TRUE(load_log_to_string(log_filename, str)); @@ -136,42 +142,13 @@ TEST(logging, all) cleanup(); } -TEST(logging, glob_suffix) -{ - init(); - mlog_set_categories("x.y*:TRACE"); - log(); - std::string str; - ASSERT_TRUE(load_log_to_string(log_filename, str)); - ASSERT_TRUE(str.find("global") == std::string::npos); - ASSERT_TRUE(str.find("x.y.z") != std::string::npos); - ASSERT_TRUE(str.find("x.y.x") != std::string::npos); - ASSERT_TRUE(str.find("y.y.z") == std::string::npos); - cleanup(); -} - -TEST(logging, glob_prefix) -{ - init(); - mlog_set_categories("*y.z:TRACE"); - log(); - std::string str; - ASSERT_TRUE(load_log_to_string(log_filename, str)); - ASSERT_TRUE(str.find("global") == std::string::npos); - ASSERT_TRUE(str.find("x.y.z") != std::string::npos); - ASSERT_TRUE(str.find("x.y.x") == std::string::npos); - ASSERT_TRUE(str.find("y.y.z") != std::string::npos); - cleanup(); -} - TEST(logging, last_precedence) { init(); - mlog_set_categories("gobal:FATAL,glo*:DEBUG"); + oxen::logging::process_categories_string("*:warning,global:critical,global:debug"); log(); std::string str; ASSERT_TRUE(load_log_to_string(log_filename, str)); - ASSERT_TRUE(nlines(str) == 1); ASSERT_TRUE(str.find("global") != std::string::npos); ASSERT_TRUE(str.find("x.y.z") == std::string::npos); ASSERT_TRUE(str.find("x.y.x") == std::string::npos); diff --git a/tests/unit_tests/main.cpp b/tests/unit_tests/main.cpp index 179cddb49..3a20e3afe 100644 --- a/tests/unit_tests/main.cpp +++ b/tests/unit_tests/main.cpp @@ -55,7 +55,6 @@ int main(int argc, char** argv) tools::on_startup(); epee::string_tools::set_module_name_and_folder(argv[0]); - mlog_configure(mlog_get_default_log_path("unit_tests.log"), true); epee::debug::get_set_enable_assert(true, false); ::testing::InitGoogleTest(&argc, argv); @@ -77,11 +76,15 @@ int main(int argc, char** argv) return 1; unit_test::data_dir = command_line::get_arg(vm, arg_data_dir); - const int log_level = command_line::get_arg(vm, arg_log_level); - if (0 <= log_level && log_level <= 4) - { - mlog_set_log_level(log_level); + + oxen::log::Level log_level; + if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level))) { + log_level = *level; + } else { + throw std::runtime_error{"Incorrect log level"}; } + oxen::logging::init("unit_tests.log", log_level); + CATCH_ENTRY_L0("main", 1); diff --git a/tests/unit_tests/memwipe.cpp b/tests/unit_tests/memwipe.cpp index a1a0d0a17..62849f2c8 100644 --- a/tests/unit_tests/memwipe.cpp +++ b/tests/unit_tests/memwipe.cpp @@ -48,10 +48,10 @@ static void test(bool wipe) char *quux = (char*)malloc(4); // same size, just after free, so we're likely to get the same, depending on the allocator if ((intptr_t)quux == foop) { - MDEBUG(std::hex << std::setw(8) << std::setfill('0') << *(uint32_t*)quux); + //oxen::log::debug(logcat, "{}{}{}{}", std::hex, std::setw(8), std::setfill('0'), *(uint32_t*)quux); if (wipe) { ASSERT_TRUE(memcmp(quux, "bar", 3)); } } - else MWARNING("We did not get the same location, cannot check"); + //else oxen::log::warning(logcat, "We did not get the same location, cannot check"); free(quux); } diff --git a/tests/unit_tests/multiexp.cpp b/tests/unit_tests/multiexp.cpp index 0d93ae62d..3c22e2d2d 100644 --- a/tests/unit_tests/multiexp.cpp +++ b/tests/unit_tests/multiexp.cpp @@ -32,6 +32,7 @@ #include "ringct/rctOps.h" #include "ringct/multiexp.h" + namespace { const rct::key TESTPOW2SCALAR = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; diff --git a/tests/unit_tests/multisig.cpp b/tests/unit_tests/multisig.cpp index 4de1d862c..dede64fb5 100644 --- a/tests/unit_tests/multisig.cpp +++ b/tests/unit_tests/multisig.cpp @@ -81,7 +81,7 @@ static void make_wallet(unsigned int idx, tools::wallet2 &wallet) } catch (const std::exception &e) { - MFATAL("Error creating test wallet: " << e.what()); + oxen::log::error(globallogcat, "Error creating test wallet: {}", e.what()); ASSERT_TRUE(0); } } diff --git a/tests/unit_tests/output_selection.cpp b/tests/unit_tests/output_selection.cpp index 89a96d2f9..2e8864c6a 100644 --- a/tests/unit_tests/output_selection.cpp +++ b/tests/unit_tests/output_selection.cpp @@ -129,7 +129,7 @@ TEST(select_outputs, gamma) ++i; } double median = tools::median(std::move(ages)); - MDEBUG("median age: " << median / 86400. << " days"); + oxen::log::debug(globallogcat, "median age: {} days", median / 86400.); ASSERT_GE(median, 1.3 * 86400); ASSERT_LE(median, 1.4 * 86400); } @@ -171,8 +171,8 @@ TEST(select_outputs, density) } float selected_ratio = count_selected / (float)NPICKS; float chain_ratio = count_chain / (float)n_outs; - MDEBUG(count_selected << "/" << NPICKS << " outputs selected in blocks of density " << d << ", " << 100.0f * selected_ratio << "%"); - MDEBUG(count_chain << "/" << offsets.size() << " outputs in blocks of density " << d << ", " << 100.0f * chain_ratio << "%"); + oxen::log::debug(globallogcat, "{}/{} outputs selected in blocks of density {}, {}%", count_selected, NPICKS, d, 100.0f * selected_ratio); + oxen::log::debug(globallogcat, "{}/{} outputs in blocks of density {}, {}%", count_chain, offsets.size(), d, 100.0f * chain_ratio); ASSERT_LT(fabsf(selected_ratio - chain_ratio), 0.025f); } } @@ -216,6 +216,6 @@ TEST(select_outputs, same_distribution) avg_dev += dev; } avg_dev /= 100; - MDEBUG("avg_dev: " << avg_dev); + oxen::log::debug(globallogcat, "avg_dev: {}", avg_dev); ASSERT_LT(avg_dev, 0.02); } diff --git a/tests/unit_tests/service_nodes_swarm.cpp b/tests/unit_tests/service_nodes_swarm.cpp index 2a27af912..bf1821614 100644 --- a/tests/unit_tests/service_nodes_swarm.cpp +++ b/tests/unit_tests/service_nodes_swarm.cpp @@ -92,7 +92,7 @@ void registerInitialSnodes(swarm_snode_map_t& swarm_to_snodes, size_t reg_per_bl calc_swarm_changes(swarm_to_snodes, i /* seed */); unassigned_snodes.clear(); num_snodes += reg_per_block; - LOG_PRINT_L2("num_snodes: " << num_snodes); + oxen::log::debug(globallogcat, "num_snodes: {}", num_snodes); validateSwarmsNoDereg(swarm_to_snodes, num_snodes); } } diff --git a/tests/unit_tests/subaddress.cpp b/tests/unit_tests/subaddress.cpp index 433653b49..f8b01e677 100644 --- a/tests/unit_tests/subaddress.cpp +++ b/tests/unit_tests/subaddress.cpp @@ -46,7 +46,7 @@ class WalletSubaddress : public ::testing::Test } catch (const std::exception& e) { - LOG_ERROR("failed to generate wallet: " << e.what()); + oxen::log::error(globallogcat, "failed to generate wallet: {}", e.what()); throw; } From 469a6ebdb689e1264683702126e53942260ed37c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 14:07:09 -0300 Subject: [PATCH 02/32] Bump oxen-logging to stable release; fix imported fmt/spdlog targets The tagged 1.0.0 release includes a fix for the fmt::fmt/spdlog::spdlog targets not being transitively available. (It does require a cmake version bump to 3.13, though, to make it work). --- CMakeLists.txt | 2 +- README.md | 2 +- external/oxen-logging | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 01afd1238..9be0f5f59 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,7 @@ if(CCACHE_PROGRAM) endforeach() endif() -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.13...3.24) message(STATUS "CMake version ${CMAKE_VERSION}") # Has to be set before `project()`, and ignored on non-macos: diff --git a/README.md b/README.md index 278721325..6735a9785 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ library archives (`.a`). | Dep | Min. version | Vendored | Debian/Ubuntu pkg | Arch pkg | Fedora | Optional | Purpose | | ------------ | ------------- | -------- | ---------------------- | ------------ | ------------------- | -------- | ---------------- | | GCC | 8.1.0 | NO | `g++`[1] | `base-devel` | `gcc` | NO | | -| CMake | 3.10 | NO | `cmake` | `cmake` | `cmake` | NO | | +| CMake | 3.13 | NO | `cmake` | `cmake` | `cmake` | NO | | | pkg-config | any | NO | `pkg-config` | `base-devel` | `pkgconf` | NO | | | Boost | 1.65 | NO | `libboost-all-dev`[2] | `boost` | `boost-devel` | NO | C++ libraries | | libzmq | 4.3.0 | YES | `libzmq3-dev` | `zeromq` | `zeromq-devel` | NO | ZeroMQ library | diff --git a/external/oxen-logging b/external/oxen-logging index 98a8882c8..16e3c23d5 160000 --- a/external/oxen-logging +++ b/external/oxen-logging @@ -1 +1 @@ -Subproject commit 98a8882c81aa046fbadc0571fcea7bf92ed20154 +Subproject commit 16e3c23d5ebbde10da13719286d06f1c92e59037 From eb4c9ca52df322bd665c13f99b6651bbf510b3ef Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 16:01:16 -0300 Subject: [PATCH 03/32] Dep updates - oxenmq requires >= .13 for the fmt header - update oxen-logging with cmake build fix and text style support --- external/CMakeLists.txt | 2 +- external/oxen-logging | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 03740a801..60671626e 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -60,7 +60,7 @@ macro(system_or_submodule BIGNAME smallname pkgconf subdir) endmacro() system_or_submodule(OXENC oxenc liboxenc>=1.0.3 oxen-encoding) -system_or_submodule(OXENMQ oxenmq liboxenmq>=1.2.12 oxen-mq) +system_or_submodule(OXENMQ oxenmq liboxenmq>=1.2.13 oxen-mq) add_subdirectory(db_drivers) add_subdirectory(randomx EXCLUDE_FROM_ALL) diff --git a/external/oxen-logging b/external/oxen-logging index 16e3c23d5..f54003ea4 160000 --- a/external/oxen-logging +++ b/external/oxen-logging @@ -1 +1 @@ -Subproject commit 16e3c23d5ebbde10da13719286d06f1c92e59037 +Subproject commit f54003ea4d44388b66045009facc762747e7bfba From 980237a95b0e21b54d13d131a8bd5af97c30c42c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 16:28:50 -0300 Subject: [PATCH 04/32] Fix missing oxen logger include when no HIDAPI oxen_logger was getting included indirectly via something device_ledger.hpp includes, but that doesn't get included at all if HIDAPI headers weren't found. --- src/device/device.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/device/device.cpp b/src/device/device.cpp index c0a825d5f..40273e41a 100644 --- a/src/device/device.cpp +++ b/src/device/device.cpp @@ -29,6 +29,7 @@ #include "device.hpp" #include "device_default.hpp" +#include "logging/oxen_logger.h" #ifdef WITH_DEVICE_LEDGER #include "device_ledger.hpp" #endif From c9934b9f5fe410f6754190afa7443473df0c6c70 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 20:27:12 -0300 Subject: [PATCH 05/32] Change most oxen::log::whatever to log::whatever oxen::log::info(...), etc. are a bit too verbose; this simplifies them to just `log::info(...)`, etc. by aliasing the `oxen::log` namespace into most of the common namespaces we use in core. This result is usage that is shorter but also reads better: oxen::log::info(logcat, "blah: {}", 42); log::info(logcat, "blah: {}", 42); --- src/blockchain_db/blockchain_db.cpp | 12 +- src/blockchain_db/lmdb/db_lmdb.cpp | 489 +++++------ src/blockchain_db/locked_txn.h | 6 +- src/blockchain_db/sqlite/db_sqlite.cpp | 76 +- .../blockchain_ancestry.cpp | 78 +- .../blockchain_blackball.cpp | 96 +-- src/blockchain_utilities/blockchain_depth.cpp | 58 +- .../blockchain_export.cpp | 29 +- .../blockchain_import.cpp | 84 +- src/blockchain_utilities/blockchain_prune.cpp | 50 +- .../blockchain_prune_known_spent_data.cpp | 48 +- src/blockchain_utilities/blockchain_stats.cpp | 23 +- src/blockchain_utilities/blockchain_usage.cpp | 28 +- src/blockchain_utilities/blocksdat_file.cpp | 22 +- src/blockchain_utilities/bootstrap_file.cpp | 69 +- src/checkpoints/checkpoints.cpp | 18 +- src/common/apply_permutation.h | 4 +- src/common/command_line.h | 9 +- src/common/file.cpp | 14 +- src/common/notify.cpp | 2 +- src/common/scoped_message_writer.cpp | 8 +- src/common/signal_handler.h | 3 +- src/common/spawn.cpp | 22 +- src/common/threadpool.cpp | 3 +- src/common/util.cpp | 8 +- src/cryptonote_basic/account.cpp | 8 +- src/cryptonote_basic/cryptonote_basic.h | 2 +- .../cryptonote_basic_impl.cpp | 12 +- .../cryptonote_format_utils.cpp | 56 +- .../cryptonote_format_utils.h | 4 +- src/cryptonote_basic/miner.cpp | 38 +- src/cryptonote_core/blockchain.cpp | 652 +++++++-------- src/cryptonote_core/cryptonote_core.cpp | 186 ++--- src/cryptonote_core/cryptonote_tx_utils.cpp | 66 +- src/cryptonote_core/oxen_name_system.cpp | 67 +- src/cryptonote_core/pulse.cpp | 127 +-- src/cryptonote_core/service_node_list.cpp | 292 +++---- .../service_node_quorum_cop.cpp | 68 +- src/cryptonote_core/service_node_quorum_cop.h | 2 +- src/cryptonote_core/service_node_rules.cpp | 18 +- src/cryptonote_core/service_node_swarm.cpp | 30 +- src/cryptonote_core/service_node_voting.cpp | 70 +- src/cryptonote_core/tx_blink.cpp | 2 +- src/cryptonote_core/tx_pool.cpp | 158 ++-- src/cryptonote_core/tx_sanity_check.cpp | 12 +- src/cryptonote_protocol/block_queue.cpp | 28 +- .../cryptonote_protocol_handler.h | 4 +- .../cryptonote_protocol_handler.inl | 382 ++++----- src/cryptonote_protocol/levin_notify.cpp | 8 +- src/cryptonote_protocol/quorumnet.cpp | 155 ++-- src/daemon/command_parser_executor.cpp | 11 +- src/daemon/daemon.cpp | 65 +- src/daemon/main.cpp | 14 +- src/debug_utilities/cn_deserialize.cpp | 8 +- src/device/device.cpp | 6 +- src/device/device.hpp | 3 + src/device/device_ledger.cpp | 52 +- src/device/io_hid.cpp | 10 +- src/device/io_ledger_tcp.cpp | 7 +- src/device/log.cpp | 8 +- src/device_trezor/device_trezor.cpp | 32 +- src/device_trezor/device_trezor_base.cpp | 56 +- src/device_trezor/trezor/transport.cpp | 46 +- src/gen_multisig/gen_multisig.cpp | 3 +- src/logging/oxen_logger.cpp | 58 +- src/logging/oxen_logger.h | 18 +- src/mnemonics/electrum-words.cpp | 32 +- src/mnemonics/language_base.h | 9 +- src/multisig/multisig.cpp | 3 - src/p2p/net_node.cpp | 33 +- src/p2p/net_node.h | 4 +- src/p2p/net_node.inl | 230 +++--- src/p2p/net_peerlist.cpp | 2 +- src/ringct/bulletproofs.cc | 2 +- src/ringct/multiexp.cc | 2 +- src/ringct/rctOps.cpp | 4 +- src/ringct/rctSigs.cpp | 43 +- src/ringct/rctTypes.cpp | 2 +- src/rpc/core_rpc_server.cpp | 58 +- src/rpc/http_client.cpp | 8 +- src/rpc/http_server.cpp | 50 +- src/rpc/lmq_server.cpp | 28 +- src/simplewallet/simplewallet.cpp | 111 +-- src/simplewallet/simplewallet.h | 4 +- src/sqlitedb/database.cpp | 10 +- src/sqlitedb/database.hpp | 7 +- src/wallet/api/address_book.cpp | 4 +- src/wallet/api/pending_transaction.cpp | 6 +- src/wallet/api/stake_unlock_result.cpp | 2 +- src/wallet/api/stake_unlock_result.h | 6 +- src/wallet/api/subaddress.cpp | 4 +- src/wallet/api/subaddress_account.cpp | 2 +- src/wallet/api/transaction_history.cpp | 2 +- src/wallet/api/unsigned_transaction.cpp | 4 +- src/wallet/api/utils.cpp | 3 +- src/wallet/api/wallet.cpp | 134 ++- src/wallet/api/wallet.h | 4 + src/wallet/api/wallet_manager.cpp | 6 +- src/wallet/message_store.cpp | 17 +- src/wallet/message_store.h | 2 - src/wallet/message_transporter.cpp | 9 +- src/wallet/node_rpc_proxy.cpp | 4 +- src/wallet/node_rpc_proxy.h | 4 +- src/wallet/ringdb.cpp | 55 +- src/wallet/wallet2.cpp | 768 +++++++++--------- src/wallet/wallet2.h | 4 +- src/wallet/wallet_args.cpp | 19 +- src/wallet/wallet_rpc_server.cpp | 134 +-- src/wallet/wallet_rpc_server.h | 2 - src/wallet/wallet_rpc_server_commands_defs.h | 2 - src/wallet3/transaction_scanner.cpp | 5 +- 111 files changed, 2993 insertions(+), 2954 deletions(-) diff --git a/src/blockchain_db/blockchain_db.cpp b/src/blockchain_db/blockchain_db.cpp index 152485e31..179debe52 100644 --- a/src/blockchain_db/blockchain_db.cpp +++ b/src/blockchain_db/blockchain_db.cpp @@ -43,7 +43,7 @@ namespace cryptonote { - static auto logcat = oxen::log::Cat("blockchain.db"); + static auto logcat = log::Cat("blockchain.db"); const command_line::arg_descriptor arg_db_sync_mode = { "db-sync-mode" @@ -84,7 +84,7 @@ void BlockchainDB::add_transaction(const crypto::hash& blk_hash, const std::pair { // should only need to compute hash for miner transactions tx_hash = get_transaction_hash(tx); - oxen::log::trace(logcat, "null tx_hash_ptr - needed to compute: {}", tx_hash); + log::trace(logcat, "null tx_hash_ptr - needed to compute: {}", tx_hash); } else { @@ -118,7 +118,7 @@ void BlockchainDB::add_transaction(const crypto::hash& blk_hash, const std::pair } else { - oxen::log::info(logcat, "Unsupported input type, removing key images and aborting transaction addition"); + 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(tx_input)) @@ -329,7 +329,7 @@ void BlockchainDB::reset_stats() void BlockchainDB::show_stats() { - oxen::log::info(logcat, "\n*********************************\n \ + log::info(logcat, "\n*********************************\n \ num_calls: {}\n \ time_blk_hash: {}\n \ time_tx_exists: {}\n \ @@ -343,7 +343,7 @@ void BlockchainDB::show_stats() void BlockchainDB::fixup(cryptonote::network_type) { if (is_read_only()) { - oxen::log::info(logcat, "Database is opened read only - skipping fixup check"); + log::info(logcat, "Database is opened read only - skipping fixup check"); return; } @@ -391,7 +391,7 @@ uint64_t BlockchainDB::get_tx_block_height(const crypto::hash &h) const if (result == std::numeric_limits::max()) { std::string err = "tx_data_t with hash " + tools::type_to_hex(h) + " not found in db"; - oxen::log::info(logcat, "{}", err); + log::info(logcat, "{}", err); throw TX_DNE(std::move(err)); } return result; diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index 3ce362ce3..5e28a79f4 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -70,8 +70,9 @@ constexpr lmdb_version VERSION = tools::enum_top; namespace { + namespace log = oxen::log; - static auto logcat = oxen::log::Cat("blockchain.db.lmdb"); + static auto logcat = log::Cat("blockchain.db.lmdb"); // This MUST be identical to output_data_t, without the extra rct data at the end struct pre_rct_output_data_t @@ -85,14 +86,14 @@ static_assert(sizeof(pre_rct_output_data_t) == sizeof(crypto::public_key) + 2*si template void throw0(const T &e) { - oxen::log::warning(logcat, e.what()); + log::warning(logcat, e.what()); throw e; } template void throw1(const T &e) { - oxen::log::info(logcat, e.what()); + log::info(logcat, e.what()); throw e; } @@ -320,7 +321,7 @@ public: else if constexpr (sizeof...(More)) load_variant(); else { - oxen::log::warning(logcat, "Invalid stored type size in iterable_db: stored size ({}) matched none of {}", v.mv_size, tools::type_name()); + log::warning(logcat, "Invalid stored type size in iterable_db: stored size ({}) matched none of {}", v.mv_size, tools::type_name()); var::get<0>(element.second) = nullptr; } } @@ -489,7 +490,7 @@ mdb_txn_safe::~mdb_txn_safe() { if (!m_check) return; - oxen::log::trace(logcat, "mdb_txn_safe: destructor"); + log::trace(logcat, "mdb_txn_safe: destructor"); if (m_tinfo != nullptr) { mdb_txn_reset(m_tinfo->m_ti_rtxn); @@ -498,7 +499,7 @@ mdb_txn_safe::~mdb_txn_safe() { if (m_batch_txn) // this is a batch txn and should have been handled before this point for safety { - oxen::log::warning(logcat, "WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()"); + log::warning(logcat, "WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()"); } else { @@ -508,7 +509,7 @@ mdb_txn_safe::~mdb_txn_safe() // // NOTE: not sure if this is ever reached for a non-batch write // transaction, but it's probably not ideal if it did. - oxen::log::trace(logcat, "mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()"); + log::trace(logcat, "mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()"); } mdb_txn_abort(m_txn); } @@ -538,7 +539,7 @@ void mdb_txn_safe::commit(std::string message) void mdb_txn_safe::abort() { - oxen::log::trace(logcat, "mdb_txn_safe: abort()"); + log::trace(logcat, "mdb_txn_safe: abort()"); if(m_txn != nullptr) { mdb_txn_abort(m_txn); @@ -546,7 +547,7 @@ void mdb_txn_safe::abort() } else { - oxen::log::warning(logcat, "WARNING: mdb_txn_safe: abort() called, but m_txn is NULL"); + log::warning(logcat, "WARNING: mdb_txn_safe: abort() called, but m_txn is NULL"); } } @@ -574,7 +575,7 @@ void lmdb_resized(MDB_env *env) { mdb_txn_safe::prevent_new_txns(); - oxen::log::info(logcat, "LMDB map resize detected."); + log::info(logcat, "LMDB map resize detected."); MDB_envinfo mei; @@ -590,7 +591,7 @@ void lmdb_resized(MDB_env *env) mdb_env_info(env, &mei); uint64_t new_mapsize = mei.me_mapsize; - oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", old / (1024 * 1024), new_mapsize / (1024 * 1024)); + log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", old / (1024 * 1024), new_mapsize / (1024 * 1024)); mdb_txn_safe::allow_new_txns(); } @@ -623,7 +624,7 @@ void BlockchainLMDB::check_open() const void BlockchainLMDB::do_resize(uint64_t increase_size) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); std::lock_guard lock{*this}; const uint64_t add_size = 1LL << 30; @@ -633,14 +634,14 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) auto si = fs::space(m_folder); if(si.available < add_size) { - oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available, {} MB needed", (si.available >> 20L), (add_size >> 20L)); + log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available, {} MB needed", (si.available >> 20L), (add_size >> 20L)); return; } } catch(...) { // print something but proceed. - oxen::log::warning(logcat, "Unable to query free disk space."); + log::warning(logcat, "Unable to query free disk space."); } MDB_envinfo mei; @@ -682,7 +683,7 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) if (result) throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str())); - oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); + log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); mdb_txn_safe::allow_new_txns(); } @@ -690,7 +691,7 @@ void BlockchainLMDB::do_resize(uint64_t increase_size) // threshold_size is used for batch transactions bool BlockchainLMDB::need_resize(uint64_t threshold_size) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); #if defined(ENABLE_AUTO_RESIZE) MDB_envinfo mei; @@ -706,18 +707,18 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const // additional size needed. uint64_t size_used = mst.ms_psize * mei.me_last_pgno; - oxen::log::debug(logcat, "DB map size: {}", mei.me_mapsize); - oxen::log::debug(logcat, "Space used: {}", size_used); - oxen::log::debug(logcat, "Space remaining: {}", mei.me_mapsize - size_used); - oxen::log::debug(logcat, "Size threshold: {}", threshold_size); + log::debug(logcat, "DB map size: {}", mei.me_mapsize); + log::debug(logcat, "Space used: {}", size_used); + log::debug(logcat, "Space remaining: {}", mei.me_mapsize - size_used); + log::debug(logcat, "Size threshold: {}", threshold_size); float resize_percent = RESIZE_PERCENT; - oxen::log::debug(logcat, "Percent used: {} Percent threshold: {}", 100.*size_used/mei.me_mapsize, 100.*resize_percent); + log::debug(logcat, "Percent used: {} Percent threshold: {}", 100.*size_used/mei.me_mapsize, 100.*resize_percent); if (threshold_size > 0) { if (mei.me_mapsize - size_used < threshold_size) { - oxen::log::info(logcat, "Threshold met (size-based)"); + log::info(logcat, "Threshold met (size-based)"); return true; } else @@ -726,7 +727,7 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const if ((double)size_used / mei.me_mapsize > resize_percent) { - oxen::log::info(logcat, "Threshold met (percent-based)"); + log::info(logcat, "Threshold met (percent-based)"); return true; } return false; @@ -737,15 +738,15 @@ bool BlockchainLMDB::need_resize(uint64_t threshold_size) const void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint64_t batch_bytes) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); - oxen::log::trace(logcat, "[{}] checking DB size", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "[{}] checking DB size", __func__); const uint64_t min_increase_size = 512 * (1 << 20); uint64_t threshold_size = 0; uint64_t increase_size = 0; if (batch_num_blocks > 0) { threshold_size = get_estimated_batch_size(batch_num_blocks, batch_bytes); - oxen::log::debug(logcat, "calculated batch size: {}", threshold_size); + log::debug(logcat, "calculated batch size: {}", threshold_size); // The increased DB size could be a multiple of threshold_size, a fixed // size increase (> threshold_size), or other variations. @@ -754,7 +755,7 @@ void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint6 // minimum size increase is used to avoid frequent resizes when the batch // size is set to a very small numbers of blocks. increase_size = (threshold_size > min_increase_size) ? threshold_size : min_increase_size; - oxen::log::debug(logcat, "increase size: {}", increase_size); + log::debug(logcat, "increase size: {}", increase_size); } // if threshold_size is 0 (i.e. number of blocks for batch not passed in), it @@ -762,14 +763,14 @@ void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint6 // size-based check if (need_resize(threshold_size)) { - oxen::log::info(logcat, "[batch] DB resize needed"); + log::info(logcat, "[batch] DB resize needed"); do_resize(increase_size); } } uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uint64_t batch_bytes) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t threshold_size = 0; // batch size estimate * batch safety factor = final size estimate @@ -792,7 +793,7 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin block_start = block_stop - num_prev_blocks + 1; uint32_t num_blocks_used = 0; uint64_t total_block_size = 0; - oxen::log::debug(logcat, "[{}] m_height: {} block_start: {} block_stop: {}", __func__, m_height, block_start, block_stop); + log::debug(logcat, "[{}] m_height: {} block_start: {} block_stop: {}", __func__, m_height, block_start, block_stop); size_t avg_block_size = 0; if (batch_bytes) { @@ -801,12 +802,12 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin } if (m_height == 0) { - oxen::log::debug(logcat, "No existing blocks to check for average block size"); + log::debug(logcat, "No existing blocks to check for average block size"); } else if (m_cum_count >= num_prev_blocks) { avg_block_size = m_cum_size / m_cum_count; - oxen::log::debug(logcat, "average block size across recent {} blocks: {}", m_cum_count, avg_block_size); + log::debug(logcat, "average block size across recent {} blocks: {}", m_cum_count, avg_block_size); m_cum_size = 0; m_cum_count = 0; } @@ -828,12 +829,12 @@ uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uin } if (my_rtxn) block_rtxn_stop(); avg_block_size = total_block_size / (num_blocks_used ? num_blocks_used : 1); - oxen::log::debug(logcat, "average block size across recent {} blocks: {}", num_blocks_used, avg_block_size); + log::debug(logcat, "average block size across recent {} blocks: {}", num_blocks_used, avg_block_size); } estim: if (avg_block_size < min_block_size) avg_block_size = min_block_size; - oxen::log::debug(logcat, "estimated average block size for batch: {}", avg_block_size); + log::debug(logcat, "estimated average block size for batch: {}", avg_block_size); // bigger safety margin on smaller block sizes if (batch_fudge_factor < 5000.0) @@ -845,7 +846,7 @@ estim: void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated, uint64_t num_rct_outs, const crypto::hash& blk_hash) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -862,8 +863,8 @@ void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t l int result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &parent_key, MDB_GET_BOTH); if (result) { - oxen::log::trace(logcat, "m_height: {}", m_height); - oxen::log::trace(logcat, "parent_key: {}", blk.prev_id); + log::trace(logcat, "m_height: {}", m_height); + log::trace(logcat, "parent_key: {}", blk.prev_id); throw0(DB_ERROR(lmdb_error("Failed to get top block hash to check for new block's parent: ", result).c_str())); } blk_height *prev = (blk_height *)parent_key.mv_data; @@ -923,7 +924,7 @@ void BlockchainLMDB::remove_block() { int result; - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -958,7 +959,7 @@ void BlockchainLMDB::remove_block() uint64_t BlockchainLMDB::add_transaction_data(const crypto::hash& blk_hash, const std::pair& txp, const crypto::hash& tx_hash, const crypto::hash& tx_prunable_hash) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -1049,7 +1050,7 @@ void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const { int result; - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1106,7 +1107,7 @@ void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const result = mdb_cursor_get(m_cur_tx_outputs, &val_tx_id, NULL, MDB_SET); if (result == MDB_NOTFOUND) - oxen::log::info(logcat, "tx has no outputs to remove: {}", tx_hash); + log::info(logcat, "tx has no outputs to remove: {}", tx_hash); else if (result) throw1(DB_ERROR(lmdb_error("Failed to locate tx outputs for removal: ", result).c_str())); if (!result) @@ -1127,7 +1128,7 @@ uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash, const uint64_t unlock_time, const rct::key *commitment) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; uint64_t m_height = height(); @@ -1190,7 +1191,7 @@ uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash, void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, const std::vector& amount_output_indices) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(tx_outputs) @@ -1203,7 +1204,7 @@ void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, MDB_val v; v.mv_data = num_outputs ? (void *)amount_output_indices.data() : (void*)""; v.mv_size = sizeof(uint64_t) * num_outputs; - // oxen::log::info(logcat, "tx_outputs[tx_hash] size: {}", v.mv_size); + // log::info(logcat, "tx_outputs[tx_hash] size: {}", v.mv_size); result = mdb_cursor_put(m_cur_tx_outputs, &k_tx_id, &v, MDB_APPEND); if (result) @@ -1212,7 +1213,7 @@ void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id, void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& tx) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); std::vector> amount_output_indices_set = get_tx_amount_output_indices(tx_id, 1); const std::vector &amount_output_indices = amount_output_indices_set.front(); @@ -1220,7 +1221,7 @@ void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& if (amount_output_indices.empty()) { if (tx.vout.empty()) - oxen::log::debug(logcat, "tx has no outputs, so no output indices"); + log::debug(logcat, "tx has no outputs, so no output indices"); else throw0(DB_ERROR("tx has outputs, but no output indices found")); } @@ -1235,7 +1236,7 @@ void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_index) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(output_amounts); @@ -1273,13 +1274,13 @@ void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_in void BlockchainLMDB::prune_outputs(uint64_t amount) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(output_amounts); CURSOR(output_txs); - oxen::log::info(logcat, "Pruning outputs for amount {}", amount); + log::info(logcat, "Pruning outputs for amount {}", amount); MDB_val v; MDB_val_set(k, amount); @@ -1292,14 +1293,14 @@ void BlockchainLMDB::prune_outputs(uint64_t amount) // gather output ids mdb_size_t num_elems; mdb_cursor_count(m_cur_output_amounts, &num_elems); - oxen::log::info(logcat, "{} outputs found", num_elems); + log::info(logcat, "{} outputs found", num_elems); std::vector output_ids; output_ids.reserve(num_elems); while (1) { const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data; output_ids.push_back(okp->output_id); - oxen::log::debug(logcat, "output id {}", okp->output_id); + log::debug(logcat, "output id {}", okp->output_id); result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_NEXT_DUP); if (result == MDB_NOTFOUND) break; @@ -1327,7 +1328,7 @@ void BlockchainLMDB::prune_outputs(uint64_t amount) void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1344,7 +1345,7 @@ void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image) void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1364,7 +1365,7 @@ void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image) BlockchainLMDB::~BlockchainLMDB() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); // batch transaction shouldn't be active at this point. If it is, consider it aborted. if (m_batch_active) @@ -1378,7 +1379,7 @@ BlockchainLMDB::~BlockchainLMDB() BlockchainLMDB::BlockchainLMDB(bool batch_transactions): BlockchainDB() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); // initialize folder to something "safe" just in case // someone accidentally misuses this class... m_folder = "thishsouldnotexistbecauseitisgibberish"; @@ -1398,7 +1399,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net int result; int mdb_flags = MDB_NORDAHEAD; - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (m_open) throw0(DB_OPEN_FAILURE("Attempted to open db, but it's already open")); @@ -1419,8 +1420,8 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net if (fs::exists(old_files / BLOCKCHAINDATA_FILENAME) || fs::exists(old_files / BLOCKCHAINDATA_LOCK_FILENAME)) { - oxen::log::warning(logcat, "Found existing LMDB files in {}", old_files.u8string()); - oxen::log::warning(logcat, "Move {} and/or {} to {}, or delete them, and then restart", BLOCKCHAINDATA_FILENAME, BLOCKCHAINDATA_LOCK_FILENAME, filename); + log::warning(logcat, "Found existing LMDB files in {}", old_files.u8string()); + log::warning(logcat, "Move {} and/or {} to {}, or delete them, and then restart", BLOCKCHAINDATA_FILENAME, BLOCKCHAINDATA_LOCK_FILENAME, filename); throw DB_ERROR("Database could not be opened"); } @@ -1428,7 +1429,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net #ifdef __OpenBSD__ if ((mdb_flags & MDB_WRITEMAP) == 0) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Running on OpenBSD: forcing WRITEMAP")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Running on OpenBSD: forcing WRITEMAP")); mdb_flags |= MDB_WRITEMAP; } #endif @@ -1469,12 +1470,12 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net throw0(DB_ERROR(lmdb_error("Failed to set max memory map size: ", result).c_str())); mdb_env_info(m_env, &mei); cur_mapsize = (uint64_t)mei.me_mapsize; - oxen::log::info(logcat, "LMDB memory map size: {}", cur_mapsize); + log::info(logcat, "LMDB memory map size: {}", cur_mapsize); } if (need_resize()) { - oxen::log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); + log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); do_resize(); } @@ -1560,7 +1561,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net MDB_stat db_stats; if ((result = mdb_stat(txn, m_blocks, &db_stats))) throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); - oxen::log::debug(logcat, "Setting m_height to: {}", db_stats.ms_entries); + log::debug(logcat, "Setting m_height to: {}", db_stats.ms_entries); uint64_t m_height = db_stats.ms_entries; MDB_val_str(k, "version"); @@ -1574,17 +1575,17 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net bool failed = false; if (db_version > static_cast(VERSION)) { - oxen::log::warning(logcat, "Existing lmdb database was made by a later version ({}). We don't know how it will change yet.", db_version); - oxen::log::error(logcat, "Existing lmdb database is incompatible with this version."); - oxen::log::error(logcat, "Please delete the existing database and resync."); + log::warning(logcat, "Existing lmdb database was made by a later version ({}). We don't know how it will change yet.", db_version); + log::error(logcat, "Existing lmdb database is incompatible with this version."); + log::error(logcat, "Please delete the existing database and resync."); failed = true; } else if (db_version < static_cast(VERSION)) { if (mdb_flags & MDB_RDONLY) { - oxen::log::error(logcat, "Existing lmdb database needs to be converted, which cannot be done on a read-only database."); - oxen::log::error(logcat, "Please run oxend once to convert the database."); + log::error(logcat, "Existing lmdb database needs to be converted, which cannot be done on a read-only database."); + log::error(logcat, "Please run oxend once to convert the database."); failed = true; } else @@ -1618,7 +1619,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net txn.abort(); mdb_env_close(m_env); m_open = false; - oxen::log::error(logcat, "Failed to write version to database."); + log::error(logcat, "Failed to write version to database."); return; } } @@ -1632,10 +1633,10 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net void BlockchainLMDB::close() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (m_batch_active) { - oxen::log::trace(logcat, "close() first calling batch_abort() due to active batch transaction"); + log::trace(logcat, "close() first calling batch_abort() due to active batch transaction"); batch_abort(); } this->sync(); @@ -1648,7 +1649,7 @@ void BlockchainLMDB::close() void BlockchainLMDB::sync() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); if (is_read_only()) @@ -1664,13 +1665,13 @@ void BlockchainLMDB::sync() void BlockchainLMDB::safesyncmode(const bool onoff) { - oxen::log::info(logcat, "switching safe mode {}", (onoff ? "on" : "off")); + log::info(logcat, "switching safe mode {}", (onoff ? "on" : "off")); mdb_env_set_flags(m_env, MDB_NOSYNC|MDB_MAPASYNC, !onoff); } void BlockchainLMDB::reset() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_safe txn; @@ -1726,7 +1727,7 @@ void BlockchainLMDB::reset() std::vector BlockchainLMDB::get_filenames() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); std::vector paths; paths.push_back(m_folder / BLOCKCHAINDATA_FILENAME); paths.push_back(m_folder / BLOCKCHAINDATA_LOCK_FILENAME); @@ -1742,7 +1743,7 @@ bool BlockchainLMDB::remove_data_file(const fs::path& folder) const } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to remove {}: {}", filename, e.what()); + log::error(logcat, "Failed to remove {}: {}", filename, e.what()); return false; } return true; @@ -1750,26 +1751,26 @@ bool BlockchainLMDB::remove_data_file(const fs::path& folder) const std::string BlockchainLMDB::get_db_name() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); return "lmdb"s; } void BlockchainLMDB::lock() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); m_synchronization_lock.lock(); } bool BlockchainLMDB::try_lock() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); return m_synchronization_lock.try_lock(); } void BlockchainLMDB::unlock() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); m_synchronization_lock.unlock(); } @@ -1823,7 +1824,7 @@ void BlockchainLMDB::unlock() void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const std::string &blob, const txpool_tx_meta_t &meta) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1849,7 +1850,7 @@ void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const std::string & void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1875,7 +1876,7 @@ void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_ uint64_t BlockchainLMDB::get_txpool_tx_count(bool include_unrelayed_txes) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); int result; @@ -1919,7 +1920,7 @@ uint64_t BlockchainLMDB::get_txpool_tx_count(bool include_unrelayed_txes) const bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -1934,7 +1935,7 @@ bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid) const void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -1964,7 +1965,7 @@ void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid) bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -1984,7 +1985,7 @@ bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta bool BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, std::string &bd) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2015,7 +2016,7 @@ std::string BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid) const uint32_t BlockchainLMDB::get_blockchain_pruning_seed() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2049,7 +2050,7 @@ enum { prune_mode_prune, prune_mode_update, prune_mode_check }; bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); const uint32_t log_stripes = tools::get_pruning_log_stripes(pruning_seed); if (log_stripes && log_stripes != PRUNING_LOG_STRIPES) throw0(DB_ERROR("Pruning seed not in range")); @@ -2083,7 +2084,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode != prune_mode_prune) { txn.abort(); - oxen::log::debug(logcat, "Pruning not enabled, nothing to do"); + log::debug(logcat, "Pruning not enabled, nothing to do"); return true; } if (pruning_seed == 0) @@ -2117,9 +2118,9 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) } if (mode == prune_mode_check) - oxen::log::info(logcat, "Checking blockchain pruning..."); + log::info(logcat, "Checking blockchain pruning..."); else - oxen::log::info(logcat, "Pruning blockchain..."); + log::info(logcat, "Pruning blockchain..."); MDB_cursor *c_txs_pruned, *c_txs_prunable, *c_txs_prunable_tip; result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned); @@ -2155,12 +2156,12 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) ++n_prunable_records; result = mdb_cursor_get(c_txs_prunable, &k, &v, MDB_SET); if (result == MDB_NOTFOUND) - oxen::log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); + log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); else if (result) throw0(DB_ERROR(lmdb_error("Failed to find transaction prunable data: ", result).c_str())); else { - oxen::log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); + log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); ++n_pruned_records; ++commit_counter; n_bytes += k.mv_size + v.mv_size; @@ -2175,7 +2176,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode != prune_mode_check && commit_counter >= 4096) { - oxen::log::debug(logcat, "Committing txn at checkpoint..."); + log::debug(logcat, "Committing txn at checkpoint..."); txn.commit(); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -2225,7 +2226,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (result && result != MDB_NOTFOUND) throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str())); if (result == MDB_NOTFOUND) - oxen::log::error(logcat, "Transaction not found in prunable tip table for height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); + log::error(logcat, "Transaction not found in prunable tip table for height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } else { @@ -2243,16 +2244,16 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (mode == prune_mode_check) { if (result != MDB_NOTFOUND) - oxen::log::error(logcat, "Prunable data found for pruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); + log::error(logcat, "Prunable data found for pruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } else { ++n_prunable_records; if (result == MDB_NOTFOUND) - oxen::log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); + log::warning(logcat, "Already pruned at height {}/{}", block_height, blockchain_height); else { - oxen::log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); + log::debug(logcat, "Pruning at height {}/{}", block_height, blockchain_height); ++n_pruned_records; n_bytes += kp.mv_size + v.mv_size; result = mdb_cursor_del(c_txs_prunable, 0); @@ -2271,13 +2272,13 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) if (result && result != MDB_NOTFOUND) throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str())); if (result == MDB_NOTFOUND) - oxen::log::error(logcat, "Prunable data not found for unpruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); + log::error(logcat, "Prunable data not found for unpruned height {}/{}, seed {}", block_height, blockchain_height, epee::string_tools::to_string_hex(pruning_seed)); } } if (mode != prune_mode_check && commit_counter >= 4096) { - oxen::log::debug(logcat, "Committing txn at checkpoint..."); + log::debug(logcat, "Committing txn at checkpoint..."); txn.commit(); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -2317,7 +2318,7 @@ bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed) txn.commit(); - oxen::log::info(logcat, "{} blockchain in {}: {} MB ({} MB) prunded in {} records ({}/{} {} byte pages), {}/{} pruned records", + log::info(logcat, "{} blockchain in {}: {} MB ({} MB) prunded in {} records ({}/{} {} byte pages), {}/{} pruned records", (mode == prune_mode_check ? "Checked" : "Pruned"), tools::friendly_duration(std::chrono::steady_clock::now() - t), (n_bytes/1024.0f/1024.0f), @@ -2348,7 +2349,7 @@ bool BlockchainLMDB::check_pruning() bool BlockchainLMDB::for_all_txpool_txes(std::function f, bool include_blob, bool include_unrelayed_txes) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2461,7 +2462,7 @@ static bool read_alt_block_data_from_mdb_val(MDB_val const v, alt_block_data_t * bool BlockchainLMDB::for_all_alt_blocks(std::function f, bool include_blob) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2503,7 +2504,7 @@ bool BlockchainLMDB::for_all_alt_blocks(std::function(height); return result; } std::string BlockchainLMDB::get_block_blob(const crypto::hash& h) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); return get_block_blob_from_height(get_block_height(h)); @@ -2597,7 +2598,7 @@ std::string BlockchainLMDB::get_block_blob(const crypto::hash& h) const uint64_t BlockchainLMDB::get_block_height(const crypto::hash& h) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2623,14 +2624,14 @@ block_header BlockchainLMDB::get_block_header_from_height(uint64_t height) const std::string BlockchainLMDB::get_block_blob_from_height(uint64_t height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); std::string result = get_and_convert_block_blob_from_height(height); return result; } uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2652,7 +2653,7 @@ uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const std::vector BlockchainLMDB::get_block_cumulative_rct_outputs(const std::vector &heights) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector res; int result; @@ -2713,7 +2714,7 @@ std::vector BlockchainLMDB::get_block_cumulative_rct_outputs(const std uint64_t BlockchainLMDB::get_top_block_timestamp() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -2728,7 +2729,7 @@ uint64_t BlockchainLMDB::get_top_block_timestamp() const size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2750,7 +2751,7 @@ size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const std::vector BlockchainLMDB::get_block_info_64bit_fields(uint64_t start_height, size_t count, uint64_t (*extract)(const mdb_block_info* bi_data)) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2802,7 +2803,7 @@ std::vector BlockchainLMDB::get_block_info_64bit_fields(uint64_t start uint64_t BlockchainLMDB::get_max_block_size() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2823,7 +2824,7 @@ uint64_t BlockchainLMDB::get_max_block_size() void BlockchainLMDB::add_max_block_size(uint64_t sz) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -2864,7 +2865,7 @@ std::vector BlockchainLMDB::get_long_term_block_weights(uint64_t start difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{} height: {}", __func__, height); + log::trace(logcat, "BlockchainLMDB::{} height: {}", __func__, height); check_open(); TXN_PREFIX_RDONLY(); @@ -2886,7 +2887,7 @@ difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); difficulty_type diff1 = 0; @@ -2903,7 +2904,7 @@ difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) con uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2925,7 +2926,7 @@ uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& heigh uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2947,7 +2948,7 @@ uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) cons crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -2969,7 +2970,7 @@ crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) std::vector BlockchainLMDB::get_blocks_range(const uint64_t& h1, const uint64_t& h2) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -2983,7 +2984,7 @@ std::vector BlockchainLMDB::get_blocks_range(const uint64_t& h1, const ui std::vector BlockchainLMDB::get_hashes_range(const uint64_t& h1, const uint64_t& h2) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -2997,7 +2998,7 @@ std::vector BlockchainLMDB::get_hashes_range(const uint64_t& h1, c crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); if (block_height) @@ -3012,7 +3013,7 @@ crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const block BlockchainLMDB::get_top_block() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -3027,7 +3028,7 @@ block BlockchainLMDB::get_top_block() const uint64_t BlockchainLMDB::height() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); int result; @@ -3041,7 +3042,7 @@ uint64_t BlockchainLMDB::height() const uint64_t BlockchainLMDB::num_outputs() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); int result; @@ -3063,7 +3064,7 @@ uint64_t BlockchainLMDB::num_outputs() const bool BlockchainLMDB::tx_exists(const crypto::hash& h) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3083,7 +3084,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h) const if (! tx_found) { - oxen::log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); + log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); return false; } @@ -3092,7 +3093,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h) const bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3111,7 +3112,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const bool ret = false; if (get_result == MDB_NOTFOUND) { - oxen::log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); + log::info(logcat, "transaction with hash {} not found in db", tools::type_to_hex(h)); } else if (get_result) throw0(DB_ERROR(lmdb_error("DB error attempting to fetch transaction from hash", get_result).c_str())); @@ -3123,7 +3124,7 @@ bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3143,7 +3144,7 @@ uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, std::string &bd) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3178,7 +3179,7 @@ bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, std::string &bd) const bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, std::string &bd) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3206,7 +3207,7 @@ bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, std::string &bd) bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t count, std::vector &bd) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); if (!count) @@ -3246,7 +3247,7 @@ bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t coun bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, std::string &bd) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3274,7 +3275,7 @@ bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, std::string &bd bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::hash &prunable_hash) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3302,7 +3303,7 @@ bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::h uint64_t BlockchainLMDB::get_tx_count() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3317,7 +3318,7 @@ uint64_t BlockchainLMDB::get_tx_count() const std::vector BlockchainLMDB::get_tx_list(const std::vector& hlist) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector v; @@ -3331,7 +3332,7 @@ std::vector BlockchainLMDB::get_tx_list(const std::vector BlockchainLMDB::get_tx_block_heights(const std::vector& hs) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); std::vector result; result.reserve(hs.size()); @@ -3355,7 +3356,7 @@ std::vector BlockchainLMDB::get_tx_block_heights(const std::vector offsets; std::vector indices; offsets.push_back(index); @@ -3445,7 +3446,7 @@ tx_out_index BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, con std::vector> BlockchainLMDB::get_tx_amount_output_indices(uint64_t tx_id, size_t n_txes) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); @@ -3462,7 +3463,7 @@ std::vector> BlockchainLMDB::get_tx_amount_output_indices( { int result = mdb_cursor_get(m_cur_tx_outputs, &k_tx_id, &v, op); if (result == MDB_NOTFOUND) - oxen::log::warning(logcat, "WARNING: Unexpected: tx has no amount indices stored in " + log::warning(logcat, "WARNING: Unexpected: tx has no amount indices stored in " "tx_outputs, but it should have an empty entry even if it's a tx without " "outputs"); else if (result) @@ -3487,7 +3488,7 @@ std::vector> BlockchainLMDB::get_tx_amount_output_indices( bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); bool ret; @@ -3503,7 +3504,7 @@ bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const bool BlockchainLMDB::for_all_key_images(std::function f) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3534,7 +3535,7 @@ bool BlockchainLMDB::for_all_key_images(std::function f) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3583,7 +3584,7 @@ bool BlockchainLMDB::for_blocks_range(const uint64_t& h1, const uint64_t& h2, st bool BlockchainLMDB::for_all_transactions(std::function f, bool pruned) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3645,7 +3646,7 @@ bool BlockchainLMDB::for_all_transactions(std::function f) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3678,7 +3679,7 @@ bool BlockchainLMDB::for_all_outputs(std::function &f) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -3700,7 +3701,7 @@ bool BlockchainLMDB::for_all_outputs(uint64_t amount, const std::functionm_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } - oxen::log::trace(logcat, "batch transaction: begin"); + log::trace(logcat, "batch transaction: begin"); return true; } void BlockchainLMDB::batch_commit() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3772,11 +3773,11 @@ void BlockchainLMDB::batch_commit() check_open(); - oxen::log::trace(logcat, "batch transaction: committing..."); + log::trace(logcat, "batch transaction: committing..."); auto time1 = std::chrono::steady_clock::now(); m_write_txn->commit(); time_commit1 += std::chrono::steady_clock::now() - time1; - oxen::log::trace(logcat, "batch transaction: committed"); + log::trace(logcat, "batch transaction: committed"); m_write_txn = nullptr; delete m_write_batch_txn; @@ -3796,7 +3797,7 @@ void BlockchainLMDB::cleanup_batch() void BlockchainLMDB::batch_stop() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3806,7 +3807,7 @@ void BlockchainLMDB::batch_stop() if (m_writer != boost::this_thread::get_id()) throw1(DB_ERROR("batch transaction owned by other thread")); check_open(); - oxen::log::trace(logcat, "batch transaction: committing..."); + log::trace(logcat, "batch transaction: committing..."); auto time1 = std::chrono::steady_clock::now(); try { @@ -3819,12 +3820,12 @@ void BlockchainLMDB::batch_stop() cleanup_batch(); throw; } - oxen::log::trace(logcat, "batch transaction: end"); + log::trace(logcat, "batch transaction: end"); } void BlockchainLMDB::batch_abort() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (! m_batch_transactions) throw0(DB_ERROR("batch transactions not enabled")); if (! m_batch_active) @@ -3842,18 +3843,18 @@ void BlockchainLMDB::batch_abort() m_write_batch_txn = nullptr; m_batch_active = false; memset(&m_wcursors, 0, sizeof(m_wcursors)); - oxen::log::trace(logcat, "batch transaction: aborted"); + log::trace(logcat, "batch transaction: aborted"); } void BlockchainLMDB::set_batch_transactions(bool batch_transactions) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if ((batch_transactions) && (m_batch_transactions)) { - oxen::log::info(logcat, "batch transaction mode already enabled, but asked to enable batch mode"); + log::info(logcat, "batch transaction mode already enabled, but asked to enable batch mode"); } m_batch_transactions = batch_transactions; - oxen::log::info(logcat, "batch transactions {}", (m_batch_transactions ? "enabled" : "disabled")); + log::info(logcat, "batch transactions {}", (m_batch_transactions ? "enabled" : "disabled")); } // return true if we started the txn, false if already started @@ -3890,13 +3891,13 @@ bool BlockchainLMDB::block_rtxn_start(MDB_txn **mtxn, mdb_txn_cursors **mcur) co *mcur = &tinfo->m_ti_rcursors; if (ret) - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); return ret; } void BlockchainLMDB::block_rtxn_stop() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); mdb_txn_reset(m_tinfo->m_ti_rtxn); memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } @@ -3910,7 +3911,7 @@ bool BlockchainLMDB::block_rtxn_start() const void BlockchainLMDB::block_wtxn_start() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); // Distinguish the exceptions here from exceptions that would be thrown while // using the txn and committing it. // @@ -3943,7 +3944,7 @@ void BlockchainLMDB::block_wtxn_start() void BlockchainLMDB::block_wtxn_stop() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (!m_write_txn) throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn when no such txn exists in ")+__FUNCTION__).c_str())); if (m_writer != boost::this_thread::get_id()) @@ -3964,7 +3965,7 @@ void BlockchainLMDB::block_wtxn_stop() void BlockchainLMDB::block_wtxn_abort() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); if (!m_write_txn) throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn when no such txn exists in ")+__FUNCTION__).c_str())); if (m_writer != boost::this_thread::get_id()) @@ -3980,7 +3981,7 @@ void BlockchainLMDB::block_wtxn_abort() void BlockchainLMDB::block_rtxn_abort() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); mdb_txn_reset(m_tinfo->m_ti_rtxn); memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags)); } @@ -3988,7 +3989,7 @@ void BlockchainLMDB::block_rtxn_abort() const uint64_t BlockchainLMDB::add_block(const std::pair& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated, const std::vector>& txs) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); uint64_t m_height = height(); @@ -3997,7 +3998,7 @@ uint64_t BlockchainLMDB::add_block(const std::pair& blk, siz // for batch mode, DB resize check is done at start of batch transaction if (! m_batch_active && need_resize()) { - oxen::log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); + log::warning(logcat, "LMDB memory map needs to be resized, doing that now."); do_resize(); } } @@ -4034,7 +4035,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check result.len = sizeof(header) + bytes_for_signatures; if (result.len > sizeof(result.data)) { - oxen::log::warning(logcat, "Unexpected pre-calculated maximum number of bytes: {}, is insufficient to store signatures requiring: {} bytes", sizeof(result.data), result.len); + log::warning(logcat, "Unexpected pre-calculated maximum number of bytes: {}, is insufficient to store signatures requiring: {} bytes", sizeof(result.data), result.len); assert(result.len <= sizeof(result.data)); return false; } @@ -4051,7 +4052,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check char const *end = result.data + sizeof(result.data); if (buffer_ptr > end) { - oxen::log::warning(logcat, "Unexpected memcpy bounds overflow on update_block_checkpoint"); + log::warning(logcat, "Unexpected memcpy bounds overflow on update_block_checkpoint"); assert(buffer_ptr <= end); return false; } @@ -4062,7 +4063,7 @@ static bool convert_checkpoint_into_buffer(checkpoint_t const &checkpoint, check void BlockchainLMDB::update_block_checkpoint(checkpoint_t const &checkpoint) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); checkpoint_mdb_buffer buffer = {}; convert_checkpoint_into_buffer(checkpoint, buffer); @@ -4082,7 +4083,7 @@ void BlockchainLMDB::update_block_checkpoint(checkpoint_t const &checkpoint) void BlockchainLMDB::remove_block_checkpoint(uint64_t height) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4143,14 +4144,14 @@ bool BlockchainLMDB::get_block_checkpoint_internal(uint64_t height, checkpoint_t bool BlockchainLMDB::get_block_checkpoint(uint64_t height, checkpoint_t &checkpoint) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); bool result = get_block_checkpoint_internal(height, checkpoint, MDB_SET_KEY); return result; } bool BlockchainLMDB::get_top_checkpoint(checkpoint_t &checkpoint) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); bool result = get_block_checkpoint_internal(0, checkpoint, MDB_LAST); return result; } @@ -4244,7 +4245,7 @@ std::vector BlockchainLMDB::get_checkpoints_range(uint64_t start, void BlockchainLMDB::pop_block(block& blk, std::vector& txs) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); block_wtxn_start(); @@ -4264,7 +4265,7 @@ void BlockchainLMDB::pop_block(block& blk, std::vector& txs) void BlockchainLMDB::get_output_tx_and_index_from_global(const std::vector &global_indices, std::vector &tx_out_indices) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); tx_out_indices.clear(); tx_out_indices.reserve(global_indices.size()); @@ -4292,7 +4293,7 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c if (amounts.size() != 1 && amounts.size() != offsets.size()) throw0(DB_ERROR("Invalid sizes of amounts and offets")); - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); auto db3 = std::chrono::steady_clock::now(); check_open(); outputs.clear(); @@ -4313,7 +4314,7 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c { if (allow_partial) { - oxen::log::debug(logcat, "Partial result: {}/{}", outputs.size(), offsets.size()); + log::debug(logcat, "Partial result: {}/{}", outputs.size(), offsets.size()); break; } throw1(OUTPUT_DNE((std::string("Attempting to get output pubkey by global index (amount ") + std::to_string(amount) + ", index " + std::to_string(offsets[i]) + ", count " + std::to_string(get_num_outputs(amount)) + "), but key does not exist (current height " + std::to_string(height()) + ")").c_str())); @@ -4335,12 +4336,12 @@ void BlockchainLMDB::get_output_key(const epee::span &amounts, c data.commitment = rct::zeroCommit(amount); } } - oxen::log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); + log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); } void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std::vector &offsets, std::vector &indices) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); indices.clear(); @@ -4370,12 +4371,12 @@ void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std:: { get_output_tx_and_index_from_global(tx_indices, indices); } - oxen::log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); + log::trace(logcat, "db3: {}", tools::friendly_duration(std::chrono::steady_clock::now() - db3)); } std::map> BlockchainLMDB::get_output_histogram(const std::vector &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4466,7 +4467,7 @@ std::map> BlockchainLMDB::get bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, std::vector &distribution, uint64_t &base) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4511,7 +4512,7 @@ bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_heig void BlockchainLMDB::get_output_blacklist(std::vector &blacklist) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4554,7 +4555,7 @@ void BlockchainLMDB::add_output_blacklist(std::vector const &blacklist if (blacklist.size() == 0) return; - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4571,7 +4572,7 @@ void BlockchainLMDB::add_output_blacklist(std::vector const &blacklist void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string &block, std::string const *checkpoint) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4614,7 +4615,7 @@ void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote:: bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t *data, std::string *block, std::string *checkpoint) const { - oxen::log::trace(logcat, "BlockchainLMDB:: {}", __func__); + log::trace(logcat, "BlockchainLMDB:: {}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4635,7 +4636,7 @@ bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t * void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -4653,7 +4654,7 @@ void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid) uint64_t BlockchainLMDB::get_alt_block_count() { - oxen::log::trace(logcat, "BlockchainLMDB:: {}", __func__); + log::trace(logcat, "BlockchainLMDB:: {}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -4673,7 +4674,7 @@ uint64_t BlockchainLMDB::get_alt_block_count() void BlockchainLMDB::drop_alt_blocks() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX(0); @@ -4705,7 +4706,7 @@ uint64_t BlockchainLMDB::get_database_size() const void BlockchainLMDB::fixup(cryptonote::network_type nettype) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); // Always call parent as well BlockchainDB::fixup(nettype); @@ -4775,8 +4776,8 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) curr_cumulative_diff = next_block.bi_diff; curr_timestamp = next_block.bi_timestamp; - if (old_cumulative_diff != next_block.bi_diff) oxen::log::warning(logcat, "Height: {} curr difficulty: {}, new difficulty: {}", curr_height, old_cumulative_diff, next_block.bi_diff); - else oxen::log::debug(logcat, "Height: {} difficulty unchanged ({})", curr_height, old_cumulative_diff); + if (old_cumulative_diff != next_block.bi_diff) log::warning(logcat, "Height: {} curr difficulty: {}, new difficulty: {}", curr_height, old_cumulative_diff, next_block.bi_diff); + else log::debug(logcat, "Height: {} difficulty unchanged ({})", curr_height, old_cumulative_diff); // NOTE: Store to DB MDB_val_set(val, next_block); @@ -4786,7 +4787,7 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) catch (DB_ERROR const &e) { block_wtxn_abort(); - oxen::log::warning(logcat, "Something went wrong recalculating difficulty for block {}{}", curr_height, e.what()); + log::warning(logcat, "Something went wrong recalculating difficulty for block {}{}", curr_height, e.what()); return; } } @@ -4795,7 +4796,7 @@ void BlockchainLMDB::fixup(cryptonote::network_type nettype) } catch (DB_ERROR const &e) { - oxen::log::warning(logcat, "Something went wrong in the pre-amble of recalculating difficulty for block: {}", e.what()); + log::warning(logcat, "Something went wrong in the pre-amble of recalculating difficulty for block: {}", e.what()); return; } } @@ -4840,15 +4841,15 @@ static int write_db_version(MDB_env *env, MDB_dbi &dest, uint32_t version) void BlockchainLMDB::migrate_0_1() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i, z, m_height; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 0 to 1 - this may take a while:")); - oxen::log::info(logcat, "updating blocks, hf_versions, outputs, txs, and spent_keys tables..."); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 0 to 1 - this may take a while:")); + log::info(logcat, "updating blocks, hf_versions, outputs, txs, and spent_keys tables..."); do { result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -4859,10 +4860,10 @@ void BlockchainLMDB::migrate_0_1() if ((result = mdb_stat(txn, m_blocks, &db_stats))) throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); m_height = db_stats.ms_entries; - oxen::log::info(logcat, "Total number of blocks: {}", m_height); - oxen::log::info(logcat, "block migration will update block_heights, block_info, and hf_versions..."); + log::info(logcat, "Total number of blocks: {}", m_height); + log::info(logcat, "block migration will update block_heights, block_info, and hf_versions..."); - oxen::log::info(logcat, "migrating block_heights:"); + log::info(logcat, "migrating block_heights:"); MDB_dbi o_heights; unsigned int flags; @@ -4872,7 +4873,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if ((flags & (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) == (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) { txn.abort(); - oxen::log::info(logcat, " block_heights already migrated"); + log::info(logcat, " block_heights already migrated"); break; } @@ -4963,7 +4964,7 @@ void BlockchainLMDB::migrate_0_1() * new table is DUPFIXED, k(zeroval), v{height, values...}. */ do { - oxen::log::info(logcat, "migrating block info:"); + log::info(logcat, "migrating block info:"); MDB_dbi coins; result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -4972,7 +4973,7 @@ void BlockchainLMDB::migrate_0_1() result = mdb_dbi_open(txn, "block_coins", 0, &coins); if (result == MDB_NOTFOUND) { txn.abort(); - oxen::log::info(logcat, " block_info already migrated"); + log::info(logcat, " block_info already migrated"); break; } MDB_dbi diffs, hashes, sizes, timestamps; @@ -5094,7 +5095,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - oxen::log::info(logcat, "migrating hf_versions:"); + log::info(logcat, "migrating hf_versions:"); MDB_dbi o_hfv; unsigned int flags; @@ -5107,7 +5108,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if (flags & MDB_INTEGERKEY) { txn.abort(); - oxen::log::info(logcat, " hf_versions already migrated"); + log::info(logcat, " hf_versions already migrated"); break; } @@ -5177,7 +5178,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - oxen::log::info(logcat, "deleting old indices:"); + log::info(logcat, "deleting old indices:"); /* Delete all other tables, we're just going to recreate them */ MDB_dbi dbi; @@ -5188,13 +5189,13 @@ void BlockchainLMDB::migrate_0_1() result = mdb_dbi_open(txn, "tx_unlocks", 0, &dbi); if (result == MDB_NOTFOUND) { txn.abort(); - oxen::log::info(logcat, " old indices already deleted"); + log::info(logcat, " old indices already deleted"); break; } txn.abort(); #define DELETE_DB(x) do { \ - oxen::log::info(logcat, " " x ":"); \ + log::info(logcat, " " x ":"); \ result = mdb_txn_begin(m_env, NULL, 0, txn); \ if (result) \ throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str())); \ @@ -5230,7 +5231,7 @@ void BlockchainLMDB::migrate_0_1() } while(0); do { - oxen::log::info(logcat, "migrating txs and outputs:"); + log::info(logcat, "migrating txs and outputs:"); unsigned int flags; result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -5242,7 +5243,7 @@ void BlockchainLMDB::migrate_0_1() /* if the flags are what we expect, this table has already been migrated */ if (flags & MDB_INTEGERKEY) { txn.abort(); - oxen::log::info(logcat, " txs already migrated"); + log::info(logcat, " txs already migrated"); break; } @@ -5374,15 +5375,15 @@ void BlockchainLMDB::migrate_0_1() void BlockchainLMDB::migrate_1_2() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i, z; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 1 to 2 - this may take a while:")); - oxen::log::info(logcat, "updating txs_pruned and txs_prunable tables..."); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 1 to 2 - this may take a while:")); + log::info(logcat, "updating txs_pruned and txs_prunable tables..."); do { result = mdb_txn_begin(m_env, NULL, 0, txn); @@ -5406,11 +5407,11 @@ void BlockchainLMDB::migrate_1_2() if (db_stats_txs_pruned.ms_entries == db_stats_txs.ms_entries) { txn.commit(); - oxen::log::info(logcat, "txs already migrated"); + log::info(logcat, "txs already migrated"); break; } - oxen::log::info(logcat, "updating txs tables:"); + log::info(logcat, "updating txs tables:"); MDB_cursor *c_old, *c_cur0, *c_cur1, *c_cur2; i = 0; @@ -5509,17 +5510,17 @@ void BlockchainLMDB::migrate_1_2() void BlockchainLMDB::migrate_2_3() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); uint64_t i; int result; mdb_txn_safe txn(false); MDB_val k, v; char *ptr; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 2 to 3 - this may take a while:")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 2 to 3 - this may take a while:")); do { - oxen::log::info(logcat, "migrating block info:"); + log::info(logcat, "migrating block info:"); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -5530,12 +5531,12 @@ void BlockchainLMDB::migrate_2_3() throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str())); const uint64_t blockchain_height = db_stats.ms_entries; - oxen::log::debug(logcat, "enumerating rct outputs..."); + log::debug(logcat, "enumerating rct outputs..."); std::vector distribution(blockchain_height, 0); bool r = for_all_outputs(0, [&](uint64_t height) { if (height >= blockchain_height) { - oxen::log::error(logcat, "Output found claiming height >= blockchain height"); + log::error(logcat, "Output found claiming height >= blockchain height"); return false; } distribution[height]++; @@ -5631,8 +5632,8 @@ void BlockchainLMDB::migrate_2_3() void BlockchainLMDB::migrate_3_4() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 3 to 4 - this may take a while:")); + log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 3 to 4 - this may take a while:")); // Migrate output blacklist { @@ -5725,7 +5726,7 @@ void BlockchainLMDB::migrate_3_4() bool past_long_term_weight = false; do { - oxen::log::info(logcat, "migrating block info:"); + log::info(logcat, "migrating block info:"); result = mdb_txn_begin(m_env, NULL, 0, txn); if (result) @@ -5860,8 +5861,8 @@ void BlockchainLMDB::migrate_3_4() void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 4 to 5 - this may take a while:")); + log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 4 to 5 - this may take a while:")); mdb_txn_safe txn(false); { @@ -5933,8 +5934,8 @@ void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) void BlockchainLMDB::migrate_5_6() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 5 to 6 - this may take a while:")); + log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 5 to 6 - this may take a while:")); mdb_txn_safe txn(false); { @@ -6042,8 +6043,8 @@ void BlockchainLMDB::migrate_5_6() void BlockchainLMDB::migrate_6_7() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 6 to 7 - this may take a while:")); + log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 6 to 7 - this may take a while:")); std::vector checkpoints; checkpoints.reserve(1024); @@ -6133,7 +6134,7 @@ uint64_t constexpr SERVICE_NODE_BLOB_SHORT_TERM_KEY = 1; uint64_t constexpr SERVICE_NODE_BLOB_LONG_TERM_KEY = 2; void BlockchainLMDB::set_service_node_data(const std::string& data, bool long_term) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -6150,7 +6151,7 @@ void BlockchainLMDB::set_service_node_data(const std::string& data, bool long_te bool BlockchainLMDB::get_service_node_data(std::string& data, bool long_term) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6180,7 +6181,7 @@ bool BlockchainLMDB::get_service_node_data(std::string& data, bool long_term) co void BlockchainLMDB::clear_service_node_data() { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; @@ -6290,7 +6291,7 @@ static_assert(sizeof(service_node_proof_serialized) == 72, "service node seriali bool BlockchainLMDB::get_service_node_proof(const crypto::public_key &pubkey, service_nodes::proof_info &proof) const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6314,7 +6315,7 @@ bool BlockchainLMDB::get_service_node_proof(const crypto::public_key &pubkey, se void BlockchainLMDB::set_service_node_proof(const crypto::public_key &pubkey, const service_nodes::proof_info &proof) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); service_node_proof_serialized data{proof}; @@ -6331,7 +6332,7 @@ void BlockchainLMDB::set_service_node_proof(const crypto::public_key &pubkey, co std::unordered_map BlockchainLMDB::get_all_service_node_proofs() const { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); TXN_PREFIX_RDONLY(); @@ -6351,7 +6352,7 @@ std::unordered_map BlockchainLMDB bool BlockchainLMDB::remove_service_node_proof(const crypto::public_key& pubkey) { - oxen::log::trace(logcat, "BlockchainLMDB::{}", __func__); + log::trace(logcat, "BlockchainLMDB::{}", __func__); check_open(); mdb_txn_cursors *m_cursors = &m_wcursors; CURSOR(service_node_proofs) diff --git a/src/blockchain_db/locked_txn.h b/src/blockchain_db/locked_txn.h index a2eb49c7d..084ad6b5d 100644 --- a/src/blockchain_db/locked_txn.h +++ b/src/blockchain_db/locked_txn.h @@ -30,6 +30,8 @@ #pragma once +#include "cryptonote_core/blockchain.h" + namespace cryptonote { // This class is meant to create a batch when none currently exists. @@ -46,8 +48,8 @@ namespace cryptonote LockedTXN(LockedTXN &&o) : m_db{o.m_db}, m_batch{o.m_batch} { o.m_batch = false; } LockedTXN &operator=(LockedTXN &&) = delete; - void commit() { try { if (m_batch) { m_db.batch_stop(); m_batch = false; } } catch (const std::exception &e) { oxen::log::warning(globallogcat, "LockedTXN::commit filtering exception: {}", e.what()); } } - void abort() { try { if (m_batch) { m_db.batch_abort(); m_batch = false; } } catch (const std::exception &e) { oxen::log::warning(globallogcat, "LockedTXN::abort filtering exception: {}", e.what()); } } + void commit() { try { if (m_batch) { m_db.batch_stop(); m_batch = false; } } catch (const std::exception &e) { log::warning(globallogcat, "LockedTXN::commit filtering exception: {}", e.what()); } } + void abort() { try { if (m_batch) { m_db.batch_abort(); m_batch = false; } } catch (const std::exception &e) { log::warning(globallogcat, "LockedTXN::abort filtering exception: {}", e.what()); } } ~LockedTXN() { this->abort(); } private: BlockchainDB &m_db; diff --git a/src/blockchain_db/sqlite/db_sqlite.cpp b/src/blockchain_db/sqlite/db_sqlite.cpp index 242309893..75dd9e80e 100644 --- a/src/blockchain_db/sqlite/db_sqlite.cpp +++ b/src/blockchain_db/sqlite/db_sqlite.cpp @@ -42,10 +42,10 @@ namespace cryptonote { - static auto logcat = oxen::log::Cat("blockchain.db.sqlite"); + static auto logcat = log::Cat("blockchain.db.sqlite"); BlockchainSQLite::BlockchainSQLite(cryptonote::network_type nettype, fs::path db_path): db::Database(db_path, ""), m_nettype(nettype), filename {db_path.u8string()} { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); height = 0; if (!db.tableExists("batched_payments_accrued") || !db.tableExists("batched_payments_raw") || !db.tableExists("batch_db_info")) { @@ -58,7 +58,7 @@ namespace cryptonote { } void BlockchainSQLite::create_schema() { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto& netconf = cryptonote::get_config(m_nettype); @@ -117,7 +117,7 @@ namespace cryptonote { )", netconf.BATCHING_INTERVAL)); - oxen::log::debug(logcat, "Database setup complete"); + log::debug(logcat, "Database setup complete"); } void BlockchainSQLite::upgrade_schema() { @@ -130,7 +130,7 @@ namespace cryptonote { } if (!have_offset) { - oxen::log::info(logcat, "Adding payout_offset to batching db"); + log::info(logcat, "Adding payout_offset to batching db"); auto& netconf = get_config(m_nettype); SQLite::Transaction transaction{ db, @@ -165,7 +165,7 @@ namespace cryptonote { if (count != 0) { constexpr auto error = "Batching db update to add offsets failed: not all addresses were converted"; - oxen::log::error(logcat, error); + log::error(logcat, error); throw std::runtime_error{error}; } @@ -174,7 +174,7 @@ namespace cryptonote { } void BlockchainSQLite::reset_database() { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); db.exec(R"( DROP TABLE IF EXISTS batched_payments_accrued; @@ -188,11 +188,11 @@ namespace cryptonote { create_schema(); - oxen::log::debug(logcat, "Database reset complete"); + log::debug(logcat, "Database reset complete"); } void BlockchainSQLite::update_height(uint64_t new_height) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with new height: {}", __func__, new_height); + log::trace(logcat, "BlockchainDB_SQLITE::{} Called with new height: {}", __func__, new_height); height = new_height; prepared_exec( "UPDATE batch_db_info SET height = ?", @@ -200,12 +200,12 @@ namespace cryptonote { } void BlockchainSQLite::increment_height() { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height + 1); + log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height + 1); update_height(height + 1); } void BlockchainSQLite::decrement_height() { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height - 1); + log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, height - 1); update_height(height - 1); } @@ -220,7 +220,7 @@ namespace cryptonote { bool BlockchainSQLite::add_sn_rewards(const std::vector& payments) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto insert_payment = prepared_st( "INSERT INTO batched_payments_accrued (address, payout_offset, amount) VALUES (?, ?, ?)" " ON CONFLICT (address) DO UPDATE SET amount = amount + excluded.amount"); @@ -231,7 +231,7 @@ namespace cryptonote { auto offset = static_cast(payment.address_info.address.modulus(netconf.BATCHING_INTERVAL)); auto amt = static_cast(payment.amount); const auto& address_str = get_address_str(payment.address_info.address); - oxen::log::trace(logcat, "Adding record for SN reward contributor {} to database with amount {}", address_str, amt); + log::trace(logcat, "Adding record for SN reward contributor {} to database with amount {}", address_str, amt); db::exec_query(insert_payment, address_str, offset, amt); insert_payment->reset(); } @@ -240,7 +240,7 @@ namespace cryptonote { } bool BlockchainSQLite::subtract_sn_rewards(const std::vector& payments) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto update_payment = prepared_st( "UPDATE batched_payments_accrued SET amount = (amount - ?) WHERE address = ?"); @@ -248,7 +248,7 @@ namespace cryptonote { const auto& address_str = get_address_str(payment.address_info.address); auto result = db::exec_query(update_payment, static_cast(payment.amount), address_str); if (!result) { - oxen::log::error(logcat, "tried to subtract payment from an address that doesn't exist: {}", address_str); + log::error(logcat, "tried to subtract payment from an address that doesn't exist: {}", address_str); return false; } update_payment->reset(); @@ -258,7 +258,7 @@ namespace cryptonote { } std::vector BlockchainSQLite::get_sn_payments(uint64_t block_height) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); // <= here because we might have crap in the db that we don't clear until we actually add the HF // block later on. (This is a pretty slim edge case that happened on devnet and is probably @@ -287,7 +287,7 @@ namespace cryptonote { uint64_t BlockchainSQLite::get_accrued_earnings(const std::string& address) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto earnings = prepared_maybe_get( "SELECT amount FROM batched_payments_accrued WHERE address = ?", @@ -296,7 +296,7 @@ namespace cryptonote { } std::pair, std::vector> BlockchainSQLite::get_all_accrued_earnings() { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); std::pair, std::vector> result; auto& [addresses, amounts] = result; @@ -314,7 +314,7 @@ namespace cryptonote { } void BlockchainSQLite::calculate_rewards(hf hf_version, uint64_t distribution_amount, const service_nodes::service_node_info& sn_info, std::vector& payments) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); // Find out how much is due for the operator: fee_portions/PORTIONS * reward assert(sn_info.portions_for_operator <= old::STAKING_PORTIONS); @@ -421,7 +421,7 @@ namespace cryptonote { bool BlockchainSQLite::add_block(const cryptonote::block& block, const service_nodes::service_node_list::state_t& service_nodes_state) { auto block_height = get_block_height(block); - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); + log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); auto hf_version = block.major_version; if (hf_version < hf::hf19_reward_batching) { @@ -431,13 +431,13 @@ namespace cryptonote { auto fork_height = cryptonote::get_hard_fork_heights(m_nettype, hf::hf19_reward_batching); if (block_height == fork_height.first.value_or(0)) { - oxen::log::debug(logcat, "Batching of Service Node Rewards Begins"); + log::debug(logcat, "Batching of Service Node Rewards Begins"); reset_database(); update_height(block_height - 1); } if (block_height != height + 1) { - oxen::log::error(logcat, "Block height ({}) out of sync with batching database ({})", block_height, height); + log::error(logcat, "Block height ({}) out of sync with batching database ({})", block_height, height); return false; } @@ -470,7 +470,7 @@ namespace cryptonote { transaction.commit(); } catch (std::exception& e) { - oxen::log::error(logcat, "Error adding reward payments: {}", e.what()); + log::error(logcat, "Error adding reward payments: {}", e.what()); return false; } return true; @@ -480,13 +480,13 @@ namespace cryptonote { const service_nodes::service_node_list::state_t& service_nodes_state) { auto block_height = get_block_height(block); - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); + log::trace(logcat, "BlockchainDB_SQLITE::{} called on height: {}", __func__, block_height); if (height < block_height) { - oxen::log::debug(logcat, "Block above batching DB height skipping pop"); + log::debug(logcat, "Block above batching DB height skipping pop"); return true; } if (block_height != height) { - oxen::log::error(logcat, "Block height out of sync with batching database"); + log::error(logcat, "Block height out of sync with batching database"); return false; } @@ -512,7 +512,7 @@ namespace cryptonote { decrement_height(); transaction.commit(); } catch (std::exception& e) { - oxen::log::error(logcat, "Error subtracting reward payments: {}", e.what()); + log::error(logcat, "Error subtracting reward payments: {}", e.what()); return false; } return true; @@ -522,10 +522,10 @@ namespace cryptonote { const std::vector>& miner_tx_vouts, const std::vector& calculated_payments_from_batching_db, uint64_t block_height) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); if (miner_tx_vouts.size() != calculated_payments_from_batching_db.size()) { - oxen::log::error(logcat, "Length of batch payments ({}) does not match block vouts ({})", calculated_payments_from_batching_db.size(), miner_tx_vouts.size()); + log::error(logcat, "Length of batch payments ({}) does not match block vouts ({})", calculated_payments_from_batching_db.size(), miner_tx_vouts.size()); return false; } @@ -544,23 +544,23 @@ namespace cryptonote { uint64_t amount = amt * BATCH_REWARD_FACTOR; const auto& from_db = calculated_payments_from_batching_db[vout_index]; if (amount != from_db.amount) { - oxen::log::error(logcat, "Batched payout amount incorrect. Should be {}, not {}", from_db.amount, amount); + log::error(logcat, "Batched payout amount incorrect. Should be {}, not {}", from_db.amount, amount); return false; } crypto::public_key out_eph_public_key{}; if (!cryptonote::get_deterministic_output_key(from_db.address_info.address, deterministic_keypair, vout_index, out_eph_public_key)) { - oxen::log::error(logcat, "Failed to generate output one-time public key"); + log::error(logcat, "Failed to generate output one-time public key"); return false; } if (tools::view_guts(pubkey) != tools::view_guts(out_eph_public_key)) { - oxen::log::error(logcat, "Output ephemeral public key does not match"); + log::error(logcat, "Output ephemeral public key does not match"); return false; } total_oxen_payout_in_vouts += amount; finalised_payments.emplace_back(from_db.address_info, amount); } if (total_oxen_payout_in_vouts != total_oxen_payout_in_our_db) { - oxen::log::error(logcat, "Total batched payout amount incorrect. Should be {}, not {}", total_oxen_payout_in_our_db, total_oxen_payout_in_vouts); + log::error(logcat, "Total batched payout amount incorrect. Should be {}, not {}", total_oxen_payout_in_our_db, total_oxen_payout_in_vouts); return false; } @@ -568,7 +568,7 @@ namespace cryptonote { } bool BlockchainSQLite::save_payments(uint64_t block_height, const std::vector& paid_amounts) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); + log::trace(logcat, "BlockchainDB_SQLITE::{}", __func__); auto select_sum = prepared_st( "SELECT amount from batched_payments_accrued WHERE address = ?"); @@ -586,7 +586,7 @@ namespace cryptonote { auto amount = static_cast(*maybe_amount) / BATCH_REWARD_FACTOR * BATCH_REWARD_FACTOR; if (amount != payment.amount) { - oxen::log::error(logcat, "Invalid amounts passed in to save payments for address {}: received {}, expected {} (truncated from {})", address_str, payment.amount, amount, *maybe_amount); + log::error(logcat, "Invalid amounts passed in to save payments for address {}: received {}, expected {} (truncated from {})", address_str, payment.amount, amount, *maybe_amount); return false; } @@ -595,7 +595,7 @@ namespace cryptonote { } else { // This shouldn't occur: we validate payout addresses much earlier in the block validation. - oxen::log::error(logcat, "Internal error: Invalid amounts passed in to save payments for address {}: that address has no accrued rewards", address_str); + log::error(logcat, "Internal error: Invalid amounts passed in to save payments for address {}: that address has no accrued rewards", address_str); return false; } @@ -605,7 +605,7 @@ namespace cryptonote { } std::vector BlockchainSQLite::get_block_payments(uint64_t block_height) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); + log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); std::vector payments_at_height; auto paid = prepared_results( @@ -622,7 +622,7 @@ namespace cryptonote { } bool BlockchainSQLite::delete_block_payments(uint64_t block_height) { - oxen::log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); + log::trace(logcat, "BlockchainDB_SQLITE::{} Called with height: {}", __func__, block_height); prepared_exec( "DELETE FROM batched_payments_paid WHERE height_paid >= ?", static_cast(block_height)); diff --git a/src/blockchain_utilities/blockchain_ancestry.cpp b/src/blockchain_utilities/blockchain_ancestry.cpp index 6d0df3702..7563fb966 100644 --- a/src/blockchain_utilities/blockchain_ancestry.cpp +++ b/src/blockchain_utilities/blockchain_ancestry.cpp @@ -49,11 +49,11 @@ #include "cryptonote_core/uptime_proof.h" #include -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + static bool stop_requested = false; static uint64_t cached_txes = 0, cached_blocks = 0, cached_outputs = 0, total_txes = 0, total_blocks = 0, total_outputs = 0; static bool opt_cache_outputs = false, opt_cache_txes = false, opt_cache_blocks = false; @@ -103,7 +103,7 @@ struct tx_data_t vin.push_back(std::make_pair(txin->amount, cryptonote::relative_output_offsets_to_absolute(txin->key_offsets))); else { - oxen::log::warning(logcat, "Bad vin type in txid {}", get_transaction_hash(tx)); + log::warning(logcat, "Bad vin type in txid {}", get_transaction_hash(tx)); throw std::runtime_error("Bad vin type"); } } @@ -117,7 +117,7 @@ struct tx_data_t } else { - oxen::log::warning(logcat, "Bad vout type in txid {}", get_transaction_hash(tx)); + log::warning(logcat, "Bad vout type in txid {}", get_transaction_hash(tx)); throw std::runtime_error("Bad vout type"); } } @@ -216,7 +216,7 @@ static std::unordered_set get_ancestry(const std::unordered_map>::const_iterator i = ancestry.find(txid); if (i == ancestry.end()) { - //oxen::log::error(logcat, "txid ancestry not found: {}", txid); + //log::error(logcat, "txid ancestry not found: {}", txid); //throw std::runtime_error("txid ancestry not found"); return std::unordered_set(); } @@ -235,7 +235,7 @@ static bool get_block_from_height(ancestry_state_t &state, BlockchainDB *db, uin std::string bd = db->get_block_blob_from_height(height); if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return false; } if (opt_cache_blocks) @@ -260,13 +260,13 @@ static bool get_transaction(ancestry_state_t &state, BlockchainDB *db, const cry std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - oxen::log::warning(logcat, "Failed to get txid {} from db", txid); + log::warning(logcat, "Failed to get txid {} from db", txid); return false; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - oxen::log::warning(logcat, "Bad tx: {}", txid); + log::warning(logcat, "Bad tx: {}", txid); return false; } tx_data = ::tx_data_t(tx); @@ -305,7 +305,7 @@ static bool get_output_txid(ancestry_state_t &state, BlockchainDB *db, uint64_t } else { - oxen::log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); + log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); return false; } } @@ -389,7 +389,7 @@ int main(int argc, char* argv[]) } auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-ancestry.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -397,7 +397,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); @@ -437,19 +437,19 @@ int main(int argc, char* argv[]) } } - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - oxen::log::warning(logcat, "database: LMDB"); + log::warning(logcat, "database: LMDB"); fs::path filename = fs::u8path(opt_data_dir) / db->get_db_name(); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -457,20 +457,20 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Source blockchain storage initialized OK"); std::vector start_txids; ancestry_state_t state; fs::path state_file_path = fs::u8path(opt_data_dir) / "ancestry-state.bin"; - oxen::log::warning(logcat, "Loading state data from {}", state_file_path); + log::warning(logcat, "Loading state data from {}", state_file_path); fs::ifstream state_data_in; state_data_in.open(state_file_path, std::ios_base::binary | std::ios_base::in); if (!state_data_in.fail()) @@ -482,7 +482,7 @@ int main(int argc, char* argv[]) } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to load state data from {}, restarting from scratch", state_file_path); + log::error(logcat, "Failed to load state data from {}, restarting from scratch", state_file_path); state = ancestry_state_t(); } state_data_in.close(); @@ -496,7 +496,7 @@ int main(int argc, char* argv[]) const uint64_t db_height = db->height(); if (opt_refresh) { - oxen::log::info(logcat, "Starting from height {}", state.height); + log::info(logcat, "Starting from height {}", state.height); state.block_cache.reserve(db_height); for (uint64_t h = state.height; h < db_height; ++h) { @@ -506,7 +506,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return 1; } if (opt_cache_blocks) @@ -537,13 +537,13 @@ int main(int argc, char* argv[]) std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - oxen::log::warning(logcat, "Failed to get txid {} from db", txid); + log::warning(logcat, "Failed to get txid {} from db", txid); return 1; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - oxen::log::warning(logcat, "Bad tx: {}", txid); + log::warning(logcat, "Bad tx: {}", txid); return 1; } tx_data = ::tx_data_t(tx); @@ -568,7 +568,7 @@ int main(int argc, char* argv[]) crypto::hash output_txid; if (!get_output_txid(state, db, amount, offset, output_txid)) { - oxen::log::warning(logcat, "Output originating transaction not found"); + log::warning(logcat, "Output originating transaction not found"); return 1; } add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid)); @@ -577,19 +577,19 @@ int main(int argc, char* argv[]) } const size_t ancestry_size = get_ancestry(state.ancestry, txid).size(); block_ancestry_size += ancestry_size; - oxen::log::info(logcat, "{}: {}", txid, ancestry_size); + log::info(logcat, "{}: {}", txid, ancestry_size); } if (!txids.empty()) { std::string stats_msg; - oxen::log::info(logcat, "Height {}: {} average over {}{}", h, (block_ancestry_size / txids.size()), txids.size(), stats_msg); + log::info(logcat, "Height {}: {} average over {}{}", h, (block_ancestry_size / txids.size()), txids.size(), stats_msg); } state.height = h; if (stop_requested) break; } - oxen::log::warning(logcat, "Saving state data to {}", state_file_path); + log::warning(logcat, "Saving state data to {}", state_file_path); std::ofstream state_data_out; state_data_out.open(state_file_path, std::ios_base::binary | std::ios_base::out | std::ios::trunc); if (!state_data_out.fail()) @@ -601,7 +601,7 @@ int main(int argc, char* argv[]) } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to save state data to {}", state_file_path); + log::error(logcat, "Failed to save state data to {}", state_file_path); } state_data_out.close(); } @@ -610,8 +610,8 @@ int main(int argc, char* argv[]) { if (state.height < db_height) { - oxen::log::warning(logcat, "The state file is only built up to height {}, but the blockchain reached height {}", state.height, db_height); - oxen::log::warning(logcat, "You may want to run with --refresh if you want to get ancestry for newer data"); + log::warning(logcat, "The state file is only built up to height {}, but the blockchain reached height {}", state.height, db_height); + log::warning(logcat, "You may want to run with --refresh if you want to get ancestry for newer data"); } } @@ -624,7 +624,7 @@ int main(int argc, char* argv[]) crypto::hash txid; if (!get_output_txid(state, db, output_amount, output_offset, txid)) { - oxen::log::warning(logcat, "Output not found in db"); + log::warning(logcat, "Output not found in db"); return 1; } start_txids.push_back(txid); @@ -635,7 +635,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return 1; } for (const crypto::hash &txid: b.tx_hashes) @@ -644,13 +644,13 @@ int main(int argc, char* argv[]) if (start_txids.empty()) { - oxen::log::warning(logcat, "No transaction(s) to check"); + log::warning(logcat, "No transaction(s) to check"); return 1; } for (const crypto::hash &start_txid: start_txids) { - oxen::log::warning(logcat, "Checking ancestry for txid {}", start_txid); + log::warning(logcat, "Checking ancestry for txid {}", start_txid); std::unordered_map ancestry; @@ -686,22 +686,22 @@ int main(int argc, char* argv[]) crypto::hash output_txid; if (!get_output_txid(state, db, amount, offset, output_txid)) { - oxen::log::warning(logcat, "Output originating transaction not found"); + log::warning(logcat, "Output originating transaction not found"); return 1; } add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid)); txids.push_back(output_txid); - oxen::log::debug(logcat, "adding txid: {}", output_txid); + log::debug(logcat, "adding txid: {}", output_txid); } } } } - oxen::log::info(logcat, "Ancestry for {}: {} / {}", start_txid, get_deduplicated_ancestry(ancestry), get_full_ancestry(ancestry)); + log::info(logcat, "Ancestry for {}: {} / {}", start_txid, get_deduplicated_ancestry(ancestry), get_full_ancestry(ancestry)); for (const auto &i: ancestry) { - oxen::log::info(logcat, "{}/{}: {}", cryptonote::print_money(i.first.amount), i.first.offset, i.second); + log::info(logcat, "{}/{}: {}", cryptonote::print_money(i.first.amount), i.first.offset, i.second); } } @@ -709,7 +709,7 @@ done: core_storage->deinit(); if (opt_show_cache_stats) - oxen::log::info(logcat, "cache: txes {}%, blocks {}%, outputs {}%", std::to_string(cached_txes*100./total_txes), std::to_string(cached_blocks*100./total_blocks), std::to_string(cached_outputs*100./total_outputs)); + log::info(logcat, "cache: txes {}%, blocks {}%, outputs {}%", std::to_string(cached_txes*100./total_txes), std::to_string(cached_blocks*100./total_blocks), std::to_string(cached_outputs*100./total_outputs)); return 0; diff --git a/src/blockchain_utilities/blockchain_blackball.cpp b/src/blockchain_utilities/blockchain_blackball.cpp index 17fb6be2e..fa63b28ce 100644 --- a/src/blockchain_utilities/blockchain_blackball.cpp +++ b/src/blockchain_utilities/blockchain_blackball.cpp @@ -48,11 +48,11 @@ #include "cryptonote_core/uptime_proof.h" #include -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + static const char zerokey[8] = {0}; static const MDB_val zerokval = { sizeof(zerokey), (void *)zerokey }; @@ -90,7 +90,7 @@ static bool parse_db_sync_mode(std::string db_sync_mode) auto options = tools::split_any(db_sync_mode, " :", true); for(const auto &option : options) - oxen::log::debug(logcat, "option: {}", option); + log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -206,14 +206,14 @@ static int resize_env(const char *db_path) auto si = fs::space(fs::u8path(db_path)); if(si.available < needed) { - oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); + log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); return ENOSPC; } } catch(...) { // print something but proceed. - oxen::log::warning(logcat, "Unable to query free disk space."); + log::warning(logcat, "Unable to query free disk space."); } mapsize += needed; @@ -227,11 +227,11 @@ static void init(fs::path cache_filename) bool tx_active = false; int dbr; - oxen::log::info(logcat, "Creating spent output cache in {}", cache_filename); + log::info(logcat, "Creating spent output cache in {}", cache_filename); std::error_code ec; if (fs::create_directories(cache_filename, ec); ec) - oxen::log::warning(logcat, "Failed to create output cache directory {}: {}", cache_filename, ec.message()); + log::warning(logcat, "Failed to create output cache directory {}: {}", cache_filename, ec.message()); int flags = 0; if (db_flags & DBF_FAST) @@ -392,7 +392,7 @@ static bool for_all_transactions(const fs::path& filename, uint64_t& start_idx, std::string_view bd{static_cast(v.mv_data), v.mv_size}; serialization::parse_binary(bd, tx); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse transaction from blob: {}", e.what()); + log::error(logcat, "Failed to parse transaction from blob: {}", e.what()); return false; } @@ -607,7 +607,7 @@ static std::vector canonicalize(const std::vector &v) } if (c.size() < v.size()) { - oxen::log::info(logcat, "Ring has duplicate member(s): {}", tools::join(" ", v)); + log::info(logcat, "Ring has duplicate member(s): {}", tools::join(" ", v)); } return c; } @@ -955,7 +955,7 @@ static void open_db(const fs::path& filename, MDB_env** env, MDB_txn** txn, MDB_ { std::error_code ec; if (fs::create_directories(filename, ec); ec) - oxen::log::warning(logcat, "Failed to create lmdb path {}: {}", filename, ec.message()); + log::warning(logcat, "Failed to create lmdb path {}: {}", filename, ec.message()); int flags = MDB_RDONLY; if (db_flags & DBF_FAST) @@ -967,7 +967,7 @@ static void open_db(const fs::path& filename, MDB_env** env, MDB_txn** txn, MDB_ CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr))); dbr = mdb_env_set_maxdbs(*env, 1); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to set max env dbs: " + std::string(mdb_strerror(dbr))); - oxen::log::info(logcat, "Opening oxen blockchain at {}", filename); + log::info(logcat, "Opening oxen blockchain at {}", filename); dbr = mdb_env_open(*env, filename.string().c_str(), flags, 0664); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to open rings database file '" + filename.u8string() + "': " + std::string(mdb_strerror(dbr))); @@ -1065,7 +1065,7 @@ static std::vector> load_outputs(const fs::path& f if (!f) { - oxen::log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); + log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); return {}; } while (1) @@ -1073,7 +1073,7 @@ static std::vector> load_outputs(const fs::path& f char s[256]; if (!fgets(s, sizeof(s), f)) { - oxen::log::error(logcat, "Error reading from {}: {}", filename, strerror(errno)); + log::error(logcat, "Error reading from {}: {}", filename, strerror(errno)); break; } if (feof(f)) @@ -1091,7 +1091,7 @@ static std::vector> load_outputs(const fs::path& f } if (amount == std::numeric_limits::max()) { - oxen::log::error(logcat, "Bad format in {}", filename); + log::error(logcat, "Bad format in {}", filename); continue; } if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits::max() - offset) @@ -1105,7 +1105,7 @@ static std::vector> load_outputs(const fs::path& f } else { - oxen::log::error(logcat, "Bad format in {}", filename); + log::error(logcat, "Bad format in {}", filename); continue; } } @@ -1124,7 +1124,7 @@ static bool export_spent_outputs(MDB_cursor* cur, const fs::path& filename) if (!f) { - oxen::log::error(logcat, "Failed to open {}: {}", filename, strerror(errno)); + log::error(logcat, "Failed to open {}: {}", filename, strerror(errno)); return false; } @@ -1141,7 +1141,7 @@ static bool export_spent_outputs(MDB_cursor* cur, const fs::path& filename) if (dbr) { fclose(f); - oxen::log::error(logcat, "Failed to enumerate spent outputs: {}", mdb_strerror(dbr)); + log::error(logcat, "Failed to enumerate spent outputs: {}", mdb_strerror(dbr)); return false; } const uint64_t amount = *(const uint64_t*)k.mv_data; @@ -1242,7 +1242,7 @@ int main(int argc, char* argv[]) auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-mark-spent-outputs.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -1250,7 +1250,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); fs::path output_file_path = fs::u8path(command_line::get_arg(vm, arg_blackball_db_dir)); bool opt_rct_only = command_line::get_arg(vm, arg_rct_only); @@ -1266,7 +1266,7 @@ int main(int argc, char* argv[]) std::string db_sync_mode = command_line::get_arg(vm, arg_db_sync_mode); if (!parse_db_sync_mode(db_sync_mode)) { - oxen::log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); + log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); return 1; } @@ -1275,7 +1275,7 @@ int main(int argc, char* argv[]) inputs.push_back(fs::u8path(in)); if (inputs.empty()) { - oxen::log::warning(logcat, "No inputs given"); + log::warning(logcat, "No inputs given"); return 1; } @@ -1289,7 +1289,7 @@ int main(int argc, char* argv[]) fs::path cache_dir = output_file_path / "spent-outputs-cache"; init(cache_dir); - oxen::log::warning(logcat, "Scanning for spent outputs..."); + log::warning(logcat, "Scanning for spent outputs..."); size_t done = 0; @@ -1318,7 +1318,7 @@ int main(int argc, char* argv[]) { if (!start_blackballed_outputs) { - oxen::log::info(logcat, "Spent outputs database is empty. Either you haven't run the analysis mode yet, or there is really no output marked as spent."); + log::info(logcat, "Spent outputs database is empty. Either you haven't run the analysis mode yet, or there is really no output marked as spent."); goto skip_secondary_passes; } MDB_txn *txn; @@ -1343,7 +1343,7 @@ int main(int argc, char* argv[]) { uint64_t window_front = (height / STAT_WINDOW - 1) * STAT_WINDOW; uint64_t window_back = window_front + STAT_WINDOW - 1; - oxen::log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); + log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); outs_total = outs_spent = 0; } } @@ -1360,11 +1360,11 @@ int main(int argc, char* argv[]) { uint64_t window_front = (height / STAT_WINDOW) * STAT_WINDOW; uint64_t window_back = height; - oxen::log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); + log::warning(logcat, "{}-{}: {}% ( {} / {} )", window_front, window_back, (100.0f * outs_spent / outs_total), outs_spent, outs_total); } if (stop_requested) { - oxen::log::info(logcat, "Stopping scan..."); + log::info(logcat, "Stopping scan..."); return false; } return true; @@ -1377,7 +1377,7 @@ int main(int argc, char* argv[]) if (!extra_spent_outputs.empty()) { - oxen::log::info(logcat, "Adding {} extra spent outputs", extra_spent_outputs.size()); + log::info(logcat, "Adding {} extra spent outputs", extra_spent_outputs.size()); MDB_txn *txn; int dbr = mdb_txn_begin(env, NULL, 0, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); @@ -1412,9 +1412,9 @@ int main(int argc, char* argv[]) if (n > 0 && start_idx == 0) { start_idx = find_first_diverging_transaction(inputs[0], inputs[n]); - oxen::log::warning(logcat, "First diverging transaction at {}", start_idx); + log::warning(logcat, "First diverging transaction at {}", start_idx); } - oxen::log::warning(logcat, "Reading blockchain from {} from {}", inputs[n], start_idx); + log::warning(logcat, "Reading blockchain from {} from {}", inputs[n], start_idx); MDB_txn *txn; int dbr = mdb_txn_begin(env, NULL, 0, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); @@ -1451,7 +1451,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[0]); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in a 1-ring", output.first, output.second); + log::info(logcat, "Marking output {}/{} as spent, due to being used in a 1-ring", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1465,7 +1465,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[o]); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in {} identical {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); + log::info(logcat, "Marking output {}/{} as spent, due to being used in {} identical {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1480,7 +1480,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, o); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to as many outputs of that amount being spent as exist so far", output.first, output.second); + log::info(logcat, "Marking output {}/{} as spent, due to as many outputs of that amount being spent as exist so far", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1495,7 +1495,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, absolute[o]); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in {} subsets of {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); + log::info(logcat, "Marking output {}/{} as spent, due to being used in {} subsets of {}-rings", output.first, output.second, new_ring.size(), new_ring.size()); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1505,11 +1505,11 @@ int main(int argc, char* argv[]) } else if (n > 0 && get_relative_ring(txn, txin.k_image, relative_ring)) { - oxen::log::debug(logcat, "Key image {} already seen: rings {}, {}", txin.k_image, tools::join(" ", relative_ring), tools::join(" ", txin.key_offsets)); + log::debug(logcat, "Key image {} already seen: rings {}, {}", txin.k_image, tools::join(" ", relative_ring), tools::join(" ", txin.key_offsets)); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; if (relative_ring != txin.key_offsets) { - oxen::log::debug(logcat, "Rings are different"); + log::debug(logcat, "Rings are different"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; const std::vector r0 = cryptonote::relative_output_offsets_to_absolute(relative_ring); const std::vector r1 = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets); @@ -1521,7 +1521,7 @@ int main(int argc, char* argv[]) } if (common.empty()) { - oxen::log::error(logcat, "Rings for the same key image are disjoint"); + log::error(logcat, "Rings for the same key image are disjoint"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } else if (common.size() == 1) @@ -1529,7 +1529,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(txin.amount, common[0]); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in rings with a single common element", output.first, output.second); + log::info(logcat, "Marking output {}/{} as spent, due to being used in rings with a single common element", output.first, output.second); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; } blackballs.push_back(output); @@ -1538,7 +1538,7 @@ int main(int argc, char* argv[]) } else { - oxen::log::debug(logcat, "The intersection has more than one element, it's still ok"); + log::debug(logcat, "The intersection has more than one element, it's still ok"); std::cout << "\r" << start_idx << "/" << n_txes << " \r" << std::flush; for (const auto &out: r0) if (std::find(common.begin(), common.end(), out) != common.end()) @@ -1594,7 +1594,7 @@ int main(int argc, char* argv[]) if (stop_requested) { - oxen::log::info(logcat, "Stopping scan..."); + log::info(logcat, "Stopping scan..."); return false; } return true; @@ -1602,7 +1602,7 @@ int main(int argc, char* argv[]) mdb_cursor_close(cur); dbr = mdb_txn_commit(txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr))); - oxen::log::warning(logcat, "blockchain from {} processed till tx idx {}", inputs[n], start_idx); + log::warning(logcat, "blockchain from {} processed till tx idx {}", inputs[n], start_idx); if (stop_requested) break; } @@ -1621,7 +1621,7 @@ int main(int argc, char* argv[]) while (!work_spent.empty()) { - oxen::log::warning(logcat, "Secondary pass on {} spent outputs", work_spent.size()); + log::warning(logcat, "Secondary pass on {} spent outputs", work_spent.size()); int dbr = resize_env(cache_dir.string().c_str()); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to resize LMDB database: " + std::string(mdb_strerror(dbr))); @@ -1659,7 +1659,7 @@ int main(int argc, char* argv[]) const std::pair output = std::make_pair(od.amount, last_unknown); if (opt_verbose) { - oxen::log::info(logcat, "Marking output {}/{} as spent, due to being used in a {}-ring where all other outputs are known to be spent", output.first, output.second, absolute.size()); + log::info(logcat, "Marking output {}/{} as spent, due to being used in a {}-ring where all other outputs are known to be spent", output.first, output.second, absolute.size()); } blackballs.push_back(output); if (add_spent_output(cur, output_data(od.amount, last_unknown))) @@ -1670,7 +1670,7 @@ int main(int argc, char* argv[]) if (stop_requested) { - oxen::log::info(logcat, "Stopping secondary passes. Secondary passes are not incremental, they will re-run fully."); + log::info(logcat, "Stopping secondary passes. Secondary passes are not incremental, they will re-run fully."); return 0; } } @@ -1686,15 +1686,15 @@ int main(int argc, char* argv[]) skip_secondary_passes: uint64_t diff = get_num_spent_outputs() - start_blackballed_outputs; - oxen::log::warning(logcat, "{} new outputs marked as spent, {} total outputs marked as spent", std::to_string(diff), get_num_spent_outputs()); + log::warning(logcat, "{} new outputs marked as spent, {} total outputs marked as spent", std::to_string(diff), get_num_spent_outputs()); MDB_txn *txn; dbr = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn); CHECK_AND_ASSERT_THROW_MES(!dbr, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); uint64_t pre_rct = 0, rct = 0; get_num_outputs(txn0, cur0, dbi0, pre_rct, rct); - oxen::log::info(logcat, "Total pre-rct outputs: {}", pre_rct); - oxen::log::info(logcat, "Total rct outputs: {}", rct); + log::info(logcat, "Total pre-rct outputs: {}", pre_rct); + log::info(logcat, "Total rct outputs: {}", rct); static const struct { const char *key; uint64_t base; } stat_keys[] = { { "pre-rct-ring-size-1", pre_rct }, { "rct-ring-size-1", rct }, { "pre-rct-duplicate-rings", pre_rct }, { "rct-duplicate-rings", rct }, @@ -1710,7 +1710,7 @@ skip_secondary_passes: if (!get_stat(txn, key.key, data)) data = 0; float percent = key.base ? 100.0f * data / key.base : 0.0f; - oxen::log::info(logcat, "{}: {} ({}%)", key.key, data, percent); + log::info(logcat, "{}: {} ({}%)", key.key, data, percent); } mdb_txn_abort(txn); @@ -1727,7 +1727,7 @@ skip_secondary_passes: mdb_txn_abort(txn); } - oxen::log::warning(logcat, "Blockchain spent output data exported OK"); + log::warning(logcat, "Blockchain spent output data exported OK"); close_db(env0, txn0, cur0, dbi0); close(); return 0; diff --git a/src/blockchain_utilities/blockchain_depth.cpp b/src/blockchain_utilities/blockchain_depth.cpp index 7510b154e..bf4de31c3 100644 --- a/src/blockchain_utilities/blockchain_depth.cpp +++ b/src/blockchain_utilities/blockchain_depth.cpp @@ -36,11 +36,11 @@ #include "version.h" #include -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + int main(int argc, char* argv[]) { TRY_ENTRY(); @@ -89,7 +89,7 @@ int main(int argc, char* argv[]) auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-depth.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -97,7 +97,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -121,19 +121,19 @@ int main(int argc, char* argv[]) } } - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - oxen::log::warning(logcat, "database: LMDB"); + log::warning(logcat, "database: LMDB"); const fs::path filename = fs::u8path(command_line::get_arg(vm, cryptonote::arg_data_dir)) / db->get_db_name(); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -141,13 +141,13 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Source blockchain storage initialized OK"); std::vector start_txids; if (!opt_txid_string.empty()) @@ -160,7 +160,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return 1; } for (const crypto::hash &txid: b.tx_hashes) @@ -171,7 +171,7 @@ int main(int argc, char* argv[]) if (start_txids.empty()) { - oxen::log::warning(logcat, "No transaction(s) to check"); + log::warning(logcat, "No transaction(s) to check"); return 1; } @@ -181,31 +181,31 @@ int main(int argc, char* argv[]) uint64_t depth = 0; bool coinbase = false; - oxen::log::warning(logcat, "Checking depth for txid {}", start_txid); + log::warning(logcat, "Checking depth for txid {}", start_txid); std::vector txids(1, start_txid); while (!coinbase) { - oxen::log::warning(logcat, "Considering {} transaction(s) at depth {}", txids.size(), depth); + log::warning(logcat, "Considering {} transaction(s) at depth {}", txids.size(), depth); std::vector new_txids; for (const crypto::hash &txid: txids) { std::string bd; if (!db->get_pruned_tx_blob(txid, bd)) { - oxen::log::warning(logcat, "Failed to get txid {} from db", txid); + log::warning(logcat, "Failed to get txid {} from db", txid); return 1; } cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx)) { - oxen::log::warning(logcat, "Bad tx: {}", txid); + log::warning(logcat, "Bad tx: {}", txid); return 1; } for (size_t ring = 0; ring < tx.vin.size(); ++ring) { if (std::holds_alternative(tx.vin[ring])) { - oxen::log::debug(logcat, "{} is a coinbase transaction", txid); + log::debug(logcat, "{} is a coinbase transaction", txid); coinbase = true; goto done; } @@ -221,7 +221,7 @@ int main(int argc, char* argv[]) cryptonote::block b; if (!cryptonote::parse_and_validate_block_from_blob(bd, b)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return 1; } // find the tx which created this output @@ -234,13 +234,13 @@ int main(int argc, char* argv[]) { found = true; new_txids.push_back(cryptonote::get_transaction_hash(b.miner_tx)); - oxen::log::debug(logcat, "adding txid: {}", cryptonote::get_transaction_hash(b.miner_tx)); + log::debug(logcat, "adding txid: {}", cryptonote::get_transaction_hash(b.miner_tx)); break; } } else { - oxen::log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); + log::warning(logcat, "Bad vout type in txid {}", cryptonote::get_transaction_hash(b.miner_tx)); return 1; } } @@ -250,13 +250,13 @@ int main(int argc, char* argv[]) break; if (!db->get_pruned_tx_blob(block_txid, bd)) { - oxen::log::warning(logcat, "Failed to get txid {} from db", block_txid); + log::warning(logcat, "Failed to get txid {} from db", block_txid); return 1; } cryptonote::transaction tx2; if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx2)) { - oxen::log::warning(logcat, "Bad tx: {}", block_txid); + log::warning(logcat, "Bad tx: {}", block_txid); return 1; } for (size_t out = 0; out < tx2.vout.size(); ++out) @@ -267,27 +267,27 @@ int main(int argc, char* argv[]) { found = true; new_txids.push_back(block_txid); - oxen::log::debug(logcat, "adding txid: {}", block_txid); + log::debug(logcat, "adding txid: {}", block_txid); break; } } else { - oxen::log::warning(logcat, "Bad vout type in txid {}", block_txid); + log::warning(logcat, "Bad vout type in txid {}", block_txid); return 1; } } } if (!found) { - oxen::log::warning(logcat, "Output originating transaction not found"); + log::warning(logcat, "Output originating transaction not found"); return 1; } } } else { - oxen::log::warning(logcat, "Bad vin type in txid {}", txid); + log::warning(logcat, "Bad vin type in txid {}", txid); return 1; } } @@ -299,15 +299,15 @@ int main(int argc, char* argv[]) } } done: - oxen::log::warning(logcat, "Min depth for txid {}: {}", start_txid, depth); + log::warning(logcat, "Min depth for txid {}: {}", start_txid, depth); depths.push_back(depth); } uint64_t cumulative_depth = 0; for (uint64_t depth: depths) cumulative_depth += depth; - oxen::log::warning(logcat, "Average min depth for {} transaction(s): {}", start_txids.size(), cumulative_depth/(float)depths.size()); - oxen::log::warning(logcat, "Median min depth for {} transaction(s): {}", start_txids.size(), tools::median(std::move(depths))); + log::warning(logcat, "Average min depth for {} transaction(s): {}", start_txids.size(), cumulative_depth/(float)depths.size()); + log::warning(logcat, "Median min depth for {} transaction(s): {}", start_txids.size(), tools::median(std::move(depths))); core_storage->deinit(); return 0; diff --git a/src/blockchain_utilities/blockchain_export.cpp b/src/blockchain_utilities/blockchain_export.cpp index 7e0a3e761..72d293dd6 100644 --- a/src/blockchain_utilities/blockchain_export.cpp +++ b/src/blockchain_utilities/blockchain_export.cpp @@ -36,12 +36,13 @@ #include "cryptonote_core/uptime_proof.h" #include -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; int main(int argc, char* argv[]) { + using namespace oxen; + auto logcat = log::Cat("bcutil"); + TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); @@ -92,7 +93,7 @@ int main(int argc, char* argv[]) auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-export.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -100,7 +101,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -118,42 +119,42 @@ int main(int argc, char* argv[]) output_file_path = fs::u8path(command_line::get_arg(vm, arg_output_file)); else output_file_path = config_folder / "export" / BLOCKCHAIN_RAW; - oxen::log::warning(logcat, "Export output file: {}", output_file_path.string()); + log::warning(logcat, "Export output file: {}", output_file_path.string()); - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - oxen::log::warning(logcat, "database: LMDB"); + log::warning(logcat, "database: LMDB"); auto filename = config_folder / db->get_db_name(); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { db->open(filename, core_storage->nettype(), DBF_RDONLY); } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr, nullptr, opt_testnet ? cryptonote::network_type::TESTNET : opt_devnet ? cryptonote::network_type::DEVNET : cryptonote::network_type::MAINNET); if (core_storage->get_blockchain_pruning_seed() && !opt_blocks_dat) { - oxen::log::warning(logcat, "Blockchain is pruned, cannot export"); + log::warning(logcat, "Blockchain is pruned, cannot export"); return 1; } CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); - oxen::log::warning(logcat, "Exporting blockchain raw data..."); + log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Exporting blockchain raw data..."); if (opt_blocks_dat) { @@ -166,7 +167,7 @@ int main(int argc, char* argv[]) r = bootstrap.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } CHECK_AND_ASSERT_MES(r, 1, "Failed to export blockchain raw data"); - oxen::log::warning(logcat, "Blockchain raw data exported OK"); + log::warning(logcat, "Blockchain raw data exported OK"); return 0; CATCH_ENTRY("Export error", 1); diff --git a/src/blockchain_utilities/blockchain_import.cpp b/src/blockchain_utilities/blockchain_import.cpp index 37786f091..75a46a988 100644 --- a/src/blockchain_utilities/blockchain_import.cpp +++ b/src/blockchain_utilities/blockchain_import.cpp @@ -48,8 +48,6 @@ #include #include -static auto logcat = oxen::log::Cat("bcutil"); - namespace { // CONFIG @@ -89,6 +87,8 @@ namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + // db_mode: safe, fast, fastest int get_db_flags_from_mode(const std::string& db_mode) { @@ -144,7 +144,7 @@ int check_flush(cryptonote::core &core, std::vector &block cryptonote::block block; if (!parse_and_validate_block_from_blob(b.block, block)) { - oxen::log::error(logcat, "Failed to parse block: {}", tools::type_to_hex(get_blob_hash(b.block))); + log::error(logcat, "Failed to parse block: {}", tools::type_to_hex(get_blob_hash(b.block))); core.cleanup_handle_incoming_blocks(); return 1; } @@ -156,12 +156,12 @@ int check_flush(cryptonote::core &core, std::vector &block std::vector pblocks; if (!core.prepare_handle_incoming_blocks(blocks, pblocks)) { - oxen::log::error(logcat, "Failed to prepare to add blocks"); + log::error(logcat, "Failed to prepare to add blocks"); return 1; } if (!pblocks.empty() && pblocks.size() != blocks.size()) { - oxen::log::error(logcat, "Unexpected parsed blocks size"); + log::error(logcat, "Unexpected parsed blocks size"); core.cleanup_handle_incoming_blocks(); return 1; } @@ -176,7 +176,7 @@ int check_flush(cryptonote::core &core, std::vector &block core.handle_incoming_tx(tx_blob, tvc, tx_pool_options::from_block()); if(tvc.m_verifivation_failed) { - oxen::log::error(logcat, "transaction verification failed, tx_id = {}", tools::type_to_hex(get_blob_hash(tx_blob))); + log::error(logcat, "transaction verification failed, tx_id = {}", tools::type_to_hex(get_blob_hash(tx_blob))); core.cleanup_handle_incoming_blocks(); return 1; } @@ -190,13 +190,13 @@ int check_flush(cryptonote::core &core, std::vector &block if(bvc.m_verifivation_failed) { - oxen::log::error(logcat, "Block verification failed, id = {}", tools::type_to_hex(get_blob_hash(block_entry.block))); + log::error(logcat, "Block verification failed, id = {}", tools::type_to_hex(get_blob_hash(block_entry.block))); core.cleanup_handle_incoming_blocks(); return 1; } if(bvc.m_marked_as_orphaned) { - oxen::log::error(logcat, "Block received at sync phase was marked as orphaned"); + log::error(logcat, "Block received at sync phase was marked as orphaned"); core.cleanup_handle_incoming_blocks(); return 1; } @@ -218,7 +218,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (std::error_code ec; !fs::exists(import_file_path, ec)) { - oxen::log::error(logcat, "bootstrap file not found: {}", import_file_path); + log::error(logcat, "bootstrap file not found: {}", import_file_path); return false; } @@ -231,7 +231,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u std::streampos pos; // BootstrapFile bootstrap(import_file_path); uint64_t total_source_blocks = bootstrap.count_blocks(import_file_path, pos, seek_height); - oxen::log::info(logcat, "bootstrap file last block number: {} (zero-based height) total blocks: {}", total_source_blocks-1, total_source_blocks); + log::info(logcat, "bootstrap file last block number: {} (zero-based height) total blocks: {}", total_source_blocks-1, total_source_blocks); if (total_source_blocks-1 <= start_height) { @@ -244,7 +244,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (import_file.fail()) { - oxen::log::error(logcat, "import_file.open() fail"); + log::error(logcat, "import_file.open() fail"); return false; } @@ -268,11 +268,11 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u // These are what we'll try to use, and they don't have to be a determination // from source and destination blockchains, but those are the defaults. - oxen::log::info(logcat, "start block: {} stop block: {}", start_height, block_stop); + log::info(logcat, "start block: {} stop block: {}", start_height, block_stop); bool use_batch = opt_batch && !opt_verify; - oxen::log::info(logcat, "Reading blockchain from bootstrap file..."); + log::info(logcat, "Reading blockchain from bootstrap file..."); std::cout << "\n"; std::vector blocks; @@ -311,7 +311,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u // TODO: bootstrap.read_chunk(); if (! import_file) { std::cout << refresh_string; - oxen::log::info(logcat, "End of file reached"); + log::info(logcat, "End of file reached"); quit = 1; break; } @@ -322,19 +322,19 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of chunk size: "s + e.what()); } - oxen::log::debug(logcat, "chunk_size: {}", chunk_size); + log::debug(logcat, "chunk_size: {}", chunk_size); if (chunk_size > BUFFER_SIZE) { - oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); + log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); throw std::runtime_error("Aborting: chunk size exceeds buffer size"); } if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD) { - oxen::log::info(logcat, "NOTE: chunk_size {} > {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD); + log::info(logcat, "NOTE: chunk_size {} > {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD); } else if (chunk_size == 0) { - oxen::log::error(logcat, "ERROR: chunk_size == 0"); + log::error(logcat, "ERROR: chunk_size == 0"); return 2; } import_file.read(buffer_block, chunk_size); @@ -342,25 +342,25 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if (import_file.eof()) { std::cout << refresh_string; - oxen::log::info(logcat, "End of file reached - file was truncated"); + log::info(logcat, "End of file reached - file was truncated"); quit = 1; break; } else { - oxen::log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); + log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); return 2; } } bytes_read += chunk_size; - oxen::log::debug(logcat, "Total bytes read: {}", bytes_read); + log::debug(logcat, "Total bytes read: {}", bytes_read); if (h > block_stop) { std::cout << refresh_string << "block " << h-1 << " / " << block_stop << "\n" << std::endl; - oxen::log::info(logcat, "Specified block number reached - stopping. block: {} total blocks: {}", h-1, h); + log::info(logcat, "Specified block number reached - stopping. block: {} total blocks: {}", h-1, h); quit = 1; break; } @@ -383,14 +383,14 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u if ((h-1) % display_interval == 0) { std::cout << refresh_string; - oxen::log::debug(logcat, "loading block number {}", h-1); + log::debug(logcat, "loading block number {}", h-1); } else { - oxen::log::debug(logcat, "loading block number {}", h-1); + log::debug(logcat, "loading block number {}", h-1); } b = bp.block; - oxen::log::debug(logcat, "block prev_id: {}\n", b.prev_id); + log::debug(logcat, "block prev_id: {}\n", b.prev_id); if ((h-1) % progress_interval == 0) { @@ -455,7 +455,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u catch (const std::exception& e) { std::cout << refresh_string; - oxen::log::error(logcat, "Error adding block to blockchain: {}", e.what()); + log::error(logcat, "Error adding block to blockchain: {}", e.what()); quit = 2; // make sure we don't commit partial block data break; } @@ -485,7 +485,7 @@ int import_from_file(cryptonote::core& core, const fs::path& import_file_path, u catch (const std::exception& e) { std::cout << refresh_string; - oxen::log::error(logcat, "exception while reading from file, height={}: {}", h, e.what()); + log::error(logcat, "exception while reading from file, height={}: {}", h, e.what()); return 2; } } // while @@ -514,10 +514,10 @@ quitting: } core.get_blockchain_storage().get_db().show_stats(); - oxen::log::info(logcat, "Number of blocks imported: {}", num_imported); + log::info(logcat, "Number of blocks imported: {}", num_imported); if (h > 0) // TODO: if there was an error, the last added block is probably at zero-based height h-2 - oxen::log::info(logcat, "Finished at block: {} total blocks: {}", h-1, h); + log::info(logcat, "Finished at block: {} total blocks: {}", h-1, h); std::cout << "\n"; return 0; @@ -635,7 +635,7 @@ int main(int argc, char* argv[]) } m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-import.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -644,7 +644,7 @@ int main(int argc, char* argv[]) } oxen::logging::init(log_file_path, log_level); - oxen::log::info(logcat, "Starting..."); + log::info(logcat, "Starting..."); fs::path import_file_path; @@ -660,25 +660,25 @@ int main(int argc, char* argv[]) return 0; } - oxen::log::info(logcat, "database: LMDB"); - oxen::log::info(logcat, "verify: {}", opt_verify); + log::info(logcat, "database: LMDB"); + log::info(logcat, "verify: {}", opt_verify); if (opt_batch) { - oxen::log::info(logcat, "batch: {} batch size: {}", opt_batch, db_batch_size); + log::info(logcat, "batch: {} batch size: {}", opt_batch, db_batch_size); } else { - oxen::log::info(logcat, "batch: {}", opt_batch); + log::info(logcat, "batch: {}", opt_batch); } - oxen::log::info(logcat, "resume: {}", opt_resume); - oxen::log::info(logcat, "nettype: {}", (opt_testnet ? "testnet" : opt_devnet ? "devnet" : "mainnet")); + log::info(logcat, "resume: {}", opt_resume); + log::info(logcat, "nettype: {}", (opt_testnet ? "testnet" : opt_devnet ? "devnet" : "mainnet")); - oxen::log::info(logcat, "bootstrap file path: {}", import_file_path); - oxen::log::info(logcat, "database path: {}", m_config_folder); + log::info(logcat, "bootstrap file path: {}", import_file_path); + log::info(logcat, "database path: {}", m_config_folder); if (!opt_verify) { - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "\n\ + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "\n\ Import is set to proceed WITHOUT VERIFICATION.\n\ This is a DANGEROUS operation: if the file was tampered with in transit, or obtained from a malicious source,\n\ you could end up with a compromised database. It is recommended to NOT use {}.\n\ @@ -712,9 +712,9 @@ int main(int argc, char* argv[]) if (!command_line::is_arg_defaulted(vm, arg_pop_blocks)) { num_blocks = command_line::get_arg(vm, arg_pop_blocks); - oxen::log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); + log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); pop_blocks(core, num_blocks); - oxen::log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); + log::info(logcat, "height: {}", core.get_blockchain_storage().get_current_blockchain_height()); return 0; } diff --git a/src/blockchain_utilities/blockchain_prune.cpp b/src/blockchain_utilities/blockchain_prune.cpp index c880e8534..5bdc15806 100644 --- a/src/blockchain_utilities/blockchain_prune.cpp +++ b/src/blockchain_utilities/blockchain_prune.cpp @@ -39,13 +39,13 @@ #include "blockchain_objects.h" #include "version.h" -static auto logcat = oxen::log::Cat("bcutil"); - #define MDB_val_set(var, val) MDB_val var = {sizeof(val), (void *)&val} namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + static fs::path db_path; // default to fast:1 @@ -56,7 +56,7 @@ static std::error_code replace_file(const fs::path& replacement_name, const fs:: { std::error_code ec = fs::rename(replacement_name, replaced_name); if (ec) - oxen::log::error(logcat, "Error renaming {} to {}: {}", replacement_name, replaced_name, ec.message()); + log::error(logcat, "Error renaming {} to {}: {}", replacement_name, replaced_name, ec.message()); return ec; } @@ -93,7 +93,7 @@ static void add_size(MDB_env *env, uint64_t bytes) auto si = fs::space(db_path); if(si.available < bytes) { - oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: ", + log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: ", (si.available >> 20L) << " MB available, " << (bytes >> 20L) << " MB needed"); return; } @@ -101,7 +101,7 @@ static void add_size(MDB_env *env, uint64_t bytes) catch(...) { // print something but proceed. - oxen::log::warning(logcat, "Unable to query free disk space."); + log::warning(logcat, "Unable to query free disk space."); } MDB_envinfo mei; @@ -116,7 +116,7 @@ static void add_size(MDB_env *env, uint64_t bytes) if (result) throw std::runtime_error("Failed to set new mapsize to " + std::to_string(new_mapsize) + ": " + std::string(mdb_strerror(result))); - oxen::log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); + log::info(logcat, "LMDB Mapsize increased. Old: {}MiB, New: {}MiB", mei.me_mapsize / (1024 * 1024), new_mapsize / (1024 * 1024)); } static void check_resize(MDB_env *env, size_t bytes) @@ -153,7 +153,7 @@ static void copy_table(MDB_env *env0, MDB_env *env1, const char *table, unsigned bool tx_active0 = false, tx_active1 = false; int dbr; - oxen::log::info(logcat, "Copying {}", table); + log::info(logcat, "Copying {}", table); OXEN_DEFER { if (tx_active1) mdb_txn_abort(txn1); @@ -250,7 +250,7 @@ static void prune(MDB_env *env0, MDB_env *env1) bool tx_active0 = false, tx_active1 = false; int dbr; - oxen::log::info(logcat, "Creating pruned txs_prunable"); + log::info(logcat, "Creating pruned txs_prunable"); OXEN_DEFER { if (tx_active1) mdb_txn_abort(txn1); @@ -335,7 +335,7 @@ static void prune(MDB_env *env0, MDB_env *env1) MDB_val_set(kk, ti->data.tx_id); if (block_height + PRUNING_TIP_BLOCKS >= blockchain_height) { - oxen::log::debug(logcat, "{}/{} is in tip", block_height, blockchain_height); + log::debug(logcat, "{}/{} is in tip", block_height, blockchain_height); MDB_val_set(vv, block_height); dbr = mdb_cursor_put(cur1_txs_prunable_tip, &kk, &vv, 0); if (dbr) throw std::runtime_error("Failed to write prunable tx tip data: " + std::string(mdb_strerror(dbr))); @@ -359,7 +359,7 @@ static void prune(MDB_env *env0, MDB_env *env1) } else { - oxen::log::debug(logcat, "{}/{} should be pruned, dropping", block_height, blockchain_height); + log::debug(logcat, "{}/{} should be pruned, dropping", block_height, blockchain_height); } } @@ -385,7 +385,7 @@ static bool parse_db_sync_mode(std::string db_sync_mode, uint64_t &db_flags) auto options = tools::split_any(db_sync_mode, " :", true); for(const auto &option : options) - oxen::log::debug(logcat, "option: {}", option); + log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -489,7 +489,7 @@ int main(int argc, char* argv[]) else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - oxen::log::info(logcat, "Starting..."); + log::info(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -503,7 +503,7 @@ int main(int argc, char* argv[]) uint64_t db_flags = 0; if (!parse_db_sync_mode(db_sync_mode, db_flags)) { - oxen::log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); + log::error(logcat, "Invalid db sync mode: {}", db_sync_mode); return 1; } @@ -518,7 +518,7 @@ int main(int argc, char* argv[]) // Blockchain* core_storage = new Blockchain(NULL); // because unlike blockchain_storage constructor, which takes a pointer to // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object. - oxen::log::info(logcat, "Initializing source blockchain (BlockchainDB)"); + log::info(logcat, "Initializing source blockchain (BlockchainDB)"); std::array core_storage; fs::path paths[2]; bool already_pruned = false; @@ -530,7 +530,7 @@ int main(int argc, char* argv[]) BlockchainDB* db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } @@ -541,7 +541,7 @@ int main(int argc, char* argv[]) { if (!fs::is_directory(paths[1])) { - oxen::log::error(logcat, "LMDB needs a directory path, but a file was passed: {}", paths[1].string()); + log::error(logcat, "LMDB needs a directory path, but a file was passed: {}", paths[1].string()); return 1; } } @@ -549,7 +549,7 @@ int main(int argc, char* argv[]) { if (!fs::create_directories(paths[1])) { - oxen::log::error(logcat, "Failed to create directory: {}", paths[1].string()); + log::error(logcat, "Failed to create directory: {}", paths[1].string()); return 1; } } @@ -560,7 +560,7 @@ int main(int argc, char* argv[]) paths[0] = fs::u8path(data_dir) / db->get_db_name(); } - oxen::log::info(logcat, "Loading blockchain from folder {} ...", paths[n]); + log::info(logcat, "Loading blockchain from folder {} ...", paths[n]); try { @@ -568,19 +568,19 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::error(logcat, "Error opening database: {}", e.what()); + log::error(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage[n]->init(db, nullptr /*ons_db*/, net_type); std::string source_dest = n == 0 ? "source" : "pruned"; CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize " << source_dest << " blockchain storage"); - oxen::log::info(logcat, "{} blockchain storage initialized OK", source_dest); + log::info(logcat, "{} blockchain storage initialized OK", source_dest); if (n == 0 && core_storage[0]->get_blockchain_pruning_seed()) { if (!opt_copy_pruned_database) { - oxen::log::error(logcat, "Blockchain is already pruned, use --{} to copy it anyway", arg_copy_pruned_database.name); + log::error(logcat, "Blockchain is already pruned, use --{} to copy it anyway", arg_copy_pruned_database.name); return 1; } already_pruned = true; @@ -591,7 +591,7 @@ int main(int argc, char* argv[]) core_storage[1]->deinit(); delete core_storage[1]; - oxen::log::info(logcat, "Pruning..."); + log::info(logcat, "Pruning..."); MDB_env *env0 = NULL, *env1 = NULL; open(env0, paths[0], db_flags, true); open(env1, paths[1], db_flags, false); @@ -623,16 +623,16 @@ int main(int argc, char* argv[]) close(env1); close(env0); - oxen::log::info(logcat, "Swapping databases, pre-pruning blockchain will be left in {}", paths[0].string() + "-old and can be removed if desired"); + log::info(logcat, "Swapping databases, pre-pruning blockchain will be left in {}", paths[0].string() + "-old and can be removed if desired"); fs::path old = paths[0]; old += "-old"; if (replace_file(paths[0], old) || replace_file(paths[1], paths[0])) { - oxen::log::error(logcat, "Blockchain pruned OK, but renaming failed"); + log::error(logcat, "Blockchain pruned OK, but renaming failed"); return 1; } - oxen::log::info(logcat, "Blockchain pruned OK"); + log::info(logcat, "Blockchain pruned OK"); return 0; CATCH_ENTRY("Pruning error", 1); diff --git a/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp b/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp index 71574af48..1400622b5 100644 --- a/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp +++ b/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp @@ -37,11 +37,11 @@ #include "blockchain_db/blockchain_db.h" #include "version.h" -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("bcutil"); + static std::map load_outputs(const fs::path& filename) { std::map outputs; @@ -56,7 +56,7 @@ static std::map load_outputs(const fs::path& filename) if (!f) { - oxen::log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); + log::error(logcat, "Failed to load outputs from {}: {}", filename, strerror(errno)); return {}; } while (1) @@ -79,7 +79,7 @@ static std::map load_outputs(const fs::path& filename) } if (amount == std::numeric_limits::max()) { - oxen::log::error(logcat, "Bad format in {}", filename); + log::error(logcat, "Bad format in {}", filename); continue; } if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits::max() - offset) @@ -92,7 +92,7 @@ static std::map load_outputs(const fs::path& filename) } else { - oxen::log::error(logcat, "Bad format in {}", filename); + log::error(logcat, "Bad format in {}", filename); continue; } } @@ -155,7 +155,7 @@ int main(int argc, char* argv[]) else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -165,18 +165,18 @@ int main(int argc, char* argv[]) const auto input = fs::u8path(command_line::get_arg(vm, arg_input)); - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } const fs::path filename = fs::u8path(command_line::get_arg(vm, cryptonote::arg_data_dir)) / db->get_db_name(); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -184,20 +184,20 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Source blockchain storage initialized OK"); std::map known_spent_outputs; if (input.empty()) { std::map> outputs; - oxen::log::warning(logcat, "Scanning for known spent data..."); + log::warning(logcat, "Scanning for known spent data..."); db->for_all_transactions([&](const crypto::hash &txid, const cryptonote::transaction &tx){ const bool miner_tx = tx.vin.size() == 1 && std::holds_alternative(tx.vin[0]); for (const auto &in: tx.vin) @@ -226,11 +226,11 @@ int main(int argc, char* argv[]) } else { - oxen::log::warning(logcat, "Loading known spent data..."); + log::warning(logcat, "Loading known spent data..."); known_spent_outputs = load_outputs(input); } - oxen::log::warning(logcat, "Pruning known spent data..."); + log::warning(logcat, "Pruning known spent data..."); bool stop_requested = false; tools::signal_handler::install([&stop_requested](int type) { @@ -248,22 +248,22 @@ int main(int argc, char* argv[]) if (i->first == 0) { if (opt_verbose) - oxen::log::info(logcat, "Ignoring output value {}, with {} outputs", i->first, num_outputs); + log::info(logcat, "Ignoring output value {}, with {} outputs", i->first, num_outputs); continue; } num_eligible_outputs += num_outputs; num_eligible_known_spent_outputs += i->second; if (opt_verbose) - oxen::log::info(logcat, "{}: {}/{}", i->first, i->second, num_outputs); + log::info(logcat, "{}: {}/{}", i->first, i->second, num_outputs); if (num_outputs > i->second) continue; if (num_outputs && num_outputs < i->second) { - oxen::log::error(logcat, "More outputs are spent than known for amount {}, not touching", i->first); + log::error(logcat, "More outputs are spent than known for amount {}, not touching", i->first); continue; } if (opt_verbose) - oxen::log::info(logcat, "Pruning data for {} outputs", num_outputs); + log::info(logcat, "Pruning data for {} outputs", num_outputs); if (!opt_dry_run) db->prune_outputs(i->first); num_prunable_outputs += i->second; @@ -271,13 +271,13 @@ int main(int argc, char* argv[]) db->batch_stop(); - oxen::log::info(logcat, "Total outputs: {}", num_total_outputs); - oxen::log::info(logcat, "Known spent outputs: {}", num_known_spent_outputs); - oxen::log::info(logcat, "Eligible outputs: {}", num_eligible_outputs); - oxen::log::info(logcat, "Eligible known spent outputs: {}", num_eligible_known_spent_outputs); - oxen::log::info(logcat, "Prunable outputs: {}", num_prunable_outputs); + log::info(logcat, "Total outputs: {}", num_total_outputs); + log::info(logcat, "Known spent outputs: {}", num_known_spent_outputs); + log::info(logcat, "Eligible outputs: {}", num_eligible_outputs); + log::info(logcat, "Eligible known spent outputs: {}", num_eligible_known_spent_outputs); + log::info(logcat, "Prunable outputs: {}", num_prunable_outputs); - oxen::log::warning(logcat, "Blockchain known spent data pruned OK"); + log::warning(logcat, "Blockchain known spent data pruned OK"); core_storage->deinit(); return 0; diff --git a/src/blockchain_utilities/blockchain_stats.cpp b/src/blockchain_utilities/blockchain_stats.cpp index c3046b165..1baab0cad 100644 --- a/src/blockchain_utilities/blockchain_stats.cpp +++ b/src/blockchain_utilities/blockchain_stats.cpp @@ -43,11 +43,12 @@ namespace po = boost::program_options; using namespace cryptonote; -static auto logcat = oxen::log::Cat("bcutil"); static bool stop_requested = false; int main(int argc, char* argv[]) { + static auto logcat = log::Cat("bcutil"); + TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); @@ -102,7 +103,7 @@ int main(int argc, char* argv[]) auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-stats.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -110,7 +111,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); @@ -123,18 +124,18 @@ int main(int argc, char* argv[]) bool do_ringsize = command_line::get_arg(vm, arg_ringsize); bool do_hours = command_line::get_arg(vm, arg_hours); - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } const fs::path filename = fs::u8path(opt_data_dir) / db->get_db_name(); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -142,13 +143,13 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Source blockchain storage initialized OK"); tools::signal_handler::install([](int type) { stop_requested = true; @@ -157,7 +158,7 @@ int main(int argc, char* argv[]) const uint64_t db_height = db->height(); if (!block_stop) block_stop = db_height; - oxen::log::info(logcat, "Starting from height {}, stopping at height {}", block_start, block_stop); + log::info(logcat, "Starting from height {}, stopping at height {}", block_start, block_stop); /* * The default output can be plotted with GnuPlot using these commands: @@ -212,7 +213,7 @@ plot 'stats.csv' index "DATA" using (timecolumn(1,"%Y-%m-%d")):4 with lines, '' cryptonote::block blk; if (!cryptonote::parse_and_validate_block_from_blob(bd, blk)) { - oxen::log::warning(logcat, "Bad block from db"); + log::warning(logcat, "Bad block from db"); return 1; } auto ts = std::chrono::system_clock::from_time_t(blk.timestamp); @@ -272,7 +273,7 @@ skip: transaction tx; if (!parse_and_validate_tx_base_from_blob(bd, tx)) { - oxen::log::warning(logcat, "Bad txn from db"); + log::warning(logcat, "Bad txn from db"); return 1; } currsz += bd.size(); diff --git a/src/blockchain_utilities/blockchain_usage.cpp b/src/blockchain_utilities/blockchain_usage.cpp index ef8a480e6..688e1ea17 100644 --- a/src/blockchain_utilities/blockchain_usage.cpp +++ b/src/blockchain_utilities/blockchain_usage.cpp @@ -39,7 +39,7 @@ namespace po = boost::program_options; using namespace cryptonote; -static auto logcat = oxen::log::Cat("quorum_cop"); +static auto logcat = log::Cat("quorum_cop"); struct output_data { @@ -120,7 +120,7 @@ int main(int argc, char* argv[]) auto m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); auto log_file_path = m_config_folder + "oxen-blockchain-usage.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -128,7 +128,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_devnet = command_line::get_arg(vm, cryptonote::arg_devnet_on); @@ -146,7 +146,7 @@ int main(int argc, char* argv[]) // Blockchain* core_storage = new Blockchain(NULL); // because unlike blockchain_storage constructor, which takes a pointer to // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object. - oxen::log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); + log::warning(logcat, "Initializing source blockchain (BlockchainDB)"); const std::string input = command_line::get_arg(vm, arg_input); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; @@ -154,13 +154,13 @@ int main(int argc, char* argv[]) BlockchainDB *db = new_db(); if (db == NULL) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); throw std::runtime_error("Failed to initialize a database"); } - oxen::log::warning(logcat, "database: LMDB"); + log::warning(logcat, "database: LMDB"); const fs::path filename = fs::u8path(input); - oxen::log::warning(logcat, "Loading blockchain from folder {} ...", filename); + log::warning(logcat, "Loading blockchain from folder {} ...", filename); try { @@ -168,22 +168,22 @@ int main(int argc, char* argv[]) } catch (const std::exception& e) { - oxen::log::warning(logcat, "Error opening database: {}", e.what()); + log::warning(logcat, "Error opening database: {}", e.what()); return 1; } r = core_storage->init(db, nullptr /*ons_db*/, nullptr, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); - oxen::log::warning(logcat, "Source blockchain storage initialized OK"); + log::warning(logcat, "Source blockchain storage initialized OK"); - oxen::log::warning(logcat, "Building usage patterns..."); + log::warning(logcat, "Building usage patterns..."); size_t done = 0; std::unordered_map> outputs; std::unordered_map indices; - oxen::log::warning(logcat, "Reading blockchain from {}", input); + log::warning(logcat, "Reading blockchain from {}", input); core_storage->for_all_transactions([&](const crypto::hash &hash, const cryptonote::transaction &tx)->bool { const bool coinbase = tx.vin.size() == 1 && std::holds_alternative(tx.vin[0]); @@ -228,15 +228,15 @@ int main(int argc, char* argv[]) for (const auto &c: counts) { float percent = 100.f * c.second / total; - oxen::log::info(logcat, "{} outputs used {} times ({}%)", std::to_string(c.second), c.first, percent); + log::info(logcat, "{} outputs used {} times ({}%)", std::to_string(c.second), c.first, percent); } } else { - oxen::log::info(logcat, "No outputs to process"); + log::info(logcat, "No outputs to process"); } - oxen::log::warning(logcat, "Blockchain usage exported OK"); + log::warning(logcat, "Blockchain usage exported OK"); return 0; CATCH_ENTRY("Export error", 1); diff --git a/src/blockchain_utilities/blocksdat_file.cpp b/src/blockchain_utilities/blocksdat_file.cpp index 90c70fdd7..192b64135 100644 --- a/src/blockchain_utilities/blocksdat_file.cpp +++ b/src/blockchain_utilities/blocksdat_file.cpp @@ -30,13 +30,11 @@ #include "blocksdat_file.h" #include -namespace po = boost::program_options; - using namespace cryptonote; namespace { - static auto logcat = oxen::log::Cat("bcutil"); + static auto logcat = log::Cat("bcutil"); std::string refresh_string = "\r \r"; } @@ -52,7 +50,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) { if (!fs::is_directory(dir_path)) { - oxen::log::error(logcat, "export directory path is a file: {}", dir_path); + log::error(logcat, "export directory path is a file: {}", dir_path); return false; } } @@ -60,7 +58,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) { if (!fs::create_directory(dir_path)) { - oxen::log::error(logcat, "Failed to create directory {}", dir_path); + log::error(logcat, "Failed to create directory {}", dir_path); return false; } } @@ -68,7 +66,7 @@ bool BlocksdatFile::open_writer(const fs::path& file_path, uint64_t block_stop) m_raw_data_file = new std::ofstream(); - oxen::log::info(logcat, "creating file"); + log::info(logcat, "creating file"); m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc); if (m_raw_data_file->fail()) @@ -133,21 +131,21 @@ bool BlocksdatFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem uint64_t block_start = 0; uint64_t block_stop = 0; - oxen::log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); + log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height())) { - oxen::log::info(logcat, "Using requested block height: {}", requested_block_stop); + log::info(logcat, "Using requested block height: {}", requested_block_stop); block_stop = requested_block_stop; } else { block_stop = m_blockchain_storage->get_current_blockchain_height() - 1; - oxen::log::info(logcat, "Using block height of source blockchain: {}", block_stop); + log::info(logcat, "Using block height of source blockchain: {}", block_stop); } - oxen::log::info(logcat, "Storing blocks raw data..."); + log::info(logcat, "Storing blocks raw data..."); if (!BlocksdatFile::open_writer(output_file, block_stop)) { - oxen::log::error(logcat, "failed to open raw file for write"); + log::error(logcat, "failed to open raw file for write"); return false; } for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height) @@ -167,7 +165,7 @@ bool BlocksdatFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem std::cout << refresh_string; std::cout << "block " << m_cur_height-1 << "/" << block_stop << "\n"; - oxen::log::info(logcat, "Number of blocks exported: {}", num_blocks_written); + log::info(logcat, "Number of blocks exported: {}", num_blocks_written); return BlocksdatFile::close(); } diff --git a/src/blockchain_utilities/bootstrap_file.cpp b/src/blockchain_utilities/bootstrap_file.cpp index 0c45bfc91..0d53c2348 100644 --- a/src/blockchain_utilities/bootstrap_file.cpp +++ b/src/blockchain_utilities/bootstrap_file.cpp @@ -33,8 +33,6 @@ #include "bootstrap_file.h" -static auto logcat = oxen::log::Cat("bcutil"); - namespace po = boost::program_options; using namespace cryptonote; @@ -47,6 +45,7 @@ namespace const uint32_t header_size = 1024; std::string refresh_string = "\r \r"; + auto logcat = log::Cat("bcutil"); } @@ -60,7 +59,7 @@ bool BootstrapFile::open_writer(const fs::path& file_path) { if (!fs::is_directory(dir_path)) { - oxen::log::error(logcat, "export directory path is a file: {}", dir_path); + log::error(logcat, "export directory path is a file: {}", dir_path); return false; } } @@ -68,7 +67,7 @@ bool BootstrapFile::open_writer(const fs::path& file_path) { if (!fs::create_directory(dir_path)) { - oxen::log::error(logcat, "Failed to create directory {}", dir_path); + log::error(logcat, "Failed to create directory {}", dir_path); return false; } } @@ -81,14 +80,14 @@ bool BootstrapFile::open_writer(const fs::path& file_path) if (! fs::exists(file_path)) { - oxen::log::debug(logcat, "creating file"); + log::debug(logcat, "creating file"); do_initialize_file = true; num_blocks = 0; } else { num_blocks = count_blocks(file_path.string()); - oxen::log::debug(logcat, "appending to existing file with height: {} total blocks: {}", num_blocks-1, num_blocks); + log::debug(logcat, "appending to existing file with height: {} total blocks: {}", num_blocks-1, num_blocks); } m_height = num_blocks; @@ -139,7 +138,7 @@ bool BootstrapFile::initialize_file() uint32_t bd_size = 0; std::string bd = t_serializable_object_to_blob(bfi); - oxen::log::debug(logcat, "bootstrap::file_info size: {}", bd.size()); + log::debug(logcat, "bootstrap::file_info size: {}", bd.size()); bd_size = bd.size(); try { @@ -151,7 +150,7 @@ bool BootstrapFile::initialize_file() output_stream_header << bd; bd = t_serializable_object_to_blob(bbi); - oxen::log::debug(logcat, "bootstrap::blocks_info size: {}", bd.size()); + log::debug(logcat, "bootstrap::blocks_info size: {}", bd.size()); bd_size = bd.size(); try { @@ -175,10 +174,10 @@ void BootstrapFile::flush_chunk() m_output_stream->flush(); uint32_t chunk_size = m_buffer.size(); - // oxen::log::trace(logcat, "chunk_size {}", chunk_size); + // log::trace(logcat, "chunk_size {}", chunk_size); if (chunk_size > BUFFER_SIZE) { - oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); + log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {}", chunk_size, BUFFER_SIZE); } std::string blob; @@ -200,14 +199,14 @@ void BootstrapFile::flush_chunk() long num_chars_written = pos_after - pos_before; if (static_cast(num_chars_written) != chunk_size) { - oxen::log::error(logcat, "Error writing chunk: height: {} chunk_size: {} num chars written: {}", m_cur_height, chunk_size, num_chars_written); + log::error(logcat, "Error writing chunk: height: {} chunk_size: {} num chars written: {}", m_cur_height, chunk_size, num_chars_written); throw std::runtime_error("Error writing chunk"); } m_buffer.clear(); delete m_output_stream; m_output_stream = new boost::iostreams::stream>(m_buffer); - oxen::log::debug(logcat, "flushed chunk: chunk_size: {}", chunk_size); + log::debug(logcat, "flushed chunk: chunk_size: {}", chunk_size); } void BootstrapFile::write_block(block& block) @@ -271,10 +270,10 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem m_blockchain_storage = _blockchain_storage; m_tx_pool = _tx_pool; uint64_t progress_interval = 100; - oxen::log::info(logcat, "Storing blocks raw data..."); + log::info(logcat, "Storing blocks raw data..."); if (!BootstrapFile::open_writer(output_file)) { - oxen::log::error(logcat, "failed to open raw file for write"); + log::error(logcat, "failed to open raw file for write"); return false; } block b; @@ -284,16 +283,16 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem // height. uint64_t block_start = m_height; uint64_t block_stop = 0; - oxen::log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); + log::info(logcat, "source blockchain height: {}", m_blockchain_storage->get_current_blockchain_height()-1); if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height())) { - oxen::log::info(logcat, "Using requested block height: {}", requested_block_stop); + log::info(logcat, "Using requested block height: {}", requested_block_stop); block_stop = requested_block_stop; } else { block_stop = m_blockchain_storage->get_current_blockchain_height() - 1; - oxen::log::info(logcat, "Using block height of source blockchain: {}", block_stop); + log::info(logcat, "Using block height of source blockchain: {}", block_stop); } for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height) { @@ -319,9 +318,9 @@ bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_mem std::cout << refresh_string; std::cout << "block " << m_cur_height-1 << "/" << block_stop << "\n"; - oxen::log::info(logcat, "Number of blocks exported: {}", num_blocks_written); + log::info(logcat, "Number of blocks exported: {}", num_blocks_written); if (num_blocks_written > 0) - oxen::log::info(logcat, "Largest chunk: {} bytes", m_max_chunk); + log::info(logcat, "Largest chunk: {} bytes", m_max_chunk); return BootstrapFile::close(); } @@ -345,11 +344,11 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) if (file_magic != blockchain_raw_magic) { - oxen::log::error(logcat, "bootstrap file not recognized"); + log::error(logcat, "bootstrap file not recognized"); throw std::runtime_error("Aborting"); } else - oxen::log::info(logcat, "bootstrap file recognized"); + log::info(logcat, "bootstrap file recognized"); uint32_t buflen_file_info; @@ -362,7 +361,7 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of buflen_file_info: "s + e.what()); } - oxen::log::info(logcat, "bootstrap::file_info size: {}", buflen_file_info); + log::info(logcat, "bootstrap::file_info size: {}", buflen_file_info); if (buflen_file_info > sizeof(buf1)) throw std::runtime_error("Error: bootstrap::file_info size exceeds buffer size"); @@ -376,9 +375,9 @@ uint64_t BootstrapFile::seek_to_first_chunk(fs::ifstream& import_file) } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of bootstrap::file_info: "s + e.what()); } - oxen::log::info(logcat, "bootstrap file v{}.{}", unsigned(bfi.major_version), unsigned(bfi.minor_version)); - oxen::log::info(logcat, "bootstrap magic size: {}", sizeof(file_magic)); - oxen::log::info(logcat, "bootstrap header size: {}", bfi.header_size); + log::info(logcat, "bootstrap file v{}.{}", unsigned(bfi.major_version), unsigned(bfi.minor_version)); + log::info(logcat, "bootstrap magic size: {}", sizeof(file_magic)); + log::info(logcat, "bootstrap header size: {}", bfi.header_size); uint64_t full_header_size = sizeof(file_magic) + bfi.header_size; import_file.seekg(full_header_size); @@ -398,7 +397,7 @@ uint64_t BootstrapFile::count_bytes(fs::ifstream& import_file, uint64_t blocks, import_file.read(buf1, sizeof(chunk_size)); if (!import_file) { std::cout << refresh_string; - oxen::log::debug(logcat, "End of file reached"); + log::debug(logcat, "End of file reached"); quit = true; break; } @@ -409,29 +408,29 @@ uint64_t BootstrapFile::count_bytes(fs::ifstream& import_file, uint64_t blocks, } catch (const std::exception& e) { throw std::runtime_error("Error in deserialization of chunk_size: "s + e.what()); } - oxen::log::debug(logcat, "chunk_size: {}", chunk_size); + log::debug(logcat, "chunk_size: {}", chunk_size); if (chunk_size > BUFFER_SIZE) { std::cout << refresh_string; - oxen::log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {} height: {}, offset {}", chunk_size, BUFFER_SIZE, h-1, bytes_read); + log::warning(logcat, "WARNING: chunk_size {} > BUFFER_SIZE {} height: {}, offset {}", chunk_size, BUFFER_SIZE, h-1, bytes_read); throw std::runtime_error("Aborting: chunk size exceeds buffer size"); } if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD) { std::cout << refresh_string; - oxen::log::debug(logcat, "NOTE: chunk_size {} > {} height: {}, offset {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD, h-1, bytes_read); + log::debug(logcat, "NOTE: chunk_size {} > {} height: {}, offset {}", chunk_size, CHUNK_SIZE_WARNING_THRESHOLD, h-1, bytes_read); } else if (chunk_size <= 0) { std::cout << refresh_string; - oxen::log::debug(logcat, "ERROR: chunk_size {} <= 0 height: {}, offset {}", chunk_size, h-1, bytes_read); + log::debug(logcat, "ERROR: chunk_size {} <= 0 height: {}, offset {}", chunk_size, h-1, bytes_read); throw std::runtime_error("Aborting"); } // skip to next expected block size value import_file.seekg(chunk_size, std::ios_base::cur); if (! import_file) { std::cout << refresh_string; - oxen::log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); + log::error(logcat, "ERROR: unexpected end of file: bytes read before error: {} of chunk_size {}", import_file.gcount(), chunk_size); throw std::runtime_error("Aborting"); } bytes_read += chunk_size; @@ -456,7 +455,7 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre { if (std::error_code ec; !fs::exists(import_file_path, ec)) { - oxen::log::error(logcat, "bootstrap file not found: {}", import_file_path); + log::error(logcat, "bootstrap file not found: {}", import_file_path); throw std::runtime_error("Aborting"); } fs::ifstream import_file{import_file_path, std::ios::binary}; @@ -465,14 +464,14 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre uint64_t h = 0; if (import_file.fail()) { - oxen::log::error(logcat, "import_file.open() fail"); + log::error(logcat, "import_file.open() fail"); throw std::runtime_error("Aborting"); } uint64_t full_header_size; // 4 byte magic + length of header structures full_header_size = seek_to_first_chunk(import_file); - oxen::log::info(logcat, "Scanning blockchain from bootstrap file..."); + log::info(logcat, "Scanning blockchain from bootstrap file..."); bool quit = false; uint64_t bytes_read = 0, blocks; int progress_interval = 10; @@ -492,7 +491,7 @@ uint64_t BootstrapFile::count_blocks(const fs::path& import_file_path, std::stre std::flush; // std::cout << refresh_string; - oxen::log::debug(logcat, "Number bytes scanned: {}", bytes_read); + log::debug(logcat, "Number bytes scanned: {}", bytes_read); } import_file.close(); diff --git a/src/checkpoints/checkpoints.cpp b/src/checkpoints/checkpoints.cpp index 861b99f94..4630269db 100644 --- a/src/checkpoints/checkpoints.cpp +++ b/src/checkpoints/checkpoints.cpp @@ -47,15 +47,15 @@ namespace cryptonote { - static auto logcat = oxen::log::Cat("checkpoints"); + static auto logcat = log::Cat("checkpoints"); bool checkpoint_t::check(crypto::hash const &hash) const { bool result = block_hash == hash; if (result) - oxen::log::info(logcat, "CHECKPOINT PASSED FOR HEIGHT {} {}", height, block_hash); + log::info(logcat, "CHECKPOINT PASSED FOR HEIGHT {} {}", height, block_hash); else - oxen::log::warning(logcat, "CHECKPOINT FAILED FOR HEIGHT {}. EXPECTED HASH {}GIVEN HASH: {}", height, block_hash, hash); + log::warning(logcat, "CHECKPOINT FAILED FOR HEIGHT {}. EXPECTED HASH {}GIVEN HASH: {}", height, block_hash, hash); return result; }; @@ -96,7 +96,7 @@ namespace cryptonote { if (std::error_code ec; !fs::exists(json_hashfile_fullpath, ec)) { - oxen::log::info(logcat, "Blockchain checkpoints file not found"); + log::info(logcat, "Blockchain checkpoints file not found"); return true; } @@ -105,7 +105,7 @@ namespace cryptonote !tools::slurp_file(json_hashfile_fullpath, contents) || !epee::serialization::load_t_from_json(hashes, contents)) { - oxen::log::error(logcat, "Error loading checkpoints from {}", json_hashfile_fullpath); + log::error(logcat, "Error loading checkpoints from {}", json_hashfile_fullpath); return false; } @@ -122,7 +122,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", height, e.what()); + log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", height, e.what()); return false; } } @@ -161,7 +161,7 @@ namespace cryptonote } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to add checkpoint with hash: {} at height: {}, what = {}", checkpoint.block_hash, checkpoint.height, e.what()); + log::error(logcat, "Failed to add checkpoint with hash: {} at height: {}, what = {}", checkpoint.block_hash, checkpoint.height, e.what()); result = false; } @@ -202,7 +202,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Pruning block checkpoint on block added failed non-trivially at height: {}, what = {}", m_last_cull_height, e.what()); + log::error(logcat, "Pruning block checkpoint on block added failed non-trivially at height: {}, what = {}", m_last_cull_height, e.what()); } } @@ -229,7 +229,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Remove block checkpoint on detach failed non-trivially at height: {}, what = {}", delete_height, e.what()); + log::error(logcat, "Remove block checkpoint on detach failed non-trivially at height: {}, what = {}", delete_height, e.what()); } } } diff --git a/src/common/apply_permutation.h b/src/common/apply_permutation.h index c48559b73..3724b8bb8 100644 --- a/src/common/apply_permutation.h +++ b/src/common/apply_permutation.h @@ -46,7 +46,7 @@ void apply_permutation(std::vector permutation, const F &swap) for (size_t n = 0; n < permutation.size(); ++n) if (std::find(permutation.begin(), permutation.end(), n) == permutation.end()) { - oxen::log::error(globallogcat, "Bad permutation"); + log::error(globallogcat, "Bad permutation"); throw std::runtime_error("Bad permutation"); return; } @@ -70,7 +70,7 @@ void apply_permutation(const std::vector &permutation, std::vector &v { if (permutation.size() != v.size()) { - oxen::log::error(globallogcat, "Mismatched vector sizes"); + log::error(globallogcat, "Mismatched vector sizes"); throw std::runtime_error("Mismatched vector sizes"); return; } diff --git a/src/common/command_line.h b/src/common/command_line.h index 234ebf167..b64f1c9ba 100644 --- a/src/common/command_line.h +++ b/src/common/command_line.h @@ -45,8 +45,7 @@ namespace command_line { - - static auto logcat = oxen::log::Cat("global"); + namespace log = oxen::log; inline const char* tr(const char* str) { return i18n_translate(str, "command_line"); } @@ -221,7 +220,7 @@ namespace command_line if (0 != description.find_nothrow(arg.name, false)) { if (!unique) - oxen::log::error(logcat, "Argument already exists: {}", arg.name); + log::error(globallogcat, "Argument already exists: {}", arg.name); return; } @@ -234,7 +233,7 @@ namespace command_line if (0 != description.find_nothrow(arg.name, false)) { if (!unique) - oxen::log::error(logcat, "Argument already exists: {}", arg.name); + log::error(globallogcat, "Argument already exists: {}", arg.name); return; } @@ -247,7 +246,7 @@ namespace command_line if (0 != description.find_nothrow(arg.name, false)) { if (!unique) - oxen::log::error(logcat, "Argument already exists: {}", arg.name); + log::error(globallogcat, "Argument already exists: {}", arg.name); return; } diff --git a/src/common/file.cpp b/src/common/file.cpp index 240255eb5..037991f1b 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -63,7 +63,7 @@ namespace tools { - static auto logcat = oxen::log::Cat("util"); + static auto logcat = log::Cat("util"); #ifndef _WIN32 static int flock_exnb(int fd) @@ -78,7 +78,7 @@ namespace tools { fl.l_len = 0; ret = fcntl(fd, F_SETLK, &fl); if (ret < 0) - oxen::log::error(logcat, "Error locking fd {}: {} ({})", fd, errno, strerror(errno)); + log::error(logcat, "Error locking fd {}: {} ({})", fd, errno, strerror(errno)); return ret; } #endif @@ -208,14 +208,14 @@ namespace tools { memset(&ov, 0, sizeof(ov)); if (!LockFileEx(m_fd, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ov)) { - oxen::log::error(logcat, "Failed to lock {}: {}", filename, std::error_code(GetLastError(), std::system_category())); + log::error(logcat, "Failed to lock {}: {}", filename, std::error_code(GetLastError(), std::system_category())); CloseHandle(m_fd); m_fd = INVALID_HANDLE_VALUE; } } else { - oxen::log::error(logcat, "Failed to open {}: {}", filename, std::error_code(GetLastError(), std::system_category())); + log::error(logcat, "Failed to open {}: {}", filename, std::error_code(GetLastError(), std::system_category())); } #else m_fd = open(filename.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666); @@ -223,14 +223,14 @@ namespace tools { { if (flock_exnb(m_fd) == -1) { - oxen::log::error(logcat, "Failed to lock {}: {}", filename, std::strerror(errno)); + log::error(logcat, "Failed to lock {}: {}", filename, std::strerror(errno)); close(m_fd); m_fd = -1; } } else { - oxen::log::error(logcat, "Failed to open {}: {}", filename, std::strerror(errno)); + log::error(logcat, "Failed to open {}: {}", filename, std::strerror(errno)); } #endif } @@ -265,7 +265,7 @@ namespace tools { return fs::path{psz_path}; } - oxen::log::error(logcat, "SHGetSpecialFolderPathW() failed, could not obtain requested path."); + log::error(logcat, "SHGetSpecialFolderPathW() failed, could not obtain requested path."); return ""; } #endif diff --git a/src/common/notify.cpp b/src/common/notify.cpp index 6d04e5933..5fe3281bc 100644 --- a/src/common/notify.cpp +++ b/src/common/notify.cpp @@ -35,7 +35,7 @@ namespace tools { - static auto logcat = oxen::log::Cat("notify"); + static auto logcat = log::Cat("notify"); /* TODO: diff --git a/src/common/scoped_message_writer.cpp b/src/common/scoped_message_writer.cpp index 4c5f8891c..b24e3bc47 100644 --- a/src/common/scoped_message_writer.cpp +++ b/src/common/scoped_message_writer.cpp @@ -1,8 +1,10 @@ #include "scoped_message_writer.h" -static auto logcat = oxen::log::Cat("msgwriter"); +namespace tools { -tools::scoped_message_writer::~scoped_message_writer() +static auto logcat = log::Cat("msgwriter"); + +scoped_message_writer::~scoped_message_writer() { if (m_flush) { @@ -14,3 +16,5 @@ tools::scoped_message_writer::~scoped_message_writer() std::cout << std::endl; } } + +} diff --git a/src/common/signal_handler.h b/src/common/signal_handler.h index 5e4e5628d..176842065 100644 --- a/src/common/signal_handler.h +++ b/src/common/signal_handler.h @@ -3,6 +3,7 @@ #include #include #include +#include "logging/oxen_logger.h" namespace tools { @@ -47,7 +48,7 @@ namespace tools { } else { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Got control signal {}. Exiting without saving...", type); + log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Got control signal {}. Exiting without saving...", type); return FALSE; } return TRUE; diff --git a/src/common/spawn.cpp b/src/common/spawn.cpp index f88b5b5e3..7ae7dbeaa 100644 --- a/src/common/spawn.cpp +++ b/src/common/spawn.cpp @@ -46,7 +46,7 @@ namespace tools { - static auto logcat = oxen::log::Cat("spawn"); + static auto logcat = log::Cat("spawn"); #ifndef _WIN32 static void closefrom(int fd) @@ -83,7 +83,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w // wchar_t* but out input is utf-8). Shame on you for this garbage API, Windows. if (!CreateProcessA(filename.string().c_str(), commandLine, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)) { - oxen::log::error(logcat, "CreateProcess failed. Error code {}", GetLastError()); + log::error(logcat, "CreateProcess failed. Error code {}", GetLastError()); return -1; } @@ -100,18 +100,18 @@ int spawn(const fs::path& filename, const std::vector& args, bool w DWORD result = WaitForSingleObject(pi.hProcess, INFINITE); if (result != WAIT_OBJECT_0) { - oxen::log::error(logcat, "WaitForSingleObject failed. Result {}, error code {}", result, GetLastError()); + log::error(logcat, "WaitForSingleObject failed. Result {}, error code {}", result, GetLastError()); return -1; } DWORD exitCode; if (!GetExitCodeProcess(pi.hProcess, &exitCode)) { - oxen::log::error(logcat, "GetExitCodeProcess failed. Error code {}", GetLastError()); + log::error(logcat, "GetExitCodeProcess failed. Error code {}", GetLastError()); return -1; } - oxen::log::info(logcat, "Child exited with {}", exitCode); + log::info(logcat, "Child exited with {}", exitCode); return static_cast(exitCode); #else std::vector argv(args.size() + 1); @@ -122,7 +122,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w pid_t pid = fork(); if (pid < 0) { - oxen::log::error(logcat, "Error forking: {}", strerror(errno)); + log::error(logcat, "Error forking: {}", strerror(errno)); return -1; } @@ -133,7 +133,7 @@ int spawn(const fs::path& filename, const std::vector& args, bool w close(0); char *envp[] = {NULL}; execve(filename.c_str(), argv.data(), envp); - oxen::log::error(logcat, "Failed to execve: {}", strerror(errno)); + log::error(logcat, "Failed to execve: {}", strerror(errno)); return -1; } @@ -151,22 +151,22 @@ int spawn(const fs::path& filename, const std::vector& args, bool w int wstatus = 0; pid_t w = waitpid(pid, &wstatus, WUNTRACED | WCONTINUED); if (w < 0) { - oxen::log::error(logcat, "Error waiting for child: {}", strerror(errno)); + log::error(logcat, "Error waiting for child: {}", strerror(errno)); return -1; } if (WIFEXITED(wstatus)) { - oxen::log::info(logcat, "Child exited with {}", WEXITSTATUS(wstatus)); + log::info(logcat, "Child exited with {}", WEXITSTATUS(wstatus)); return WEXITSTATUS(wstatus); } if (WIFSIGNALED(wstatus)) { - oxen::log::info(logcat, "Child killed by {}", WEXITSTATUS(wstatus)); + log::info(logcat, "Child killed by {}", WEXITSTATUS(wstatus)); return WEXITSTATUS(wstatus); } } } - oxen::log::error(logcat, "Secret passage found"); + log::error(logcat, "Secret passage found"); return -1; #endif } diff --git a/src/common/threadpool.cpp b/src/common/threadpool.cpp index 035a8a184..3f95c6362 100644 --- a/src/common/threadpool.cpp +++ b/src/common/threadpool.cpp @@ -37,7 +37,6 @@ static thread_local bool is_leaf = false; namespace tools { - static auto logcat = oxen::log::Cat("global"); threadpool::threadpool(unsigned int max_threads) : running(true), active(0) { create(max_threads); @@ -115,7 +114,7 @@ threadpool::waiter::~waiter() { std::unique_lock lock{mt}; if (num) - oxen::log::error(logcat, "wait should have been called before waiter dtor - waiting now"); + log::error(globallogcat, "wait should have been called before waiter dtor - waiting now"); } catch (...) { /* ignore */ } try diff --git a/src/common/util.cpp b/src/common/util.cpp index 5f593f76f..66185eedb 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -55,7 +55,7 @@ namespace tools { - static auto logcat = oxen::log::Cat("util"); + static auto logcat = log::Cat("util"); bool disable_core_dumps() { @@ -65,7 +65,7 @@ namespace tools rlimit.rlim_cur = rlimit.rlim_max = 0; if (setrlimit(RLIMIT_CORE, &rlimit)) { - oxen::log::warning(logcat, "Failed to disable core dumps"); + log::warning(logcat, "Failed to disable core dumps"); return false; } #endif @@ -78,7 +78,7 @@ namespace tools struct rlimit rlim; if (getrlimit(RLIMIT_MEMLOCK, &rlim) < 0) { - oxen::log::error(logcat, "Failed to determine the lockable memory limit"); + log::error(logcat, "Failed to determine the lockable memory limit"); return -1; } return rlim.rlim_cur; @@ -92,7 +92,7 @@ namespace tools #ifdef __GLIBC__ const char *ver = ::gnu_get_libc_version(); if (!strcmp(ver, "2.25")) - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Running with glibc {}, hangs may occur - change glibc version if possible", ver)); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Running with glibc {}, hangs may occur - change glibc version if possible", ver)); #endif return true; diff --git a/src/cryptonote_basic/account.cpp b/src/cryptonote_basic/account.cpp index d2fac1c9a..4d0bfbe10 100644 --- a/src/cryptonote_basic/account.cpp +++ b/src/cryptonote_basic/account.cpp @@ -49,7 +49,7 @@ DISABLE_VS_WARNINGS(4244 4345) namespace cryptonote { - static auto logcat = oxen::log::Cat("account"); + static auto logcat = log::Cat("account"); //----------------------------------------------------------------- hw::device& account_keys::get_device() const { @@ -58,7 +58,7 @@ DISABLE_VS_WARNINGS(4244 4345) //----------------------------------------------------------------- void account_keys::set_device( hw::device &hwdev) { m_device = &hwdev; - oxen::log::debug(oxen::log::Cat("device"), "account_keys::set_device device type: {}", tools::type_name(typeid(hwdev))); + log::debug(log::Cat("device"), "account_keys::set_device device type: {}", tools::type_name(typeid(hwdev))); } //----------------------------------------------------------------- static void derive_key(const crypto::chacha_key &base_key, crypto::chacha_key &key) @@ -141,7 +141,7 @@ DISABLE_VS_WARNINGS(4244 4345) try{ m_keys.get_device().disconnect(); } catch (const std::exception &e){ - oxen::log::error(logcat, "Device disconnect exception: {}", e.what()); + log::error(logcat, "Device disconnect exception: {}", e.what()); } } //----------------------------------------------------------------- @@ -205,7 +205,7 @@ DISABLE_VS_WARNINGS(4244 4345) void account_base::create_from_device(hw::device &hwdev) { m_keys.set_device(hwdev); - oxen::log::debug(oxen::log::Cat("device"), "device type: {}", tools::type_name(typeid(hwdev))); + log::debug(log::Cat("device"), "device type: {}", tools::type_name(typeid(hwdev))); CHECK_AND_ASSERT_THROW_MES(hwdev.init(), "Device init failed"); CHECK_AND_ASSERT_THROW_MES(hwdev.connect(), "Device connect failed"); try { diff --git a/src/cryptonote_basic/cryptonote_basic.h b/src/cryptonote_basic/cryptonote_basic.h index 4bb3e6503..b76e53bfa 100644 --- a/src/cryptonote_basic/cryptonote_basic.h +++ b/src/cryptonote_basic/cryptonote_basic.h @@ -228,7 +228,7 @@ namespace cryptonote { if (out_index >= output_unlock_times.size()) { - oxen::log::error(globallogcat, "Tried to get unlock time of a v3 transaction with missing output unlock time"); + log::error(globallogcat, "Tried to get unlock time of a v3 transaction with missing output unlock time"); return unlock_time; } return output_unlock_times[out_index]; diff --git a/src/cryptonote_basic/cryptonote_basic_impl.cpp b/src/cryptonote_basic/cryptonote_basic_impl.cpp index cd7fc3227..2c6871949 100644 --- a/src/cryptonote_basic/cryptonote_basic_impl.cpp +++ b/src/cryptonote_basic/cryptonote_basic_impl.cpp @@ -44,7 +44,7 @@ namespace cryptonote { - static auto logcat = oxen::log::Cat("cn"); + static auto logcat = log::Cat("cn"); struct integrated_address { account_public_address adr; @@ -133,7 +133,7 @@ namespace cryptonote { } if(current_block_weight > 2 * median_weight) { - oxen::log::error(logcat, "Block cumulative weight is too big: {}, expected less than {}", current_block_weight, 2 * median_weight); + log::error(logcat, "Block cumulative weight is too big: {}, expected less than {}", current_block_weight, 2 * median_weight); return false; } @@ -225,7 +225,7 @@ namespace cryptonote { uint64_t prefix{0}; if (!tools::base58::decode_addr(str, prefix, data)) { - oxen::log::debug(logcat, "Invalid address format"); + log::debug(logcat, "Invalid address format"); return false; } @@ -245,7 +245,7 @@ namespace cryptonote { info.has_payment_id = false; } else { - oxen::log::info(logcat, "Wrong address prefix: {}, expected {} or {} or {}", prefix, address_prefix, integrated_address_prefix, subaddress_prefix); + log::info(logcat, "Wrong address prefix: {}, expected {} or {} or {}", prefix, address_prefix, integrated_address_prefix, subaddress_prefix); return false; } @@ -262,13 +262,13 @@ namespace cryptonote { serialization::parse_binary(data, info.address); } } catch (const std::exception& e) { - oxen::log::info(logcat, "Account public address keys can't be parsed: "s + e.what()); + log::info(logcat, "Account public address keys can't be parsed: "s + e.what()); return false; } if (!crypto::check_key(info.address.m_spend_public_key) || !crypto::check_key(info.address.m_view_public_key)) { - oxen::log::info(logcat, "Failed to validate address keys"); + log::info(logcat, "Failed to validate address keys"); return false; } diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index 5bf22ac62..d016b8f11 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -55,11 +55,11 @@ using namespace crypto; -#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {oxen::log::warning(logcat, message); throw std::runtime_error(message);}} +#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {log::warning(logcat, message); throw std::runtime_error(message);}} namespace cryptonote { - static auto logcat = oxen::log::Cat("cn"); + static auto logcat = log::Cat("cn"); static inline unsigned char *operator &(ec_point &point) { return &reinterpret_cast(point); @@ -135,14 +135,14 @@ namespace cryptonote return true; if (rv.outPk.size() != tx.vout.size()) { - oxen::log::info(logcat, "Failed to parse transaction from blob, bad outPk size in tx {}", get_transaction_hash(tx)); + log::info(logcat, "Failed to parse transaction from blob, bad outPk size in tx {}", get_transaction_hash(tx)); return false; } for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n) { if (!std::holds_alternative(tx.vout[n].target)) { - oxen::log::info(logcat, "Unsupported output type in tx {}", get_transaction_hash(tx)); + log::info(logcat, "Unsupported output type in tx {}", get_transaction_hash(tx)); return false; } rv.outPk[n].dest = rct::pk2rct(var::get(tx.vout[n].target).key); @@ -155,18 +155,18 @@ namespace cryptonote { if (rv.p.bulletproofs.size() != 1) { - oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs size in tx {}", get_transaction_hash(tx)); + log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs size in tx {}", get_transaction_hash(tx)); return false; } if (rv.p.bulletproofs[0].L.size() < 6) { - oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs L size in tx {}", get_transaction_hash(tx)); + log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs L size in tx {}", get_transaction_hash(tx)); return false; } const size_t max_outputs = 1 << (rv.p.bulletproofs[0].L.size() - 6); if (max_outputs < tx.vout.size()) { - oxen::log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs max outputs in tx {}", get_transaction_hash(tx)); + log::info(logcat, "Failed to parse transaction from blob, bad bulletproofs max outputs in tx {}", get_transaction_hash(tx)); return false; } const size_t n_amounts = tx.vout.size(); @@ -197,7 +197,7 @@ namespace cryptonote try { serialization::serialize(ba, tx); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse and validate transaction from blob: {}", e.what()); + log::error(logcat, "Failed to parse and validate transaction from blob: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data"); @@ -212,7 +212,7 @@ namespace cryptonote try { tx.serialize_base(ba); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse transaction base from blob: {}", e.what()); + log::error(logcat, "Failed to parse transaction base from blob: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, "Failed to expand transaction data"); @@ -226,7 +226,7 @@ namespace cryptonote try { serialization::value(ba, tx); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse transaction prefix from blob: {}", e.what()); + log::error(logcat, "Failed to parse transaction prefix from blob: {}", e.what()); return false; } return true; @@ -238,7 +238,7 @@ namespace cryptonote try { serialization::serialize(ba, tx); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse and validate transaction from blob + hash: {}", e.what()); + log::error(logcat, "Failed to parse and validate transaction from blob + hash: {}", e.what()); return false; } CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, "Failed to expand transaction data"); @@ -270,7 +270,7 @@ namespace cryptonote bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); if (!r) { - oxen::log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", tx_public_key, ack.m_view_secret_key); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", tx_public_key, ack.m_view_secret_key); memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation)); } @@ -281,7 +281,7 @@ namespace cryptonote r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); if (!r) { - oxen::log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], ack.m_view_secret_key); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], ack.m_view_secret_key); } else { @@ -528,7 +528,7 @@ namespace cryptonote try { serialization::deserialize_all(ar, tx_extra_fields); } catch (const std::exception& e) { - oxen::log::warning(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); + log::warning(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); return false; } @@ -549,7 +549,7 @@ namespace cryptonote for (auto& f : tx_extra_fields) serialization::value(ar, f); } catch (const std::exception& e) { - oxen::log::info(logcat, "failed to serialize tx extra field: {}", e.what()); + log::info(logcat, "failed to serialize tx extra field: {}", e.what()); return false; } @@ -611,7 +611,7 @@ namespace cryptonote tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys }; if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) { - oxen::log::info(logcat, "failed to serialize tx extra additional tx pub keys"); + log::info(logcat, "failed to serialize tx extra additional tx pub keys"); return false; } return true; @@ -684,7 +684,7 @@ namespace cryptonote tx_extra_field field = proofs; if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) { - oxen::log::info(logcat, "failed to serialize tx extra tx key image proof"); + log::info(logcat, "failed to serialize tx extra tx key image proof"); return false; } @@ -696,7 +696,7 @@ namespace cryptonote tx_extra_field field = unlock; if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) { - oxen::log::info(logcat, "failed to serialize tx extra tx key image unlock"); + log::info(logcat, "failed to serialize tx extra tx key image unlock"); return false; } return true; @@ -731,7 +731,7 @@ namespace cryptonote if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) { - oxen::log::info(logcat, "failed to serialize tx extra registration tx"); + log::info(logcat, "failed to serialize tx extra registration tx"); return false; } @@ -794,7 +794,7 @@ namespace cryptonote value(newar, field); } while (ar.remaining_bytes() > 0); } catch (const std::exception& e) { - oxen::log::info(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); + log::info(logcat, "{}: failed to deserialize extra field: {}; extra = {}", __func__, e.what(), oxenc::to_hex(tx_extra.begin(), tx_extra.end())); return false; } @@ -854,7 +854,7 @@ namespace cryptonote tx_extra_field field = tx_extra_burn{burn}; if (!add_tx_extra_field_to_tx_extra(tx_extra, field)) { - oxen::log::info(logcat, "failed to serialize tx extra burn amount"); + log::info(logcat, "failed to serialize tx extra burn amount"); return false; } return true; @@ -903,13 +903,13 @@ namespace cryptonote { if (!tx.is_transfer() && tx.vout.size() != 0) { - oxen::log::warning(logcat, "tx type: {} must have 0 outputs, received: {}, id={}", transaction::type_to_string(tx.type), tx.vout.size(), get_transaction_hash(tx)); + log::warning(logcat, "tx type: {} must have 0 outputs, received: {}, id={}", transaction::type_to_string(tx.type), tx.vout.size(), get_transaction_hash(tx)); return false; } if (tx.version >= txversion::v3_per_output_unlock_times && tx.vout.size() != tx.output_unlock_times.size()) { - oxen::log::warning(logcat, "tx version: {} must have equal number of output unlock times and outputs", transaction::version_to_string(tx.version)); + log::warning(logcat, "tx version: {} must have equal number of output unlock times and outputs", transaction::version_to_string(tx.version)); return false; } @@ -924,7 +924,7 @@ namespace cryptonote { if (out.amount <= 0) { - oxen::log::warning(logcat, "zero amount output in transaction id={}", get_transaction_hash(tx)); + log::warning(logcat, "zero amount output in transaction id={}", get_transaction_hash(tx)); return false; } } @@ -1227,7 +1227,7 @@ namespace cryptonote const_cast(t).rct_signatures.p.serialize_rctsig_prunable( ba, t.rct_signatures.type, t.vin.size(), t.vout.size(), mixin); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to serialize rct signatures (prunable): {}", e.what()); + log::error(logcat, "Failed to serialize rct signatures (prunable): {}", e.what()); return false; } cryptonote::get_blob_hash(ba.str(), res); @@ -1314,7 +1314,7 @@ namespace cryptonote try { tt.rct_signatures.serialize_rctsig_base(ba, t.vin.size(), t.vout.size()); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to serialize rct signatures base: {}", e.what()); + log::error(logcat, "Failed to serialize rct signatures base: {}", e.what()); return false; } cryptonote::get_blob_hash(ba.str(), hashes[1]); @@ -1327,7 +1327,7 @@ namespace cryptonote } else if (!calculate_transaction_prunable_hash(t, &blob, hashes[2])) { - oxen::log::error(logcat, "Failed to get tx prunable hash"); + log::error(logcat, "Failed to get tx prunable hash"); return false; } @@ -1447,7 +1447,7 @@ namespace cryptonote try { serialization::serialize(ba, b); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse block from blob: {}", e.what()); + log::error(logcat, "Failed to parse block from blob: {}", e.what()); return false; } b.invalidate_hashes(); diff --git a/src/cryptonote_basic/cryptonote_format_utils.h b/src/cryptonote_basic/cryptonote_format_utils.h index f54c1b4e3..ac71e511a 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.h +++ b/src/cryptonote_basic/cryptonote_format_utils.h @@ -273,7 +273,7 @@ namespace cryptonote blob = serialization::dump_binary(const_cast&>(val)); return true; } catch (const std::exception& e) { - oxen::log::error(globallogcat, "Serialization of {} failed: {}", tools::type_name(typeid(T)), e.what()); + log::error(globallogcat, "Serialization of {} failed: {}", tools::type_name(typeid(T)), e.what()); return false; } } @@ -318,7 +318,7 @@ namespace cryptonote try { serialize(ar, obj); } catch (const std::exception& e) { - oxen::log::error(globallogcat, "obj_to_json_str failed: serialization failed: {}", e.what()); + log::error(globallogcat, "obj_to_json_str failed: serialization failed: {}", e.what()); return ""s; } return ss.str(); diff --git a/src/cryptonote_basic/miner.cpp b/src/cryptonote_basic/miner.cpp index 5587b1845..caf5a1dd7 100644 --- a/src/cryptonote_basic/miner.cpp +++ b/src/cryptonote_basic/miner.cpp @@ -53,7 +53,7 @@ extern "C" void rx_slow_hash_free_state(); namespace cryptonote { - static auto logcat = oxen::log::Cat("miner"); + static auto logcat = log::Cat("miner"); namespace { @@ -103,7 +103,7 @@ namespace cryptonote if(!m_phandler->create_next_miner_block_template(bl, m_mine_address, di, height, expected_reward, ""s)) { - oxen::log::error(logcat, "Failed to get_block_template(), stopping mining"); + log::error(logcat, "Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di, height, expected_reward); @@ -148,7 +148,7 @@ namespace cryptonote address_parse_info info; if(!cryptonote::get_account_address_from_str(info, nettype, command_line::get_arg(vm, arg_start_mining)) || info.is_subaddress) { - oxen::log::error(logcat, "Target account address {} has wrong format, starting daemon canceled", command_line::get_arg(vm, arg_start_mining)); + log::error(logcat, "Target account address {} has wrong format, starting daemon canceled", command_line::get_arg(vm, arg_start_mining)); return false; } m_mine_address = info.address; @@ -185,13 +185,13 @@ namespace cryptonote std::unique_lock lock{m_threads_lock}; if(is_mining()) { - oxen::log::error(logcat, "Starting miner but it's already started"); + log::error(logcat, "Starting miner but it's already started"); return false; } if(!m_threads.empty()) { - oxen::log::error(logcat, "Unable to start miner because there are active mining threads"); + log::error(logcat, "Unable to start miner because there are active mining threads"); return false; } @@ -200,12 +200,12 @@ namespace cryptonote m_stop = false; m_stop_height = stop_after > 0 ? m_height + stop_after : std::numeric_limits::max(); if (stop_after > 0) - oxen::log::info(logcat, "Mining until height {}", m_stop_height); + log::info(logcat, "Mining until height {}", m_stop_height); for (int i = 0; i < m_threads_total; i++) m_threads.emplace_back([=] { return worker_thread(i, slow_mining); }); - oxen::log::info(logcat, "Mining has started with {} threads, good luck!", m_threads_total); + log::info(logcat, "Mining has started with {} threads, good luck!", m_threads_total); return true; } @@ -223,13 +223,13 @@ namespace cryptonote //----------------------------------------------------------------------------------------------------- bool miner::stop() { - oxen::log::trace(logcat, "Miner has received stop signal"); + log::trace(logcat, "Miner has received stop signal"); std::unique_lock lock{m_threads_lock}; bool mining = !m_threads.empty(); if (!mining) { - oxen::log::trace(logcat, "Not mining - nothing to stop" ); + log::trace(logcat, "Not mining - nothing to stop" ); return true; } @@ -238,7 +238,7 @@ namespace cryptonote if (th.joinable()) th.join(); - oxen::log::info(logcat, "Mining has been stopped, {} finished", m_threads.size()); + log::info(logcat, "Mining has been stopped, {} finished", m_threads.size()); m_threads.clear(); rx_stop_mining(); return true; @@ -272,29 +272,29 @@ namespace cryptonote void miner::pause() { std::unique_lock lock{m_miners_count_mutex}; - oxen::log::debug(logcat, "miner::pause: {} -> {}", m_pausers_count, (m_pausers_count + 1)); + log::debug(logcat, "miner::pause: {} -> {}", m_pausers_count, (m_pausers_count + 1)); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) - oxen::log::debug(logcat, "MINING PAUSED"); + log::debug(logcat, "MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { std::unique_lock lock{m_miners_count_mutex}; - oxen::log::debug(logcat, "miner::resume: {} -> {}", m_pausers_count, (m_pausers_count - 1)); + log::debug(logcat, "miner::resume: {} -> {}", m_pausers_count, (m_pausers_count - 1)); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; - oxen::log::error(logcat, "Unexpected miner::resume() called"); + log::error(logcat, "Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) - oxen::log::debug(logcat, "MINING RESUMED"); + log::debug(logcat, "MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread(uint32_t index, bool slow_mining) { - oxen::log::info(logcat, "Miner thread was started [{}]", index); + log::info(logcat, "Miner thread was started [{}]", index); uint32_t nonce = m_starter_nonce + index; uint64_t height = 0; difficulty_type local_diff = 0; @@ -325,7 +325,7 @@ namespace cryptonote if(!local_template_ver)//no any set_block_template call { - oxen::log::debug(logcat, "Block template not set yet"); + log::debug(logcat, "Block template not set yet"); std::this_thread::sleep_for(1s); continue; } @@ -345,7 +345,7 @@ namespace cryptonote if(check_hash(h, local_diff)) { //we lucky! - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Found block {} at height {} for difficulty: {}", get_block_hash(b), height, local_diff)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Found block {} at height {} for difficulty: {}", get_block_hash(b), height, local_diff)); cryptonote::block_verification_context bvc; m_phandler->handle_block_found(b, bvc); } @@ -354,7 +354,7 @@ namespace cryptonote ++m_hashes; } rx_slow_hash_free_state(); - oxen::log::info(logcat, "Miner thread stopped [{}]", index); + log::info(logcat, "Miner thread stopped [{}]", index); if (call_stop) // Call in a detached thread because the thread calling stop() needs to be able to join this // worker thread. diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index a4c3dd3e2..1917e0493 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -90,7 +90,7 @@ using namespace crypto; using namespace cryptonote; -static auto logcat = oxen::log::Cat("blockchain"); +static auto logcat = log::Cat("blockchain"); DISABLE_VS_WARNINGS(4267) @@ -124,7 +124,7 @@ Blockchain::Blockchain(tx_memory_pool& tx_pool, service_nodes::service_node_list m_batch_success(true), m_prepare_height(0) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); } //------------------------------------------------------------------ Blockchain::~Blockchain() @@ -135,7 +135,7 @@ Blockchain::~Blockchain() //------------------------------------------------------------------ bool Blockchain::have_tx(const crypto::hash &id) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -145,7 +145,7 @@ bool Blockchain::have_tx(const crypto::hash &id) const //------------------------------------------------------------------ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -159,7 +159,7 @@ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const template bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, visitor_t &vis, const crypto::hash &tx_prefix_hash, uint64_t* pmax_related_block_height) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // ND: Disable locking and make method private. //std::unique_lock lock{*this}; @@ -194,13 +194,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi m_db->get_output_key(epee::span(&tx_in_to_key.amount, 1), absolute_offsets, outputs, true); if (absolute_offsets.size() != outputs.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); + log::error(log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } catch (...) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); + log::error(log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } @@ -209,7 +209,7 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi // check for partial results and add the rest if needed; if (outputs.size() < absolute_offsets.size() && outputs.size() > 0) { - oxen::log::debug(logcat, "Additional outputs needed: {}", absolute_offsets.size() - outputs.size()); + log::debug(logcat, "Additional outputs needed: {}", absolute_offsets.size() - outputs.size()); std::vector < uint64_t > add_offsets; std::vector add_outputs; add_outputs.reserve(absolute_offsets.size() - outputs.size()); @@ -220,13 +220,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi m_db->get_output_key(epee::span(&tx_in_to_key.amount, 1), add_offsets, add_outputs, true); if (add_offsets.size() != add_outputs.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); + log::error(log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } } catch (...) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); + log::error(log::Cat("verify"), "Output does not exist! amount = {}", tx_in_to_key.amount); return false; } outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end()); @@ -250,13 +250,13 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi // call to the passed boost visitor to grab the public key for the output if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to handle_output for output no = {}, with absolute offset {}", count, i); + log::error(log::Cat("verify"), "Failed to handle_output for output no = {}, with absolute offset {}", count, i); return false; } } catch (...) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist! amount = {}, absolute_offset = {}", tx_in_to_key.amount, i); + log::error(log::Cat("verify"), "Output does not exist! amount = {}, absolute_offset = {}", tx_in_to_key.amount, i); return false; } @@ -274,12 +274,12 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi } catch (const OUTPUT_DNE& e) { - oxen::log::error(oxen::log::Cat("verify"), "Output does not exist: {}", e.what()); + log::error(log::Cat("verify"), "Output does not exist: {}", e.what()); return false; } catch (const TX_DNE& e) { - oxen::log::error(oxen::log::Cat("verify"), "Transaction does not exist: {}", e.what()); + log::error(log::Cat("verify"), "Transaction does not exist: {}", e.what()); return false; } @@ -290,7 +290,7 @@ bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, vi //------------------------------------------------------------------ uint64_t Blockchain::get_current_blockchain_height(bool lock) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -329,7 +329,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() int64_t const total_blocks = static_cast(end_height) - static_cast(start_height); if (total_blocks <= 0) return true; if (total_blocks > 1) - oxen::log::info(logcat, "Loading blocks into oxen subsystems, scanning blockchain from height: {} to: {} (snl: {}, ons: {}, sqlite: {})", start_height, end_height, snl_height, ons_height, sqlite_height); + log::info(logcat, "Loading blocks into oxen subsystems, scanning blockchain from height: {} to: {} (snl: {}, ons: {}, sqlite: {})", start_height, end_height, snl_height, ons_height, sqlite_height); using clock = std::chrono::steady_clock; using dseconds = std::chrono::duration; @@ -347,7 +347,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() if (duration >= 10s) { m_service_node_list.store(); - oxen::log::info(logcat, "... scanning height {} ({:.3f}s) (snl: {:.3f}s, ons: {:.3f}s, batch: {:.3f}s)", + log::info(logcat, "... scanning height {} ({:.3f}s) (snl: {:.3f}s, ons: {:.3f}s, batch: {:.3f}s)", start_height + (index * BLOCK_COUNT), duration.count(), snl_iteration_duration.count(), @@ -372,7 +372,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() uint64_t height = start_height + (index * BLOCK_COUNT); if (!get_blocks_only(height, static_cast(BLOCK_COUNT), blocks)) { - oxen::log::error(logcat, "Unable to get checkpointed historical blocks for updating oxen subsystems"); + log::error(logcat, "Unable to get checkpointed historical blocks for updating oxen subsystems"); return false; } @@ -383,7 +383,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() std::vector txs; if (!get_transactions(blk.tx_hashes, txs)) { - oxen::log::error(logcat, "Unable to get transactions for block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); + log::error(logcat, "Unable to get transactions for block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); return false; } @@ -399,7 +399,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() try { m_service_node_list.block_add(blk, txs, checkpoint_ptr); } catch (const std::exception& e) { - oxen::log::error(logcat, "Unable to process block for updating service node list: {}", e.what()); + log::error(logcat, "Unable to process block for updating service node list: {}", e.what()); return false; } snl_iteration_duration += clock::now() - snl_start; @@ -410,7 +410,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() auto ons_start = clock::now(); if (!m_ons_db.add_block(blk, txs)) { - oxen::log::error(logcat, "Unable to process block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); + log::error(logcat, "Unable to process block for updating ONS DB: {}", cryptonote::get_block_hash(blk)); return false; } ons_iteration_duration += clock::now() - ons_start; @@ -421,7 +421,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() auto sqlite_start = clock::now(); if (!m_service_node_list.process_batching_rewards(blk)) { - oxen::log::error(logcat, "Unable to process block for updating SQLite DB: {}", cryptonote::get_block_hash(blk)); + log::error(logcat, "Unable to process block for updating SQLite DB: {}", cryptonote::get_block_hash(blk)); return false; } sqlite_iteration_duration += clock::now() - sqlite_start; @@ -431,7 +431,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() if (total_blocks > 1) { - oxen::log::info(logcat, "Done recalculating oxen subsystems in {:.2f}s ({:.2f}s snl; {:.2f}s ons; {:.2f}s batch)", + log::info(logcat, "Done recalculating oxen subsystems in {:.2f}s ({:.2f}s snl; {:.2f}s ons; {:.2f}s batch)", dseconds{clock::now() - scan_start}.count(), snl_duration.count(), ons_duration.count(), sqlite_duration.count()); } @@ -446,7 +446,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptr sqlite_db, const network_type nettype, bool offline, const cryptonote::test_options *test_options, difficulty_type fixed_difficulty, const GetCheckpointsCallback& get_checkpoints/* = nullptr*/) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); CHECK_AND_ASSERT_MES(nettype != network_type::FAKECHAIN || test_options, false, "fake chain network type used without options"); @@ -454,12 +454,12 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptris_open()) { - oxen::log::error(logcat, "Attempted to init Blockchain with unopened DB"); + log::error(logcat, "Attempted to init Blockchain with unopened DB"); delete db; return false; } @@ -490,7 +490,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrheight()) { - oxen::log::info(logcat, "Blockchain not loaded, generating genesis block."); + log::info(logcat, "Blockchain not loaded, generating genesis block."); block bl; block_verification_context bvc{}; generate_genesis_block(bl, m_nettype); @@ -527,7 +527,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrheight() - 1, epee::misc_utils::get_time_interval_string(timestamp_diff)); + log::info(logcat, "Blockchain initialized. last block: {}, {} time ago", m_db->height() - 1, epee::misc_utils::get_time_interval_string(timestamp_diff)); rtxn_guard.stop(); uint64_t num_popped_blocks = 0; @@ -540,15 +540,15 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptr 0) - oxen::log::info(logcat, "Initial popping done, top block: {}, top height: {}, block version: {}", top_id, top_height, (uint64_t)top_block.major_version); + log::info(logcat, "Initial popping done, top block: {}, top height: {}, block version: {}", top_id, top_height, (uint64_t)top_block.major_version); break; } else { if (num_popped_blocks == 0) - oxen::log::info(logcat, "Current top block {} at height {} has version {} which disagrees with the ideal version {}", top_id, top_height, (uint64_t)top_block.major_version, (uint64_t)ideal_hf_version); + log::info(logcat, "Current top block {} at height {} has version {} which disagrees with the ideal version {}", top_id, top_height, (uint64_t)top_block.major_version, (uint64_t)ideal_hf_version); if (num_popped_blocks % 100 == 0) - oxen::log::info(logcat, "Popping blocks... {}", top_height); + log::info(logcat, "Popping blocks... {}", top_height); ++num_popped_blocks; block popped_block; std::vector popped_txs; @@ -557,7 +557,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrpop_block(popped_block, popped_txs); if (!m_service_node_list.pop_batching_rewards_block(popped_block)) { - oxen::log::error(logcat, "Failed to pop to batch rewards DB. throwing"); + log::error(logcat, "Failed to pop to batch rewards DB. throwing"); throw std::runtime_error("Failed to pop to batch reward DB."); } } @@ -565,12 +565,12 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptris_read_only() && !load_missing_blocks_into_oxen_subsystems()) { - oxen::log::error(logcat, "Failed to load blocks into oxen subsystems"); + log::error(logcat, "Failed to load blocks into oxen subsystems"); return false; } @@ -616,7 +616,7 @@ bool Blockchain::init(BlockchainDB* db, sqlite3 *ons_db, std::shared_ptrclose(); - oxen::log::trace(logcat, "Local blockchain read/write activity stopped successfully"); + log::trace(logcat, "Local blockchain read/write activity stopped successfully"); } } catch (const std::exception& e) { - oxen::log::error(logcat, std::string("Error closing blockchain db: ") + e.what()); + log::error(logcat, std::string("Error closing blockchain db: ") + e.what()); } catch (...) { - oxen::log::error(logcat, "There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); + log::error(logcat, "There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); } delete m_db; @@ -703,7 +703,7 @@ void Blockchain::pop_blocks(uint64_t nblocks) { if (nblocks >= BLOCKS_PER_DAY && (i != 0 && (i % blocks_per_update == 0))) { - oxen::log::info(logcat, "... popping blocks {}% completed, height: {} ({}s)", + log::info(logcat, "... popping blocks {}% completed, height: {} ({}s)", (++progress * PERCENT_PER_PROGRESS_UPDATE), (blockchain_height - i), std::chrono::duration{std::chrono::steady_clock::now() - pop_blocks_started}.count() ); @@ -714,7 +714,7 @@ void Blockchain::pop_blocks(uint64_t nblocks) } catch (const std::exception& e) { - oxen::log::error(logcat, "Error when popping blocks after processing {} blocks: {}", i, e.what()); + log::error(logcat, "Error when popping blocks after processing {} blocks: {}", i, e.what()); if (stop_batch) m_db->batch_abort(); return; @@ -736,7 +736,7 @@ void Blockchain::pop_blocks(uint64_t nblocks) // from it to the tx_pool block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; @@ -755,18 +755,18 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) // so we re-throw catch (const std::exception& e) { - oxen::log::error(logcat, "Error popping block from blockchain: {}", e.what()); + log::error(logcat, "Error popping block from blockchain: {}", e.what()); throw; } catch (...) { - oxen::log::error(logcat, "Error popping block from blockchain, throwing!"); + log::error(logcat, "Error popping block from blockchain, throwing!"); throw; } if (pop_batching_rewards && !m_service_node_list.pop_batching_rewards_block(popped_block)) { - oxen::log::error(logcat, "Failed to pop to batch rewards DB"); + log::error(logcat, "Failed to pop to batch rewards DB"); throw std::runtime_error("Failed to pop batch rewards DB"); } @@ -795,12 +795,12 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) bool r = m_tx_pool.add_tx(tx, tvc, tx_pool_options::from_block(), version); if (!r) { - oxen::log::error(logcat, "Error returning transaction to tx_pool"); + log::error(logcat, "Error returning transaction to tx_pool"); } } } if (pruned) - oxen::log::warning(logcat, "{} pruned txes could not be added back to the txpool", pruned); + log::warning(logcat, "{} pruned txes could not be added back to the txpool", pruned); m_blocks_longhash_table.clear(); m_scan_table.clear(); @@ -814,7 +814,7 @@ block Blockchain::pop_block_from_blockchain(bool pop_batching_rewards = true) //------------------------------------------------------------------ bool Blockchain::reset_and_set_genesis_block(const block& b) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; invalidate_block_template_cache(); @@ -834,14 +834,14 @@ bool Blockchain::reset_and_set_genesis_block(const block& b) //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id(uint64_t& height) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; return m_db->top_block_hash(&height); } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -859,7 +859,7 @@ crypto::hash Blockchain::get_tail_id() const */ void Blockchain::get_short_chain_history(std::list& ids) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t sz = m_db->height(); if(!sz) @@ -877,7 +877,7 @@ void Blockchain::get_short_chain_history(std::list& ids) const //------------------------------------------------------------------ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -891,12 +891,12 @@ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const } catch (const std::exception& e) { - oxen::log::error(logcat, std::string("Something went wrong fetching block hash by height: ") + e.what()); + log::error(logcat, std::string("Something went wrong fetching block hash by height: ") + e.what()); throw; } catch (...) { - oxen::log::error(logcat, std::string("Something went wrong fetching block hash by height")); + log::error(logcat, std::string("Something went wrong fetching block hash by height")); throw; } return null_hash; @@ -911,7 +911,7 @@ crypto::hash Blockchain::get_pending_block_id_by_height(uint64_t height) const //------------------------------------------------------------------ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // try to find block in main chain @@ -931,7 +931,7 @@ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orph { if (!cryptonote::parse_and_validate_block_from_blob(blob, blk)) { - oxen::log::error(logcat, "Found block {} in alt chain, but failed to parse it", h); + log::error(logcat, "Found block {} in alt chain, but failed to parse it", h); throw std::runtime_error("Found block in alt chain, but failed to parse it"); } if (orphan) @@ -941,12 +941,12 @@ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk, bool *orph } catch (const std::exception& e) { - oxen::log::error(logcat, std::string("Something went wrong fetching block by hash: ") + e.what()); + log::error(logcat, std::string("Something went wrong fetching block by hash: ") + e.what()); throw; } catch (...) { - oxen::log::error(logcat, std::string("Something went wrong fetching block hash by hash")); + log::error(logcat, std::string("Something went wrong fetching block hash by hash")); throw; } @@ -970,7 +970,7 @@ bool Blockchain::get_block_by_height(uint64_t height, block &blk) const // less blocks than desired if there aren't enough. difficulty_type Blockchain::get_difficulty_for_next_block(bool pulse) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); if (m_fixed_difficulty) { return m_db->height() ? m_fixed_difficulty : 1; @@ -1030,7 +1030,7 @@ std::vector Blockchain::get_last_block_timestamps(unsigned int blocks) c // that had been removed. bool Blockchain::rollback_blockchain_switching(const std::list& original_chain, uint64_t rollback_height) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // fail if rollback_height passed is too high @@ -1061,10 +1061,10 @@ bool Blockchain::rollback_blockchain_switching(const std::listbatch_start(); - oxen::log::debug(logcat, "Rolling back to height {}", rollback_height); + log::debug(logcat, "Rolling back to height {}", rollback_height); bool ret = rollback_blockchain_switching({}, rollback_height); if (stop_batch) m_db->batch_stop(); @@ -1084,7 +1084,7 @@ bool Blockchain::blink_rollback(uint64_t rollback_height) // boolean based on success therein. bool Blockchain::switch_to_alternative_blockchain(const std::list& alt_chain, bool keep_disconnected_chain) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_cache.m_timestamps_and_difficulties_height = 0; @@ -1095,7 +1095,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listblock_exists(alt_chain.front().bl.prev_id)) { - oxen::log::error(logcat, "Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); + log::error(logcat, "Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); return false; } @@ -1129,7 +1129,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listremove_alt_block(blkid); alt_ch_iter++; @@ -1159,7 +1159,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listheight())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "REORGANIZE SUCCESS! on height: {}, new blockchain size: {}", split_height, m_db->height())); return true; } //------------------------------------------------------------------ @@ -1197,7 +1197,7 @@ difficulty_type Blockchain::get_difficulty_for_alternative_chain(const std::list if (pulse) return PULSE_FIXED_DIFFICULTY; - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); uint64_t block_count = 0; { @@ -1278,24 +1278,24 @@ difficulty_type Blockchain::get_difficulty_for_alternative_chain(const std::list // a non-overflowing tx amount (dubious necessity on this check) bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, hf hf_version) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); if (b.miner_tx.vout.size() > 0) { CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs"); CHECK_AND_ASSERT_MES(std::holds_alternative(b.miner_tx.vin[0]), false, "coinbase transaction in the block has the wrong type"); if (var::get(b.miner_tx.vin[0]).height != height) { - oxen::log::warning(logcat, "The miner transaction in block has invalid height: {}, expected: {}", var::get(b.miner_tx.vin[0]).height, height); + log::warning(logcat, "The miner transaction in block has invalid height: {}, expected: {}", var::get(b.miner_tx.vin[0]).height, height); return false; } - oxen::log::debug(logcat, "Miner tx hash: {}", get_transaction_hash(b.miner_tx)); + log::debug(logcat, "Miner tx hash: {}", get_transaction_hash(b.miner_tx)); CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction has the wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + MINED_MONEY_UNLOCK_WINDOW); if (hf_version >= hf::hf12_checkpointing) { if (b.miner_tx.type != txtype::standard) { - oxen::log::error(logcat, "Coinbase invalid transaction type for coinbase transaction."); + log::error(logcat, "Coinbase invalid transaction type for coinbase transaction."); return false; } @@ -1303,7 +1303,7 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, txversion max_version = transaction::get_min_version_for_hf(hf_version); if (b.miner_tx.version < min_version || b.miner_tx.version > max_version) { - oxen::log::error(oxen::log::Cat("verify"), "Coinbase invalid version: {} for hardfork: {} min/max version: {}/{}", b.miner_tx.version, static_cast(hf_version), min_version, max_version); + log::error(log::Cat("verify"), "Coinbase invalid version: {} for hardfork: {} min/max version: {}/{}", b.miner_tx.version, static_cast(hf_version), min_version, max_version); return false; } } @@ -1317,7 +1317,7 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, // does not overflow a uint64_t, and this transaction *is* a uint64_t... if(!check_outs_overflow(b.miner_tx)) { - oxen::log::error(logcat, "miner transaction has money overflow in block {}", get_block_hash(b)); + log::error(logcat, "miner transaction has money overflow in block {}", get_block_hash(b)); return false; } } @@ -1328,12 +1328,12 @@ bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height, // This function validates the miner transaction reward bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_weight, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, hf version) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); //validate reward uint64_t const money_in_use = get_outs_money_amount(b.miner_tx); if (b.miner_tx.vout.size() == 0) { if (b.major_version < hf::hf19_reward_batching) { - oxen::log::error(oxen::log::Cat("verify"), "miner tx has no outputs"); + log::error(log::Cat("verify"), "miner tx has no outputs"); return false; } } @@ -1356,7 +1356,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl block_reward_context.height = height; if (!calc_batched_governance_reward(height, block_reward_context.batched_governance)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to calculate batched governance reward"); + log::error(log::Cat("verify"), "Failed to calculate batched governance reward"); return false; } @@ -1379,7 +1379,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl try { hook(hook_data); } catch (const std::exception& e) { - oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Miner tx failed validation: {}", e.what())); + log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Miner tx failed validation: {}", e.what())); return false; } } @@ -1388,13 +1388,13 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl { if (version >= hf::hf10_bulletproofs && reward_parts.governance_paid == 0) { - oxen::log::error(logcat, "Governance reward should not be 0 after hardfork v10 if this height has a governance output because it is the batched payout height"); + log::error(logcat, "Governance reward should not be 0 after hardfork v10 if this height has a governance output because it is the batched payout height"); return false; } if (b.miner_tx.vout.back().amount != reward_parts.governance_paid) { - oxen::log::error(logcat, "Governance reward amount incorrect. Should be: {}, is: {}", print_money(reward_parts.governance_paid), print_money(b.miner_tx.vout.back().amount)); + log::error(logcat, "Governance reward amount incorrect. Should be: {}, is: {}", print_money(reward_parts.governance_paid), print_money(b.miner_tx.vout.back().amount)); return false; } @@ -1406,7 +1406,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl var::get(b.miner_tx.vout.back().target).key, m_nettype)) { - oxen::log::error(logcat, "Governance reward public key incorrect."); + log::error(logcat, "Governance reward public key incorrect."); return false; } } @@ -1425,7 +1425,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl if (money_in_use > max_money_in_use) { - oxen::log::error(oxen::log::Cat("verify"), "coinbase transaction spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(money_in_use), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); + log::error(log::Cat("verify"), "coinbase transaction spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(money_in_use), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); return false; } @@ -1436,7 +1436,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl if (b.reward > reward_parts.base_miner + reward_parts.miner_fee + reward_parts.service_node_total) { - oxen::log::error(oxen::log::Cat("verify"), "block reward to be batched spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(b.reward), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); + log::error(log::Cat("verify"), "block reward to be batched spends too much money ({}). Maximum block reward is {} (= {} base + {} fees)", print_money(b.reward), print_money(max_money_in_use), print_money(max_base_reward), print_money(reward_parts.miner_fee)); return false; } @@ -1446,7 +1446,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl // get the block weights of the last blocks, and return by reference . void Blockchain::get_last_n_blocks_weights(std::vector& weights, size_t count) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto h = m_db->height(); @@ -1461,7 +1461,7 @@ void Blockchain::get_last_n_blocks_weights(std::vector& weights, size_ //------------------------------------------------------------------ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, size_t count) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; @@ -1479,7 +1479,7 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si if (cached) { - oxen::log::trace(logcat, "requesting {} from {}, cached", count, start_height); + log::trace(logcat, "requesting {} from {}, cached", count, start_height); return m_long_term_block_weights_cache_rolling_median.median(); } @@ -1490,14 +1490,14 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si crypto::hash old_tip_hash = m_db->get_block_hash_from_height(tip_height - 1); if (old_tip_hash == m_long_term_block_weights_cache_tip_hash) { - oxen::log::trace(logcat, "requesting {} from {}, incremental", count, start_height); + log::trace(logcat, "requesting {} from {}, incremental", count, start_height); m_long_term_block_weights_cache_tip_hash = tip_hash; m_long_term_block_weights_cache_rolling_median.insert(m_db->get_block_long_term_weight(tip_height)); return m_long_term_block_weights_cache_rolling_median.median(); } } - oxen::log::trace(logcat, "requesting {} from {}, uncached", count, start_height); + log::trace(logcat, "requesting {} from {}, uncached", count, start_height); std::vector weights = m_db->get_long_term_block_weights(start_height, count); m_long_term_block_weights_cache_tip_hash = tip_hash; m_long_term_block_weights_cache_rolling_median.clear(); @@ -1508,13 +1508,13 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_limit() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); return m_current_block_cumul_weight_limit; } //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_block_weight_median() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); return m_current_block_cumul_weight_median; } //------------------------------------------------------------------ @@ -1526,7 +1526,7 @@ uint64_t Blockchain::get_current_cumulative_block_weight_median() const // This function makes a new block for a miner to mine the hash for bool Blockchain::create_block_template_internal(block& b, const crypto::hash *from_block, const block_template_info& info, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const std::string& ex_nonce) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); size_t median_weight; uint64_t already_generated_coins; uint64_t pool_cookie; @@ -1540,7 +1540,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr // just after the block template was created if (info.miner_address != m_btc_address && m_btc_nonce == ex_nonce && m_btc_pool_cookie == m_tx_pool.cookie() && m_btc.prev_id == get_tail_id()) { - oxen::log::debug(logcat, "Using cached template"); + log::debug(logcat, "Using cached template"); const uint64_t now = time(NULL); if (m_btc.timestamp < now /*ensures it can't get below the median of the last few blocks*/ || !info.is_miner) m_btc.timestamp = now; @@ -1550,7 +1550,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr expected_reward = m_btc_expected_reward; return true; } - oxen::log::debug(logcat, "Not using cached template: address {}, nonce {}, cookie {}, from_block {}", (bool)(info.miner_address != m_btc_address), (m_btc_nonce == ex_nonce), (m_btc_pool_cookie == m_tx_pool.cookie()), (!!from_block)); + log::debug(logcat, "Not using cached template: address {}, nonce {}, cookie {}, from_block {}", (bool)(info.miner_address != m_btc_address), (m_btc_nonce == ex_nonce), (m_btc_pool_cookie == m_tx_pool.cookie()), (!!from_block)); invalidate_block_template_cache(); } @@ -1565,7 +1565,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr bool parent_in_main = m_db->block_exists(*from_block); if (!parent_in_alt && !parent_in_main) { - oxen::log::error(logcat, "Unknown from block"); + log::error(logcat, "Unknown from block"); return false; } @@ -1656,7 +1656,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr : oxen_miner_tx_context::pulse_block(m_nettype, info.service_node_payout, m_service_node_list.get_block_leader()); if (!calc_batched_governance_reward(height, miner_tx_context.batched_governance)) { - oxen::log::error(logcat, "Failed to calculate batched governance reward"); + log::error(logcat, "Failed to calculate batched governance reward"); return false; } @@ -1695,11 +1695,11 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr if (cumulative_weight != txs_weight + get_transaction_weight(b.miner_tx)) { //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_weight - oxen::log::debug(logcat, "Miner tx creation has no luck with delta_extra size = {} and {}", delta, delta - 1); + log::debug(logcat, "Miner tx creation has no luck with delta_extra size = {} and {}", delta, delta - 1); cumulative_weight += delta - 1; continue; } - oxen::log::debug(logcat, "Setting extra for block: {}, try_count={}", b.miner_tx.extra.size(), try_count); + log::debug(logcat, "Setting extra for block: {}, try_count={}", b.miner_tx.extra.size(), try_count); } } CHECK_AND_ASSERT_MES(cumulative_weight == txs_weight + get_transaction_weight(b.miner_tx), false, "unexpected case: cumulative_weight=" << cumulative_weight << " is not equal txs_cumulative_weight=" << txs_weight << " + get_transaction_weight(b.miner_tx)=" << get_transaction_weight(b.miner_tx)); @@ -1716,7 +1716,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr b.height = height; return true; } - oxen::log::error(logcat, "Failed to create_block_template with {} tries", 10); + log::error(logcat, "Failed to create_block_template with {} tries", 10); return false; } //------------------------------------------------------------------ @@ -1751,7 +1751,7 @@ bool Blockchain::create_next_pulse_block_template(block& b, const service_nodes: // the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector& timestamps) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; @@ -1847,7 +1847,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // make sure alt chain doesn't somehow start past the end of the main chain if (blockchain_height < alt_chain.front().height) { - oxen::log::info(logcat, "main blockchain wrong height: {}, alt_chain: {}", m_db->height(), alt_chain.front().height); + log::info(logcat, "main blockchain wrong height: {}, alt_chain: {}", m_db->height(), alt_chain.front().height); failed = true; } @@ -1855,7 +1855,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // this alternate chain with it. if (!failed && !m_db->block_exists(alt_chain.front().bl.prev_id)) { - oxen::log::info(logcat, "alternate chain does not appear to connect to main chain...: {}", alt_chain.front().bl.prev_id); + log::info(logcat, "alternate chain does not appear to connect to main chain...: {}", alt_chain.front().bl.prev_id); failed = true; } @@ -1863,13 +1863,13 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, auto h = m_db->get_block_hash_from_height(alt_chain.front().height - 1); if (!failed && h != alt_chain.front().bl.prev_id) { - oxen::log::info(logcat, "alternative chain has wrong connection to main chain: {}, mismatched with: {}", h, alt_chain.front().bl.prev_id); + log::info(logcat, "alternative chain has wrong connection to main chain: {}, mismatched with: {}", h, alt_chain.front().bl.prev_id); failed = true; } if (!failed && !m_checkpoints.is_alternative_block_allowed(blockchain_height, alt_chain.front().height, nullptr /*service_node_checkpoint*/)) { - oxen::log::debug(logcat, "alternative chain is too old to consider: {}", h); + log::debug(logcat, "alternative chain is too old to consider: {}", h); failed = true; } @@ -1907,7 +1907,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, // a long forked chain eventually. bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc, checkpoint_t const *checkpoint) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t const blk_height = get_block_height(b); @@ -1920,7 +1920,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id if (!(parent_in_main || parent_in_alt)) { bvc.m_marked_as_orphaned = true; - oxen::log::error(oxen::log::Cat("verify"), "Block recognized as orphaned and rejected, id = {}, height {}, parent in alt {}, parent in main {} (parent {}, current top {}, chain height {})", id, blk_height, parent_in_alt, parent_in_main, b.prev_id, get_tail_id(), chain_height); + log::error(log::Cat("verify"), "Block recognized as orphaned and rejected, id = {}, height {}, parent in alt {}, parent in main {} (parent {}, current top {}, chain height {})", id, blk_height, parent_in_alt, parent_in_main, b.prev_id, get_tail_id(), chain_height); return true; } @@ -1946,7 +1946,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id // (not earlier than the median of the last X blocks in the built alt chain) if(!check_block_timestamp(std::move(timestamps), b)) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} for alternative chain, has invalid timestamp: {}", id, b.timestamp); + log::error(log::Cat("verify"), "Block with id: {} for alternative chain, has invalid timestamp: {}", id, b.timestamp); bvc.m_verifivation_failed = true; return false; } @@ -2010,7 +2010,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_base_from_blob(blob, tx)) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} (as alternative) refers to unparsable transaction hash {}.", tools::type_to_hex(id), txid); + log::error(log::Cat("verify"), "Block with id: {} (as alternative) refers to unparsable transaction hash {}.", tools::type_to_hex(id), txid); bvc.m_verifivation_failed = true; return false; } @@ -2050,7 +2050,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id { if (!service_node_checkpoint) { - oxen::log::error(logcat, "CHECKPOINT VALIDATION FAILED FOR ALT BLOCK"); + log::error(logcat, "CHECKPOINT VALIDATION FAILED FOR ALT BLOCK"); bvc.m_verifivation_failed = true; return false; } @@ -2074,14 +2074,14 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id std::string blob; if (!m_tx_pool.get_transaction(missed_tx, blob)) { - oxen::log::error(oxen::log::Cat("verify"), "Alternative block references unknown TX, rejected alt block {} {}", blk_height, id); + log::error(log::Cat("verify"), "Alternative block references unknown TX, rejected alt block {} {}", blk_height, id); return false; } transaction tx; if (!parse_and_validate_tx_from_blob(blob, tx)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to parse block blob from tx pool when querying the missed transactions in block {} {}", blk_height, id); + log::error(log::Cat("verify"), "Failed to parse block blob from tx pool when querying the missed transactions in block {} {}", blk_height, id); return false; } @@ -2094,7 +2094,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id try { hook(hook_data); } catch (const std::exception& e) { - oxen::log::info(logcat, "Failed to add alt block: {}", e.what()); + log::info(logcat, "Failed to add alt block: {}", e.what()); return false; } } @@ -2116,7 +2116,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id std::vector blocks; if (!get_blocks_only(start, end - start, blocks, nullptr /*txs*/)) { - oxen::log::error(logcat, "Unexpected failure to query blocks for alt chain switching calculation from {} to {}", start, (end - 1)); + log::error(logcat, "Unexpected failure to query blocks for alt chain switching calculation from {} to {}", start, (end - 1)); return false; } @@ -2166,7 +2166,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id if (!pulse_block) stream << " PoW: " << blk_pow.proof_of_work; stream << " difficulty: " << current_diff; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "{}", stream.str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "{}", stream.str())); return true; } } @@ -2182,12 +2182,12 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id bool keep_alt_chain = false; if (alt_chain_has_more_checkpoints) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {}, checkpoint is found in alternative chain on height {}", alt_chain.front().height, m_db->height() - 1, blk_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {}, checkpoint is found in alternative chain on height {}", alt_chain.front().height, m_db->height() - 1, blk_height)); } else { keep_alt_chain = true; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); } bool r = switch_to_alternative_blockchain(alt_chain, keep_alt_chain); @@ -2199,7 +2199,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); return true; } } @@ -2207,7 +2207,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id { if (alt_chain_has_greater_pow) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); bool r = switch_to_alternative_blockchain(alt_chain, true); if (r) bvc.m_added_to_main_chain = true; @@ -2217,7 +2217,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); return true; } } @@ -2228,7 +2228,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id //------------------------------------------------------------------ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vector& blocks, std::vector* txs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; const uint64_t height = m_db->height(); if(start_offset >= height) @@ -2244,7 +2244,7 @@ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vecto } catch(std::exception const &e) { - oxen::log::error(logcat, "Invalid block at height {}. {}", start_offset + i, e.what()); + log::error(logcat, "Invalid block at height {}. {}", start_offset + i, e.what()); return false; } } @@ -2264,7 +2264,7 @@ bool Blockchain::get_blocks_only(uint64_t start_offset, size_t count, std::vecto //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks, std::vector& txs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; if(start_offset >= m_db->height()) return false; @@ -2286,7 +2286,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; const uint64_t height = m_db->height(); if(start_offset >= height) @@ -2299,7 +2299,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vectorget_block_blob_from_height(start_offset + i), block{}); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { - oxen::log::error(logcat, "Invalid block"); + log::error(logcat, "Invalid block"); return false; } } @@ -2315,7 +2315,7 @@ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::vector& blocks) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; blocks.reserve(m_db->get_alt_block_count()); m_db->for_all_alt_blocks([&blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string *block_blob, const std::string *checkpoint_blob) { if (!block_blob) { - oxen::log::error(logcat, "No blob, but blobs were requested"); + log::error(logcat, "No blob, but blobs were requested"); return false; } cryptonote::block bl; if (cryptonote::parse_and_validate_block_from_blob(*block_blob, bl)) blocks.push_back(std::move(bl)); else - oxen::log::error(logcat, "Failed to parse block from blob"); + log::error(logcat, "Failed to parse block from blob"); return true; }, true); return true; @@ -2450,7 +2450,7 @@ bool Blockchain::get_alternative_blocks(std::vector& blocks) const //------------------------------------------------------------------ size_t Blockchain::get_alternative_blocks_count() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; return m_db->get_alt_block_count(); } @@ -2484,7 +2484,7 @@ crypto::public_key Blockchain::get_output_key(uint64_t amount, uint64_t global_i //------------------------------------------------------------------ bool Blockchain::get_outs(const rpc::GET_OUTPUTS_BIN::request& req, rpc::GET_OUTPUTS_BIN::response& res) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; res.outs.clear(); @@ -2504,7 +2504,7 @@ bool Blockchain::get_outs(const rpc::GET_OUTPUTS_BIN::request& req, rpc::GET_OUT m_db->get_output_key(epee::span(amounts.data(), amounts.size()), offsets, data); if (data.size() != req.outputs.size()) { - oxen::log::error(logcat, "Unexpected output data size: expected {}, got {}", req.outputs.size(), data.size()); + log::error(logcat, "Unexpected output data size: expected {}, got {}", req.outputs.size(), data.size()); return false; } for (const auto &t: data) @@ -2584,14 +2584,14 @@ void Blockchain::get_output_blacklist(std::vector &blacklist) const // This is used to see what to send another node that needs to sync. bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, uint64_t& starter_offset) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // make sure the request includes at least the genesis block, otherwise // how can we expect to sync from the client that the block list came from? if(qblock_ids.empty()) { - oxen::log::info(oxen::log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, dropping connection", qblock_ids.size()); + log::info(log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, dropping connection", qblock_ids.size()); return false; } @@ -2601,7 +2601,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc auto gen_hash = m_db->get_block_hash_from_height(0); if(qblock_ids.back() != gen_hash) { - oxen::log::info(oxen::log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: id: {}, expected: {}, dropping connection", qblock_ids.back(), gen_hash); + log::info(log::Cat("net.p2p"), "Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block mismatch: id: {}, expected: {}, dropping connection", qblock_ids.back(), gen_hash); return false; } @@ -2618,7 +2618,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc } catch (const std::exception& e) { - oxen::log::warning(logcat, "Non-critical error trying to find block by hash in BlockchainDB, hash: {}", *bl_it); + log::warning(logcat, "Non-critical error trying to find block by hash in BlockchainDB, hash: {}", *bl_it); return false; } } @@ -2627,7 +2627,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc // but just in case... if(bl_it == qblock_ids.end()) { - oxen::log::error(logcat, "Internal error handling connection, can't find split point"); + log::error(logcat, "Internal error handling connection, can't find split point"); return false; } @@ -2638,7 +2638,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc //------------------------------------------------------------------ uint64_t Blockchain::block_difficulty(uint64_t i) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -2649,7 +2649,7 @@ uint64_t Blockchain::block_difficulty(uint64_t i) const } catch (const BLOCK_DNE& e) { - oxen::log::error(logcat, "Attempted to get block difficulty for height above blockchain height"); + log::error(logcat, "Attempted to get block difficulty for height above blockchain height"); } return 0; } @@ -2658,7 +2658,7 @@ uint64_t Blockchain::block_difficulty(uint64_t i) const // alternatively, return true only if no blocks missed bool Blockchain::get_blocks(const std::vector& block_ids, std::vector>& blocks, std::unordered_set* missed_bs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; blocks.reserve(block_ids.size()); @@ -2672,7 +2672,7 @@ bool Blockchain::get_blocks(const std::vector& block_ids, std::vec blocks.push_back(std::make_pair(m_db->get_block_blob_from_height(height), block())); if (!parse_and_validate_block_from_blob(blocks.back().first, blocks.back().second)) { - oxen::log::error(logcat, "Invalid block: {}", block_hash); + log::error(logcat, "Invalid block: {}", block_hash); blocks.pop_back(); if (missed_bs) missed_bs->insert(block_hash); } @@ -2692,7 +2692,7 @@ bool Blockchain::get_blocks(const std::vector& block_ids, std::vec // alternatively, return true only if no transactions missed bool Blockchain::get_transactions_blobs(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs, bool pruned) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2718,7 +2718,7 @@ bool Blockchain::get_transactions_blobs(const std::vector& txs_ids //------------------------------------------------------------------ std::vector Blockchain::get_transactions_heights(const std::vector& txs_ids) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto heights = m_db->get_tx_block_heights(txs_ids); @@ -2742,7 +2742,7 @@ size_t get_transaction_version(const std::string &bd) //------------------------------------------------------------------ bool Blockchain::get_split_transactions_blobs(const std::vector& txs_ids, std::vector>& txs, std::unordered_set* missed_txs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2756,7 +2756,7 @@ bool Blockchain::get_split_transactions_blobs(const std::vector& t auto& [hash, pruned, pruned_hash, prunable] = txs.emplace_back(tx_hash, std::move(tx), crypto::null_hash, std::string()); if (!is_v1_tx(pruned) && !m_db->get_prunable_tx_hash(tx_hash, pruned_hash)) { - oxen::log::error(logcat, "Prunable data hash not found for {}", tx_hash); + log::error(logcat, "Prunable data hash not found for {}", tx_hash); return false; } if (!m_db->get_prunable_tx_blob(tx_hash, prunable)) @@ -2775,7 +2775,7 @@ bool Blockchain::get_split_transactions_blobs(const std::vector& t //------------------------------------------------------------------ bool Blockchain::get_transactions(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; txs.reserve(txs_ids.size()); @@ -2790,7 +2790,7 @@ bool Blockchain::get_transactions(const std::vector& txs_ids, std: txs.emplace_back(); if (!parse_and_validate_tx_from_blob(tx, txs.back())) { - oxen::log::error(logcat, "Invalid transaction"); + log::error(logcat, "Invalid transaction"); return false; } } @@ -2810,7 +2810,7 @@ bool Blockchain::get_transactions(const std::vector& txs_ids, std: // BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes. bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, std::vector& hashes, uint64_t& start_height, uint64_t& current_height, bool clip_pruned) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // if we can't find the split point, return false @@ -2840,7 +2840,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc bool Blockchain::find_blockchain_supplement(const std::list& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; bool result = find_blockchain_supplement(qblock_ids, resp.m_block_ids, resp.start_height, resp.total_height, true); @@ -2856,7 +2856,7 @@ bool Blockchain::find_blockchain_supplement(const std::list& qbloc // blocks by reference. bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, const std::list& qblock_ids, std::vector, std::vector > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_count) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; // if a specific start height has been requested @@ -2915,11 +2915,11 @@ bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, cons //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(cryptonote::block const &block) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto i_res = m_invalid_blocks.insert(get_block_hash(block)); CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid block returned status failed"); - oxen::log::info(logcat, "BLOCK ADDED AS INVALID: {}\n, prev_id={}, m_invalid_blocks count={}", (*i_res.first), block.prev_id, m_invalid_blocks.size()); + log::info(logcat, "BLOCK ADDED AS INVALID: {}\n, prev_id={}, m_invalid_blocks count={}", (*i_res.first), block.prev_id, m_invalid_blocks.size()); return true; } @@ -2931,31 +2931,31 @@ hf Blockchain::get_network_version(std::optional height) const { //------------------------------------------------------------------ void Blockchain::flush_invalid_blocks() { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; m_invalid_blocks.clear(); } //------------------------------------------------------------------ bool Blockchain::have_block(const crypto::hash& id) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; if(m_db->block_exists(id)) { - oxen::log::debug(logcat, "block {} found in main chain", id); + log::debug(logcat, "block {} found in main chain", id); return true; } if(m_db->get_alt_block(id, NULL, NULL, NULL)) { - oxen::log::debug(logcat, "block {} found in alternative chains", id); + log::debug(logcat, "block {} found in alternative chains", id); return true; } if(m_invalid_blocks.count(id)) { - oxen::log::debug(logcat, "block {} found in m_invalid_blocks", id); + log::debug(logcat, "block {} found in m_invalid_blocks", id); return true; } @@ -2964,7 +2964,7 @@ bool Blockchain::have_block(const crypto::hash& id) const //------------------------------------------------------------------ size_t Blockchain::get_total_transactions() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // WARNING: this function does not take m_blockchain_lock, and thus should only call read only // m_db functions which do not depend on one another (ie, no getheight + gethash(height-1), as // well as not accessing class members, even read only (ie, m_invalid_blocks). The caller must @@ -2981,7 +2981,7 @@ size_t Blockchain::get_total_transactions() const // remove them later if the block fails validation. bool Blockchain::check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; auto add_transaction_input_visitor = [&keys_this_block, this](const auto& in) { using T = std::decay_t; @@ -3007,7 +3007,7 @@ bool Blockchain::check_for_double_spend(const transaction& tx, key_images_contai { if (!var::visit(add_transaction_input_visitor, in)) { - oxen::log::error(logcat, "Double spend detected!"); + log::error(logcat, "Double spend detected!"); return false; } } @@ -3017,12 +3017,12 @@ bool Blockchain::check_for_double_spend(const transaction& tx, key_images_contai //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector>& indexs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { - oxen::log::error(oxen::log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); + log::error(log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); return false; } indexs = m_db->get_tx_amount_output_indices(tx_index, n_txes); @@ -3033,12 +3033,12 @@ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector& indexs) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { - oxen::log::error(oxen::log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); + log::error(log::Cat("verify"), "get_tx_outputs_gindexs failed to find transaction with id = {}", tx_id); return false; } std::vector> indices = m_db->get_tx_amount_output_indices(tx_index, 1); @@ -3060,7 +3060,7 @@ void Blockchain::on_new_tx_from_block(const cryptonote::transaction &tx) size_t ring_size = 0; if (!tx.vin.empty() && std::holds_alternative(tx.vin[0])) ring_size = var::get(tx.vin[0]).key_offsets.size(); - oxen::log::info(logcat, "HASH: - I/M/O: {}/{}/{} H: {} chcktx: {}", tx.vin.size(), ring_size, tx.vout.size(), 0, tools::friendly_duration(std::chrono::steady_clock::now() - a)); + log::info(logcat, "HASH: - I/M/O: {}/{}/{} H: {} chcktx: {}", tx.vin.size(), ring_size, tx.vout.size(), 0, tools::friendly_duration(std::chrono::steady_clock::now() - a)); } } #endif @@ -3076,7 +3076,7 @@ void Blockchain::on_new_tx_from_block(const cryptonote::transaction &tx) // as a return-by-reference. bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block, std::unordered_set* key_image_conflicts) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; #if defined(PER_BLOCK_CHECKPOINT) @@ -3096,7 +3096,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_heigh size_t ring_size = 0; if (!tx.vin.empty() && std::holds_alternative(tx.vin[0])) ring_size = var::get(tx.vin[0]).key_offsets.size(); - oxen::log::info(logcat, "HASH: {} I/M/O: {}/{}/{} H: {} ms: {} B: {} W: {}", get_transaction_hash(tx), tx.vin.size(), ring_size, tx.vout.size(), max_used_block_height, tools::friendly_duration(std::chrono::steady_clock::now() - a + m_fake_scan_time), get_object_blobsize(tx), get_transaction_weight(tx)); + log::info(logcat, "HASH: {} I/M/O: {}/{}/{} H: {} ms: {} B: {} W: {}", get_transaction_hash(tx), tx.vin.size(), ring_size, tx.vout.size(), max_used_block_height, tools::friendly_duration(std::chrono::steady_clock::now() - a + m_fake_scan_time), get_object_blobsize(tx), get_transaction_weight(tx)); } if (!res) return false; @@ -3109,7 +3109,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_heigh //------------------------------------------------------------------ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context &tvc) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); std::unique_lock lock{*this}; for (const auto &o: tx.vout) { @@ -3137,7 +3137,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context const bool bulletproof = rct::is_rct_bulletproof(tx.rct_signatures.type); if (bulletproof || !tx.rct_signatures.p.bulletproofs.empty()) { - oxen::log::error(oxen::log::Cat("verify"), "Bulletproofs are not allowed before v10"); + log::error(log::Cat("verify"), "Bulletproofs are not allowed before v10"); tvc.m_invalid_output = true; return false; } @@ -3150,7 +3150,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (auto hf10_height = hard_fork_begins(m_nettype, hf::hf10_bulletproofs); hf10_height && height > *hf10_height) { - oxen::log::error(oxen::log::Cat("verify"), "Borromean range proofs are not allowed after v10"); + log::error(log::Cat("verify"), "Borromean range proofs are not allowed after v10"); tvc.m_invalid_output = true; return false; } @@ -3159,7 +3159,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (hf_version < feature::SMALLER_BP) { if (tx.rct_signatures.type == rct::RCTType::Bulletproof2) { - oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::Bulletproof2, static_cast(feature::SMALLER_BP)); + log::error(log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::Bulletproof2, static_cast(feature::SMALLER_BP)); tvc.m_invalid_output = true; return false; } @@ -3170,7 +3170,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context { if (tx.rct_signatures.type == rct::RCTType::Bulletproof) { - oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed after v{}", (unsigned)rct::RCTType::Bulletproof, static_cast(feature::SMALLER_BP)); + log::error(log::Cat("verify"), "Ringct type {} is not allowed after v{}", (unsigned)rct::RCTType::Bulletproof, static_cast(feature::SMALLER_BP)); tvc.m_invalid_output = true; return false; } @@ -3182,7 +3182,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context if (tx.version >= txversion::v4_tx_types && tx.is_transfer()) { if (tx.rct_signatures.type == rct::RCTType::CLSAG) { - oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::CLSAG, static_cast(feature::CLSAG)); + log::error(log::Cat("verify"), "Ringct type {} is not allowed before v{}", (unsigned)rct::RCTType::CLSAG, static_cast(feature::CLSAG)); tvc.m_invalid_output = true; return false; } @@ -3197,7 +3197,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context && tx.version >= txversion::v4_tx_types && tx.is_transfer() && (hf_version > feature::CLSAG || height >= 10 + *hard_fork_begins(m_nettype, feature::CLSAG))) { - oxen::log::error(oxen::log::Cat("verify"), "Ringct type {} is not allowed from v{}", (unsigned)tx.rct_signatures.type, static_cast(feature::CLSAG)); + log::error(log::Cat("verify"), "Ringct type {} is not allowed from v{}", (unsigned)tx.rct_signatures.type, static_cast(feature::CLSAG)); tvc.m_invalid_output = true; return false; } @@ -3207,7 +3207,7 @@ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context //------------------------------------------------------------------ bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); for (const txin_v& in: tx.vin) { if (!std::holds_alternative(in)) @@ -3307,7 +3307,7 @@ bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_pr // using threads, etc.) bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height, std::unordered_set* key_image_conflicts) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); uint64_t max_used_block_height = 0; if (!pmax_used_block_height) pmax_used_block_height = &max_used_block_height; @@ -3325,9 +3325,9 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (tvc.m_invalid_version || tvc.m_invalid_type) { if (tvc.m_invalid_version) - oxen::log::error(oxen::log::Cat("verify"), "TX Invalid version: {} for hardfork: {} min/max version: {}/{}", tx.version, (int)hf_version, min_version, max_version); + log::error(log::Cat("verify"), "TX Invalid version: {} for hardfork: {} min/max version: {}/{}", tx.version, (int)hf_version, min_version, max_version); if (tvc.m_invalid_type) - oxen::log::error(oxen::log::Cat("verify"), "TX Invalid type: {} for hardfork: {} max type: {}", tx.type, (int)hf_version, max_type); + log::error(log::Cat("verify"), "TX Invalid type: {} for hardfork: {} max type: {}", tx.type, (int)hf_version, max_type); return false; } } @@ -3336,7 +3336,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (tx.type != txtype::oxen_name_system && !std::holds_alternative(tx.vin[0]) && hf_version >= feature::MIN_2_OUTPUTS && tx.vout.size() < 2) { - oxen::log::error(oxen::log::Cat("verify"), "Tx {} has fewer than two outputs, which is not allowed as of hardfork {}", get_transaction_hash(tx), static_cast(feature::MIN_2_OUTPUTS)); + log::error(log::Cat("verify"), "Tx {} has fewer than two outputs, which is not allowed as of hardfork {}", get_transaction_hash(tx), static_cast(feature::MIN_2_OUTPUTS)); tvc.m_too_few_outputs = true; return false; } @@ -3363,7 +3363,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // Mixin Check, from hard fork 7, we require mixin at least 9, always. if (in_to_key.key_offsets.size() - 1 != cryptonote::TX_OUTPUT_DECOYS) { - oxen::log::error(oxen::log::Cat("verify"), "Tx {} has incorrect ring size: {} expected: {}", get_transaction_hash(tx), in_to_key.key_offsets.size() - 1, cryptonote::TX_OUTPUT_DECOYS); + log::error(log::Cat("verify"), "Tx {} has incorrect ring size: {} expected: {}", get_transaction_hash(tx), in_to_key.key_offsets.size() - 1, cryptonote::TX_OUTPUT_DECOYS); tvc.m_low_mixin = true; return false; } @@ -3372,7 +3372,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (last_key_image && memcmp(&in_to_key.k_image, last_key_image, sizeof(*last_key_image)) >= 0) { - oxen::log::error(oxen::log::Cat("verify"), "transaction has unsorted inputs"); + log::error(log::Cat("verify"), "transaction has unsorted inputs"); tvc.m_verifivation_failed = true; return false; } @@ -3381,7 +3381,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if(have_tx_keyimg_as_spent(in_to_key.k_image)) { - oxen::log::error(oxen::log::Cat("verify"), "Key image already spent in blockchain: {}", tools::type_to_hex(in_to_key.k_image)); + log::error(log::Cat("verify"), "Key image already spent in blockchain: {}", tools::type_to_hex(in_to_key.k_image)); if (key_image_conflicts) key_image_conflicts->insert(in_to_key.k_image); else @@ -3395,10 +3395,10 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // signature spending it. if (!check_tx_input(in_to_key, tx_prefix_hash, pubkeys[sig_index], pmax_used_block_height)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ring signature for tx {} vin key with k_image: {} sig_index: {}", get_transaction_hash(tx), in_to_key.k_image, sig_index); + log::error(log::Cat("verify"), "Failed to check ring signature for tx {} vin key with k_image: {} sig_index: {}", get_transaction_hash(tx), in_to_key.k_image, sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { - oxen::log::error(oxen::log::Cat("verify"), " *pmax_used_block_height: {}", *pmax_used_block_height); + log::error(log::Cat("verify"), " *pmax_used_block_height: {}", *pmax_used_block_height); } return false; @@ -3415,7 +3415,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (in_to_key.k_image == entry.key_image) // Check if key image is on the blacklist { - oxen::log::error(oxen::log::Cat("verify"), "Key image: {} is blacklisted by the service node network", tools::type_to_hex(entry.key_image)); + log::error(log::Cat("verify"), "Key image: {} is blacklisted by the service node network", tools::type_to_hex(entry.key_image)); tvc.m_key_image_blacklisted = true; return false; } @@ -3424,7 +3424,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t unlock_height = 0; if (m_service_node_list.is_key_image_locked(in_to_key.k_image, &unlock_height)) { - oxen::log::error(oxen::log::Cat("verify"), "Key image: {} is locked in a stake until height: {}", tools::type_to_hex(in_to_key.k_image), unlock_height); + log::error(log::Cat("verify"), "Key image: {} is locked in a stake until height: {}", tools::type_to_hex(in_to_key.k_image), unlock_height); tvc.m_key_image_locked_by_snode = true; return false; } @@ -3439,7 +3439,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to expand rct signatures!"); + log::error(log::Cat("verify"), "Failed to expand rct signatures!"); return false; } @@ -3453,7 +3453,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // we only accept no signatures for coinbase txes if (!std::holds_alternative(tx.vin[0])) { - oxen::log::error(oxen::log::Cat("verify"), "Null rct signature on non-coinbase tx"); + log::error(log::Cat("verify"), "Null rct signature on non-coinbase tx"); return false; } break; @@ -3467,14 +3467,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys.size() != rv.mixRing.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t i = 0; i < pubkeys.size(); ++i) { if (pubkeys[i].size() != rv.mixRing[i].size()) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } } @@ -3485,12 +3485,12 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[n][m].dest)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[n][m].mask)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); return false; } } @@ -3500,7 +3500,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, const size_t n_sigs = rv.type == rct::RCTType::CLSAG ? rv.p.CLSAGs.size() : rv.p.MGs.size(); if (n_sigs != tx.vin.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched MGs/vin sizes"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched MGs/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) @@ -3512,14 +3512,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, error = rv.p.MGs[n].II.empty() || memcmp(&var::get(tx.vin[n]).k_image, &rv.p.MGs[n].II[0], 32); if (error) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched key image"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched key image"); return false; } } if (!rct::verRctNonSemanticsSimple(rv)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures!"); + log::error(log::Cat("verify"), "Failed to check ringct signatures!"); return false; } break; @@ -3535,7 +3535,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, size_matches &= pubkeys.size() == rv.mixRing[i].size(); if (!size_matches) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } @@ -3545,12 +3545,12 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched pubkey at vin {}, index {}", n, m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched commitment at vin {}, index {}", n, m); return false; } } @@ -3559,32 +3559,32 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (rv.p.MGs.size() != 1) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: Bad MGs size"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: Bad MGs size"); return false; } if (rv.p.MGs.empty() || rv.p.MGs[0].II.size() != tx.vin.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (memcmp(&var::get(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); + log::error(log::Cat("verify"), "Failed to check ringct signatures: mismatched II/vin sizes"); return false; } } if (!rct::verRct(rv, false)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to check ringct signatures!"); + log::error(log::Cat("verify"), "Failed to check ringct signatures!"); return false; } break; } default: - oxen::log::error(oxen::log::Cat("verify"), "{}: Unsupported rct type: {}", __func__, (int)rv.type); + log::error(log::Cat("verify"), "{}: Unsupported rct type: {}", __func__, (int)rv.type); return false; } @@ -3595,7 +3595,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { if (proof.V.size() > 1 && !hack::test_suite_permissive_txes) { - oxen::log::error(oxen::log::Cat("verify"), "Multi output bulletproofs are invalid before v10"); + log::error(log::Cat("verify"), "Multi output bulletproofs are invalid before v10"); return false; } } @@ -3607,7 +3607,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, std::string fail_reason; if (!m_ons_db.validate_ons_tx(hf_version, get_current_blockchain_height(), tx, data, &fail_reason)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to validate ONS TX reason: {}", fail_reason); + log::error(log::Cat("verify"), "Failed to validate ONS TX reason: {}", fail_reason); tvc.m_verbose_error = std::move(fail_reason); return false; } @@ -3621,7 +3621,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, { tvc.m_invalid_input = true; tvc.m_verifivation_failed = true; - oxen::log::error(oxen::log::Cat("verify"), "TX type: {} should have 0 fee!", tx.type); + log::error(log::Cat("verify"), "TX type: {} should have 0 fee!", tx.type); return false; } @@ -3630,14 +3630,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, hf_version)) { - oxen::log::error(oxen::log::Cat("verify"), "TX did not have the state change metadata in the tx_extra"); + log::error(log::Cat("verify"), "TX did not have the state change metadata in the tx_extra"); return false; } auto quorum = m_service_node_list.get_quorum(service_nodes::quorum_type::obligations, state_change.block_height); if (!quorum) { - oxen::log::error(oxen::log::Cat("verify"), "could not get obligations quorum for recent state change tx"); + log::error(log::Cat("verify"), "could not get obligations quorum for recent state change tx"); return false; } @@ -3646,7 +3646,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, // will be set by the above on serious failures (i.e. illegal value), but not for less // serious ones like state change heights slightly outside of allowed bounds: //tvc.m_verifivation_failed = true; - oxen::log::error(oxen::log::Cat("verify"), "tx: {}, state change tx could not be completely verified reason: {}", get_transaction_hash(tx), print_vote_verification_context(tvc.m_vote_ctx)); + log::error(log::Cat("verify"), "tx: {}, state change tx could not be completely verified reason: {}", get_transaction_hash(tx), print_vote_verification_context(tvc.m_vote_ctx)); return false; } @@ -3657,14 +3657,14 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, std::vector service_node_array = m_service_node_list.get_service_node_list_state({state_change_service_node_pubkey}); if (service_node_array.empty()) { - oxen::log::error(oxen::log::Cat("verify"), "Service Node no longer exists on the network, state change can be ignored"); + log::error(log::Cat("verify"), "Service Node no longer exists on the network, state change can be ignored"); return hf_version < hf::hf12_checkpointing; // NOTE: Used to be allowed pre HF12. } const auto& service_node_info = *service_node_array[0].info; if (!service_node_info.can_transition_to_state(hf_version, state_change.block_height, state_change.state)) { - oxen::log::error(oxen::log::Cat("verify"), "State change trying to vote Service Node into the same state it invalid (expired, already applied, or impossible)"); + log::error(log::Cat("verify"), "State change trying to vote Service Node into the same state it invalid (expired, already applied, or impossible)"); tvc.m_double_spend = true; return false; } @@ -3674,7 +3674,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, cryptonote::tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - oxen::log::error(logcat, "TX extra didn't have key image unlock in the tx_extra"); + log::error(logcat, "TX extra didn't have key image unlock in the tx_extra"); return false; } @@ -3682,7 +3682,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t unlock_height = 0; if (!m_service_node_list.is_key_image_locked(unlock.key_image, &unlock_height, &contribution)) { - oxen::log::error(oxen::log::Cat("verify"), "Requested key image: {} to unlock is not locked", tools::type_to_hex(unlock.key_image)); + log::error(log::Cat("verify"), "Requested key image: {} to unlock is not locked", tools::type_to_hex(unlock.key_image)); tvc.m_invalid_input = true; return false; } @@ -3690,7 +3690,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, if (!crypto::check_signature(service_nodes::generate_request_stake_unlock_hash(unlock.nonce), contribution.key_image_pub_key, unlock.signature)) { - oxen::log::error(logcat, "Could not verify key image unlock transaction signature for tx: {}", get_transaction_hash(tx)); + log::error(logcat, "Could not verify key image unlock transaction signature for tx: {}", get_transaction_hash(tx)); return false; } @@ -3703,7 +3703,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, } else { - oxen::log::error(oxen::log::Cat("verify"), "Unhandled tx type: {} rejecting tx: {}", tx.type, get_transaction_hash(tx)); + log::error(log::Cat("verify"), "Unhandled tx type: {} rejecting tx: {}", tx.type, get_transaction_hash(tx)); tvc.m_invalid_type = true;; return false; } @@ -3794,7 +3794,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee(uint64_t block_reward, siz // quantize fee up to 8 decimals uint64_t mask = get_fee_quantization_mask(); uint64_t qlo = (lo + mask - 1) / mask * mask; - oxen::log::debug(logcat, "lo {}, qlo {}, mask {}", print_money(lo), print_money(qlo), mask); + log::debug(logcat, "lo {}, qlo {}, mask {}", print_money(lo), print_money(qlo), mask); fees.first = qlo; return fees; @@ -3817,7 +3817,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 { const bool use_long_term_median_in_fee = version >= feature::LONG_TERM_BLOCK_WEIGHT; auto fees = get_dynamic_base_fee(base_reward, use_long_term_median_in_fee ? std::min(median, m_long_term_effective_median_block_weight) : median, version); - oxen::log::debug(logcat, "Using {}/byte + {}/out fee", print_money(fees.first), print_money(fees.second)); + log::debug(logcat, "Using {}/byte + {}/out fee", print_money(fees.first), print_money(fees.second)); needed_fee = tx_weight * fees.first + tx_outs * fees.second; // quantize fee up to 8 decimals const uint64_t mask = get_fee_quantization_mask(); @@ -3827,7 +3827,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 { auto fees = get_dynamic_base_fee(base_reward, median, version); assert(fees.second == 0); - oxen::log::debug(logcat, "Using {}/kB fee", print_money(fees.first)); + log::debug(logcat, "Using {}/kB fee", print_money(fees.first)); needed_fee = tx_weight / 1024; needed_fee += (tx_weight % 1024) ? 1 : 0; @@ -3843,7 +3843,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 if (fee < needed_fee) { - oxen::log::error(oxen::log::Cat("verify"), "transaction fee is not enough: {}, minimum fee: {}", print_money(fee), print_money(needed_fee)); + log::error(log::Cat("verify"), "transaction fee is not enough: {}, minimum fee: {}", print_money(fee), print_money(needed_fee)); return false; } @@ -3852,7 +3852,7 @@ bool Blockchain::check_fee(size_t tx_weight, size_t tx_outs, uint64_t fee, uint6 uint64_t need_burned = opts.burn_fixed + base_miner_fee * opts.burn_percent / 100; if (burned < need_burned) { - oxen::log::error(oxen::log::Cat("verify"), "transaction burned fee is not enough: {}, minimum fee: {}", print_money(burned), print_money(need_burned)); + log::error(log::Cat("verify"), "transaction burned fee is not enough: {}, minimum fee: {}", print_money(burned), print_money(need_burned)); return false; } } @@ -3883,7 +3883,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl uint64_t base_reward, base_reward_unpenalized; if (!get_base_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, base_reward_unpenalized, version, m_db->height())) { - oxen::log::error(logcat, "Failed to determine block reward, using placeholder {} as a high bound", print_money(BLOCK_REWARD_OVERESTIMATE)); + log::error(logcat, "Failed to determine block reward, using placeholder {} as a high bound", print_money(BLOCK_REWARD_OVERESTIMATE)); base_reward = BLOCK_REWARD_OVERESTIMATE; } @@ -3891,7 +3891,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl const uint64_t use_median_value = use_long_term_median_in_fee ? std::min(median, m_long_term_effective_median_block_weight) : median; auto fee = get_dynamic_base_fee(base_reward, use_median_value, version); const bool per_byte = version < feature::PER_BYTE_FEE; - oxen::log::debug(logcat, "Estimating {}-block fee at {}/{} + {}.out", grace_blocks, print_money(fee.first), (per_byte ? "byte" : "kB"), print_money(fee.second)); + log::debug(logcat, "Estimating {}-block fee at {}/{} + {}.out", grace_blocks, print_money(fee.first), (per_byte ? "byte" : "kB"), print_money(fee.second)); return fee; } @@ -3900,7 +3900,7 @@ byte_and_output_fees Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_bl // a block index or a unix time. bool Blockchain::is_output_spendtime_unlocked(uint64_t unlock_time) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); return cryptonote::rules::is_output_unlocked(unlock_time, m_db->height()); } //------------------------------------------------------------------ @@ -3908,7 +3908,7 @@ bool Blockchain::is_output_spendtime_unlocked(uint64_t unlock_time) const // and validates that they exist and are usable. bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_prefix_hash, std::vector &output_keys, uint64_t* pmax_related_block_height) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // ND: // 1. Disable locking and make method private. @@ -3927,7 +3927,7 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ //check tx unlock time if (!m_bch.is_output_spendtime_unlocked(unlock_time)) { - oxen::log::error(oxen::log::Cat("verify"), "One of outputs for one of inputs has wrong tx.unlock_time = {}", unlock_time); + log::error(log::Cat("verify"), "One of outputs for one of inputs has wrong tx.unlock_time = {}", unlock_time); return false; } @@ -3947,13 +3947,13 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ outputs_visitor vi(output_keys, *this); if (!scan_outputkeys_for_indexes(txin, vi, tx_prefix_hash, pmax_related_block_height)) { - oxen::log::error(oxen::log::Cat("verify"), "Failed to get output keys for tx with amount = {} and count indixes {}", print_money(txin.amount), txin.key_offsets.size()); + log::error(log::Cat("verify"), "Failed to get output keys for tx with amount = {} and count indixes {}", print_money(txin.amount), txin.key_offsets.size()); return false; } if(txin.key_offsets.size() != output_keys.size()) { - oxen::log::error(oxen::log::Cat("verify"), "Output keys for tx with amount = {} and count indexes {} returned wrong keys count {}", txin.amount, txin.key_offsets.size(), output_keys.size()); + log::error(log::Cat("verify"), "Output keys for tx with amount = {} and count indexes {} returned wrong keys count {}", txin.amount, txin.key_offsets.size(), output_keys.size()); return false; } // rct_signatures will be expanded after this @@ -3963,7 +3963,7 @@ bool Blockchain::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_ //TODO: Is this intended to do something else? Need to look into the todo there. uint64_t Blockchain::get_adjusted_time() const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); //TODO: add collecting median time return time(NULL); } @@ -3971,12 +3971,12 @@ uint64_t Blockchain::get_adjusted_time() const //TODO: revisit, has changed a bit on upstream bool Blockchain::check_block_timestamp(std::vector timestamps, const block& b, uint64_t& median_ts) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); median_ts = tools::median(std::move(timestamps)); if(b.timestamp < median_ts) { - oxen::log::error(oxen::log::Cat("verify"), "Timestamp of block with id: {}, {}, less than median of last {} blocks, {}", get_block_hash(b), b.timestamp, BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW, median_ts); + log::error(log::Cat("verify"), "Timestamp of block with id: {}, {}, less than median of last {} blocks, {}", get_block_hash(b), b.timestamp, BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW, median_ts); return false; } @@ -3992,11 +3992,11 @@ bool Blockchain::check_block_timestamp(std::vector timestamps, const b // false otherwise bool Blockchain::check_block_timestamp(const block& b, uint64_t& median_ts) const { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); uint64_t cryptonote_block_future_time_limit = old::BLOCK_FUTURE_TIME_LIMIT_V2; if(b.timestamp > get_adjusted_time() + cryptonote_block_future_time_limit) { - oxen::log::error(oxen::log::Cat("verify"), "Timestamp of block with id: {}, {}, bigger than adjusted time + 2 hours", get_block_hash(b), b.timestamp); + log::error(log::Cat("verify"), "Timestamp of block with id: {}, {}, bigger than adjusted time + 2 hours", get_block_hash(b), b.timestamp); return false; } @@ -4036,7 +4036,7 @@ void Blockchain::return_tx_to_pool(std::vector &txids) size_t tx_weight; uint64_t fee; bool relayed, do_not_relay, double_spend_seen; - oxen::log::info(logcat, "Removing txid {} from the pool", txid); + log::info(logcat, "Removing txid {} from the pool", txid); if(m_tx_pool.have_tx(txid) && !m_tx_pool.take_tx(txid, tx, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { - oxen::log::error(logcat, "Failed to remove txid {} from the pool", txid); + log::error(logcat, "Failed to remove txid {} from the pool", txid); res = false; } } @@ -4114,7 +4114,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co { if (blk_hash != expected_hash) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id is INVALID: {}, expected {}", blk_hash, expected_hash); + log::error(log::Cat("verify"), "Block with id is INVALID: {}, expected {}", blk_hash, expected_hash); result.valid = false; return result; } @@ -4123,7 +4123,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co } else { - oxen::log::info(oxen::log::Cat("verify"), "No pre-validated hash at height {}, verifying fully", chain_height); + log::info(log::Cat("verify"), "No pre-validated hash at height {}, verifying fully", chain_height); } } #endif @@ -4150,7 +4150,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co // validate proof_of_work versus difficulty target result.valid = check_hash(result.proof_of_work, difficulty); if (!result.valid) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} with id: {}\n does not have enough proof of work: {} at height {}, required difficulty: {}", (alt_block ? "Alternative block" : "Block"), blk_hash, result.proof_of_work, blk_height, difficulty)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} with id: {}\n does not have enough proof of work: {} at height {}, required difficulty: {}", (alt_block ? "Alternative block" : "Block"), blk_hash, result.proof_of_work, blk_height, difficulty)); } return result; @@ -4167,13 +4167,13 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block { if(cryptonote::get_block_height(blk) == 0) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} (as alternative), but miner tx says height is 0.", blk_hash); + log::error(log::Cat("verify"), "Block with id: {} (as alternative), but miner tx says height is 0.", blk_hash); return false; } if (!m_checkpoints.is_alternative_block_allowed(chain_height, blk_height, nullptr)) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} can't be accepted for alternative chain, block height: {}, chain height: {}", blk_hash, blk_height, chain_height); + log::error(log::Cat("verify"), "Block with id: {} can't be accepted for alternative chain, block height: {}, chain height: {}", blk_hash, blk_height, chain_height); return false; } @@ -4182,7 +4182,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (auto v = get_network_version(blk_height); blk.major_version != v || (v < hf::hf19_reward_batching && blk.minor_version < static_cast(v))) { - oxen::log::info(logcat, "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(v), static_cast(v), blk_height); + log::info(logcat, "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(v), static_cast(v), blk_height); return false; } } @@ -4191,7 +4191,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block crypto::hash top_hash = get_tail_id(); if(blk.prev_id != top_hash) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has wrong prev_id: {}, expected: {}", blk_hash, blk.prev_id, top_hash)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has wrong prev_id: {}, expected: {}", blk_hash, blk.prev_id, top_hash)); return false; } @@ -4203,11 +4203,11 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (auto now = std::chrono::steady_clock::now(); now > last_outdated_warning + 5min) { last_outdated_warning = now; - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "A block was seen on the network with a version higher than the last")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "known one. This may be an old version of the daemon, and a software")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "update may be required to sync further. Try running: update check")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "A block was seen on the network with a version higher than the last")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "known one. This may be an old version of the daemon, and a software")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "update may be required to sync further. Try running: update check")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); } } @@ -4215,7 +4215,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (blk.major_version != required_major_version || (blk.major_version < hf::hf19_reward_batching && blk.minor_version < static_cast(required_major_version))) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(required_major_version), static_cast(required_major_version), blk_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(required_major_version), static_cast(required_major_version), blk_height)); return false; } @@ -4228,7 +4228,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block { if (!service_node_checkpoint || (service_node_checkpoint && blk.major_version >= hf::hf13_enforce_checkpoints)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "CHECKPOINT VALIDATION FAILED")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "CHECKPOINT VALIDATION FAILED")); return false; } } @@ -4238,7 +4238,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // number of the most recent blocks. if(!check_block_timestamp(blk)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid timestamp: {}", blk_hash, blk.timestamp)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid timestamp: {}", blk_hash, blk.timestamp)); return false; } } @@ -4248,7 +4248,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // sanity check basic miner tx properties; if(!prevalidate_miner_transaction(blk, alt_block ? blk_height : chain_height, hf_version)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} failed to pass prevalidation", blk_hash)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} failed to pass prevalidation", blk_hash)); return false; } @@ -4260,7 +4260,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // m_db->add_block() bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc, checkpoint_t const *checkpoint, bool notify) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); auto block_processing_start = std::chrono::steady_clock::now(); std::unique_lock lock{*this}; @@ -4338,7 +4338,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if (m_db->tx_exists(tx_id)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} attempting to add transaction already in blockchain with id: {}", id, tx_id)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} attempting to add transaction already in blockchain with id: {}", id, tx_id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4350,7 +4350,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // get transaction with hash from tx_pool if(!m_tx_pool.take_tx(tx_id, tx_tmp, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one unknown transaction with id: {}", id, tx_id)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one unknown transaction with id: {}", id, tx_id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4372,7 +4372,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly. // if (!check_for_double_spend(tx, keys)) // { - // oxen::log::warning(logcat, "Double spend detected in transaction (id: {}", tx_id); + // log::warning(logcat, "Double spend detected in transaction (id: {}", tx_id); // bvc.m_verifivation_failed = true; // break; // } @@ -4388,13 +4388,13 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& tx_verification_context tvc{}; if(!check_tx_inputs(tx, tvc)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id)); add_block_as_invalid(bl); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id {} added as invalid because of wrong inputs in transactions", id)); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "tx_index {}, m_blocks_txs_check {}:", tx_index, m_blocks_txs_check.size())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id {} added as invalid because of wrong inputs in transactions", id)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "tx_index {}, m_blocks_txs_check {}:", tx_index, m_blocks_txs_check.size())); for (const auto &h: m_blocks_txs_check) - oxen::log::error(oxen::log::Cat("verify"), " {}", h); + log::error(log::Cat("verify"), " {}", h); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4407,9 +4407,9 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // the transaction inputs, but do some sanity checks anyway. if (tx_index >= m_blocks_txs_check.size() || memcmp(&m_blocks_txs_check[tx_index++], &tx_id, sizeof(tx_id)) != 0) { - oxen::log::error(oxen::log::Cat("verify"), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id); + log::error(log::Cat("verify"), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id); add_block_as_invalid(bl); - oxen::log::error(oxen::log::Cat("verify"), "Block with id {} added as invalid because of wrong inputs in transactions", id); + log::error(log::Cat("verify"), "Block with id {} added as invalid because of wrong inputs in transactions", id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4428,7 +4428,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& uint64_t already_generated_coins = chain_height ? m_db->get_block_already_generated_coins(chain_height - 1) : 0; if(!validate_miner_transaction(bl, cumulative_block_weight, fee_summary, base_reward, already_generated_coins, get_network_version())) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block {} with id: {} has incorrect miner transaction", (chain_height - 1), id)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block {} with id: {} has incorrect miner transaction", (chain_height - 1), id)); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4464,7 +4464,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } catch (const KEY_IMAGE_EXISTS& e) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4473,7 +4473,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& catch (const std::exception& e) { //TODO: figure out the best way to deal with this failure - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4482,7 +4482,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } else { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Blocks that failed verification should not reach here")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Blocks that failed verification should not reach here")); } auto abort_block = oxen::defer([&]() { @@ -4507,14 +4507,14 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { m_service_node_list.block_add(bl, only_txs, checkpoint); } catch (const std::exception& e) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to Service Node List: {}", e.what())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to Service Node List: {}", e.what())); bvc.m_verifivation_failed = true; return false; } if (!m_ons_db.add_block(bl, only_txs)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to ONS DB.")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to ONS DB.")); bvc.m_verifivation_failed = true; return false; } @@ -4522,7 +4522,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if (m_sqlite_db) { if (!m_service_node_list.process_batching_rewards(bl)) { - oxen::log::error(logcat, "Failed to add block to batch rewards DB."); + log::error(logcat, "Failed to add block to batch rewards DB."); bvc.m_verifivation_failed = true; return false; } @@ -4537,7 +4537,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { hook(hook_data); } catch (const std::exception& e) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block added hook failed with exception: ", e.what())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block added hook failed with exception: ", e.what())); bvc.m_verifivation_failed = true; return false; } @@ -4548,7 +4548,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // do this after updating the hard fork state since the weight limit may change due to fork if (!update_next_cumulative_weight_limit()) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to update next cumulative weight limit")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to update next cumulative weight limit")); return false; } @@ -4556,7 +4556,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& uint64_t const fee_after_penalty = get_outs_money_amount(bl.miner_tx) - base_reward; if (bl.signatures.size() == service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES) { - oxen::log::info(logcat, "\n+++++ PULSE BLOCK SUCCESSFULLY ADDED\n\tid: {}\n\tHEIGHT: {}, v{}.{}\n\tblock reward: {}({} + {}) , coinbase_weight: {}, cumulative weight: {}, {}ms", + log::info(logcat, "\n+++++ PULSE BLOCK SUCCESSFULLY ADDED\n\tid: {}\n\tHEIGHT: {}, v{}.{}\n\tblock reward: {}({} + {}) , coinbase_weight: {}, cumulative weight: {}, {}ms", id, new_height-1, static_cast(bl.major_version), @@ -4571,7 +4571,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& else { assert(bl.signatures.empty() && "Signatures were supposed to be checked in Service Node List already."); - oxen::log::info(logcat, "\n+++++ MINER BLOCK SUCCESSFULLY ADDED\n\n\tid: {}\n\tPoW: {}\n\tHEIGHT: {}, v{}.{}, difficulty: {}\n\tblock reward: {}({} + {}), coinbase_weight: {}, cumulative weight: {}, {}({})", + log::info(logcat, "\n+++++ MINER BLOCK SUCCESSFULLY ADDED\n\n\tid: {}\n\tPoW: {}\n\tHEIGHT: {}, v{}.{}, difficulty: {}\n\tblock reward: {}({} + {}), coinbase_weight: {}, cumulative weight: {}, {}({})", id, miner.blk_pow.proof_of_work, new_height - 1, @@ -4590,7 +4590,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if(m_show_time_stats) { - oxen::log::info(logcat, + log::info(logcat, "Height: {} coinbase weight: {} cumm: {} p/t: {} ({}/{}/{}/{}/{}/{}/{}/{})", new_height, coinbase_weight, @@ -4662,7 +4662,7 @@ uint64_t Blockchain::get_next_long_term_block_weight(uint64_t block_weight) cons bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effective_median_block_weight) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); // when we reach this, the last hf version is not yet written to the db const uint64_t db_height = m_db->height(); @@ -4735,13 +4735,13 @@ bool Blockchain::update_next_cumulative_weight_limit(uint64_t *long_term_effecti bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc, checkpoint_t const *checkpoint) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); crypto::hash id = get_block_hash(bl); auto lock = tools::unique_locks(m_tx_pool, *this); db_rtxn_guard rtxn_guard(m_db); if(have_block(id)) { - oxen::log::trace(logcat, "block with id = {} already exists", id); + log::trace(logcat, "block with id = {} already exists", id); bvc.m_already_exists = true; m_blocks_txs_check.clear(); return false; @@ -4761,7 +4761,7 @@ bool Blockchain::add_new_block(const block& bl, block_verification_context& bvc, } catch (const std::exception &e) { - oxen::log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", block_height, e.what()); + log::error(logcat, "Get block checkpoint from DB failed at height: {}, what = {}", block_height, e.what()); } } @@ -4796,25 +4796,25 @@ bool Blockchain::update_checkpoints_from_json_file(const fs::path& file_path) std::vector::const_iterator one_past_last_to_check = checkpoint_hashes.end(); uint64_t prev_max_height = m_checkpoints.get_max_height(); - oxen::log::info(logcat, "Adding checkpoints from blockchain hashfile: {}", file_path); - oxen::log::info(logcat, "Hard-coded max checkpoint height is {}", prev_max_height); + log::info(logcat, "Adding checkpoints from blockchain hashfile: {}", file_path); + log::info(logcat, "Hard-coded max checkpoint height is {}", prev_max_height); for (std::vector::const_iterator it = checkpoint_hashes.begin(); it != one_past_last_to_check; it++) { uint64_t height; height = it->height; if (height <= prev_max_height) { - oxen::log::info(logcat, "ignoring checkpoint height {}", height); + log::info(logcat, "ignoring checkpoint height {}", height); } else { if (first_to_check == checkpoint_hashes.end()) first_to_check = it; std::string blockhash = it->hash; - oxen::log::info(logcat, "Adding checkpoint height {}, hash={}", height, blockhash); + log::info(logcat, "Adding checkpoint height {}, hash={}", height, blockhash); if (!m_checkpoints.add_checkpoint(height, blockhash)) { one_past_last_to_check = it; - oxen::log::info(logcat, "Failed to add checkpoint at height {}, hash={}", height, blockhash); + log::info(logcat, "Failed to add checkpoint at height {}, hash={}", height, blockhash); break; } } @@ -4840,7 +4840,7 @@ bool Blockchain::update_checkpoints_from_json_file(const fs::path& file_path) if (!m_checkpoints.check_block(block_height, m_db->get_block_hash_from_height(block_height), nullptr)) { // roll back to a couple of blocks before the checkpoint - oxen::log::error(logcat, "Local blockchain failed to pass a checkpoint, rolling back!"); + log::error(logcat, "Local blockchain failed to pass a checkpoint, rolling back!"); std::list empty; rollback_blockchain_switching(empty, block_height- 2); result = false; @@ -4883,7 +4883,7 @@ void Blockchain::block_longhash_worker(uint64_t height, const epee::span 0) @@ -4908,7 +4908,7 @@ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) } else if (m_db_sync_threshold && ((m_db_sync_on_blocks && m_sync_counter >= m_db_sync_threshold) || (!m_db_sync_on_blocks && m_bytes_to_sync >= m_db_sync_threshold))) { - oxen::log::debug(logcat, "Sync threshold met, syncing"); + log::debug(logcat, "Sync threshold met, syncing"); if(m_db_sync_mode == db_async) { m_sync_counter = 0; @@ -4933,7 +4933,7 @@ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) // when we're well clear of the precomputed hashes, free the memory if (!m_blocks_hash_check.empty() && m_db->height() > m_blocks_hash_check.size() + 4096) { - oxen::log::info(logcat, "Dumping block hashes, we're now 4k past {}", m_blocks_hash_check.size()); + log::info(logcat, "Dumping block hashes, we're now 4k past {}", m_blocks_hash_check.size()); m_blocks_hash_check.clear(); m_blocks_hash_check.shrink_to_fit(); } @@ -4955,7 +4955,7 @@ void Blockchain::output_scan_worker(const uint64_t amount, const std::vector::max() / 2, 0, "usable is negative"); return usable; } @@ -5107,7 +5107,7 @@ bool Blockchain::calc_batched_governance_reward(uint64_t height, uint64_t &rewar std::vector blocks; if (!get_blocks_only(start_height, num_blocks, blocks)) { - oxen::log::error(logcat, "Unable to get historical blocks to calculated batched governance payment"); + log::error(logcat, "Unable to get historical blocks to calculated batched governance payment"); return false; } @@ -5129,7 +5129,7 @@ bool Blockchain::calc_batched_governance_reward(uint64_t height, uint64_t &rewar // keys. bool Blockchain::prepare_handle_incoming_blocks(const std::vector &blocks_entry, std::vector &blocks) { - oxen::log::trace(logcat, "Blockchain::{}", __func__); + log::trace(logcat, "Blockchain::{}", __func__); auto prepare = std::chrono::steady_clock::now(); uint64_t bytes = 0; size_t total_txs = 0; @@ -5189,7 +5189,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector> maps(threads); auto it = blocks_entry.begin(); unsigned blockidx = 0; @@ -5210,7 +5210,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector 1 && threads > 1 && m_show_time_stats) - oxen::log::debug(logcat, "Prepare blocks took: {}", tools::friendly_duration(prepare_elapsed)); + log::debug(logcat, "Prepare blocks took: {}", tools::friendly_duration(prepare_elapsed)); auto scantable = std::chrono::steady_clock::now(); @@ -5308,7 +5308,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector= txes.size()) { - oxen::log::error(oxen::log::Cat("verify"), "tx_index is out of sync"); + log::error(log::Cat("verify"), "tx_index is out of sync"); m_scan_table.clear(); return false; } @@ -5318,7 +5318,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vectorsecond.find(in_to_key.k_image); if (it != its->second.end()) { - oxen::log::error(oxen::log::Cat("verify"), "Duplicate key_image found from incoming blocks."); + log::error(log::Cat("verify"), "Duplicate key_image found from incoming blocks."); m_scan_table.clear(); return false; } @@ -5434,7 +5434,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector= txes.size()) { - oxen::log::error(oxen::log::Cat("verify"), "tx_index is out of sync"); + log::error(log::Cat("verify"), "tx_index is out of sync"); m_scan_table.clear(); return false; } @@ -5445,7 +5445,7 @@ bool Blockchain::prepare_handle_incoming_blocks(const std::vector> m_db->for_all_alt_blocks([&alt_blocks](const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const std::string *block_blob, const std::string *checkpoint_blob) { if (!block_blob) { - oxen::log::error(logcat, "No blob, but blobs were requested"); + log::error(logcat, "No blob, but blobs were requested"); return false; } @@ -5594,7 +5594,7 @@ std::vector> if (data.checkpointed && checkpoint_blob) { if (!t_serializable_object_from_blob(checkpoint, *checkpoint_blob)) - oxen::log::error(logcat, "Failed to parse checkpoint from blob"); + log::error(logcat, "Failed to parse checkpoint from blob"); } cryptonote::block block; @@ -5604,7 +5604,7 @@ std::vector> alt_blocks.insert(std::make_pair(cryptonote::get_block_hash(bei.bl), std::move(bei))); } else - oxen::log::error(logcat, "Failed to parse block from blob"); + log::error(logcat, "Failed to parse block from blob"); return true; }, true); @@ -5652,30 +5652,30 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get std::string_view checkpoints = get_checkpoints(m_nettype); if (!checkpoints.empty()) { - oxen::log::info(logcat, "Loading precomputed blocks ({} bytes)", checkpoints.size()); + log::info(logcat, "Loading precomputed blocks ({} bytes)", checkpoints.size()); if (m_nettype == network_type::MAINNET) { // first check hash crypto::hash hash; if (!tools::sha256sum_str(checkpoints, hash)) { - oxen::log::error(logcat, "Failed to hash precomputed blocks data"); + log::error(logcat, "Failed to hash precomputed blocks data"); return; } constexpr auto EXPECTED_SHA256_HASH = "d5772a74dadb64a439b60312f9dc3e5243157c5477037a318840b8c36da9644b"sv; - oxen::log::info(logcat, "Precomputed blocks hash: {}, expected {}", hash, EXPECTED_SHA256_HASH); + log::info(logcat, "Precomputed blocks hash: {}, expected {}", hash, EXPECTED_SHA256_HASH); crypto::hash expected_hash; if (!tools::hex_to_type(EXPECTED_SHA256_HASH, expected_hash)) { - oxen::log::error(logcat, "Failed to parse expected block hashes hash"); + log::error(logcat, "Failed to parse expected block hashes hash"); return; } if (hash != expected_hash) { - oxen::log::error(logcat, "Block hash data does not match expected hash"); + log::error(logcat, "Block hash data does not match expected hash"); return; } } @@ -5685,13 +5685,13 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get auto nblocks = oxenc::load_little_to_host(checkpoints.data()); if (nblocks > (std::numeric_limits::max() - 4) / sizeof(hash)) { - oxen::log::error(logcat, "Block hash data is too large"); + log::error(logcat, "Block hash data is too large"); return; } const size_t size_needed = 4 + (nblocks * sizeof(crypto::hash)); if(checkpoints.size() != size_needed) { - oxen::log::error(logcat, "Failed to load hashes - unexpected data size {}, expected {}", checkpoints.size(), size_needed); + log::error(logcat, "Failed to load hashes - unexpected data size {}, expected {}", checkpoints.size(), size_needed); return; } else if(nblocks > 0 && nblocks > (m_db->height() + HASH_OF_HASHES_STEP - 1) / HASH_OF_HASHES_STEP) @@ -5705,7 +5705,7 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get checkpoints.remove_prefix(sizeof(hash.data)); } m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, crypto::null_hash); - oxen::log::info(logcat, "{} block hashes loaded", nblocks); + log::info(logcat, "{} block hashes loaded", nblocks); // FIXME: clear tx_pool because the process might have been // terminated and caused it to store txs kept by blocks. @@ -5769,13 +5769,13 @@ bool Blockchain::for_all_outputs(uint64_t amount, std::function arg_testnet_on = { "testnet" @@ -383,7 +383,7 @@ namespace cryptonote bool args_okay = true; if (m_quorumnet_port == 0) { - oxen::log::error(logcat, "Quorumnet port cannot be 0; please specify a valid port to listen on with: '--{} '", arg_quorumnet_port.name); + log::error(logcat, "Quorumnet port cannot be 0; please specify a valid port to listen on with: '--{} '", arg_quorumnet_port.name); args_okay = false; } @@ -391,27 +391,27 @@ namespace cryptonote if (pub_ip.size()) { if (!epee::string_tools::get_ip_int32_from_string(m_sn_public_ip, pub_ip)) { - oxen::log::error(logcat, "Unable to parse IPv4 public address from: {}", pub_ip); + log::error(logcat, "Unable to parse IPv4 public address from: {}", pub_ip); args_okay = false; } if (!epee::net_utils::is_ip_public(m_sn_public_ip)) { if (m_service_node_list.debug_allow_local_ips) { - oxen::log::warning(logcat, "Address given for public-ip is not public; allowing it because dev-allow-local-ips was specified. This service node WILL NOT WORK ON THE PUBLIC OXEN NETWORK!"); + log::warning(logcat, "Address given for public-ip is not public; allowing it because dev-allow-local-ips was specified. This service node WILL NOT WORK ON THE PUBLIC OXEN NETWORK!"); } else { - oxen::log::error(logcat, "Address given for public-ip is not public: {}", epee::string_tools::get_ip_string_from_int32(m_sn_public_ip)); + log::error(logcat, "Address given for public-ip is not public: {}", epee::string_tools::get_ip_string_from_int32(m_sn_public_ip)); args_okay = false; } } } else { - oxen::log::error(logcat, "Please specify an IPv4 public address which the service node & storage server is accessible from with: '--{} '", arg_public_ip.name); + log::error(logcat, "Please specify an IPv4 public address which the service node & storage server is accessible from with: '--{} '", arg_public_ip.name); args_okay = false; } if (!args_okay) { - oxen::log::error(logcat, + log::error(logcat, "IMPORTANT: One or more required service node-related configuration settings/options were omitted or invalid please fix them and restart oxend."); return false; } @@ -592,14 +592,14 @@ namespace cryptonote // make sure the data directory exists, and try to lock it if (std::error_code ec; !fs::is_directory(folder, ec) && !fs::create_directories(folder, ec) && ec) { - oxen::log::error(logcat, "Failed to create directory " + folder.u8string() + (ec ? ": " + ec.message() : ""s)); + log::error(logcat, "Failed to create directory " + folder.u8string() + (ec ? ": " + ec.message() : ""s)); return false; } std::unique_ptr db(new_db()); if (!db) { - oxen::log::error(logcat, "Failed to initialize a database"); + log::error(logcat, "Failed to initialize a database"); return false; } @@ -615,7 +615,7 @@ namespace cryptonote auto sqliteDB = std::make_shared(m_nettype, sqlite_db_file_path); folder /= db->get_db_name(); - oxen::log::info(logcat, "Loading blockchain from folder {} ...", folder); + log::info(logcat, "Loading blockchain from folder {} ...", folder); // default to fast:async:1 if overridden blockchain_db_sync_mode sync_mode = db_defaultsync; @@ -627,7 +627,7 @@ namespace cryptonote // reset the db by removing the database file before opening it if (!db->remove_data_file(folder)) { - oxen::log::error(logcat, "Failed to remove data file in {}", folder); + log::error(logcat, "Failed to remove data file in {}", folder); return false; } fs::remove(ons_db_file_path); @@ -643,7 +643,7 @@ namespace cryptonote const bool db_sync_mode_is_default = command_line::is_arg_defaulted(vm, cryptonote::arg_db_sync_mode); for(const auto &option : options) - oxen::log::debug(logcat, "option: {}", option); + log::debug(logcat, "option: {}", option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; @@ -702,7 +702,7 @@ namespace cryptonote } else { - oxen::log::error(logcat, "Invalid db sync mode: {}", options[2]); + log::error(logcat, "Invalid db sync mode: {}", options[2]); return false; } } @@ -716,7 +716,7 @@ namespace cryptonote } catch (const DB_ERROR& e) { - oxen::log::error(logcat, "Error opening database: {}", e.what()); + log::error(logcat, "Error opening database: {}", e.what()); return false; } @@ -742,7 +742,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to parse reorg notify spec"); + log::error(logcat, "Failed to parse reorg notify spec"); } try @@ -756,7 +756,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to parse block rate notify spec"); + log::error(logcat, "Failed to parse block rate notify spec"); } cryptonote::test_options regtest_test_options{}; @@ -808,9 +808,9 @@ namespace cryptonote block_sync_size = command_line::get_arg(vm, arg_block_sync_size); if (block_sync_size > BLOCKS_SYNCHRONIZING_MAX_COUNT) - oxen::log::error(logcat, "Error --block-sync-size cannot be greater than {}", BLOCKS_SYNCHRONIZING_MAX_COUNT); + log::error(logcat, "Error --block-sync-size cannot be greater than {}", BLOCKS_SYNCHRONIZING_MAX_COUNT); - oxen::log::info(logcat, "Loading checkpoints"); + log::info(logcat, "Loading checkpoints"); CHECK_AND_ASSERT_MES(update_checkpoints_from_json_file(), false, "One or more checkpoints loaded from json conflicted with existing checkpoints."); r = m_miner.init(vm, m_nettype); @@ -824,7 +824,7 @@ namespace cryptonote // display a message if the blockchain is not pruned yet if (!m_blockchain_storage.get_blockchain_pruning_seed()) { - oxen::log::info(logcat, "Pruning blockchain..."); + log::info(logcat, "Pruning blockchain..."); CHECK_AND_ASSERT_MES(m_blockchain_storage.prune_blockchain(), false, "Failed to prune blockchain"); } else @@ -863,7 +863,7 @@ namespace cryptonote try { generate_pair(privkey, pubkey); } catch (const std::exception& e) { - oxen::log::error(logcat, "failed to generate keypair {}", e.what()); + log::error(logcat, "failed to generate keypair {}", e.what()); return false; } @@ -942,16 +942,16 @@ namespace cryptonote } if (m_service_node) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Service node public keys:")); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- primary: {}", tools::type_to_hex(keys.pub))); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- ed25519: {}", tools::type_to_hex(keys.pub_ed25519))); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Service node public keys:")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- primary: {}", tools::type_to_hex(keys.pub))); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- ed25519: {}", tools::type_to_hex(keys.pub_ed25519))); // .snode address is the ed25519 pubkey, encoded with base32z and with .snode appended: - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- lokinet: {}.snode", oxenc::to_base32z(tools::view_guts(keys.pub_ed25519)))); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- x25519: {}", tools::type_to_hex(keys.pub_x25519))); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- lokinet: {}.snode", oxenc::to_base32z(tools::view_guts(keys.pub_ed25519)))); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- x25519: {}", tools::type_to_hex(keys.pub_x25519))); } else { // Only print the x25519 version because it's the only thing useful for a non-SN (for // encrypted LMQ RPC connections). - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "x25519 public key: {}", tools::type_to_hex(keys.pub_x25519))); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "x25519 public key: {}", tools::type_to_hex(keys.pub_x25519))); } return true; @@ -985,20 +985,20 @@ namespace cryptonote if (user_auth >= AuthLevel::basic) { if (user_auth > auth) auth = user_auth; - oxen::log::info(oxen::log::Cat("omq"), "Incoming {}-authenticated connection", auth); + log::info(log::Cat("omq"), "Incoming {}-authenticated connection", auth); } - oxen::log::info(oxen::log::Cat("omq"), "Incoming [{}] curve connection from {}/{}", auth, ip, x25519_pubkey); + log::info(log::Cat("omq"), "Incoming [{}] curve connection from {}/{}", auth, ip, x25519_pubkey); } else { - oxen::log::info(oxen::log::Cat("omq"), "Incoming [{}] plain connection from {}", auth, ip); + log::info(log::Cat("omq"), "Incoming [{}] plain connection from {}", auth, ip); } return auth; } void core::init_oxenmq(const boost::program_options::variables_map& vm) { using namespace oxenmq; - oxen::log::info(omqlogcat, "Starting oxenmq"); + log::info(omqlogcat, "Starting oxenmq"); m_omq = std::make_unique( tools::copy_guts(m_service_keys.pub_x25519), tools::copy_guts(m_service_keys.key_x25519), @@ -1015,7 +1015,7 @@ namespace cryptonote // ping.ping: a simple debugging target for pinging the omq listener m_omq->add_category("ping", Access{AuthLevel::none}) .add_request_command("ping", [](Message& m) { - oxen::log::info(oxen::log::Cat("omq"), "Received ping from {}", m.conn); + log::info(log::Cat("omq"), "Received ping from {}", m.conn); m.send_reply("pong"); }) ; @@ -1027,7 +1027,7 @@ namespace cryptonote if (listen_ip.empty()) listen_ip = "0.0.0.0"; std::string qnet_listen = "tcp://" + listen_ip + ":" + std::to_string(m_quorumnet_port); - oxen::log::info(logcat, "- listening on {} (quorumnet)", qnet_listen); + log::info(logcat, "- listening on {} (quorumnet)", qnet_listen); m_omq->listen_curve(qnet_listen, [this, public_=command_line::get_arg(vm, arg_omq_quorumnet_public)](std::string_view ip, std::string_view pk, bool) { return omq_allow(ip, pk, public_ ? AuthLevel::basic : AuthLevel::none); @@ -1106,14 +1106,14 @@ namespace cryptonote { if(tx_info.blob->size() > MAX_TX_SIZE) { - oxen::log::info(logcat, "WRONG TRANSACTION BLOB, too big size {}, rejected", tx_info.blob->size()); + log::info(logcat, "WRONG TRANSACTION BLOB, too big size {}, rejected", tx_info.blob->size()); tx_info.tvc.m_verifivation_failed = true; tx_info.tvc.m_too_big = true; return; } else if (tx_info.blob->empty()) { - oxen::log::info(logcat, "WRONG TRANSACTION BLOB, blob is empty, rejected"); + log::info(logcat, "WRONG TRANSACTION BLOB, blob is empty, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1121,7 +1121,7 @@ namespace cryptonote tx_info.parsed = parse_and_validate_tx_from_blob(*tx_info.blob, tx_info.tx, tx_info.tx_hash); if(!tx_info.parsed) { - oxen::log::info(logcat, "WRONG TRANSACTION BLOB, Failed to parse, rejected"); + log::info(logcat, "WRONG TRANSACTION BLOB, Failed to parse, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1132,7 +1132,7 @@ namespace cryptonote { if (bad_semantics_txes[idx].find(tx_info.tx_hash) != bad_semantics_txes[idx].end()) { - oxen::log::info(logcat, "Transaction already seen with bad semantics, rejected"); + log::info(logcat, "Transaction already seen with bad semantics, rejected"); tx_info.tvc.m_verifivation_failed = true; return; } @@ -1142,7 +1142,7 @@ namespace cryptonote //----------------------------------------------------------------------------------------------- void core::set_semantics_failed(const crypto::hash &tx_hash) { - oxen::log::info(logcat, "WRONG TRANSACTION BLOB, Failed to check tx {} semantic, rejected", tx_hash); + log::info(logcat, "WRONG TRANSACTION BLOB, Failed to check tx {} semantic, rejected", tx_hash); bad_semantics_txes_lock.lock(); bad_semantics_txes[0].insert(tx_hash); if (bad_semantics_txes[0].size() >= BAD_SEMANTICS_TXES_MAX_SIZE) @@ -1167,7 +1167,7 @@ namespace cryptonote { if (kept_by_block && get_blockchain_storage().is_within_compiled_block_hash_area()) { - oxen::log::trace(logcat, "Skipping semantics check for txs kept by block in embedded hash area"); + log::trace(logcat, "Skipping semantics check for txs kept by block in embedded hash area"); return; } @@ -1191,7 +1191,7 @@ namespace cryptonote switch (rv.type) { case rct::RCTType::Null: // coinbase should not come here, so we reject for all other types - oxen::log::error(oxen::log::Cat("verify"), "Unexpected Null rctSig type"); + log::error(log::Cat("verify"), "Unexpected Null rctSig type"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1199,7 +1199,7 @@ namespace cryptonote case rct::RCTType::Simple: if (!rct::verRctSemanticsSimple(rv)) { - oxen::log::error(oxen::log::Cat("verify"), "rct signature semantics check failed"); + log::error(log::Cat("verify"), "rct signature semantics check failed"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1209,7 +1209,7 @@ namespace cryptonote case rct::RCTType::Full: if (!rct::verRct(rv, true)) { - oxen::log::error(oxen::log::Cat("verify"), "rct signature semantics check failed"); + log::error(log::Cat("verify"), "rct signature semantics check failed"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1221,7 +1221,7 @@ namespace cryptonote case rct::RCTType::CLSAG: if (!is_canonical_bulletproof_layout(rv.p.bulletproofs)) { - oxen::log::error(oxen::log::Cat("verify"), "Bulletproof does not have canonical form"); + log::error(log::Cat("verify"), "Bulletproof does not have canonical form"); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1230,7 +1230,7 @@ namespace cryptonote rvv.push_back(&rv); // delayed batch verification break; default: - oxen::log::error(oxen::log::Cat("verify"), "Unknown rct type: {}", (int)rv.type); + log::error(log::Cat("verify"), "Unknown rct type: {}", (int)rv.type); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; @@ -1239,7 +1239,7 @@ namespace cryptonote } if (!rvv.empty() && !rct::verRctSemanticsSimple(rvv)) { - oxen::log::info(logcat, "One transaction among this group has bad semantics, verifying one at a time"); + log::info(logcat, "One transaction among this group has bad semantics, verifying one at a time"); const bool assumed_bad = rvv.size() == 1; // if there's only one tx, it must be the bad one for (size_t n = 0; n < tx_info.size(); ++n) { @@ -1274,7 +1274,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(oxen::log::Cat("verify"), "Exception in handle_incoming_tx_pre: {}", e.what()); + log::error(log::Cat("verify"), "Exception in handle_incoming_tx_pre: {}", e.what()); info.tvc.m_verifivation_failed = true; } }); @@ -1287,12 +1287,12 @@ namespace cryptonote if(m_mempool.have_tx(info.tx_hash)) { - oxen::log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); + log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); info.already_have = true; } else if(m_blockchain_storage.have_tx(info.tx_hash)) { - oxen::log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); + log::debug(logcat, "tx {} already has a transaction in tx_pool", info.tx_hash); info.already_have = true; } } @@ -1336,15 +1336,15 @@ namespace cryptonote } if (m_mempool.add_tx(info.tx, info.tx_hash, *info.blob, weight, info.tvc, *local_opts, version, blink_rollback_height)) { - oxen::log::debug(logcat, "tx added: {}", info.tx_hash); + log::debug(logcat, "tx added: {}", info.tx_hash); } else { ok = false; if (info.tvc.m_verifivation_failed) - oxen::log::error(oxen::log::Cat("verify"), "Transaction verification failed: {}", info.tx_hash); + log::error(log::Cat("verify"), "Transaction verification failed: {}", info.tx_hash); else if (info.tvc.m_verifivation_impossible) - oxen::log::error(oxen::log::Cat("verify"), "Transaction verification impossible: {}", info.tx_hash); + log::error(log::Cat("verify"), "Transaction verification impossible: {}", info.tx_hash); } } @@ -1405,7 +1405,7 @@ namespace cryptonote } } - oxen::log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out immutable txes", want_count, blinks.size()); + log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out immutable txes", want_count, blinks.size()); if (!want_count) return results; // Step 2: filter out any transactions for which we already have a blink signature @@ -1415,14 +1415,14 @@ namespace cryptonote { if (want[i] && m_mempool.has_blink(blinks[i].tx_hash)) { - oxen::log::debug(logcat, "Ignoring blink data for {}: already have blink signatures", blinks[i].tx_hash); + log::debug(logcat, "Ignoring blink data for {}: already have blink signatures", blinks[i].tx_hash); want[i] = false; // Already have it, move along want_count--; } } } - oxen::log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out existing blink sigs", want_count, blinks.size()); + log::debug(logcat, "Want {} of {} incoming blink signature sets after filtering out existing blink sigs", want_count, blinks.size()); if (!want_count) return results; // Step 3: create new blink_tx objects for txes and add the blink signatures. We can do all of @@ -1448,7 +1448,7 @@ namespace cryptonote std::any_of(bdata.position.begin(), bdata.position.end(), [](const auto &p) { return p >= service_nodes::BLINK_SUBQUORUM_SIZE; }) || // invalid position std::any_of(bdata.quorum.begin(), bdata.quorum.end(), [](const auto &qi) { return qi >= tools::enum_count; }) // invalid quorum index ) { - oxen::log::info(logcat, "Invalid blink tx {}: invalid signature data", bdata.tx_hash); + log::info(logcat, "Invalid blink tx {}: invalid signature data", bdata.tx_hash); continue; } @@ -1462,7 +1462,7 @@ namespace cryptonote q = get_quorum(service_nodes::quorum_type::blink, q_height); if (!q) { - oxen::log::info(logcat, "Don't have a quorum for height {} (yet?), ignoring this blink", q_height); + log::info(logcat, "Don't have a quorum for height {} (yet?), ignoring this blink", q_height); no_quorum = true; break; } @@ -1483,9 +1483,9 @@ namespace cryptonote } if (blink.approved()) { - oxen::log::info(logcat, "Blink tx {} blink signatures approved with {} signature validation failures", bdata.tx_hash, failures.size()); + log::info(logcat, "Blink tx {} blink signatures approved with {} signature validation failures", bdata.tx_hash, failures.size()); for (auto &f : failures) - oxen::log::debug(logcat, "- failure for quorum {}, position {}: {}", int(bdata.quorum[f.first]), int(bdata.position[f.first]), f.second); + log::debug(logcat, "- failure for quorum {}, position {}: {}", int(bdata.quorum[f.first]), int(bdata.position[f.first]), f.second); } else { @@ -1493,7 +1493,7 @@ namespace cryptonote os << "Blink validation failed:"; for (auto &f : failures) os << " [" << int(bdata.quorum[f.first]) << ":" << int(bdata.position[f.first]) << "]: " << f.second; - oxen::log::info(logcat, "Invalid blink tx {}: {}", bdata.tx_hash, os.str()); + log::info(logcat, "Invalid blink tx {}: {}", bdata.tx_hash, os.str()); } } @@ -1515,7 +1515,7 @@ namespace cryptonote if (added) { - oxen::log::info(logcat, "Added blink signatures for {} blinks", added); + log::info(logcat, "Added blink signatures for {} blinks", added); long_poll_trigger(m_mempool); } @@ -1534,7 +1534,7 @@ namespace cryptonote { if (tx.vin.empty()) { - oxen::log::error(oxen::log::Cat("verify"), "tx with empty inputs, rejected for tx id= {}", get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx with empty inputs, rejected for tx id= {}", get_transaction_hash(tx)); return false; } } @@ -1542,20 +1542,20 @@ namespace cryptonote { if (tx.vin.size() != 0) { - oxen::log::error(oxen::log::Cat("verify"), "tx type: {} must have 0 inputs, received: {}, rejected for tx id = {}", tx.type, tx.vin.size(), get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx type: {} must have 0 inputs, received: {}, rejected for tx id = {}", tx.type, tx.vin.size(), get_transaction_hash(tx)); return false; } } if(!check_inputs_types_supported(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "unsupported input types for tx id= {}", get_transaction_hash(tx)); + log::error(log::Cat("verify"), "unsupported input types for tx id= {}", get_transaction_hash(tx)); return false; } if(!check_outs_valid(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "tx with invalid outputs, rejected for tx id= {}", get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx with invalid outputs, rejected for tx id= {}", get_transaction_hash(tx)); return false; } @@ -1563,14 +1563,14 @@ namespace cryptonote { if (tx.rct_signatures.outPk.size() != tx.vout.size()) { - oxen::log::error(oxen::log::Cat("verify"), "tx with mismatched vout/outPk count, rejected for tx id= {}", get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx with mismatched vout/outPk count, rejected for tx id= {}", get_transaction_hash(tx)); return false; } } if(!check_money_overflow(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "tx has money overflow, rejected for tx id= {}", get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx has money overflow, rejected for tx id= {}", get_transaction_hash(tx)); return false; } @@ -1582,32 +1582,32 @@ namespace cryptonote if(amount_in <= amount_out) { - oxen::log::error(oxen::log::Cat("verify"), "tx with wrong amounts: ins {}, outs {}, rejected for tx id= {}", amount_in, amount_out, get_transaction_hash(tx)); + log::error(log::Cat("verify"), "tx with wrong amounts: ins {}, outs {}, rejected for tx id= {}", amount_in, amount_out, get_transaction_hash(tx)); return false; } } if(!keeped_by_block && get_transaction_weight(tx) >= m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE) { - oxen::log::error(oxen::log::Cat("verify"), "tx is too large {}, expected not bigger than {}", get_transaction_weight(tx), m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE); + log::error(log::Cat("verify"), "tx is too large {}, expected not bigger than {}", get_transaction_weight(tx), m_blockchain_storage.get_current_cumulative_block_weight_limit() - COINBASE_BLOB_RESERVED_SIZE); return false; } if(!check_tx_inputs_keyimages_diff(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "tx uses a single key image more than once"); + log::error(log::Cat("verify"), "tx uses a single key image more than once"); return false; } if (!check_tx_inputs_ring_members_diff(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "tx uses duplicate ring members"); + log::error(log::Cat("verify"), "tx uses duplicate ring members"); return false; } if (!check_tx_inputs_keyimages_domain(tx)) { - oxen::log::error(oxen::log::Cat("verify"), "tx uses key image not in the valid domain"); + log::error(log::Cat("verify"), "tx uses key image not in the valid domain"); return false; } @@ -1634,7 +1634,7 @@ namespace cryptonote "quorum.timestamp", [this, pubkey](bool success, std::vector data) { const time_t local_seconds = time(nullptr); - oxen::log::debug(logcat, "Timestamp message received: {}, local time is: ", data[0], local_seconds); + log::debug(logcat, "Timestamp message received: {}, local time is: ", data[0], local_seconds); if(success){ int64_t received_seconds; if (tools::parse_int(data[0],received_seconds)){ @@ -1651,7 +1651,7 @@ namespace cryptonote // Counts the number of times we have been out of sync if (m_sn_times.failures() > (m_sn_times.size() * service_nodes::MAXIMUM_EXTERNAL_OUT_OF_SYNC/100)) { - oxen::log::warning(logcat, "service node time might be out of sync"); + log::warning(logcat, "service node time might be out of sync"); // If we are out of sync record the other service node as in sync m_service_node_list.record_timesync_status(pubkey, true); } else { @@ -1763,7 +1763,7 @@ namespace cryptonote if (cache_to > 0 && count > CACHE_EXCLUSIVE) { cache_build_started = std::chrono::steady_clock::now(); m_coinbase_cache.building = true; // Block out other threads until we're done - oxen::log::info(logcat, "Starting slow cache build request for get_coinbase_tx_sum({}, {})", start_offset, count); + log::info(logcat, "Starting slow cache build request for get_coinbase_tx_sum({}, {})", start_offset, count); } } } @@ -1800,7 +1800,7 @@ namespace cryptonote if (m_coinbase_cache.building) { m_coinbase_cache.building = false; - oxen::log::info(logcat, "Finishing cache build for get_coinbase_tx_sum in {} s", + log::info(logcat, "Finishing cache build for get_coinbase_tx_sum in {} s", std::chrono::duration{std::chrono::steady_clock::now() - cache_build_started}.count()); } cache_to = 0; @@ -1894,7 +1894,7 @@ namespace cryptonote } if (relayed) - oxen::log::info(logcat, "Submitted uptime-proof for Service Node (yours): {}", m_service_keys.pub); + log::info(logcat, "Submitted uptime-proof for Service Node (yours): {}", m_service_keys.pub); return true; } @@ -1936,7 +1936,7 @@ namespace cryptonote crypto::hash tx_hash; if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash)) { - oxen::log::error(logcat, "Failed to parse relayed transaction"); + log::error(logcat, "Failed to parse relayed transaction"); return crypto::null_hash; } txs.push_back(std::make_pair(tx_hash, std::move(tx_blob))); @@ -2055,7 +2055,7 @@ namespace cryptonote std::vector pblocks; if (!prepare_handle_incoming_blocks(blocks, pblocks)) { - oxen::log::error(logcat, "Block found, but failed to prepare to add"); + log::error(logcat, "Block found, but failed to prepare to add"); return false; } // add_new_block will verify block and set bvc.m_verification_failed accordingly @@ -2067,7 +2067,7 @@ namespace cryptonote if (bvc.m_verifivation_failed) { bool pulse = cryptonote::block_has_pulse_components(b); - oxen::log::error(oxen::log::Cat("verify"), "{} block failed verification\n{}", (pulse ? "Pulse" : "Mined"), cryptonote::obj_to_json_str(b)); + log::error(log::Cat("verify"), "{} block failed verification\n{}", (pulse ? "Pulse" : "Mined"), cryptonote::obj_to_json_str(b)); return false; } else if(bvc.m_added_to_main_chain) @@ -2077,7 +2077,7 @@ namespace cryptonote m_blockchain_storage.get_transactions_blobs(b.tx_hashes, txs, &missed_txs); if(missed_txs.size() && m_blockchain_storage.get_block_id_by_height(get_block_height(b)) != get_block_hash(b)) { - oxen::log::info(logcat, "Block found but, seems that reorganize just happened after that, do not relay this block"); + log::info(logcat, "Block found but, seems that reorganize just happened after that, do not relay this block"); return true; } CHECK_AND_ASSERT_MES(txs.size() == b.tx_hashes.size() && !missed_txs.size(), false, "can't find some transactions in found block:" << get_block_hash(b) << " txs.size()=" << txs.size() @@ -2147,7 +2147,7 @@ namespace cryptonote } if (((size_t)-1) <= 0xffffffff && block_blob.size() >= 0x3fffffff) - oxen::log::warning(logcat, "This block's size is {}, closing on the 32 bit limit", block_blob.size()); + log::warning(logcat, "This block's size is {}, closing on the 32 bit limit", block_blob.size()); CHECK_AND_ASSERT_MES(update_checkpoints_from_json_file(), false, "One or more checkpoints loaded from json conflicted with existing checkpoints."); @@ -2157,7 +2157,7 @@ namespace cryptonote crypto::hash block_hash; if(!parse_and_validate_block_from_blob(block_blob, lb, block_hash)) { - oxen::log::info(logcat, "Failed to parse and validate new block"); + log::info(logcat, "Failed to parse and validate new block"); bvc.m_verifivation_failed = true; return false; } @@ -2182,7 +2182,7 @@ namespace cryptonote // plus the tx hashes, the weight will typically be much larger than the blob size if(block_blob.size() > m_blockchain_storage.get_current_cumulative_block_weight_limit() + BLOCK_SIZE_SANITY_LEEWAY) { - oxen::log::info(logcat, "WRONG BLOCK BLOB, sanity check failed on size {}, rejected", block_blob.size()); + log::info(logcat, "WRONG BLOCK BLOB, sanity check failed on size {}, rejected", block_blob.size()); return false; } return true; @@ -2231,7 +2231,7 @@ namespace cryptonote const std::chrono::seconds elapsed{std::time(nullptr) - last_ping}; if (elapsed > lifetime) { - oxen::log::warning(logcat, "Have not heard from {} {}", what, + log::warning(logcat, "Have not heard from {} {}", what, (!last_ping ? "since starting" : "since more than " + tools::get_human_readable_timespan(elapsed) + " ago")); return false; @@ -2268,7 +2268,7 @@ namespace cryptonote auto pubkey = m_service_node_list.get_pubkey_from_x25519(m_service_keys.pub_x25519); if (pubkey != crypto::null_pkey && pubkey != m_service_keys.pub && m_service_node_list.is_service_node(pubkey, false /*don't require active*/)) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as this service node. This typically means both have the same 'key_ed25519' private key file.")); return; } @@ -2284,7 +2284,7 @@ namespace cryptonote if (pk != m_service_keys.pub && proof.proof->public_ip == m_sn_public_ip && (proof.proof->qnet_port == m_quorumnet_port || ( m_nettype != network_type::DEVNET && (proof.proof->storage_https_port == storage_https_port() || proof.proof->storage_omq_port == storage_omq_port())))) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Another service node ({}) is broadcasting the same public IP and ports as this service node ({}:{}[qnet], :{}[SS-HTTP], :{}[SS-LMQ]). This will lead to deregistration of one or both service nodes if not corrected. (Do both service nodes have the correct IP for the service-node-public-ip setting?)", pk, epee::string_tools::get_ip_string_from_int32(m_sn_public_ip), proof.proof->qnet_port, proof.proof->storage_https_port, proof.proof->storage_omq_port)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Another service node ({}) is broadcasting the same public IP and ports as this service node ({}:{}[qnet], :{}[SS-HTTP], :{}[SS-LMQ]). This will lead to deregistration of one or both service nodes if not corrected. (Do both service nodes have the correct IP for the service-node-public-ip setting?)", pk, epee::string_tools::get_ip_string_from_int32(m_sn_public_ip), proof.proof->qnet_port, proof.proof->storage_https_port, proof.proof->storage_omq_port)); }); } @@ -2292,13 +2292,13 @@ namespace cryptonote { if (!check_external_ping(m_last_storage_server_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "the storage server")) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to submit uptime proof: have not heard from the storage server recently. Make sure that it is running! It is required to run alongside the Loki daemon")); return; } if (!check_external_ping(m_last_lokinet_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "Lokinet")) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to submit uptime proof: have not heard from lokinet recently. Make sure that it is running! It is required to run alongside the Loki daemon")); return; } @@ -2323,7 +2323,7 @@ namespace cryptonote main_message = "The daemon is running offline and will not attempt to sync to the Loki network."; else main_message = "The daemon will start synchronizing with the network. This may take a long time to complete."; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ {}\n\n\ You can set the level of process detailization through \"set_log \" command,\n\ where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING).\n\ @@ -2361,7 +2361,7 @@ Use \"help \" to see a command's documentation.\n\ { uint64_t free_space = get_free_space(); if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Free space is below 1 GB on {}", m_config_folder)); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Free space is below 1 GB on {}", m_config_folder)); return true; } //----------------------------------------------------------------------------------------------- @@ -2401,7 +2401,7 @@ Use \"help \" to see a command's documentation.\n\ { if (m_offline || m_nettype == network_type::FAKECHAIN || m_target_blockchain_height > get_current_blockchain_height() || m_target_blockchain_height == 0) { - oxen::log::debug(logcat, "Not checking block rate, offline or syncing"); + log::debug(logcat, "Not checking block rate, offline or syncing"); return true; } @@ -2418,10 +2418,10 @@ Use \"help \" to see a command's documentation.\n\ const time_t time_boundary = now - static_cast(seconds[n]); for (time_t ts: timestamps) b += ts >= time_boundary; const double p = probability(b, seconds[n] / tools::to_seconds(TARGET_BLOCK_TIME)); - oxen::log::debug(logcat, "blocks in the last {} minutes: {} (probability {})", seconds[n] / 60, b, p); + log::debug(logcat, "blocks in the last {} minutes: {} (probability {})", seconds[n] / 60, b, p); if (p < threshold) { - oxen::log::warning(logcat, "There were {}{} blocks in the last {} minutes, \ + log::warning(logcat, "There were {}{} blocks in the last {} minutes, \ there might be large hash rate changes, or we might be partitioned, \ cut off from the Loki network or under attack, or your computer's time is off. \ Or it could be just sheer bad luck.", b, (b == max_blocks_checked ? " or more" : ""), seconds[n] / 60); diff --git a/src/cryptonote_core/cryptonote_tx_utils.cpp b/src/cryptonote_core/cryptonote_tx_utils.cpp index 6bc59123d..18e6fb16a 100644 --- a/src/cryptonote_core/cryptonote_tx_utils.cpp +++ b/src/cryptonote_core/cryptonote_tx_utils.cpp @@ -78,7 +78,7 @@ namespace cryptonote } } } - oxen::log::debug(globallogcat, "destinations include {} standard addresses and {} subaddresses", num_stdaddresses, num_subaddresses); + log::debug(globallogcat, "destinations include {} standard addresses and {} subaddresses", num_stdaddresses, num_subaddresses); } keypair get_deterministic_keypair_from_height(uint64_t height) @@ -127,7 +127,7 @@ namespace cryptonote if (!get_deterministic_output_key(governance_wallet_address.address, gov_key, output_index, correct_key)) { - oxen::log::error(globallogcat, "Failed to generate deterministic output key for governance wallet output validation"); + log::error(globallogcat, "Failed to generate deterministic output key for governance wallet output validation"); return false; } @@ -289,7 +289,7 @@ namespace cryptonote block_reward_parts reward_parts{}; if(!get_oxen_block_reward(median_weight, current_block_weight, already_generated_coins, hard_fork_version, reward_parts, block_reward_context)) { - oxen::log::warning(globallogcat, "Failed to calculate block reward"); + log::warning(globallogcat, "Failed to calculate block reward"); return std::make_pair(false, block_rewards); } @@ -459,7 +459,7 @@ namespace cryptonote if (!get_deterministic_output_key(address, derivation_pair, it - rewards.begin(), out_eph_public_key)) { - oxen::log::error(globallogcat, "Failed to generate output one-time public key"); + log::error(globallogcat, "Failed to generate output one-time public key"); return std::make_pair(false, block_rewards); } @@ -515,13 +515,13 @@ namespace cryptonote uint64_t base_reward, base_reward_unpenalized; if (!get_base_block_reward(median_weight, current_block_weight, already_generated_coins, base_reward, base_reward_unpenalized, hard_fork_version, oxen_context.height)) { - oxen::log::error(globallogcat, "Failed to calculate base block reward"); + log::error(globallogcat, "Failed to calculate base block reward"); return false; } if (base_reward == 0) { - oxen::log::error(globallogcat, "Unexpected base reward of 0"); + log::error(globallogcat, "Unexpected base reward of 0"); return false; } @@ -575,9 +575,9 @@ namespace cryptonote if (allocated > base_reward_unpenalized || remainder != 0) { if (allocated > base_reward_unpenalized) - oxen::log::error(globallogcat, "We allocated more reward {} than what was available {}", cryptonote::print_money(allocated), cryptonote::print_money(base_reward_unpenalized)); + log::error(globallogcat, "We allocated more reward {} than what was available {}", cryptonote::print_money(allocated), cryptonote::print_money(base_reward_unpenalized)); else - oxen::log::error(globallogcat, "We allocated reward but there was still {} oxen left to distribute.", cryptonote::print_money(remainder)); + log::error(globallogcat, "We allocated reward but there was still {} oxen left to distribute.", cryptonote::print_money(remainder)); return false; } } @@ -618,7 +618,7 @@ namespace cryptonote if (sources.empty()) { - oxen::log::error(globallogcat, "Empty sources"); + log::error(globallogcat, "Empty sources"); return false; } @@ -640,7 +640,7 @@ namespace cryptonote if (tx_params.burn_percent) { - oxen::log::error(globallogcat, "cannot construct tx: internal error: burn percent must be converted to fixed burn amount in the wallet"); + log::error(globallogcat, "cannot construct tx: internal error: burn percent must be converted to fixed burn amount in the wallet"); return false; } @@ -651,7 +651,7 @@ namespace cryptonote crypto::secret_key tx_sk{tx_key}; if (!hwdev.update_staking_tx_secret_key(tx_sk)) { - oxen::log::warning(globallogcat, "Failed to add tx secret key to stake transaction"); + log::warning(globallogcat, "Failed to add tx secret key to stake transaction"); return false; } cryptonote::add_tx_secret_key_to_tx_extra(tx.extra, tx_sk); @@ -670,17 +670,17 @@ namespace cryptonote crypto::hash8 payment_id8 = null_hash8; if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { - oxen::log::debug(globallogcat, "Encrypting payment id {}", payment_id8); + log::debug(globallogcat, "Encrypting payment id {}", payment_id8); crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); if (view_key_pub == null_pkey) { - oxen::log::error(globallogcat, "Destinations have to have exactly one output to support encrypted payment ids"); + log::error(globallogcat, "Destinations have to have exactly one output to support encrypted payment ids"); return false; } if (!hwdev.encrypt_payment_id(payment_id8, view_key_pub, tx_key)) { - oxen::log::error(globallogcat, "Failed to encrypt payment id"); + log::error(globallogcat, "Failed to encrypt payment id"); return false; } @@ -689,10 +689,10 @@ namespace cryptonote remove_field_from_tx_extra(tx.extra); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) { - oxen::log::error(globallogcat, "Failed to add encrypted payment id to tx extra"); + log::error(globallogcat, "Failed to add encrypted payment id to tx extra"); return false; } - oxen::log::info(globallogcat, "Encrypted payment ID: {}", payment_id8); + log::info(globallogcat, "Encrypted payment ID: {}", payment_id8); add_dummy_payment_id = false; } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) @@ -714,7 +714,7 @@ namespace cryptonote crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); if (view_key_pub == null_pkey) { - oxen::log::error(globallogcat, "Failed to get key to encrypt dummy payment id with"); + log::error(globallogcat, "Failed to get key to encrypt dummy payment id with"); } else { @@ -722,7 +722,7 @@ namespace cryptonote set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) { - oxen::log::error(globallogcat, "Failed to add dummy encrypted payment id to tx extra"); + log::error(globallogcat, "Failed to add dummy encrypted payment id to tx extra"); // continue anyway } } @@ -730,7 +730,7 @@ namespace cryptonote } else { - oxen::log::warning(globallogcat, "Failed to parse tx extra"); + log::warning(globallogcat, "Failed to parse tx extra"); tx_extra_fields.clear(); } @@ -748,7 +748,7 @@ namespace cryptonote ++idx; if(src_entr.real_output >= src_entr.outputs.size()) { - oxen::log::error(globallogcat, "real_output index ({})bigger than output_keys.size()={}", src_entr.real_output, src_entr.outputs.size()); + log::error(globallogcat, "real_output index ({})bigger than output_keys.size()={}", src_entr.real_output, src_entr.outputs.size()); return false; } summary_inputs_money += src_entr.amount; @@ -760,16 +760,16 @@ namespace cryptonote const auto& out_key = reinterpret_cast(src_entr.outputs[src_entr.real_output].second.dest); if(!generate_key_image_helper(sender_account_keys, subaddresses, out_key, src_entr.real_out_tx_key, src_entr.real_out_additional_tx_keys, src_entr.real_output_in_tx_index, in_ephemeral,img, hwdev)) { - oxen::log::error(globallogcat, "Key image generation failed!"); + log::error(globallogcat, "Key image generation failed!"); return false; } //check that derivated key is equal with real output key (if non multisig) if(!msout && !(in_ephemeral.pub == src_entr.outputs[src_entr.real_output].second.dest) ) { - oxen::log::error(globallogcat, "derived public key mismatch with output public key at index {}, real out {}!\nderived_key: {}\nreal output_public_key: {}", idx, src_entr.real_output, tools::type_to_hex(in_ephemeral.pub), tools::type_to_hex(src_entr.outputs[src_entr.real_output].second.dest)); - oxen::log::error(globallogcat, "amount {}, rct {}", src_entr.amount, src_entr.rct); - oxen::log::error(globallogcat, "tx pubkey {}, real_output_in_tx_index {}", src_entr.real_out_tx_key, src_entr.real_output_in_tx_index); + log::error(globallogcat, "derived public key mismatch with output public key at index {}, real out {}!\nderived_key: {}\nreal output_public_key: {}", idx, src_entr.real_output, tools::type_to_hex(in_ephemeral.pub), tools::type_to_hex(src_entr.outputs[src_entr.real_output].second.dest)); + log::error(globallogcat, "amount {}, rct {}", src_entr.amount, src_entr.rct); + log::error(globallogcat, "tx pubkey {}, real_output_in_tx_index {}", src_entr.real_out_tx_key, src_entr.real_output_in_tx_index); return false; } @@ -874,7 +874,7 @@ namespace cryptonote keypair ephemeral_keys{}; if(!generate_key_image_helper(sender_account_keys, subaddresses, out_eph_public_key, txkey_pub, additional_tx_public_keys, output_index, ephemeral_keys, proof.key_image, hwdev)) { - oxen::log::error(globallogcat, "Key image generation failed for staking TX!"); + log::error(globallogcat, "Key image generation failed for staking TX!"); return false; } @@ -904,12 +904,12 @@ namespace cryptonote remove_field_from_tx_extra(tx.extra); - oxen::log::debug(globallogcat, "tx pubkey: {}", txkey_pub); + log::debug(globallogcat, "tx pubkey: {}", txkey_pub); if (need_additional_txkeys) { - oxen::log::debug(globallogcat, "additional tx pubkeys: "); + log::debug(globallogcat, "additional tx pubkeys: "); for (size_t i = 0; i < additional_tx_public_keys.size(); ++i) - oxen::log::debug(globallogcat, "{}", additional_tx_public_keys[i]); + log::debug(globallogcat, "{}", additional_tx_public_keys[i]); add_additional_tx_pub_keys_to_extra(tx.extra, additional_tx_public_keys); } @@ -919,7 +919,7 @@ namespace cryptonote //check money if(summary_outs_money > summary_inputs_money ) { - oxen::log::error(globallogcat, "Transaction inputs money ({}) less than outputs money ({})", summary_inputs_money, summary_outs_money); + log::error(globallogcat, "Transaction inputs money ({}) less than outputs money ({})", summary_inputs_money, summary_outs_money); return false; } @@ -929,7 +929,7 @@ namespace cryptonote zero_secret_key &= (sender_account_keys.m_spend_secret_key.data[i] == 0); if (zero_secret_key) { - oxen::log::debug(globallogcat, "Null secret key, skipping signatures"); + log::debug(globallogcat, "Null secret key, skipping signatures"); } uint64_t amount_in = 0, amount_out = 0; @@ -979,13 +979,13 @@ namespace cryptonote { if (amount_in < amount_out + tx_params.burn_fixed) { - oxen::log::error(globallogcat, "invalid burn amount: tx does not have enough unspent funds available; amount_in: {}; amount_out + tx_params.burn_fixed: {} + {}", std::to_string(amount_in), std::to_string(amount_out), std::to_string(tx_params.burn_fixed)); + log::error(globallogcat, "invalid burn amount: tx does not have enough unspent funds available; amount_in: {}; amount_out + tx_params.burn_fixed: {} + {}", std::to_string(amount_in), std::to_string(amount_out), std::to_string(tx_params.burn_fixed)); return false; } remove_field_from_tx_extra(tx.extra); // doesn't have to be present (but the wallet puts a dummy here as a safety to avoid growing the tx) if (!add_burned_amount_to_tx_extra(tx.extra, tx_params.burn_fixed)) { - oxen::log::error(globallogcat, "failed to add burn amount to tx extra"); + log::error(globallogcat, "failed to add burn amount to tx extra"); return false; } } @@ -1007,7 +1007,7 @@ namespace cryptonote CHECK_AND_ASSERT_MES(tx.vout.size() == outSk.size(), false, "outSk size does not match vout"); - oxen::log::info(oxen::log::Cat("construct_tx"), "transaction_created: {}\n{}\n", get_transaction_hash(tx), obj_to_json_str(tx)); + log::info(log::Cat("construct_tx"), "transaction_created: {}\n{}\n", get_transaction_hash(tx), obj_to_json_str(tx)); tx.invalidate_hashes(); diff --git a/src/cryptonote_core/oxen_name_system.cpp b/src/cryptonote_core/oxen_name_system.cpp index b0eeda481..a7bef7cde 100644 --- a/src/cryptonote_core/oxen_name_system.cpp +++ b/src/cryptonote_core/oxen_name_system.cpp @@ -40,7 +40,8 @@ using cryptonote::hf; namespace ons { -static auto logcat = oxen::log::Cat("ons"); +namespace log = oxen::log; +static auto logcat = log::Cat("ons"); enum struct ons_sql_type { @@ -361,7 +362,7 @@ bool sql_copy_blob(sql_compiled_statement& statement, I column, void *dest, size auto blob = get(statement, column); if (blob.data.size() != dest_size) { - oxen::log::warning(logcat, "Unexpected blob size={}, in ONS DB does not match expected size={}", blob.data.size(), dest_size); + log::warning(logcat, "Unexpected blob size={}, in ONS DB does not match expected size={}", blob.data.size(), dest_size); assert(blob.data.size() == dest_size); return false; } @@ -389,7 +390,7 @@ mapping_record sql_get_mapping_from_statement(sql_compiled_statement& statement) auto value = get(statement, mapping_record_column::encrypted_value); if (value.size() > result.encrypted_value.buffer.size()) { - oxen::log::error(logcat, "Unexpected encrypted value blob with size={}, in ONS db larger than the available size={}", value.size(), result.encrypted_value.buffer.size()); + log::error(logcat, "Unexpected encrypted value blob with size={}, in ONS db larger than the available size={}", value.size(), result.encrypted_value.buffer.size()); return result; } result.encrypted_value.len = value.size(); @@ -435,7 +436,7 @@ bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, voi { switch (type) { - default: oxen::log::error(logcat, "Unhandled ons type enum with value: {}, in: {}", (int)type, __func__); break; + default: log::error(logcat, "Unhandled ons type enum with value: {}, in: {}", (int)type, __func__); break; case ons_sql_type::internal_cmd: break; case ons_sql_type::get_owner: @@ -499,7 +500,7 @@ bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, voi default: { - oxen::log::info(logcat, "Failed to execute statement: {}, reason: {}", sqlite3_sql(statement.statement), sqlite3_errstr(step_result)); + log::info(logcat, "Failed to execute statement: {}, reason: {}", sqlite3_sql(statement.statement), sqlite3_errstr(step_result)); infinite_loop = false; break; } @@ -541,7 +542,7 @@ bool sql_compiled_statement::compile(std::string_view query, bool optimise_for_m #endif if (prepare_result != SQLITE_OK) { - oxen::log::error(logcat, "Can not compile SQL statement:\n{}\nReason: {}", query, sqlite3_errstr(prepare_result)); + log::error(logcat, "Can not compile SQL statement:\n{}\nReason: {}", query, sqlite3_errstr(prepare_result)); return false; } sqlite3_finalize(statement); @@ -568,7 +569,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int sql_init = sqlite3_initialize(); if (sql_init != SQLITE_OK) { - oxen::log::error(logcat, "Failed to initialize sqlite3: {}", sqlite3_errstr(sql_init)); + log::error(logcat, "Failed to initialize sqlite3: {}", sqlite3_errstr(sql_init)); return nullptr; } @@ -576,7 +577,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int sql_open = sqlite3_open_v2(file_path.u8string().c_str(), &result, flags, nullptr); if (sql_open != SQLITE_OK) { - oxen::log::error(logcat, "Failed to open ONS db at: {}, reason: {}", file_path, sqlite3_errstr(sql_open)); + log::error(logcat, "Failed to open ONS db at: {}, reason: {}", file_path, sqlite3_errstr(sql_open)); return nullptr; } @@ -591,7 +592,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) int exec = sqlite3_exec(result, "PRAGMA journal_mode = WAL", nullptr, nullptr, nullptr); if (exec != SQLITE_OK) { - oxen::log::error(logcat, "Failed to set journal mode to WAL: {}", sqlite3_errstr(exec)); + log::error(logcat, "Failed to set journal mode to WAL: {}", sqlite3_errstr(exec)); return nullptr; } @@ -605,7 +606,7 @@ sqlite3 *init_oxen_name_system(const fs::path& file_path, bool read_only) exec = sqlite3_exec(result, "PRAGMA synchronous = NORMAL", nullptr, nullptr, nullptr); if (exec != SQLITE_OK) { - oxen::log::error(logcat, "Failed to set synchronous mode to NORMAL: {}", sqlite3_errstr(exec)); + log::error(logcat, "Failed to set synchronous mode to NORMAL: {}", sqlite3_errstr(exec)); return nullptr; } @@ -664,7 +665,7 @@ std::string tx_extra_signature(std::string_view value, ons::generic_owner const static_assert(sizeof(crypto::hash) == crypto_generichash_BYTES, "Using libsodium generichash for signature hash, require we fit into crypto::hash"); if (value.size() > mapping_value::BUFFER_SIZE) { - oxen::log::error(logcat, "Unexpected value len={} greater than the expected capacity={}", value.size(), mapping_value::BUFFER_SIZE); + log::error(logcat, "Unexpected value len={} greater than the expected capacity={}", value.size(), mapping_value::BUFFER_SIZE); return ""s; } @@ -858,7 +859,7 @@ bool validate_ons_name(mapping_type type, std::string name, std::string *reason) } else { - oxen::log::error(logcat, "Type not implemented"); + log::error(logcat, "Type not implemented"); return false; } @@ -1410,7 +1411,7 @@ bool mapping_value::encrypt(std::string_view name, const crypto::hash* name_hash if (encryption_len > buffer.size()) { - oxen::log::error(logcat, "Encrypted value pre-allocated buffer too small={}, required={}", buffer.size(), encryption_len); + log::error(logcat, "Encrypted value pre-allocated buffer too small={}, required={}", buffer.size(), encryption_len); return false; } @@ -1482,18 +1483,18 @@ bool mapping_value::decrypt(std::string_view name, mapping_type type, const cryp plain_len == WALLET_ACCOUNT_BINARY_LENGTH_INC_PAYMENT_ID || plain_len == WALLET_ACCOUNT_BINARY_LENGTH_NO_PAYMENT_ID) { dec_length = plain_len; } else { - oxen::log::error(logcat, "Invalid wallet mapping_type length passed to mapping_value::decrypt"); + log::error(logcat, "Invalid wallet mapping_type length passed to mapping_value::decrypt"); return false; } break; - default: oxen::log::error(logcat, "Invalid mapping_type passed to mapping_value::decrypt"); + default: log::error(logcat, "Invalid mapping_type passed to mapping_value::decrypt"); return false; } auto expected_len = dec_length + crypto_aead_xchacha20poly1305_ietf_ABYTES + crypto_aead_xchacha20poly1305_ietf_NPUBBYTES; if (len != expected_len) { - oxen::log::error(logcat, "Encrypted value size is invalid={}, expected={}", len, expected_len); + log::error(logcat, "Encrypted value size is invalid={}, expected={}", len, expected_len); return false; } const auto& [enc, nonce] = value_nonce(type); @@ -1597,7 +1598,7 @@ CREATE INDEX IF NOT EXISTS mapping_type_name_exp ON mappings (type, name_hash, e int table_created = sqlite3_exec(ons_db.db, BUILD_TABLE_SQL.c_str(), nullptr /*callback*/, nullptr /*callback context*/, &table_err_msg); if (table_created != SQLITE_OK) { - oxen::log::error(logcat, "Can not generate SQL table for ONS: {}", (table_err_msg ? table_err_msg : "??")); + log::error(logcat, "Can not generate SQL table for ONS: {}", (table_err_msg ? table_err_msg : "??")); sqlite3_free(table_err_msg); return false; } @@ -1627,7 +1628,7 @@ CREATE INDEX IF NOT EXISTS mapping_type_name_exp ON mappings (type, name_hash, e "ALTER TABLE mappings ADD COLUMN update_height INTEGER NOT NULL DEFAULT register_height", nullptr /*callback*/, nullptr /*callback ctx*/, nullptr /*errstr*/); - oxen::log::info(logcat, "Migrating ONS mappings database to new format"); + log::info(logcat, "Migrating ONS mappings database to new format"); const std::string migrate = R"( BEGIN TRANSACTION; ALTER TABLE mappings RENAME TO mappings_old; @@ -1646,7 +1647,7 @@ COMMIT TRANSACTION; int migrated = sqlite3_exec(ons_db.db, migrate.c_str(), nullptr /*callback*/, nullptr /*callback context*/, &table_err_msg); if (migrated != SQLITE_OK) { - oxen::log::error(logcat, "Can not migrate SQL mappings table for ONS: {}", (table_err_msg ? table_err_msg : "??")); + log::error(logcat, "Can not migrate SQL mappings table for ONS: {}", (table_err_msg ? table_err_msg : "??")); sqlite3_free(table_err_msg); return false; } @@ -1687,14 +1688,14 @@ scoped_db_transaction::scoped_db_transaction(name_system_db &ons_db) { if (ons_db.transaction_begun) { - oxen::log::error(logcat, "Failed to begin transaction, transaction exists previously that was not closed properly"); + log::error(logcat, "Failed to begin transaction, transaction exists previously that was not closed properly"); return; } char *sql_err = nullptr; if (sqlite3_exec(ons_db.db, "BEGIN;", nullptr, nullptr, &sql_err) != SQLITE_OK) { - oxen::log::error(logcat, "Failed to begin transaction , reason={}", (sql_err ? sql_err : "??")); + log::error(logcat, "Failed to begin transaction , reason={}", (sql_err ? sql_err : "??")); sqlite3_free(sql_err); return; } @@ -1708,14 +1709,14 @@ scoped_db_transaction::~scoped_db_transaction() if (!initialised) return; if (!ons_db.transaction_begun) { - oxen::log::error(logcat, "Trying to apply non-existent transaction (no prior history of a db transaction beginning) to the ONS DB"); + log::error(logcat, "Trying to apply non-existent transaction (no prior history of a db transaction beginning) to the ONS DB"); return; } char *sql_err = nullptr; if (sqlite3_exec(ons_db.db, commit ? "END;" : "ROLLBACK;", NULL, NULL, &sql_err) != SQLITE_OK) { - oxen::log::error(logcat, "Failed to {} transaction to ONS DB, reason={}", (commit ? "end " : "rollback "), (sql_err ? sql_err : "??")); + log::error(logcat, "Failed to {} transaction to ONS DB, reason={}", (commit ? "end " : "rollback "), (sql_err ? sql_err : "??")); sqlite3_free(sql_err); return; } @@ -1792,13 +1793,13 @@ AND NOT EXISTS (SELECT * FROM mappings WHERE owner.id = mappings.backup_owner_ { if (!blockchain) { - oxen::log::error(logcat, "Migration required, blockchain can not be nullptr"); + log::error(logcat, "Migration required, blockchain can not be nullptr"); return false; } if (blockchain->get_db().is_read_only()) { - oxen::log::error(logcat, "DB is opened in read-only mode, unable to migrate ONS DB"); + log::error(logcat, "DB is opened in read-only mode, unable to migrate ONS DB"); return false; } @@ -1949,7 +1950,7 @@ std::optional add_or_get_owner_id(ons::name_system_db &ons_db, crypto:: { if (!ons_db.save_owner(key, &result)) { - oxen::log::info(logcat, "Failed to save ONS owner to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); + log::info(logcat, "Failed to save ONS owner to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); return std::nullopt; } } @@ -1994,7 +1995,7 @@ SELECT type, name_hash, ?, ?)"; auto opt_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.owner); if (!opt_id) { - oxen::log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); + log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); assert(opt_id); return {}; } @@ -2009,7 +2010,7 @@ SELECT type, name_hash, ?, ?)"; auto opt_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.backup_owner); if (!opt_id) { - oxen::log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); + log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); assert(opt_id); return {}; } @@ -2046,7 +2047,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ auto owner_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.owner); if (!owner_id) { - oxen::log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); + log::error(logcat, "Failed to add or get owner with key={}", entry.owner.to_string(ons_db.network_type())); assert(owner_id); return false; } @@ -2057,7 +2058,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ backup_owner_id = add_or_get_owner_id(ons_db, tx_hash, entry, entry.backup_owner); if (!backup_owner_id) { - oxen::log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); + log::error(logcat, "Failed to add or get backup owner with key={}", entry.backup_owner.to_string(ons_db.network_type())); assert(backup_owner_id); return false; } @@ -2067,7 +2068,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ if (expiry) *expiry += height; if (!ons_db.save_mapping(tx_hash, entry, height, expiry, *owner_id, backup_owner_id)) { - oxen::log::info(logcat, "Failed to save ONS entry to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); + log::info(logcat, "Failed to save ONS entry to DB tx: {}, type: {}, name_hash: {}, owner: {}", tx_hash, entry.type, entry.name_hash, entry.owner.to_string(ons_db.network_type())); return false; } } @@ -2085,7 +2086,7 @@ bool add_ons_entry(ons::name_system_db &ons_db, uint64_t height, cryptonote::tx_ sql_compiled_statement statement{ons_db}; if (!statement.compile(sql, false /*optimise_for_multiple_usage*/)) { - oxen::log::error(logcat, "Failed to compile SQL statement for updating ONS record={}", sql); + log::error(logcat, "Failed to compile SQL statement for updating ONS record={}", sql); return false; } @@ -2123,7 +2124,7 @@ bool name_system_db::add_block(const cryptonote::block &block, const std::vector std::string fail_reason; if (!validate_ons_tx(block.major_version, height, tx, entry, &fail_reason)) { - oxen::log::error(logcat, "ONS TX: Failed to validate for tx={}. This should have failed validation earlier reason={}", get_transaction_hash(tx), fail_reason); + log::error(logcat, "ONS TX: Failed to validate for tx={}. This should have failed validation earlier reason={}", get_transaction_hash(tx), fail_reason); assert("Failed to validate acquire name service. Should already have failed validation prior" == nullptr); return false; } diff --git a/src/cryptonote_core/pulse.cpp b/src/cryptonote_core/pulse.cpp index f7c8273c6..fbaf7eaff 100644 --- a/src/cryptonote_core/pulse.cpp +++ b/src/cryptonote_core/pulse.cpp @@ -18,7 +18,15 @@ extern "C" #include }; -static auto logcat = oxen::log::Cat("pulse"); +namespace pulse +{ + +namespace log = oxen::log; + +namespace +{ + +auto logcat = log::Cat("pulse"); // Deliberately makes pulse communications flakey for testing purposes: //#define PULSE_TEST_CODE @@ -214,9 +222,7 @@ struct round_context round_state state; }; -static round_context context; -namespace -{ +round_context context; crypto::hash blake2b_hash(void const *data, size_t size) { @@ -456,7 +462,7 @@ bool enforce_validator_participation_and_timeouts(round_context const &context, if (timed_out && !all_received) { - oxen::log::debug(logcat, "{}Stage timed out: insufficient responses. Expected ({}) {} received ({}) {}", log_prefix(context), bitset_view16(validator_bitset).count(), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string()); + log::debug(logcat, "{}Stage timed out: insufficient responses. Expected ({}) {} received ({}) {}", log_prefix(context), bitset_view16(validator_bitset).count(), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string()); return false; } @@ -466,7 +472,7 @@ bool enforce_validator_participation_and_timeouts(round_context const &context, bool unexpected_items = (stage.bitset | validator_bitset) != validator_bitset; if (stage.msgs_received == 0 || unexpected_items) { - oxen::log::error(logcat, "{}Internal error: expected bitset {}, but accepted and received {}", log_prefix(context), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).to_string()); + log::error(logcat, "{}Internal error: expected bitset {}, but accepted and received {}", log_prefix(context), bitset_view16(validator_bitset).to_string(), bitset_view16(stage.bitset).to_string()); return false; } @@ -475,7 +481,7 @@ bool enforce_validator_participation_and_timeouts(round_context const &context, } // anonymous namespace -void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) +void handle_message(void *quorumnet_state, pulse::message const &msg) { if (context.state < round_state::wait_for_round) { @@ -520,13 +526,13 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) // marked an error, just ignored. print_err = false; - oxen::log::trace(logcat, "{}Received valid message from the past (round {}), ignoring", log_prefix(context), +msg.round); + log::trace(logcat, "{}Received valid message from the past (round {}), ignoring", log_prefix(context), +msg.round); break; } // else: Message has unknown origins, it is not something we know how to validate. } if (print_err) - oxen::log::error(logcat, sig_check_err); + log::error(logcat, sig_check_err); return; } @@ -536,7 +542,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) { case pulse::message_type::invalid: { - oxen::log::trace(logcat, "{}Received invalid message type, dropped", log_prefix(context)); + log::trace(logcat, "{}Received invalid message type, dropped", log_prefix(context)); return; } @@ -565,7 +571,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto &[entry, queued] = stage->queue.buffer[msg.quorum_position]; if (queued == queueing_state::empty) { - oxen::log::trace(logcat, "{}Message received early {}, queueing until we're ready.", log_prefix(context), msg_source_string(context, msg)); + log::trace(logcat, "{}Message received early {}, queueing until we're ready.", log_prefix(context), msg_source_string(context, msg)); stage->queue.count++; entry = std::move(msg); queued = queueing_state::received; @@ -583,14 +589,14 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) if ((validator_bit & context.transient.wait_for_handshake_bitsets.best_bitset) == 0) { auto bitset_view = bitset_view16(context.transient.wait_for_handshake_bitsets.best_bitset).to_string(); - oxen::log::trace(logcat, "{}Dropping {}. Not a locked in participant, bitset is {}", log_prefix(context), msg_source_string(context, msg), bitset_view); + log::trace(logcat, "{}Dropping {}. Not a locked in participant, bitset is {}", log_prefix(context), msg_source_string(context, msg), bitset_view); return; } } if (msg.quorum_position >= service_nodes::PULSE_QUORUM_NUM_VALIDATORS) { - oxen::log::trace(logcat, "{}Dropping {}. Message quorum position indexes oob", log_prefix(context), msg_source_string(context, msg)); + log::trace(logcat, "{}Dropping {}. Message quorum position indexes oob", log_prefix(context), msg_source_string(context, msg)); return; } @@ -608,7 +614,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto &quorum = context.transient.send_and_wait_for_handshakes.data; if (quorum[msg.quorum_position]) return; quorum[msg.quorum_position] = true; - oxen::log::trace(logcat, "{}Received handshake with quorum position bit ({}) {} saved to bitset {}", log_prefix(context), msg.quorum_position, bitset_view16(validator_bit).to_string(), bitset_view16(stage->bitset).to_string()); + log::trace(logcat, "{}Received handshake with quorum position bit ({}) {} saved to bitset {}", log_prefix(context), msg.quorum_position, bitset_view16(validator_bit).to_string(), bitset_view16(stage->bitset).to_string()); } break; @@ -629,13 +635,13 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) cryptonote::block block = {}; if (!cryptonote::t_serializable_object_from_blob(block, msg.block_template.blob)) { - oxen::log::trace(logcat, "{}Received unparsable pulse block template blob", log_prefix(context)); + log::trace(logcat, "{}Received unparsable pulse block template blob", log_prefix(context)); return; } if (block.pulse.round != context.prepare_for_round.round) { - oxen::log::trace(logcat, "{}Received pulse block template specifying different round {}, expected {}", log_prefix(context), +block.pulse.round, +context.prepare_for_round.round); + log::trace(logcat, "{}Received pulse block template specifying different round {}, expected {}", log_prefix(context), +block.pulse.round, +context.prepare_for_round.round); return; } @@ -643,7 +649,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) { auto block_bitset = bitset_view16(block.pulse.validator_bitset); auto our_bitset = bitset_view16(context.transient.wait_for_handshake_bitsets.best_bitset); - oxen::log::trace(logcat, "{}Received pulse block template specifying different validator handshake bitsets {}, expected {}", log_prefix(context), block_bitset.to_string(), our_bitset.to_string()); + log::trace(logcat, "{}Received pulse block template specifying different validator handshake bitsets {}, expected {}", log_prefix(context), block_bitset.to_string(), our_bitset.to_string()); return; } @@ -671,7 +677,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) auto derived = blake2b_hash(msg.random_value.value.data, sizeof(msg.random_value.value.data)); if (derived != *hash) { - oxen::log::trace(logcat, "{}Dropping {}. Rederived random value hash {} does not match original hash {}", log_prefix(context), msg_source_string(context, msg), derived, *hash); + log::trace(logcat, "{}Dropping {}. Rederived random value hash {} does not match original hash {}", log_prefix(context), msg_source_string(context, msg), derived, *hash); return; } } @@ -692,7 +698,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) crypto::public_key const &validator_key = context.prepare_for_round.quorum.validators[msg.quorum_position]; if (!crypto::check_signature(final_block_hash, validator_key, msg.signed_block.signature_of_final_block_hash)) { - oxen::log::trace(logcat, "{}Dropping {}. Signature signing final block hash {} does not validate with the Service Node", log_prefix(context), msg_source_string(context, msg), msg.signed_block.signature_of_final_block_hash); + log::trace(logcat, "{}Dropping {}. Signature signing final block hash {} does not validate with the Service Node", log_prefix(context), msg_source_string(context, msg), msg.signed_block.signature_of_final_block_hash); return; } @@ -712,7 +718,7 @@ void pulse::handle_message(void *quorumnet_state, pulse::message const &msg) } // TODO(doyle): Update pulse::perpare_for_round with this function after the hard fork and sanity check it on testnet. -bool pulse::convert_time_to_round(pulse::time_point const& time, pulse::time_point const& r0_timestamp, uint8_t* round) +bool convert_time_to_round(pulse::time_point const& time, pulse::time_point const& r0_timestamp, uint8_t* round) { const auto time_since_round_started = time <= r0_timestamp ? 0s : (time - r0_timestamp); size_t result_usize = time_since_round_started / service_nodes::PULSE_ROUND_TIME; @@ -720,7 +726,7 @@ bool pulse::convert_time_to_round(pulse::time_point const& time, pulse::time_poi return result_usize <= 255; } -bool pulse::get_round_timings(cryptonote::Blockchain const &blockchain, uint64_t block_height, uint64_t prev_timestamp, pulse::timings ×) +bool get_round_timings(cryptonote::Blockchain const &blockchain, uint64_t block_height, uint64_t prev_timestamp, pulse::timings ×) { times = {}; auto hf16 = hard_fork_begins(blockchain.nettype(), cryptonote::hf::hf16_pulse); @@ -749,6 +755,8 @@ bool pulse::get_round_timings(cryptonote::Blockchain const &blockchain, uint64_t return true; } +namespace { + /* Pulse progresses via a state-machine that is iterated through job submissions to 1 dedicated Pulse thread, started by LMQ. @@ -1042,7 +1050,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (context.wait_for_next_block.height == chain_height) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - oxen::log::debug(logcat, "{}Network is currently producing block {}, waiting until next block", log_prefix(context), chain_height); + log::debug(logcat, "{}Network is currently producing block {}, waiting until next block", log_prefix(context), chain_height); return round_state::wait_for_next_block; } @@ -1050,7 +1058,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (prev_hash == crypto::null_hash) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - oxen::log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); + log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); return round_state::wait_for_next_block; } @@ -1062,7 +1070,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr catch(std::exception const &e) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - oxen::log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); + log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); return round_state::wait_for_next_block; } @@ -1070,7 +1078,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr if (!get_round_timings(blockchain, chain_height, prev_timestamp, times)) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) - oxen::log::error(logcat, "{}Failed to query the block data for Pulse timings", log_prefix(context)); + log::error(logcat, "{}Failed to query the block data for Pulse timings", log_prefix(context)); return round_state::wait_for_next_block; } @@ -1129,7 +1137,7 @@ round_state prepare_for_round(round_context &context, service_nodes::service_nod if (round_usize > 255) // Network stalled { - oxen::log::info(logcat, "{}Pulse has timed out, reverting to accepting miner blocks only.", log_prefix(context)); + log::info(logcat, "{}Pulse has timed out, reverting to accepting miner blocks only.", log_prefix(context)); return goto_wait_for_next_block_and_clear_round_data(context); } @@ -1164,11 +1172,11 @@ round_state prepare_for_round(round_context &context, service_nodes::service_nod if (!service_nodes::verify_pulse_quorum_sizes(context.prepare_for_round.quorum)) { - oxen::log::info(logcat, "{}Insufficient Service Nodes to execute Pulse on height {}, we require a PoW miner block. Sleeping until next block.", log_prefix(context), context.wait_for_next_block.height); + log::info(logcat, "{}Insufficient Service Nodes to execute Pulse on height {}, we require a PoW miner block. Sleeping until next block.", log_prefix(context), context.wait_for_next_block.height); return goto_wait_for_next_block_and_clear_round_data(context); } - oxen::log::debug(logcat, "{}Generate Pulse quorum: {}", log_prefix(context), context.prepare_for_round.quorum); + log::debug(logcat, "{}Generate Pulse quorum: {}", log_prefix(context), context.prepare_for_round.quorum); // // NOTE: Quorum participation @@ -1204,7 +1212,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const const auto curr_height = blockchain.get_current_blockchain_height(true /*lock*/); if (context.wait_for_next_block.height != curr_height) { - oxen::log::debug(logcat, "{}Block height changed whilst waiting for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); + log::debug(logcat, "{}Block height changed whilst waiting for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); return goto_wait_for_next_block_and_clear_round_data(context); } @@ -1212,7 +1220,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const if (auto now = pulse::clock::now(); now < start_time) { for (static uint64_t last_height = 0; last_height != context.wait_for_next_block.height; last_height = context.wait_for_next_block.height) - oxen::log::info(logcat, "{}Waiting for round {} to start in {}", log_prefix(context), +context.prepare_for_round.round, tools::friendly_duration(start_time - now)); + log::info(logcat, "{}Waiting for round {} to start in {}", log_prefix(context), +context.prepare_for_round.round, tools::friendly_duration(start_time - now)); return round_state::wait_for_round; } @@ -1225,7 +1233,7 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const size_t faulty_chance = tools::uniform_distribution_portable(tools::rng, 100); if (faulty_chance < 10) { - oxen::log::debug(logcat, "{}FAULTY NODE ACTIVATED", log_prefix(context)); + log::debug(logcat, "{}FAULTY NODE ACTIVATED", log_prefix(context)); return goto_preparing_for_next_round(context); } @@ -1234,24 +1242,24 @@ round_state wait_for_round(round_context &context, cryptonote::Blockchain const { auto sleep_time = std::chrono::seconds(tools::uniform_distribution_portable(tools::rng, 20)); std::this_thread::sleep_for(sleep_time); - oxen::log::debug(logcat, "{}SLEEP TIME ACTIVATED {}s", log_prefix(context), tools::to_seconds(sleep_time)); + log::debug(logcat, "{}SLEEP TIME ACTIVATED {}s", log_prefix(context), tools::to_seconds(sleep_time)); } } #endif if (context.prepare_for_round.participant == sn_type::validator) { - oxen::log::info(logcat, "{}We are a pulse validator, sending handshake bit and collecting other handshakes.", log_prefix(context)); + log::info(logcat, "{}We are a pulse validator, sending handshake bit and collecting other handshakes.", log_prefix(context)); return round_state::send_and_wait_for_handshakes; } else if (context.prepare_for_round.participant == sn_type::producer) { - oxen::log::info(logcat, "{}We are the block producer for height {} in round {}, awaiting handshake bitsets.", log_prefix(context), context.wait_for_next_block.height, +context.prepare_for_round.round); + log::info(logcat, "{}We are the block producer for height {} in round {}, awaiting handshake bitsets.", log_prefix(context), context.wait_for_next_block.height, +context.prepare_for_round.round); return round_state::wait_for_handshake_bitsets; } else { - oxen::log::debug(logcat, "{}Non-participant for round, waiting on next round or block.", log_prefix(context)); + log::debug(logcat, "{}Non-participant for round, waiting on next round or block.", log_prefix(context)); return goto_preparing_for_next_round(context); } } @@ -1271,7 +1279,7 @@ round_state send_and_wait_for_handshakes(round_context &context, void *quorumnet } catch (std::exception const &e) { - oxen::log::error(logcat, "{}Attempting to invoke and send a Pulse participation handshake unexpectedly failed. {}", log_prefix(context), e.what()); + log::error(logcat, "{}Attempting to invoke and send a Pulse participation handshake unexpectedly failed. {}", log_prefix(context), e.what()); return goto_preparing_for_next_round(context); } } @@ -1292,7 +1300,7 @@ round_state send_and_wait_for_handshakes(round_context &context, void *quorumnet if (all_handshakes || timed_out) { bool missing_handshakes = timed_out && !all_handshakes; - oxen::log::info(logcat, "{}Collected validator handshakes {}{}Sending handshake bitset and collecting other validator bitsets.", log_prefix(context), bitset_view16(stage.bitset).to_string(), (missing_handshakes ? ", we timed out and some handshakes were not seen! " : ". ")); + log::info(logcat, "{}Collected validator handshakes {}{}Sending handshake bitset and collecting other validator bitsets.", log_prefix(context), bitset_view16(stage.bitset).to_string(), (missing_handshakes ? ", we timed out and some handshakes were not seen! " : ". ")); return round_state::send_handshake_bitsets; } else @@ -1310,7 +1318,7 @@ round_state send_handshake_bitsets(round_context &context, void *quorumnet_state } catch(std::exception const &e) { - oxen::log::error(logcat, "{}Attempting to invoke and send a Pulse validator bitset unexpectedly failed. {}", log_prefix(context), e.what()); + log::error(logcat, "{}Attempting to invoke and send a Pulse validator bitset unexpectedly failed. {}", log_prefix(context), e.what()); return goto_preparing_for_next_round(context); } } @@ -1340,7 +1348,7 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se best_bitset = *bitset; count = num; } - oxen::log::trace(logcat, "{}Collected from V[{}], handshake bitset {}", log_prefix(context), quorum_index, bitset_view16(*bitset).to_string()); + log::trace(logcat, "{}Collected from V[{}], handshake bitset {}", log_prefix(context), quorum_index, bitset_view16(*bitset).to_string()); } } @@ -1354,19 +1362,19 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se { // Less than the threshold of the validators can come to agreement about // which validators are online, we wait until the next round. - oxen::log::debug(logcat, "{}{}/{} \ + log::debug(logcat, "{}{}/{} \ validators did not send any handshake bitset or sent an empty handshake \ bitset and have failed to come to agreement. Waiting until next round.", log_prefix(context), count, quorum.size()); } else if (i_am_not_participating) { - oxen::log::debug(logcat, "{}The participating validator bitset {} does not include us (quorum index {}). Waiting until next round.", log_prefix(context), bitset_view16(best_bitset).to_string(), context.prepare_for_round.my_quorum_position); + log::debug(logcat, "{}The participating validator bitset {} does not include us (quorum index {}). Waiting until next round.", log_prefix(context), bitset_view16(best_bitset).to_string(), context.prepare_for_round.my_quorum_position); } else { // Can't come to agreement, see threshold comment above - oxen::log::debug(logcat, "{}We heard back from less than {} of the validators ({}/{}). Waiting until next round.", log_prefix(context), service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES, count, quorum.size()); + log::debug(logcat, "{}We heard back from less than {} of the validators ({}/{}). Waiting until next round.", log_prefix(context), service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES, count, quorum.size()); } return goto_preparing_for_next_round(context); @@ -1374,7 +1382,7 @@ round_state wait_for_handshake_bitsets(round_context &context, service_nodes::se context.transient.wait_for_handshake_bitsets.best_bitset = best_bitset; context.transient.wait_for_handshake_bitsets.best_count = count; - oxen::log::info(logcat, "{}{}/{} validators agreed on the participating nodes in the quorum {}{}", log_prefix(context), count, quorum.size(), + log::info(logcat, "{}{}/{} validators agreed on the participating nodes in the quorum {}{}", log_prefix(context), count, quorum.size(), bitset_view16(best_bitset).to_string(), (context.prepare_for_round.participant == sn_type::producer ? "" : ". Awaiting block template from block producer")); @@ -1396,14 +1404,14 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s // Invariants if (list_state.empty()) { - oxen::log::warning(logcat, "{}Block producer (us) is not available on the service node list, waiting until next round", log_prefix(context)); + log::warning(logcat, "{}Block producer (us) is not available on the service node list, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } std::shared_ptr info = list_state[0].info; if (!info->is_active()) { - oxen::log::warning(logcat, "{}Block producer (us) is not an active service node, waiting until next round", log_prefix(context)); + log::warning(logcat, "{}Block producer (us) is not an active service node, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } @@ -1418,13 +1426,13 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s context.transient.wait_for_handshake_bitsets.best_bitset, height)) { - oxen::log::error(logcat, "{}Failed to generate a block template, waiting until next round", log_prefix(context)); + log::error(logcat, "{}Failed to generate a block template, waiting until next round", log_prefix(context)); return goto_preparing_for_next_round(context); } if (context.wait_for_next_block.height != height) { - oxen::log::debug(logcat, "{}Block height changed whilst preparing block template for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); + log::debug(logcat, "{}Block height changed whilst preparing block template for round {}, restarting Pulse stages", log_prefix(context), +context.prepare_for_round.round); return goto_wait_for_next_block_and_clear_round_data(context); } } @@ -1436,7 +1444,7 @@ round_state send_block_template(round_context &context, void *quorumnet_state, s crypto::generate_signature(msg_signature_hash(context.wait_for_next_block.top_hash, msg), key.pub, key.key, msg.signature); // Send - oxen::log::info(logcat, "{}Validators are handshaken and ready, sending block template from producer (us) to validators.\n{}", log_prefix(context), cryptonote::obj_to_json_str(block)); + log::info(logcat, "{}Validators are handshaken and ready, sending block template from producer (us) to validators.\n{}", log_prefix(context), cryptonote::obj_to_json_str(block)); cryptonote::quorumnet_pulse_relay_message_to_quorum(quorumnet_state, msg, context.prepare_for_round.quorum, true /*block_producer*/); return goto_preparing_for_next_round(context); } @@ -1454,7 +1462,7 @@ round_state wait_for_block_template(round_context &context, service_nodes::servi if (received) { cryptonote::block const &block = context.transient.wait_for_block_template.block; - oxen::log::info(logcat, "{}Valid block received: {}", log_prefix(context), cryptonote::obj_to_json_str(context.transient.wait_for_block_template.block)); + log::info(logcat, "{}Valid block received: {}", log_prefix(context), cryptonote::obj_to_json_str(context.transient.wait_for_block_template.block)); // Generate my random value and its hash crypto::generate_random_bytes_thread_safe(sizeof(context.transient.random_value.send.data), context.transient.random_value.send.data.data); @@ -1463,7 +1471,7 @@ round_state wait_for_block_template(round_context &context, service_nodes::servi } else { - oxen::log::info(logcat, "{}Timed out, block template was not received", log_prefix(context)); + log::info(logcat, "{}Timed out, block template was not received", log_prefix(context)); return goto_preparing_for_next_round(context); } } @@ -1503,7 +1511,7 @@ round_state send_and_wait_for_random_value_hashes(round_context &context, servic if (!enforce_validator_participation_and_timeouts(context, stage, node_list, timed_out, all_hashes)) return goto_preparing_for_next_round(context); - oxen::log::info(logcat, "{}Received {} random value hashes from {}{}", log_prefix(context), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string(), (timed_out ? ". We timed out and some hashes are missing" : "")); + log::info(logcat, "{}Received {} random value hashes from {}{}", log_prefix(context), bitset_view16(stage.bitset).count(), bitset_view16(stage.bitset).to_string(), (timed_out ? ". We timed out and some hashes are missing" : "")); return round_state::send_and_wait_for_random_value; } @@ -1561,7 +1569,7 @@ round_state send_and_wait_for_random_value(round_context &context, service_nodes string.data()[i] = '.'; #endif - oxen::log::debug(logcat, "{}Final random value seeding with V[{}] {}", log_prefix(context), index, string.view()); + log::debug(logcat, "{}Final random value seeding with V[{}] {}", log_prefix(context), index, string.view()); crypto_generichash_update(&state, random_value->data, sizeof(random_value->data)); } } @@ -1583,7 +1591,7 @@ round_state send_and_wait_for_random_value(round_context &context, service_nodes crypto::hash const &final_block_hash = cryptonote::get_block_hash(final_block); crypto::generate_signature(final_block_hash, key.pub, key.key, context.transient.signed_block.send.data); - oxen::log::info(logcat, "{}Block final random value {} generated from validators {}", log_prefix(context), oxenc::to_hex(tools::view_guts(final_block.pulse.random_value.data)), bitset_view16(stage.bitset).to_string()); + log::info(logcat, "{}Block final random value {} generated from validators {}", log_prefix(context), oxenc::to_hex(tools::view_guts(final_block.pulse.random_value.data)), bitset_view16(stage.bitset).to_string()); return round_state::send_and_wait_for_signed_blocks; } @@ -1645,12 +1653,12 @@ round_state send_and_wait_for_signed_blocks(round_context &context, service_node uint16_t validator_index = indices[index]; auto const &signature = quorum[validator_index]; assert(signature); - oxen::log::debug(logcat, "{}Signature added: {}:{}, {}", log_prefix(context), validator_index, context.prepare_for_round.quorum.validators[validator_index], *signature); + log::debug(logcat, "{}Signature added: {}:{}, {}", log_prefix(context), validator_index, context.prepare_for_round.quorum.validators[validator_index], *signature); final_block.signatures.emplace_back(validator_index, *signature); } // Propagate Final Block - oxen::log::debug(logcat, "{}Final signed block constructed\n{}", log_prefix(context), cryptonote::obj_to_json_str(final_block)); + log::debug(logcat, "{}Final signed block constructed\n{}", log_prefix(context), cryptonote::obj_to_json_str(final_block)); cryptonote::block_verification_context bvc = {}; if (!core.handle_block_found(final_block, bvc)) return goto_preparing_for_next_round(context); @@ -1661,7 +1669,9 @@ round_state send_and_wait_for_signed_blocks(round_context &context, service_node return round_state::send_and_wait_for_signed_blocks; } -void pulse::main(void *quorumnet_state, cryptonote::core &core) +} // anonymous namespace + +void main(void *quorumnet_state, cryptonote::core &core) { cryptonote::Blockchain &blockchain = core.get_blockchain_storage(); service_nodes::service_node_keys const &key = core.get_service_keys(); @@ -1673,14 +1683,14 @@ void pulse::main(void *quorumnet_state, cryptonote::core &core) if (!hf16) { for (static bool once = true; once; once = !once) - oxen::log::error(logcat, "Pulse: HF16 is not defined, pulse worker waiting"); + log::error(logcat, "Pulse: HF16 is not defined, pulse worker waiting"); return; } if (uint64_t height = blockchain.get_current_blockchain_height(true /*lock*/); height < *hf16) { for (static bool once = true; once; once = !once) - oxen::log::debug(logcat, "Pulse: Network at block {} is not ready for Pulse until block {}, waiting", height, *hf16); + log::debug(logcat, "Pulse: Network at block {} is not ready for Pulse until block {}, waiting", height, *hf16); return; } @@ -1743,3 +1753,4 @@ void pulse::main(void *quorumnet_state, cryptonote::core &core) } } +} // namespace pulse diff --git a/src/cryptonote_core/service_node_list.cpp b/src/cryptonote_core/service_node_list.cpp index e2b5e5022..171f19e59 100644 --- a/src/cryptonote_core/service_node_list.cpp +++ b/src/cryptonote_core/service_node_list.cpp @@ -72,7 +72,7 @@ using cryptonote::hf; namespace service_nodes { - static auto logcat = oxen::log::Cat("service_nodes"); + static auto logcat = log::Cat("service_nodes"); size_t constexpr STORE_LONG_TERM_STATE_INTERVAL = 10000; @@ -109,7 +109,7 @@ namespace service_nodes uint64_t current_height = m_blockchain.get_current_blockchain_height(); bool loaded = load(current_height); if (loaded && m_transient.old_quorum_states.size() < std::min(m_store_quorum_history, uint64_t{10})) { - oxen::log::warning(logcat, "Full history storage requested, but {} old quorum states found", m_transient.old_quorum_states.size()); + log::warning(logcat, "Full history storage requested, but {} old quorum states found", m_transient.old_quorum_states.size()); loaded = false; // Either we don't have stored history or the history is very short, so recalculation is necessary or cheap. } @@ -202,13 +202,13 @@ namespace service_nodes else if (group == quorum_group::worker) array = &quorum.workers; else { - oxen::log::error(logcat, "Invalid quorum group specified"); + log::error(logcat, "Invalid quorum group specified"); return false; } if (quorum_index >= array->size()) { - oxen::log::error(logcat, "Quorum indexing out of bounds: {}, quorum_size: {}", quorum_index, array->size()); + log::error(logcat, "Quorum indexing out of bounds: {}, quorum_size: {}", quorum_index, array->size()); return false; } @@ -221,7 +221,7 @@ namespace service_nodes std::shared_ptr quorum = get_quorum(type, height); if (!quorum) { - oxen::log::info(logcat, "Quorum for height: {}, was not stored by the daemon", height); + log::info(logcat, "Quorum for height: {}, was not stored by the daemon", height); return false; } @@ -474,13 +474,13 @@ namespace service_nodes money_transferred = rct::decodeRct(tx.rct_signatures, rct::sk2rct(scalar1), i, mask, hwdev); break; default: - oxen::log::warning(logcat, "{}: Unsupported rct type: {}", __func__, (int)tx.rct_signatures.type); + log::warning(logcat, "{}: Unsupported rct type: {}", __func__, (int)tx.rct_signatures.type); return 0; } } catch (const std::exception &e) { - oxen::log::warning(logcat, "Failed to decode input {}", i); + log::warning(logcat, "Failed to decode input {}", i); return 0; } @@ -499,7 +499,7 @@ namespace service_nodes if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, contribution->tx_key)) { - oxen::log::info(logcat, "TX: There was a service node contributor but no secret key in the tx extra for tx: {}", txid); + log::info(logcat, "TX: There was a service node contributor but no secret key in the tx extra for tx: {}", txid); return false; } @@ -541,7 +541,7 @@ namespace service_nodes crypto::key_derivation derivation; if (!crypto::generate_key_derivation(contribution->address.m_view_public_key, contribution->tx_key, derivation)) { - oxen::log::info(logcat, "TX: Failed to generate key derivation on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Failed to generate key derivation on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -564,7 +564,7 @@ namespace service_nodes cryptonote::tx_extra_tx_key_image_proofs key_image_proofs; if (!get_field_from_tx_extra(tx.extra, key_image_proofs)) { - oxen::log::info(logcat, "TX: Didn't have key image proofs in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Didn't have key image proofs in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); stake_decoded = false; } @@ -593,7 +593,7 @@ namespace service_nodes // P' := Derivation + B if (!hwdev.derive_public_key(derivation, output_index, contribution->address.m_spend_public_key, ephemeral_pub_key)) { - oxen::log::info(logcat, "TX: Could not derive TX ephemeral key on height: {} for tx: {} for output: {}", block_height, get_transaction_hash(tx), output_index); + log::info(logcat, "TX: Could not derive TX ephemeral key on height: {} for tx: {} for output: {}", block_height, get_transaction_hash(tx), output_index); continue; } @@ -601,7 +601,7 @@ namespace service_nodes const auto& out_to_key = var::get(tx.vout[output_index].target); if (out_to_key.key != ephemeral_pub_key) { - oxen::log::info(logcat, "TX: Derived TX ephemeral key did not match tx stored key on height: {} for tx: {} for output: {}", block_height, cryptonote::get_transaction_hash(tx), output_index); + log::info(logcat, "TX: Derived TX ephemeral key did not match tx stored key on height: {} for tx: {} for output: {}", block_height, cryptonote::get_transaction_hash(tx), output_index); continue; } } @@ -680,7 +680,7 @@ namespace service_nodes cryptonote::tx_extra_service_node_state_change state_change; if (!cryptonote::get_service_node_state_change_from_tx_extra(tx.extra, state_change, hf_version)) { - oxen::log::error(logcat, "Transaction: {}, did not have valid state change data in tx extra rejecting malformed tx", cryptonote::get_transaction_hash(tx)); + log::error(logcat, "Transaction: {}, did not have valid state change data in tx extra rejecting malformed tx", cryptonote::get_transaction_hash(tx)); return false; } @@ -690,7 +690,7 @@ namespace service_nodes it = state_archive.find(state_change.block_height); if (it == state_archive.end()) { - oxen::log::error(logcat, "Transaction: {} in block {} {} references quorum height but that height is not stored!", cryptonote::get_transaction_hash(tx), cryptonote::get_block_height(block), cryptonote::get_block_hash(block), state_change.block_height); + log::error(logcat, "Transaction: {} in block {} {} references quorum height but that height is not stored!", cryptonote::get_transaction_hash(tx), cryptonote::get_block_height(block), cryptonote::get_block_hash(block), state_change.block_height); return false; } } @@ -716,20 +716,20 @@ namespace service_nodes if (!quorums) { - oxen::log::error(logcat, "Could not get a quorum that could completely validate the votes from state change in tx: {}, skipping transaction", get_transaction_hash(tx)); + log::error(logcat, "Could not get a quorum that could completely validate the votes from state change in tx: {}, skipping transaction", get_transaction_hash(tx)); return false; } crypto::public_key key; if (!get_pubkey_from_quorum(*quorums->obligations, quorum_group::worker, state_change.service_node_index, key)) { - oxen::log::error(logcat, "Retrieving the public key from state change in tx: {} failed", cryptonote::get_transaction_hash(tx)); + log::error(logcat, "Retrieving the public key from state change in tx: {} failed", cryptonote::get_transaction_hash(tx)); return false; } auto iter = service_nodes_infos.find(key); if (iter == service_nodes_infos.end()) { - oxen::log::debug(logcat, "Received state change tx for non-registered service node {} (perhaps a delayed tx?)", key); + log::debug(logcat, "Received state change tx for non-registered service node {} (perhaps a delayed tx?)", key); return false; } @@ -740,9 +740,9 @@ namespace service_nodes switch (state_change.state) { case new_state::deregister: if (is_me) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Deregistration for service node (yours): {}", key)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Deregistration for service node (yours): {}", key)); else - oxen::log::info(logcat, "Deregistration for service node: {}", key); + log::info(logcat, "Deregistration for service node: {}", key); if (hf_version >= hf::hf11_infinite_staking) { @@ -764,19 +764,19 @@ namespace service_nodes case new_state::decommission: if (hf_version < hf::hf12_checkpointing) { - oxen::log::error(logcat, "Invalid decommission transaction seen before network v12"); + log::error(logcat, "Invalid decommission transaction seen before network v12"); return false; } if (info.is_decommissioned()) { - oxen::log::debug(logcat, "Received decommission tx for already-decommissioned service node {}; ignoring", key); + log::debug(logcat, "Received decommission tx for already-decommissioned service node {}; ignoring", key); return false; } if (is_me) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Temporary decommission for service node (yours): {}", key)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Temporary decommission for service node (yours): {}", key)); else - oxen::log::info(logcat, "Temporary decommission for service node: {}", key); + log::info(logcat, "Temporary decommission for service node: {}", key); info.active_since_height = -info.active_since_height; info.last_decommission_height = block_height; @@ -802,19 +802,19 @@ namespace service_nodes case new_state::recommission: { if (hf_version < hf::hf12_checkpointing) { - oxen::log::error(logcat, "Invalid recommission transaction seen before network v12"); + log::error(logcat, "Invalid recommission transaction seen before network v12"); return false; } if (!info.is_decommissioned()) { - oxen::log::debug(logcat, "Received recommission tx for already-active service node {}; ignoring", key); + log::debug(logcat, "Received recommission tx for already-active service node {}; ignoring", key); return false; } if (is_me) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Recommission for service node (yours): {}", key)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Recommission for service node (yours): {}", key)); else - oxen::log::info(logcat, "Recommission for service node: {}", key); + log::info(logcat, "Recommission for service node: {}", key); // To figure out how much credit the node gets at recommissioned we need to know how much it // had when it got decommissioned, and how long it's been decommisioned. @@ -847,19 +847,19 @@ namespace service_nodes } case new_state::ip_change_penalty: if (hf_version < hf::hf12_checkpointing) { - oxen::log::error(logcat, "Invalid ip_change_penalty transaction seen before network v12"); + log::error(logcat, "Invalid ip_change_penalty transaction seen before network v12"); return false; } if (info.is_decommissioned()) { - oxen::log::debug(logcat, "Received reset position tx for service node {} but it is already decommissioned; ignoring", key); + log::debug(logcat, "Received reset position tx for service node {} but it is already decommissioned; ignoring", key); return false; } if (is_me) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Reward position reset for service node (yours): {}", key)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Reward position reset for service node (yours): {}", key)); else - oxen::log::info(logcat, "Reward position reset for service node: {}", key); + log::info(logcat, "Reward position reset for service node: {}", key); // Move the SN at the back of the list as if it had just registered (or just won) @@ -870,7 +870,7 @@ namespace service_nodes default: // dev bug! - oxen::log::error(logcat, "BUG: Service node state change tx has unknown state {}", static_cast(state_change.state)); + log::error(logcat, "BUG: Service node state change tx has unknown state {}", static_cast(state_change.state)); return false; } } @@ -888,14 +888,14 @@ namespace service_nodes const service_node_info &node_info = *it->second; if (node_info.requested_unlock_height != KEY_IMAGE_AWAITING_UNLOCK_HEIGHT) { - oxen::log::info(logcat, "Unlock TX: Node already requested an unlock at height: {} rejected on height: {} for tx: {}", node_info.requested_unlock_height, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Unlock TX: Node already requested an unlock at height: {} rejected on height: {} for tx: {}", node_info.requested_unlock_height, block_height, cryptonote::get_transaction_hash(tx)); return false; } cryptonote::tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - oxen::log::info(logcat, "Unlock TX: Didn't have key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Unlock TX: Didn't have key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -917,7 +917,7 @@ namespace service_nodes { if (cit->amount < small_contributor_amount_threshold && (block_height - node_info.registration_height) < service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) { - oxen::log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); + log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); return false; } } @@ -926,7 +926,7 @@ namespace service_nodes { if (cit->amount < 3749 && (block_height - node_info.registration_height) < service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER) { - oxen::log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); + log::info(logcat, "Unlock TX: small contributor trying to unlock node before {} blocks have passed, rejected on height: {} for tx: {}", std::to_string(service_nodes::SMALL_CONTRIBUTOR_UNLOCK_TIMER), block_height, get_transaction_hash(tx)); return false; } } @@ -939,7 +939,7 @@ namespace service_nodes } else { - oxen::log::info(logcat, "Unlock TX: Couldn't verify key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, get_transaction_hash(tx)); + log::info(logcat, "Unlock TX: Couldn't verify key image unlock in the tx_extra, rejected on height: {} for tx: {}", block_height, get_transaction_hash(tx)); return false; } } @@ -1001,7 +1001,7 @@ namespace service_nodes } catch (const invalid_registration &e) { - oxen::log::info(logcat, "Invalid registration ({} @ {}): {}", cryptonote::get_transaction_hash(tx), block_height, e.what()); + log::info(logcat, "Invalid registration ({} @ {}): {}", cryptonote::get_transaction_hash(tx), block_height, e.what()); return false; } @@ -1012,7 +1012,7 @@ namespace service_nodes staking_components stake = {}; if (!tx_get_staking_components_and_amounts(nettype, hf_version, tx, block_height, &stake)) { - oxen::log::info(logcat, "Register TX: Had service node registration fields, but could not decode contribution on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Register TX: Had service node registration fields, but could not decode contribution on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1022,7 +1022,7 @@ namespace service_nodes // 1. the staked amount in the tx must be a single output. if (stake.locked_contributions.size() != 1) { - oxen::log::info(logcat, "Register TX invalid: multi-output registration transactions are not permitted as of HF16"); + log::info(logcat, "Register TX invalid: multi-output registration transactions are not permitted as of HF16"); return false; } @@ -1030,7 +1030,7 @@ namespace service_nodes // could manually construct a registration tx that stakes for someone *other* than the operator). if (stake.address != reg.reserved[0].first) { - oxen::log::info(logcat, "Register TX invalid: registration stake is not from the operator"); + log::info(logcat, "Register TX invalid: registration stake is not from the operator"); return false; } @@ -1043,7 +1043,7 @@ namespace service_nodes const uint64_t min_transfer = get_min_node_contribution(hf_version, staking_requirement, 0, 0); if (stake.transferred < min_transfer) { - oxen::log::info(logcat, "Register TX: Contribution transferred: {} didn't meet the minimum transfer requirement: {} on height: {} for tx: {}", stake.transferred, min_transfer, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Register TX: Contribution transferred: {} didn't meet the minimum transfer requirement: {} on height: {} for tx: {}", stake.transferred, min_transfer, block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1056,7 +1056,7 @@ namespace service_nodes // the registration details, and we disallow a non-operator registration. if (total_num_of_addr > oxen::MAX_CONTRIBUTORS_V1) { - oxen::log::info(logcat, "Register TX: Number of participants: {} exceeded the max number of contributions: {} on height: {} for tx: {}", total_num_of_addr, oxen::MAX_CONTRIBUTORS_V1, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Register TX: Number of participants: {} exceeded the max number of contributions: {} on height: {} for tx: {}", total_num_of_addr, oxen::MAX_CONTRIBUTORS_V1, block_height, cryptonote::get_transaction_hash(tx)); return false; } } @@ -1088,7 +1088,7 @@ namespace service_nodes { if (it2->first == addr) { - oxen::log::info(logcat, "Invalid registration: duplicate reserved address in registration (tx {})", cryptonote::get_transaction_hash(tx)); + log::info(logcat, "Invalid registration: duplicate reserved address in registration (tx {})", cryptonote::get_transaction_hash(tx)); return false; } } @@ -1108,7 +1108,7 @@ namespace service_nodes // reserved amount was higher (though wallets would never actually do this). if (hf_version >= hf::hf16_pulse && stake.transferred < info.contributors[0].reserved) { - oxen::log::info(logcat, "Register TX rejected: TX does not have sufficient operator stake"); + log::info(logcat, "Register TX rejected: TX does not have sufficient operator stake"); return false; } @@ -1144,9 +1144,9 @@ namespace service_nodes } if (my_keys && my_keys->pub == key) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} on height: {}", key, block_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} on height: {}", key, block_height)); else - oxen::log::info(logcat, "New service node registered: {} on height: {}", key, block_height); + log::info(logcat, "New service node registered: {} on height: {}", key, block_height); } else { @@ -1178,16 +1178,16 @@ namespace service_nodes { if (registered_during_grace_period) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node re-registered (yours): {} at block height: {}", key, block_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node re-registered (yours): {} at block height: {}", key, block_height)); } else { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} at block height: {}", key, block_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} at block height: {}", key, block_height)); } } else { - oxen::log::info(logcat, "New service node registered: {} at block height: {}", key, block_height); + log::info(logcat, "New service node registered: {} at block height: {}", key, block_height); } } @@ -1204,27 +1204,27 @@ namespace service_nodes if (!tx_get_staking_components_and_amounts(nettype, hf_version, tx, block_height, &stake)) { if (stake.service_node_pubkey) - oxen::log::info(logcat, "TX: Could not decode contribution for service node: {} on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Could not decode contribution for service node: {} on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } auto iter = service_nodes_infos.find(stake.service_node_pubkey); if (iter == service_nodes_infos.end()) { - oxen::log::info(logcat, "TX: Contribution received for service node: {}, but could not be found in the service node list on height: {} for tx: {}\n This could mean that the service node was deregistered before the contribution was processed.", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Contribution received for service node: {}, but could not be found in the service node list on height: {} for tx: {}\n This could mean that the service node was deregistered before the contribution was processed.", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } const service_node_info& curinfo = *iter->second; if (curinfo.is_fully_funded()) { - oxen::log::info(logcat, "TX: Service node: {} is already fully funded, but contribution received on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Service node: {} is already fully funded, but contribution received on height: {} for tx: {}", stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } if (!cryptonote::get_tx_secret_key_from_tx_extra(tx.extra, stake.tx_key)) { - oxen::log::info(logcat, "TX: Failed to get tx secret key from contribution received on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Failed to get tx secret key from contribution received on height: {} for tx: {}", block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1252,7 +1252,7 @@ namespace service_nodes { // Nothing has ever created stake txes with multiple stake outputs, but we start enforcing // that in HF16. - oxen::log::info(logcat, "Ignoring staking tx: multi-output stakes are not permitted as of HF16"); + log::info(logcat, "Ignoring staking tx: multi-output stakes are not permitted as of HF16"); return false; } @@ -1274,7 +1274,7 @@ namespace service_nodes if (too_many_contributions) { - oxen::log::info(logcat, "TX: Already hit the max number of contributions: {} for contributor: {} on height: {} for tx: {}", (hf_version >= hf::hf19_reward_batching ? oxen::MAX_CONTRIBUTORS_HF19 : oxen::MAX_CONTRIBUTORS_V1), cryptonote::get_account_address_as_str(nettype, false, stake.address), block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Already hit the max number of contributions: {} for contributor: {} on height: {} for tx: {}", (hf_version >= hf::hf19_reward_batching ? oxen::MAX_CONTRIBUTORS_HF19 : oxen::MAX_CONTRIBUTORS_V1), cryptonote::get_account_address_as_str(nettype, false, stake.address), block_height, cryptonote::get_transaction_hash(tx)); return false; } } @@ -1301,7 +1301,7 @@ namespace service_nodes if (stake.transferred < min_contribution) { - oxen::log::info(logcat, "TX: Amount {} did not meet min {} for service node: {} on height: {} for tx: {}", stake.transferred, min_contribution, stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); + log::info(logcat, "TX: Amount {} did not meet min {} for service node: {} on height: {} for tx: {}", stake.transferred, min_contribution, stake.service_node_pubkey, block_height, cryptonote::get_transaction_hash(tx)); return false; } @@ -1310,7 +1310,7 @@ namespace service_nodes if (auto max = get_max_node_contribution(hf_version, curinfo.staking_requirement, curinfo.total_reserved - contr_unfilled_reserved); stake.transferred > max) { - oxen::log::info(logcat, "TX: Amount {} is too large (max {}). This is probably a result of competing stakes.", stake.transferred, max); + log::info(logcat, "TX: Amount {} is too large (max {}). This is probably a result of competing stakes.", stake.transferred, max); return false; } @@ -1348,7 +1348,7 @@ namespace service_nodes for (const auto &contribution : stake.locked_contributions) contributor.locked_contributions.push_back(contribution); - oxen::log::info(logcat, "Contribution of {} received for service node {}", stake.transferred, stake.service_node_pubkey); + log::info(logcat, "Contribution of {} received for service node {}", stake.transferred, stake.service_node_pubkey); if (info.is_fully_funded()) { info.active_since_height = block_height; return true; @@ -1404,14 +1404,14 @@ namespace service_nodes if (cryptonote::block_has_pulse_components(block)) { if (log_errors) - oxen::log::info(logcat, "Pulse {} received but only miner blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); + log::info(logcat, "Pulse {} received but only miner blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } if (block.pulse.round != 0) { if (log_errors) - oxen::log::info(logcat, "Miner {} given but unexpectedly set round {} on height {}", block_type, block.pulse.round, height); + log::info(logcat, "Miner {} given but unexpectedly set round {} on height {}", block_type, block.pulse.round, height); return false; } @@ -1419,14 +1419,14 @@ namespace service_nodes { std::bitset<8 * sizeof(block.pulse.validator_bitset)> const bitset = block.pulse.validator_bitset; if (log_errors) - oxen::log::info(logcat, "Miner {} block given but unexpectedly set validator bitset {} on height {}", block_type, bitset.to_string(), height); + log::info(logcat, "Miner {} block given but unexpectedly set validator bitset {} on height {}", block_type, bitset.to_string(), height); return false; } if (block.signatures.size()) { if (log_errors) - oxen::log::info(logcat, "Miner {} block given but unexpectedly has {} signatures on height {}", block_type, block.signatures.size(), height); + log::info(logcat, "Miner {} block given but unexpectedly has {} signatures on height {}", block_type, block.signatures.size(), height); return false; } @@ -1437,7 +1437,7 @@ namespace service_nodes if (!cryptonote::block_has_pulse_components(block)) { if (log_errors) - oxen::log::info(logcat, "Miner {} received but only pulse blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); + log::info(logcat, "Miner {} received but only pulse blocks are permitted\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } @@ -1456,7 +1456,7 @@ namespace service_nodes std::string begin = tools::get_human_readable_timestamp(begin_time); std::string end = tools::get_human_readable_timestamp(end_time); if (log_errors) - oxen::log::info(logcat, "Pulse {} with round {} specifies timestamp {} is not within an acceptable range of time [{}, {}]", block_type, +block.pulse.round, time, begin, end); + log::info(logcat, "Pulse {} with round {} specifies timestamp {} is not within an acceptable range of time [{}, {}]", block_type, +block.pulse.round, time, begin, end); return false; } } @@ -1464,7 +1464,7 @@ namespace service_nodes if (block.nonce != 0) { if (log_errors) - oxen::log::info(logcat, "Pulse {} specified a nonce when quorum block generation is available, nonce: {}", block_type, block.nonce); + log::info(logcat, "Pulse {} specified a nonce when quorum block generation is available, nonce: {}", block_type, block.nonce); return false; } @@ -1476,7 +1476,7 @@ namespace service_nodes bool failed_quorum_verify = true; if (pulse_quorum) { - oxen::log::info(logcat, "Verifying alt-block {}:{} against main chain quorum", height, hash); + log::info(logcat, "Verifying alt-block {}:{} against main chain quorum", height, hash); failed_quorum_verify = service_nodes::verify_quorum_signatures(*pulse_quorum, quorum_type::pulse, block.major_version, @@ -1489,7 +1489,7 @@ namespace service_nodes // NOTE: Check alt pulse quorums if (failed_quorum_verify) { - oxen::log::info(logcat, "Verifying alt-block {}:{} against alt chain quorum(s)", height, hash); + log::info(logcat, "Verifying alt-block {}:{} against alt chain quorum(s)", height, hash); for (auto const &alt_quorum : alt_pulse_quorums) { if (service_nodes::verify_quorum_signatures(*alt_quorum, @@ -1517,7 +1517,7 @@ namespace service_nodes if (insufficient_nodes_for_pulse) { if (log_errors) - oxen::log::info(logcat, "Pulse {} specified but no quorum available {}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); + log::info(logcat, "Pulse {} specified but no quorum available {}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); return false; } @@ -1534,7 +1534,7 @@ namespace service_nodes { // NOTE: These invariants are already checked in verify_quorum_signatures if (alt_block) - oxen::log::info(logcat, "Alt-block {}:{} verified successfully", height, hash); + log::info(logcat, "Alt-block {}:{} verified successfully", height, hash); assert(block.pulse.validator_bitset != 0); assert(block.pulse.validator_bitset < (1 << PULSE_QUORUM_NUM_VALIDATORS)); assert(block.signatures.size() == service_nodes::PULSE_BLOCK_REQUIRED_SIGNATURES); @@ -1542,7 +1542,7 @@ namespace service_nodes else { if (log_errors) - oxen::log::info(logcat, "Pulse {} failed quorum verification\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); + log::info(logcat, "Pulse {} failed quorum verification\n{}", block_type, dump_pulse_block_data(block, pulse_quorum.get())); } return quorum_verified; @@ -1558,18 +1558,18 @@ namespace service_nodes catch(std::exception const &e) { // ignore not found block, try alt db - oxen::log::info(logcat, "Block {} not found in main DB, searching alt DB", hash); + log::info(logcat, "Block {} not found in main DB, searching alt DB", hash); cryptonote::alt_block_data_t alt_data; std::string blob; if (!db.get_alt_block(hash, &alt_data, &blob, nullptr)) { - oxen::log::error(logcat, "Failed to find block {}", hash); + log::error(logcat, "Failed to find block {}", hash); return false; } if (!cryptonote::parse_and_validate_block_from_blob(blob, block, nullptr)) { - oxen::log::error(logcat, "Failed to parse alt block blob at {}:{}", alt_data.height, hash); + log::error(logcat, "Failed to parse alt block blob at {}:{}", alt_data.height, hash); return false; } } @@ -1757,7 +1757,7 @@ namespace service_nodes uint64_t block_height = cryptonote::get_block_height(block); if (m_blockchain.nettype() != cryptonote::network_type::FAKECHAIN && block.major_version >= hf::hf19_reward_batching && height() != block_height) { - oxen::log::error(logcat, "Service node list out of sync with the batching database, adding block will fail because the service node list is at height: {} and the batching database is at height: {}", height(), m_blockchain.sqlite_db()->height+1); + log::error(logcat, "Service node list out of sync with the batching database, adding block will fail because the service node list is at height: {} and the batching database is at height: {}", height(), m_blockchain.sqlite_db()->height+1); return false; } return m_blockchain.sqlite_db()->add_block(block, m_state); @@ -1876,7 +1876,7 @@ namespace service_nodes uint64_t const top_height = cryptonote::get_block_height(top_block); if (top_height < PULSE_QUORUM_ENTROPY_LAG) { - oxen::log::error(logcat, "Insufficient blocks to get quorum entropy for Pulse, height is {}, we need {} blocks.", top_height, PULSE_QUORUM_ENTROPY_LAG); + log::error(logcat, "Insufficient blocks to get quorum entropy for Pulse, height is {}, we need {} blocks.", top_height, PULSE_QUORUM_ENTROPY_LAG); return {}; } @@ -1896,7 +1896,7 @@ namespace service_nodes cryptonote::block block; if (!find_block_in_db(db, prev_hash, block)) { - oxen::log::error(logcat, "Failed to get quorum entropy for Pulse, block at {}{}", prev_height, prev_hash); + log::error(logcat, "Failed to get quorum entropy for Pulse, block at {}{}", prev_height, prev_hash); return {}; } @@ -1917,7 +1917,7 @@ namespace service_nodes cryptonote::block top_block; if (!find_block_in_db(db, top_hash, top_block)) { - oxen::log::error(logcat, "Failed to get quorum entropy for Pulse, next block parent {}", top_hash); + log::error(logcat, "Failed to get quorum entropy for Pulse, next block parent {}", top_hash); return {}; } @@ -1940,13 +1940,13 @@ namespace service_nodes service_nodes::quorum result = {}; if (active_snode_list.size() < pulse_min_service_nodes(nettype)) { - oxen::log::debug(logcat, "Insufficient active Service Nodes for Pulse: {}", active_snode_list.size()); + log::debug(logcat, "Insufficient active Service Nodes for Pulse: {}", active_snode_list.size()); return result; } if (pulse_entropy.size() != PULSE_QUORUM_SIZE) { - oxen::log::debug(logcat, "Blockchain has insufficient blocks to generate Pulse data"); + log::debug(logcat, "Blockchain has insufficient blocks to generate Pulse data"); return result; } @@ -2103,7 +2103,7 @@ namespace service_nodes // NOTE: NOP. Pulse quorums are generated pre-Service Node List changes for the block case quorum_type::pulse: continue; - default: oxen::log::error(logcat, "Unhandled quorum type enum with value: {}", type_int); continue; + default: log::error(logcat, "Unhandled quorum type enum with value: {}", type_int); continue; } quorum->validators.reserve(num_validators); @@ -2193,9 +2193,9 @@ namespace service_nodes if (i != service_nodes_infos.end()) { if (my_keys && my_keys->pub == pubkey) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node expired (yours): {} at block height: {}", pubkey, block_height)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node expired (yours): {} at block height: {}", pubkey, block_height)); else - oxen::log::info(logcat, "Service node expired: {} at block height: {}", pubkey, block_height); + log::info(logcat, "Service node expired: {} at block height: {}", pubkey, block_height); need_swarm_update += i->second->is_active(); service_nodes_infos.erase(i); @@ -2386,7 +2386,7 @@ namespace service_nodes } catch (std::exception const &e) { - oxen::log::error(logcat, "Failed to get historical block to find expired nodes in v9: {}", e.what()); + log::error(logcat, "Failed to get historical block to find expired nodes in v9: {}", e.what()); return expired_nodes; } @@ -2398,7 +2398,7 @@ namespace service_nodes cryptonote::transaction tx; if (!db.get_tx(hash, tx)) { - oxen::log::error(logcat, "Failed to get historical tx to find expired service nodes in v9"); + log::error(logcat, "Failed to get historical tx to find expired service nodes in v9"); continue; } @@ -2582,7 +2582,7 @@ namespace service_nodes if (block.major_version >= hf::hf19_reward_batching) { mode = verify_mode::batched_sn_rewards; - oxen::log::debug(logcat, "Batched miner reward"); + log::debug(logcat, "Batched miner reward"); } size_t expected_vouts_size; @@ -2889,7 +2889,7 @@ namespace service_nodes try { serialization::serialize(ba, m_transient.cache_long_term_data); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to store service node info: failed to serialize long term data: {}", e.what()); + log::error(logcat, "Failed to store service node info: failed to serialize long term data: {}", e.what()); return false; } m_transient.cache_data_blob.append(ba.str()); @@ -2906,7 +2906,7 @@ namespace service_nodes try { serialization::serialize(ba, m_transient.cache_short_term_data); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to store service node info: failed to serialize short term data: {}", e.what()); + log::error(logcat, "Failed to store service node info: failed to serialize short term data: {}", e.what()); return false; } m_transient.cache_data_blob.append(ba.str()); @@ -3070,7 +3070,7 @@ namespace service_nodes if (pk && 0 == crypto_sign_ed25519_pk_to_curve25519(pubkey_x25519.data, pk.data)) { proof->pubkey_ed25519 = pk; } else { - oxen::log::warning(logcat, "Failed to derive x25519 pubkey from ed25519 pubkey {}", proof->pubkey_ed25519); + log::warning(logcat, "Failed to derive x25519 pubkey from ed25519 pubkey {}", proof->pubkey_ed25519); pubkey_x25519 = crypto::x25519_public_key::null(); proof->pubkey_ed25519 = crypto::ed25519_public_key::null(); } @@ -3083,7 +3083,7 @@ namespace service_nodes auto vers = get_network_version_revision(m_blockchain.nettype(), m_blockchain.get_current_blockchain_height()); if (vers >= std::make_pair(hf::hf18, uint8_t{1})) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: Old format (non-bt) proofs are not acceptable from v18+1 onwards", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: Old format (non-bt) proofs are not acceptable from v18+1 onwards", proof.pubkey); return false; } @@ -3094,20 +3094,20 @@ namespace service_nodes auto time_deviation = now - std::chrono::system_clock::from_time_t(proof.timestamp); if (time_deviation > netconf.UPTIME_PROOF_TOLERANCE || time_deviation < -netconf.UPTIME_PROOF_TOLERANCE) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof.pubkey); return false; } for (auto const &min : MIN_UPTIME_PROOF_VERSIONS) if (vers >= min.hardfork_revision && proof.snode_version < min.oxend) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof.pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); + log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof.pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); return false; } if (!debug_allow_local_ips && !epee::net_utils::is_ip_public(proof.public_ip)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof.pubkey); return false; } @@ -3119,32 +3119,32 @@ namespace service_nodes if (!crypto::check_signature(hash, proof.pubkey, proof.sig)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof.pubkey); return false; } crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); if (!proof.pubkey_ed25519) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof.pubkey, proof.pubkey_ed25519); + log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof.pubkey, proof.pubkey_ed25519); return false; } if (0 != crypto_sign_verify_detached(proof.sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof.pubkey_ed25519.data)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof.pubkey); return false; } if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof.pubkey_ed25519.data) || !derived_x25519_pubkey) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof.pubkey); return false; } if (proof.qnet_port == 0) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof.pubkey); return false; } @@ -3152,7 +3152,7 @@ namespace service_nodes auto it = m_state.service_nodes_infos.find(proof.pubkey); if (it == m_state.service_nodes_infos.end()) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof.pubkey); return false; } @@ -3161,22 +3161,22 @@ namespace service_nodes if (now <= std::chrono::system_clock::from_time_t(iproof.timestamp) + std::chrono::seconds{netconf.UPTIME_PROOF_FREQUENCY} / 2) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof.pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof.pubkey); return false; } if (m_service_node_keys && proof.pubkey == m_service_node_keys->pub) { my_uptime_proof_confirmation = true; - oxen::log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof.pubkey); + log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof.pubkey); } else { my_uptime_proof_confirmation = false; - oxen::log::debug(logcat, "Accepted uptime proof from {}", proof.pubkey); + log::debug(logcat, "Accepted uptime proof from {}", proof.pubkey); if (m_service_node_keys && proof.pubkey_ed25519 == m_service_node_keys->pub_ed25519) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof.pubkey)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof.pubkey)); } auto old_x25519 = iproof.pubkey_x25519; @@ -3212,7 +3212,7 @@ namespace service_nodes auto time_deviation = now - std::chrono::system_clock::from_time_t(proof->timestamp); if (time_deviation > netconf.UPTIME_PROOF_TOLERANCE || time_deviation < -netconf.UPTIME_PROOF_TOLERANCE) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: timestamp is too far from now", proof->pubkey); return false; } @@ -3220,17 +3220,17 @@ namespace service_nodes if (vers >= min.hardfork_revision && m_blockchain.nettype() != cryptonote::network_type::DEVNET) { if (proof->version < min.oxend) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); + log::debug(logcat, "Rejecting uptime proof from {}: v{}+ oxend version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.oxend), static_cast(vers.first), vers.second); return false; } if (proof->lokinet_version < min.lokinet) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ lokinet version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.lokinet), static_cast(vers.first), vers.second); + log::debug(logcat, "Rejecting uptime proof from {}: v{}+ lokinet version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.lokinet), static_cast(vers.first), vers.second); return false; } if (proof->storage_server_version < min.storage_server) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: v{}+ storage server version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.storage_server), static_cast(vers.first), vers.second); + log::debug(logcat, "Rejecting uptime proof from {}: v{}+ storage server version is required for v{}.{}+ network proofs", proof->pubkey, tools::join(".", min.storage_server), static_cast(vers.first), vers.second); return false; } } @@ -3238,7 +3238,7 @@ namespace service_nodes if (!debug_allow_local_ips && !epee::net_utils::is_ip_public(proof->public_ip)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: public_ip is not actually public", proof->pubkey); return false; } @@ -3249,32 +3249,32 @@ namespace service_nodes if (!crypto::check_signature(hash, proof->pubkey, proof->sig)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: signature validation failed", proof->pubkey); return false; } crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); if (!proof->pubkey_ed25519) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof->pubkey, proof->pubkey_ed25519); + log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof->pubkey, proof->pubkey_ed25519); return false; } if (0 != crypto_sign_verify_detached(proof->sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof->pubkey_ed25519.data)) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof->pubkey); return false; } if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof->pubkey_ed25519.data) || !derived_x25519_pubkey) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof->pubkey); return false; } if (proof->qnet_port == 0) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: invalid quorumnet port in uptime proof", proof->pubkey); return false; } @@ -3282,7 +3282,7 @@ namespace service_nodes auto it = m_state.service_nodes_infos.find(proof->pubkey); if (it == m_state.service_nodes_infos.end()) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: no such service node is currently registered", proof->pubkey); return false; } @@ -3290,22 +3290,22 @@ namespace service_nodes if (now <= std::chrono::system_clock::from_time_t(iproof.timestamp) + std::chrono::seconds{netconf.UPTIME_PROOF_FREQUENCY} / 2) { - oxen::log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof->pubkey); + log::debug(logcat, "Rejecting uptime proof from {}: already received one uptime proof for this node recently", proof->pubkey); return false; } if (m_service_node_keys && proof->pubkey == m_service_node_keys->pub) { my_uptime_proof_confirmation = true; - oxen::log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof->pubkey); + log::info(logcat, "Received uptime-proof confirmation back from network for Service Node (yours): {}", proof->pubkey); } else { my_uptime_proof_confirmation = false; - oxen::log::debug(logcat, "Accepted uptime proof from {}", proof->pubkey); + log::debug(logcat, "Accepted uptime proof from {}", proof->pubkey); if (m_service_node_keys && proof->pubkey_ed25519 == m_service_node_keys->pub_ed25519) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof->pubkey)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof->pubkey)); } auto old_x25519 = iproof.pubkey_x25519; @@ -3335,7 +3335,7 @@ namespace service_nodes void service_node_list::cleanup_proofs() { - oxen::log::debug(logcat, "Cleaning up expired SN proofs"); + log::debug(logcat, "Cleaning up expired SN proofs"); auto locks = tools::unique_locks(m_sn_mutex, m_blockchain); uint64_t now = std::time(nullptr); auto& db = m_blockchain.get_db(); @@ -3397,7 +3397,7 @@ namespace service_nodes auto pubkey = get_pubkey_from_x25519(x25519_pub); if (!pubkey) { - oxen::log::debug(logcat, "no connection available: could not find primary pubkey from x25519 pubkey {}", x25519_pub); + log::debug(logcat, "no connection available: could not find primary pubkey from x25519 pubkey {}", x25519_pub); return ""; } @@ -3411,11 +3411,11 @@ namespace service_nodes }); if (!found) { - oxen::log::debug(logcat, "no connection available: primary pubkey {} is not registered", pubkey); + log::debug(logcat, "no connection available: primary pubkey {} is not registered", pubkey); return ""; } if (!(ip && port)) { - oxen::log::debug(logcat, "no connection available: service node {} has no associated ip and/or port", pubkey); + log::debug(logcat, "no connection available: service node {} has no associated ip and/or port", pubkey); return ""; } @@ -3477,11 +3477,11 @@ namespace service_nodes const auto type = storage_server ? "storage server"sv : "lokinet"sv; if (!m_state.service_nodes_infos.count(pubkey)) { - oxen::log::debug(logcat, "Dropping {} reachable report: {} is not a registered SN pubkey", type, pubkey); + log::debug(logcat, "Dropping {} reachable report: {} is not a registered SN pubkey", type, pubkey); return false; } - oxen::log::debug(logcat, "Received {}{} report for SN {}", type, (reachable ? " reachable" : " UNREACHABLE"), pubkey); + log::debug(logcat, "Received {}{} report for SN {}", type, (reachable ? " reachable" : " UNREACHABLE"), pubkey); const auto now = std::chrono::steady_clock::now(); @@ -3579,7 +3579,7 @@ namespace service_nodes bool service_node_list::load(const uint64_t current_height) { - oxen::log::info(logcat, "service_node_list::load()"); + log::info(logcat, "service_node_list::load()"); reset(false); if (!m_blockchain.has_db()) { @@ -3616,7 +3616,7 @@ namespace service_nodes size_t const last_index = data_in.states.size() - 1; if ((data_in.states.back().height % STORE_LONG_TERM_STATE_INTERVAL) != 0) { - oxen::log::warning(logcat, "Last serialised quorum height: {} in archive is unexpectedly not a multiple of: {}, regenerating state", data_in.states.back().height, STORE_LONG_TERM_STATE_INTERVAL); + log::warning(logcat, "Last serialised quorum height: {} in archive is unexpectedly not a multiple of: {}, regenerating state", data_in.states.back().height, STORE_LONG_TERM_STATE_INTERVAL); return false; } @@ -3669,7 +3669,7 @@ namespace service_nodes try { serialization::parse_binary(blob, data_in); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to parse service node data from blob: {}", e.what()); + log::error(logcat, "Failed to parse service node data from blob: {}", e.what()); return false; } @@ -3690,7 +3690,7 @@ namespace service_nodes if (states.height <= last_loaded_height) { - oxen::log::warning(logcat, "Serialised quorums is not stored in ascending order by height in DB, failed to load from DB"); + log::warning(logcat, "Serialised quorums is not stored in ascending order by height in DB, failed to load from DB"); return false; } last_loaded_height = states.height; @@ -3703,7 +3703,7 @@ namespace service_nodes size_t const last_index = data_in.states.size() - 1; if (data_in.states[last_index].only_stored_quorums) { - oxen::log::warning(logcat, "Unexpected last serialized state only has quorums loaded"); + log::warning(logcat, "Unexpected last serialized state only has quorums loaded"); return false; } @@ -3747,10 +3747,10 @@ namespace service_nodes initialize_x25519_map(); - oxen::log::info(logcat, "Service node data loaded successfully, height: {}", m_state.height); - oxen::log::info(logcat, "{} nodes and {} recent states loaded, {} historical states loaded, ({})", m_state.service_nodes_infos.size(), m_transient.state_history.size(), m_transient.state_archive.size(), tools::get_human_readable_bytes(bytes_loaded)); + log::info(logcat, "Service node data loaded successfully, height: {}", m_state.height); + log::info(logcat, "{} nodes and {} recent states loaded, {} historical states loaded, ({})", m_state.service_nodes_infos.size(), m_transient.state_history.size(), m_transient.state_archive.size(), tools::get_human_readable_bytes(bytes_loaded)); - oxen::log::info(logcat, "service_node_list::load() returning success"); + log::info(logcat, "service_node_list::load() returning success"); return true; } @@ -3945,7 +3945,7 @@ namespace service_nodes try { reg = convert_registration_args(nettype, hf_version, args, staking_requirement); } catch (const invalid_registration& e) { - oxen::log::error(logcat, "{}{}", tr("Could not parse registration arguments: "), e.what()); + log::error(logcat, "{}{}", tr("Could not parse registration arguments: "), e.what()); return false; } @@ -3977,23 +3977,23 @@ namespace service_nodes { // If the SN expired and was reregistered since the height we'll be voting on it prematurely if (!is_fully_funded()) { - oxen::log::debug(logcat, "SN vote at height {} invalid: not fully funded", height); + log::debug(logcat, "SN vote at height {} invalid: not fully funded", height); return false; } else if (height <= registration_height) { - oxen::log::debug(logcat, "SN vote at height {} invalid: height <= reg height ({})", height, registration_height); + log::debug(logcat, "SN vote at height {} invalid: height <= reg height ({})", height, registration_height); return false; } else if (is_decommissioned() && height <= last_decommission_height) { - oxen::log::debug(logcat, "SN vote at height {} invalid: height <= last decomm height ({})", height, last_decommission_height); + log::debug(logcat, "SN vote at height {} invalid: height <= last decomm height ({})", height, last_decommission_height); return false; } else if (is_active()) { assert(active_since_height >= 0); // should be satisfied whenever is_active() is true if (height <= static_cast(active_since_height)) { - oxen::log::debug(logcat, "SN vote at height {} invalid: height <= active-since height ({})", height, active_since_height); + log::debug(logcat, "SN vote at height {} invalid: height <= active-since height ({})", height, active_since_height); return false; } } - oxen::log::trace(logcat, "SN vote at height {} is valid.", height); + log::trace(logcat, "SN vote at height {} is valid.", height); return true; } @@ -4001,25 +4001,25 @@ namespace service_nodes { if (hf_version >= hf::hf13_enforce_checkpoints) { if (!can_be_voted_on(height)) { - oxen::log::debug(logcat, "SN state transition invalid: {} is not a valid vote height", height); + log::debug(logcat, "SN state transition invalid: {} is not a valid vote height", height); return false; } if (proposed_state == new_state::deregister) { if (height <= registration_height) { - oxen::log::debug(logcat, "SN deregister invalid: vote height ({}) <= registration_height ({})", height, registration_height); + log::debug(logcat, "SN deregister invalid: vote height ({}) <= registration_height ({})", height, registration_height); return false; } } else if (proposed_state == new_state::ip_change_penalty) { if (height <= last_ip_change_height) { - oxen::log::debug(logcat, "SN ip change penality invalid: vote height ({}) <= last_ip_change_height ({})", height, last_ip_change_height); + log::debug(logcat, "SN ip change penality invalid: vote height ({}) <= last_ip_change_height ({})", height, last_ip_change_height); return false; } } } else { // pre-HF13 if (proposed_state == new_state::deregister) { if (height < registration_height) { - oxen::log::debug(logcat, "SN deregister invalid: vote height ({}) < registration_height ({})", height, registration_height); + log::debug(logcat, "SN deregister invalid: vote height ({}) < registration_height ({})", height, registration_height); return false; } } @@ -4027,18 +4027,18 @@ namespace service_nodes if (is_decommissioned()) { if (proposed_state == new_state::decommission) { - oxen::log::debug(logcat, "SN decommission invalid: already decommissioned"); + log::debug(logcat, "SN decommission invalid: already decommissioned"); return false; } else if (proposed_state == new_state::ip_change_penalty) { - oxen::log::debug(logcat, "SN ip change penalty invalid: currently decommissioned"); + log::debug(logcat, "SN ip change penalty invalid: currently decommissioned"); return false; } return true; // recomm or dereg } else if (proposed_state == new_state::recommission) { - oxen::log::debug(logcat, "SN recommission invalid: not recommissioned"); + log::debug(logcat, "SN recommission invalid: not recommissioned"); return false; } - oxen::log::trace(logcat, "SN state change is valid"); + log::trace(logcat, "SN state change is valid"); return true; } diff --git a/src/cryptonote_core/service_node_quorum_cop.cpp b/src/cryptonote_core/service_node_quorum_cop.cpp index bbe9b49c4..1f62031a5 100644 --- a/src/cryptonote_core/service_node_quorum_cop.cpp +++ b/src/cryptonote_core/service_node_quorum_cop.cpp @@ -43,7 +43,7 @@ using cryptonote::hf; namespace service_nodes { - static auto logcat = oxen::log::Cat("quorum_cop"); + static auto logcat = log::Cat("quorum_cop"); std::optional> service_node_test_results::why() const { @@ -111,20 +111,20 @@ namespace service_nodes if (check_uptime_obligation && time_since_last_uptime_proof > netconf.UPTIME_PROOF_VALIDITY) { - oxen::log::info(logcat, "Service Node: {}, failed uptime proof obligation check: the last uptime proof ({}) was older than max validity ({})", pubkey, tools::get_human_readable_timespan(time_since_last_uptime_proof), tools::get_human_readable_timespan(netconf.UPTIME_PROOF_VALIDITY)); + log::info(logcat, "Service Node: {}, failed uptime proof obligation check: the last uptime proof ({}) was older than max validity ({})", pubkey, tools::get_human_readable_timespan(time_since_last_uptime_proof), tools::get_human_readable_timespan(netconf.UPTIME_PROOF_VALIDITY)); result.uptime_proved = false; } if (!ss_reachable) { - oxen::log::info(logcat, "Service Node storage server is not reachable for node: {}", pubkey); + log::info(logcat, "Service Node storage server is not reachable for node: {}", pubkey); result.storage_server_reachable = false; } // TODO: perhaps come back and make this activate on some "soft fork" height before HF19? if (!lokinet_reachable && hf_version >= hf::hf19_reward_batching) { - oxen::log::info(logcat, "Service Node lokinet is not reachable for node: {}", pubkey); + log::info(logcat, "Service Node lokinet is not reachable for node: {}", pubkey); result.lokinet_reachable = false; } @@ -146,24 +146,24 @@ namespace service_nodes { if (check_checkpoint_obligation && checkpoint_participation.failures() > CHECKPOINT_MAX_MISSABLE_VOTES) { - oxen::log::info(logcat, "Service Node: {}, failed checkpoint obligation check", pubkey); + log::info(logcat, "Service Node: {}, failed checkpoint obligation check", pubkey); result.checkpoint_participation = false; } if (pulse_participation.failures() > PULSE_MAX_MISSABLE_VOTES) { - oxen::log::info(logcat, "Service Node: {}, failed pulse obligation check", pubkey); + log::info(logcat, "Service Node: {}, failed pulse obligation check", pubkey); result.pulse_participation = false; } if (timestamp_participation.failures() > TIMESTAMP_MAX_MISSABLE_VOTES) { - oxen::log::info(logcat, "Service Node: {}, failed timestamp obligation check", pubkey); + log::info(logcat, "Service Node: {}, failed timestamp obligation check", pubkey); result.timestamp_participation = false; } if (timesync_status.failures() > TIMESYNC_MAX_UNSYNCED_VOTES) { - oxen::log::info(logcat, "Service Node: {}, failed timesync obligation check", pubkey); + log::info(logcat, "Service Node: {}, failed timesync obligation check", pubkey); result.timesync_status = false; } } @@ -182,8 +182,8 @@ namespace service_nodes { if (!by_pop_blocks) { - oxen::log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for obligations up to {}", height, m_obligations_height); - oxen::log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); + log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for obligations up to {}", height, m_obligations_height); + log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); } m_obligations_height = height; } @@ -192,8 +192,8 @@ namespace service_nodes { if (!by_pop_blocks) { - oxen::log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for checkpointing up to {}", height, m_last_checkpointed_height); - oxen::log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); + log::error(logcat, "The blockchain was detached to height: {}, but quorum cop has already processed votes for checkpointing up to {}", height, m_last_checkpointed_height); + log::error(logcat, "This implies a reorg occured that was over {}. This should rarely happen! Please report this to the devs.", REORG_SAFETY_BUFFER_BLOCKS); } m_last_checkpointed_height = height - (height % CHECKPOINT_INTERVAL); } @@ -257,7 +257,7 @@ namespace service_nodes default: { assert("Unhandled quorum type " == 0); - oxen::log::error(logcat, "Unhandled quorum type with value: {}", (int)type); + log::error(logcat, "Unhandled quorum type with value: {}", (int)type); } break; case quorum_type::obligations: @@ -309,7 +309,7 @@ namespace service_nodes if (!quorum) { // TODO(oxen): Fatal error - oxen::log::error(logcat, "Obligations quorum for height: {} was not cached in daemon!", m_obligations_height); + log::error(logcat, "Obligations quorum for height: {} was not cached in daemon!", m_obligations_height); continue; } @@ -348,12 +348,12 @@ namespace service_nodes if (passed) { if (info.is_decommissioned()) { vote_for_state = new_state::recommission; - oxen::log::debug(logcat, "Decommissioned service node {} is now passing required checks; voting to recommission", quorum->workers[node_index]); + log::debug(logcat, "Decommissioned service node {} is now passing required checks; voting to recommission", quorum->workers[node_index]); } else if (!test_results.single_ip) { // Don't worry about this if the SN is getting recommissioned (above) -- it'll // already reenter at the bottom. vote_for_state = new_state::ip_change_penalty; - oxen::log::debug(logcat, "Service node {} was observed with multiple IPs recently; voting to reset reward position", quorum->workers[node_index]); + log::debug(logcat, "Service node {} was observed with multiple IPs recently; voting to reset reward position", quorum->workers[node_index]); } else { good++; continue; @@ -372,35 +372,35 @@ namespace service_nodes if (info.is_decommissioned()) { if (credit >= 0) { - oxen::log::debug(logcat, "Decommissioned service node {} is still not passing required checks, but has remaining credit ({} blocks); abstaining (to leave decommissioned)", quorum->workers[node_index], credit); + log::debug(logcat, "Decommissioned service node {} is still not passing required checks, but has remaining credit ({} blocks); abstaining (to leave decommissioned)", quorum->workers[node_index], credit); continue; } - oxen::log::debug(logcat, "Decommissioned service node {} has no remaining credit; voting to deregister", quorum->workers[node_index]); + log::debug(logcat, "Decommissioned service node {} has no remaining credit; voting to deregister", quorum->workers[node_index]); vote_for_state = new_state::deregister; // Credit ran out! } else { if (credit >= DECOMMISSION_MINIMUM) { vote_for_state = new_state::decommission; - oxen::log::debug(logcat, "Service node {} has stopped passing required checks, but has sufficient earned credit ({} blocks) to avoid deregistration; voting to decommission", quorum->workers[node_index], credit); + log::debug(logcat, "Service node {} has stopped passing required checks, but has sufficient earned credit ({} blocks) to avoid deregistration; voting to decommission", quorum->workers[node_index], credit); } else { vote_for_state = new_state::deregister; - oxen::log::debug(logcat, "Service node {} has stopped passing required checks, but does not ahve sufficient earned credit ({} blocks, {} required) to decommission; voting to deregister", quorum->workers[node_index], credit, DECOMMISSION_MINIMUM); + log::debug(logcat, "Service node {} has stopped passing required checks, but does not ahve sufficient earned credit ({} blocks, {} required) to decommission; voting to deregister", quorum->workers[node_index], credit, DECOMMISSION_MINIMUM); } } } if (vote_for_state == new_state::deregister && height - *cryptonote::get_hard_fork_heights(m_core.get_nettype(), hf_version).first < netconf.HARDFORK_DEREGISTRATION_GRACE_PERIOD) { - oxen::log::debug(logcat, "Decommissioned service node {} is still not passing required checks, and has no remaining credits left. However it is within the grace period of a hardfork so has not been deregistered.", quorum->workers[node_index]); + log::debug(logcat, "Decommissioned service node {} is still not passing required checks, and has no remaining credits left. However it is within the grace period of a hardfork so has not been deregistered.", quorum->workers[node_index]); continue; } quorum_vote_t vote = service_nodes::make_state_change_vote(m_obligations_height, static_cast(index_in_group), node_index, vote_for_state, reason, my_keys); cryptonote::vote_verification_context vvc; if (!handle_vote(vote, vvc)) - oxen::log::error(logcat, "Failed to add state change vote; reason: {}", print_vote_verification_context(vvc, &vote)); + log::error(logcat, "Failed to add state change vote; reason: {}", print_vote_verification_context(vvc, &vote)); } if (good > 0) - oxen::log::debug(logcat, "{} of {} service nodes are active and passing checks; no state change votes required", good, total); + log::debug(logcat, "{} of {} service nodes are active and passing checks; no state change votes required", good, total); } else if (!tested_myself_once_per_block && (find_index_in_quorum_group(quorum->workers, my_keys.pub) >= 0)) { @@ -424,15 +424,15 @@ namespace service_nodes if (print_failings) { - oxen::log::warning(logcat, "{}{}", (info.is_decommissioned() + log::warning(logcat, "{}{}", (info.is_decommissioned() ? "Service Node (yours) is currently decommissioned and being tested in quorum: " : "Service Node (yours) is active but is not passing tests for quorum: "), m_obligations_height); if (auto why = my_test_results.why()) - oxen::log::warning(logcat, tools::join("\n", *why)); + log::warning(logcat, tools::join("\n", *why)); else - oxen::log::warning(logcat, "Service Node is passing all local tests"); - oxen::log::warning(logcat, "(Note that some tests, such as storage server and lokinet reachability, can only assessed by remote service nodes)"); + log::warning(logcat, "Service Node is passing all local tests"); + log::warning(logcat, "(Note that some tests, such as storage server and lokinet reachability, can only assessed by remote service nodes)"); } } } @@ -466,7 +466,7 @@ namespace service_nodes if (!quorum) { // TODO(oxen): Fatal error - oxen::log::error(logcat, "Checkpoint quorum for height: {} was not cached in daemon!", m_last_checkpointed_height); + log::error(logcat, "Checkpoint quorum for height: {} was not cached in daemon!", m_last_checkpointed_height); continue; } @@ -480,7 +480,7 @@ namespace service_nodes quorum_vote_t vote = make_checkpointing_vote(checkpointed_height_hf_version, block_hash, m_last_checkpointed_height, static_cast(index_in_group), my_keys); cryptonote::vote_verification_context vvc = {}; if (!handle_vote(vote, vvc)) - oxen::log::error(logcat, "Failed to add checkpoint vote; reason: {}", print_vote_verification_context(vvc, &vote)); + log::error(logcat, "Failed to add checkpoint vote; reason: {}", print_vote_verification_context(vvc, &vote)); } } } @@ -505,7 +505,7 @@ namespace service_nodes { if (votes.size() < STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE) { - oxen::log::debug(logcat, "Don't have enough votes yet to submit a state change transaction: have {} of {} required", votes.size(), STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE); + log::debug(logcat, "Don't have enough votes yet to submit a state change transaction: have {} of {} required", votes.size(), STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE); return true; } @@ -551,12 +551,12 @@ namespace service_nodes bool result = core.handle_incoming_tx(cryptonote::tx_to_blob(state_change_tx), tvc, cryptonote::tx_pool_options::new_tx()); if (!result || tvc.m_verifivation_failed) { - oxen::log::info(logcat, "A full state change tx for height: {} and service node: {} could not be verified and was not added to the memory pool, reason: {}", vote.block_height, vote.state_change.worker_index, print_tx_verification_context(tvc, &state_change_tx)); + log::info(logcat, "A full state change tx for height: {} and service node: {} could not be verified and was not added to the memory pool, reason: {}", vote.block_height, vote.state_change.worker_index, print_tx_verification_context(tvc, &state_change_tx)); return false; } } else - oxen::log::info(logcat, "Failed to add state change to tx extra for height: {} and service node: {}", vote.block_height, vote.state_change.worker_index); + log::info(logcat, "Failed to add state change to tx extra for height: {} and service node: {}", vote.block_height, vote.state_change.worker_index); return true; } @@ -565,7 +565,7 @@ namespace service_nodes { if (votes.size() < CHECKPOINT_MIN_VOTES) { - oxen::log::debug(logcat, "Don't have enough votes yet to submit a checkpoint: have {} of {} required", votes.size(), CHECKPOINT_MIN_VOTES); + log::debug(logcat, "Don't have enough votes yet to submit a checkpoint: have {} of {} required", votes.size(), CHECKPOINT_MIN_VOTES); return true; } @@ -657,7 +657,7 @@ namespace service_nodes { default: { - oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); + log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return false; }; diff --git a/src/cryptonote_core/service_node_quorum_cop.h b/src/cryptonote_core/service_node_quorum_cop.h index e24f97af6..0d44fc3ea 100644 --- a/src/cryptonote_core/service_node_quorum_cop.h +++ b/src/cryptonote_core/service_node_quorum_cop.h @@ -89,7 +89,7 @@ namespace service_nodes else if (type == quorum_type::checkpointing) return checkpointing; else if (type == quorum_type::blink) return blink; else if (type == quorum_type::pulse) return pulse; - oxen::log::error(oxen::log::Cat("quorum_cop"), "Developer error: Unhandled quorum enum with value: {}", (size_t)type); + log::error(log::Cat("quorum_cop"), "Developer error: Unhandled quorum enum with value: {}", (size_t)type); assert(!"Developer error: Unhandled quorum enum with value: "); return nullptr; } diff --git a/src/cryptonote_core/service_node_rules.cpp b/src/cryptonote_core/service_node_rules.cpp index d2a39e599..f7a312bd9 100644 --- a/src/cryptonote_core/service_node_rules.cpp +++ b/src/cryptonote_core/service_node_rules.cpp @@ -16,7 +16,7 @@ using cryptonote::hf; namespace service_nodes { -static auto logcat = oxen::log::Cat("service_nodes"); +static auto logcat = log::Cat("service_nodes"); uint64_t get_staking_requirement(cryptonote::network_type nettype, hf hardfork) { @@ -112,11 +112,11 @@ bool check_service_node_portions(hf hf_version, const std::vector hf::hf19_reward_batching) { - oxen::log::info(logcat, "Registration tx rejected: portions-based registrations not permitted after HF19"); + log::info(logcat, "Registration tx rejected: portions-based registrations not permitted after HF19"); return false; } if (portions.size() > oxen::MAX_CONTRIBUTORS_V1) { - oxen::log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", portions.size(), oxen::MAX_CONTRIBUTORS_V1); + log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", portions.size(), oxen::MAX_CONTRIBUTORS_V1); return false; } @@ -127,11 +127,11 @@ bool check_service_node_portions(hf hf_version, const std::vector remaining) { - oxen::log::info(logcat, "Registration tx rejected: portion {} exceeds available portions", i); + log::info(logcat, "Registration tx rejected: portion {} exceeds available portions", i); return false; } @@ -145,11 +145,11 @@ bool check_service_node_portions(hf hf_version, const std::vector>& stakes) { if (hf_version < hf::hf19_reward_batching) { - oxen::log::info(logcat, "Registration tx rejected: amount-based registrations not accepted before HF19"); + log::info(logcat, "Registration tx rejected: amount-based registrations not accepted before HF19"); return false; // OXEN-based registrations not accepted before HF19 } if (stakes.size() > oxen::MAX_CONTRIBUTORS_HF19) { - oxen::log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", stakes.size(), oxen::MAX_CONTRIBUTORS_HF19); + log::info(logcat, "Registration tx rejected: too many contributors ({} > {})", stakes.size(), oxen::MAX_CONTRIBUTORS_HF19); return false; } @@ -163,11 +163,11 @@ bool check_service_node_stakes(hf hf_version, cryptonote::network_type nettype, const uint64_t min_stake = i == 0 ? operator_requirement : get_min_node_contribution(hf_version, staking_requirement, reserved, i); if (stakes[i].second < min_stake) { - oxen::log::info(logcat, "Registration tx rejected: stake {} too small ({} < {})", i, stakes[i].second, min_stake); + log::info(logcat, "Registration tx rejected: stake {} too small ({} < {})", i, stakes[i].second, min_stake); return false; } if (stakes[i].second > remaining) { - oxen::log::info(logcat, "Registration tx rejected: stake {} ({}) exceeds available remaining stake ({})", i, stakes[i].second, remaining); + log::info(logcat, "Registration tx rejected: stake {} ({}) exceeds available remaining stake ({})", i, stakes[i].second, remaining); return false; } diff --git a/src/cryptonote_core/service_node_swarm.cpp b/src/cryptonote_core/service_node_swarm.cpp index 4e583d448..67a5c193e 100644 --- a/src/cryptonote_core/service_node_swarm.cpp +++ b/src/cryptonote_core/service_node_swarm.cpp @@ -9,7 +9,7 @@ namespace service_nodes { - static auto logcat = oxen::log::Cat("service_nodes"); + static auto logcat = log::Cat("service_nodes"); uint64_t get_new_swarm_id(const swarm_snode_map_t &swarm_to_snodes) { @@ -69,7 +69,7 @@ namespace service_nodes const ssize_t margin = pair.second.size() - EXCESS_BASE; return result + std::max(margin, ssize_t(0)); }); - oxen::log::debug(logcat, "Calculated excess: {}", excess); + log::debug(logcat, "Calculated excess: {}", excess); return excess; }; @@ -80,7 +80,7 @@ namespace service_nodes prod_static size_t calc_threshold(const swarm_snode_map_t &swarm_to_snodes) { const size_t threshold = NEW_SWARM_SIZE + (swarm_to_snodes.size() * IDEAL_SWARM_MARGIN); - oxen::log::debug(logcat, "Calculated threshold: {}", threshold); + log::debug(logcat, "Calculated threshold: {}", threshold); return threshold; }; @@ -136,7 +136,7 @@ namespace service_nodes while (calc_excess(swarm_to_snodes) >= calc_threshold(swarm_to_snodes)) { - oxen::log::debug(logcat, "New swarm creation"); + log::debug(logcat, "New swarm creation"); std::vector new_swarm_snodes; new_swarm_snodes.reserve(NEW_SWARM_SIZE); while (new_swarm_snodes.size() < NEW_SWARM_SIZE) @@ -145,7 +145,7 @@ namespace service_nodes get_excess_pool(EXCESS_BASE, swarm_to_snodes, pool_snodes, excess); if (pool_snodes.size() == 0) { - oxen::log::error(logcat, "Error while getting excess pool for new swarm creation"); + log::error(logcat, "Error while getting excess pool for new swarm creation"); return; } const auto& random_excess_snode = pick_from_excess_pool(pool_snodes, mt); @@ -155,12 +155,12 @@ namespace service_nodes const auto new_swarm_id = get_new_swarm_id(swarm_to_snodes); if (auto [it, ins] = swarm_to_snodes.emplace(new_swarm_id, std::move(new_swarm_snodes)); !ins) { - oxen::log::error(logcat, "New swarm ID gave a swarm id ({}) that already exists -- this is a bug!", new_swarm_id); + log::error(logcat, "New swarm ID gave a swarm id ({}) that already exists -- this is a bug!", new_swarm_id); // If we actually abort() here then hitting this would potentially kill the whole network // if we hit this bug, so just warn very loudly and move on; if it happens we'll have to // track down the bug and fix it separately. } else { - oxen::log::debug(logcat, "Created new swarm from excess: {}", new_swarm_id); + log::debug(logcat, "Created new swarm from excess: {}", new_swarm_id); } } } @@ -227,22 +227,22 @@ namespace service_nodes swarm_to_snodes.erase(it); } - oxen::log::trace(logcat, "calc_swarm_changes. swarms: {}, regs: {}", swarm_to_snodes.size(), unassigned_snodes.size()); + log::trace(logcat, "calc_swarm_changes. swarms: {}, regs: {}", swarm_to_snodes.size(), unassigned_snodes.size()); /// 0. Ensure there is always 1 swarm if (swarm_to_snodes.size() == 0) { const auto new_swarm_id = get_new_swarm_id({}); swarm_to_snodes.insert({new_swarm_id, {}}); - oxen::log::debug(logcat, "Created initial swarm {}", new_swarm_id); + log::debug(logcat, "Created initial swarm {}", new_swarm_id); } /// 1. Assign new registered snodes assign_snodes(unassigned_snodes, swarm_to_snodes, mersenne_twister, FILL_SWARM_LOWER_PERCENTILE); - oxen::log::debug(logcat, "After assignment:"); + log::debug(logcat, "After assignment:"); for (const auto &entry : swarm_to_snodes) { - oxen::log::debug(logcat, "{}: {}", entry.first, entry.second.size()); + log::debug(logcat, "{}: {}", entry.first, entry.second.size()); } /// 2. *Robin Hood Round* steal snodes from wealthy swarms and give them to the poor @@ -275,7 +275,7 @@ namespace service_nodes remove_excess_snode_from_swarm(excess_snode, swarm_to_snodes); /// Add public key to poor swarm poor_swarm_snodes.push_back(excess_snode.public_key); - oxen::log::debug(logcat, "Stolen 1 snode from {} and donated to {}", excess_snode.public_key, swarm.swarm_id); + log::debug(logcat, "Stolen 1 snode from {} and donated to {}", excess_snode.public_key, swarm.swarm_id); } while (poor_swarm_snodes.size() < MIN_SWARM_SIZE); /// If there is not enough excess for the current swarm, @@ -301,7 +301,7 @@ namespace service_nodes if (it == swarm_to_snodes.end()) break; - oxen::log::warning(logcat, "swarm {} is DECOMMISSIONED", it->first); + log::warning(logcat, "swarm {} is DECOMMISSIONED", it->first); /// Good ol' switcheroo std::vector decommissioned_snodes; std::swap(decommissioned_snodes, it->second); @@ -313,10 +313,10 @@ namespace service_nodes } /// print - oxen::log::debug(logcat, "Swarm outputs:"); + log::debug(logcat, "Swarm outputs:"); for (const auto &entry : swarm_to_snodes) { - oxen::log::debug(logcat, "{}: {}", entry.first, entry.second.size()); + log::debug(logcat, "{}: {}", entry.first, entry.second.size()); } } } diff --git a/src/cryptonote_core/service_node_voting.cpp b/src/cryptonote_core/service_node_voting.cpp index b6a691a04..c521ec571 100644 --- a/src/cryptonote_core/service_node_voting.cpp +++ b/src/cryptonote_core/service_node_voting.cpp @@ -47,7 +47,7 @@ using cryptonote::hf; namespace service_nodes { - static auto logcat = oxen::log::Cat("service_nodes"); + static auto logcat = log::Cat("service_nodes"); static crypto::hash make_state_change_vote_hash(uint64_t block_height, uint32_t service_node_index, new_state state) { @@ -71,7 +71,7 @@ namespace service_nodes { default: { - oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); + log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return result; }; @@ -107,7 +107,7 @@ namespace service_nodes if (worker_index >= quorum.workers.size()) { if (vvc) vvc->m_worker_index_out_of_bounds = true; - oxen::log::info(logcat, "Quorum worker index in was out of bounds: {}, expected to be in range of: [0, {}", worker_index, quorum.workers.size()); + log::info(logcat, "Quorum worker index in was out of bounds: {}, expected to be in range of: [0, {}", worker_index, quorum.workers.size()); return false; } return true; @@ -118,7 +118,7 @@ namespace service_nodes if (validator_index >= quorum.validators.size()) { if (vvc) vvc->m_validator_index_out_of_bounds = true; - oxen::log::info(logcat, "Validator's index was out of bounds: {}, expected to be in range of: [0, {}", validator_index, quorum.validators.size()); + log::info(logcat, "Validator's index was out of bounds: {}, expected to be in range of: [0, {}", validator_index, quorum.validators.size()); return false; } return true; @@ -138,26 +138,26 @@ namespace service_nodes auto &vvc = tvc.m_vote_ctx; if (state_change.state != new_state::deregister && hf_version < hf::hf12_checkpointing) { - oxen::log::info(logcat, "Non-deregister state changes are invalid before v12"); + log::info(logcat, "Non-deregister state changes are invalid before v12"); return bad_tx(tvc); } if (state_change.state >= new_state::_count) { - oxen::log::info(logcat, "Unknown state change to new state: {}", static_cast(state_change.state)); + log::info(logcat, "Unknown state change to new state: {}", static_cast(state_change.state)); return bad_tx(tvc); } if (state_change.votes.size() < service_nodes::STATE_CHANGE_MIN_VOTES_TO_CHANGE_STATE) { - oxen::log::info(logcat, "Not enough votes"); + log::info(logcat, "Not enough votes"); vvc.m_not_enough_votes = true; return bad_tx(tvc); } if (state_change.votes.size() > service_nodes::STATE_CHANGE_QUORUM_SIZE) { - oxen::log::info(logcat, "Too many votes"); + log::info(logcat, "Too many votes"); return bad_tx(tvc); } @@ -168,7 +168,7 @@ namespace service_nodes { if (state_change.block_height >= latest_height) { - oxen::log::info(logcat, "Received state change tx for height: {} and service node: {}, is newer than current height: {} blocks and has been rejected.", state_change.block_height, state_change.service_node_index, latest_height); + log::info(logcat, "Received state change tx for height: {} and service node: {}, is newer than current height: {} blocks and has been rejected.", state_change.block_height, state_change.service_node_index, latest_height); vvc.m_invalid_block_height = true; if (state_change.block_height >= latest_height + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER) tvc.m_verifivation_failed = true; @@ -177,7 +177,7 @@ namespace service_nodes if (latest_height >= state_change.block_height + service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS) { - oxen::log::info(logcat, "Received state change tx for height: {} and service node: {}, is older than: {} (current height: {}) blocks and has been rejected.", state_change.block_height, state_change.service_node_index, service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS, latest_height); + log::info(logcat, "Received state change tx for height: {} and service node: {}, is older than: {} (current height: {}) blocks and has been rejected.", state_change.block_height, state_change.service_node_index, service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS, latest_height); vvc.m_invalid_block_height = true; if (latest_height >= state_change.block_height + (service_nodes::STATE_CHANGE_TX_LIFETIME_IN_BLOCKS + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER)) tvc.m_verifivation_failed = true; @@ -195,7 +195,7 @@ namespace service_nodes if (validator_index_tracker >= static_cast(vote.validator_index)) { vvc.m_votes_not_sorted = true; - oxen::log::info(logcat, "Vote validator index is not stored in ascending order, prev validator index: {}, curr index: {}", validator_index_tracker, vote.validator_index); + log::info(logcat, "Vote validator index is not stored in ascending order, prev validator index: {}, curr index: {}", validator_index_tracker, vote.validator_index); return bad_tx(tvc); } validator_index_tracker = vote.validator_index; @@ -207,14 +207,14 @@ namespace service_nodes if (++validator_set[vote.validator_index] > 1) { vvc.m_duplicate_voters = true; - oxen::log::info(logcat, "Voter quorum index is duplicated: {}", vote.validator_index); + log::info(logcat, "Voter quorum index is duplicated: {}", vote.validator_index); return bad_tx(tvc); } crypto::public_key const &key = quorum.validators[vote.validator_index]; if (!crypto::check_signature(hash, key, vote.signature)) { - oxen::log::info(logcat, "Invalid signature for voter {}/{}", vote.validator_index, key); + log::info(logcat, "Invalid signature for voter {}/{}", vote.validator_index, key); vvc.m_signature_not_valid = true; return bad_tx(tvc); } @@ -241,13 +241,13 @@ namespace service_nodes { if (signatures.size() < service_nodes::CHECKPOINT_MIN_VOTES) { - oxen::log::info(logcat, "Checkpoint has insufficient signatures to be considered at height: {}", height); + log::info(logcat, "Checkpoint has insufficient signatures to be considered at height: {}", height); return false; } if (signatures.size() > service_nodes::CHECKPOINT_QUORUM_SIZE) { - oxen::log::info(logcat, "Checkpoint has too many signatures to be considered at height: {}", height); + log::info(logcat, "Checkpoint has too many signatures to be considered at height: {}", height); return false; } @@ -259,13 +259,13 @@ namespace service_nodes { if (signatures.size() != PULSE_BLOCK_REQUIRED_SIGNATURES) { - oxen::log::info(logcat, "Pulse block has {} signatures but requires {}", signatures.size(), PULSE_BLOCK_REQUIRED_SIGNATURES); + log::info(logcat, "Pulse block has {} signatures but requires {}", signatures.size(), PULSE_BLOCK_REQUIRED_SIGNATURES); return false; } if (!block) { - oxen::log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); + log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); return false; } @@ -273,7 +273,7 @@ namespace service_nodes { auto mask = std::bitset(pulse_validator_bit_mask()); auto other = std::bitset(block->pulse.validator_bitset); - oxen::log::info(logcat, "Pulse block specifies validator participation bits out of bounds. Expected the bit mask: {}, block: {}", mask.to_string(), other.to_string()); + log::info(logcat, "Pulse block specifies validator participation bits out of bounds. Expected the bit mask: {}, block: {}", mask.to_string(), other.to_string()); return false; } } @@ -290,7 +290,7 @@ namespace service_nodes if (curr >= next) { - oxen::log::info(logcat, "Voters in signatures are not given in ascending order, failed verification at height: {}", height); + log::info(logcat, "Voters in signatures are not given in ascending order, failed verification at height: {}", height); return false; } } @@ -302,14 +302,14 @@ namespace service_nodes { if (!block) { - oxen::log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); + log::info(logcat, "Internal Error: Wrong type passed in any object, expected block."); return false; } uint16_t bit = 1 << quorum_signature.voter_index; if ((block->pulse.validator_bitset & bit) == 0) { - oxen::log::info(logcat, "Received pulse signature from validator {} that is not participating in round {}", static_cast(quorum_signature.voter_index), static_cast(block->pulse.round)); + log::info(logcat, "Received pulse signature from validator {} that is not participating in round {}", static_cast(quorum_signature.voter_index), static_cast(block->pulse.round)); return false; } } @@ -317,19 +317,19 @@ namespace service_nodes crypto::public_key const &key = quorum.validators[quorum_signature.voter_index]; if (quorum_signature.voter_index >= unique_vote_set.size()) { - oxen::log::info(logcat, "Internal Error: Voter Index indexes out of bounds of the vote set, index: {}vote set size: {}", quorum_signature.voter_index, unique_vote_set.size()); + log::info(logcat, "Internal Error: Voter Index indexes out of bounds of the vote set, index: {}vote set size: {}", quorum_signature.voter_index, unique_vote_set.size()); return false; } if (unique_vote_set[quorum_signature.voter_index]++) { - oxen::log::info(logcat, "Voter: {}, quorum index is duplicated: {}, failed verification at height: {}", tools::type_to_hex(key), quorum_signature.voter_index, height); + log::info(logcat, "Voter: {}, quorum index is duplicated: {}, failed verification at height: {}", tools::type_to_hex(key), quorum_signature.voter_index, height); return false; } if (!crypto::check_signature(hash, key, quorum_signature.signature)) { - oxen::log::info(logcat, "Incorrect signature for vote, failed verification at height: {} for voter: {}\n{}", height, key, quorum); + log::info(logcat, "Incorrect signature for vote, failed verification at height: {} for voter: {}\n{}", height, key, quorum); return false; } } @@ -349,13 +349,13 @@ namespace service_nodes { if ((checkpoint.height % service_nodes::CHECKPOINT_INTERVAL) != 0) { - oxen::log::info(logcat, "Checkpoint given but not expecting a checkpoint at height: {}", checkpoint.height); + log::info(logcat, "Checkpoint given but not expecting a checkpoint at height: {}", checkpoint.height); return false; } if (!verify_quorum_signatures(quorum, quorum_type::checkpointing, hf_version, checkpoint.height, checkpoint.block_hash, checkpoint.signatures)) { - oxen::log::info(logcat, "Checkpoint failed signature validation at block {} {}", checkpoint.height, checkpoint.block_hash); + log::info(logcat, "Checkpoint failed signature validation at block {} {}", checkpoint.height, checkpoint.block_hash); return false; } } @@ -363,7 +363,7 @@ namespace service_nodes { if (checkpoint.signatures.size() != 0) { - oxen::log::info(logcat, "Non service-node checkpoints should have no signatures, checkpoint failed at height: {}", checkpoint.height); + log::info(logcat, "Non service-node checkpoints should have no signatures, checkpoint failed at height: {}", checkpoint.height); return false; } } @@ -413,13 +413,13 @@ namespace service_nodes if (latest_height > vote.block_height + VOTE_LIFETIME) { height_in_buffer = latest_height <= vote.block_height + (VOTE_LIFETIME + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER); - oxen::log::info(logcat, "Received vote for height: {}, is older than: {} blocks and has been rejected.", vote.block_height, VOTE_LIFETIME); + log::info(logcat, "Received vote for height: {}, is older than: {} blocks and has been rejected.", vote.block_height, VOTE_LIFETIME); vvc.m_invalid_block_height = true; } else if (vote.block_height > latest_height) { height_in_buffer = vote.block_height <= latest_height + VOTE_OR_TX_VERIFY_HEIGHT_BUFFER; - oxen::log::info(logcat, "Received vote for height: {}, is newer than: {} (latest block height) and has been rejected.", vote.block_height, latest_height); + log::info(logcat, "Received vote for height: {}, is newer than: {} (latest block height) and has been rejected.", vote.block_height, latest_height); vvc.m_invalid_block_height = true; } @@ -465,7 +465,7 @@ namespace service_nodes { default: { - oxen::log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); + log::info(logcat, "Unhandled vote type with value: {}", (int)vote.type); assert("Unhandled vote type" == 0); return false; }; @@ -474,7 +474,7 @@ namespace service_nodes { if (vote.group != quorum_group::validator) { - oxen::log::info(logcat, "Vote received specifies incorrect voting group, expected vote from validator"); + log::info(logcat, "Vote received specifies incorrect voting group, expected vote from validator"); vvc.m_incorrect_voting_group = true; result = false; } @@ -491,7 +491,7 @@ namespace service_nodes { if (vote.group != quorum_group::validator) { - oxen::log::info(logcat, "Vote received specifies incorrect voting group"); + log::info(logcat, "Vote received specifies incorrect voting group"); vvc.m_incorrect_voting_group = true; result = false; } @@ -509,7 +509,7 @@ namespace service_nodes result = crypto::check_signature(hash, key, vote.signature); if (result) - oxen::log::debug(logcat, "Signature accepted for {} voter {}/{} voting for worker {} at height {}", vote.type, vote.index_in_group, key, (vote.type == quorum_type::obligations ? " voting for worker " + std::to_string(vote.state_change.worker_index) : ""), vote.block_height); + log::debug(logcat, "Signature accepted for {} voter {}/{} voting for worker {} at height {}", vote.type, vote.index_in_group, key, (vote.type == quorum_type::obligations ? " voting for worker " + std::to_string(vote.state_change.worker_index) : ""), vote.block_height); else vvc.m_signature_not_valid = true; @@ -532,7 +532,7 @@ namespace service_nodes switch(find_vote.type) { default: - oxen::log::info(logcat, "Unhandled find_vote type with value: {}", (int)find_vote.type); + log::info(logcat, "Unhandled find_vote type with value: {}", (int)find_vote.type); assert("Unhandled find_vote type" == 0); return nullptr; @@ -643,7 +643,7 @@ namespace service_nodes cryptonote::tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, version)) { - oxen::log::error(logcat, "Could not get state change from tx, possibly corrupt tx"); + log::error(logcat, "Could not get state change from tx, possibly corrupt tx"); continue; } diff --git a/src/cryptonote_core/tx_blink.cpp b/src/cryptonote_core/tx_blink.cpp index b9e0525de..71f55f685 100644 --- a/src/cryptonote_core/tx_blink.cpp +++ b/src/cryptonote_core/tx_blink.cpp @@ -50,7 +50,7 @@ crypto::public_key blink_tx::get_sn_pubkey(subquorum q, int position, const serv if (!blink_quorum) { // TODO FIXME XXX - we don't want a failure here; if this happens we need to go back into state // history to retrieve the state info. (Or maybe this can't happen?) - oxen::log::error(globallogcat, "FIXME: could not get blink quorum for blink_tx"); + log::error(globallogcat, "FIXME: could not get blink quorum for blink_tx"); return crypto::null_pkey; } diff --git a/src/cryptonote_core/tx_pool.cpp b/src/cryptonote_core/tx_pool.cpp index 40de5928a..b2e66fd53 100644 --- a/src/cryptonote_core/tx_pool.cpp +++ b/src/cryptonote_core/tx_pool.cpp @@ -57,7 +57,7 @@ using namespace crypto; namespace cryptonote { - static auto logcat = oxen::log::Cat("txpool"); + static auto logcat = log::Cat("txpool"); namespace { @@ -103,7 +103,7 @@ namespace cryptonote tx_extra_service_node_state_change state_change; if (!get_service_node_state_change_from_tx_extra(tx.extra, state_change, hard_fork_version)) { - oxen::log::error(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in your blockchain, rejecting malformed state change", get_transaction_hash(tx)); + log::error(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in your blockchain, rejecting malformed state change", get_transaction_hash(tx)); return false; } @@ -128,7 +128,7 @@ namespace cryptonote tx_extra_service_node_state_change pool_tx_state_change; if (!get_service_node_state_change_from_tx_extra(pool_tx.extra, pool_tx_state_change, hard_fork_version)) { - oxen::log::info(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(pool_tx)); + log::info(logcat, "Could not get service node state change from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(pool_tx)); continue; } @@ -160,7 +160,7 @@ namespace cryptonote tx_extra_tx_key_image_unlock unlock; if (!cryptonote::get_field_from_tx_extra(tx.extra, unlock)) { - oxen::log::error(logcat, "Could not get key image unlock from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); + log::error(logcat, "Could not get key image unlock from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); return true; } @@ -174,13 +174,13 @@ namespace cryptonote tx_extra_tx_key_image_unlock pool_unlock; if (!cryptonote::get_field_from_tx_extra(pool_tx.extra, pool_unlock)) { - oxen::log::info(logcat, "Could not get key image unlock from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); + log::info(logcat, "Could not get key image unlock from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); return true; } if (unlock == pool_unlock) { - oxen::log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting to unlock the same key image already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); + log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting to unlock the same key image already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); return true; } } @@ -191,7 +191,7 @@ namespace cryptonote tx_extra_oxen_name_system data; if (!cryptonote::get_field_from_tx_extra(tx.extra, data)) { - oxen::log::error(logcat, "Could not get acquire name service from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); + log::error(logcat, "Could not get acquire name service from tx: {}, tx to add is possibly invalid, rejecting", get_transaction_hash(tx)); return true; } @@ -205,13 +205,13 @@ namespace cryptonote tx_extra_oxen_name_system pool_data; if (!cryptonote::get_field_from_tx_extra(pool_tx.extra, pool_data)) { - oxen::log::info(logcat, "Could not get acquire name service from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); + log::info(logcat, "Could not get acquire name service from tx: {}, possibly corrupt tx in the pool", get_transaction_hash(tx)); return true; } if (data.type == pool_data.type && data.name_hash == pool_data.name_hash) { - oxen::log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting the same ONS entry already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); + log::info(logcat, "New TX: {}, has TX: {} from the pool that is requesting the same ONS entry already.", get_transaction_hash(tx), get_transaction_hash(pool_tx)); return true; } } @@ -221,7 +221,7 @@ namespace cryptonote if (tx.type != txtype::standard && tx.type != txtype::stake) { // NOTE(oxen): This is a developer error. If we come across this in production, be conservative and just reject - oxen::log::error(logcat, "Unrecognised transaction type: {} for tx: {}", tx.type, get_transaction_hash(tx)); + log::error(logcat, "Unrecognised transaction type: {} for tx: {}", tx.type, get_transaction_hash(tx)); return true; } } @@ -244,7 +244,7 @@ namespace cryptonote if (tx.version == txversion::v0) { // v0 never accepted - oxen::log::info(logcat, "transaction version 0 is invalid"); + log::info(logcat, "transaction version 0 is invalid"); tvc.m_verifivation_failed = true; return false; } @@ -291,7 +291,7 @@ namespace cryptonote size_t tx_weight_limit = get_transaction_weight_limit(hf_version); if ((!opts.kept_by_block || hf_version >= feature::PER_BYTE_FEE) && tx_weight > tx_weight_limit) { - oxen::log::info(logcat, "transaction is too heavy: {} bytes, maximum weight: {}", tx_weight, tx_weight_limit); + log::info(logcat, "transaction is too heavy: {} bytes, maximum weight: {}", tx_weight, tx_weight_limit); tvc.m_verifivation_failed = true; tvc.m_too_big = true; return false; @@ -315,7 +315,7 @@ namespace cryptonote if (tx_hash != id && m_blinks.count(tx_hash)) { // Warn on this because it almost certainly indicates something malicious - oxen::log::warning(logcat, "Not re-adding popped/incoming tx {} to the mempool: it conflicts with blink tx {}", id, tx_hash); + log::warning(logcat, "Not re-adding popped/incoming tx {} to the mempool: it conflicts with blink tx {}", id, tx_hash); double_spend = true; break; } @@ -323,17 +323,17 @@ namespace cryptonote } else if (opts.approved_blink) { - oxen::log::debug(logcat, "Incoming blink tx is approved, but has {} conflicting local tx(es); dropping conflicts", conflict_txs.size()); + log::debug(logcat, "Incoming blink tx is approved, but has {} conflicting local tx(es); dropping conflicts", conflict_txs.size()); if (remove_blink_conflicts(id, conflict_txs, blink_rollback_height)) double_spend = false; else - oxen::log::error(logcat, "Blink error: incoming blink tx cannot be accepted as it conflicts with checkpointed txs"); + log::error(logcat, "Blink error: incoming blink tx cannot be accepted as it conflicts with checkpointed txs"); } if (double_spend) { mark_double_spend(tx); - oxen::log::info(logcat, "Transaction with id= {} used already spent key images", id); + log::info(logcat, "Transaction with id= {} used already spent key images", id); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; @@ -343,7 +343,7 @@ namespace cryptonote if (!opts.kept_by_block && have_duplicated_non_standard_tx(tx, hf_version)) { mark_double_spend(tx); - oxen::log::info(logcat, "Transaction with id= {} already has a duplicate tx for height", id); + log::info(logcat, "Transaction with id= {} already has a duplicate tx for height", id); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; @@ -351,7 +351,7 @@ namespace cryptonote if (!m_blockchain.check_tx_outputs(tx, tvc)) { - oxen::log::info(logcat, "Transaction with id= {} has at least one invalid output", id); + log::info(logcat, "Transaction with id= {} has at least one invalid output", id); tvc.m_verifivation_failed = true; tvc.m_invalid_output = true; return false; @@ -401,14 +401,14 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Error adding transaction to txpool: {}", e.what()); + log::error(logcat, "Error adding transaction to txpool: {}", e.what()); return false; } tvc.m_verifivation_impossible = true; tvc.m_added_to_pool = true; }else { - oxen::log::info(logcat, "tx used wrong inputs, rejected"); + log::info(logcat, "tx used wrong inputs, rejected"); tvc.m_verifivation_failed = true; tvc.m_invalid_input = true; return false; @@ -447,7 +447,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "internal error: error adding transaction to txpool: {}", e.what()); + log::error(logcat, "internal error: error adding transaction to txpool: {}", e.what()); return false; } tvc.m_added_to_pool = true; @@ -461,7 +461,7 @@ namespace cryptonote ++m_cookie; - oxen::log::info(logcat, "Transaction added to pool: txid {} weight: {} fee/byte: {}", id, tx_weight, (fee / (double)(tx_weight ? tx_weight : 1))); + log::info(logcat, "Transaction added to pool: txid {} weight: {} fee/byte: {}", id, tx_weight, (fee / (double)(tx_weight ? tx_weight : 1))); if (!opts.kept_by_block && !opts.do_not_relay) for (auto& notify : m_tx_notify) @@ -649,7 +649,7 @@ namespace cryptonote { if (m_blinks.count(tx_hash)) { - oxen::log::error(logcat, "Blink error: incoming blink tx {} conflicts with another blink tx {}", id, tx_hash); + log::error(logcat, "Blink error: incoming blink tx {} conflicts with another blink tx {}", id, tx_hash); return false; } } @@ -662,7 +662,7 @@ namespace cryptonote auto heights = m_blockchain.get_transactions_heights(conflict_txs); for (size_t i = 0; i < heights.size(); ++i) { - oxen::log::debug(logcat, "Conflicting tx {}{}", conflict_txs[i], (heights[i] ? "mined at height " + std::to_string(heights[i]) : "in mempool")); + log::debug(logcat, "Conflicting tx {}{}", conflict_txs[i], (heights[i] ? "mined at height " + std::to_string(heights[i]) : "in mempool")); if (!heights[i]) { mempool_txs.push_back(conflict_txs[i]); @@ -682,10 +682,10 @@ namespace cryptonote LockedTXN txnlock(m_blockchain); for (auto &tx : mempool_txs) { - oxen::log::warning(logcat, "Removing conflicting tx {} from mempool for incoming blink tx {}", tx, id); + log::warning(logcat, "Removing conflicting tx {} from mempool for incoming blink tx {}", tx, id); if (!remove_tx(tx)) { - oxen::log::error(logcat, "Internal error: Unable to clear conflicting tx {} from mempool for incoming blink tx {}", tx, id); + log::error(logcat, "Internal error: Unable to clear conflicting tx {} from mempool for incoming blink tx {}", tx, id); return false; } } @@ -694,7 +694,7 @@ namespace cryptonote if (blink_rollback_height && rollback_height_needed < *blink_rollback_height) { - oxen::log::info(logcat, "Incoming blink tx requires a rollback to the {} to un-mine conflicting transactions", rollback_height_needed); + log::info(logcat, "Incoming blink tx requires a rollback to the {} to un-mine conflicting transactions", rollback_height_needed); *blink_rollback_height = rollback_height_needed; } @@ -719,7 +719,7 @@ namespace cryptonote const auto it = stc_it ? *stc_it : find_tx_in_sorted_container(txid); if (it == m_txs_by_fee_and_receive_time.end()) { - oxen::log::error(logcat, "Failed to find tx in txpool sorted list"); + log::error(logcat, "Failed to find tx in txpool sorted list"); return false; } @@ -727,7 +727,7 @@ namespace cryptonote cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(tx_blob, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); return false; } @@ -738,14 +738,14 @@ namespace cryptonote meta = &lookup_meta; else { - oxen::log::error(logcat, "Failed to find tx in txpool"); + log::error(logcat, "Failed to find tx in txpool"); return false; } } // remove first, in case this throws, so key images aren't removed const uint64_t tx_fee = std::get<1>(it->first); - oxen::log::info(logcat, "Removing tx {} from txpool: weight: {}, fee/byte: {}", txid, meta->weight, tx_fee); + log::info(logcat, "Removing tx {} from txpool: weight: {}, fee/byte: {}", txid, meta->weight, tx_fee); m_blockchain.remove_txpool_tx(txid); m_txpool_weight -= meta->weight; remove_transaction_keyimages(tx, txid); @@ -772,7 +772,7 @@ namespace cryptonote txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { - oxen::log::error(logcat, "Failed to find tx in txpool"); + log::error(logcat, "Failed to find tx in txpool"); return false; } auto del_it = forward ? it++ : it--; @@ -792,7 +792,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Error while pruning txpool: {}", e.what()); + log::error(logcat, "Error while pruning txpool: {}", e.what()); return false; } }; @@ -823,7 +823,7 @@ namespace cryptonote if (changed) ++m_cookie; if (m_txpool_weight > m_txpool_max_weight) - oxen::log::info(logcat, "Pool weight after pruning is still larger than limit: {}/{}", m_txpool_weight, m_txpool_max_weight); + log::info(logcat, "Pool weight after pruning is still larger than limit: {}/{}", m_txpool_weight, m_txpool_max_weight); } //--------------------------------------------------------------------------------- bool tx_memory_pool::insert_key_images(const transaction_prefix &tx, const crypto::hash &id, bool kept_by_block) @@ -896,7 +896,7 @@ namespace cryptonote txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(id, meta)) { - oxen::log::error(logcat, "Failed to find tx in txpool"); + log::error(logcat, "Failed to find tx in txpool"); return false; } txblob = m_blockchain.get_txpool_tx_blob(id); @@ -907,7 +907,7 @@ namespace cryptonote } else if (!parse_and_validate_tx_from_blob(txblob, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); return false; } else @@ -928,7 +928,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to remove tx from txpool: {}", e.what()); + log::error(logcat, "Failed to remove tx from txpool: {}", e.what()); return false; } @@ -971,11 +971,11 @@ namespace cryptonote if((tx_age > tools::to_seconds(MEMPOOL_TX_LIVETIME) && !meta.kept_by_block) || (tx_age > tools::to_seconds(MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME) && meta.kept_by_block) ) { - oxen::log::info(logcat, "Tx {} removed from tx pool due to outdated, age: {}", txid, tx_age); + log::info(logcat, "Tx {} removed from tx pool due to outdated, age: {}", txid, tx_age); auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { - oxen::log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); + log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); } else { @@ -999,7 +999,7 @@ namespace cryptonote cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(bd, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); // continue } else @@ -1012,7 +1012,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::warning(logcat, "Failed to remove stuck transaction: {}", txid); + log::warning(logcat, "Failed to remove stuck transaction: {}", txid); // ignore error } } @@ -1046,7 +1046,7 @@ namespace cryptonote cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(bd, tx)) { - oxen::log::info(logcat, "TX in pool could not be parsed from blob, txid: {}", txid); + log::info(logcat, "TX in pool could not be parsed from blob, txid: {}", txid); return true; } @@ -1058,7 +1058,7 @@ namespace cryptonote crypto::hash max_used_block_id = null_hash; if (!m_blockchain.check_tx_inputs(tx, max_used_block_height, max_used_block_id, tvc, /*kept_by_block*/ false)) { - oxen::log::info(logcat, "TX type: {} considered for relaying failed tx inputs check, txid: {}, reason: {}", tx.type, txid, print_tx_verification_context(tvc, &tx)); + log::info(logcat, "TX type: {} considered for relaying failed tx inputs check, txid: {}, reason: {}", tx.type, txid, print_tx_verification_context(tvc, &tx)); return true; } } @@ -1067,7 +1067,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to get transaction blob from db"); + log::error(logcat, "Failed to get transaction blob from db"); // ignore error } } @@ -1092,7 +1092,7 @@ namespace cryptonote ++updated; } } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to upate txpool transaction metadata: {}", e.what()); + log::error(logcat, "Failed to upate txpool transaction metadata: {}", e.what()); } } lock.commit(); @@ -1120,7 +1120,7 @@ namespace cryptonote } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to update txpool transaction metadata: {}", e.what()); + log::error(logcat, "Failed to update txpool transaction metadata: {}", e.what()); // continue } } @@ -1142,7 +1142,7 @@ namespace cryptonote transaction tx; if (!parse_and_validate_tx_from_blob(*bd, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); // continue return true; } @@ -1349,14 +1349,14 @@ namespace cryptonote crypto::hash tx_hash; if (!get_transaction_hash(pool_tx, tx_hash)) { - oxen::log::error(logcat, "Failed to get transaction hash from txpool to check if we can prune a state change"); + log::error(logcat, "Failed to get transaction hash from txpool to check if we can prune a state change"); continue; } txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(tx_hash, meta)) { - oxen::log::error(logcat, "Failed to get tx meta from txpool to check if we can prune a state change"); + log::error(logcat, "Failed to get tx meta from txpool to check if we can prune a state change"); continue; } @@ -1463,11 +1463,11 @@ namespace cryptonote { // Sanity check; if this happens checkpoints are failing and we can't guarantee blinks // anyway (because the blink quorums are not immutable). - oxen::log::error(logcat, "Unable to scan for conflicts: blockchain checkpoints are too far back"); + log::error(logcat, "Unable to scan for conflicts: blockchain checkpoints are too far back"); } else { - oxen::log::debug(logcat, "Found {} conflicting key images for blink tx {}; checking to see if we can roll back", key_image_conflicts.size(), txid); + log::debug(logcat, "Found {} conflicting key images for blink tx {}; checking to see if we can roll back", key_image_conflicts.size(), txid); // Check all the key images of all the blockchain transactions in blocks since the immutable // height, and remove any conflicts from the set of conflicts, updating the rollback height // as we go. If we remove all then rolling back will work, and we can accept the blink, @@ -1491,7 +1491,7 @@ namespace cryptonote txs.clear(); if (!m_blockchain.get_transactions(block.tx_hashes, txs)) { - oxen::log::error(logcat, "Unable to get transactions for block {}", block.hash); + log::error(logcat, "Unable to get transactions for block {}", block.hash); can_fix_with_a_rollback = false; break; } @@ -1508,18 +1508,18 @@ namespace cryptonote end: if (key_image_conflicts.empty() && earliest < height && earliest > immutable) { - oxen::log::debug(logcat, "Blink admission requires rolling back to height {}", earliest); + log::debug(logcat, "Blink admission requires rolling back to height {}", earliest); can_fix_with_a_rollback = true; if (*blink_rollback_height == 0 || *blink_rollback_height > earliest) *blink_rollback_height = earliest; } } else - oxen::log::error(logcat, "Failed to retrieve blocks for trying a blink rollback!"); + log::error(logcat, "Failed to retrieve blocks for trying a blink rollback!"); } if (!can_fix_with_a_rollback) { - oxen::log::warning(logcat, "Blink admission of {} is not possible even with a rollback: found {} key image conflicts in immutable blocks", txid, key_image_conflicts.size()); + log::warning(logcat, "Blink admission of {} is not possible even with a rollback: found {} key image conflicts in immutable blocks", txid, key_image_conflicts.size()); ret = false; tvc.m_double_spend = true; } @@ -1654,13 +1654,13 @@ end: txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { - oxen::log::error(logcat, "Failed to find tx meta in txpool"); + log::error(logcat, "Failed to find tx meta in txpool"); // continue, not fatal continue; } if (!meta.double_spend_seen) { - oxen::log::debug(logcat, "Marking {} as double spending {}", txid, itk.k_image); + log::debug(logcat, "Marking {} as double spending {}", txid, itk.k_image); meta.double_spend_seen = true; changed = true; try @@ -1669,7 +1669,7 @@ end: } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to update tx meta: {}", e.what()); + log::error(logcat, "Failed to update tx meta: {}", e.what()); // continue, not fatal } } @@ -1697,7 +1697,7 @@ end: block_reward_parts reward_parts = {}; if (!get_oxen_block_reward(median_weight, total_weight, already_generated_coins, version, reward_parts, block_reward_context)) { - oxen::log::error(logcat, "Failed to get block reward for empty block"); + log::error(logcat, "Failed to get block reward for empty block"); return false; } @@ -1707,7 +1707,7 @@ end: size_t const max_total_weight = 2 * median_weight - COINBASE_BLOB_RESERVED_SIZE; std::unordered_set k_images; - oxen::log::debug(logcat, "Filling block template, median weight {}, {} txes in the pool", median_weight, m_txs_by_fee_and_receive_time.size()); + log::debug(logcat, "Filling block template, median weight {}, {} txes in the pool", median_weight, m_txs_by_fee_and_receive_time.size()); LockedTXN lock(m_blockchain); @@ -1719,15 +1719,15 @@ end: txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(sorted_it.second, meta)) { - oxen::log::error(logcat, " failed to find tx meta"); + log::error(logcat, " failed to find tx meta"); continue; } - oxen::log::debug(logcat, "Considering {}, weight {}, current block weight {}/{}, current reward {}", sorted_it.second, meta.weight, total_weight, max_total_weight, print_money(best_reward)); + log::debug(logcat, "Considering {}, weight {}, current block weight {}/{}, current reward {}", sorted_it.second, meta.weight, total_weight, max_total_weight, print_money(best_reward)); // Can not exceed maximum block weight if (max_total_weight < total_weight + meta.weight) { - oxen::log::debug(logcat, " would exceed maximum block weight"); + log::debug(logcat, " would exceed maximum block weight"); continue; } @@ -1739,7 +1739,7 @@ end: block_reward_parts next_reward_parts = {}; if(!get_oxen_block_reward(median_weight, total_weight + meta.weight, already_generated_coins, version, next_reward_parts, next_block_reward_context)) { - oxen::log::debug(logcat, "Block reward calculation bug"); + log::debug(logcat, "Block reward calculation bug"); return false; } @@ -1759,7 +1759,7 @@ end: // If we're getting lower reward tx, don't include this TX if (next_reward < best_reward) { - oxen::log::debug(logcat, " would decrease reward to {}", print_money(next_reward)); + log::debug(logcat, " would decrease reward to {}", print_money(next_reward)); continue; } @@ -1782,7 +1782,7 @@ end: } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to check transaction readiness: {}", e.what()); + log::error(logcat, "Failed to check transaction readiness: {}", e.what()); // continue, not fatal } if (memcmp(&original_meta, &meta, sizeof(meta))) @@ -1793,18 +1793,18 @@ end: } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to update tx meta: {}", e.what()); + log::error(logcat, "Failed to update tx meta: {}", e.what()); // continue, not fatal } } if (!ready) { - oxen::log::debug(logcat, " not ready to go"); + log::debug(logcat, " not ready to go"); continue; } if (have_key_images(k_images, tx)) { - oxen::log::debug(logcat, " key images already seen"); + log::debug(logcat, " key images already seen"); continue; } @@ -1814,12 +1814,12 @@ end: net_fee = next_reward_parts.miner_fee; best_reward = next_reward; append_key_images(k_images, tx); - oxen::log::debug(logcat, " added, new block weight {}/{}, reward {}", total_weight, max_total_weight, print_money(best_reward)); + log::debug(logcat, " added, new block weight {}/{}, reward {}", total_weight, max_total_weight, print_money(best_reward)); } lock.commit(); expected_reward = best_reward; - oxen::log::debug(logcat, "Block template filled with {} txes, weight {}/{}, reward {} (including {} in fees)", bl.tx_hashes.size(), total_weight, max_total_weight, print_money(best_reward), print_money(net_fee)); + log::debug(logcat, "Block template filled with {} txes, weight {}/{}, reward {} (including {} in fees)", bl.tx_hashes.size(), total_weight, max_total_weight, print_money(best_reward), print_money(net_fee)); return true; } //--------------------------------------------------------------------------------- @@ -1834,11 +1834,11 @@ end: m_blockchain.for_all_txpool_txes([this, &remove, tx_weight_limit](const crypto::hash &txid, const txpool_tx_meta_t &meta, const std::string*) { m_txpool_weight += meta.weight; if (meta.weight > tx_weight_limit) { - oxen::log::info(logcat, "Transaction {} is too big ({} bytes), removing it from pool", txid, meta.weight); + log::info(logcat, "Transaction {} is too big ({} bytes), removing it from pool", txid, meta.weight); remove.insert(txid); } else if (m_blockchain.have_tx(txid)) { - oxen::log::info(logcat, "Transaction {} is in the blockchain, removing it from pool", txid); + log::info(logcat, "Transaction {} is in the blockchain, removing it from pool", txid); remove.insert(txid); } return true; @@ -1856,7 +1856,7 @@ end: cryptonote::transaction tx; if (!parse_and_validate_tx_from_blob(txblob, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); continue; } // remove tx from db first @@ -1866,7 +1866,7 @@ end: auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { - oxen::log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); + log::info(logcat, "Removing tx {} from tx pool, but it was not found in the sorted txs container!", txid); } else { @@ -1876,7 +1876,7 @@ end: } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to remove invalid tx from pool"); + log::error(logcat, "Failed to remove invalid tx from pool"); // continue } } @@ -1908,13 +1908,13 @@ end: cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(*bd, tx)) { - oxen::log::warning(logcat, "Failed to parse tx from txpool, removing"); + log::warning(logcat, "Failed to parse tx from txpool, removing"); remove.push_back(txid); return true; } if (!insert_key_images(tx, txid, meta.kept_by_block)) { - oxen::log::error(logcat, "Failed to insert key images from txpool tx"); + log::error(logcat, "Failed to insert key images from txpool tx"); return false; } @@ -1937,7 +1937,7 @@ end: } catch (const std::exception &e) { - oxen::log::warning(logcat, "Failed to remove corrupt transaction: {}", txid); + log::warning(logcat, "Failed to remove corrupt transaction: {}", txid); // ignore error } } diff --git a/src/cryptonote_core/tx_sanity_check.cpp b/src/cryptonote_core/tx_sanity_check.cpp index d58e5ae1c..d7d340baa 100644 --- a/src/cryptonote_core/tx_sanity_check.cpp +++ b/src/cryptonote_core/tx_sanity_check.cpp @@ -37,7 +37,7 @@ namespace cryptonote { -static auto logcat = oxen::log::Cat("verify"); +static auto logcat = log::Cat("verify"); bool tx_sanity_check(const std::string &tx_blob, uint64_t rct_outs_available) { @@ -45,13 +45,13 @@ bool tx_sanity_check(const std::string &tx_blob, uint64_t rct_outs_available) if (!cryptonote::parse_and_validate_tx_from_blob(tx_blob, tx)) { - oxen::log::error(logcat, "Failed to parse transaction"); + log::error(logcat, "Failed to parse transaction"); return false; } if (cryptonote::is_coinbase(tx)) { - oxen::log::error(logcat, "Transaction is coinbase"); + log::error(logcat, "Transaction is coinbase"); return false; } std::set rct_indices; @@ -76,7 +76,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui { if (n_indices <= 10) { - oxen::log::debug(logcat, "n_indices is only {}, not checking", n_indices); + log::debug(logcat, "n_indices is only {}, not checking", n_indices); return true; } @@ -85,7 +85,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui if (rct_indices.size() < n_indices * 8 / 10) { - oxen::log::error(logcat, "amount of unique indices is too low (amount of rct indices is {}, out of total {} indices)", rct_indices.size(), n_indices); + log::error(logcat, "amount of unique indices is too low (amount of rct indices is {}, out of total {} indices)", rct_indices.size(), n_indices); return false; } @@ -93,7 +93,7 @@ bool tx_sanity_check(const std::set &rct_indices, size_t n_indices, ui uint64_t median = tools::median(std::move(offsets)); if (median < rct_outs_available * 6 / 10) { - oxen::log::error(logcat, "median offset index is too low (median is {} out of total {}offsets). Transactions should contain a higher fraction of recent outputs.", median, rct_outs_available); + log::error(logcat, "median offset index is too low (median is {} out of total {}offsets). Transactions should contain a higher fraction of recent outputs.", median, rct_outs_available); return false; } diff --git a/src/cryptonote_protocol/block_queue.cpp b/src/cryptonote_protocol/block_queue.cpp index e3ae75053..7ae677555 100644 --- a/src/cryptonote_protocol/block_queue.cpp +++ b/src/cryptonote_protocol/block_queue.cpp @@ -52,7 +52,7 @@ struct hash namespace cryptonote { - static auto logcat = oxen::log::Cat("cn.block_queue"); + static auto logcat = log::Cat("cn.block_queue"); void block_queue::add_blocks(uint64_t height, std::vector bcel, const boost::uuids::uuid &connection_id, float rate, size_t size) { @@ -181,9 +181,9 @@ uint64_t block_queue::get_next_needed_height(uint64_t blockchain_height) const void block_queue::print() const { std::unique_lock lock{mutex}; - oxen::log::debug(logcat, "Block queue has {} spans", blocks.size()); + log::debug(logcat, "Block queue has {} spans", blocks.size()); for (const auto &span: blocks) - oxen::log::debug(logcat, " {} - {} ({}) - {} {} ({} kB/s)", span.start_block_height, (span.start_block_height+span.nblocks-1), span.nblocks, (span.blocks.empty() ? "scheduled" : "filled "), boost::lexical_cast(span.connection_id), ((unsigned)(span.rate*10/1024.f))/10.f); + log::debug(logcat, " {} - {} ({}) - {} {} ({} kB/s)", span.start_block_height, (span.start_block_height+span.nblocks-1), span.nblocks, (span.blocks.empty() ? "scheduled" : "filled "), boost::lexical_cast(span.connection_id), ((unsigned)(span.rate*10/1024.f))/10.f); } std::string block_queue::get_overview(uint64_t blockchain_height) const @@ -241,15 +241,15 @@ std::pair block_queue::reserve_span( { std::unique_lock lock{mutex}; - oxen::log::debug(logcat, "reserve_span: first_block_height {}, last_block_height {}, max {}, seed {}, blockchain_height {}, block hashes size {}", first_block_height, last_block_height, max_blocks, epee::string_tools::to_string_hex(pruning_seed), blockchain_height, block_hashes.size()); + log::debug(logcat, "reserve_span: first_block_height {}, last_block_height {}, max {}, seed {}, blockchain_height {}, block hashes size {}", first_block_height, last_block_height, max_blocks, epee::string_tools::to_string_hex(pruning_seed), blockchain_height, block_hashes.size()); if (last_block_height < first_block_height || max_blocks == 0) { - oxen::log::debug(logcat, "reserve_span: early out: first_block_height {}, last_block_height {}, max_blocks {}", first_block_height, last_block_height, max_blocks); + log::debug(logcat, "reserve_span: early out: first_block_height {}, last_block_height {}, max_blocks {}", first_block_height, last_block_height, max_blocks); return std::make_pair(0, 0); } if (block_hashes.size() > last_block_height) { - oxen::log::debug(logcat, "reserve_span: more block hashes than fit within last_block_height: {} and {}", block_hashes.size(), last_block_height); + log::debug(logcat, "reserve_span: more block hashes than fit within last_block_height: {} and {}", block_hashes.size(), last_block_height); return std::make_pair(0, 0); } @@ -264,17 +264,17 @@ std::pair block_queue::reserve_span( // if the peer's pruned for the starting block and its unpruned stripe comes next, start downloading from there const uint32_t next_unpruned_height = tools::get_next_unpruned_block_height(span_start_height, blockchain_height, pruning_seed); - oxen::log::debug(logcat, "reserve_span: next_unpruned_height {} from {} and seed {}, limit {}", next_unpruned_height, span_start_height, epee::string_tools::to_string_hex(pruning_seed), span_start_height); + log::debug(logcat, "reserve_span: next_unpruned_height {} from {} and seed {}, limit {}", next_unpruned_height, span_start_height, epee::string_tools::to_string_hex(pruning_seed), span_start_height); if (next_unpruned_height > span_start_height && next_unpruned_height < span_start_height + PRUNING_STRIPE_SIZE) { - oxen::log::debug(logcat, "We can download from next span: ideal height {}, next unpruned height {}(+{}), current seed {}", span_start_height, next_unpruned_height, next_unpruned_height - span_start_height, pruning_seed); + log::debug(logcat, "We can download from next span: ideal height {}, next unpruned height {}(+{}), current seed {}", span_start_height, next_unpruned_height, next_unpruned_height - span_start_height, pruning_seed); span_start_height = next_unpruned_height; } - oxen::log::debug(logcat, "span_start_height: {}", span_start_height); + log::debug(logcat, "span_start_height: {}", span_start_height); const uint64_t block_hashes_start_height = last_block_height - block_hashes.size() + 1; if (span_start_height >= block_hashes.size() + block_hashes_start_height) { - oxen::log::debug(logcat, "Out of hashes, cannot reserve"); + log::debug(logcat, "Out of hashes, cannot reserve"); return std::make_pair(0, 0); } @@ -295,10 +295,10 @@ std::pair block_queue::reserve_span( } if (span_length == 0) { - oxen::log::debug(logcat, "span_length 0, cannot reserve"); + log::debug(logcat, "span_length 0, cannot reserve"); return std::make_pair(0, 0); } - oxen::log::debug(logcat, "Reserving span {} - {} for {}", span_start_height, (span_start_height + span_length - 1), boost::lexical_cast(connection_id)); + log::debug(logcat, "Reserving span {} - {} for {}", span_start_height, (span_start_height + span_length - 1), boost::lexical_cast(connection_id)); add_blocks(span_start_height, span_length, connection_id, std::chrono::steady_clock::now()); set_span_hashes(span_start_height, connection_id, hashes); return std::make_pair(span_start_height, span_length); @@ -464,7 +464,7 @@ float block_queue::get_speed(const boost::uuids::uuid &connection_id) const return 1.0f; // everything dead ? Can't happen, but let's trap anyway const float speed = conn_rate / best_rate; - oxen::log::trace(logcat, " Relative speed for {}: {} ({}/{}", boost::lexical_cast(connection_id), speed, conn_rate, best_rate); + log::trace(logcat, " Relative speed for {}: {} ({}/{}", boost::lexical_cast(connection_id), speed, conn_rate, best_rate); return speed; } @@ -489,7 +489,7 @@ float block_queue::get_download_rate(const boost::uuids::uuid &connection_id) co if (conn_rate < 0) conn_rate = 0.0f; - oxen::log::trace(logcat, "Download rate for {}: {} b/s", boost::lexical_cast(connection_id), conn_rate); + log::trace(logcat, "Download rate for {}: {} b/s", boost::lexical_cast(connection_id), conn_rate); return conn_rate; } diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.h b/src/cryptonote_protocol/cryptonote_protocol_handler.h index ebc9a456e..e3044dd70 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.h +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.h @@ -134,7 +134,7 @@ namespace cryptonote template bool relay_to_synchronized_peers(typename T::request& arg, cryptonote_connection_context& exclude_context) { - oxen::log::debug(globallogcat, "[{}] post relay {} -->", epee::net_utils::print_connection_context_short(exclude_context), tools::type_name()); + log::debug(globallogcat, "[{}] post relay {} -->", epee::net_utils::print_connection_context_short(exclude_context), tools::type_name()); std::vector> connections; m_p2p->for_each_connection([&exclude_context, &connections](connection_context& context, nodetool::peerid_type peer_id) { @@ -211,7 +211,7 @@ namespace cryptonote template bool post_notify(typename t_parameter::request& arg, cryptonote_connection_context& context) { - oxen::log::debug(globallogcat, "[{}] post {} -->", epee::net_utils::print_connection_context_short(context), tools::type_name()); + log::debug(globallogcat, "[{}] post {} -->", epee::net_utils::print_connection_context_short(context), tools::type_name()); std::string blob; epee::serialization::store_t_to_binary(arg, blob); return m_p2p->invoke_notify_to_peer(t_parameter::ID, epee::strspan(blob), context); diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.inl b/src/cryptonote_protocol/cryptonote_protocol_handler.inl index 7e1763243..9e2c4b23f 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.inl +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.inl @@ -60,7 +60,7 @@ namespace cryptonote { - static auto logcat = oxen::log::Cat("net.cn"); + static auto logcat = log::Cat("net.cn"); constexpr size_t BLOCK_QUEUE_NSPANS_THRESHOLD = 10; // chunks of N blocks constexpr size_t BLOCK_QUEUE_SIZE_THRESHOLD = 100*1024*1024; // bytes, i.e. 100 MB @@ -120,7 +120,7 @@ namespace cryptonote template bool t_cryptonote_protocol_handler::on_callback(cryptonote_connection_context& context) { - oxen::log::debug(logcat, "callback fired"); + log::debug(logcat, "callback fired"); CHECK_AND_ASSERT_MES_CC( context.m_callback_request_count > 0, false, "false callback fired, but context.m_callback_request_count=" << context.m_callback_request_count); --context.m_callback_request_count; @@ -129,11 +129,11 @@ namespace cryptonote NOTIFY_REQUEST_CHAIN::request r{}; context.m_needed_objects.clear(); m_core.get_blockchain_storage().get_short_chain_history(r.block_ids); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); post_notify(r, context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); } else if(context.m_state == cryptonote_connection_context::state_standby) { @@ -175,9 +175,9 @@ namespace cryptonote context.m_need_blink_sync = false; if (!r.heights.empty()) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_BLOCK_BLINKS: requesting blink tx lists for {} blocks", r.heights.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_BLOCK_BLINKS: requesting blink tx lists for {} blocks", r.heights.size()); post_notify(r, context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting block blinks", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting block blinks", cryptonote::get_protocol_state_string(context.m_state)); } } @@ -244,7 +244,7 @@ namespace cryptonote << std::setw(10) << up_sum << std::setw(13) << up_curr_sum << "\n"; - oxen::log::warning(logcat, "Connections:\n{}", ss.str()); + log::warning(logcat, "Connections:\n{}", ss.str()); } //------------------------------------------------------------------------------------------------------------------------ // Returns a list of connection_info objects describing each open p2p connection @@ -331,7 +331,7 @@ namespace cryptonote if (version != hshd.top_version) { if (version < hshd.top_version && version == get_network_version(nettype, m_core.get_current_blockchain_height())) - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "{} peer claims higher version than we think ({} for {} instead of {}) 0 we may be forked from the network and a software upgrade may be needed", context, (unsigned)hshd.top_version, (hshd.current_height - 1), (unsigned)version)); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "{} peer claims higher version than we think ({} for {} instead of {}) 0 we may be forked from the network and a software upgrade may be needed", context, (unsigned)hshd.top_version, (hshd.current_height - 1), (unsigned)version)); return false; } } @@ -342,7 +342,7 @@ namespace cryptonote const uint32_t log_stripes = tools::get_pruning_log_stripes(hshd.pruning_seed); if (log_stripes != PRUNING_LOG_STRIPES || tools::get_pruning_stripe(hshd.pruning_seed) > (1u << log_stripes)) { - oxen::log::warning(logcat, "{} peer claim unexpected pruning seed {}, disconnecting", context, epee::string_tools::to_string_hex(hshd.pruning_seed)); + log::warning(logcat, "{} peer claim unexpected pruning seed {}, disconnecting", context, epee::string_tools::to_string_hex(hshd.pruning_seed)); return false; } } @@ -351,7 +351,7 @@ namespace cryptonote context.m_pruning_seed = hshd.pruning_seed; if constexpr (PRUNING_DEBUG_SPOOF_SEED) { context.m_pruning_seed = tools::make_pruning_seed(1 + (context.m_remote_address.as().ip()) % (1 << PRUNING_LOG_STRIPES), PRUNING_LOG_STRIPES); - oxen::log::info(logcat, "{}{}, seed address {}", context, "New connection posing as pruning seed ", epee::string_tools::to_string_hex(context.m_pruning_seed), &context.m_pruning_seed); + log::info(logcat, "{}{}, seed address {}", context, "New connection posing as pruning seed ", epee::string_tools::to_string_hex(context.m_pruning_seed), &context.m_pruning_seed); } // No chain synchronization over hidden networks (tor, i2p, etc.) @@ -369,12 +369,12 @@ namespace cryptonote { if (hshd.blink_blocks.size() != hshd.blink_hash.size()) { - oxen::log::warning(logcat, "{} peer sent illegal mismatched blink heights/hashes; disconnecting", context); + log::warning(logcat, "{} peer sent illegal mismatched blink heights/hashes; disconnecting", context); return false; } else if (hshd.blink_blocks.size() > 1000) { - oxen::log::warning(logcat, "{} peer sent too many post-checkpoint blink blocks; disconnecting", context); + log::warning(logcat, "{} peer sent too many post-checkpoint blink blocks; disconnecting", context); return false; } @@ -388,13 +388,13 @@ namespace cryptonote context.m_blink_state.erase(context.m_blink_state.lower_bound(1), context.m_blink_state.lower_bound(immutable_height + 1)); auto our_blink_hashes = m_core.get_pool().get_blink_checksums(); uint64_t last_height; - oxen::log::debug(logcat, "Peer sent {} blink hashes", hshd.blink_blocks.size()); + log::debug(logcat, "Peer sent {} blink hashes", hshd.blink_blocks.size()); for (size_t i = 0; i < hshd.blink_blocks.size(); i++) { auto &height = hshd.blink_blocks[i]; if (i == 0 || height > last_height) last_height = height; else { - oxen::log::warning(logcat, "{} peer sent blink tx heights out of order, which is not valid; disconnecting", context); + log::warning(logcat, "{} peer sent blink tx heights out of order, which is not valid; disconnecting", context); return false; } @@ -429,7 +429,7 @@ namespace cryptonote } if (context.m_need_blink_sync) - oxen::log::info(logcat, "{}Need to synchronized blink signatures", context); + log::info(logcat, "{}Need to synchronized blink signatures", context); } uint64_t target = m_core.get_target_blockchain_height(); @@ -448,9 +448,9 @@ namespace cryptonote uint64_t max_block_height = std::max(hshd.current_height, curr_height); std::string sync_msg = fmt::format("{}Sync data returned a new top block candidate: {} -> {} [Your node is {} blocks ({} {})]\nSYNCHRONIZATION started", context, curr_height, hshd.current_height, abs_diff, tools::get_human_readable_timespan(abs_diff*TARGET_BLOCK_TIME), (0 <= diff ? "behind" : "ahead")); if (is_initial) - oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::cyan), sync_msg)); + log::info(globallogcat, fmt::format(fg(fmt::terminal_color::cyan), sync_msg)); else - oxen::log::debug(globallogcat, sync_msg); + log::debug(globallogcat, sync_msg); m_period_start_time = m_sync_start_time = std::chrono::steady_clock::now(); m_sync_start_height = curr_height; @@ -491,12 +491,12 @@ namespace cryptonote if (context.m_need_blink_sync || context.m_state == cryptonote_connection_context::state_synchronizing) { - oxen::log::debug(logcat, "{}Remote blockchain height: {}, id: {}", context, hshd.current_height, hshd.top_id); + log::debug(logcat, "{}Remote blockchain height: {}, id: {}", context, hshd.current_height, hshd.top_id); //let the socket to send response to handshake, but request callback, to let send request data after response - oxen::log::debug(logcat, "requesting callback"); + log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); } return true; } @@ -532,20 +532,20 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_fluffy_block(int command, NOTIFY_NEW_FLUFFY_BLOCK::request& arg, cryptonote_connection_context& context) { - if(oxen::log::Cat("net.p2p,msg")->should_log(oxen::log::Level::info)) + if(log::Cat("net.p2p,msg")->should_log(log::Level::info)) { crypto::hash hash; cryptonote::block b; bool ret = cryptonote::parse_and_validate_block_from_blob(arg.b.block, b, &hash); if (ret) - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_FLUFFY_BLOCK {} (height {}, {} txes)", hash, arg.current_blockchain_height, arg.b.txs.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_FLUFFY_BLOCK {} (height {}, {} txes)", hash, arg.current_blockchain_height, arg.b.txs.size()); } if(context.m_state != cryptonote_connection_context::state_normal) return 1; if(!is_synchronized() || m_no_sync) // can happen if a peer connection goes to normal but another thread still hasn't finished adding queued blocks { - oxen::log::debug(logcat, "{}Received new block while syncing, ignored", context); + log::debug(logcat, "{}Received new block while syncing, ignored", context); return 1; } @@ -560,7 +560,7 @@ namespace cryptonote // What we asked for != to what we received .. if(context.m_requested_objects.size() != arg.b.txs.size()) { - oxen::log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK -> request/response mismatch, block = {}, requested = {}, received = {}, dropping connection", tools::type_to_hex(get_blob_hash(arg.b.block)), context.m_requested_objects.size(), new_block.tx_hashes.size()); + log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK -> request/response mismatch, block = {}, requested = {}, received = {}, dropping connection", tools::type_to_hex(get_blob_hash(arg.b.block)), context.m_requested_objects.size(), new_block.tx_hashes.size()); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -588,7 +588,7 @@ namespace cryptonote { if(!get_transaction_hash(tx, tx_hash)) { - oxen::log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, dropping connection"); + log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -596,7 +596,7 @@ namespace cryptonote } catch(...) { - oxen::log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, exception thrown, dropping connection"); + log::info(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: get_transaction_hash failed, exception thrown, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -614,7 +614,7 @@ namespace cryptonote auto req_tx_it = context.m_requested_objects.find(tx_hash); if(req_tx_it == context.m_requested_objects.end()) { - oxen::log::error(logcat, "Peer sent wrong transaction (NOTIFY_NEW_FLUFFY_BLOCK): transaction with id = {} wasn't requested, dropping connection", tx_hash); + log::error(logcat, "Peer sent wrong transaction (NOTIFY_NEW_FLUFFY_BLOCK): transaction with id = {} wasn't requested, dropping connection", tx_hash); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -627,11 +627,11 @@ namespace cryptonote // sent in our pool, so don't verify again.. if(!m_core.get_pool().have_tx(tx_hash)) { - oxen::log::debug(logcat, "Incoming tx {} not in pool, adding", tx_hash); + log::debug(logcat, "Incoming tx {} not in pool, adding", tx_hash); cryptonote::tx_verification_context tvc{}; if(!m_core.handle_incoming_tx(tx_blob, tvc, tx_pool_options::from_block()) || tvc.m_verifivation_failed) { - oxen::log::info(logcat, "Block verification failed: transaction verification failed, dropping connection"); + log::info(logcat, "Block verification failed: transaction verification failed, dropping connection"); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -647,7 +647,7 @@ namespace cryptonote } else { - oxen::log::error(logcat, "sent wrong tx: failed to parse and validate transaction: {}, dropping connection", oxenc::to_hex(tx_blob)); + log::error(logcat, "sent wrong tx: failed to parse and validate transaction: {}, dropping connection", oxenc::to_hex(tx_blob)); drop_connection(context, false, false); m_core.resume_mine(); return 1; @@ -660,7 +660,7 @@ namespace cryptonote // ones we received. if(context.m_requested_objects.size()) { - oxen::log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: peer sent the number of transaction requested, but not the actual transactions requested, context.m_requested_objects.size() = {}, dropping connection", context.m_requested_objects.size()); + log::error(logcat, "NOTIFY_NEW_FLUFFY_BLOCK: peer sent the number of transaction requested, but not the actual transactions requested, context.m_requested_objects.size() = {}, dropping connection", context.m_requested_objects.size()); drop_connection(context, false, false); m_core.resume_mine(); @@ -689,14 +689,14 @@ namespace cryptonote } else { - oxen::log::error(logcat, "1 tx requested, none not found, but {} returned", txes.size()); + log::error(logcat, "1 tx requested, none not found, but {} returned", txes.size()); m_core.resume_mine(); return 1; } } else { - oxen::log::debug(logcat, "Tx {} not found in pool", tx_hash); + log::debug(logcat, "Tx {} not found in pool", tx_hash); need_tx_indices.push_back(tx_idx); } } @@ -707,21 +707,21 @@ namespace cryptonote if(!need_tx_indices.empty()) // drats, we don't have everything.. { // request non-mempool txs - oxen::log::debug(logcat, "We are missing {} txes for this fluffy block", need_tx_indices.size()); + log::debug(logcat, "We are missing {} txes for this fluffy block", need_tx_indices.size()); for (auto txidx: need_tx_indices) - oxen::log::debug(logcat, " tx {}", new_block.tx_hashes[txidx]); + log::debug(logcat, " tx {}", new_block.tx_hashes[txidx]); NOTIFY_REQUEST_FLUFFY_MISSING_TX::request missing_tx_req; missing_tx_req.block_hash = get_block_hash(new_block); missing_tx_req.current_blockchain_height = arg.current_blockchain_height; missing_tx_req.missing_tx_indices = std::move(need_tx_indices); m_core.resume_mine(); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_indices.size()={}", missing_tx_req.missing_tx_indices.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_indices.size()={}", missing_tx_req.missing_tx_indices.size()); post_notify(missing_tx_req, context); } else // whoo-hoo we've got em all .. { - oxen::log::debug(logcat, "We have all needed txes for this fluffy block"); + log::debug(logcat, "We have all needed txes for this fluffy block"); block_complete_entry b = {}; b.block = arg.b.block; @@ -734,7 +734,7 @@ namespace cryptonote std::vector pblocks; if (!m_core.prepare_handle_incoming_blocks(blocks, pblocks)) { - oxen::log::warning(logcat, "Failure in prepare_handle_incoming_blocks"); + log::warning(logcat, "Failure in prepare_handle_incoming_blocks"); m_core.resume_mine(); return 1; } @@ -743,7 +743,7 @@ namespace cryptonote m_core.handle_incoming_block(arg.b.block, pblocks.empty() ? NULL : &pblocks[0], bvc, nullptr /*checkpoint*/); // got block from handle_notify_new_block if (!m_core.cleanup_handle_incoming_blocks(true)) { - oxen::log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); + log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); m_core.resume_mine(); return 1; } @@ -751,7 +751,7 @@ namespace cryptonote if( bvc.m_verifivation_failed ) { - oxen::log::warning(logcat, "Block verification failed, dropping connection"); + log::warning(logcat, "Block verification failed, dropping connection"); drop_connection(context, true, false); return 1; } @@ -769,15 +769,15 @@ namespace cryptonote context.m_state = cryptonote_connection_context::state_synchronizing; NOTIFY_REQUEST_CHAIN::request r{}; m_core.get_blockchain_storage().get_short_chain_history(r.block_ids); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}", r.block_ids.size()); post_notify(r, context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); } } } else { - oxen::log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(arg.b.block)); + log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(arg.b.block)); m_core.resume_mine(); drop_connection(context, false, false); @@ -791,7 +791,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_uptime_proof(int command, NOTIFY_UPTIME_PROOF::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_UPTIME_PROOF"); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_UPTIME_PROOF"); // NOTE: Don't relay your own uptime proof, otherwise we have the following situation // Node1 sends uptime -> @@ -823,7 +823,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_btencoded_uptime_proof(int command, NOTIFY_BTENCODED_UPTIME_PROOF::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_BTENCODED_UPTIME_PROOF"); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_BTENCODED_UPTIME_PROOF"); // NOTE: Don't relay your own uptime proof, otherwise we have the following situation // Node1 sends uptime -> @@ -857,14 +857,14 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_service_node_vote(int command, NOTIFY_NEW_SERVICE_NODE_VOTE::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_SERVICE_NODE_VOTE ({} txes)", arg.votes.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_SERVICE_NODE_VOTE ({} txes)", arg.votes.size()); if(context.m_state != cryptonote_connection_context::state_normal) return 1; if(!is_synchronized() || m_no_sync) { - oxen::log::debug(logcat, "{}Received new service node vote while syncing, ignored", context); + log::debug(logcat, "{}Received new service node vote while syncing, ignored", context); return 1; } @@ -875,7 +875,7 @@ namespace cryptonote if (vvc.m_verification_failed) { - oxen::log::info(logcat, "Vote type: {}, verification failed, dropping connection", it->type); + log::info(logcat, "Vote type: {}, verification failed, dropping connection", it->type); drop_connection(context, false /*add_fail*/, false /*flush_all_spans i.e. delete cached block data from this peer*/); return 1; } @@ -900,7 +900,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_request_fluffy_missing_tx(int command, NOTIFY_REQUEST_FLUFFY_MISSING_TX::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_FLUFFY_MISSING_TX ({} txes), block hash {}", arg.missing_tx_indices.size(), arg.block_hash); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_FLUFFY_MISSING_TX ({} txes), block hash {}", arg.missing_tx_indices.size(), arg.block_hash); std::vector> local_blocks; std::vector local_txs; @@ -908,7 +908,7 @@ namespace cryptonote block b; if (!m_core.get_block_by_hash(arg.block_hash, b)) { - oxen::log::error(logcat, "failed to find block: {}, dropping connection", arg.block_hash); + log::error(logcat, "failed to find block: {}, dropping connection", arg.block_hash); drop_connection(context, false, false); return 1; } @@ -927,7 +927,7 @@ namespace cryptonote { if (!requested_index_set.insert(requested_index).second) { - oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for the same tx index more than once, tx index = {}, block tx count {}, block_height = {}, dropping connection", requested_index, b.tx_hashes.size(), arg.current_blockchain_height); + log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for the same tx index more than once, tx index = {}, block tx count {}, block_height = {}, dropping connection", requested_index, b.tx_hashes.size(), arg.current_blockchain_height); drop_connection(context, false, false); return 1; @@ -939,12 +939,12 @@ namespace cryptonote { if(tx_idx < b.tx_hashes.size()) { - oxen::log::debug(logcat, " tx {}", b.tx_hashes[tx_idx]); + log::debug(logcat, " tx {}", b.tx_hashes[tx_idx]); txids.push_back(b.tx_hashes[tx_idx]); } else { - oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for a tx whose index is out of bounds, tx index = {}, block tx count {}, block_height = {}, dropping connection ", tx_idx, b.tx_hashes.size(), arg.current_blockchain_height); + log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, request is asking for a tx whose index is out of bounds, tx index = {}, block tx count {}, block_height = {}, dropping connection ", tx_idx, b.tx_hashes.size(), arg.current_blockchain_height); drop_connection(context, false, false); return 1; @@ -955,13 +955,13 @@ namespace cryptonote std::unordered_set missed; if (!m_core.get_transactions(txids, txs, &missed)) { - oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, failed to get requested transactions"); + log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, failed to get requested transactions"); drop_connection(context, false, false); return 1; } if (!missed.empty() || txs.size() != txids.size()) { - oxen::log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, {} requested transactions not found, dropping connection", missed.size()); + log::error(logcat, "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, {} requested transactions not found, dropping connection", missed.size()); drop_connection(context, false, false); return 1; } @@ -971,7 +971,7 @@ namespace cryptonote fluffy_response.b.txs.push_back(t_serializable_object_to_blob(tx)); } - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: txs.size()={}, rsp.current_blockchain_height={}", fluffy_response.b.txs.size(), fluffy_response.current_blockchain_height); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: txs.size()={}, rsp.current_blockchain_height={}", fluffy_response.b.txs.size(), fluffy_response.current_blockchain_height); post_notify(fluffy_response, context); return 1; @@ -980,7 +980,7 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_notify_new_transactions(int command, NOTIFY_NEW_TRANSACTIONS::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_TRANSACTIONS ({} txes w/ {} blinks)", arg.txs.size(), arg.blinks.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_NEW_TRANSACTIONS ({} txes w/ {} blinks)", arg.txs.size(), arg.blinks.size()); for (const auto &blob: arg.txs) if(OXEN_LOG_ENABLED(info)) { @@ -988,7 +988,7 @@ namespace cryptonote crypto::hash hash; bool ret = cryptonote::parse_and_validate_tx_from_blob(blob, tx, hash); if (ret) - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Including transaction {}", hash); + log::info(log::Cat("net.p2p.msg"), "Including transaction {}", hash); } if(context.m_state != cryptonote_connection_context::state_normal) @@ -1000,7 +1000,7 @@ namespace cryptonote bool syncing = !is_synchronized(); if((syncing && !arg.requested) || m_no_sync) { - oxen::log::debug(logcat, "{}Received new tx while syncing, ignored", context); + log::debug(logcat, "{}Received new tx while syncing, ignored", context); return 1; } @@ -1050,7 +1050,7 @@ namespace cryptonote if (blink_rollback_height > 0) { - oxen::log::debug(logcat, "after handling parsed txes we need to rollback to height: {}", blink_rollback_height); + log::debug(logcat, "after handling parsed txes we need to rollback to height: {}", blink_rollback_height); // We need to clear back to and including block at height blink_rollback_height (so that the // new blockchain "height", i.e. of current top_block_height+1, is blink_rollback_height). auto &blockchain = m_core.get_blockchain_storage(); @@ -1060,13 +1060,13 @@ namespace cryptonote immutable = blockchain.get_immutable_height(); if (immutable >= blink_rollback_height) { - oxen::log::warning(logcat, "blink rollback specified a block at or before the immutable height; we can only roll back to the immutable height."); + log::warning(logcat, "blink rollback specified a block at or before the immutable height; we can only roll back to the immutable height."); blink_rollback_height = immutable + 1; } if (blink_rollback_height < height) m_core.get_blockchain_storage().blink_rollback(blink_rollback_height); else - oxen::log::debug(logcat, "Nothing to roll back"); + log::debug(logcat, "Nothing to roll back"); } } @@ -1083,7 +1083,7 @@ namespace cryptonote // so don't drop the connection). if (!syncing && (!all_okay || bad_blinks)) { - oxen::log::info(logcat, "{} verification(s) failed, dropping connection", (!all_okay && bad_blinks ? "Tx and Blink" : !all_okay ? "Tx" : "Blink")); + log::info(logcat, "{} verification(s) failed, dropping connection", (!all_okay && bad_blinks ? "Tx and Blink" : !all_okay ? "Tx" : "Blink")); drop_connection(context, false, false); } @@ -1093,10 +1093,10 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_request_get_blocks(int command, NOTIFY_REQUEST_GET_BLOCKS::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_BLOCKS ({} blocks)", arg.blocks.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_BLOCKS ({} blocks)", arg.blocks.size()); if (arg.blocks.size() > CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT) { - oxen::log::error(logcat, "Requested blocks count is too big ({}) expected not more than {}", arg.blocks.size(), CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT); + log::error(logcat, "Requested blocks count is too big ({}) expected not more than {}", arg.blocks.size(), CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT); drop_connection(context, false, false); return 1; } @@ -1104,11 +1104,11 @@ namespace cryptonote NOTIFY_RESPONSE_GET_BLOCKS::request rsp; if(!m_core.get_blockchain_storage().handle_get_blocks(arg, rsp)) { - oxen::log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_BLOCKS, dropping connection"); + log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_BLOCKS, dropping connection"); drop_connection(context, false, false); return 1; } - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_GET_BLOCKS: blocks.size()={}, rsp.m_current_blockchain_height={}, missed_ids.size()={}", rsp.blocks.size(), rsp.current_blockchain_height, rsp.missed_ids.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_GET_BLOCKS: blocks.size()={}, rsp.m_current_blockchain_height={}, missed_ids.size()={}", rsp.blocks.size(), rsp.current_blockchain_height, rsp.missed_ids.size()); post_notify(rsp, context); return 1; } @@ -1118,8 +1118,8 @@ namespace cryptonote template int t_cryptonote_protocol_handler::handle_response_get_blocks(int command, NOTIFY_RESPONSE_GET_BLOCKS::request& arg, cryptonote_connection_context& context) { - oxen::log::debug(logcat, "Received NOTIFY_RESPONSE_GET_BLOCKS ({} blocks)", arg.blocks.size()); - oxen::log::debug(oxen::log::Cat("net.p2p.msg"), "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received blocks", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "Received NOTIFY_RESPONSE_GET_BLOCKS ({} blocks)", arg.blocks.size()); + log::debug(log::Cat("net.p2p.msg"), "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received blocks", cryptonote::get_protocol_state_string(context.m_state)); auto request_time = *context.m_last_request_time; context.m_last_request_time.reset(); @@ -1147,11 +1147,11 @@ namespace cryptonote } ++m_sync_spans_downloaded; m_sync_download_objects_size += size; - oxen::log::debug(logcat, "{} downloaded {} bytes worth of blocks", context, size); + log::debug(logcat, "{} downloaded {} bytes worth of blocks", context, size); if(context.m_last_response_height > arg.current_blockchain_height) { - oxen::log::error(logcat, "sent wrong NOTIFY_GET_BLOCKS: arg.m_current_blockchain_height={} < m_last_response_height={}, dropping connection", arg.current_blockchain_height, context.m_last_response_height); + log::error(logcat, "sent wrong NOTIFY_GET_BLOCKS: arg.m_current_blockchain_height={} < m_last_response_height={}, dropping connection", arg.current_blockchain_height, context.m_last_response_height); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1176,14 +1176,14 @@ namespace cryptonote crypto::hash block_hash; if(!parse_and_validate_block_from_blob(block_entry.block, b, block_hash)) { - oxen::log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(block_entry.block)); + log::error(logcat, "sent wrong block: failed to parse and validate block: {}, dropping connection", oxenc::to_hex(block_entry.block)); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } if (b.miner_tx.vin.size() != 1 || !std::holds_alternative(b.miner_tx.vin.front())) { - oxen::log::error(logcat, "sent wrong block: block: miner tx does not have exactly one txin_gen input {}, dropping connection", oxenc::to_hex(block_entry.block)); + log::error(logcat, "sent wrong block: block: miner tx does not have exactly one txin_gen input {}, dropping connection", oxenc::to_hex(block_entry.block)); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1194,14 +1194,14 @@ namespace cryptonote auto req_it = context.m_requested_objects.find(block_hash); if(req_it == context.m_requested_objects.end()) { - oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={} wasn't requested, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block))); + log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={} wasn't requested, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block))); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } if(b.tx_hashes.size() != block_entry.txs.size()) { - oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={}, tx_hashes.size()= {} mismatch with block_complete_entry.m_txs.size()= {}, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block)), b.tx_hashes.size(), block_entry.txs.size()); + log::error(logcat, "sent wrong NOTIFY_RESPONSE_GET_BLOCKS: block with id={}, tx_hashes.size()= {} mismatch with block_complete_entry.m_txs.size()= {}, dropping connection", tools::type_to_hex(get_blob_hash(block_entry.block)), b.tx_hashes.size(), block_entry.txs.size()); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; @@ -1213,19 +1213,19 @@ namespace cryptonote if(!context.m_requested_objects.empty()) { - oxen::log::error(logcat, "{}returned not all requested objects (context.m_requested_objects.size()={}), dropping connection", context, context.m_requested_objects.size()); + log::error(logcat, "{}returned not all requested objects (context.m_requested_objects.size()={}), dropping connection", context, context.m_requested_objects.size()); drop_connection(context, false, false); ++m_sync_bad_spans_downloaded; return 1; } { - oxen::log::debug(globallogcat, fmt::format(fg(fmt::terminal_color::yellow), "{} Got NEW BLOCKS inside of {}: size: {}, blocks: {} - {} (pruning seed {})", context, __FUNCTION__, arg.blocks.size(), start_height, (start_height + arg.blocks.size() - 1), epee::string_tools::to_string_hex(context.m_pruning_seed))); + log::debug(globallogcat, fmt::format(fg(fmt::terminal_color::yellow), "{} Got NEW BLOCKS inside of {}: size: {}, blocks: {} - {} (pruning seed {})", context, __FUNCTION__, arg.blocks.size(), start_height, (start_height + arg.blocks.size() - 1), epee::string_tools::to_string_hex(context.m_pruning_seed))); // add that new span to the block queue seconds_f dt = now - request_time; const double rate = size / dt.count(); - oxen::log::debug(logcat, "{} adding span: {} at height {}, {} seconds, {} kB/s, size now {} MB", context, arg.blocks.size(), start_height, dt.count(), (rate/1024), (m_block_queue.get_data_size() + blocks_size) / 1048576.f); + log::debug(logcat, "{} adding span: {} at height {}, {} seconds, {} kB/s, size now {} MB", context, arg.blocks.size(), start_height, dt.count(), (rate/1024), (m_block_queue.get_data_size() + blocks_size) / 1048576.f); m_block_queue.add_blocks(start_height, arg.blocks, context.m_connection_id, rate, blocks_size); const crypto::hash last_block_hash = cryptonote::get_block_hash(b); @@ -1299,11 +1299,11 @@ namespace cryptonote const std::unique_lock sync{m_sync_lock, std::try_to_lock}; if (!sync) { - oxen::log::debug(logcat, "{}Failed to lock m_sync_lock, going back to download", context); + log::debug(logcat, "{}Failed to lock m_sync_lock, going back to download", context); goto skip; } - oxen::log::debug(logcat, "{} lock m_sync_lock, adding blocks to chain...", context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "adding blocks", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{} lock m_sync_lock, adding blocks to chain...", context); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "adding blocks", cryptonote::get_protocol_state_string(context.m_state)); { m_core.pause_mine(); @@ -1322,38 +1322,38 @@ namespace cryptonote boost::uuids::uuid span_connection_id; if (!m_block_queue.get_next_span(start_height, blocks, span_connection_id)) { - oxen::log::debug(logcat, "{} no next span found, going back to download", context); + log::debug(logcat, "{} no next span found, going back to download", context); break; } if (blocks.empty()) { - oxen::log::error(logcat, "{}Next span has no blocks", context); + log::error(logcat, "{}Next span has no blocks", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } - oxen::log::debug(logcat, "{} next span in the queue has blocks {}-{}, we need {}", context, start_height, (start_height + blocks.size() - 1), previous_height); + log::debug(logcat, "{} next span in the queue has blocks {}-{}, we need {}", context, start_height, (start_height + blocks.size() - 1), previous_height); block new_block; crypto::hash last_block_hash; if (!parse_and_validate_block_from_blob(blocks.back().block, new_block, last_block_hash)) { - oxen::log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); + log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } if (m_core.have_block(last_block_hash)) { const uint64_t subchain_height = start_height + blocks.size(); - oxen::log::debug(logcat, "{}{} - {}, blockchain height {}", context, "These are old blocks, ignoring: blocks ", start_height, (subchain_height-1), m_core.get_current_blockchain_height()); + log::debug(logcat, "{}{} - {}, blockchain height {}", context, "These are old blocks, ignoring: blocks ", start_height, (subchain_height-1), m_core.get_current_blockchain_height()); m_block_queue.remove_spans(span_connection_id, start_height); ++m_sync_old_spans_downloaded; continue; } if (!parse_and_validate_block_from_blob(blocks.front().block, new_block)) { - oxen::log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); + log::error(logcat, "{}Failed to parse block, but it should already have been parsed", context); m_block_queue.remove_spans(span_connection_id, start_height); continue; } @@ -1376,20 +1376,20 @@ namespace cryptonote { if (should_drop_connection(context, get_next_needed_pruning_stripe().first)) { - oxen::log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - dropping connection", context); + log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - dropping connection", context); if (!context.m_is_income) m_p2p->add_used_stripe_peer(context); drop_connection(context, false, true); return 1; } - oxen::log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - back to download", context); + log::debug(logcat, "{}Got block with unknown parent which was not requested, but peer does not have that block - back to download", context); goto skip; } // this can happen if a connection was sicced onto a late span, if it did not have those blocks, // since we don't know that at the sic time - oxen::log::error(logcat, "Got block with unknown parent which was not requested - querying block hashes"); + log::error(logcat, "Got block with unknown parent which was not requested - querying block hashes"); m_block_queue.remove_spans(span_connection_id, start_height); context.m_needed_objects.clear(); context.m_last_response_height = 0; @@ -1397,7 +1397,7 @@ namespace cryptonote } // parent was requested, so we wait for it to be retrieved - oxen::log::debug(logcat, "{} parent was requested, we'll get back to it", context); + log::debug(logcat, "{} parent was requested, we'll get back to it", context); break; } @@ -1407,13 +1407,13 @@ namespace cryptonote { starting = false; auto elapsed = std::chrono::steady_clock::now() - m_last_add_end_time; - oxen::log::debug(logcat, "Restarting adding block after idle for {} seconds", tools::friendly_duration(elapsed)); + log::debug(logcat, "Restarting adding block after idle for {} seconds", tools::friendly_duration(elapsed)); } std::vector pblocks; if (!m_core.prepare_handle_incoming_blocks(blocks, pblocks)) { - oxen::log::error(logcat, "Failure in prepare_handle_incoming_blocks"); + log::error(logcat, "Failure in prepare_handle_incoming_blocks"); return 1; } @@ -1422,7 +1422,7 @@ namespace cryptonote OXEN_DEFER { if (!m_core.cleanup_handle_incoming_blocks()) - oxen::log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); + log::warning(logcat, "Failure in cleanup_handle_incoming_blocks"); // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it if (remove_spans) @@ -1431,7 +1431,7 @@ namespace cryptonote if (!pblocks.empty() && pblocks.size() != blocks.size()) { - oxen::log::error(logcat, "Internal error: blocks.size() != block_entry.txs.size()"); + log::error(logcat, "Internal error: blocks.size() != block_entry.txs.size()"); return 1; } @@ -1455,11 +1455,11 @@ namespace cryptonote if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool{ cryptonote::transaction tx; parse_and_validate_tx_from_blob(block_entry.txs[i], tx); // must succeed if we got here - oxen::log::error(logcat, "transaction verification failed on NOTIFY_RESPONSE_GET_BLOCKS, tx_id = {}, dropping connection", tools::type_to_hex(cryptonote::get_transaction_hash(tx))); + log::error(logcat, "transaction verification failed on NOTIFY_RESPONSE_GET_BLOCKS, tx_id = {}, dropping connection", tools::type_to_hex(cryptonote::get_transaction_hash(tx))); drop_connection(context, false, true); return 1; })) - oxen::log::error(logcat, "span connection id not found"); + log::error(logcat, "span connection id not found"); remove_spans = true; return 1; @@ -1480,7 +1480,7 @@ namespace cryptonote if (!t_serializable_object_from_blob(checkpoint_allocated_on_stack_, block_entry.checkpoint)) { - oxen::log::error(logcat, "Checkpoint blob available but failed to parse"); + log::error(logcat, "Checkpoint blob available but failed to parse"); return false; } @@ -1502,11 +1502,11 @@ namespace cryptonote ? "Block verification failed, dropping connection" : "Block received at sync phase was marked as orphaned, dropping connection"; - oxen::log::info(logcat, err_msg); + log::info(logcat, err_msg); drop_connection(context, true, true); return 1; })) - oxen::log::error(logcat, "span connection id not found"); + log::error(logcat, "span connection id not found"); remove_spans = true; return 1; @@ -1518,7 +1518,7 @@ namespace cryptonote } // each download block remove_spans = true; - oxen::log::debug(logcat, "{}Block process time ({} blocks, {} txs): {} ({}/{})", + log::debug(logcat, "{}Block process time ({} blocks, {} txs): {} ({}/{})", context, blocks.size(), num_txs, @@ -1561,14 +1561,14 @@ namespace cryptonote + std::to_string(previous_stripe) + " -> " + std::to_string(current_stripe); if (OXEN_LOG_ENABLED(debug)) timing_message += std::string(": ") + m_block_queue.get_overview(current_blockchain_height); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {}/{} {} {}", current_blockchain_height, target_blockchain_height, progress_message, timing_message)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {}/{} {} {}", current_blockchain_height, target_blockchain_height, progress_message, timing_message)); if (previous_stripe != current_stripe) notify_new_stripe(context, current_stripe); } } } - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "stopping adding blocks", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "stopping adding blocks", cryptonote::get_protocol_state_string(context.m_state)); if (should_download_next_span(context, false)) { @@ -1588,7 +1588,7 @@ namespace cryptonote skip: if (!request_missing_objects(context, true, force_next_span)) { - oxen::log::error(logcat, "Failed to request missing objects, dropping connection"); + log::error(logcat, "Failed to request missing objects, dropping connection"); drop_connection(context, false, false); return 1; } @@ -1608,10 +1608,10 @@ skip: if (stripe && peer_stripe && peer_stripe != stripe) return true; context.m_state = cryptonote_connection_context::state_synchronizing; - oxen::log::debug(logcat, "requesting callback"); + log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting callback", cryptonote::get_protocol_state_string(context.m_state)); } return true; }); @@ -1622,11 +1622,11 @@ skip: template int t_cryptonote_protocol_handler::handle_request_get_txs(int command, NOTIFY_REQUEST_GET_TXS::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_TXS ({} txs)", arg.txs.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_GET_TXS ({} txs)", arg.txs.size()); if (arg.txs.size() > CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT) { - oxen::log::error(logcat, "Requested txs count is too big ({}) expected not mroe than {}", arg.txs.size(), CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); + log::error(logcat, "Requested txs count is too big ({}) expected not mroe than {}", arg.txs.size(), CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); drop_connection(context, false, false); return 1; } @@ -1635,11 +1635,11 @@ skip: rsp.requested = true; if(!m_core.get_blockchain_storage().handle_get_txs(arg, rsp)) { - oxen::log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_TXS, dropping connection"); + log::error(logcat, "failed to handle request NOTIFY_REQUEST_GET_TXS, dropping connection"); drop_connection(context, false, false); return 1; } - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_NEW_TRANSACTIONS: requested=true, txs[{}], blinks[{}]", rsp.txs.size(), rsp.blinks.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_NEW_TRANSACTIONS: requested=true, txs[{}], blinks[{}]", rsp.txs.size(), rsp.blinks.size()); post_notify(rsp, context); return 1; } @@ -1656,7 +1656,7 @@ skip: template bool t_cryptonote_protocol_handler::kick_idle_peers() { - oxen::log::trace(logcat, "Checking for idle peers..."); + log::trace(logcat, "Checking for idle peers..."); m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool { if (context.m_state == cryptonote_connection_context::state_synchronizing && context.m_last_request_time) @@ -1664,8 +1664,8 @@ skip: const auto dt = std::chrono::steady_clock::now() - *context.m_last_request_time; if (dt > IDLE_PEER_KICK_TIME) { - oxen::log::info(logcat, "{} kicking idle peer, last update {} seconds ago", context, seconds_f{dt}.count()); - oxen::log::debug(logcat, "requesting callback"); + log::info(logcat, "{} kicking idle peer, last update {} seconds ago", context, seconds_f{dt}.count()); + log::debug(logcat, "requesting callback"); context.m_last_request_time.reset(); context.m_state = cryptonote_connection_context::state_standby; // we'll go back to adding, then (if we can't), download ++context.m_callback_request_count; @@ -1685,7 +1685,7 @@ skip: if (target > height) // if we're not synced yet, don't do it return true; - oxen::log::trace(logcat, "Checking for outgoing syncing peers..."); + log::trace(logcat, "Checking for outgoing syncing peers..."); unsigned n_syncing = 0, n_synced = 0; boost::uuids::uuid last_synced_peer_id(boost::uuids::nil_uuid()); m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id)->bool @@ -1702,17 +1702,17 @@ skip: } return true; }); - oxen::log::trace(logcat, "{} syncing, {} synced", n_syncing, n_synced); + log::trace(logcat, "{} syncing, {} synced", n_syncing, n_synced); // if we're at max out peers, and not enough are syncing if (n_synced + n_syncing >= m_max_out_peers && n_syncing < p2p::DEFAULT_SYNC_SEARCH_CONNECTIONS_COUNT && last_synced_peer_id != boost::uuids::nil_uuid()) { if (!m_p2p->for_connection(last_synced_peer_id, [&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id)->bool{ - oxen::log::debug(logcat, "{}dropping synced peer, {} syncing, {} synced", ctx, n_syncing, n_synced); + log::debug(logcat, "{}dropping synced peer, {} syncing, {} synced", ctx, n_syncing, n_synced); drop_connection(ctx, false, false); return true; })) - oxen::log::debug(logcat, "Failed to find peer we wanted to drop"); + log::debug(logcat, "Failed to find peer we wanted to drop"); } return true; @@ -1725,7 +1725,7 @@ skip: { if (context.m_state == cryptonote_connection_context::state_standby) { - oxen::log::debug(logcat, "requesting callback"); + log::debug(logcat, "requesting callback"); ++context.m_callback_request_count; m_p2p->request_callback(context); } @@ -1737,15 +1737,15 @@ skip: template int t_cryptonote_protocol_handler::handle_request_chain(int command, NOTIFY_REQUEST_CHAIN::request& arg, cryptonote_connection_context& context) { - oxen::log::debug(logcat, "Received NOTIFY_REQUEST_CHAIN ({} blocks)", arg.block_ids.size()); + log::debug(logcat, "Received NOTIFY_REQUEST_CHAIN ({} blocks)", arg.block_ids.size()); NOTIFY_RESPONSE_CHAIN_ENTRY::request r; if(!m_core.find_blockchain_supplement(arg.block_ids, r)) { - oxen::log::error(logcat, "Failed to handle NOTIFY_REQUEST_CHAIN."); + log::error(logcat, "Failed to handle NOTIFY_REQUEST_CHAIN."); drop_connection(context, false, false); return 1; } - oxen::log::debug(logcat, "-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height={}, m_total_height={}, m_block_ids.size()={}", r.start_height, r.total_height, r.m_block_ids.size()); + log::debug(logcat, "-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height={}, m_total_height={}, m_block_ids.size()={}", r.start_height, r.total_height, r.m_block_ids.size()); post_notify(r, context); return 1; } @@ -1767,7 +1767,7 @@ skip: { if (!m_block_queue.has_next_span(blockchain_height, filled, request_time, connection_id)) { - oxen::log::debug(logcat, "{} we should download it as no peer reserved it", context); + log::debug(logcat, "{} we should download it as no peer reserved it", context); return true; } if (!filled) @@ -1775,7 +1775,7 @@ skip: const auto dt = now - request_time; if (dt >= REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD) { - oxen::log::debug(logcat, "{} we should download it as it's not been received yet after {}", context, seconds_f{dt}.count()); + log::debug(logcat, "{} we should download it as it's not been received yet after {}", context, seconds_f{dt}.count()); return true; } @@ -1791,7 +1791,7 @@ skip: const bool stalled = last_activity > LAST_ACTIVITY_STALL_THRESHOLD; if (stalled) { - oxen::log::debug(logcat, "{} we should download it as the downloading peer is stalling for {} seconds", context, seconds_f{last_activity}.count()); + log::debug(logcat, "{} we should download it as the downloading peer is stalling for {} seconds", context, seconds_f{last_activity}.count()); download = true; return true; } @@ -1819,7 +1819,7 @@ skip: } if (dl_speed * .8f > ctx.m_current_speed_down * multiplier) { - oxen::log::debug(logcat, "{} we should download it as we are substantially faster ({} vs {}, multiplier {} after {} seconds)", context, dl_speed, ctx.m_current_speed_down, multiplier, seconds_f{dt}.count()); + log::debug(logcat, "{} we should download it as we are substantially faster ({} vs {}, multiplier {} after {} seconds)", context, dl_speed, ctx.m_current_speed_down, multiplier, seconds_f{dt}.count()); download = true; return true; } @@ -1831,7 +1831,7 @@ skip: } else { - oxen::log::warning(logcat, "{} we should download it as the downloading peer is unexpectedly not known to us", context); + log::warning(logcat, "{} we should download it as the downloading peer is unexpectedly not known to us", context); return true; } } @@ -1846,19 +1846,19 @@ skip: { if (context.m_anchor) { - oxen::log::debug(logcat, "{}This is an anchor peer, not dropping", context); + log::debug(logcat, "{}This is an anchor peer, not dropping", context); return false; } if (context.m_pruning_seed == 0) { - oxen::log::debug(logcat, "{}This peer is not striped, not dropping", context); + log::debug(logcat, "{}This peer is not striped, not dropping", context); return false; } const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed); if (next_stripe == peer_stripe) { - oxen::log::debug(logcat, "{}This peer has needed stripe {}, not dropping", context, peer_stripe); + log::debug(logcat, "{}This peer has needed stripe {}, not dropping", context, peer_stripe); return false; } @@ -1867,7 +1867,7 @@ skip: const uint64_t next_available_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1; if (tools::has_unpruned_block(next_available_block_height, context.m_remote_blockchain_height, context.m_pruning_seed)) { - oxen::log::debug(logcat, "{}This peer has unpruned next block at height {}, not dropping", context, next_available_block_height); + log::debug(logcat, "{}This peer has unpruned next block at height {}, not dropping", context, next_available_block_height); return false; } } @@ -1885,11 +1885,11 @@ skip: const uint32_t distance = (peer_stripe + (1<= m_max_out_peers && n_peers_on_next_stripe == 0) || (distance > 1 && n_peers_on_next_stripe <= 2) || distance > 2) { - oxen::log::debug(logcat, "{}we want seed {}, and either {} is at max out peers ({}) or distance {} from {} to {} is too large and we have only {} peers on next seed, dropping connection to make space", context, next_stripe, n_out_peers, m_max_out_peers, distance, next_stripe, peer_stripe, n_peers_on_next_stripe); + log::debug(logcat, "{}we want seed {}, and either {} is at max out peers ({}) or distance {} from {} to {} is too large and we have only {} peers on next seed, dropping connection to make space", context, next_stripe, n_out_peers, m_max_out_peers, distance, next_stripe, peer_stripe, n_peers_on_next_stripe); return true; } } - oxen::log::debug(logcat, "{}End of checks, not dropping", context); + log::debug(logcat, "{}End of checks, not dropping", context); return false; } //------------------------------------------------------------------------------------------------------------------------ @@ -1908,7 +1908,7 @@ skip: } if (skip > 0) { - oxen::log::debug(logcat, "{}skipping {}/{} blocks", context, skip, context.m_needed_objects.size()); + log::debug(logcat, "{}skipping {}/{} blocks", context, skip, context.m_needed_objects.size()); context.m_needed_objects = std::vector(context.m_needed_objects.begin() + skip, context.m_needed_objects.end()); } } @@ -1956,17 +1956,17 @@ skip: return false; // drop outgoing connections } - oxen::log::debug(logcat, "{}proceed {} (queue {}, stripe {}/{}), {}-{} needed, bc add stripe {}, we have {}), bc_height {}", context, proceed, queue_proceed, stripe_proceed_main, stripe_proceed_secondary, next_needed_pruning_stripe.first, next_needed_pruning_stripe.second, add_stripe, peer_stripe, bc_height); - oxen::log::debug(logcat, "{} - next_block_height {}, seed {}, next_needed_height {}", context, next_block_height, epee::string_tools::to_string_hex(context.m_pruning_seed), next_needed_height); - oxen::log::debug(logcat, "{} - last_response_height {}, m_needed_objects size {}", context, context.m_last_response_height, context.m_needed_objects.size()); + log::debug(logcat, "{}proceed {} (queue {}, stripe {}/{}), {}-{} needed, bc add stripe {}, we have {}), bc_height {}", context, proceed, queue_proceed, stripe_proceed_main, stripe_proceed_secondary, next_needed_pruning_stripe.first, next_needed_pruning_stripe.second, add_stripe, peer_stripe, bc_height); + log::debug(logcat, "{} - next_block_height {}, seed {}, next_needed_height {}", context, next_block_height, epee::string_tools::to_string_hex(context.m_pruning_seed), next_needed_height); + log::debug(logcat, "{} - last_response_height {}, m_needed_objects size {}", context, context.m_last_response_height, context.m_needed_objects.size()); // if we're waiting for next span, try to get it before unblocking threads below, // or a runaway downloading of future spans might happen if (stripe_proceed_main && should_download_next_span(context, true)) { - oxen::log::debug(logcat, "{} we should try for that next span too, we think we could get it faster, resuming", context); + log::debug(logcat, "{} we should try for that next span too, we think we could get it faster, resuming", context); force_next_span = true; - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); break; } @@ -1974,8 +1974,8 @@ skip: { if (context.m_state != cryptonote_connection_context::state_standby) { - oxen::log::debug(logcat, "{}{} and {}, resuming", context, "Block queue is ", nspans, size); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}{} and {}, resuming", context, "Block queue is ", nspans, size); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); } break; } @@ -1990,8 +1990,8 @@ skip: boost::uuids::uuid connection_id; if (m_block_queue.has_next_span(m_core.get_current_blockchain_height(), filled, time, connection_id) && filled) { - oxen::log::debug(logcat, "{}No other thread is adding blocks, and next span needed is ready, resuming", context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}No other thread is adding blocks, and next span needed is ready, resuming", context); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "resuming", cryptonote::get_protocol_state_string(context.m_state)); context.m_state = cryptonote_connection_context::state_standby; ++context.m_callback_request_count; m_p2p->request_callback(context); @@ -2007,7 +2007,7 @@ skip: auto ns = std::chrono::steady_clock::now() - m_last_add_end_time; if (ns >= DROP_ON_SYNC_WEDGE_THRESHOLD) { - oxen::log::debug(logcat, "{}Block addition seems to have wedged, dropping connection", context); + log::debug(logcat, "{}Block addition seems to have wedged, dropping connection", context); return false; } } @@ -2017,11 +2017,11 @@ skip: if (context.m_state != cryptonote_connection_context::state_standby) { if (!queue_proceed) - oxen::log::debug(logcat, "{}{} and {}, pausing", context, "Block queue is ", nspans, size); + log::debug(logcat, "{}{} and {}, pausing", context, "Block queue is ", nspans, size); else if (!stripe_proceed_main && !stripe_proceed_secondary) - oxen::log::debug(logcat, "{}We do not have the stripe required to download another block, pausing", context); + log::debug(logcat, "{}We do not have the stripe required to download another block, pausing", context); context.m_state = cryptonote_connection_context::state_standby; - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "pausing", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "pausing", cryptonote::get_protocol_state_string(context.m_state)); } return true; @@ -2029,7 +2029,7 @@ skip: context.m_state = cryptonote_connection_context::state_synchronizing; } - oxen::log::debug(logcat, "{} request_missing_objects: check {}, force_next_span {}, m_needed_objects {} lrh {}, chain {}, pruning seed {}", context, check_having_blocks, force_next_span, context.m_needed_objects.size(), context.m_last_response_height, m_core.get_current_blockchain_height(), epee::string_tools::to_string_hex(context.m_pruning_seed)); + log::debug(logcat, "{} request_missing_objects: check {}, force_next_span {}, m_needed_objects {} lrh {}, chain {}, pruning seed {}", context, check_having_blocks, force_next_span, context.m_needed_objects.size(), context.m_last_response_height, m_core.get_current_blockchain_height(), epee::string_tools::to_string_hex(context.m_pruning_seed)); if(context.m_needed_objects.size() || force_next_span) { //we know objects that we need, request this objects @@ -2059,10 +2059,10 @@ skip: } if (span.second == 0) { - oxen::log::debug(logcat, "{} span size is 0", context); + log::debug(logcat, "{} span size is 0", context); if (context.m_last_response_height + 1 < context.m_needed_objects.size()) { - oxen::log::error(logcat, "{} ERROR: inconsistent context: lrh {}, nos {}", context, context.m_last_response_height, context.m_needed_objects.size()); + log::error(logcat, "{} ERROR: inconsistent context: lrh {}, nos {}", context, context.m_last_response_height, context.m_needed_objects.size()); context.m_needed_objects.clear(); context.m_last_response_height = 0; goto skip; @@ -2071,19 +2071,19 @@ skip: const uint64_t first_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1; span = m_block_queue.reserve_span(first_block_height, context.m_last_response_height, count_limit, context.m_connection_id, context.m_pruning_seed, context.m_remote_blockchain_height, context.m_needed_objects); - oxen::log::debug(logcat, "{} span from {}: {}/{}", context, first_block_height, span.first, span.second); + log::debug(logcat, "{} span from {}: {}/{}", context, first_block_height, span.first, span.second); if (span.second > 0) { const uint32_t stripe = tools::get_pruning_stripe(span.first, context.m_remote_blockchain_height, PRUNING_LOG_STRIPES); if (context.m_pruning_seed && stripe != tools::get_pruning_stripe(context.m_pruning_seed)) { - oxen::log::debug(logcat, "{} starting early on next seed ({} with stripe {}, context seed {})", context, span.first, stripe, epee::string_tools::to_string_hex(context.m_pruning_seed)); + log::debug(logcat, "{} starting early on next seed ({} with stripe {}, context seed {})", context, span.first, stripe, epee::string_tools::to_string_hex(context.m_pruning_seed)); } } } if (span.second == 0 && !force_next_span) { - oxen::log::debug(logcat, "{} still no span reserved, we may be in the corner case of next span scheduled and everything else scheduled/filled", context); + log::debug(logcat, "{} still no span reserved, we may be in the corner case of next span scheduled and everything else scheduled/filled", context); std::vector hashes; boost::uuids::uuid span_connection_id; span = m_block_queue.get_next_span_if_scheduled(hashes, span_connection_id); @@ -2104,7 +2104,7 @@ skip: } } } - oxen::log::debug(logcat, "{} span: {}/{} ({} - {})", context, span.first, span.second, span.first, (span.first + span.second - 1)); + log::debug(logcat, "{} span: {}/{} ({} - {})", context, span.first, span.second, span.first, (span.first + span.second - 1)); if (span.second > 0) { if (!is_next) @@ -2113,14 +2113,14 @@ skip: uint64_t skip = span.first - first_context_block_height; if (skip > context.m_needed_objects.size()) { - oxen::log::error(logcat, "ERROR: skip {}, m_needed_objects {}, first_context_block_height{}", skip, context.m_needed_objects.size(), first_context_block_height); + log::error(logcat, "ERROR: skip {}, m_needed_objects {}, first_context_block_height{}", skip, context.m_needed_objects.size(), first_context_block_height); return false; } if (skip > 0) context.m_needed_objects = std::vector(context.m_needed_objects.begin() + skip, context.m_needed_objects.end()); if (context.m_needed_objects.size() < span.second) { - oxen::log::error(logcat, "ERROR: span {}/{}, m_needed_objects {}", span.first, span.second, context.m_needed_objects.size()); + log::error(logcat, "ERROR: span {}/{}, m_needed_objects {}", span.first, span.second, context.m_needed_objects.size()); return false; } @@ -2134,10 +2134,10 @@ skip: } context.m_last_request_time = std::chrono::steady_clock::now(); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()={}, requested blocks count={} / {} from {}, first hash {}", req.blocks.size(), count, count_limit, span.first, req.blocks.front()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()={}, requested blocks count={} / {} from {}, first hash {}", req.blocks.size(), count, count_limit, span.first, req.blocks.front()); post_notify(req, context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting objects", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting objects", cryptonote::get_protocol_state_string(context.m_state)); return true; } @@ -2149,7 +2149,7 @@ skip: { // at this point, we have to either close the connection, or start getting blocks past the // current point, or become dormant - oxen::log::debug(logcat, "{}this peer is pruned at seed {}, next stripe needed is {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), next_stripe); + log::debug(logcat, "{}this peer is pruned at seed {}, next stripe needed is {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), next_stripe); if (!context.m_is_income) { if (should_drop_connection(context, next_stripe)) @@ -2160,7 +2160,7 @@ skip: } // we'll get back stuck waiting for the go ahead context.m_state = cryptonote_connection_context::state_normal; - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "Nothing to do for now, switching to normal state", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "Nothing to do for now, switching to normal state", cryptonote::get_protocol_state_string(context.m_state)); return true; } } @@ -2182,8 +2182,8 @@ skip: bool filled = false; if (m_block_queue.get_next_span(start_height, blocks, span_connection_id, filled) && filled) { - oxen::log::debug(logcat, "{}No other thread is adding blocks, resuming", context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "will try to add blocks next", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}No other thread is adding blocks, resuming", context); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "will try to add blocks next", cryptonote::get_protocol_state_string(context.m_state)); context.m_state = cryptonote_connection_context::state_standby; ++context.m_callback_request_count; m_p2p->request_callback(context); @@ -2207,9 +2207,9 @@ skip: } context.m_last_request_time = std::chrono::steady_clock::now(); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, start_from_current_chain {}", r.block_ids.size(), start_from_current_chain); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()={}, start_from_current_chain {}", r.block_ids.size(), start_from_current_chain); post_notify(r, context); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting chain", cryptonote::get_protocol_state_string(context.m_state)); }else { CHECK_AND_ASSERT_MES(context.m_last_response_height == context.m_remote_blockchain_height-1 @@ -2226,13 +2226,13 @@ skip: { if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height()) { - oxen::log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "SYNCHRONIZED OK")); + log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "SYNCHRONIZED OK")); on_connection_synchronized(); } } else { - oxen::log::info(logcat, "{} we've reached this peer's blockchain height", context); + log::info(logcat, "{} we've reached this peer's blockchain height", context); } } return true; @@ -2255,10 +2255,10 @@ skip: if (synced_seconds == 0s) synced_seconds = 1s; float blocks_per_second = synced_blocks / (float)synced_seconds.count(); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {} blocks in {} ({} blocks per second)", synced_blocks, tools::get_human_readable_timespan(synced_seconds), blocks_per_second)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {} blocks in {} ({} blocks per second)", synced_blocks, tools::get_human_readable_timespan(synced_seconds), blocks_per_second)); } } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ You are now synchronized with the network. You may now start oxen-wallet-cli.\n\ \n\ Use the \"help\" command to see the list of available commands.\n\ @@ -2266,7 +2266,7 @@ Use the \"help\" command to see the list of available commands.\n\ if (OXEN_LOG_ENABLED(info)) { const std::chrono::duration sync_time{std::chrono::steady_clock::now() - m_sync_timer}; - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Sync time: {:.0f} min, {} + {} MB downloaded, {}% old spans, {}% bad spans", sync_time.count()/1e9/60, + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Sync time: {:.0f} min, {} + {} MB downloaded, {}% old spans, {}% bad spans", sync_time.count()/1e9/60, (10 * m_sync_download_objects_size / 1024 / 1024) / 10.f, (10 * m_sync_download_chain_size / 1024 / 1024) / 10.f, 100.0f * m_sync_old_spans_downloaded / m_sync_spans_downloaded, @@ -2294,8 +2294,8 @@ Use the \"help\" command to see the list of available commands.\n\ template int t_cryptonote_protocol_handler::handle_response_chain_entry(int command, NOTIFY_RESPONSE_CHAIN_ENTRY::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()={}, m_start_height={}, m_total_height={}", arg.m_block_ids.size(), arg.start_height, arg.total_height); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received chain", cryptonote::get_protocol_state_string(context.m_state)); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()={}, m_start_height={}, m_total_height={}", arg.m_block_ids.size(), arg.start_height, arg.total_height); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "received chain", cryptonote::get_protocol_state_string(context.m_state)); context.m_last_request_time.reset(); @@ -2303,21 +2303,21 @@ Use the \"help\" command to see the list of available commands.\n\ if(!arg.m_block_ids.size()) { - oxen::log::error(logcat, "sent empty m_block_ids, dropping connection"); + log::error(logcat, "sent empty m_block_ids, dropping connection"); drop_connection(context, true, false); return 1; } if (arg.total_height < arg.m_block_ids.size() || arg.start_height > arg.total_height - arg.m_block_ids.size()) { - oxen::log::error(logcat, "sent invalid start/nblocks/height, dropping connection"); + log::error(logcat, "sent invalid start/nblocks/height, dropping connection"); drop_connection(context, true, false); return 1; } - oxen::log::debug(logcat, "{}first block hash {}, last {}", context, arg.m_block_ids.front(), arg.m_block_ids.back()); + log::debug(logcat, "{}first block hash {}, last {}", context, arg.m_block_ids.front(), arg.m_block_ids.back()); if (arg.total_height >= MAX_BLOCK_NUMBER || arg.m_block_ids.size() >= MAX_BLOCK_NUMBER) { - oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with total_height={} and block_ids={}", arg.total_height, arg.m_block_ids.size()); + log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with total_height={} and block_ids={}", arg.total_height, arg.m_block_ids.size()); drop_connection(context, false, false); return 1; } @@ -2325,7 +2325,7 @@ Use the \"help\" command to see the list of available commands.\n\ context.m_last_response_height = arg.start_height + arg.m_block_ids.size()-1; if(context.m_last_response_height > context.m_remote_blockchain_height) { - oxen::log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with m_total_height={}, m_start_height= {}, m_block_ids.size()={}", arg.total_height, arg.start_height, arg.m_block_ids.size()); + log::error(logcat, "sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with m_total_height={}, m_start_height= {}, m_block_ids.size()={}", arg.total_height, arg.start_height, arg.m_block_ids.size()); drop_connection(context, false, false); return 1; } @@ -2333,7 +2333,7 @@ Use the \"help\" command to see the list of available commands.\n\ uint64_t n_use_blocks = m_core.prevalidate_block_hashes(arg.start_height, arg.m_block_ids); if (n_use_blocks + HASH_OF_HASHES_STEP <= arg.m_block_ids.size()) { - oxen::log::error(logcat, "Most blocks are invalid, dropping connection"); + log::error(logcat, "Most blocks are invalid, dropping connection"); drop_connection(context, true, false); return 1; } @@ -2350,7 +2350,7 @@ Use the \"help\" command to see the list of available commands.\n\ if (!request_missing_objects(context, false)) { - oxen::log::error(logcat, "Failed to request missing objects, dropping connection"); + log::error(logcat, "Failed to request missing objects, dropping connection"); drop_connection(context, false, false); return 1; } @@ -2365,12 +2365,12 @@ Use the \"help\" command to see the list of available commands.\n\ template int t_cryptonote_protocol_handler::handle_request_block_blinks(int command, NOTIFY_REQUEST_BLOCK_BLINKS::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_BLOCK_BLINKS: heights.size()={}", arg.heights.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_REQUEST_BLOCK_BLINKS: heights.size()={}", arg.heights.size()); NOTIFY_RESPONSE_BLOCK_BLINKS::request r; r.txs = m_core.get_pool().get_mined_blinks({arg.heights.begin(), arg.heights.end()}); - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", r.txs.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", r.txs.size()); post_notify(r, context); return 1; } @@ -2378,12 +2378,12 @@ Use the \"help\" command to see the list of available commands.\n\ template int t_cryptonote_protocol_handler::handle_response_block_blinks(int command, NOTIFY_RESPONSE_BLOCK_BLINKS::request& arg, cryptonote_connection_context& context) { - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", arg.txs.size()); + log::info(log::Cat("net.p2p.msg"), "Received NOTIFY_RESPONSE_BLOCK_BLINKS: txs.size()={}", arg.txs.size()); m_core.get_pool().keep_missing_blinks(arg.txs); if (arg.txs.empty()) { - oxen::log::debug(logcat, "NOTIFY_RESPONSE_BLOCKS_BLINKS included only blink txes we already knew about"); + log::debug(logcat, "NOTIFY_RESPONSE_BLOCKS_BLINKS included only blink txes we already knew about"); return 1; } @@ -2398,10 +2398,10 @@ Use the \"help\" command to see the list of available commands.\n\ arg.txs.resize(arg.txs.size() - CURRENCY_PROTOCOL_MAX_TXS_REQUEST_COUNT); } - oxen::log::info(oxen::log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_TXS: requesting for tx & blink data, txs.size()={}", req.txs.size()); + log::info(log::Cat("net.p2p.msg"), "-->>NOTIFY_REQUEST_GET_TXS: requesting for tx & blink data, txs.size()={}", req.txs.size()); post_notify(req, context); } - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting missing blink txs", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "requesting missing blink txs", cryptonote::get_protocol_state_string(context.m_state)); return 1; } //------------------------------------------------------------------------------------------------------------------------ @@ -2414,7 +2414,7 @@ Use the \"help\" command to see the list of available commands.\n\ { if (peer_id && exclude_context.m_connection_id != context.m_connection_id && context.m_remote_address.get_zone() == epee::net_utils::zone::public_) { - oxen::log::debug(logcat, "{}PEER FLUFFY BLOCKS - RELAYING THIN/COMPACT WHATEVER BLOCK", context); + log::debug(logcat, "{}PEER FLUFFY BLOCKS - RELAYING THIN/COMPACT WHATEVER BLOCK", context); fluffyConnections.push_back({context.m_remote_address.get_zone(), context.m_connection_id}); } return true; @@ -2432,7 +2432,7 @@ Use the \"help\" command to see the list of available commands.\n\ // relay_block is only meant to send the header, tx blobs should be // requested subsequently in handle notify fluffy transactions - oxen::log::debug(logcat, "relay_block called with argument that contains TX blobs, this is the non-expected case"); + log::debug(logcat, "relay_block called with argument that contains TX blobs, this is the non-expected case"); NOTIFY_NEW_FLUFFY_BLOCK::request arg_without_tx_blobs = {}; arg_without_tx_blobs.current_blockchain_height = arg.current_blockchain_height; arg_without_tx_blobs.b.block = arg.b.block; @@ -2551,7 +2551,7 @@ Use the \"help\" command to see the list of available commands.\n\ const bool use_next = (n_next > m_max_out_peers / 2 && n_subsequent <= 1) || (n_next > 2 && n_subsequent == 0); const uint32_t ret_stripe = use_next ? subsequent_pruning_stripe: next_pruning_stripe; const std::string po = get_peers_overview(); - oxen::log::debug(oxen::log::Cat(po), "get_next_needed_pruning_stripe: want height {} ({} from blockchain, {} from block queue), stripe {} ({}/{} on it and {} on {}, {} others) -> {} (+{}), current peers {}", want_height, want_height_from_blockchain, want_height_from_block_queue, next_pruning_stripe, n_next, m_max_out_peers, n_subsequent, subsequent_pruning_stripe, n_others, ret_stripe, (ret_stripe - next_pruning_stripe + (1 << PRUNING_LOG_STRIPES)) % (1 << PRUNING_LOG_STRIPES), po); + log::debug(log::Cat(po), "get_next_needed_pruning_stripe: want height {} ({} from blockchain, {} from block queue), stripe {} ({}/{} on it and {} on {}, {} others) -> {} (+{}), current peers {}", want_height, want_height_from_blockchain, want_height_from_block_queue, next_pruning_stripe, n_next, m_max_out_peers, n_subsequent, subsequent_pruning_stripe, n_others, ret_stripe, (ret_stripe - next_pruning_stripe + (1 << PRUNING_LOG_STRIPES)) % (1 << PRUNING_LOG_STRIPES), po); return std::make_pair(next_pruning_stripe, ret_stripe); } //------------------------------------------------------------------------------------------------------------------------ @@ -2576,7 +2576,7 @@ Use the \"help\" command to see the list of available commands.\n\ template void t_cryptonote_protocol_handler::drop_connection(cryptonote_connection_context &context, bool add_fail, bool flush_all_spans) { - oxen::log::debug(logcat, "{}dropping connection id {} (pruning seed {}), add_fail {}, flush_all_spans {}", context, boost::lexical_cast(context.m_connection_id), epee::string_tools::to_string_hex(context.m_pruning_seed), add_fail, flush_all_spans); + log::debug(logcat, "{}dropping connection id {} (pruning seed {}), add_fail {}, flush_all_spans {}", context, boost::lexical_cast(context.m_connection_id), epee::string_tools::to_string_hex(context.m_pruning_seed), add_fail, flush_all_spans); if (add_fail) m_p2p->add_host_fail(context.m_remote_address); @@ -2589,7 +2589,7 @@ Use the \"help\" command to see the list of available commands.\n\ // them before we close the connection and so might never learn of the problem. if (context.m_drop_count >= 1) { - oxen::log::debug(logcat, "{}{} a second chance before dropping", context, "giving connect id ", boost::lexical_cast(context.m_connection_id)); + log::debug(logcat, "{}{} a second chance before dropping", context, "giving connect id ", boost::lexical_cast(context.m_connection_id)); ++context.m_drop_count; } else @@ -2608,14 +2608,14 @@ Use the \"help\" command to see the list of available commands.\n\ const uint64_t previous_target = m_core.get_target_blockchain_height(); if (target < previous_target) { - oxen::log::info(logcat, "Target height decreasing from {} to {}", previous_target, target); + log::info(logcat, "Target height decreasing from {} to {}", previous_target, target); m_core.set_target_blockchain_height(target); if (target == 0 && context.m_state > cryptonote_connection_context::state_before_handshake && !m_stopping) - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::yellow), "oxend is now disconnected from the network")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::yellow), "oxend is now disconnected from the network")); } m_block_queue.flush_spans(context.m_connection_id, false); - oxen::log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "closed", cryptonote::get_protocol_state_string(context.m_state)); + log::debug(logcat, "{}[{}] state: {} in state {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed), "closed", cryptonote::get_protocol_state_string(context.m_state)); } //------------------------------------------------------------------------------------------------------------------------ diff --git a/src/cryptonote_protocol/levin_notify.cpp b/src/cryptonote_protocol/levin_notify.cpp index 4f4a1262c..013f006cf 100644 --- a/src/cryptonote_protocol/levin_notify.cpp +++ b/src/cryptonote_protocol/levin_notify.cpp @@ -45,7 +45,7 @@ namespace cryptonote::levin { - static auto logcat = oxen::log::Cat("net.p2p.tx"); + static auto logcat = log::Cat("net.p2p.tx"); namespace { @@ -236,7 +236,7 @@ namespace cryptonote::levin if (!channel.connection.is_nil()) channel.queue.push_back(std::move(message_)); else if (destination_ == 0 && zone_->connection_count == 0) - oxen::log::warning(logcat, "Unable to send transaction(s) over anonymity network - no available outbound connections"); + log::warning(logcat, "Unable to send transaction(s) over anonymity network - no available outbound connections"); } }; @@ -439,7 +439,7 @@ namespace cryptonote::levin auto connections = get_out_connections(*zone_->p2p); if (connections.empty()) - oxen::log::warning(logcat, "Lost all outbound connections to anonymity network - currently unable to send transaction(s)"); + log::warning(logcat, "Lost all outbound connections to anonymity network - currently unable to send transaction(s)"); zone_->strand.post(update_channels{zone_, std::move(connections)}); } @@ -553,7 +553,7 @@ namespace cryptonote::levin )}; if (MAX_FRAGMENTS * zone_->noise.size() < message.size()) { - oxen::log::error(logcat, "notify::send_txs provided message exceeding covert fragment size"); + log::error(logcat, "notify::send_txs provided message exceeding covert fragment size"); return false; } diff --git a/src/cryptonote_protocol/quorumnet.cpp b/src/cryptonote_protocol/quorumnet.cpp index 5bc02cdf6..118b135b1 100644 --- a/src/cryptonote_protocol/quorumnet.cpp +++ b/src/cryptonote_protocol/quorumnet.cpp @@ -47,7 +47,8 @@ namespace quorumnet { - static auto logcat = oxen::log::Cat("qnet"); + namespace log = oxen::log; + static auto logcat = log::Cat("qnet"); namespace { @@ -162,18 +163,18 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It for (auto it = quorum_begin; it != quorum_end; it++) candidates.insert((*it)->validators.begin(), (*it)->validators.end()); - oxen::log::debug(logcat, "Have {} SN candidates", candidates.size()); + log::debug(logcat, "Have {} SN candidates", candidates.size()); std::vectorversion)>> remotes; // {x25519 pubkey, connect string, version} remotes.reserve(candidates.size()); core.get_service_node_list().for_each_service_node_info_and_proof(candidates.begin(), candidates.end(), [&remotes](const auto &pubkey, const auto &info, const auto &proof) { if (!info.is_active()) { - oxen::log::trace(logcat, "Not include inactive node {}", pubkey); + log::trace(logcat, "Not include inactive node {}", pubkey); return; } if (!proof.pubkey_x25519 || !proof.proof->qnet_port || !proof.proof->public_ip) { - oxen::log::trace(logcat, "Not including node {}: missing x25519({}), public_ip({}), or qnet port({})", pubkey, to_hex(get_data_as_string(proof.pubkey_x25519)), epee::string_tools::get_ip_string_from_int32(proof.proof->public_ip), proof.proof->qnet_port); + log::trace(logcat, "Not including node {}: missing x25519({}), public_ip({}), or qnet port({})", pubkey, to_hex(get_data_as_string(proof.pubkey_x25519)), epee::string_tools::get_ip_string_from_int32(proof.proof->public_ip), proof.proof->qnet_port); return; } remotes.emplace_back(get_data_as_string(proof.pubkey_x25519), @@ -182,7 +183,7 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It }); // Select 4 random SNs to send the data to, but prefer SNs with newer versions because they may have network fixes. - oxen::log::debug(logcat, "Have {} candidates after checking active status and connection details", remotes.size()); + log::debug(logcat, "Have {} candidates after checking active status and connection details", remotes.size()); std::vector indices(remotes.size()); std::iota(indices.begin(), indices.end(), 0); std::shuffle(indices.begin(), indices.end(), tools::rng); @@ -206,7 +207,7 @@ peer_prepare_relay_to_quorum_subset(cryptonote::core &core, It quorum_begin, It void peer_relay_to_prepared_destinations(cryptonote::core &core, std::vector const &destinations, std::string_view command, std::string &&data) { for (auto const &[x25519_string, connect_string]: destinations) { - oxen::log::info(logcat, "Relaying data to {} @ {}", to_hex(x25519_string), connect_string); + log::info(logcat, "Relaying data to {} @ {}", to_hex(x25519_string), connect_string); core.get_omq().send(x25519_string, command, std::move(data), send_option::hint{connect_string}); } } @@ -360,10 +361,10 @@ private: size_t i = 0; for (QuorumIt qit = qbegin; qit != qend; ++i, ++qit) { if (my_position[i] < 0) { - oxen::log::trace(logcat, "Not in subquorum {}", (i == 0 ? "Q" : "Q'")); + log::trace(logcat, "Not in subquorum {}", (i == 0 ? "Q" : "Q'")); continue; } else { - oxen::log::trace(logcat, "I am in subquorum {} position {}", (i == 0 ? "Q" : "Q'"), my_position[i]); + log::trace(logcat, "I am in subquorum {} position {}", (i == 0 ? "Q" : "Q'"), my_position[i]); } auto &validators = (*qit)->validators; @@ -371,14 +372,14 @@ private: // Relay to all my outgoing targets within the quorum (connecting if not already connected) for (int j : quorum_outgoing_conns(my_position[i], validators.size())) { if (add_peer(validators[j])) - oxen::log::trace(logcat, "Relaying within subquorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); + log::trace(logcat, "Relaying within subquorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); } // Opportunistically relay to all my *incoming* sources within the quorum *if* I already // have a connection open with them, but don't open a new connection if I don't. for (int j : quorum_incoming_conns(my_position[i], validators.size())) { if (add_peer(validators[j], false /*!strong*/)) - oxen::log::trace(logcat, "Optional opportunistic relay within quorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); + log::trace(logcat, "Optional opportunistic relay within quorum {}[{}] to [{}] {}", (i == 0 ? "Q" : "Q'"), my_position[i], j, validators[j]); } // Now establish strong interconnections between quorums, if we have multiple subquorums @@ -402,12 +403,12 @@ private: if (my_position[i] >= half && my_position[i] < half*2) { int next_pos = my_position[i] - half; bool added = add_peer(next_validators[next_pos]); - oxen::log::trace(logcat, "Inter-quorum relay from Q[{}] (me) to Q'[{}] = {}{}", my_position[i], next_pos, next_validators[next_pos], (added ? "" : " (skipping; already relaying to that SN)")); + log::trace(logcat, "Inter-quorum relay from Q[{}] (me) to Q'[{}] = {}{}", my_position[i], next_pos, next_validators[next_pos], (added ? "" : " (skipping; already relaying to that SN)")); } else { - oxen::log::trace(logcat, "Q[{}] is not a Q -> Q' inter-quorum relay position", my_position[i]); + log::trace(logcat, "Q[{}] is not a Q -> Q' inter-quorum relay position", my_position[i]); } } else if (qnext != qend) { - oxen::log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i], my_position[i+1]); + log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i], my_position[i+1]); } // Exactly the same connections as above, but in reverse: the first half of Q' sends to @@ -419,12 +420,12 @@ private: if (my_position[i] < half) { int prev_pos = half + my_position[i]; bool added = add_peer(prev_validators[prev_pos]); - oxen::log::trace(logcat, "Inter-quorum relay from Q'[{}] (me) to Q[{}] = {}{}", my_position[i], prev_pos, prev_validators[prev_pos], (added ? "" : " (already relaying to that SN)")); + log::trace(logcat, "Inter-quorum relay from Q'[{}] (me) to Q[{}] = {}{}", my_position[i], prev_pos, prev_validators[prev_pos], (added ? "" : " (already relaying to that SN)")); } else { - oxen::log::trace(logcat, "Q'[{}] is not a Q' -> Q inter-quorum relay position", my_position[i]); + log::trace(logcat, "Q'[{}] is not a Q' -> Q inter-quorum relay position", my_position[i]); } } else if (qit != qbegin) { - oxen::log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i-1], my_position[i]); + log::trace(logcat, "Not doing inter-quorum relaying because I am in both quorums (Q[{}], Q'[{}])", my_position[i-1], my_position[i]); } } } @@ -433,7 +434,7 @@ private: template void relay_to_peers_impl(const std::string_view &cmd, std::array relay_data, std::index_sequence) { for (auto &peer : peers) { - oxen::log::trace(logcat, "Relaying {} to peer {}{}", cmd, to_hex(peer.first), (peer.second.empty() ? " (if connected)"s : " @ " + peer.second)); + log::trace(logcat, "Relaying {} to peer {}{}", cmd, to_hex(peer.first), (peer.second.empty() ? " (if connected)"s : " @ " + peer.second)); if (peer.second.empty()) omq.send(peer.first, cmd, relay_data[I]..., send_option::optional{}); else @@ -494,45 +495,45 @@ void relay_obligation_votes(void *obj, const std::vector relayed_votes; relayed_votes.reserve(votes.size()); for (auto &vote : votes) { if (vote.type != quorum_type::obligations) { - oxen::log::error(logcat, "Internal logic error: quorumnet asked to relay a {} vote, but should only be called with obligations votes", vote.type); + log::error(logcat, "Internal logic error: quorumnet asked to relay a {} vote, but should only be called with obligations votes", vote.type); continue; } auto quorum = qnet.core.get_service_node_list().get_quorum(vote.type, vote.block_height); if (!quorum) { - oxen::log::warning(logcat, "Unable to relay vote: no {} quorum available for height {}", vote.type, vote.block_height); + log::warning(logcat, "Unable to relay vote: no {} quorum available for height {}", vote.type, vote.block_height); continue; } auto &quorum_voters = quorum->validators; if (quorum_voters.size() < service_nodes::min_votes_for_quorum_type(vote.type)) { - oxen::log::warning(logcat, "Invalid vote relay: {} quorum @ height {} does not have enough validators ({}) to reach the minimum required votes ({})", vote.type, vote.block_height, quorum_voters.size(), service_nodes::min_votes_for_quorum_type(vote.type)); + log::warning(logcat, "Invalid vote relay: {} quorum @ height {} does not have enough validators ({}) to reach the minimum required votes ({})", vote.type, vote.block_height, quorum_voters.size(), service_nodes::min_votes_for_quorum_type(vote.type)); continue; } peer_info pinfo{qnet, vote.type, quorum.get()}; if (!pinfo.my_position_count) { - oxen::log::warning(logcat, "Invalid vote relay: vote to relay does not include this service node"); + log::warning(logcat, "Invalid vote relay: vote to relay does not include this service node"); continue; } pinfo.relay_to_peers("quorum.vote_ob", serialize_vote(vote)); relayed_votes.push_back(vote); } - oxen::log::debug(logcat, "Relayed {} votes", relayed_votes.size()); + log::debug(logcat, "Relayed {} votes", relayed_votes.size()); qnet.core.set_service_node_votes_relayed(relayed_votes); } void handle_obligation_vote(Message& m, QnetState& qnet) { - oxen::log::debug(logcat, "Received a relayed obligation vote from {}", to_hex(m.conn.pubkey())); + log::debug(logcat, "Received a relayed obligation vote from {}", to_hex(m.conn.pubkey())); if (m.data.size() != 1) { - oxen::log::info(logcat, "Ignoring vote: expected 1 data part, not {}", m.data.size()); + log::info(logcat, "Ignoring vote: expected 1 data part, not {}", m.data.size()); return; } @@ -542,11 +543,11 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { auto& vote = vvote.back(); if (vote.type != quorum_type::obligations) { - oxen::log::warning(logcat, "Received invalid non-obligations vote via quorumnet; ignoring"); + log::warning(logcat, "Received invalid non-obligations vote via quorumnet; ignoring"); return; } if (vote.block_height > qnet.core.get_current_blockchain_height()) { - oxen::log::debug(logcat, "Ignoring vote: block height {} is too high", vote.block_height); + log::debug(logcat, "Ignoring vote: block height {} is too high", vote.block_height); return; } @@ -554,7 +555,7 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { qnet.core.add_service_node_vote(vote, vvc); if (vvc.m_verification_failed) { - oxen::log::warning(logcat, "Vote verification failed; ignoring vote"); + log::warning(logcat, "Vote verification failed; ignoring vote"); return; } @@ -562,12 +563,12 @@ void handle_obligation_vote(Message& m, QnetState& qnet) { relay_obligation_votes(&qnet, std::move(vvote)); } catch (const std::exception &e) { - oxen::log::warning(logcat, "Deserialization of vote from {} failed: {}", to_hex(m.conn.pubkey()), e.what()); + log::warning(logcat, "Deserialization of vote from {} failed: {}", to_hex(m.conn.pubkey()), e.what()); } } void handle_timestamp(Message& m) { - oxen::log::debug(logcat, "Received a timestamp request from {}", to_hex(m.conn.pubkey())); + log::debug(logcat, "Received a timestamp request from {}", to_hex(m.conn.pubkey())); const time_t seconds = time(nullptr); m.send_reply(std::to_string(seconds)); } @@ -607,13 +608,13 @@ quorum_array get_blink_quorums(uint64_t blink_height, const service_node_list &s throw std::runtime_error("not enough blink nodes to form a quorum"); local_checksum += quorum_checksum(v, qi * BLINK_SUBQUORUM_SIZE); } - oxen::log::trace(logcat, "Verified enough active blink nodes for a quorum; quorum checksum: {}", local_checksum); + log::trace(logcat, "Verified enough active blink nodes for a quorum; quorum checksum: {}", local_checksum); if (input_checksum) { if (*input_checksum != local_checksum) throw std::runtime_error("wrong quorum checksum: expected " + std::to_string(local_checksum) + ", received " + std::to_string(*input_checksum)); - oxen::log::trace(logcat, "Blink quorum checksum matched"); + log::trace(logcat, "Blink quorum checksum matched"); } if (output_checksum) *output_checksum = local_checksum; @@ -664,7 +665,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (position < 0 || position >= (int) validators.size()) { - oxen::log::warning(logcat, "Invalid blink signature: subquorum position is invalid"); + log::warning(logcat, "Invalid blink signature: subquorum position is invalid"); it = signatures.erase(it); } else if (btx.get_signature_status(subquorum, position) != blink_tx::signature_status::none) { it = signatures.erase(it); @@ -688,7 +689,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (!crypto::check_signature(btx.hash(approval), validators[position], signature)) { - oxen::log::warning(logcat, "Invalid blink signature: signature verification failed"); + log::warning(logcat, "Invalid blink signature: signature verification failed"); it = signatures.erase(it); continue; } @@ -705,7 +706,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & bool already_approved = btx.approved(), already_rejected = !already_approved && btx.rejected(); - oxen::log::trace(logcat, "Before recording new signatures I have existing signatures: {}", debug_known_signatures(btx, blink_quorums)); + log::trace(logcat, "Before recording new signatures I have existing signatures: {}", debug_known_signatures(btx, blink_quorums)); // Now actually add them (and do one last check on them) for (auto it = signatures.begin(); it != signatures.end(); ) { @@ -719,7 +720,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & auto &validators = blink_quorums[qi]->validators; if (btx.add_prechecked_signature(subquorum, position, approval, signature)) { - oxen::log::debug(logcat, "Validated and stored {} signature for tx {}, subquorum {}, position {}", (approval ? "approval" : "rejection"), btx.get_txhash(), int{qi}, position); + log::debug(logcat, "Validated and stored {} signature for tx {}, subquorum {}, position {}", (approval ? "approval" : "rejection"), btx.get_txhash(), int{qi}, position); ++it; } else { @@ -730,7 +731,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & } if (!signatures.empty()) { - oxen::log::debug(logcat, "Updated signatures; now have signatures: {}", debug_known_signatures(btx, blink_quorums)); + log::debug(logcat, "Updated signatures; now have signatures: {}", debug_known_signatures(btx, blink_quorums)); if (!already_approved && !already_rejected) { if (btx.approved()) { @@ -743,7 +744,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & } if (became_approved) { - oxen::log::info(logcat, "Accumulated enough signatures for blink tx: enabling tx relay"); + log::info(logcat, "Accumulated enough signatures for blink tx: enabling tx relay"); auto &pool = qnet.core.get_pool(); { auto lock = pool.blink_unique_lock(); @@ -767,7 +768,7 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & peer_info pinfo{qnet, quorum_type::blink, blink_quorums.begin(), blink_quorums.end(), true /*opportunistic*/, std::move(relay_exclude)}; - oxen::log::debug(logcat, "Relaying {} blink signatures to {} (strong) + {} (opportunistic blink peers)", signatures.size(), pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); + log::debug(logcat, "Relaying {} blink signatures to {} (strong) + {} (opportunistic blink peers)", signatures.size(), pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); bt_list i_list, p_list, r_list, s_list; for (auto &s : signatures) { @@ -789,14 +790,14 @@ void process_blink_signatures(QnetState &qnet, const std::shared_ptr & pinfo.relay_to_peers("quorum.blink_sign", blink_sign_data); - oxen::log::trace(logcat, "Done blink signature relay"); + log::trace(logcat, "Done blink signature relay"); if (reply_tag && reply_conn) { if (became_approved) { - oxen::log::info(logcat, "Blink tx became approved; sending result back to originating node"); + log::info(logcat, "Blink tx became approved; sending result back to originating node"); qnet.omq.send(reply_conn, "bl.good", bt_serialize(bt_dict{{"!", reply_tag}}), send_option::optional{}); } else if (became_rejected) { - oxen::log::info(logcat, "Blink tx became rejected; sending result back to originating node"); + log::info(logcat, "Blink tx became rejected; sending result back to originating node"); qnet.omq.send(reply_conn, "bl.bad", bt_serialize(bt_dict{{"!", reply_tag}}), send_option::optional{}); } } @@ -834,7 +835,7 @@ void handle_blink(Message& m, QnetState& qnet) { // message and close it. // If an outgoing connection - refuse reconnections via ZAP and just close it. - oxen::log::debug(logcat, "Received a blink tx from {}{}", (m.conn.sn() ? "SN " : "non-SN "), to_hex(m.conn.pubkey())); + log::debug(logcat, "Received a blink tx from {}{}", (m.conn.sn() ? "SN " : "non-SN "), to_hex(m.conn.pubkey())); assert(qnet.core.service_node()); if (!qnet.core.service_node()) @@ -842,7 +843,7 @@ void handle_blink(Message& m, QnetState& qnet) { const auto& keys = qnet.core.get_service_keys(); if (m.data.size() != 1) { - oxen::log::info(logcat, "Rejecting blink message: expected one data entry not {}", m.data.size()); + log::info(logcat, "Rejecting blink message: expected one data entry not {}", m.data.size()); // No valid data and so no reply tag; we can't send a response return; } @@ -854,7 +855,7 @@ void handle_blink(Message& m, QnetState& qnet) { auto hf_version = get_network_version(qnet.core.get_nettype(), local_height); if (hf_version < cryptonote::feature::BLINK) { - oxen::log::warning(logcat, "Rejecting blink message: blink is not available for hardfork {}", (int) hf_version); + log::warning(logcat, "Rejecting blink message: blink is not available for hardfork {}", (int) hf_version); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; @@ -864,29 +865,29 @@ void handle_blink(Message& m, QnetState& qnet) { auto blink_height = get_int(data.at("h")); if (blink_height < local_height - 2) { - oxen::log::info(logcat, "Rejecting blink tx because blink auth height is too low ({} vs. {})", blink_height, local_height); + log::info(logcat, "Rejecting blink tx because blink auth height is too low ({} vs. {})", blink_height, local_height); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; } else if (blink_height > local_height + 2) { // TODO: if within some threshold (maybe 5-10?) we could hold it and process it once we are // within 2. - oxen::log::info(logcat, "Rejecting blink tx because blink auth height is too high ({} vs. {})", blink_height, local_height); + log::info(logcat, "Rejecting blink tx because blink auth height is too high ({} vs. {})", blink_height, local_height); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid blink authorization height"sv}})); return; } - oxen::log::trace(logcat, "Blink tx auth height {} is valid (local height is {})", blink_height, local_height); + log::trace(logcat, "Blink tx auth height {} is valid (local height is {})", blink_height, local_height); auto t_it = data.find("t"); if (t_it == data.end()) { - oxen::log::info(logcat, "Rejecting blink tx: no tx data included in request"); + log::info(logcat, "Rejecting blink tx: no tx data included in request"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "No transaction included in blink request"sv}})); return; } const std::string &tx_data = var::get(t_it->second); - oxen::log::trace(logcat, "Blink tx data is {} bytes", tx_data.size()); + log::trace(logcat, "Blink tx data is {} bytes", tx_data.size()); // "hash" is optional -- it lets us short-circuit processing the tx if we've already seen it, // and is added internally by SN-to-SN forwards but not the original submitter. We don't trust @@ -910,7 +911,7 @@ void handle_blink(Message& m, QnetState& qnet) { if (already_approved || already_rejected) { // Quorum approved/rejected the tx before we received the submitted blink, // reply with a bl.good/bl.bad immediately (done below, outside the lock). - oxen::log::info(logcat, "Submitted blink tx already {}; sending result back to originating node", (already_approved ? "approved" : "rejected")); + log::info(logcat, "Submitted blink tx already {}; sending result back to originating node", (already_approved ? "approved" : "rejected")); } else { // We've already seen it but are still waiting on more signatures to // determine the result, so stash the tag & pubkey in the metadata to delay @@ -921,14 +922,14 @@ void handle_blink(Message& m, QnetState& qnet) { return; } } else { - oxen::log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); + log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); return; } } } - oxen::log::trace(logcat, "Blink tx hash: {}", to_hex(tx_hash.data)); + log::trace(logcat, "Blink tx hash: {}", to_hex(tx_hash.data)); } else { - oxen::log::info(logcat, "Rejecting blink tx: invalid tx hash included in request"); + log::info(logcat, "Rejecting blink tx: invalid tx hash included in request"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid transaction hash"s}})); return; @@ -944,7 +945,7 @@ void handle_blink(Message& m, QnetState& qnet) { try { blink_quorums = get_blink_quorums(blink_height, qnet.core.get_service_node_list(), &checksum); } catch (const std::runtime_error &e) { - oxen::log::info(logcat, "Rejecting blink tx: {}", e.what()); + log::info(logcat, "Rejecting blink tx: {}", e.what()); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Unable to retrieve blink quorum: "s + e.what()}})); return; @@ -955,9 +956,9 @@ void handle_blink(Message& m, QnetState& qnet) { }; if (pinfo.my_position_count > 0) - oxen::log::trace(logcat, "Found this SN in {} subquorums", pinfo.my_position_count); + log::trace(logcat, "Found this SN in {} subquorums", pinfo.my_position_count); else { - oxen::log::info(logcat, "Rejecting blink tx: this service node is not a member of the blink quorum!"); + log::info(logcat, "Rejecting blink tx: this service node is not a member of the blink quorum!"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Blink tx relayed to non-blink quorum member"sv}})); return; @@ -974,27 +975,27 @@ void handle_blink(Message& m, QnetState& qnet) { { crypto::hash tx_hash_actual; if (!cryptonote::parse_and_validate_tx_from_blob(tx_data, tx, tx_hash_actual)) { - oxen::log::info(logcat, "Rejecting blink tx: failed to parse transaction data"); + log::info(logcat, "Rejecting blink tx: failed to parse transaction data"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Failed to parse transaction data"sv}})); return; } - oxen::log::trace(logcat, "Successfully parsed transaction data"); + log::trace(logcat, "Successfully parsed transaction data"); if (tx_hash != tx_hash_actual) { - oxen::log::info(logcat, "Rejecting blink tx: submitted tx hash {} did not match actual tx hash {}", tx_hash, tx_hash_actual); + log::info(logcat, "Rejecting blink tx: submitted tx hash {} did not match actual tx hash {}", tx_hash, tx_hash_actual); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "Invalid transaction hash"sv}})); return; } else { - oxen::log::trace(logcat, "Pre-computed tx hash matches actual tx hash"); + log::trace(logcat, "Pre-computed tx hash matches actual tx hash"); } } // Abort if we don't have at least one strong peer to send it to. This can only happen if it's // a brand new SN (not just restarted!) that hasn't received uptime proofs before. if (!pinfo.strong_peers) { - oxen::log::warning(logcat, "Could not find connection info for any blink quorum peers. Aborting blink tx"); + log::warning(logcat, "Could not find connection info for any blink quorum peers. Aborting blink tx"); if (tag) m.send_back("bl.nostart", bt_serialize(bt_dict{{"!", tag}, {"e", "No quorum peers are currently reachable"sv}})); return; @@ -1007,7 +1008,7 @@ void handle_blink(Message& m, QnetState& qnet) { std::unique_lock lock{qnet.mutex}; auto &bl_info = qnet.blinks[blink_height][tx_hash]; if (bl_info.btxptr) { - oxen::log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); + log::debug(logcat, "Already seen and forwarded this blink tx, ignoring it."); return; } bl_info.btxptr = btxptr; @@ -1019,7 +1020,7 @@ void handle_blink(Message& m, QnetState& qnet) { bl_info.reply_conn = m.conn; } } - oxen::log::trace(logcat, "Accepted new blink tx for verification"); + log::trace(logcat, "Accepted new blink tx for verification"); // The submission looks good. We distribute it first, *before* we start verifying the actual tx // details, for two reasons: we want other quorum members to start verifying ASAP, and we want @@ -1038,7 +1039,7 @@ void handle_blink(Message& m, QnetState& qnet) { {"t", tx_data}, {"#", tx_hash_str}, }; - oxen::log::debug(logcat, "Relaying blink tx to {} strong and {} opportunistic blink peers", pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); + log::debug(logcat, "Relaying blink tx to {} strong and {} opportunistic blink peers", pinfo.strong_peers, (pinfo.peers.size() - pinfo.strong_peers)); pinfo.relay_to_peers("blink.submit", blink_data); } @@ -1050,15 +1051,15 @@ void handle_blink(Message& m, QnetState& qnet) { max = tx.get_max_version_for_hf(hf_version); if (tx.version < min || tx.version > max) { approved = false; - oxen::log::info(logcat, "Blink TX {} rejected because TX version {} invalid: TX version not between {} and {}", tx_hash, tx.version, min, max); + log::info(logcat, "Blink TX {} rejected because TX version {} invalid: TX version not between {} and {}", tx_hash, tx.version, min, max); } else { bool already_in_mempool; cryptonote::tx_verification_context tvc = {}; approved = qnet.core.get_pool().add_new_blink(btxptr, tvc, already_in_mempool); - oxen::log::info(logcat, "Blink TX {}{}", tx_hash, (approved ? " approved and added to mempool" : " rejected")); + log::info(logcat, "Blink TX {}{}", tx_hash, (approved ? " approved and added to mempool" : " rejected")); if (!approved) - oxen::log::debug(logcat, "TX rejected because: {}", print_tx_verification_context(tvc)); + log::debug(logcat, "TX rejected because: {}", print_tx_verification_context(tvc)); } auto hash_to_sign = btx.hash(approved); @@ -1121,7 +1122,7 @@ crypto::signature convert_string_view_bytes_to_signature(std::string_view sig_st /// /// Signatures will be forwarded if new; known signatures will be ignored. void handle_blink_signature(Message& m, QnetState& qnet) { - oxen::log::debug(logcat, "Received a blink tx signature from SN {}", to_hex(m.conn.pubkey())); + log::debug(logcat, "Received a blink tx signature from SN {}", to_hex(m.conn.pubkey())); if (m.data.size() != 1) throw std::runtime_error("Rejecting blink signature: expected one data entry not " + std::to_string(m.data.size())); @@ -1219,7 +1220,7 @@ void handle_blink_signature(Message& m, QnetState& qnet) { // exclusive mutex, so check it again before we stash a delayed signature. find_blink(); if (!btxptr) { - oxen::log::info(logcat, "Blink tx not found in local blink cache; delaying signature verification"); + log::info(logcat, "Blink tx not found in local blink cache; delaying signature verification"); auto &delayed = qnet.blinks[blink_height][tx_hash].pending_sigs; for (auto &sig : signatures) delayed.insert(std::move(sig)); @@ -1227,7 +1228,7 @@ void handle_blink_signature(Message& m, QnetState& qnet) { } } - oxen::log::info(logcat, "Found blink tx in local blink cache"); + log::info(logcat, "Found blink tx in local blink cache"); process_blink_signatures(qnet, btxptr, blink_quorums, checksum, std::move(signatures), reply_tag, reply_conn, m.conn.pubkey()); } @@ -1369,14 +1370,14 @@ void common_blink_response(uint64_t tag, cryptonote::blink_result res, std::stri /// promise unless we get a nostart response from a majority of the remotes. void handle_blink_not_started(Message& m) { if (m.data.size() != 1) { - oxen::log::error(logcat, "Bad blink not started response: expected one data entry not {}", m.data.size()); + log::error(logcat, "Bad blink not started response: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); auto tag = get_int(data.at("!")); auto& error = var::get(data.at("e")); - oxen::log::info(logcat, "Received no-start blink response: {}", error); + log::info(logcat, "Received no-start blink response: {}", error); common_blink_response(tag, cryptonote::blink_result::rejected, std::move(error), true /*nostart*/); } @@ -1388,7 +1389,7 @@ void handle_blink_not_started(Message& m) { /// void handle_blink_failure(Message &m) { if (m.data.size() != 1) { - oxen::log::error(logcat, "Blink failure message not understood: expected one data entry not {}", m.data.size()); + log::error(logcat, "Blink failure message not understood: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); @@ -1400,7 +1401,7 @@ void handle_blink_failure(Message &m) { // signature receipt, not at rejection time), so for now we don't include it. //auto &error = var::get(data.at("e")); - oxen::log::info(logcat, "Received blink failure response"); + log::info(logcat, "Received blink failure response"); common_blink_response(tag, cryptonote::blink_result::rejected, "Transaction rejected by quorum"s); } @@ -1412,13 +1413,13 @@ void handle_blink_failure(Message &m) { /// void handle_blink_success(Message& m) { if (m.data.size() != 1) { - oxen::log::error(logcat, "Blink success message not understood: expected one data entry not {}", m.data.size()); + log::error(logcat, "Blink success message not understood: expected one data entry not {}", m.data.size()); return; } auto data = bt_deserialize(m.data[0]); auto tag = get_int(data.at("!")); - oxen::log::info(logcat, "Received blink success response"); + log::info(logcat, "Received blink success response"); common_blink_response(tag, cryptonote::blink_result::accepted, ""s); } diff --git a/src/daemon/command_parser_executor.cpp b/src/daemon/command_parser_executor.cpp index 7fce0e33c..69fef0aed 100644 --- a/src/daemon/command_parser_executor.cpp +++ b/src/daemon/command_parser_executor.cpp @@ -39,7 +39,8 @@ namespace daemonize { -static auto logcat = oxen::log::Cat("daemon"); +namespace log = oxen::log; +static auto logcat = log::Cat("daemon"); // Consumes an argument from the given list, if present, parsing it into `var`. // Returns false upon parse failure, true otherwise. @@ -359,7 +360,7 @@ bool command_parser_executor::print_block(const std::vector& args) crypto::hash block_hash; if (tools::hex_to_type(arg, block_hash)) return m_executor.print_block_by_hash(block_hash, include_hex); - oxen::log::error(logcat, "Invalid hash or height value: {}", arg); + log::error(logcat, "Invalid hash or height value: {}", arg); } return false; @@ -396,7 +397,7 @@ bool command_parser_executor::print_transaction(const std::vector& if (tools::hex_to_type(str_hash, tx_hash)) m_executor.print_transaction(tx_hash, include_metadata, include_hex, include_json); else - oxen::log::error(logcat, "Invalid transaction hash: {}", str_hash); + log::error(logcat, "Invalid transaction hash: {}", str_hash); return true; } @@ -546,7 +547,7 @@ bool command_parser_executor::out_peers(const std::vector& args) } catch(const std::exception& ex) { - oxen::log::error(logcat, "stoi exception"); + log::error(logcat, "stoi exception"); return false; } @@ -566,7 +567,7 @@ bool command_parser_executor::in_peers(const std::vector& args) } catch(const std::exception& ex) { - oxen::log::error(logcat, "stoi exception"); + log::error(logcat, "stoi exception"); return false; } diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index 032c94a89..ffbf9e737 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -69,7 +69,8 @@ using namespace std::literals; namespace daemonize { -static auto logcat = oxen::log::Cat("daemon"); +namespace log = oxen::log; +static auto logcat = log::Cat("daemon"); std::pair parse_ip_port(std::string_view ip_port, const std::string& argname) { @@ -110,13 +111,13 @@ daemon::daemon(boost::program_options::variables_map vm_) : p2p{std::make_unique(*protocol)}, rpc{std::make_unique(*core, *p2p)} { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Initializing daemon objects...")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Initializing daemon objects...")); - oxen::log::info(logcat, "- cryptonote protocol"); + log::info(logcat, "- cryptonote protocol"); if (!protocol->init(vm)) throw std::runtime_error("Failed to initialize cryptonote protocol."); - oxen::log::info(logcat, "- p2p"); + log::info(logcat, "- p2p"); if (!p2p->init(vm)) throw std::runtime_error("Failed to initialize p2p server."); @@ -145,7 +146,7 @@ daemon::daemon(boost::program_options::variables_map vm_) : std::vector> rpc_listen_admin, rpc_listen_public; if (deprecated_rpc_options) { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead", deprecated_option_names)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead", deprecated_option_names)); // These old options from Monero are really janky: --restricted-rpc turns the main port // restricted, but then we also have --rpc-restricted-bind-port but both are stuck with @@ -208,55 +209,55 @@ daemon::daemon(boost::program_options::variables_map vm_) : if (!rpc_listen_admin.empty()) { - oxen::log::info(logcat, "- admin HTTP RPC server"); + log::info(logcat, "- admin HTTP RPC server"); http_rpc_admin.emplace(*rpc, rpc_config, false /*not restricted*/, std::move(rpc_listen_admin)); } if (!rpc_listen_public.empty()) { - oxen::log::info(logcat, "- public HTTP RPC server"); + log::info(logcat, "- public HTTP RPC server"); http_rpc_public.emplace(*rpc, rpc_config, true /*restricted*/, std::move(rpc_listen_public)); } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Done daemon object initialization")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Done daemon object initialization")); } daemon::~daemon() { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitializing daemon objects...")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitializing daemon objects...")); if (http_rpc_public) { - oxen::log::info(logcat, "- public HTTP RPC server"); + log::info(logcat, "- public HTTP RPC server"); http_rpc_public.reset(); } if (http_rpc_admin) { - oxen::log::info(logcat, "- admin HTTP RPC server"); + log::info(logcat, "- admin HTTP RPC server"); http_rpc_admin.reset(); } - oxen::log::info(logcat, "- p2p"); + log::info(logcat, "- p2p"); try { p2p->deinit(); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to deinitialize p2p: {}", e.what()); + log::error(logcat, "Failed to deinitialize p2p: {}", e.what()); } - oxen::log::info(logcat, "- core"); + log::info(logcat, "- core"); try { core->deinit(); core->set_cryptonote_protocol(nullptr); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to deinitialize core: {}", e.what()); + log::error(logcat, "Failed to deinitialize core: {}", e.what()); } - oxen::log::info(logcat, "- cryptonote protocol"); + log::info(logcat, "- cryptonote protocol"); try { protocol->deinit(); protocol->set_p2p_endpoint(nullptr); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to stop cryptonote protocol: {}", e.what()); + log::error(logcat, "Failed to stop cryptonote protocol: {}", e.what()); } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitialization complete")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitialization complete")); } void daemon::init_options(boost::program_options::options_description& option_spec, boost::program_options::options_description& hidden) @@ -297,32 +298,32 @@ bool daemon::run(bool interactive) try { - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Starting up oxend services...")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Starting up oxend services...")); cryptonote::GetCheckpointsCallback get_checkpoints; #if defined(PER_BLOCK_CHECKPOINT) get_checkpoints = blocks::GetCheckpointsData; #endif - oxen::log::info(logcat, "Starting core"); + log::info(logcat, "Starting core"); if (!core->init(vm, nullptr, get_checkpoints)) throw std::runtime_error("Failed to start core"); - oxen::log::info(logcat, "Starting OxenMQ"); + log::info(logcat, "Starting OxenMQ"); omq_rpc = std::make_unique(*core, *rpc, vm); core->start_oxenmq(); if (http_rpc_admin) { - oxen::log::info(logcat, "Starting admin HTTP RPC server"); + log::info(logcat, "Starting admin HTTP RPC server"); http_rpc_admin->start(); } if (http_rpc_public) { - oxen::log::info(logcat, "Starting public HTTP RPC server"); + log::info(logcat, "Starting public HTTP RPC server"); http_rpc_public->start(); } std::optional rpc_commands; if (interactive) { - oxen::log::info(logcat, "Starting command-line processor"); + log::info(logcat, "Starting command-line processor"); auto& omq = core->get_omq(); std::promise p; @@ -341,42 +342,42 @@ bool daemon::run(bool interactive) rpc_commands->start_handling([this] { stop(); }); } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Starting up main network")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Starting up main network")); #ifdef ENABLE_SYSTEMD sd_notify(0, ("READY=1\nSTATUS=" + core->get_status_string()).c_str()); #endif p2p->run(); // blocks until p2p goes down - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Main network stopped")); + log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Main network stopped")); if (rpc_commands) { - oxen::log::info(logcat, "Stopping RPC command processor"); + log::info(logcat, "Stopping RPC command processor"); rpc_commands->stop_handling(); rpc_commands.reset(); } if (http_rpc_public) { - oxen::log::info(logcat, "Stopping public HTTP RPC server..."); + log::info(logcat, "Stopping public HTTP RPC server..."); http_rpc_public->shutdown(); } if (http_rpc_admin) { - oxen::log::info(logcat, "Stopping admin HTTP RPC server..."); + log::info(logcat, "Stopping admin HTTP RPC server..."); http_rpc_admin->shutdown(); } - oxen::log::info(logcat, "Node stopped."); + log::info(logcat, "Node stopped."); return true; } catch (std::exception const& ex) { - oxen::log::error(logcat, ex.what()); + log::error(logcat, ex.what()); return false; } catch (...) { - oxen::log::error(logcat, "Unknown exception occured!"); + log::error(logcat, "Unknown exception occured!"); return false; } } diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp index 9c4957c1f..fe146670d 100644 --- a/src/daemon/main.cpp +++ b/src/daemon/main.cpp @@ -51,11 +51,13 @@ namespace po = boost::program_options; +namespace Log = oxen::log; // capital Log to avoid conflict with math.h log() + using namespace std::literals; namespace { - static auto logcat = oxen::log::Cat("daemon"); + auto logcat = Log::Cat("daemon"); // Some ANSI color sequences that we use here (before the log system is initialized): constexpr auto RESET = "\033[0m"; @@ -295,7 +297,7 @@ int main(int argc, char const * argv[]) // if log-file argument given: // absolute path // relative path: relative to data_dir - oxen::log::Level log_level; + Log::Level log_level; if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, daemon_args::arg_log_level).c_str())) { log_level = *level; } else { @@ -317,7 +319,7 @@ int main(int argc, char const * argv[]) // logging is now set up // FIXME: only print this when starting up as a daemon but not when running rpc commands - oxen::log::info(logcat, "Oxen '{}' (v{})", OXEN_RELEASE_NAME, OXEN_VERSION_FULL); + Log::info(logcat, "Oxen '{}' (v{})", OXEN_RELEASE_NAME, OXEN_VERSION_FULL); // If there are positional options, we're running a daemon command { @@ -354,7 +356,7 @@ int main(int argc, char const * argv[]) } } - oxen::log::info(logcat, "Moving from main() into the daemonize now."); + Log::info(logcat, "Moving from main() into the daemonize now."); return daemonizer::daemonize("Oxen Daemon", argc, argv, std::move(vm)) ? 0 : 1; @@ -362,14 +364,14 @@ int main(int argc, char const * argv[]) catch (std::exception const & ex) { if (logs_initialized) - oxen::log::error(logcat, "Exception in main! {}", ex.what()); + Log::error(logcat, "Exception in main! {}", ex.what()); else std::cerr << RED << "Exception in main! " << ex.what() << RESET << "\n"; } catch (...) { if (logs_initialized) - oxen::log::error(logcat, "Exception in main! (unknown exception type)"); + Log::error(logcat, "Exception in main! (unknown exception type)"); else std::cerr << RED << "Exception in main! (unknown exception type)" << RESET << "\n"; } diff --git a/src/debug_utilities/cn_deserialize.cpp b/src/debug_utilities/cn_deserialize.cpp index 420220565..b32ad7585 100644 --- a/src/debug_utilities/cn_deserialize.cpp +++ b/src/debug_utilities/cn_deserialize.cpp @@ -36,12 +36,12 @@ #include "version.h" #include -static auto logcat = oxen::log::Cat("debugtools.deserialize"); - namespace po = boost::program_options; using namespace cryptonote; +static auto logcat = log::Cat("debugtools.deserialize"); + static std::string extra_nonce_to_string(const cryptonote::tx_extra_nonce &extra_nonce) { if (extra_nonce.nonce.size() == 9 && extra_nonce.nonce[0] == TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID) @@ -182,7 +182,7 @@ int main(int argc, char* argv[]) } auto log_file_path = "cn_deserialize.log"; - oxen::log::Level log_level; + log::Level log_level; if(auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level))) { log_level = *level; } else { @@ -190,7 +190,7 @@ int main(int argc, char* argv[]) throw std::runtime_error{"Incorrect log level"}; } oxen::logging::init(log_file_path, log_level); - oxen::log::warning(logcat, "Starting..."); + log::warning(logcat, "Starting..."); if (oxenc::is_hex(input)) { diff --git a/src/device/device.cpp b/src/device/device.cpp index 40273e41a..341cba98b 100644 --- a/src/device/device.cpp +++ b/src/device/device.cpp @@ -38,7 +38,7 @@ namespace hw { - static auto logcat = oxen::log::Cat("device"); + static auto logcat = log::Cat("device"); /* ======================================================================= */ /* SETUP */ @@ -86,9 +86,9 @@ namespace hw { auto device = registry.find(device_descriptor_lookup); if (device == registry.end()) { - oxen::log::error(logcat, "Device not found in registry: '{}'. Known devices: ", device_descriptor); + log::error(logcat, "Device not found in registry: '{}'. Known devices: ", device_descriptor); for (const auto& sm_pair : registry) - oxen::log::error(logcat, " - {}", sm_pair.first); + log::error(logcat, " - {}", sm_pair.first); throw std::runtime_error("device not found: " + device_descriptor); } return *device->second; diff --git a/src/device/device.hpp b/src/device/device.hpp index 9aaebda62..3be4c2fc6 100644 --- a/src/device/device.hpp +++ b/src/device/device.hpp @@ -35,6 +35,7 @@ #include "cryptonote_config.h" #include "epee/wipeable_string.h" #include "cryptonote_basic/txtypes.h" +#include "logging/oxen_logger.h" #ifndef USE_DEVICE_LEDGER @@ -62,6 +63,8 @@ namespace cryptonote } namespace hw { + namespace log = oxen::log; + class device_progress { public: virtual double progress() const { return 0; } diff --git a/src/device/device_ledger.cpp b/src/device/device_ledger.cpp index 9d8fbb104..2d6e38dcd 100644 --- a/src/device/device_ledger.cpp +++ b/src/device/device_ledger.cpp @@ -50,7 +50,7 @@ namespace hw::ledger { #ifdef WITH_DEVICE_LEDGER - static auto logcat = oxen::log::Cat("device.ledger"); + static auto logcat = log::Cat("device.ledger"); /* ===================================================================== */ /* === Debug ==== */ @@ -319,7 +319,7 @@ namespace hw::ledger { reset_buffer(); has_view_key = false; tx_in_progress = false; - oxen::log::debug(logcat, "Device {} Created", id); + log::debug(logcat, "Device {} Created", id); } device_ledger::device_ledger(io::ledger_tcp&& tcp) : hw_device{std::make_unique(std::move(tcp))} { @@ -327,12 +327,12 @@ namespace hw::ledger { reset_buffer(); has_view_key = false; tx_in_progress = false; - oxen::log::debug(logcat, "Device {} (tcp) created", id); + log::debug(logcat, "Device {} (tcp) created", id); } device_ledger::~device_ledger() { release(); - oxen::log::debug(logcat, "Device {} Destroyed", id); + log::debug(logcat, "Device {} Destroyed", id); } /* ======================================================================= */ @@ -341,24 +341,24 @@ namespace hw::ledger { //lock the device for a long sequence void device_ledger::lock() { - oxen::log::debug(logcat, "Ask for LOCKING for device {} in thread ", name); + log::debug(logcat, "Ask for LOCKING for device {} in thread ", name); device_locker.lock(); - oxen::log::debug(logcat, "Device {} LOCKed", name); + log::debug(logcat, "Device {} LOCKed", name); } //lock the device for a long sequence bool device_ledger::try_lock() { - oxen::log::debug(logcat, "Ask for LOCKING(try) for device {} in thread ", name); + log::debug(logcat, "Ask for LOCKING(try) for device {} in thread ", name); bool r = device_locker.try_lock(); - oxen::log::debug(logcat, "Device {}{} LOCKed(try)", name, (r ? "" : " not")); + log::debug(logcat, "Device {}{} LOCKed(try)", name, (r ? "" : " not")); return r; } //unlock the device after a long sequence void device_ledger::unlock() { - oxen::log::debug(logcat, "Ask for UNLOCKING for device {} in thread ", name); + log::debug(logcat, "Ask for UNLOCKING for device {} in thread ", name); device_locker.unlock(); - oxen::log::debug(logcat, "Device {} UNLOCKed", name); + log::debug(logcat, "Device {} UNLOCKed", name); } @@ -381,14 +381,14 @@ namespace hw::ledger { #endif cmd << " p=(0x" << std::setw(2) << +buffer_send[2] << ",0x" << std::setw(2) << +buffer_send[3] << ')'; cmd << " sz=0x" << std::setw(2) << +buffer_send[4] << '[' << std::to_string(buffer_send[4]) << "] "; - oxen::log::debug(logcat, "CMD: {}{}", cmd.str(), oxenc::to_hex(buffer_send + 5, buffer_send + length_send)); + log::debug(logcat, "CMD: {}{}", cmd.str(), oxenc::to_hex(buffer_send + 5, buffer_send + length_send)); last_cmd = std::chrono::steady_clock::now(); } } void device_ledger::logRESP() { if (apdu_verbose) - oxen::log::debug(logcat, "RESP (+{}): {} {}", tools::short_duration(std::chrono::steady_clock::now() - last_cmd), oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}), oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); + log::debug(logcat, "RESP (+{}): {} {}", tools::short_duration(std::chrono::steady_clock::now() - last_cmd), oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}), oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); } int device_ledger::set_command_header(unsigned char ins, unsigned char p1, unsigned char p2) { @@ -453,7 +453,7 @@ namespace hw::ledger { } void device_ledger::send_secret(const unsigned char sec[32], int &offset) { - oxen::log::debug(logcat, "send_secret: {}", tx_in_progress); + log::debug(logcat, "send_secret: {}", tx_in_progress); send_bytes(sec, 32, offset); if (tx_in_progress) { CHECK_AND_ASSERT_THROW_MES(offset + 32 <= BUFFER_SEND_SIZE, "send_secret: out of bounds write (mac)"); @@ -463,7 +463,7 @@ namespace hw::ledger { } void device_ledger::receive_secret(unsigned char sec[32], int &offset) { - oxen::log::debug(logcat, "receive_secret: {}", tx_in_progress); + log::debug(logcat, "receive_secret: {}", tx_in_progress); receive_bytes(sec, 32, offset); if (tx_in_progress) { CHECK_AND_ASSERT_THROW_MES(offset + 32 <= BUFFER_RECV_SIZE, "receive_secret: out of bounds read (mac)"); @@ -563,7 +563,7 @@ namespace hw::ledger { #endif release(); hw_device->init(); - oxen::log::debug(logcat, "Device {} HIDUSB inited", id); + log::debug(logcat, "Device {} HIDUSB inited", id); return true; } @@ -653,7 +653,7 @@ namespace hw::ledger { std::string coin{reinterpret_cast(buffer_recv), 4}; auto device_nettype = static_cast(buffer_recv[4]); - oxen::log::debug(logcat, "Ledger wallet is set to {} {}", coin, nettype_string(device_nettype)); + log::debug(logcat, "Ledger wallet is set to {} {}", coin, nettype_string(device_nettype)); if (coin != COIN_NETWORK) throw std::runtime_error{"Invalid wallet app: expected " + std::string{COIN_NETWORK} + ", got " + coin}; if (device_nettype != nettype) @@ -683,7 +683,7 @@ namespace hw::ledger { case mode::NONE: break; } - oxen::log::debug(logcat, "Switch to mode: {}", +static_cast(m)); + log::debug(logcat, "Switch to mode: {}", +static_cast(m)); return device::set_mode(m); } @@ -717,7 +717,7 @@ namespace hw::ledger { //View key is retrieved, if allowed, to speed up blockchain parsing receive_bytes(viewkey.data, 32); has_view_key = !is_fake_view_key(viewkey); - oxen::log::debug(logcat, "{}", (has_view_key ? "Have view key" : "Have no view key")); + log::debug(logcat, "{}", (has_view_key ? "Have view key" : "Have no view key")); #ifdef DEBUG_HWDEVICE send_simple(INS_GET_KEY, 0x04); @@ -784,7 +784,7 @@ namespace hw::ledger { if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { //If we are in TRANSACTION_PARSE, the given derivation has been retrieved uncrypted (wihtout the help //of the device), so continue that way. - oxen::log::debug(logcat, "derive_subaddress_public_key : PARSE mode with known viewkey"); + log::debug(logcat, "derive_subaddress_public_key : PARSE mode with known viewkey"); crypto::derive_subaddress_public_key(pub, derivation, output_index, derived_pub); } else { @@ -1098,7 +1098,7 @@ namespace hw::ledger { if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { //A derivation is requested in PARSE mode and we have the view key, //so do that without the device and return the derivation unencrypted. - oxen::log::debug(logcat, "generate_key_derivation : PARSE mode with known viewkey"); + log::debug(logcat, "generate_key_derivation : PARSE mode with known viewkey"); //Note derivation in PARSE mode can only happen with viewkey, so assert it! assert(is_fake_view_key(sec)); r = crypto::generate_key_derivation(pub, viewkey, derivation); @@ -1130,12 +1130,12 @@ namespace hw::ledger { const crypto::public_key *pkey = nullptr; if (derivation == main_derivation) { pkey = &tx_pub_key; - oxen::log::debug(logcat, "conceal derivation with main tx pub key"); + log::debug(logcat, "conceal derivation with main tx pub key"); } else { for (size_t n = 0; n < additional_derivations.size(); ++n) { if (derivation == additional_derivations[n]) { pkey = &additional_tx_pub_keys[n]; - oxen::log::debug(logcat, "conceal derivation with additionnal tx pub key"); + log::debug(logcat, "conceal derivation with additionnal tx pub key"); break; } } @@ -1431,7 +1431,7 @@ namespace hw::ledger { log_hexbuffer("GENERATE_TX_PROOF: **r** ", sig.r.data, sizeof(sig.r.data)); debug_device->generate_tx_proof(prefix_hash_x, R_x, A_x, B_x, D_x, r_x, sig_x); - oxen::log::debug(logcat, "FAIL is normal if random is not fixed in proof"); + log::debug(logcat, "FAIL is normal if random is not fixed in proof"); check32("generate_tx_proof", "c", sig_x.c.data, sig.c.data); check32("generate_tx_proof", "r", sig_x.r.data, sig.r.data); @@ -1493,7 +1493,7 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE crypto::hash h_x; debug_device->get_transaction_prefix_hash(tx, h_x); - oxen::log::debug(logcat, "get_transaction_prefix_hash [[IN]] h_x/1 {}", h_x); + log::debug(logcat, "get_transaction_prefix_hash [[IN]] h_x/1 {}", h_x); #endif // As of protocol version 4, we send: @@ -1744,7 +1744,7 @@ namespace hw::ledger { receive_bytes(unmasked.mask.bytes, 32, offset); #ifdef DEBUG_HWDEVICE - oxen::log::debug(logcat, "ecdhEncode: Akout: {}", AKout_x); + log::debug(logcat, "ecdhEncode: Akout: {}", AKout_x); check32("ecdhEncode", "amount", unmasked_x.amount.bytes, unmasked.amount.bytes); check32("ecdhEncode", "mask", unmasked_x.mask.bytes, unmasked.mask.bytes); @@ -1776,7 +1776,7 @@ namespace hw::ledger { receive_bytes(masked.mask.bytes, 32, offset); #ifdef DEBUG_HWDEVICE - oxen::log::debug(logcat, "ecdhEncode: Akout: {}", AKout_x); + log::debug(logcat, "ecdhEncode: Akout: {}", AKout_x); check32("ecdhDecode", "amount", masked_x.amount.bytes, masked.amount.bytes); check32("ecdhDecode", "mask", masked_x.mask.bytes, masked.mask.bytes); #endif diff --git a/src/device/io_hid.cpp b/src/device/io_hid.cpp index b90779850..755942627 100644 --- a/src/device/io_hid.cpp +++ b/src/device/io_hid.cpp @@ -34,7 +34,7 @@ namespace hw::io { - static auto logcat = oxen::log::Cat("device.io"); + static auto logcat = log::Cat("device.io"); static constexpr size_t MAX_BLOCK = 64; @@ -71,7 +71,7 @@ namespace hw::io { void hid::io_hid_log(int read, unsigned char* buffer, int block_len) { if (hid_verbose) - oxen::log::debug(logcat, "HID {} : {}", (read ? '<' : '>'), oxenc::to_hex(buffer, buffer + block_len)); + log::debug(logcat, "HID {} : {}", (read ? '<' : '>'), oxenc::to_hex(buffer, buffer + block_len)); } void hid::init() { @@ -90,7 +90,7 @@ namespace hw::io { hid_device_info* hid::find_device(hid_device_info* devices_list, std::optional interface_number, std::optional usage_page) { bool select_any = !interface_number && !usage_page; - oxen::log::debug(logcat, "Looking for {}{}{}{}", (select_any ? "any HID Device" : "HID Device with"), + log::debug(logcat, "Looking for {}{}{}{}", (select_any ? "any HID Device" : "HID Device with"), (interface_number ? (" interface_number " + std::to_string(*interface_number)) : ""), ((interface_number && usage_page) ? " or" : ""), (usage_page ? (" usage_page " + std::to_string(*usage_page)) : "")); @@ -102,7 +102,7 @@ namespace hw::io { || (usage_page && devices_list->usage_page == *usage_page)) result = devices_list; - oxen::log::debug(logcat, "{} HID Device path {} interface_number {} usage_page {}", (result == devices_list ? "SELECTED" : "SKIPPED ") + log::debug(logcat, "{} HID Device path {} interface_number {} usage_page {}", (result == devices_list ? "SELECTED" : "SKIPPED ") ,safe_hid_path(devices_list) ,devices_list->interface_number ,devices_list->usage_page); @@ -117,7 +117,7 @@ namespace hw::io { hid_device_info* hwdev_info_list = hid_enumerate(vid, pid); if (!hwdev_info_list) { - oxen::log::debug(logcat, "Unable to enumerate device {}:{}: {}", vid, pid, safe_hid_error(usb_device)); + log::debug(logcat, "Unable to enumerate device {}:{}: {}", vid, pid, safe_hid_error(usb_device)); return false; } hid_device* hwdev = nullptr; diff --git a/src/device/io_ledger_tcp.cpp b/src/device/io_ledger_tcp.cpp index 953131bf2..aa98049c1 100644 --- a/src/device/io_ledger_tcp.cpp +++ b/src/device/io_ledger_tcp.cpp @@ -6,6 +6,7 @@ #include #include "epee/misc_log_ex.h" #include "logging/oxen_logger.h" +#include "log.hpp" extern "C" { #ifdef _WIN32 @@ -24,7 +25,7 @@ extern "C" { namespace hw::io { -static auto logcat = oxen::log::Cat("device.io"); +static auto logcat = log::Cat("device.io"); static std::string to_string(const addrinfo* a) { std::array buf; @@ -77,7 +78,7 @@ void ledger_tcp::connect() { bool connected = false; const char* err = "An unknown error occurred"; for (a = addr; a && !connected; a = a->ai_next) { - oxen::log::debug(logcat, "Attempting to connect to {}", to_string(a)); + log::debug(logcat, "Attempting to connect to {}", to_string(a)); int rc = ::connect(fd, a->ai_addr, a->ai_addrlen); connected = rc == 0; if (rc == -1) { @@ -103,7 +104,7 @@ void ledger_tcp::connect() { if (!connected) throw std::runtime_error{"Failed to connect to " + host + ":" + port + ": " + err}; - oxen::log::debug(logcat, "Connected to {}", to_string(a)); + log::debug(logcat, "Connected to {}", to_string(a)); #ifdef _WIN32 blocking_param = 0; diff --git a/src/device/log.cpp b/src/device/log.cpp index 0100a21d2..7d94ff518 100644 --- a/src/device/log.cpp +++ b/src/device/log.cpp @@ -34,21 +34,21 @@ namespace hw { - static auto logcat = oxen::log::Cat("device"); + static auto logcat = log::Cat("device"); void log_hexbuffer(std::string_view msg, const void* buff, size_t len) { - oxen::log::debug(logcat, "{}: {}", msg, oxenc::to_hex(std::string_view{reinterpret_cast(buff), len})); + log::debug(logcat, "{}: {}", msg, oxenc::to_hex(std::string_view{reinterpret_cast(buff), len})); } void log_message(std::string_view msg, std::string_view info) { - oxen::log::debug(logcat, "{}: {}", msg, info); + log::debug(logcat, "{}: {}", msg, info); } #ifdef WITH_DEVICE_LEDGER namespace ledger { - static auto logcat = oxen::log::Cat("device.ledger"); + static auto logcat = log::Cat("device.ledger"); #ifdef DEBUG_HWDEVICE diff --git a/src/device_trezor/device_trezor.cpp b/src/device_trezor/device_trezor.cpp index af1e06715..f903d1a70 100644 --- a/src/device_trezor/device_trezor.cpp +++ b/src/device_trezor/device_trezor.cpp @@ -35,7 +35,7 @@ namespace trezor { #ifdef WITH_DEVICE_TREZOR -static auto logcat = oxen::log::Cat("device.trezor"); +static auto logcat = log::Cat("device.trezor"); #define HW_TREZOR_NAME "Trezor" @@ -67,7 +67,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); disconnect(); release(); } catch(std::exception const& e){ - oxen::log::warning(logcat, "Could not disconnect and release: {}", e.what()); + log::warning(logcat, "Could not disconnect and release: {}", e.what()); } } @@ -112,7 +112,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); } catch(const std::exception & e) { - oxen::log::error(logcat, "Live refresh could not be terminated: {}", e.what()); + log::error(logcat, "Live refresh could not be terminated: {}", e.what()); } } @@ -142,14 +142,14 @@ static auto logcat = oxen::log::Cat("device.trezor"); continue; } - oxen::log::trace(logcat, "Closing live refresh process due to inactivity"); + log::trace(logcat, "Closing live refresh process due to inactivity"); try { live_refresh_finish(); } catch(const std::exception &e) { - oxen::log::warning(logcat, "Live refresh auto-finish failed: {}", e.what()); + log::warning(logcat, "Live refresh auto-finish failed: {}", e.what()); } } } @@ -171,14 +171,14 @@ static auto logcat = oxen::log::Cat("device.trezor"); return true; } catch(std::exception const& e){ - oxen::log::error(logcat, "Get public address exception: {}", e.what()); + log::error(logcat, "Get public address exception: {}", e.what()); return false; } } bool device_trezor::get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) { try { - oxen::log::debug(logcat, "Loading view-only key from the Trezor. Please check the Trezor for a confirmation."); + log::debug(logcat, "Loading view-only key from the Trezor. Please check the Trezor for a confirmation."); auto res = get_view_key(); CHECK_AND_ASSERT_MES(res->watch_key().size() == 32, false, "Trezor returned invalid view key"); @@ -195,7 +195,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); return true; } catch(std::exception const& e){ - oxen::log::error(logcat, "Get secret keys exception: {}", e.what()); + log::error(logcat, "Get secret keys exception: {}", e.what()); return false; } } @@ -236,7 +236,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); } auto response = this->client_exchange(req); - oxen::log::trace(logcat, "Get address response received"); + log::trace(logcat, "Get address response received"); return response; } @@ -252,7 +252,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); this->set_msg_addr(req.get(), path, network_type); auto response = this->client_exchange(req); - oxen::log::trace(logcat, "Get watch key response received"); + log::trace(logcat, "Get watch key response received"); return response; } @@ -281,7 +281,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); this->set_msg_addr(req.get()); auto response = this->client_exchange(req); - oxen::log::trace(logcat, "Get TX key response received"); + log::trace(logcat, "Get TX key response received"); protocol::tx::get_tx_key_ack(tx_keys, tx_aux_data.tx_prefix_hash, view_key_priv, response); } @@ -327,7 +327,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); kis.push_back(ckis); } - oxen::log::trace(logcat, "Batch {} / {} batches processed", cur, num_batches); + log::trace(logcat, "Batch {} / {} batches processed", cur, num_batches); EVENT_PROGRESS((double)cur * batch_size / mtds.size()); } EVENT_PROGRESS(1.); @@ -372,7 +372,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); try{ return is_live_refresh_enabled(); } catch(const std::exception & e){ - oxen::log::error(logcat, "Could not detect if live refresh is enabled: {}", e.what()); + log::error(logcat, "Could not detect if live refresh is enabled: {}", e.what()); } return false; } @@ -461,7 +461,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); } catch(const std::exception & e) { - oxen::log::warning(logcat, "KI computation state change failed, started: {}, e: {}", started, e.what()); + log::warning(logcat, "KI computation state change failed, started: {}, e: {}", started, e.what()); } } @@ -524,7 +524,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); // Transaction check try { - oxen::log::debug(logcat, "signed transaction: {}\n{}\n", cryptonote::get_transaction_hash(cpend.tx), cryptonote::obj_to_json_str(cpend.tx)); + log::debug(logcat, "signed transaction: {}\n{}\n", cryptonote::get_transaction_hash(cpend.tx), cryptonote::obj_to_json_str(cpend.tx)); transaction_check(cdata, aux_data); } catch(const std::exception &e){ throw exc::ProtocolException(std::string("Transaction verification failed: ") + e.what()); @@ -687,7 +687,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); if ((env_trezor_client_version = getenv("TREZOR_CLIENT_VERSION")) != nullptr){ auto succ = epee::string_tools::get_xtype_from_string(client_version, env_trezor_client_version); if (succ){ - oxen::log::info(logcat, "Trezor client version overriden by TREZOR_CLIENT_VERSION to: {}", client_version); + log::info(logcat, "Trezor client version overriden by TREZOR_CLIENT_VERSION to: {}", client_version); } } #endif diff --git a/src/device_trezor/device_trezor_base.cpp b/src/device_trezor/device_trezor_base.cpp index ef561596c..a92ee1922 100644 --- a/src/device_trezor/device_trezor_base.cpp +++ b/src/device_trezor/device_trezor_base.cpp @@ -37,7 +37,7 @@ namespace trezor { #ifdef WITH_DEVICE_TREZOR -static auto logcat = oxen::log::Cat("device.trezor"); +static auto logcat = log::Cat("device.trezor"); #define TREZOR_BIP44_HARDENED_ZERO 0x80000000 const uint32_t device_trezor_base::DEFAULT_BIP44_PATH[] = {0x8000002c, 0x80000080}; @@ -53,7 +53,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); disconnect(); release(); } catch(std::exception const& e){ - oxen::log::error(logcat, "Could not disconnect and release: {}", e.what()); + log::error(logcat, "Could not disconnect and release: {}", e.what()); } } @@ -84,7 +84,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); bool device_trezor_base::init() { if (!release()){ - oxen::log::error(logcat, "Release failed"); + log::error(logcat, "Release failed"); return false; } @@ -97,7 +97,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); return true; } catch(std::exception const& e){ - oxen::log::error(logcat, "Release exception: {}", e.what()); + log::error(logcat, "Release exception: {}", e.what()); return false; } } @@ -110,26 +110,26 @@ static auto logcat = oxen::log::Cat("device.trezor"); try { hw::trezor::t_transport_vect trans; - oxen::log::debug(logcat, "Enumerating Trezor devices..."); + log::debug(logcat, "Enumerating Trezor devices..."); enumerate(trans); sort_transports_by_env(trans); - oxen::log::debug(logcat, "Enumeration yielded {} Trezor devices", trans.size()); + log::debug(logcat, "Enumeration yielded {} Trezor devices", trans.size()); for (auto &cur : trans) { - oxen::log::debug(logcat, " device: {}", *(cur.get())); + log::debug(logcat, " device: {}", *(cur.get())); } for (auto &cur : trans) { std::string cur_path = cur->get_path(); if (tools::starts_with(cur_path, name)) { - oxen::log::debug(logcat, "Device Match: {}", cur_path); + log::debug(logcat, "Device Match: {}", cur_path); m_transport = cur; break; } } if (!m_transport) { - oxen::log::error(logcat, "No matching Trezor device found. Device specifier: \"{}\"", name); + log::error(logcat, "No matching Trezor device found. Device specifier: \"{}\"", name); return false; } @@ -141,7 +141,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); return true; } catch(std::exception const& e){ - oxen::log::error(logcat, "Open exception: {}", e.what()); + log::error(logcat, "Open exception: {}", e.what()); return false; } } @@ -157,7 +157,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); m_transport = nullptr; } catch(std::exception const& e){ - oxen::log::error(logcat, "Disconnect exception: {}", e.what()); + log::error(logcat, "Disconnect exception: {}", e.what()); m_transport = nullptr; return false; } @@ -178,28 +178,28 @@ static auto logcat = oxen::log::Cat("device.trezor"); //lock the device for a long sequence void device_trezor_base::lock() { - oxen::log::trace(logcat, "Ask for LOCKING for device {} in thread ", name); + log::trace(logcat, "Ask for LOCKING for device {} in thread ", name); device_locker.lock(); - oxen::log::trace(logcat, "Device {} LOCKed", name); + log::trace(logcat, "Device {} LOCKed", name); } //lock the device for a long sequence bool device_trezor_base::try_lock() { - oxen::log::trace(logcat, "Ask for LOCKING(try) for device {} in thread ", name); + log::trace(logcat, "Ask for LOCKING(try) for device {} in thread ", name); bool r = device_locker.try_lock(); if (r) { - oxen::log::trace(logcat, "Device {} LOCKed(try)", name); + log::trace(logcat, "Device {} LOCKed(try)", name); } else { - oxen::log::debug(logcat, "Device {} not LOCKed(try)", name); + log::debug(logcat, "Device {} not LOCKed(try)", name); } return r; } //unlock the device void device_trezor_base::unlock() { - oxen::log::trace(logcat, "Ask for UNLOCKING for device {} in thread ", name); + log::trace(logcat, "Ask for UNLOCKING for device {} in thread ", name); device_locker.unlock(); - oxen::log::trace(logcat, "Device {} UNLOCKed", name); + log::trace(logcat, "Device {} UNLOCKed", name); } /* ======================================================================= */ @@ -236,7 +236,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); pingMsg->set_message("PING"); auto success = client_exchange(pingMsg); // messages::MessageType_Success - oxen::log::debug(logcat, "Ping response {}", success->message()); + log::debug(logcat, "Ping response {}", success->message()); (void)success; } @@ -247,7 +247,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); call_ping_unsafe(); } catch(exc::TrezorException const& e){ - oxen::log::info(logcat, "Trezor does not respond: {}", e.what()); + log::info(logcat, "Trezor does not respond: {}", e.what()); throw exc::DeviceNotResponsiveException(std::string("Trezor not responding: ") + e.what()); } } @@ -340,7 +340,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); bool device_trezor_base::ping() { auto locks = tools::unique_locks(device_locker, command_locker); if (!m_transport){ - oxen::log::info(logcat, "Ping failed, device not connected"); + log::info(logcat, "Ping failed, device not connected"); return false; } @@ -349,9 +349,9 @@ static auto logcat = oxen::log::Cat("device.trezor"); return true; } catch(std::exception const& e) { - oxen::log::error(logcat, "Ping failed, exception thrown {}", e.what()); + log::error(logcat, "Ping failed, exception thrown {}", e.what()); } catch(...){ - oxen::log::error(logcat, "Ping failed, general exception thrown"); + log::error(logcat, "Ping failed, general exception thrown"); } return false; @@ -408,7 +408,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); if (debug_transport) { m_debug_callback = std::make_shared(debug_transport); } else { - oxen::log::debug(logcat, "Transport does not have debug link option"); + log::debug(logcat, "Transport does not have debug link option"); } } } @@ -421,7 +421,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); void device_trezor_base::on_button_request(GenericMessage & resp, const messages::common::ButtonRequest * msg) { CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); - oxen::log::debug(logcat, "on_button_request, code: {}", msg->code()); + log::debug(logcat, "on_button_request, code: {}", msg->code()); TREZOR_CALLBACK(on_button_request, msg->code()); @@ -438,7 +438,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); void device_trezor_base::on_pin_request(GenericMessage & resp, const messages::common::PinMatrixRequest * msg) { - oxen::log::debug(logcat, "on_pin_request"); + log::debug(logcat, "on_pin_request"); CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); std::optional pin; @@ -468,7 +468,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); void device_trezor_base::on_passphrase_request(GenericMessage & resp, const messages::common::PassphraseRequest * msg) { CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); - oxen::log::debug(logcat, "on_passhprase_request"); + log::debug(logcat, "on_passhprase_request"); // Backward compatibility, migration clause. if (msg->has__on_device() && msg->_on_device()){ @@ -524,7 +524,7 @@ static auto logcat = oxen::log::Cat("device.trezor"); void device_trezor_base::on_passphrase_state_request(GenericMessage & resp, const messages::common::Deprecated_PassphraseStateRequest * msg) { - oxen::log::debug(logcat, "on_passhprase_state_request"); + log::debug(logcat, "on_passhprase_state_request"); CHECK_AND_ASSERT_THROW_MES(msg, "Empty message"); if (msg->has_state()) { diff --git a/src/device_trezor/trezor/transport.cpp b/src/device_trezor/trezor/transport.cpp index 8e8f903db..e66d074a2 100644 --- a/src/device_trezor/trezor/transport.cpp +++ b/src/device_trezor/trezor/transport.cpp @@ -302,12 +302,12 @@ namespace trezor{ bool Transport::pre_open(){ if (m_open_counter > 0){ - oxen::log::trace(logcat, "Already opened, count: {}", m_open_counter); + log::trace(logcat, "Already opened, count: {}", m_open_counter); m_open_counter += 1; return false; } else if (m_open_counter < 0){ - oxen::log::trace(logcat, "Negative open value: {}", m_open_counter); + log::trace(logcat, "Negative open value: {}", m_open_counter); } @@ -320,7 +320,7 @@ namespace trezor{ m_open_counter -= 1; if (m_open_counter < 0){ - oxen::log::debug(logcat, "Already closed. Counter {}", m_open_counter); + log::debug(logcat, "Already closed. Counter {}", m_open_counter); } else if (m_open_counter == 0) { return true; @@ -353,7 +353,7 @@ namespace trezor{ } else if (!tools::starts_with(m_bridge_url, "http://") && !tools::starts_with(m_bridge_url, "https://")) m_bridge_url.insert(0, "http://"); - oxen::log::debug(logcat, "Bridge host: {}", m_bridge_url); + log::debug(logcat, "Bridge host: {}", m_bridge_url); } std::string BridgeTransport::get_path() const { @@ -386,11 +386,11 @@ namespace trezor{ const auto id_product = (uint16_t) itr_product->value.GetUint64(); const auto device_idx = get_device_idx(id_vendor, id_product); if (!is_device_supported(device_idx)){ - oxen::log::debug(logcat, "Device with idx {} is not supported. Vendor: {}, product: {}", device_idx, id_vendor, id_product); + log::debug(logcat, "Device with idx {} is not supported. Vendor: {}, product: {}", device_idx, id_vendor, id_product); continue; } } catch(const std::exception &e){ - oxen::log::error(logcat, "Could not detect vendor & product: {}", e.what()); + log::error(logcat, "Could not detect vendor & product: {}", e.what()); } } @@ -426,7 +426,7 @@ namespace trezor{ return; } - oxen::log::trace(logcat, "Closing Trezor:BridgeTransport"); + log::trace(logcat, "Closing Trezor:BridgeTransport"); if (!m_device_path || !m_session){ throw exc::CommunicationException("Device not open"); } @@ -580,7 +580,7 @@ namespace trezor{ parse_udp_path(m_device_host, m_device_port, *device_path); } else if ((env_trezor_path = getenv("TREZOR_PATH")) != nullptr && tools::starts_with(env_trezor_path, UdpTransport::PATH_PREFIX)){ parse_udp_path(m_device_host, m_device_port, std::string(env_trezor_path)); - oxen::log::debug(logcat, "Applied TREZOR_PATH: {}:{}", m_device_host, m_device_port); + log::debug(logcat, "Applied TREZOR_PATH: {}:{}", m_device_host, m_device_port); } else { m_device_host = DEFAULT_HOST; } @@ -664,7 +664,7 @@ namespace trezor{ return; } - oxen::log::trace(logcat, "Closing Trezor:UdpTransport"); + log::trace(logcat, "Closing Trezor:UdpTransport"); if (!m_socket) { throw exc::CommunicationException("Socket is already closed"); } @@ -682,7 +682,7 @@ namespace trezor{ t->m_device_port = m_device_port + 1; return t; #else - oxen::log::info(logcat, "Debug link is disabled in production"); + log::info(logcat, "Debug link is disabled in production"); return nullptr; #endif } @@ -726,7 +726,7 @@ namespace trezor{ } catch(exc::CommunicationException const& e){ throw; } catch(std::exception const& e){ - oxen::log::warning(logcat, "Error reading chunk, reason: {}", e.what()); + log::warning(logcat, "Error reading chunk, reason: {}", e.what()); throw exc::CommunicationException(std::string("Chunk read error: ") + std::string(e.what())); } } @@ -774,7 +774,7 @@ namespace trezor{ throw exc::TimeoutException(); } else if (ec) { - oxen::log::warning(logcat, "Reading from UDP socket failed: {}", ec.message()); + log::warning(logcat, "Reading from UDP socket failed: {}", ec.message()); throw exc::CommunicationException(); } @@ -945,13 +945,13 @@ namespace trezor{ throw std::runtime_error("Unable to enumerate libusb devices"); } - oxen::log::trace(logcat, "Libusb devices: {}", cnt); + log::trace(logcat, "Libusb devices: {}", cnt); for(ssize_t i = 0; i < cnt; i++) { libusb_device_descriptor desc{}; r = libusb_get_device_descriptor(devs[i], &desc); if (r < 0){ - oxen::log::error(logcat, "Unable to get libusb device descriptor {}", i); + log::error(logcat, "Unable to get libusb device descriptor {}", i); continue; } @@ -960,7 +960,7 @@ namespace trezor{ continue; } - oxen::log::trace(logcat, "Found Trezor device: {}:{} dev_idx {}", desc.idVendor, desc.idProduct, (int)trezor_dev_idx); + log::trace(logcat, "Found Trezor device: {}:{} dev_idx {}", desc.idVendor, desc.idProduct, (int)trezor_dev_idx); auto t = std::make_shared(std::make_optional(&desc)); t->m_bus_id = libusb_get_bus_number(devs[i]); @@ -1016,7 +1016,7 @@ namespace trezor{ libusb_device_descriptor desc{}; r = libusb_get_device_descriptor(devs[i], &desc); if (r < 0){ - oxen::log::error(logcat, "Unable to get libusb device descriptor {}", i); + log::error(logcat, "Unable to get libusb device descriptor {}", i); continue; } @@ -1031,7 +1031,7 @@ namespace trezor{ // Port resolution may fail. Non-critical error, just addressing precision is decreased. get_libusb_ports(devs[i], path); - oxen::log::trace(logcat, "Found Trezor device: {}:{}", desc.idVendor, desc.idProduct + log::trace(logcat, "Found Trezor device: {}:{}", desc.idVendor, desc.idProduct << ", dev_idx: " << (int)trezor_dev_idx << ". path: " << get_usb_path(bus_id, path)); @@ -1077,12 +1077,12 @@ namespace trezor{ return; } - oxen::log::trace(logcat, "Closing Trezor:WebUsbTransport"); + log::trace(logcat, "Closing Trezor:WebUsbTransport"); m_proto->session_end(*this); int r = libusb_release_interface(m_usb_device_handle, get_interface()); if (r != 0){ - oxen::log::error(logcat, "Could not release libusb interface: {}", r); + log::error(logcat, "Could not release libusb interface: {}", r); } m_usb_device = nullptr; @@ -1107,7 +1107,7 @@ namespace trezor{ t->m_debug_mode = true; return t; #else - oxen::log::info(logcat, "Debug link is disabled in production"); + log::info(logcat, "Debug link is disabled in production"); return nullptr; #endif } @@ -1199,7 +1199,7 @@ namespace trezor{ try{ bt.enumerate(res); } catch (const std::exception & e){ - oxen::log::error(logcat, "BridgeTransport enumeration failed:{}", e.what()); + log::error(logcat, "BridgeTransport enumeration failed:{}", e.what()); } #ifdef WITH_DEVICE_TREZOR_WEBUSB @@ -1207,7 +1207,7 @@ namespace trezor{ try{ btw.enumerate(res); } catch (const std::exception & e){ - oxen::log::error(logcat, "WebUsbTransport enumeration failed:{}", e.what()); + log::error(logcat, "WebUsbTransport enumeration failed:{}", e.what()); } #endif @@ -1216,7 +1216,7 @@ namespace trezor{ try{ btu.enumerate(res); } catch (const std::exception & e){ - oxen::log::error(logcat, "UdpTransport enumeration failed:{}", e.what()); + log::error(logcat, "UdpTransport enumeration failed:{}", e.what()); } #endif } diff --git a/src/gen_multisig/gen_multisig.cpp b/src/gen_multisig/gen_multisig.cpp index 774638684..4b428bef0 100644 --- a/src/gen_multisig/gen_multisig.cpp +++ b/src/gen_multisig/gen_multisig.cpp @@ -48,7 +48,6 @@ #include "wallet/wallet2.h" using namespace cryptonote; -using boost::lexical_cast; namespace po = boost::program_options; namespace genms @@ -61,7 +60,7 @@ namespace genms namespace { - static auto logcat = oxen::log::Cat("wallet.gen_multisig"); + static auto logcat = log::Cat("wallet.gen_multisig"); const command_line::arg_descriptor arg_filename_base = {"filename-base", genms::tr("Base filename (-1, -2, etc suffixes will be appended as needed)"), ""}; const command_line::arg_descriptor arg_scheme = {"scheme", genms::tr("Give threshold and participants at once as M/N"), ""}; diff --git a/src/logging/oxen_logger.cpp b/src/logging/oxen_logger.cpp index 66bd74c8b..335d1b8d2 100644 --- a/src/logging/oxen_logger.cpp +++ b/src/logging/oxen_logger.cpp @@ -7,10 +7,10 @@ namespace oxen::logging { - static auto logcat = oxen::log::Cat("logging"); + static auto logcat = log::Cat("logging"); void - set_additional_log_categories(oxen::log::Level& log_level) + set_additional_log_categories(log::Level& log_level) { switch (log_level) { @@ -79,7 +79,7 @@ namespace oxen::logging } void - init(const std::string& log_location, oxen::log::Level log_level) + init(const std::string& log_location, log::Level log_level) { log::reset_level(log_level); log::add_sink(log::Type::Print, "stdout"); @@ -114,19 +114,19 @@ namespace oxen::logging using namespace std::literals; - static constexpr std::array, 12> logLevels = { - {{""sv, oxen::log::Level::info}, - {"4"sv, oxen::log::Level::trace}, - {"3", oxen::log::Level::trace}, - {"2", oxen::log::Level::debug}, - {"1", oxen::log::Level::info}, - {"0", oxen::log::Level::warn}, - {"trace", oxen::log::Level::trace}, - {"debug", oxen::log::Level::debug}, - {"info", oxen::log::Level::info}, - {"warning", oxen::log::Level::warn}, - {"error", oxen::log::Level::err}, - {"critical", oxen::log::Level::critical}}}; + static constexpr std::array, 12> logLevels = { + {{""sv, log::Level::info}, + {"4"sv, log::Level::trace}, + {"3", log::Level::trace}, + {"2", log::Level::debug}, + {"1", log::Level::info}, + {"0", log::Level::warn}, + {"trace", log::Level::trace}, + {"debug", log::Level::debug}, + {"info", log::Level::info}, + {"warning", log::Level::warn}, + {"error", log::Level::err}, + {"critical", log::Level::critical}}}; std::optional parse_level(std::string_view input) @@ -137,12 +137,12 @@ namespace oxen::logging return std::nullopt; } - static constexpr std::array, 5> intLogLevels = { - {{4, oxen::log::Level::trace}, - {3, oxen::log::Level::trace}, - {2, oxen::log::Level::debug}, - {1, oxen::log::Level::info}, - {0, oxen::log::Level::warn}}}; + static constexpr std::array, 5> intLogLevels = { + {{4, log::Level::trace}, + {3, log::Level::trace}, + {2, log::Level::debug}, + {1, log::Level::info}, + {0, log::Level::warn}}}; std::optional parse_level(uint8_t input) @@ -153,13 +153,13 @@ namespace oxen::logging return std::nullopt; } - static constexpr std::array, 6> omqLogLevels = { - {{oxenmq::LogLevel::trace, oxen::log::Level::trace}, - {oxenmq::LogLevel::debug, oxen::log::Level::debug}, - {oxenmq::LogLevel::info, oxen::log::Level::info}, - {oxenmq::LogLevel::warn, oxen::log::Level::warn}, - {oxenmq::LogLevel::error, oxen::log::Level::err}, - {oxenmq::LogLevel::fatal, oxen::log::Level::critical}}}; + static constexpr std::array, 6> omqLogLevels = { + {{oxenmq::LogLevel::trace, log::Level::trace}, + {oxenmq::LogLevel::debug, log::Level::debug}, + {oxenmq::LogLevel::info, log::Level::info}, + {oxenmq::LogLevel::warn, log::Level::warn}, + {oxenmq::LogLevel::error, log::Level::err}, + {oxenmq::LogLevel::fatal, log::Level::critical}}}; std::optional parse_level(oxenmq::LogLevel input) diff --git a/src/logging/oxen_logger.h b/src/logging/oxen_logger.h index efa00d509..f86b1096d 100644 --- a/src/logging/oxen_logger.h +++ b/src/logging/oxen_logger.h @@ -7,22 +7,30 @@ #define OXEN_LOG_ENABLED(LVL) logcat->should_log(spdlog::level::LVL) +// We can't just make a global "log" namespace because it conflicts with global C log() +namespace cryptonote { namespace log = oxen::log; } +namespace crypto { namespace log = oxen::log; } +namespace tools { namespace log = oxen::log; } +namespace service_nodes { namespace log = oxen::log; } +namespace nodetool { namespace log = oxen::log; } +namespace rct { namespace log = oxen::log; } + inline auto globallogcat = oxen::log::Cat("global"); namespace oxen::logging { void - init(const std::string& log_location, oxen::log::Level log_level); + init(const std::string& log_location, log::Level log_level); void - set_additional_log_categories(const oxen::log::Level& log_level); + set_additional_log_categories(const log::Level& log_level); void process_categories_string(const std::string& categories); - std::optional + std::optional parse_level(std::string_view input); - std::optional + std::optional parse_level(uint8_t input); - std::optional + std::optional parse_level(oxenmq::LogLevel input); } // namespace oxen::logging diff --git a/src/mnemonics/electrum-words.cpp b/src/mnemonics/electrum-words.cpp index 0345d1034..f460591d4 100644 --- a/src/mnemonics/electrum-words.cpp +++ b/src/mnemonics/electrum-words.cpp @@ -69,11 +69,10 @@ namespace crypto { std::vector get_language_list(); } -} namespace { - static auto logcat = oxen::log::Cat("mnemonic"); + auto logcat = log::Cat("mnemonic"); uint32_t create_checksum_index(const std::vector &word_list, const Language::Base *language); @@ -160,7 +159,7 @@ namespace if (full_match) { *language = *it1; - oxen::log::info(logcat, "Full match for language {}", (*language)->get_english_language_name()); + log::info(logcat, "Full match for language {}", (*language)->get_english_language_name()); return true; } // Some didn't match. Clear the index array. @@ -174,11 +173,11 @@ namespace if (fallback) { *language = fallback; - oxen::log::info(logcat, "Fallback match for language {}", (*language)->get_english_language_name()); + log::info(logcat, "Fallback match for language {}", (*language)->get_english_language_name()); return true; } - oxen::log::info(logcat, "No match found"); + log::info(logcat, "No match found"); memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0])); return false; } @@ -234,18 +233,11 @@ namespace epee::wipeable_string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) : last_word; bool ret = Language::WordEqual()(trimmed_checksum, trimmed_last_word); - oxen::log::info(logcat, "Checksum is {}", (ret ? "valid" : "invalid")); + log::info(logcat, "Checksum is {}", (ret ? "valid" : "invalid")); return ret; } } -/*! - * \namespace crypto - * - * \brief crypto namespace. - */ -namespace crypto -{ /*! * \namespace crypto::ElectrumWords * @@ -271,7 +263,7 @@ namespace crypto if (len % 4) { - oxen::log::error(logcat, "Invalid seed: not a multiple of 4"); + log::error(logcat, "Invalid seed: not a multiple of 4"); return false; } @@ -283,7 +275,7 @@ namespace crypto if (seed.size() != expected/2 && seed.size() != expected && seed.size() != expected + 1) { - oxen::log::error(logcat, "Invalid seed: unexpected number of words"); + log::error(logcat, "Invalid seed: unexpected number of words"); return false; } @@ -296,7 +288,7 @@ namespace crypto Language::Base *language; if (!find_seed_language(seed, has_checksum, matched_indices, &language)) { - oxen::log::error(logcat, "Invalid seed: language not found"); + log::error(logcat, "Invalid seed: language not found"); return false; } language_name = language->get_language_name(); @@ -307,7 +299,7 @@ namespace crypto if (!checksum_test(seed, language)) { // Checksum fail - oxen::log::error(logcat, "Invalid seed: invalid checksum"); + log::error(logcat, "Invalid seed: invalid checksum"); return false; } seed.pop_back(); @@ -326,7 +318,7 @@ namespace crypto if (!(w[0]% word_list_length == w[1])) { memwipe(w, sizeof(w)); - oxen::log::error(logcat, "Invalid seed: mumble mumble"); + log::error(logcat, "Invalid seed: mumble mumble"); return false; } @@ -360,12 +352,12 @@ namespace crypto epee::wipeable_string s; if (!words_to_bytes(words, s, sizeof(dst), true, language_name)) { - oxen::log::error(logcat, "Invalid seed: failed to convert words to bytes"); + log::error(logcat, "Invalid seed: failed to convert words to bytes"); return false; } if (s.size() != sizeof(dst)) { - oxen::log::error(logcat, "Invalid seed: wrong output size"); + log::error(logcat, "Invalid seed: wrong output size"); return false; } dst = *(const crypto::secret_key*)s.data(); diff --git a/src/mnemonics/language_base.h b/src/mnemonics/language_base.h index 720deaa33..11a9ccbb1 100644 --- a/src/mnemonics/language_base.h +++ b/src/mnemonics/language_base.h @@ -38,6 +38,7 @@ #include #include #include +#include "epee/wipeable_string.h" #include "logging/oxen_logger.h" /*! @@ -46,6 +47,9 @@ */ namespace Language { + + namespace log = oxen::log; + /*! * \brief Returns a string made of (at most) the first count characters in s. * Assumes well formedness. No check is made for this. @@ -182,7 +186,6 @@ namespace Language */ void populate_maps(uint32_t flags = 0) { - auto logcat = oxen::log::Cat("global"); int ii; std::vector::const_iterator it; if (word_list.size () != NWORDS) @@ -193,7 +196,7 @@ namespace Language if ((*it).size() < unique_prefix_length) { if (flags & ALLOW_SHORT_WORDS) - oxen::log::debug(logcat, "{} word '{}' is shorter than its prefix length, {}", language_name, *it, unique_prefix_length); + log::debug(globallogcat, "{} word '{}' is shorter than its prefix length, {}", language_name, *it, unique_prefix_length); else throw std::runtime_error("Too short word in " + language_name + " word list: " + *it); } @@ -209,7 +212,7 @@ namespace Language if (trimmed_word_map.find(trimmed) != trimmed_word_map.end()) { if (flags & ALLOW_DUPLICATE_PREFIXES) - oxen::log::warning(logcat, "Duplicate prefix in {} word list: {}", language_name, std::string(trimmed.data(), trimmed.size())); + log::warning(globallogcat, "Duplicate prefix in {} word list: {}", language_name, std::string(trimmed.data(), trimmed.size())); else throw std::runtime_error("Duplicate prefix in " + language_name + " word list: " + std::string(trimmed.data(), trimmed.size())); } diff --git a/src/multisig/multisig.cpp b/src/multisig/multisig.cpp index d6b786f34..16bc2880d 100644 --- a/src/multisig/multisig.cpp +++ b/src/multisig/multisig.cpp @@ -39,9 +39,6 @@ using namespace std; namespace cryptonote { - - static auto logcat = oxen::log::Cat("multisig"); - //----------------------------------------------------------------- crypto::secret_key get_multisig_blinded_secret_key(const crypto::secret_key &key) { diff --git a/src/p2p/net_node.cpp b/src/p2p/net_node.cpp index b744523e4..82dc5b72b 100644 --- a/src/p2p/net_node.cpp +++ b/src/p2p/net_node.cpp @@ -48,8 +48,10 @@ #include "p2p/p2p_protocol_defs.h" #include "epee/string_tools.h" -namespace +namespace nodetool { + namespace { + constexpr const std::chrono::milliseconds future_poll_interval = 500ms; constexpr const std::chrono::seconds socks_connect_timeout{cryptonote::p2p::DEFAULT_SOCKS_CONNECT_TIMEOUT}; @@ -71,7 +73,7 @@ namespace expect address = T::make(value); if (!address) { - oxen::log::error("Failed to parse " << T::get_zone() << " address \"" << value << "\": " << address.error().message()); + log::error("Failed to parse " << T::get_zone() << " address \"" << value << "\": " << address.error().message()); return {}; } return {std::move(*address)}; @@ -91,7 +93,7 @@ namespace set = client->set_connect_command(remote.as()); break; default: - oxen::log::error(globallogcat, "Unsupported network address in socks_connect"); + log::error(globallogcat, "Unsupported network address in socks_connect"); return false; } @@ -100,10 +102,9 @@ namespace CHECK_AND_ASSERT_MES(sent, false, "Unexpected failure to init socks client"); return true; } -} -namespace nodetool -{ + } // anonymous namespace + const command_line::arg_descriptor arg_p2p_bind_ip = {"p2p-bind-ip", "Interface for p2p network protocol (IPv4)", "0.0.0.0"}; const command_line::arg_descriptor arg_p2p_bind_ipv6_address = {"p2p-bind-ipv6-address", "Interface for p2p network protocol (IPv6)", "::"}; const command_line::arg_descriptor arg_p2p_bind_port = { @@ -187,14 +188,14 @@ namespace nodetool set_proxy.max_connections = get_max_connections(*it); if (set_proxy.max_connections == 0) { - oxen::log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); + log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); return std::nullopt; } ++it; } if (it != pieces.end()) { - oxen::log::error(globallogcat, "Too many ',' characters given to --{}", arg_tx_proxy.name); + log::error(globallogcat, "Too many ',' characters given to --{}", arg_tx_proxy.name); return std::nullopt; } @@ -207,7 +208,7 @@ namespace nodetool set_proxy.zone = epee::net_utils::zone::i2p; break; default: - oxen::log::error(globallogcat, "Invalid network for --{}", arg_tx_proxy.name); + log::error(globallogcat, "Invalid network for --{}", arg_tx_proxy.name); return std::nullopt; } @@ -215,7 +216,7 @@ namespace nodetool std::uint16_t port = 0; if (!epee::string_tools::parse_peer_from_string(ip, port, proxy) || port == 0) { - oxen::log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_tx_proxy.name); + log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_tx_proxy.name); return std::nullopt; } set_proxy.address = ip::tcp::endpoint{ip::address_v4{oxenc::host_to_big(ip)}, port}; @@ -249,7 +250,7 @@ namespace nodetool set_inbound.max_connections = get_max_connections(pieces[2]); if (set_inbound.max_connections == 0) { - oxen::log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); + log::error(globallogcat, "Invalid max connections given to --{}", arg_tx_proxy.name); return std::nullopt; } } @@ -266,7 +267,7 @@ namespace nodetool set_inbound.default_remote = net::i2p_address::unknown(); break; default: - oxen::log::error(globallogcat, "Invalid inbound address ({}) for --{}: {}", address, arg_anonymous_inbound.name, (our_address ? "invalid type" : our_address.error().message())); + log::error(globallogcat, "Invalid inbound address ({}) for --{}: {}", address, arg_anonymous_inbound.name, (our_address ? "invalid type" : our_address.error().message())); return std::nullopt; } @@ -278,7 +279,7 @@ namespace nodetool std::uint16_t port = 0; if (!epee::string_tools::parse_peer_from_string(ip, port, bind)) { - oxen::log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_anonymous_inbound.name); + log::error(globallogcat, "Invalid ipv4:port given for --{}", arg_anonymous_inbound.name); return std::nullopt; } set_inbound.local_ip = bind.substr(0, colon); @@ -303,7 +304,7 @@ namespace nodetool if (address.get_zone() == epee::net_utils::zone::public_) return false; - oxen::log::warning(globallogcat, "Filtered command (#{}) to/from {}", command, address.str()); + log::warning(globallogcat, "Filtered command (#{}) to/from {}", command, address.str()); return true; } @@ -340,7 +341,7 @@ namespace nodetool { if (socks_connect_timeout < std::chrono::steady_clock::now() - start) { - oxen::log::error(globallogcat, "Timeout on socks connect ({} to {})", proxy.address().to_string(), remote.str()); + log::error(globallogcat, "Timeout on socks connect ({} to {})", proxy.address().to_string(), remote.str()); return std::nullopt; } @@ -354,7 +355,7 @@ namespace nodetool if (!result.first) return {std::move(result.second)}; - oxen::log::error(globallogcat, "Failed to make socks connection to {} (via {}): {}", remote.str(), proxy.address().to_string(), result.first.message()); + log::error(globallogcat, "Failed to make socks connection to {} (via {}): {}", remote.str(), proxy.address().to_string(), result.first.message()); } catch (const std::future_error&) {} diff --git a/src/p2p/net_node.h b/src/p2p/net_node.h index 26b34a27e..6833c58c5 100644 --- a/src/p2p/net_node.h +++ b/src/p2p/net_node.h @@ -369,11 +369,11 @@ namespace nodetool bool check_incoming_connections(); void kill() { ///< will be called e.g. from deinit() - oxen::log::info(globallogcat, "Killing the net_node"); + log::info(globallogcat, "Killing the net_node"); is_closing = true; if(mPeersLoggerThread) mPeersLoggerThread->join(); // make sure the thread finishes - oxen::log::info(globallogcat, "Joined extra background net_node threads"); + log::info(globallogcat, "Joined extra background net_node threads"); } //debug functions diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index 77644ab19..cf76ab6d5 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -67,7 +67,7 @@ namespace nodetool { - static auto logcat = oxen::log::Cat("net.p2p"); + static auto logcat = log::Cat("net.p2p"); template node_server::~node_server() @@ -167,7 +167,7 @@ namespace nodetool if (now >= it->second) { m_blocked_hosts.erase(it); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked.", address.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked.", address.host_str())); it = m_blocked_hosts.end(); } else @@ -188,7 +188,7 @@ namespace nodetool if (now >= it->second) { it = m_blocked_subnets.erase(it); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} unblocked", it->first.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} unblocked", it->first.host_str())); continue; } if (it->first.matches(ipv4_address)) @@ -241,7 +241,7 @@ namespace nodetool conns.clear(); } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} blocked", addr.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} blocked", addr.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -253,7 +253,7 @@ namespace nodetool if (i == m_blocked_hosts.end()) return false; m_blocked_hosts.erase(i); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked", address.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked", address.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -293,7 +293,7 @@ namespace nodetool conns.clear(); } - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} blocked.", subnet.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} blocked.", subnet.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -305,7 +305,7 @@ namespace nodetool if (i == m_blocked_subnets.end()) return false; m_blocked_subnets.erase(i); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {}", subnet.host_str())); + log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {}", subnet.host_str())); return true; } //----------------------------------------------------------------------------------- @@ -317,7 +317,7 @@ namespace nodetool std::lock_guard lock{m_host_fails_score_lock}; uint64_t fails = ++m_host_fails_score[address.host_str()]; - oxen::log::debug(logcat, "Host {} fail score={}", address.host_str(), fails); + log::debug(logcat, "Host {} fail score={}", address.host_str(), fails); if(fails > cryptonote::p2p::IP_FAILS_BEFORE_BLOCK) { auto it = m_host_fails_score.find(address.host_str()); @@ -448,7 +448,7 @@ namespace nodetool network_zone& zone = add_zone(proxy.zone); if (zone.m_connect != nullptr) { - oxen::log::error(logcat, "Listed --{} twice", arg_tx_proxy.name); + log::error(logcat, "Listed --{} twice", arg_tx_proxy.name); return false; } zone.m_connect = &socks_connect; @@ -476,7 +476,7 @@ namespace nodetool { if (zone.second.m_connect == nullptr) { - oxen::log::error(logcat, "Set outgoing peer for zone but did not set --{}", arg_tx_proxy.name); + log::error(logcat, "Set outgoing peer for zone but did not set --{}", arg_tx_proxy.name); return false; } } @@ -492,13 +492,13 @@ namespace nodetool if (!zone.m_bind_ip.empty()) { - oxen::log::error(logcat, "Listed--{} twice", arg_anonymous_inbound.name); + log::error(logcat, "Listed--{} twice", arg_anonymous_inbound.name); return false; } if (zone.m_connect == nullptr && tx_relay_zones <= 1) { - oxen::log::error(logcat, "Listed --{} without listing any --{}. The latter is necessary for sending local txes over anonymity networks", arg_anonymous_inbound.name, arg_tx_proxy.name); + log::error(logcat, "Listed --{} without listing any --{}. The latter is necessary for sending local txes over anonymity networks", arg_anonymous_inbound.name, arg_tx_proxy.name); return false; } @@ -541,7 +541,7 @@ namespace nodetool port = std::to_string(default_port); } - oxen::log::info(logcat, "Resolving node address: host={}, port={}", host, port); + log::info(logcat, "Resolving node address: host={}, port={}", host, port); io_service io_srv; ip::tcp::resolver resolver(io_srv); @@ -558,13 +558,13 @@ namespace nodetool { epee::net_utils::network_address na{epee::net_utils::ipv4_network_address{boost::asio::detail::socket_ops::host_to_network_long(endpoint.address().to_v4().to_ulong()), endpoint.port()}}; seed_nodes.push_back(na); - oxen::log::info(logcat, "Added node: {}", na.str()); + log::info(logcat, "Added node: {}", na.str()); } else { epee::net_utils::network_address na{epee::net_utils::ipv6_network_address{endpoint.address().to_v6(), endpoint.port()}}; seed_nodes.push_back(na); - oxen::log::info(logcat, "Added node: {}", na.str()); + log::info(logcat, "Added node: {}", na.str()); } } return true; @@ -700,32 +700,32 @@ namespace nodetool std::string ipv6_addr = ""; std::string ipv6_port = ""; zone.second.m_net_server.set_connection_filter(this); - oxen::log::info(logcat, "Binding (IPv4) on {}:{}", zone.second.m_bind_ip, zone.second.m_port); + log::info(logcat, "Binding (IPv4) on {}:{}", zone.second.m_bind_ip, zone.second.m_port); if (!zone.second.m_bind_ipv6_address.empty() && m_use_ipv6) { ipv6_addr = zone.second.m_bind_ipv6_address; ipv6_port = zone.second.m_port_ipv6; - oxen::log::info(logcat, "Binding (IPv6) on {}:{}", zone.second.m_bind_ipv6_address, zone.second.m_port_ipv6); + log::info(logcat, "Binding (IPv6) on {}:{}", zone.second.m_bind_ipv6_address, zone.second.m_port_ipv6); } try { res = zone.second.m_net_server.init_server(zone.second.m_port, zone.second.m_bind_ip, ipv6_port, ipv6_addr, m_use_ipv6, m_require_ipv4); CHECK_AND_ASSERT_MES(res, false, "Failed to bind server"); } catch (const std::exception& e) { - oxen::log::error(logcat, "{}", e.what()); + log::error(logcat, "{}", e.what()); res = false; } } } m_listening_port = public_zone.m_net_server.get_binded_port(); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv4) to {}:{}", public_zone.m_bind_ip, m_listening_port)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv4) to {}:{}", public_zone.m_bind_ip, m_listening_port)); if (m_use_ipv6) { m_listening_port_ipv6 = public_zone.m_net_server.get_binded_port_ipv6(); - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv6) to {}:{}", public_zone.m_bind_ipv6_address, m_listening_port_ipv6)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv6) to {}:{}", public_zone.m_bind_ipv6_address, m_listening_port_ipv6)); } if(m_external_port) - oxen::log::debug(logcat, "External port defined as {}", m_external_port); + log::debug(logcat, "External port defined as {}", m_external_port); return res; } @@ -742,7 +742,7 @@ namespace nodetool // creating thread to log number of connections mPeersLoggerThread.emplace([&]() { - oxen::log::debug(logcat, "Thread monitor number of peers - start"); + log::debug(logcat, "Thread monitor number of peers - start"); const network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_); while (!is_closing && !public_zone.m_net_server.is_stop_signal_sent()) { // main loop of thread @@ -771,7 +771,7 @@ namespace nodetool } std::this_thread::sleep_for(1s); } // main loop of thread - oxen::log::debug(logcat, "Thread monitor number of peers - done"); + log::debug(logcat, "Thread monitor number of peers - done"); }); // lambda network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_); @@ -781,13 +781,13 @@ namespace nodetool //here you can set worker threads count int thrds_count = 10; //go to loop - oxen::log::info(logcat, "Run net_service loop( {} threads)...", thrds_count); + log::info(logcat, "Run net_service loop( {} threads)...", thrds_count); if(!public_zone.m_net_server.run_server(thrds_count, true)) { - oxen::log::error(logcat, "Failed to run net tcp server!"); + log::error(logcat, "Failed to run net tcp server!"); } - oxen::log::info(logcat, "net_service loop stopped."); + log::info(logcat, "net_service loop stopped."); return true; } //----------------------------------------------------------------------------------- @@ -821,7 +821,7 @@ namespace nodetool std::error_code ec; if (fs::create_directories(m_config_folder); ec) { - oxen::log::warning(logcat, "Failed to create data directory {}", m_config_folder); + log::warning(logcat, "Failed to create data directory {}", m_config_folder); return false; } @@ -832,7 +832,7 @@ namespace nodetool const auto state_file_path = m_config_folder / cryptonote::P2P_NET_DATA_FILENAME; if (!m_peerlist_storage.store(state_file_path, active)) { - oxen::log::warning(logcat, "Failed to save config to file {}", state_file_path); + log::warning(logcat, "Failed to save config to file {}", state_file_path); return false; } CATCH_ENTRY_L0("node_server::store", false); @@ -842,10 +842,10 @@ namespace nodetool template bool node_server::send_stop_signal() { - oxen::log::debug(logcat, "[node] sending stop signal"); + log::debug(logcat, "[node] sending stop signal"); for (auto& zone : m_network_zones) zone.second.m_net_server.send_stop_signal(); - oxen::log::debug(logcat, "[node] Stop signal sent"); + log::debug(logcat, "[node] Stop signal sent"); for (auto& zone : m_network_zones) { @@ -885,7 +885,7 @@ namespace nodetool if(code < 0) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE invoke failed. ({},{})", context, code, epee::levin::get_err_descr(code)); + log::warning(logcat, "{}COMMAND_HANDSHAKE invoke failed. ({},{})", context, code, epee::levin::get_err_descr(code)); if (code == LEVIN_ERROR_CONNECTION_TIMEDOUT || code == LEVIN_ERROR_CONNECTION_DESTROYED) timeout = true; return; @@ -893,13 +893,13 @@ namespace nodetool if(rsp.node_data.network_id != m_network_id) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE Failed, wrong network! ({}), closing connection.", context, boost::lexical_cast(rsp.node_data.network_id)); + log::warning(logcat, "{}COMMAND_HANDSHAKE Failed, wrong network! ({}), closing connection.", context, boost::lexical_cast(rsp.node_data.network_id)); return; } if(!handle_remote_peerlist(rsp.local_peerlist_new, context)) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE: failed to handle_remote_peerlist(...), closing connection.", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE: failed to handle_remote_peerlist(...), closing connection.", context); add_host_fail(context.m_remote_address); return; } @@ -908,7 +908,7 @@ namespace nodetool { if(!m_payload_handler.process_payload_sync_data(std::move(rsp.payload_data), context, true)) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE invoked, but process_payload_sync_data returned false, dropping connection.", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE invoked, but process_payload_sync_data returned false, dropping connection.", context); hsh_result = false; return; } @@ -920,15 +920,15 @@ namespace nodetool // move if(rsp.node_data.peer_id == zone.m_config.m_peer_id) { - oxen::log::debug(logcat, "{}Connection to self detected, dropping connection", context); + log::debug(logcat, "{}Connection to self detected, dropping connection", context); hsh_result = false; return; } - oxen::log::info(logcat, "{}New connection handshaked, pruning seed {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed)); - oxen::log::debug(logcat, "{} COMMAND_HANDSHAKE INVOKED OK", context); + log::info(logcat, "{}New connection handshaked, pruning seed {}", context, epee::string_tools::to_string_hex(context.m_pruning_seed)); + log::debug(logcat, "{} COMMAND_HANDSHAKE INVOKED OK", context); }else { - oxen::log::debug(logcat, "{} COMMAND_HANDSHAKE(AND CLOSE) INVOKED OK", context); + log::debug(logcat, "{} COMMAND_HANDSHAKE(AND CLOSE) INVOKED OK", context); } context_ = context; }, std::chrono::milliseconds{cryptonote::p2p::DEFAULT_HANDSHAKE_INVOKE_TIMEOUT}); @@ -940,7 +940,7 @@ namespace nodetool if(!hsh_result) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE Failed", context_); + log::warning(logcat, "{}COMMAND_HANDSHAKE Failed", context_); if (!timeout) zone.m_net_server.get_config_object().close(context_.m_connection_id); } @@ -963,13 +963,13 @@ namespace nodetool context.m_in_timedsync = false; if(code < 0) { - oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC invoke failed. ({}, {})", context, code, epee::levin::get_err_descr(code)); + log::warning(logcat, "{}COMMAND_TIMED_SYNC invoke failed. ({}, {})", context, code, epee::levin::get_err_descr(code)); return; } if(!handle_remote_peerlist(rsp.local_peerlist_new, context)) { - oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC: failed to handle_remote_peerlist(...), closing connection.", context); + log::warning(logcat, "{}COMMAND_TIMED_SYNC: failed to handle_remote_peerlist(...), closing connection.", context); m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().close(context.m_connection_id ); add_host_fail(context.m_remote_address); } @@ -983,7 +983,7 @@ namespace nodetool if(!r) { - oxen::log::warning(logcat, "{}COMMAND_TIMED_SYNC Failed", context_); + log::warning(logcat, "{}COMMAND_TIMED_SYNC Failed", context_); return false; } return true; @@ -998,7 +998,7 @@ namespace nodetool size_t x = crypto::rand()%(max_index+1); size_t res = (x*x*x)/(max_index*max_index); //parabola \/ - oxen::log::debug(logcat, "Random connection index={}(x={}, max_index={})", res, x, max_index); + log::debug(logcat, "Random connection index={}(x={}, max_index={})", res, x, max_index); return res; } //----------------------------------------------------------------------------------- @@ -1091,15 +1091,15 @@ namespace nodetool } - oxen::log::debug(logcat, "Connecting to {}(peer_type={}, last_seen: {})...", na.str(), peer_type, (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); + log::debug(logcat, "Connecting to {}(peer_type={}, last_seen: {})...", na.str(), peer_type, (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); auto con = zone.m_connect(zone, na); if(!con) { if (is_priority_node(na)) - oxen::log::info(logcat, "{}[priority] Connect failed to {}", bool(con), na.str()); + log::info(logcat, "{}[priority] Connect failed to {}", bool(con), na.str()); else - oxen::log::info(logcat, "{} Connect failed to {}", bool(con), na.str()); + log::info(logcat, "{} Connect failed to {}", bool(con), na.str()); record_addr_failed(na); return false; } @@ -1112,9 +1112,9 @@ namespace nodetool { bool is_priority = is_priority_node(na); if (is_priority_node(na)) - oxen::log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); + log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); else - oxen::log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); + log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); record_addr_failed(na); return false; } @@ -1122,7 +1122,7 @@ namespace nodetool if(just_take_peerlist) { zone.m_net_server.get_config_object().close(con->m_connection_id); - oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); + log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); return true; } @@ -1144,7 +1144,7 @@ namespace nodetool zone.m_peerlist.append_with_peer_anchor(ape); zone.m_notifier.new_out_connection(); - oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK.", *con ); + log::debug(logcat, "{}CONNECTION HANDSHAKED OK.", *con ); return true; } @@ -1155,14 +1155,14 @@ namespace nodetool if (zone.m_connect == nullptr) return false; - oxen::log::info(logcat, "Connecting to {}(last_seen: {})...", na.str(), (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); + log::info(logcat, "Connecting to {}(last_seen: {})...", na.str(), (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")); auto con = zone.m_connect(zone, na); if (!con) { if (is_priority_node(na)) - oxen::log::info(logcat, "{}[priority]Connect failed to {}", p2p_connection_context{}, na.str()); + log::info(logcat, "{}[priority]Connect failed to {}", p2p_connection_context{}, na.str()); else - oxen::log::info(logcat, "{}Connect failed to {}", p2p_connection_context{}, na.str()); + log::info(logcat, "{}Connect failed to {}", p2p_connection_context{}, na.str()); record_addr_failed(na); return false; @@ -1173,16 +1173,16 @@ namespace nodetool const bool res = do_handshake_with_peer(pi, *con, true); if (!res) { if (is_priority_node(na)) - oxen::log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); + log::info(logcat, "{}[priority] Failed to HANDSHAKE with peer {}", *con, na.str()); else - oxen::log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); + log::info(logcat, "{} Failed to HANDSHAKE with peer {}", *con, na.str()); record_addr_failed(na); return false; } zone.m_net_server.get_config_object().close(con->m_connection_id); - oxen::log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); + log::debug(logcat, "{}CONNECTION HANDSHAKED OK AND CLOSED.", *con); return true; } @@ -1217,10 +1217,10 @@ namespace nodetool bool node_server::make_new_connection_from_anchor_peerlist(const std::vector& anchor_peerlist) { for (const auto& pe: anchor_peerlist) { - oxen::log::debug(logcat, "Considering connecting (out) to anchor peer: {} {}", peerid_to_string(pe.id), pe.adr.str()); + log::debug(logcat, "Considering connecting (out) to anchor peer: {} {}", peerid_to_string(pe.id), pe.adr.str()); if(is_peer_used(pe)) { - oxen::log::debug(logcat, "Peer is used"); + log::debug(logcat, "Peer is used"); continue; } @@ -1232,10 +1232,10 @@ namespace nodetool continue; } - oxen::log::debug(logcat, "Selected peer: {} {} first_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::misc_utils::get_time_interval_string(time(NULL) - pe.first_seen)); + log::debug(logcat, "Selected peer: {} {} first_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::misc_utils::get_time_interval_string(time(NULL) - pe.first_seen)); if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, 0, anchor, pe.first_seen)) { - oxen::log::debug(logcat, "Handshake failed"); + log::debug(logcat, "Handshake failed"); continue; } @@ -1305,11 +1305,11 @@ namespace nodetool if (skipped == 0 || !filtered.empty()) break; if (skipped) - oxen::log::info(logcat, "Skipping {} possible peers as they share a class B with existing peers", skipped); + log::info(logcat, "Skipping {} possible peers as they share a class B with existing peers", skipped); } if (filtered.empty()) { - oxen::log::debug(logcat, "No available peer in {} list filtered by {}", (use_white_list ? "white" : "gray"), next_needed_pruning_stripe); + log::debug(logcat, "No available peer in {} list filtered by {}", (use_white_list ? "white" : "gray"), next_needed_pruning_stripe); return false; } if (use_white_list) @@ -1326,7 +1326,7 @@ namespace nodetool peerlist_entry pe; if (zone.m_peerlist.get_white_peer_by_index(pe, filtered[i]) && pe.adr == na) { - oxen::log::debug(logcat, "Reusing stripe {} peer {}", next_needed_pruning_stripe, pe.adr.str()); + log::debug(logcat, "Reusing stripe {} peer {}", next_needed_pruning_stripe, pe.adr.str()); random_index = i; break; } @@ -1351,10 +1351,10 @@ namespace nodetool ++try_count; - oxen::log::debug(logcat, "Considering connecting (out) to {} list peer: {} {}, pruning seed {} (stripe {} needed)", (use_white_list ? "white" : "gray"), peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), next_needed_pruning_stripe); + log::debug(logcat, "Considering connecting (out) to {} list peer: {} {}, pruning seed {} (stripe {} needed)", (use_white_list ? "white" : "gray"), peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), next_needed_pruning_stripe); if(is_peer_used(pe)) { - oxen::log::debug(logcat, "Peer is used"); + log::debug(logcat, "Peer is used"); continue; } @@ -1364,10 +1364,10 @@ namespace nodetool if(is_addr_recently_failed(pe.adr)) continue; - oxen::log::debug(logcat, "Selected peer: {} {}, pruning seed {} [peer_list={}] last_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), (use_white_list ? white : gray), (pe.last_seen ? epee::misc_utils::get_time_interval_string(time(NULL) - pe.last_seen) : "never")); + log::debug(logcat, "Selected peer: {} {}, pruning seed {} [peer_list={}] last_seen: {}", peerid_to_string(pe.id), pe.adr.str(), epee::string_tools::to_string_hex(pe.pruning_seed), (use_white_list ? white : gray), (pe.last_seen ? epee::misc_utils::get_time_interval_string(time(NULL) - pe.last_seen) : "never")); if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, pe.last_seen, use_white_list ? white : gray)) { - oxen::log::debug(logcat, "Handshake failed"); + log::debug(logcat, "Handshake failed"); continue; } @@ -1386,10 +1386,10 @@ namespace nodetool { for (const auto& full_addr : get_seed_nodes()) { - oxen::log::debug(logcat, "Seed node: {}", full_addr); + log::debug(logcat, "Seed node: {}", full_addr); append_net_address(m_seed_nodes, full_addr, cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT); } - oxen::log::debug(logcat, "Number of seed nodes: {}", m_seed_nodes.size()); + log::debug(logcat, "Number of seed nodes: {}", m_seed_nodes.size()); m_seed_nodes_initialized = true; } } @@ -1418,7 +1418,7 @@ namespace nodetool { if (!m_fallback_seed_nodes_added.test_and_set()) { - oxen::log::warning(logcat, "Failed to connect to any of seed peers, trying fallback seeds"); + log::warning(logcat, "Failed to connect to any of seed peers, trying fallback seeds"); current_index = m_seed_nodes.size() - 1; { shlock.unlock(); @@ -1426,7 +1426,7 @@ namespace nodetool std::unique_lock lock{m_seed_nodes_mutex}; for (const auto &peer: get_seed_nodes(m_nettype)) { - oxen::log::debug(logcat, "Fallback seed node: {}", peer); + log::debug(logcat, "Fallback seed node: {}", peer); append_net_address(m_seed_nodes, peer, cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT); } } @@ -1434,7 +1434,7 @@ namespace nodetool } if (current_index == m_seed_nodes.size() - 1) { - oxen::log::warning(logcat, "No fallback seeds, continuing without seeds"); + log::warning(logcat, "No fallback seeds, continuing without seeds"); break; } // continue for another few cycles @@ -1442,7 +1442,7 @@ namespace nodetool else { if (!is_connected_to_at_least_one_seed_node) - oxen::log::warning(logcat, "Failed to connect to any of seed peers, continuing without seeds"); + log::warning(logcat, "Failed to connect to any of seed peers, continuing without seeds"); break; } } @@ -1516,7 +1516,7 @@ namespace nodetool if (start_conn_count == get_public_outgoing_connections_count() && start_conn_count < m_network_zones.at(zone_type::public_).m_config.m_net_config.max_out_connection_count) { - oxen::log::info(logcat, "Failed to connect to any, trying seeds"); + log::info(logcat, "Failed to connect to any, trying seeds"); if (!connect_to_seed()) return false; } @@ -1543,7 +1543,7 @@ namespace nodetool if(zone.m_net_server.is_stop_signal_sent()) return false; - oxen::log::debug(logcat, "Making expected connection, type {}, {}/{} connections", peer_type, conn_count, expected_connections); + log::debug(logcat, "Making expected connection, type {}, {}/{} connections", peer_type, conn_count, expected_connections); if (peer_type == anchor && !make_new_connection_from_anchor_peerlist(apl)) { return false; @@ -1677,11 +1677,11 @@ namespace nodetool { if (m_hide_my_port || public_zone->second.m_config.m_net_config.max_in_connection_count == 0) { - oxen::log::info(logcat, "Incoming connections disabled, enable them for full connectivity"); + log::info(logcat, "Incoming connections disabled, enable them for full connectivity"); } else { - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "No incoming connections - check firewalls/routers allow port {}", get_this_peer_port())); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "No incoming connections - check firewalls/routers allow port {}", get_this_peer_port())); } } return true; @@ -1695,7 +1695,7 @@ namespace nodetool // This really should be spaced out, i.e. the 60s sync timing should apply per peer, not // globally. - oxen::log::debug(logcat, "STARTED PEERLIST IDLE HANDSHAKE"); + log::debug(logcat, "STARTED PEERLIST IDLE HANDSHAKE"); typedef std::list > local_connects_type; local_connects_type cncts; for(auto& zone : m_network_zones) @@ -1713,7 +1713,7 @@ namespace nodetool std::for_each(cncts.begin(), cncts.end(), [&](const auto& vl){ do_peer_timed_sync(vl.first, vl.second); }); - oxen::log::debug(logcat, "FINISHED PEERLIST IDLE HANDSHAKE"); + log::debug(logcat, "FINISHED PEERLIST IDLE HANDSHAKE"); return true; } //----------------------------------------------------------------------------------- @@ -1739,7 +1739,7 @@ namespace nodetool ignore = true; if (ignore) { - oxen::log::debug(logcat, "Ignoring {}", be.adr.str()); + log::debug(logcat, "Ignoring {}", be.adr.str()); std::swap(local_peerlist[i], local_peerlist[local_peerlist.size() - 1]); local_peerlist.resize(local_peerlist.size() - 1); --i; @@ -1765,13 +1765,13 @@ namespace nodetool { if(peer.adr.get_zone() != zone) { - oxen::log::warning(logcat, "{} sent peerlist from another zone, dropping", context); + log::warning(logcat, "{} sent peerlist from another zone, dropping", context); return false; } } - oxen::log::debug(logcat, "{}REMOTE PEERLIST: remote peerlist size={}", context, peerlist_.size()); - oxen::log::trace(logcat, "{}REMOTE PEERLIST: \n{}", context, "REMOTE PEERLIST: \n", print_peerlist_to_string(peerlist_)); + log::debug(logcat, "{}REMOTE PEERLIST: remote peerlist size={}", context, peerlist_.size()); + log::trace(logcat, "{}REMOTE PEERLIST: \n{}", context, "REMOTE PEERLIST: \n", print_peerlist_to_string(peerlist_)); return m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.merge_peerlist(peerlist_, [this](const peerlist_entry &pe) { return !is_addr_recently_failed(pe.adr); }); } //----------------------------------------------------------------------------------- @@ -1811,7 +1811,7 @@ namespace nodetool { if (zone == m_network_zones.end()) { - oxen::log::warning(logcat, "Unable to relay all messages, zone not available"); + log::warning(logcat, "Unable to relay all messages, zone not available"); return false; } if (c_id.first <= zone->first) @@ -1962,7 +1962,7 @@ namespace nodetool { if(ec) { - oxen::log::warning(logcat, "{}back ping connect failed to {}", ping_context, address.str()); + log::warning(logcat, "{}back ping connect failed to {}", ping_context, address.str()); return false; } COMMAND_PING::request req{}; @@ -1983,14 +1983,14 @@ namespace nodetool { if(code <= 0) { - oxen::log::warning(logcat, "{}Failed to invoke COMMAND_PING to {}({}, {})", ping_context, address.str(), code, epee::levin::get_err_descr(code)); + log::warning(logcat, "{}Failed to invoke COMMAND_PING to {}({}, {})", ping_context, address.str(), code, epee::levin::get_err_descr(code)); return; } network_zone& zone = m_network_zones.at(address.get_zone()); if(rsp.status != COMMAND_PING::OK_RESPONSE || pr != rsp.peer_id) { - oxen::log::warning(logcat, "{}{}\" from{}, hsh_peer_id={}, rsp.peer_id={}", ping_context, "back ping invoke wrong response \"", rsp.status, address.str(), pr_, peerid_to_string(rsp.peer_id)); + log::warning(logcat, "{}{}\" from{}, hsh_peer_id={}, rsp.peer_id={}", ping_context, "back ping invoke wrong response \"", rsp.status, address.str(), pr_, peerid_to_string(rsp.peer_id)); zone.m_net_server.get_config_object().close(ping_context.m_connection_id); return; } @@ -2000,7 +2000,7 @@ namespace nodetool if(!inv_call_res) { - oxen::log::warning(logcat, "{}{}", ping_context, "back ping invoke failed to ", address.str()); + log::warning(logcat, "{}{}", ping_context, "back ping invoke failed to ", address.str()); zone.m_net_server.get_config_object().close(ping_context.m_connection_id); return false; } @@ -2008,7 +2008,7 @@ namespace nodetool }, zone.m_bind_ip); if(!r) { - oxen::log::warning(logcat, "{}Failed to call connect_async, network error.", context); + log::warning(logcat, "{}Failed to call connect_async, network error.", context); } return r; } @@ -2018,7 +2018,7 @@ namespace nodetool { if(!m_payload_handler.process_payload_sync_data(std::move(arg.payload_data), context, false)) { - oxen::log::warning(logcat, "{}Failed to process_payload_sync_data(), dropping connection", context); + log::warning(logcat, "{}Failed to process_payload_sync_data(), dropping connection", context); drop_connection(context); return 1; } @@ -2051,7 +2051,7 @@ namespace nodetool if(!context.m_is_income && zone.m_our_address.get_zone() == zone_type) rsp.local_peerlist_new.push_back(peerlist_entry{zone.m_our_address, zone.m_config.m_peer_id, std::time(nullptr)}); - oxen::log::debug(logcat, "{}COMMAND_TIMED_SYNC", context); + log::debug(logcat, "{}COMMAND_TIMED_SYNC", context); return 1; } //----------------------------------------------------------------------------------- @@ -2061,7 +2061,7 @@ namespace nodetool if(arg.node_data.network_id != m_network_id) { - oxen::log::info(logcat, "{}{}", context, "WRONG NETWORK AGENT CONNECTED! id=", boost::lexical_cast(arg.node_data.network_id)); + log::info(logcat, "{}{}", context, "WRONG NETWORK AGENT CONNECTED! id=", boost::lexical_cast(arg.node_data.network_id)); drop_connection(context); add_host_fail(context.m_remote_address); return 1; @@ -2069,7 +2069,7 @@ namespace nodetool if(!context.m_is_income) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came not from incoming connection", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE came not from incoming connection", context); drop_connection(context); add_host_fail(context.m_remote_address); return 1; @@ -2077,7 +2077,7 @@ namespace nodetool if(context.peer_id) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but seems that connection already have associated peer_id (double COMMAND_HANDSHAKE?)", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE came, but seems that connection already have associated peer_id (double COMMAND_HANDSHAKE?)", context); drop_connection(context); return 1; } @@ -2088,28 +2088,28 @@ namespace nodetool // and pass in a tor connection's peer id, and deduce the two are the same if you reject it if(arg.node_data.peer_id == zone.m_config.m_peer_id) { - oxen::log::debug(logcat, "{}Connection to self detected, dropping connection", context); + log::debug(logcat, "{}Connection to self detected, dropping connection", context); drop_connection(context); return 1; } if (zone.m_current_number_of_in_peers >= zone.m_config.m_net_config.max_in_connection_count) // in peers limit { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but already have max incoming connections, so dropping this one.", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE came, but already have max incoming connections, so dropping this one.", context); drop_connection(context); return 1; } if(!m_payload_handler.process_payload_sync_data(std::move(arg.payload_data), context, true)) { - oxen::log::warning(logcat, "{}COMMAND_HANDSHAKE came, but process_payload_sync_data returned false, dropping connection.", context); + log::warning(logcat, "{}COMMAND_HANDSHAKE came, but process_payload_sync_data returned false, dropping connection.", context); drop_connection(context); return 1; } if(has_too_many_connections(context.m_remote_address)) { - oxen::log::info(logcat, "CONNECTION FROM {} REFUSED, too many connections from the same address", context.m_remote_address.host_str()); + log::info(logcat, "CONNECTION FROM {} REFUSED, too many connections from the same address", context.m_remote_address.host_str()); drop_connection(context); return 1; } @@ -2144,7 +2144,7 @@ namespace nodetool pe.id = peer_id_l; pe.pruning_seed = context.m_pruning_seed; this->m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.append_with_peer_white(pe); - oxen::log::debug(logcat, "{}PING SUCCESS {}:{}", context, context.m_remote_address.host_str(), port_l); + log::debug(logcat, "{}PING SUCCESS {}:{}", context, context.m_remote_address.host_str(), port_l); }); } @@ -2154,14 +2154,14 @@ namespace nodetool context.sent_addresses.insert(e.adr); get_local_node_data(rsp.node_data, zone); m_payload_handler.get_payload_sync_data(rsp.payload_data); - oxen::log::debug(logcat, "{}COMMAND_HANDSHAKE", context); + log::debug(logcat, "{}COMMAND_HANDSHAKE", context); return 1; } //----------------------------------------------------------------------------------- template int node_server::handle_ping(int command, COMMAND_PING::request& arg, COMMAND_PING::response& rsp, p2p_connection_context& context) { - oxen::log::debug(logcat, "{}COMMAND_PING", context); + log::debug(logcat, "{}COMMAND_PING", context); rsp.status = COMMAND_PING::OK_RESPONSE; rsp.peer_id = m_network_zones.at(context.m_remote_address.get_zone()).m_config.m_peer_id; return 1; @@ -2174,14 +2174,14 @@ namespace nodetool std::vector pl_gray; for (auto& zone : m_network_zones) zone.second.m_peerlist.get_peerlist(pl_gray, pl_white); - oxen::log::info(logcat, "\nPeerlist white:\n{}\nPeerlist gray:\n{}", print_peerlist_to_string(pl_white), print_peerlist_to_string(pl_gray)); + log::info(logcat, "\nPeerlist white:\n{}\nPeerlist gray:\n{}", print_peerlist_to_string(pl_white), print_peerlist_to_string(pl_gray)); return true; } //----------------------------------------------------------------------------------- template bool node_server::log_connections() { - oxen::log::info(logcat, "Connections: \r\n{}", print_connections_container()); + log::info(logcat, "Connections: \r\n{}", print_connections_container()); return true; } //----------------------------------------------------------------------------------- @@ -2208,7 +2208,7 @@ namespace nodetool template void node_server::on_connection_new(p2p_connection_context& context) { - oxen::log::info(logcat, "[{}] NEW CONNECTION", epee::net_utils::print_connection_context(context)); + log::info(logcat, "[{}] NEW CONNECTION", epee::net_utils::print_connection_context(context)); } //----------------------------------------------------------------------------------- template @@ -2224,7 +2224,7 @@ namespace nodetool m_payload_handler.on_connection_close(context); - oxen::log::info(logcat, "[{}] CLOSE CONNECTION", epee::net_utils::print_connection_context(context)); + log::info(logcat, "[{}] CLOSE CONNECTION", epee::net_utils::print_connection_context(context)); } template @@ -2348,7 +2348,7 @@ namespace nodetool return true; } epee::net_utils::connection >::set_tos_flag(flag); - oxen::log::debug(logcat, "Set ToS flag {}", flag); + log::debug(logcat, "Set ToS flag {}", flag); return true; } @@ -2362,7 +2362,7 @@ namespace nodetool } epee::net_utils::connection >::set_rate_up_limit( limit ); - oxen::log::info(logcat, "Set limit-up to {} kB/s", limit); + log::info(logcat, "Set limit-up to {} kB/s", limit); return true; } @@ -2374,7 +2374,7 @@ namespace nodetool limit=cryptonote::p2p::DEFAULT_LIMIT_RATE_DOWN; } epee::net_utils::connection >::set_rate_down_limit( limit ); - oxen::log::info(logcat, "Set limit-down to {} kB/s", limit); + log::info(logcat, "Set limit-down to {} kB/s", limit); return true; } @@ -2396,11 +2396,11 @@ namespace nodetool } if(!this->islimitup) { epee::net_utils::connection >::set_rate_up_limit(limit_up); - oxen::log::info(logcat, "Set limit-up to {} kB/s", limit_up); + log::info(logcat, "Set limit-up to {} kB/s", limit_up); } if(!this->islimitdown) { epee::net_utils::connection >::set_rate_down_limit(limit_down); - oxen::log::info(logcat, "Set limit-down to {} kB/s", limit_down); + log::info(logcat, "Set limit-down to {} kB/s", limit_down); } return true; @@ -2453,12 +2453,12 @@ namespace nodetool if (!check_connection_and_handshake_with_peer(pe.adr, pe.last_seen)) { zone.second.m_peerlist.remove_from_peer_gray(pe); - oxen::log::debug(logcat, "PEER EVICTED FROM GRAY PEER LIST: address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); + log::debug(logcat, "PEER EVICTED FROM GRAY PEER LIST: address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); } else { zone.second.m_peerlist.set_peer_just_seen(pe.id, pe.adr, pe.pruning_seed); - oxen::log::debug(logcat, "PEER PROMOTED TO WHITE PEER LIST IP address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); + log::debug(logcat, "PEER PROMOTED TO WHITE PEER LIST IP address: {} Peer ID: {}", pe.adr.host_str(), peerid_to_string(pe.id)); } } return true; @@ -2472,7 +2472,7 @@ namespace nodetool return; const uint32_t index = stripe - 1; std::lock_guard lock{m_used_stripe_peers_mutex}; - oxen::log::info(logcat, "adding stripe {} peer: {}", stripe, context.m_remote_address.str()); + log::info(logcat, "adding stripe {} peer: {}", stripe, context.m_remote_address.str()); std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(), [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }); m_used_stripe_peers[index].push_back(context.m_remote_address); @@ -2486,7 +2486,7 @@ namespace nodetool return; const uint32_t index = stripe - 1; std::lock_guard lock{m_used_stripe_peers_mutex}; - oxen::log::info(logcat, "removing stripe {} peer: {}", stripe, context.m_remote_address.str()); + log::info(logcat, "removing stripe {} peer: {}", stripe, context.m_remote_address.str()); std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(), [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }); } @@ -2495,7 +2495,7 @@ namespace nodetool void node_server::clear_used_stripe_peers() { std::lock_guard lock{m_used_stripe_peers_mutex}; - oxen::log::info(logcat, "clearing used stripe peers"); + log::info(logcat, "clearing used stripe peers"); for (auto &e: m_used_stripe_peers) e.clear(); } diff --git a/src/p2p/net_peerlist.cpp b/src/p2p/net_peerlist.cpp index 8890952dc..4e83b53fb 100644 --- a/src/p2p/net_peerlist.cpp +++ b/src/p2p/net_peerlist.cpp @@ -213,7 +213,7 @@ namespace nodetool // This is different from the `return std::nullopt` cases above. Those // cases could fail due to bad file permissions, so a shutdown is // likely more appropriate. - oxen::log::warning(globallogcat, "Failed to load p2p config file, falling back to default config"); + log::warning(globallogcat, "Failed to load p2p config file, falling back to default config"); out.emplace(); } } diff --git a/src/ringct/bulletproofs.cc b/src/ringct/bulletproofs.cc index 0e80d41a5..ccc2f0f45 100644 --- a/src/ringct/bulletproofs.cc +++ b/src/ringct/bulletproofs.cc @@ -51,7 +51,7 @@ extern "C" namespace rct { -static auto logcat = oxen::log::Cat("bulletproofs"); +static auto logcat = log::Cat("bulletproofs"); static rct::key vector_exponent(const rct::keyV &a, const rct::keyV &b); static rct::keyV vector_powers(const rct::key &x, size_t n); diff --git a/src/ringct/multiexp.cc b/src/ringct/multiexp.cc index 5263acacd..05d0ad160 100644 --- a/src/ringct/multiexp.cc +++ b/src/ringct/multiexp.cc @@ -95,7 +95,7 @@ extern "C" namespace rct { -static auto logcat = oxen::log::Cat("multiexp"); +static auto logcat = log::Cat("multiexp"); static inline bool operator<(const rct::key &k0, const rct::key&k1) { diff --git a/src/ringct/rctOps.cpp b/src/ringct/rctOps.cpp index 5c943f6c5..79b4cf6e5 100644 --- a/src/ringct/rctOps.cpp +++ b/src/ringct/rctOps.cpp @@ -36,7 +36,9 @@ using namespace crypto; using namespace std; -#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {oxen::log::warning(oxen::log::Cat("ringct"), message); throw std::runtime_error(message);}} +auto logcat = oxen::log::Cat("ringct"); + +#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {oxen::log::warning(logcat, message); throw std::runtime_error(message);}} struct zero_commitment { uint64_t amount; rct::key commitment; }; static const zero_commitment zero_commitments[] = { diff --git a/src/ringct/rctSigs.cpp b/src/ringct/rctSigs.cpp index ce642f073..4c188ec2a 100644 --- a/src/ringct/rctSigs.cpp +++ b/src/ringct/rctSigs.cpp @@ -37,11 +37,10 @@ #include "cryptonote_config.h" -namespace -{ - static auto logcat = oxen::log::Cat("ringct"); +namespace rct { + static auto logcat = log::Cat("ringct"); - rct::Bulletproof make_dummy_bulletproof(const std::vector &outamounts, rct::keyV &C, rct::keyV &masks) + static rct::Bulletproof make_dummy_bulletproof(const std::vector &outamounts, rct::keyV &C, rct::keyV &masks) { const size_t n_outs = outamounts.size(); const rct::key I = rct::identity(); @@ -71,9 +70,7 @@ namespace return rct::Bulletproof{rct::keyV(n_outs, I), I, I, I, I, I, I, rct::keyV(nrl, I), rct::keyV(nrl, I), I, I, I}; } -} -namespace rct { Bulletproof proveRangeBulletproof(keyV &C, keyV &masks, const std::vector &amounts, epee::span sk, hw::device &hwdev) { CHECK_AND_ASSERT_THROW_MES(amounts.size() == sk.size(), "Invalid amounts/sk sizes"); @@ -123,7 +120,7 @@ namespace rct { for (size_t i = 0 ; i < 64 ; ++i) { if (ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) != 0 || ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) != 0) { - oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + log::info(log::Cat("verify"), "point conv failed"); return false; } } @@ -384,13 +381,13 @@ namespace rct { ge_p1p1 p1; if (ge_frombytes_vartime(&p3, H2[i].bytes) != 0) { - oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + log::info(log::Cat("verify"), "point conv failed"); return false; } ge_p3_to_cached(&cached, &p3); if (ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) != 0) { - oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + log::info(log::Cat("verify"), "point conv failed"); return false; } ge_sub(&p1, &asCi[i], &cached); @@ -564,7 +561,7 @@ namespace rct { ge_p3 Cp3; if (ge_frombytes_vartime(&Cp3, C.bytes) != 0) { - oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + log::info(log::Cat("verify"), "point conv failed"); return false; } ge_cached Ccached; @@ -576,7 +573,7 @@ namespace rct { ge_p3 p3; if (ge_frombytes_vartime(&p3, pubs[i].mask.bytes) != 0) { - oxen::log::info(oxen::log::Cat("verify"), "point conv failed"); + log::info(log::Cat("verify"), "point conv failed"); return false; } ge_sub(&p1, &p3, &Ccached); @@ -933,7 +930,7 @@ namespace rct { for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - oxen::log::info(logcat, "Range proof verified failed for proof {}", i); + log::info(logcat, "Range proof verified failed for proof {}", i); return false; } } @@ -946,7 +943,7 @@ namespace rct { DP("mg sig verified?"); DP(mgVerd); if (!mgVerd) { - oxen::log::info(logcat, "MG signature verification failed"); + log::info(logcat, "MG signature verification failed"); return false; } } @@ -955,12 +952,12 @@ namespace rct { } catch (const std::exception &e) { - oxen::log::info(logcat, "Error in verRct: {}", e.what()); + log::info(logcat, "Error in verRct: {}", e.what()); return false; } catch (...) { - oxen::log::info(logcat, "Error in verRct, but not an actual exception"); + log::info(logcat, "Error in verRct, but not an actual exception"); return false; } } @@ -1032,7 +1029,7 @@ namespace rct { //check pseudoOuts vs Outs.. if (!equalKeys(sumPseudoOuts, sumOutpks)) { - oxen::log::info(logcat, "Sum check failed"); + log::info(logcat, "Sum check failed"); return false; } @@ -1050,14 +1047,14 @@ namespace rct { } if (!proofs.empty() && !verBulletproof(proofs)) { - oxen::log::info(logcat, "Aggregate range proof verified failed"); + log::info(logcat, "Aggregate range proof verified failed"); return false; } waiter.wait(&tpool); for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - oxen::log::info(logcat, "Range proof verified failed for proof {}", i); + log::info(logcat, "Range proof verified failed for proof {}", i); return false; } } @@ -1067,12 +1064,12 @@ namespace rct { // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { - oxen::log::info(logcat, "Error in verRctSemanticsSimple: {}", e.what()); + log::info(logcat, "Error in verRctSemanticsSimple: {}", e.what()); return false; } catch (...) { - oxen::log::info(logcat, "Error in verRctSemanticsSimple, but not an actual exception"); + log::info(logcat, "Error in verRctSemanticsSimple, but not an actual exception"); return false; } } @@ -1120,7 +1117,7 @@ namespace rct { for (size_t i = 0; i < results.size(); ++i) { if (!results[i]) { - oxen::log::info(logcat, "verRctMGSimple/verRctCLSAGSimple failed for input {}", i); + log::info(logcat, "verRctMGSimple/verRctCLSAGSimple failed for input {}", i); return false; } } @@ -1130,12 +1127,12 @@ namespace rct { // we can get deep throws from ge_frombytes_vartime if input isn't valid catch (const std::exception &e) { - oxen::log::info(logcat, "Error in verRctNonSemanticsSimple: {}", e.what()); + log::info(logcat, "Error in verRctNonSemanticsSimple: {}", e.what()); return false; } catch (...) { - oxen::log::info(logcat, "Error in verRctNonSemanticsSimple, but not an actual exception"); + log::info(logcat, "Error in verRctNonSemanticsSimple, but not an actual exception"); return false; } } diff --git a/src/ringct/rctTypes.cpp b/src/ringct/rctTypes.cpp index 9f0f2680d..a8a988826 100644 --- a/src/ringct/rctTypes.cpp +++ b/src/ringct/rctTypes.cpp @@ -39,7 +39,7 @@ using namespace std; namespace rct { - static auto logcat = oxen::log::Cat("ringct"); + static auto logcat = log::Cat("ringct"); //dp //Debug printing for the above types diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 5c1661d37..60e20c623 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -77,7 +77,7 @@ namespace cryptonote::rpc { using nlohmann::json; using oxen::json_to_bt; - static auto logcat = oxen::log::Cat("daemon.rpc"); + static auto logcat = log::Cat("daemon.rpc"); namespace { @@ -366,7 +366,7 @@ namespace cryptonote::rpc { } } - oxen::log::debug(logcat, "on_get_blocks: {} blocks, {} txes, size {}", bs.size(), ntxes, size); + log::debug(logcat, "on_get_blocks: {} blocks, {} txes, size {}", bs.size(), ntxes, size); res.status = STATUS_OK; return res; } @@ -389,7 +389,7 @@ namespace cryptonote::rpc { res.blks_hashes.push_back(tools::type_to_hex(get_block_hash(blk))); } - oxen::log::debug(logcat, "on_get_alt_blocks_hashes: {} blocks ", blks.size()); + log::debug(logcat, "on_get_alt_blocks_hashes: {} blocks ", blks.size()); res.status = STATUS_OK; return res; } @@ -520,7 +520,7 @@ namespace cryptonote::rpc { return res; } res.status = STATUS_OK; - oxen::log::debug(logcat, "GET_TX_GLOBAL_OUTPUTS_INDEXES: [{}]", res.o_indexes.size()); + log::debug(logcat, "GET_TX_GLOBAL_OUTPUTS_INDEXES: [{}]", res.o_indexes.size()); return res; } @@ -734,7 +734,7 @@ namespace cryptonote::rpc { transaction tx; if (!parse_and_validate_tx_from_blob(*bd, tx)) { - oxen::log::error(logcat, "Failed to parse tx from txpool"); + log::error(logcat, "Failed to parse tx from txpool"); // continue return true; } @@ -789,7 +789,7 @@ namespace cryptonote::rpc { get.response["status"] = STATUS_FAILED; return; } - oxen::log::debug(logcat, "Found {}/{} transactions on the blockchain", txs.size(), get.request.tx_hashes.size()); + log::debug(logcat, "Found {}/{} transactions on the blockchain", txs.size(), get.request.tx_hashes.size()); } // try the pool for any missing txes @@ -840,7 +840,7 @@ namespace cryptonote::rpc { } txs = std::move(sorted_txs); get.response_hex["missed_tx"] = missed_txs; // non-plural here intentional to not break existing clients - oxen::log::debug(logcat, "Found {}/{} transactions in the pool", found_in_pool.size(), get.request.tx_hashes.size()); + log::debug(logcat, "Found {}/{} transactions in the pool", found_in_pool.size(), get.request.tx_hashes.size()); } else if (get.request.memory_pool) { txs.reserve(pool_txs.size()); std::transform(pool_txs.begin(), pool_txs.end(), std::back_inserter(txs), split_mempool_tx); @@ -854,7 +854,7 @@ namespace cryptonote::rpc { } } } catch (const std::exception& e) { - oxen::log::error(logcat, e.what()); + log::error(logcat, e.what()); get.response["status"] = "Failed: "s + e.what(); return; } @@ -982,7 +982,7 @@ namespace cryptonote::rpc { } } - oxen::log::debug(logcat, "{} transactions found, {} not found", get.response["txs"].size(), missed_txs.size()); + log::debug(logcat, "{} transactions found, {} not found", get.response["txs"].size(), missed_txs.size()); get.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ @@ -1003,7 +1003,7 @@ namespace cryptonote::rpc { try { kis = get_pool_kis(m_core); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to get pool key images: {}", e.what()); + log::error(logcat, "Failed to get pool key images: {}", e.what()); return; } } @@ -1062,7 +1062,7 @@ namespace cryptonote::rpc { { tx.response["status"] = STATUS_FAILED; auto reason = print_tx_verification_context(tvc); - oxen::log::warning(logcat, "[on_send_raw_tx]: {} {}", (tvc.m_verifivation_failed ? "tx verification failed" : "Failed to process tx"), reason); + log::warning(logcat, "[on_send_raw_tx]: {} {}", (tvc.m_verifivation_failed ? "tx verification failed" : "Failed to process tx"), reason); tx.response["reason"] = std::move(reason); tx.response["reason_codes"] = tx_verification_failure_codes(tvc); return; @@ -1089,12 +1089,12 @@ namespace cryptonote::rpc { cryptonote::address_parse_info info; if(!get_account_address_from_str(info, m_core.get_nettype(), start_mining.request.miner_address)) { start_mining.response["status"] = "Failed, invalid address"; - oxen::log::warning(logcat, start_mining.response["status"]); + log::warning(logcat, start_mining.response["status"]); return; } if (info.is_subaddress) { start_mining.response["status"] = "Mining to subaddress isn't supported yet"; - oxen::log::warning(logcat, start_mining.response["status"]); + log::warning(logcat, start_mining.response["status"]); return; } @@ -1108,7 +1108,7 @@ namespace cryptonote::rpc { // then we fail and log that. if (start_mining.request.threads_count > max_concurrency_count) { start_mining.response["status"] = "Failed, too many threads relative to CPU cores."; - oxen::log::warning(logcat, start_mining.response["status"]); + log::warning(logcat, start_mining.response["status"]); return; } @@ -1122,7 +1122,7 @@ namespace cryptonote::rpc { if(!miner.start(info.address, start_mining.request.threads_count, start_mining.request.num_blocks, start_mining.request.slow_mining)) { start_mining.response["status"] = "Failed, mining not started"; - oxen::log::warning(logcat, start_mining.response["status"]); + log::warning(logcat, start_mining.response["status"]); return; } @@ -1135,13 +1135,13 @@ namespace cryptonote::rpc { if(!miner.is_mining()) { stop_mining.response["status"] = "Mining never started"; - oxen::log::warning(logcat, stop_mining.response["status"]); + log::warning(logcat, stop_mining.response["status"]); return; } if(!miner.stop()) { stop_mining.response["status"] = "Failed, mining not stopped"; - oxen::log::warning(logcat, stop_mining.response["status"]); + log::warning(logcat, stop_mining.response["status"]); return; } @@ -1177,7 +1177,7 @@ namespace cryptonote::rpc { if( !m_core.get_blockchain_storage().store_blockchain() ) { save_bc.response["status"] = "Error while storing blockchain"; - oxen::log::warning(logcat, save_bc.response["status"]); + log::warning(logcat, save_bc.response["status"]); return; } save_bc.response["status"] = STATUS_OK; @@ -1219,7 +1219,7 @@ namespace cryptonote::rpc { } auto log_level = oxen::logging::parse_level(set_log_level.request.level); if (log_level.has_value()) - oxen::log::reset_level(*log_level); + log::reset_level(*log_level); set_log_level.response["status"] = STATUS_OK; } //------------------------------------------------------------------------------------------------------------------------------ @@ -2321,7 +2321,7 @@ namespace cryptonote::rpc { args.emplace_back(std::to_string(service_nodes::percent_to_basis_points(req.operator_cut))); } catch(const std::exception &e) { res.status = "Invalid value: "s + e.what(); - oxen::log::error(logcat, res.status); + log::error(logcat, res.status); return res; } } @@ -2651,20 +2651,20 @@ namespace cryptonote::rpc { status = fmt::format("Outdated {}. Current: {}.{}.{} Required: {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2], required[0], required[1], required[2]); - oxen::log::error(logcat, status); + log::error(logcat, status); } else if (!ed25519_pubkey.empty() // TODO: once lokinet & ss are always sending this we can remove this empty bypass && ed25519_pubkey != our_ed25519_pubkey) { status = fmt::format("Invalid {} pubkey: expected {}, received {}", name, our_ed25519_pubkey, ed25519_pubkey); - oxen::log::error(logcat, status); + log::error(logcat, status); } else { auto now = std::time(nullptr); auto old = update.exchange(now); bool significant = std::chrono::seconds{now - old} > lifetime; // Print loudly for the first ping after startup/expiry auto msg = fmt::format("Received ping from {} {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2]); if (significant) - oxen::log::info(logcat, fmt::format(fg(fmt::terminal_color::green), msg)); + log::info(logcat, fmt::format(fg(fmt::terminal_color::green), msg)); else - oxen::log::debug(logcat, msg); + log::debug(logcat, msg); success(significant); status = STATUS_OK; } @@ -2788,7 +2788,7 @@ namespace cryptonote::rpc { blobs.clear(); if (!db.get_transactions_blobs(block.second.tx_hashes, blobs)) { - oxen::log::error(logcat, "Could not query block at requested height: {}", cryptonote::get_block_height(block.second)); + log::error(logcat, "Could not query block at requested height: {}", cryptonote::get_block_height(block.second)); continue; } const auto hard_fork_version = block.second.major_version; @@ -2797,7 +2797,7 @@ namespace cryptonote::rpc { cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(blob, tx)) { - oxen::log::error(logcat, "tx could not be validated from blob, possibly corrupt blockchain"); + log::error(logcat, "tx could not be validated from blob, possibly corrupt blockchain"); continue; } if (tx.type == cryptonote::txtype::state_change) @@ -2805,7 +2805,7 @@ namespace cryptonote::rpc { cryptonote::tx_extra_service_node_state_change state_change; if (!cryptonote::get_service_node_state_change_from_tx_extra(tx.extra, state_change, hard_fork_version)) { - oxen::log::error(logcat, "Could not get state change from tx, possibly corrupt tx, hf_version {}", static_cast(hard_fork_version)); + log::error(logcat, "Could not get state change from tx, possibly corrupt tx, hf_version {}", static_cast(hard_fork_version)); continue; } @@ -2827,7 +2827,7 @@ namespace cryptonote::rpc { break; default: - oxen::log::error(logcat, "Unhandled state in on_get_service_nodes_state_changes"); + log::error(logcat, "Unhandled state in on_get_service_nodes_state_changes"); break; } } @@ -2851,7 +2851,7 @@ namespace cryptonote::rpc { { crypto::public_key pubkey; if (!tools::hex_to_type(report_peer_status.request.pubkey, pubkey)) { - oxen::log::error(logcat, "Could not parse public key: {}", report_peer_status.request.pubkey); + log::error(logcat, "Could not parse public key: {}", report_peer_status.request.pubkey); throw rpc_error{ERROR_WRONG_PARAM, "Could not parse public key"}; } diff --git a/src/rpc/http_client.cpp b/src/rpc/http_client.cpp index 265417277..bfad10f6c 100644 --- a/src/rpc/http_client.cpp +++ b/src/rpc/http_client.cpp @@ -11,7 +11,7 @@ namespace cryptonote::rpc { - static auto logcat = oxen::log::Cat("rpc.http_client"); + static auto logcat = log::Cat("rpc.http_client"); http_client_connect_error::http_client_connect_error(const cpr::Error& err, const std::string& prefix) : http_client_error{prefix + err.message}, @@ -204,7 +204,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea new_ssl_opts->SetOption(client_cert->second); } if (!verify_https) { - oxen::log::warning(logcat, "HTTPS certificate verification disabled; this connection is not secure"); + log::warning(logcat, "HTTPS certificate verification disabled; this connection is not secure"); new_ssl_opts->SetOption(cpr::ssl::VerifyHost(false)); new_ssl_opts->SetOption(cpr::ssl::VerifyPeer(false)); new_ssl_opts->SetOption(cpr::ssl::VerifyStatus(false)); @@ -224,7 +224,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea if (new_proxy) session.SetProxies(*std::move(new_proxy)); if (new_ssl_opts) session.SetSslOptions(*new_ssl_opts); - oxen::log::debug(logcat, "Submitting post request to {}", url.str()); + log::debug(logcat, "Submitting post request to {}", url.str()); session.SetUrl(url); session.SetHeader(header); session.SetBody(std::move(body)); @@ -232,7 +232,7 @@ cpr::Response http_client::post(const std::string& uri, cpr::Body body, cpr::Hea res = session.Post(); } - oxen::log::debug(logcat, "{}: {}, sent {} bytes, received {} bytes in {}", url.str(), (res.error.code != cpr::ErrorCode::OK ? res.error.message : res.status_line), res.uploaded_bytes, res.downloaded_bytes, tools::friendly_duration(std::chrono::steady_clock::now() - start)); + log::debug(logcat, "{}: {}, sent {} bytes, received {} bytes in {}", url.str(), (res.error.code != cpr::ErrorCode::OK ? res.error.message : res.status_line), res.uploaded_bytes, res.downloaded_bytes, tools::friendly_duration(std::chrono::steady_clock::now() - start)); bytes_sent += res.uploaded_bytes; bytes_received += res.downloaded_bytes; diff --git a/src/rpc/http_server.cpp b/src/rpc/http_server.cpp index 144c8edb6..f780444f5 100644 --- a/src/rpc/http_server.cpp +++ b/src/rpc/http_server.cpp @@ -14,7 +14,7 @@ namespace cryptonote::rpc { - static auto logcat = oxen::log::Cat("daemon.rpc"); + static auto logcat = log::Cat("daemon.rpc"); const command_line::arg_descriptor> http_server::arg_rpc_public{ "rpc-public", @@ -163,7 +163,7 @@ namespace cryptonote::rpc { void http_server::create_rpc_endpoints(uWS::App& http) { auto access_denied = [this](HttpResponse* res, HttpRequest* req) { - oxen::log::info(logcat, "Forbidden HTTP request for restricted endpoint {} {}", req->getMethod(), req->getUrl()); + log::info(logcat, "Forbidden HTTP request for restricted endpoint {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_FORBIDDEN); }; @@ -190,7 +190,7 @@ namespace cryptonote::rpc { http.any("/*", [this](HttpResponse* res, HttpRequest* req) { if (m_login && !check_auth(*req, *res)) return; - oxen::log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); + log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_NOT_FOUND); }); } @@ -301,19 +301,19 @@ namespace cryptonote::rpc { json_error = 0; } catch (const parse_error& e) { // This isn't really WARNable as it's the client fault; log at info level instead. - oxen::log::info(logcat, "HTTP RPC request '{}' called with invalid/unparseable data: {}", data.uri, e.what()); + log::info(logcat, "HTTP RPC request '{}' called with invalid/unparseable data: {}", data.uri, e.what()); json_error = -32602; http_message = "Unable to parse request: "s + e.what(); json_message = "Invalid params"; } catch (const rpc_error& e) { - oxen::log::warning(logcat, "HTTP RPC request '{}' failed with: {}", data.uri, e.what()); + log::warning(logcat, "HTTP RPC request '{}' failed with: {}", data.uri, e.what()); json_error = e.code; json_message = e.message; http_message = e.message; } catch (const std::exception& e) { - oxen::log::warning(logcat, "HTTP RPC request '{}' raised an exception: {}", data.uri, e.what()); + log::warning(logcat, "HTTP RPC request '{}' raised an exception: {}", data.uri, e.what()); } catch (...) { - oxen::log::warning(logcat, "HTTP RPC request '{}' raised an unknown exception", data.uri); + log::warning(logcat, "HTTP RPC request '{}' raised an unknown exception", data.uri); } if (json_error != 0) { @@ -330,7 +330,7 @@ namespace cryptonote::rpc { if (time_logging) call_duration = " in " + tools::friendly_duration(std::chrono::steady_clock::now() - start); if (OXEN_LOG_ENABLED(info)) - oxen::log::info(logcat, "HTTP RPC {} [{}] OK ({} bytes){}", data.uri, data.request.context.remote, result.size(), call_duration); + log::info(logcat, "HTTP RPC {} [{}] OK ({} bytes){}", data.uri, data.request.context.remote, result.size(), call_duration); queue_response(std::move(dataptr), std::move(result)); } @@ -371,12 +371,12 @@ namespace cryptonote::rpc { if (req.tx_pool_checksum == checksum) { // Hashes match, which means we need to defer this request until later. std::lock_guard lock{long_poll_mutex}; - oxen::log::trace(logcat, "Deferring long poll request from {}: long polling requested and remote's checksum matches current pool ({})", data->request.context.remote, checksum); + log::trace(logcat, "Deferring long poll request from {}: long polling requested and remote's checksum matches current pool ({})", data->request.context.remote, checksum); long_pollers.emplace_back(std::move(data), std::chrono::steady_clock::now() + GET_TRANSACTION_POOL_HASHES_BIN::long_poll_timeout); return; } - oxen::log::trace(logcat, "Ignoring long poll request from {}: pool hash mismatch (remote: {}, local: {})", data->request.context.remote, req.tx_pool_checksum, checksum); + log::trace(logcat, "Ignoring long poll request from {}: pool hash mismatch (remote: {}, local: {})", data->request.context.remote, req.tx_pool_checksum, checksum); } // Either not a long poll request or checksum didn't match @@ -390,7 +390,7 @@ namespace cryptonote::rpc { if (long_pollers.empty()) return; - oxen::log::debug(logcat, "TX pool changed; sending tx pool to {} pending long poll connections", long_pollers.size()); + log::debug(logcat, "TX pool changed; sending tx pool to {} pending long poll connections", long_pollers.size()); std::optional body_public, body_admin; @@ -404,7 +404,7 @@ namespace cryptonote::rpc { pool.get_transaction_hashes(pool_hashes, data.request.context.admin, true /*include_only_blinked*/); body = pool_hashes_response(std::move(pool_hashes)); } - oxen::log::trace(logcat, "Sending deferred long poll pool update to {}", data.request.context.remote); + log::trace(logcat, "Sending deferred long poll pool update to {}", data.request.context.remote); queue_response(std::move(dataptr), *body); } long_pollers.clear(); @@ -433,7 +433,7 @@ namespace cryptonote::rpc { { if (it->second < now) { - oxen::log::trace(logcat, "Sending long poll timeout to {}", it->first->request.context.remote); + log::trace(logcat, "Sending long poll timeout to {}", it->first->request.context.remote); queue_response(std::move(it->first), long_poll_timeout_body); it = long_pollers.erase(it); count++; @@ -443,9 +443,9 @@ namespace cryptonote::rpc { } if (count > 0) - oxen::log::debug(logcat, "Timed out {} long poll connections", count); + log::debug(logcat, "Timed out {} long poll connections", count); else - oxen::log::trace(logcat, "None of {} established long poll connections reached timeout", long_pollers.size()); + log::trace(logcat, "None of {} established long poll connections reached timeout", long_pollers.size()); } } // anonymous namespace @@ -462,7 +462,7 @@ namespace cryptonote::rpc { request.context.source = rpc_source::http; request.context.remote = get_remote_address(res); handle_cors(req, data->extra_headers); - oxen::log::trace(logcat, "Received {} {} request from {}", req.getMethod(), req.getUrl(), request.context.remote); + log::trace(logcat, "Received {} {} request from {}", req.getMethod(), req.getUrl(), request.context.remote); res.onAborted([data] { data->aborted = true; }); res.onData([data=std::move(data)](std::string_view d, bool done) mutable { @@ -513,7 +513,7 @@ namespace cryptonote::rpc { try { method = &jsonrpc["method"].get_ref(); } catch (const std::exception& e) { - oxen::log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", data->request.context.remote); + log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", data->request.context.remote); return data->jsonrpc_error_response(data->res, -32600, "Invalid Request", data->jsonrpc_id); } @@ -521,17 +521,17 @@ namespace cryptonote::rpc { it != rpc_commands.end() && !it->second->is_binary) data->call = it->second.get(); else { - oxen::log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", data->request.context.remote, *method); + log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", data->request.context.remote, *method); return data->jsonrpc_error_response(data->res, -32601, "Method not found", data->jsonrpc_id); } if (restricted && !data->call->is_public) { - oxen::log::warning(logcat, "Invalid JSON RPC request from {}: method '{}' is restricted", data->request.context.remote, *method); + log::warning(logcat, "Invalid JSON RPC request from {}: method '{}' is restricted", data->request.context.remote, *method); return data->jsonrpc_error_response(data->res, 403, "Forbidden; this command is not available over public RPC", data->jsonrpc_id); } - oxen::log::debug(logcat, "Incoming JSON RPC request for {} from {}", *method, data->request.context.remote); + log::debug(logcat, "Incoming JSON RPC request for {} from {}", *method, data->request.context.remote); if (auto it = jsonrpc.find("params"); it != jsonrpc.end()) data->request.body = *it; @@ -571,7 +571,7 @@ namespace cryptonote::rpc { if (!m_sent_shutdown) { - oxen::log::trace(logcat, "initiating shutdown"); + log::trace(logcat, "initiating shutdown"); if (!m_sent_startup) { m_startup_promise.set_value(false); @@ -580,7 +580,7 @@ namespace cryptonote::rpc { else if (!m_listen_socks.empty()) { loop_defer([this] { - oxen::log::trace(logcat, "closing {} listening sockets", m_listen_socks.size()); + log::trace(logcat, "closing {} listening sockets", m_listen_socks.size()); for (auto* s : m_listen_socks) us_listen_socket_close(/*ssl=*/false, s); m_listen_socks.clear(); @@ -589,7 +589,7 @@ namespace cryptonote::rpc { { // Destroy any pending long poll connections as well - oxen::log::trace(logcat, "closing pending long poll requests"); + log::trace(logcat, "closing pending long poll requests"); std::lock_guard lock{long_poll_mutex}; for (auto it = long_pollers.begin(); it != long_pollers.end(); ) { @@ -605,10 +605,10 @@ namespace cryptonote::rpc { m_sent_shutdown = true; } - oxen::log::trace(logcat, "joining rpc thread"); + log::trace(logcat, "joining rpc thread"); if (join) m_rpc_thread.join(); - oxen::log::trace(logcat, "done shutdown"); + log::trace(logcat, "done shutdown"); } http_server::~http_server() diff --git a/src/rpc/lmq_server.cpp b/src/rpc/lmq_server.cpp index b1024d7de..9bd5a9c97 100644 --- a/src/rpc/lmq_server.cpp +++ b/src/rpc/lmq_server.cpp @@ -15,7 +15,7 @@ using oxenmq::AuthLevel; namespace { -static auto logcat = oxen::log::Cat("daemon.rpc"); +static auto logcat = log::Cat("daemon.rpc"); // TODO: all of this --lmq-blah options really should be renamed to --omq-blah, but then we *also* // need some sort of backwards compatibility shim, and that is a nuissance. @@ -112,21 +112,21 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog // the quorumnet listener set up in cryptonote_core). for (const auto &addr : command_line::get_arg(vm, arg_omq_public)) { check_omq_listen_addr(addr); - oxen::log::info(logcat, "LMQ listening on {} (public unencrypted)", addr); + log::info(logcat, "LMQ listening on {} (public unencrypted)", addr); omq.listen_plain(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::basic); }); } for (const auto &addr : command_line::get_arg(vm, arg_omq_curve_public)) { check_omq_listen_addr(addr); - oxen::log::info(logcat, "LMQ listening on {} (public curve)", addr); + log::info(logcat, "LMQ listening on {} (public curve)", addr); omq.listen_curve(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::basic); }); } for (const auto &addr : command_line::get_arg(vm, arg_omq_curve)) { check_omq_listen_addr(addr); - oxen::log::info(logcat, "LMQ listening on {} (curve restricted)", addr); + log::info(logcat, "LMQ listening on {} (curve restricted)", addr); omq.listen_curve(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::denied); }); } @@ -148,7 +148,7 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog } for (const auto &addr : locals) { check_omq_listen_addr(addr); - oxen::log::info(logcat, "OMQ listening on {} (unauthenticated local admin)", addr); + log::info(logcat, "OMQ listening on {} (unauthenticated local admin)", addr); omq.listen_plain(addr, [&core](std::string_view ip, std::string_view pk, bool /*sn*/) { return core.omq_allow(ip, pk, AuthLevel::admin); }); } @@ -227,17 +227,17 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog // warnings that get generated deep inside epee, for example when passing a string or // number instead of a JSON object. If you want to find some, `grep number2 epee` (for // real). - oxen::log::info(logcat, "LMQ RPC request '{}{}' called with invalid/unparseable data: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); + log::info(logcat, "LMQ RPC request '{}{}' called with invalid/unparseable data: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); m.send_reply(LMQ_BAD_REQUEST, "Unable to parse request: "s + e.what()); return; } catch (const rpc_error& e) { - oxen::log::warning(logcat, "LMQ RPC request '{}{}' failed with: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); + log::warning(logcat, "LMQ RPC request '{}{}' failed with: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); m.send_reply(LMQ_ERROR, e.what()); return; } catch (const std::exception& e) { - oxen::log::warning(logcat, "LMQ RPC request '{}{}' raised an exception: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); + log::warning(logcat, "LMQ RPC request '{}{}' raised an exception: {}", (call.is_public ? "rpc." : "admin."), name, e.what()); } catch (...) { - oxen::log::warning(logcat, "LMQ RPC request '{}{}' raised an unknown exception", (call.is_public ? "rpc." : "admin."), name); + log::warning(logcat, "LMQ RPC request '{}{}' raised an unknown exception", (call.is_public ? "rpc." : "admin."), name); } // Don't include the exception message in case it contains something that we don't want go // back to the user. If we want to support it eventually we could add some sort of @@ -300,7 +300,7 @@ static void send_notifies(Mutex& mutex, Subs& subs, const char* desc, Call call) for (auto& conn : remove) { auto it = subs.find(conn); if (it != subs.end() && it->second.expiry < now /* recheck: client might have resubscribed in between locks */) { - oxen::log::debug(logcat, "Removing {} from {} subscriptions: subscription timed out", conn, desc); + log::debug(logcat, "Removing {} from {} subscriptions: subscription timed out", conn, desc); subs.erase(it); } } @@ -534,13 +534,13 @@ void omq_rpc::on_mempool_sub_request(oxenmq::Message& m) if (!result.second) { result.first->second.expiry = expiry; if (result.first->second.type == sub_type) { - oxen::log::trace(logcat, "Renewed mempool subscription request from conn id {}@{}", m.conn, m.remote); + log::trace(logcat, "Renewed mempool subscription request from conn id {}@{}", m.conn, m.remote); m.send_reply("ALREADY"); return; } result.first->second.type = sub_type; } - oxen::log::debug(logcat, "New {} mempool subscription request from conn {}@{}", (sub_type == mempool_sub_type::blink ? "blink" : "all"), m.conn, m.remote); + log::debug(logcat, "New {} mempool subscription request from conn {}@{}", (sub_type == mempool_sub_type::blink ? "blink" : "all"), m.conn, m.remote); m.send_reply("OK"); } } @@ -563,10 +563,10 @@ void omq_rpc::on_block_sub_request(oxenmq::Message& m) auto result = block_subs_.emplace(m.conn, block_sub{expiry}); if (!result.second) { result.first->second.expiry = expiry; - oxen::log::trace(logcat, "Renewed block subscription request from conn id {}@{}", m.conn, m.remote); + log::trace(logcat, "Renewed block subscription request from conn id {}@{}", m.conn, m.remote); m.send_reply("ALREADY"); } else { - oxen::log::debug(logcat, "New block subscription request from conn {}@{}", m.conn, m.remote); + log::debug(logcat, "New block subscription request from conn {}@{}", m.conn, m.remote); m.send_reply("OK"); } } diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 60239ccd2..ee6dc9ca1 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -92,8 +92,9 @@ extern "C" #include } -using namespace cryptonote; -namespace po = boost::program_options; +namespace cryptonote +{ + namespace string_tools = epee::string_tools; using sw = cryptonote::simple_wallet; @@ -124,7 +125,7 @@ using sw = cryptonote::simple_wallet; namespace { - static auto logcat = oxen::log::Cat("wallet.simplewallet"); + auto logcat = log::Cat("wallet.simplewallet"); const auto arg_wallet_file = wallet_args::arg_wallet_file(); const command_line::arg_descriptor arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to "), ""}; @@ -292,7 +293,7 @@ namespace auto pwd_container = tools::password_container::prompt(false, prompt, false); if (!pwd_container) { - oxen::log::error(logcat, "Failed to read secure line"); + log::error(logcat, "Failed to read secure line"); return ""; } @@ -452,7 +453,7 @@ namespace } catch (const tools::error::wallet_rpc_error& e) { - oxen::log::error(logcat, "RPC error: {}", e.to_string()); + log::error(logcat, "RPC error: {}", e.to_string()); fail_msg_writer() << sw::tr("RPC error: ") << e.what(); } catch (const tools::error::get_outs_error &e) @@ -461,19 +462,19 @@ namespace } catch (const tools::error::not_enough_unlocked_money& e) { - oxen::log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); + log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::not_enough_money& e) { - oxen::log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); + log::warning(logcat, "not enough money to transfer, available only {}, sent amount {}", print_money(e.available()), print_money(e.tx_amount())); fail_msg_writer() << sw::tr("Not enough money in unlocked balance"); warn_of_possible_attack = false; } catch (const tools::error::tx_not_possible& e) { - oxen::log::warning(logcat, "not enough money to transfer, available only {}, transaction amount {} = {} + {} (fee)", + log::warning(logcat, "not enough money to transfer, available only {}, transaction amount {} = {} + {} (fee)", print_money(e.available()), print_money(e.tx_amount() + e.fee()), print_money(e.tx_amount()), @@ -520,23 +521,23 @@ namespace } catch (const tools::error::transfer_error& e) { - oxen::log::error(logcat, "unknown transfer error: {}", e.to_string()); + log::error(logcat, "unknown transfer error: {}", e.to_string()); fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what(); } catch (const tools::error::multisig_export_needed& e) { - oxen::log::error(logcat, "Multisig error: {}", e.to_string()); + log::error(logcat, "Multisig error: {}", e.to_string()); fail_msg_writer() << sw::tr("Multisig error: ") << e.what(); warn_of_possible_attack = false; } catch (const tools::error::wallet_internal_error& e) { - oxen::log::error(logcat, "internal error: {}", e.to_string()); + log::error(logcat, "internal error: {}", e.to_string()); fail_msg_writer() << sw::tr("internal error: ") << e.what(); } catch (const std::exception& e) { - oxen::log::error(logcat, "unexpected error: {}", e.what()); + log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << sw::tr("unexpected error: ") << e.what(); } @@ -1182,7 +1183,7 @@ bool simple_wallet::export_multisig_main(const std::vector &args EN } catch (const std::exception &e) { - oxen::log::error(logcat, "Error exporting multisig info: {}", e.what()); + log::error(logcat, "Error exporting multisig info: {}", e.what()); fail_msg_writer() << tr("Error exporting multisig info: ") << e.what(); return false; } @@ -1488,7 +1489,7 @@ bool simple_wallet::submit_multisig_main(const std::vector &args EN } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return false; } @@ -1562,12 +1563,12 @@ bool simple_wallet::export_raw_multisig(const std::vector &args) } catch (const std::exception& e) { - oxen::log::error(logcat, "unexpected error: {}", e.what()); + log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { - oxen::log::error(logcat, "Unknown error"); + log::error(logcat, "Unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -2122,7 +2123,7 @@ bool simple_wallet::cold_sign_tx(const std::vector& if (accept_func && !accept_func(exported_txs)) { - oxen::log::error(logcat, "Transactions rejected by callback"); + log::error(logcat, "Transactions rejected by callback"); return false; } @@ -2507,7 +2508,7 @@ bool simple_wallet::set_device_name(const std::vector &args/* = std } } catch(const std::exception & e){ - oxen::log::warning(logcat, "Device reconnect failed: {}", e.what()); + log::warning(logcat, "Device reconnect failed: {}", e.what()); fail_msg_writer() << tr("Device reconnect failed: ") << e.what(); } @@ -3240,7 +3241,7 @@ bool simple_wallet::set_log(const std::vector &args) { auto log_level = oxen::logging::parse_level(args[0]); if (log_level.has_value()) - oxen::log::reset_level(*log_level); + log::reset_level(*log_level); else { oxen::logging::process_categories_string(args[0]); } @@ -3252,7 +3253,7 @@ bool simple_wallet::set_log(const std::vector &args) //---------------------------------------------------------------------------------------------------- bool simple_wallet::ask_wallet_create_if_needed() { - oxen::log::trace(logcat, "simple_wallet::ask_wallet_create_if_needed() started"); + log::trace(logcat, "simple_wallet::ask_wallet_create_if_needed() started"); fs::path wallet_path; std::string confirm_creation; bool wallet_name_valid = false; @@ -3260,7 +3261,7 @@ bool simple_wallet::ask_wallet_create_if_needed() bool wallet_file_exists; do{ - oxen::log::trace(logcat, "User asked to specify wallet file name."); + log::trace(logcat, "User asked to specify wallet file name."); wallet_path = fs::u8path(input_line( tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n" "Wallet file name (or Ctrl-C to quit)" : @@ -3269,7 +3270,7 @@ bool simple_wallet::ask_wallet_create_if_needed() )); if(std::cin.eof()) { - oxen::log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); + log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } if(wallet_path.empty()) @@ -3280,8 +3281,8 @@ bool simple_wallet::ask_wallet_create_if_needed() else { tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists); - oxen::log::trace(logcat, "wallet_path: {}", wallet_path); - oxen::log::trace(logcat, "keys_file_exists: {} wallet_file_exists: {}", keys_file_exists, wallet_file_exists); + log::trace(logcat, "wallet_path: {}", wallet_path); + log::trace(logcat, "keys_file_exists: {} wallet_file_exists: {}", keys_file_exists, wallet_file_exists); if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring)) { @@ -3315,7 +3316,7 @@ bool simple_wallet::ask_wallet_create_if_needed() confirm_creation = input_line(prompt, true); if(std::cin.eof()) { - oxen::log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); + log::error(logcat, "Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()"); return false; } ok = command_line::is_yes(confirm_creation); @@ -3330,7 +3331,7 @@ bool simple_wallet::ask_wallet_create_if_needed() } } while(!wallet_name_valid); - oxen::log::error(logcat, "Failed out of do-while loop in ask_wallet_create_if_needed()"); + log::error(logcat, "Failed out of do-while loop in ask_wallet_create_if_needed()"); return false; } @@ -4708,7 +4709,7 @@ bool simple_wallet::set_daemon(const std::vector& args) } else if (is_local) { - oxen::log::info(logcat, tr("Daemon is local, assuming trusted")); + log::info(logcat, tr("Daemon is local, assuming trusted")); m_wallet->set_trusted_daemon(true); } success_msg_writer() << "Daemon set to " << daemon_url << ", " << tr(m_wallet->is_trusted_daemon() ? "trusted" : "untrusted"); @@ -4855,7 +4856,7 @@ std::optional simple_wallet::on_get_password(const char * auto pwd_container = tools::password_container::prompt(false, msg.c_str()); if (!pwd_container) { - oxen::log::error(logcat, "Failed to read password"); + log::error(logcat, "Failed to read password"); return std::nullopt; } @@ -4988,27 +4989,27 @@ bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bo } catch (const tools::error::wallet_rpc_error& e) { - oxen::log::error(logcat, "RPC error: {}", e.to_string()); + log::error(logcat, "RPC error: {}", e.to_string()); ss << tr("RPC error: ") << e.what(); } catch (const tools::error::refresh_error& e) { - oxen::log::error(logcat, "refresh error: {}", e.to_string()); + log::error(logcat, "refresh error: {}", e.to_string()); ss << tr("refresh error: ") << e.what(); } catch (const tools::error::wallet_internal_error& e) { - oxen::log::error(logcat, "internal error: {}", e.to_string()); + log::error(logcat, "internal error: {}", e.to_string()); ss << tr("internal error: ") << e.what(); } catch (const std::exception& e) { - oxen::log::error(logcat, "unexpected error: {}", e.what()); + log::error(logcat, "unexpected error: {}", e.what()); ss << tr("unexpected error: ") << e.what(); } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); ss << tr("unknown error"); } @@ -5360,17 +5361,17 @@ bool simple_wallet::rescan_spent(const std::vector &args) } catch (const tools::error::wallet_rpc_error& e) { - oxen::log::error(logcat, "RPC error: {}", e.to_string()); + log::error(logcat, "RPC error: {}", e.to_string()); fail_msg_writer() << tr("RPC error: ") << e.what(); } catch (const std::exception& e) { - oxen::log::error(logcat, "unexpected error: {}", e.what()); + log::error(logcat, "unexpected error: {}", e.what()); fail_msg_writer() << tr("unexpected error: ") << e.what(); } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -5800,7 +5801,7 @@ bool simple_wallet::confirm_and_send_tx(std::vector &args_) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -6203,7 +6204,7 @@ bool simple_wallet::stake(const std::vector &args_) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } } @@ -6272,7 +6273,7 @@ bool simple_wallet::request_stake_unlock(const std::vector &args_) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -6688,7 +6689,7 @@ bool simple_wallet::ons_buy_mapping(std::vector args) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -6767,7 +6768,7 @@ bool simple_wallet::ons_renew_mapping(std::vector args) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -6823,7 +6824,7 @@ bool simple_wallet::ons_update_mapping(std::vector args) auto enc_hex = response[0]["encrypted_value"].get(); if (!oxenc::is_hex(enc_hex) || enc_hex.size() > 2*ons::mapping_value::BUFFER_SIZE) { - oxen::log::error(logcat, "invalid ONS data returned from oxend"); + log::error(logcat, "invalid ONS data returned from oxend"); fail_msg_writer() << tr("invalid ONS data returned from oxend"); return true; } @@ -6895,7 +6896,7 @@ bool simple_wallet::ons_update_mapping(std::vector args) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); return true; } @@ -7290,7 +7291,7 @@ bool simple_wallet::sweep_unmixable(const std::vector &args_) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -7413,7 +7414,7 @@ bool simple_wallet::sweep_main_internal(sweep_type_t sweep_type, std::vector &args_) } catch (...) { - oxen::log::error(logcat, "unknown error"); + log::error(logcat, "unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -7997,7 +7998,7 @@ bool simple_wallet::submit_transfer(const std::vector &args_) } catch (...) { - oxen::log::error(logcat, "Unknown error"); + log::error(logcat, "Unknown error"); fail_msg_writer() << tr("unknown error"); } @@ -9852,7 +9853,7 @@ bool simple_wallet::export_key_images(const std::vector &args) } catch (const std::exception &e) { - oxen::log::error(logcat, "Error exporting key images: {}", e.what()); + log::error(logcat, "Error exporting key images: {}", e.what()); fail_msg_writer() << "Error exporting key images: " << e.what(); return true; } @@ -10009,7 +10010,7 @@ bool simple_wallet::export_outputs(const std::vector &args) } catch (const std::exception &e) { - oxen::log::error(logcat, "Error exporting outputs: {}", e.what()); + log::error(logcat, "Error exporting outputs: {}", e.what()); fail_msg_writer() << "Error exporting outputs: " << e.what(); return true; } @@ -10283,6 +10284,9 @@ void simple_wallet::commit_or_save(std::vector& ptx_ ptx_vector.pop_back(); } } + +} // namespace cryptonote + //---------------------------------------------------------------------------------------------------- int main(int argc, char* argv[]) { @@ -10292,6 +10296,9 @@ int main(int argc, char* argv[]) auto opt_size = command_line::boost_option_sizes(); + using namespace cryptonote; + namespace po = boost::program_options; + po::options_description desc_params(wallet_args::tr("Wallet options"), opt_size.first, opt_size.second); po::options_description hidden_params("Hidden"); tools::wallet2::init_options(desc_params, hidden_params); diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index 485597b25..30772d04d 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -61,8 +61,6 @@ */ namespace cryptonote { - static auto logcat = oxen::log::Cat("wallet.simplewallet"); - enum class Transfer { Normal, Locked @@ -397,7 +395,7 @@ namespace cryptonote } else { - oxen::log::error(logcat, "Failed to get current blockchain height: {}", err); + log::error(log::Cat("wallet.simplewallet"), "Failed to get current blockchain height: {}", err); } } diff --git a/src/sqlitedb/database.cpp b/src/sqlitedb/database.cpp index 06ce0a7d7..3d5388b71 100644 --- a/src/sqlitedb/database.cpp +++ b/src/sqlitedb/database.cpp @@ -5,8 +5,6 @@ namespace db { - static auto logcat = oxen::log::Cat("db.sqlite"); - std::string multi_in_query(std::string_view prefix, size_t count, std::string_view suffix) { std::string query; @@ -46,20 +44,20 @@ namespace db { // Don't fail on these because we can still work even if they fail if (int rc = db.tryExec("PRAGMA journal_mode = WAL"); rc != SQLITE_OK) - oxen::log::error(logcat, "Failed to set journal mode to WAL: {}{}", sqlite3_errstr(rc)); + log::error(sqlitedb_logcat, "Failed to set journal mode to WAL: {}{}", sqlite3_errstr(rc)); if (int rc = db.tryExec("PRAGMA synchronous = NORMAL"); rc != SQLITE_OK) - oxen::log::error(logcat, "Failed to set synchronous mode to NORMAL: {}{}", sqlite3_errstr(rc)); + log::error(sqlitedb_logcat, "Failed to set synchronous mode to NORMAL: {}{}", sqlite3_errstr(rc)); if (int rc = db.tryExec("PRAGMA foreign_keys = ON"); rc != SQLITE_OK) { - oxen::log::error(logcat, "Failed to enable foreign keys constraints: {}", sqlite3_errstr(rc)); + log::error(sqlitedb_logcat, "Failed to enable foreign keys constraints: {}", sqlite3_errstr(rc)); throw std::runtime_error{"Foreign key constrains required"}; } int fk_enabled = db.execAndGet("PRAGMA foreign_keys").getInt(); if (fk_enabled != 1) { - oxen::log::error(logcat, "Failed to enable foreign key constraints; perhaps this sqlite3 is compiled without it?"); + log::error(sqlitedb_logcat, "Failed to enable foreign key constraints; perhaps this sqlite3 is compiled without it?"); throw std::runtime_error{"Foreign key support is required"}; } diff --git a/src/sqlitedb/database.hpp b/src/sqlitedb/database.hpp index 79b68f53a..4ea88559d 100644 --- a/src/sqlitedb/database.hpp +++ b/src/sqlitedb/database.hpp @@ -19,6 +19,9 @@ namespace db { + namespace log = oxen::log; + inline auto sqlitedb_logcat = log::Cat("db.sqlite"); + template constexpr bool is_cstr = false; template @@ -139,7 +142,7 @@ namespace db { if (result) { - oxen::log::error(oxen::log::Cat("db.sqlite"), "Expected single-row result, got multiple rows from {}", st.getQuery()); + log::error(sqlitedb_logcat, "Expected single-row result, got multiple rows from {}", st.getQuery()); throw std::runtime_error{"DB error: expected single-row result, got multiple rows"}; } result = get(st); @@ -158,7 +161,7 @@ namespace db auto maybe_result = exec_and_maybe_get(st, bind...); if (!maybe_result) { - oxen::log::error(oxen::log::Cat("db.sqlite"), "Expected single-row result, got no rows from {}", st.getQuery()); + log::error(sqlitedb_logcat, "Expected single-row result, got no rows from {}", st.getQuery()); throw std::runtime_error{"DB error: expected single-row result, got no rows"}; } return *std::move(maybe_result); diff --git a/src/wallet/api/address_book.cpp b/src/wallet/api/address_book.cpp index cd29a1452..38c942fca 100644 --- a/src/wallet/api/address_book.cpp +++ b/src/wallet/api/address_book.cpp @@ -70,7 +70,7 @@ bool AddressBookImpl::addRow(const std::string &dst_addr, const std::string &des EXPORT void AddressBookImpl::refresh() { - oxen::log::debug(logcat, "Refreshing addressbook"); + log::debug(logcat, "Refreshing addressbook"); clearRows(); @@ -93,7 +93,7 @@ void AddressBookImpl::refresh() EXPORT bool AddressBookImpl::deleteRow(std::size_t rowId) { - oxen::log::debug(logcat, "Deleting address book row {}", rowId); + log::debug(logcat, "Deleting address book row {}", rowId); bool r = m_wallet->wallet()->delete_address_book_row(rowId); if (r) refresh(); diff --git a/src/wallet/api/pending_transaction.cpp b/src/wallet/api/pending_transaction.cpp index b4ea73e21..07f933a8b 100644 --- a/src/wallet/api/pending_transaction.cpp +++ b/src/wallet/api/pending_transaction.cpp @@ -83,7 +83,7 @@ EXPORT bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, bool blink) { - oxen::log::trace(logcat, "m_pending_tx size: {}", m_pending_tx.size()); + log::trace(logcat, "m_pending_tx size: {}", m_pending_tx.size()); auto filename = fs::u8path(filename_); @@ -93,7 +93,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, if (!filename.empty()) { if (std::error_code ec_ignore; fs::exists(filename, ec_ignore) && !overwrite){ m_status = {Status_Error, tr("Attempting to save transaction to file, but specified file(s) exist. Exiting to not risk overwriting. File:") + filename.u8string()}; - oxen::log::error(m_status.second); + log::error(m_status.second); return false; } bool r = w->save_tx(m_pending_tx, filename); @@ -147,7 +147,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, m_status = {Status_Error, std::string(tr("Unknown exception: ")) + e.what()}; } catch (...) { m_status = {Status_Error, tr("Unhandled exception")}; - oxen::log::error(m_status.second); + log::error(m_status.second); } return good(); diff --git a/src/wallet/api/stake_unlock_result.cpp b/src/wallet/api/stake_unlock_result.cpp index 1489230c5..1d68cc675 100644 --- a/src/wallet/api/stake_unlock_result.cpp +++ b/src/wallet/api/stake_unlock_result.cpp @@ -13,7 +13,7 @@ StakeUnlockResultImpl::StakeUnlockResultImpl(WalletImpl& w, tools::wallet2::requ EXPORT StakeUnlockResultImpl::~StakeUnlockResultImpl() { - oxen::log::trace(logcat, "Stake Unlock Result Deleted"); + log::trace(logcat, "Stake Unlock Result Deleted"); } //---------------------------------------------------------------------------------------------------- diff --git a/src/wallet/api/stake_unlock_result.h b/src/wallet/api/stake_unlock_result.h index 6465a1c2c..7fc45739d 100644 --- a/src/wallet/api/stake_unlock_result.h +++ b/src/wallet/api/stake_unlock_result.h @@ -1,8 +1,4 @@ -#include "wallet/api/wallet2_api.h" -#include "wallet/wallet2.h" - -#include - +#include "wallet/api/wallet.h" namespace Wallet { diff --git a/src/wallet/api/subaddress.cpp b/src/wallet/api/subaddress.cpp index 93ee81b17..0509c4ad1 100644 --- a/src/wallet/api/subaddress.cpp +++ b/src/wallet/api/subaddress.cpp @@ -60,14 +60,14 @@ void SubaddressImpl::setLabel(uint32_t accountIndex, uint32_t addressIndex, cons } catch (const std::exception& e) { - oxen::log::error(logcat, "setLabel: {}", e.what()); + log::error(logcat, "setLabel: {}", e.what()); } } EXPORT void SubaddressImpl::refresh(uint32_t accountIndex) { - oxen::log::debug(logcat, "Refreshing subaddress"); + log::debug(logcat, "Refreshing subaddress"); clearRows(); auto w = m_wallet->wallet(); diff --git a/src/wallet/api/subaddress_account.cpp b/src/wallet/api/subaddress_account.cpp index 6152f2213..6188bc0e3 100644 --- a/src/wallet/api/subaddress_account.cpp +++ b/src/wallet/api/subaddress_account.cpp @@ -60,7 +60,7 @@ void SubaddressAccountImpl::setLabel(uint32_t accountIndex, const std::string &l EXPORT void SubaddressAccountImpl::refresh() { - oxen::log::debug(logcat, "Refreshing subaddress account"); + log::debug(logcat, "Refreshing subaddress account"); clearRows(); auto w = m_wallet->wallet(); diff --git a/src/wallet/api/transaction_history.cpp b/src/wallet/api/transaction_history.cpp index 7ce8d364b..9119074fd 100644 --- a/src/wallet/api/transaction_history.cpp +++ b/src/wallet/api/transaction_history.cpp @@ -259,7 +259,7 @@ void TransactionHistoryImpl::refresh() ti->m_is_stake = pd.m_type == wallet::pay_type::stake; m_history.push_back(ti); - oxen::log::info(logcat, "{}: Unconfirmed payment found {}", __FUNCTION__, pd.m_amount); + log::info(logcat, "{}: Unconfirmed payment found {}", __FUNCTION__, pd.m_amount); } } diff --git a/src/wallet/api/unsigned_transaction.cpp b/src/wallet/api/unsigned_transaction.cpp index b8951507a..af9566ee0 100644 --- a/src/wallet/api/unsigned_transaction.cpp +++ b/src/wallet/api/unsigned_transaction.cpp @@ -55,7 +55,7 @@ UnsignedTransactionImpl::UnsignedTransactionImpl(WalletImpl &wallet) EXPORT UnsignedTransactionImpl::~UnsignedTransactionImpl() { - oxen::log::trace(logcat, "Unsigned tx deleted"); + log::trace(logcat, "Unsigned tx deleted"); } EXPORT @@ -288,7 +288,7 @@ std::vector UnsignedTransactionImpl::recipientAddress() const std::vector result; for (const auto &utx: m_unsigned_tx_set.txes) { if (utx.dests.empty()) { - oxen::log::error(logcat, "empty destinations, skipped"); + log::error(logcat, "empty destinations, skipped"); continue; } result.push_back(cryptonote::get_account_address_as_str(m_wallet.m_wallet_ptr->nettype(), utx.dests[0].is_subaddress, utx.dests[0].addr)); diff --git a/src/wallet/api/utils.cpp b/src/wallet/api/utils.cpp index 542a1f194..f5046bd4b 100644 --- a/src/wallet/api/utils.cpp +++ b/src/wallet/api/utils.cpp @@ -31,6 +31,7 @@ #include "common_defines.h" #include "epee/misc_log_ex.h" #include "common/util.h" +#include "wallet.h" namespace Wallet { namespace Utils { @@ -41,7 +42,7 @@ bool isAddressLocal(const std::string &address) try { return tools::is_local_address(address); } catch (const std::exception &e) { - oxen::log::error(logcat, "error: {}", e.what()); + log::error(logcat, "error: {}", e.what()); return false; } } diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index 6cd48ed87..87ae124a1 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -58,8 +58,6 @@ using namespace cryptonote; namespace Wallet { - static auto logcat = oxen::log::Cat("WalletAPI"); - namespace { static const int DEFAULT_REFRESH_INTERVAL_MILLIS = 1000 * 10; // limit maximum refresh interval as one minute @@ -143,7 +141,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback // created or the restore height specified when wallet was recovered // if(height >= m_wallet->m_wallet_ptr->get_refresh_from_block_height() || height % 1000 == 0) { - // oxen::log::trace(logcat, "{}: new block. height: {}", __FUNCTION__, height); + // log::trace(logcat, "{}: new block. height: {}", __FUNCTION__, height); if (m_listener) { m_listener->newBlock(height); } @@ -155,7 +153,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { std::string tx_hash = tools::type_to_hex(txid); - oxen::log::trace(logcat, "{}: money received.{}{}", __FUNCTION__, (blink ? "blink: " : "height: "), height + log::trace(logcat, "{}: money received.{}{}", __FUNCTION__, (blink ? "blink: " : "height: "), height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -172,7 +170,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback std::string tx_hash = tools::type_to_hex(txid); - oxen::log::trace(logcat, "{}: unconfirmed money received. height: {}", __FUNCTION__, height + log::trace(logcat, "{}: unconfirmed money received. height: {}", __FUNCTION__, height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -193,7 +191,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { // TODO; std::string tx_hash = tools::type_to_hex(txid); - oxen::log::trace(logcat, "{}: money spent. height: {}", __FUNCTION__, height + log::trace(logcat, "{}: money spent. height: {}", __FUNCTION__, height << ", tx: " << tx_hash << ", amount: " << print_money(amount) << ", idx: " << subaddr_index); @@ -416,17 +414,17 @@ void Wallet::init(const char *argv0, const char *default_log_base_name, const st EXPORT void Wallet::debug(const std::string &category, const std::string &str) { - oxen::log::debug(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + log::debug(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT void Wallet::info(const std::string &category, const std::string &str) { - oxen::log::info(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + log::info(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT void Wallet::warning(const std::string &category, const std::string &str) { - oxen::log::warning(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + log::warning(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); } EXPORT @@ -481,7 +479,7 @@ EXPORT WalletImpl::~WalletImpl() { - oxen::log::info(__FUNCTION__); + log::info(__FUNCTION__); m_wallet_ptr->callback(nullptr); // Stop refresh and long poll threads stopRefresh(); @@ -496,7 +494,7 @@ WalletImpl::~WalletImpl() m_wallet2Callback->getListener()->onSetWallet(nullptr); } - oxen::log::info(logcat, "{} finished", __FUNCTION__); + log::info(logcat, "{} finished", __FUNCTION__); } EXPORT @@ -510,15 +508,15 @@ bool WalletImpl::create(std::string_view path_, const std::string &password, con bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - oxen::log::trace(logcat, "wallet_path: {}", path); - oxen::log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha + log::trace(logcat, "wallet_path: {}", path); + log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting."; - oxen::log::error(error); + log::error(error); setStatusCritical(error); return false; } @@ -531,7 +529,7 @@ bool WalletImpl::create(std::string_view path_, const std::string &password, con m_password = password; clearStatus(); } catch (const std::exception &e) { - oxen::log::error(logcat, "Error creating wallet: {}", e.what()); + log::error(logcat, "Error creating wallet: {}", e.what()); setStatusCritical(e.what()); return false; } @@ -553,14 +551,14 @@ bool WalletImpl::createWatchOnly(std::string_view path_, const std::string &pass bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - oxen::log::trace(logcat, "wallet_path: {}", path); - oxen::log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha + log::trace(logcat, "wallet_path: {}", path); + log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate view only wallet, but specified file(s) exist. Exiting to not risk overwriting."; - oxen::log::error(error); + log::error(error); setStatusError(error); return false; } @@ -599,7 +597,7 @@ bool WalletImpl::createWatchOnly(std::string_view path_, const std::string &pass view_wallet->import_key_images(key_images.second, key_images.first, spent, unspent, false); clearStatus(); } catch (const std::exception &e) { - oxen::log::error(logcat, "Error creating view only wallet: {}", e.what()); + log::error(logcat, "Error creating view only wallet: {}", e.what()); setStatusError(e.what()); return false; } @@ -680,16 +678,16 @@ bool WalletImpl::recoverFromKeysWithPassword(std::string_view path_, auto w = wallet(); if (has_spendkey && has_viewkey) { w->generate(path, password, info.address, spendkey, viewkey); - oxen::log::info(logcat, "Generated new wallet from spend key and view key"); + log::info(logcat, "Generated new wallet from spend key and view key"); } if(!has_spendkey && has_viewkey) { w->generate(path, password, info.address, viewkey); - oxen::log::info(logcat, "Generated new view only wallet from keys"); + log::info(logcat, "Generated new view only wallet from keys"); } if(has_spendkey && !has_viewkey) { w->generate(path, password, spendkey, true, false); setSeedLanguage(language); - oxen::log::info(logcat, "Generated deterministic wallet from spend key with seed language: " + language); + log::info(logcat, "Generated deterministic wallet from spend key with seed language: " + language); } } @@ -711,7 +709,7 @@ bool WalletImpl::recoverFromDevice(std::string_view path_, const std::string &pa try { w->restore_from_device(path, password, device_name); - oxen::log::info(logcat, "Generated new wallet from device: " + device_name); + log::info(logcat, "Generated new wallet from device: " + device_name); } catch (const std::exception& e) { setStatusError(std::string(tr("failed to generate new wallet: ")) + e.what()); @@ -749,7 +747,7 @@ bool WalletImpl::open(std::string_view path_, const std::string &password) m_password = password; } catch (const std::exception &e) { - oxen::log::error(logcat, "Error opening wallet: {}", e.what()); + log::error(logcat, "Error opening wallet: {}", e.what()); setStatusCritical(e.what()); } return good(); @@ -761,7 +759,7 @@ bool WalletImpl::recover(std::string_view path_, const std::string &password, co auto path = fs::u8path(path_); clearStatus(); if (seed.empty()) { - oxen::log::error(logcat, "Electrum seed is empty"); + log::error(logcat, "Electrum seed is empty"); setStatusError(tr("Electrum seed is empty")); return false; } @@ -798,7 +796,7 @@ bool WalletImpl::close(bool store) { bool result = false; - oxen::log::info(logcat, "closing wallet..."); + log::info(logcat, "closing wallet..."); try { auto w = wallet(); if (store) { @@ -807,18 +805,18 @@ bool WalletImpl::close(bool store) if (status().first != Status_Critical) w->store(); else - oxen::log::error(logcat, "Status_Critical - not saving wallet"); - oxen::log::info(logcat, "wallet::store done"); + log::error(logcat, "Status_Critical - not saving wallet"); + log::info(logcat, "wallet::store done"); } - oxen::log::info(logcat, "Calling wallet::stop..."); + log::info(logcat, "Calling wallet::stop..."); w->stop(); - oxen::log::info(logcat, "wallet::stop done"); + log::info(logcat, "wallet::stop done"); w->deinit(); result = true; clearStatus(); } catch (const std::exception &e) { setStatusCritical(e.what()); - oxen::log::error(logcat, "Error closing wallet: {}", e.what()); + log::error(logcat, "Error closing wallet: {}", e.what()); } return result; } @@ -961,7 +959,7 @@ bool WalletImpl::store(std::string_view path_) wallet()->store_to(path, m_password); } } catch (const std::exception &e) { - oxen::log::error(logcat, "Error saving wallet: {}", e.what()); + log::error(logcat, "Error saving wallet: {}", e.what()); setStatusError(e.what()); return false; } @@ -1019,7 +1017,7 @@ bool WalletImpl::lightWalletImportWalletRequest(std::string &payment_id, uint64_ } catch (const std::exception &e) { - oxen::log::error(logcat, "Error sending import wallet request: {}", e.what()); + log::error(logcat, "Error sending import wallet request: {}", e.what()); setStatusError(e.what()); return false; } @@ -1139,7 +1137,7 @@ uint64_t WalletImpl::daemonBlockChainHeight() const std::string err; uint64_t result = w->get_daemon_blockchain_height(err); if (!err.empty()) { - oxen::log::error(logcat, "{}: {}", __FUNCTION__, err); + log::error(logcat, "{}: {}", __FUNCTION__, err); result = 0; setStatusError(err); } else { @@ -1165,7 +1163,7 @@ uint64_t WalletImpl::daemonBlockChainTargetHeight() const std::string err; uint64_t result = w->get_daemon_blockchain_target_height(err); if (!err.empty()) { - oxen::log::error(logcat, "{}: {}", __FUNCTION__, err); + log::error(logcat, "{}: {}", __FUNCTION__, err); result = 0; setStatusError(err); } else { @@ -1205,7 +1203,7 @@ bool WalletImpl::refresh() EXPORT void WalletImpl::refreshAsync() { - oxen::log::trace(logcat, "{}: Refreshing asynchronously..", __FUNCTION__); + log::trace(logcat, "{}: Refreshing asynchronously..", __FUNCTION__); clearStatus(); m_refreshCV.notify_one(); } @@ -1236,7 +1234,7 @@ EXPORT void WalletImpl::setAutoRefreshInterval(int millis) { if (millis > MAX_REFRESH_INTERVAL_MILLIS) { - oxen::log::error(logcat, "{}: invalid refresh interval {}", __FUNCTION__, millis + log::error(logcat, "{}: invalid refresh interval {}", __FUNCTION__, millis << " ms, maximum allowed is " << MAX_REFRESH_INTERVAL_MILLIS << " ms"); m_refreshIntervalMillis = MAX_REFRESH_INTERVAL_MILLIS; } else { @@ -1313,7 +1311,7 @@ bool WalletImpl::exportKeyImages(std::string_view filename_) } catch (const std::exception &e) { - oxen::log::error(logcat, "Error exporting key images: {}", e.what()); + log::error(logcat, "Error exporting key images: {}", e.what()); setStatusError(e.what()); return false; } @@ -1332,12 +1330,12 @@ bool WalletImpl::importKeyImages(std::string_view filename_) { uint64_t spent = 0, unspent = 0; uint64_t height = wallet()->import_key_images_from_file(filename, spent, unspent); - oxen::log::debug(logcat, "Signed key images imported to height {}, ", height + log::debug(logcat, "Signed key images imported to height {}, ", height << print_money(spent) << " spent, " << print_money(unspent) << " unspent"); } catch (const std::exception &e) { - oxen::log::error(logcat, "Error exporting key images: {}", e.what()); + log::error(logcat, "Error exporting key images: {}", e.what()); setStatusError(std::string(tr("Failed to import key images: ")) + e.what()); return false; } @@ -1374,7 +1372,7 @@ std::string WalletImpl::getSubaddressLabel(uint32_t accountIndex, uint32_t addre } catch (const std::exception &e) { - oxen::log::error(logcat, "Error getting subaddress label: {}", e.what()); + log::error(logcat, "Error getting subaddress label: {}", e.what()); setStatusError(std::string(tr("Failed to get subaddress label: ")) + e.what()); return ""; } @@ -1388,7 +1386,7 @@ void WalletImpl::setSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex } catch (const std::exception &e) { - oxen::log::error(logcat, "Error setting subaddress label: {}", e.what()); + log::error(logcat, "Error setting subaddress label: {}", e.what()); setStatusError(std::string(tr("Failed to set subaddress label: ")) + e.what()); } } @@ -1411,7 +1409,7 @@ std::string WalletImpl::getMultisigInfo() const { clearStatus(); return wallet()->get_multisig_info(); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on generating multisig info: {}", e.what()); + log::error(logcat, "Error on generating multisig info: {}", e.what()); setStatusError(std::string(tr("Failed to get multisig info: ")) + e.what()); } @@ -1429,7 +1427,7 @@ std::string WalletImpl::makeMultisig(const std::vector& info, uint3 return w->make_multisig(epee::wipeable_string(m_password), info, threshold); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on making multisig wallet: {}", e.what()); + log::error(logcat, "Error on making multisig wallet: {}", e.what()); setStatusError(std::string(tr("Failed to make multisig: ")) + e.what()); } @@ -1445,7 +1443,7 @@ std::string WalletImpl::exchangeMultisigKeys(const std::vector &inf return w->exchange_multisig_keys(epee::wipeable_string(m_password), info); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on exchanging multisig keys: {}", e.what()); + log::error(logcat, "Error on exchanging multisig keys: {}", e.what()); setStatusError(std::string(tr("Failed to make multisig: ")) + e.what()); } @@ -1465,7 +1463,7 @@ bool WalletImpl::finalizeMultisig(const std::vector& extraMultisigI setStatusError(tr("Failed to finalize multisig wallet creation")); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on finalizing multisig wallet creation: {}", e.what()); + log::error(logcat, "Error on finalizing multisig wallet creation: {}", e.what()); setStatusError(std::string(tr("Failed to finalize multisig wallet creation: ")) + e.what()); } @@ -1483,7 +1481,7 @@ bool WalletImpl::exportMultisigImages(std::string& images) { images = oxenc::to_hex(blob); return true; } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on exporting multisig images: {}", e.what()); + log::error(logcat, "Error on exporting multisig images: {}", e.what()); setStatusError(std::string(tr("Failed to export multisig images: ")) + e.what()); } @@ -1502,7 +1500,7 @@ size_t WalletImpl::importMultisigImages(const std::vector& images) for (const auto& image: images) { if (!oxenc::is_hex(image)) { - oxen::log::error(logcat, "Failed to parse imported multisig images"); + log::error(logcat, "Failed to parse imported multisig images"); setStatusError(tr("Failed to parse imported multisig images")); return 0; } @@ -1512,7 +1510,7 @@ size_t WalletImpl::importMultisigImages(const std::vector& images) return w->import_multisig(blobs); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on importing multisig images: {}", e.what()); + log::error(logcat, "Error on importing multisig images: {}", e.what()); setStatusError(std::string(tr("Failed to import multisig images: ")) + e.what()); } @@ -1528,7 +1526,7 @@ bool WalletImpl::hasMultisigPartialKeyImages() const { return w->has_multisig_partial_key_images(); } catch (const std::exception& e) { - oxen::log::error(logcat, "Error on checking for partial multisig key images: {}", e.what()); + log::error(logcat, "Error on checking for partial multisig key images: {}", e.what()); setStatusError(std::string(tr("Failed to check for partial multisig key images: ")) + e.what()); } @@ -1555,7 +1553,7 @@ PendingTransaction* WalletImpl::restoreMultisigTransaction(const std::string& si return ptx; } catch (std::exception& e) { - oxen::log::error(logcat, "Error on restoring multisig transaction: {}", e.what()); + log::error(logcat, "Error on restoring multisig transaction: {}", e.what()); setStatusError(std::string(tr("Failed to restore multisig transaction: ")) + e.what()); } @@ -2272,14 +2270,14 @@ bool WalletImpl::setStatus(int status, std::string message) const EXPORT void WalletImpl::refreshThreadFunc() { - oxen::log::trace(logcat, "{}: starting refresh thread", __FUNCTION__); + log::trace(logcat, "{}: starting refresh thread", __FUNCTION__); while (true) { std::unique_lock lock{m_refreshMutex}; if (m_refreshThreadDone) { break; } - oxen::log::trace(logcat, "{}: waiting for refresh...", __FUNCTION__); + log::trace(logcat, "{}: waiting for refresh...", __FUNCTION__); // if auto refresh enabled, we wait for the "m_refreshIntervalSeconds" interval. // if not - we wait forever if (std::chrono::milliseconds max_delay{m_refreshIntervalMillis.load()}; @@ -2289,17 +2287,17 @@ void WalletImpl::refreshThreadFunc() m_refreshCV.wait(lock); } - oxen::log::trace(logcat, "{}: refresh lock acquired...", __FUNCTION__); - oxen::log::trace(logcat, "{}: m_refreshEnabled: {}", __FUNCTION__, m_refreshEnabled); + log::trace(logcat, "{}: refresh lock acquired...", __FUNCTION__); + log::trace(logcat, "{}: m_refreshEnabled: {}", __FUNCTION__, m_refreshEnabled); auto st = status(); - oxen::log::trace(logcat, "{}: m_status: {}: {}", __FUNCTION__, st.first, st.second); - oxen::log::trace(logcat, "{}: m_refreshShouldRescan: {}", __FUNCTION__, m_refreshShouldRescan); + log::trace(logcat, "{}: m_status: {}: {}", __FUNCTION__, st.first, st.second); + log::trace(logcat, "{}: m_refreshShouldRescan: {}", __FUNCTION__, m_refreshShouldRescan); if (m_refreshEnabled) { - oxen::log::trace(logcat, "{}: refreshing...", __FUNCTION__); + log::trace(logcat, "{}: refreshing...", __FUNCTION__); doRefresh(); } } - oxen::log::trace(logcat, "{}: refresh thread stopped", __FUNCTION__); + log::trace(logcat, "{}: refresh thread stopped", __FUNCTION__); } EXPORT @@ -2310,7 +2308,7 @@ void WalletImpl::doRefresh() std::lock_guard guard{m_refreshMutex2}; do { try { - oxen::log::trace(logcat, "{}: doRefresh, rescan = {}", __FUNCTION__, rescan); + log::trace(logcat, "{}: doRefresh, rescan = {}", __FUNCTION__, rescan); auto w = wallet(); // Syncing daemon and refreshing wallet simultaneously is very resource intensive. @@ -2334,7 +2332,7 @@ void WalletImpl::doRefresh() } w->find_and_save_rings(false); } else { - oxen::log::trace(logcat, "{}: skipping refresh - daemon is not synced", __FUNCTION__); + log::trace(logcat, "{}: skipping refresh - daemon is not synced", __FUNCTION__); } } catch (const std::exception &e) { setStatusError(e.what()); @@ -2352,7 +2350,7 @@ EXPORT void WalletImpl::startRefresh() { if (!m_refreshEnabled) { - oxen::log::debug(logcat, "{}: refresh started/resumed...", __FUNCTION__); + log::debug(logcat, "{}: refresh started/resumed...", __FUNCTION__); m_refreshEnabled = true; m_refreshCV.notify_one(); } @@ -2374,7 +2372,7 @@ void WalletImpl::stopRefresh() EXPORT void WalletImpl::pauseRefresh() { - oxen::log::debug(logcat, "{}: refresh paused...", __FUNCTION__); + log::debug(logcat, "{}: refresh paused...", __FUNCTION__); // TODO synchronize access if (!m_refreshThreadDone) { m_refreshEnabled = false; @@ -2420,12 +2418,12 @@ bool WalletImpl::doInit(const std::string &daemon_address, uint64_t upper_transa // If daemon isn't synced a calculated block height will be used instead //TODO: Handle light wallet scenario where block height = 0. if (isNewWallet() && daemonSynced()) { - oxen::log::debug(logcat, "{}:New Wallet - fast refresh until {}", __FUNCTION__, daemonBlockChainHeight()); + log::debug(logcat, "{}:New Wallet - fast refresh until {}", __FUNCTION__, daemonBlockChainHeight()); w->set_refresh_from_block_height(daemonBlockChainHeight()); } if (m_rebuildWalletCache) - oxen::log::debug(logcat, "{}: Rebuilding wallet cache, fast refresh until block {}", __FUNCTION__, w->get_refresh_from_block_height()); + log::debug(logcat, "{}: Rebuilding wallet cache, fast refresh until block {}", __FUNCTION__, w->get_refresh_from_block_height()); if (Utils::isAddressLocal(daemon_address)) { this->setTrustedDaemon(true); @@ -2460,7 +2458,7 @@ bool WalletImpl::rescanSpent() try { wallet()->rescan_spent(); } catch (const std::exception &e) { - oxen::log::error(logcat, "{} error: {}", __FUNCTION__, e.what()); + log::error(logcat, "{} error: {}", __FUNCTION__, e.what()); setStatusError(e.what()); return false; } @@ -2680,7 +2678,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (!tools::hex_to_type(sn_key_str, sn_key)) { error_msg = "Failed to parse service node pubkey"; - oxen::log::error(error_msg); + log::error(error_msg); transaction->setError(error_msg); return transaction; } @@ -2689,7 +2687,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (stake_result.status != tools::wallet2::stake_result_status::success) { error_msg = "Failed to create a stake transaction: " + stake_result.msg; - oxen::log::error(error_msg); + log::error(error_msg); transaction->setError(error_msg); return transaction; } diff --git a/src/wallet/api/wallet.h b/src/wallet/api/wallet.h index 0ac33e45a..fa268b1de 100644 --- a/src/wallet/api/wallet.h +++ b/src/wallet/api/wallet.h @@ -40,6 +40,10 @@ namespace Wallet { + +namespace log = oxen::log; +inline auto logcat = log::Cat("wallet.api"); + class TransactionHistoryImpl; class PendingTransactionImpl; class UnsignedTransactionImpl; diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 3c70e76e6..8ae2057a4 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -41,8 +41,6 @@ namespace Wallet { - static auto logcat = oxen::log::Cat("WalletAPI"); - EXPORT Wallet* WalletManagerImpl::createWallet(std::string_view path, const std::string &password, const std::string &language, NetworkType nettype, uint64_t kdf_rounds) @@ -190,13 +188,13 @@ std::vector WalletManagerImpl::findWallets(std::string_view path_) continue; auto filename = p.path(); - oxen::log::trace(logcat, "Checking filename: {}", filename); + log::trace(logcat, "Checking filename: {}", filename); if (filename.extension() == ".keys") { // if keys file found, checking if there's wallet file itself filename.replace_extension(); if (fs::exists(filename)) { - oxen::log::trace(logcat, "Found wallet: {}", filename); + log::trace(logcat, "Found wallet: {}", filename); result.push_back(filename.u8string()); } } diff --git a/src/wallet/message_store.cpp b/src/wallet/message_store.cpp index d374651c6..f49e1175e 100644 --- a/src/wallet/message_store.cpp +++ b/src/wallet/message_store.cpp @@ -42,7 +42,8 @@ namespace mms { - static auto logcat = oxen::log::Cat("wallet.mms"); + namespace log = oxen::log; + static auto logcat = log::Cat("wallet.mms"); message_store::message_store() { @@ -439,7 +440,7 @@ bool message_store::get_signer_index_by_monero_address(const cryptonote::account return true; } } - oxen::log::warning(logcat, "No authorized signer with Monero address {}", account_address_to_string(monero_address)); + log::warning(logcat, "No authorized signer with Monero address {}", account_address_to_string(monero_address)); return false; } @@ -454,7 +455,7 @@ bool message_store::get_signer_index_by_label(const std::string label, uint32_t return true; } } - oxen::log::warning(logcat, "No authorized signer with label {}", label); + log::warning(logcat, "No authorized signer with label {}", label); return false; } @@ -537,7 +538,7 @@ size_t message_store::add_message(const multisig_wallet_state &state, // Save for every new message right away (at least while in beta) save(state); - oxen::log::info(boost::format("Added %s message %s for signer %s of type %s") + log::info(boost::format("Added %s message %s for signer %s of type %s") % message_direction_to_string(direction) % m.id % signer_index % message_type_to_string(type)); return m_messages.size() - 1; } @@ -553,7 +554,7 @@ bool message_store::get_message_index_by_id(uint32_t id, size_t &index) const return true; } } - oxen::log::warning(logcat, "No message found with an id of {}", id); + log::warning(logcat, "No message found with an id of {}", id); return false; } @@ -719,7 +720,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: { // Simply do nothing if the file is not there; allows e.g. easy recovery // from problems with the MMS by deleting the file - oxen::log::info(logcat, "No message store file found: {}", filename); + log::info(logcat, "No message store file found: {}", filename); return; } @@ -737,7 +738,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: } catch (const std::exception &e) { - oxen::log::error(logcat, "MMS file {} has bad structure : {}", filename, e.what()); + log::error(logcat, "MMS file {} has bad structure : {}", filename, e.what()); THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename); } @@ -756,7 +757,7 @@ void message_store::read_from_file(const multisig_wallet_state &state, const fs: } catch (const std::exception &e) { - oxen::log::error(logcat, "MMS file {} has bad structure: {}", filename, e.what()); + log::error(logcat, "MMS file {} has bad structure: {}", filename, e.what()); THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename); } diff --git a/src/wallet/message_store.h b/src/wallet/message_store.h index 8ee5fc09b..0fb911ec5 100644 --- a/src/wallet/message_store.h +++ b/src/wallet/message_store.h @@ -54,8 +54,6 @@ namespace mms { - static auto logcat = oxen::log::Cat("wallet.mms"); - enum class message_type { key_set, diff --git a/src/wallet/message_transporter.cpp b/src/wallet/message_transporter.cpp index 557ff4b2f..9b9fb4226 100644 --- a/src/wallet/message_transporter.cpp +++ b/src/wallet/message_transporter.cpp @@ -39,7 +39,8 @@ using namespace std::literals; namespace mms { - static auto logcat = oxen::log::Cat("wallet.mms"); + namespace log = oxen::log; + static auto logcat = log::Cat("wallet.mms"); namespace bitmessage_rpc { @@ -113,7 +114,7 @@ bool message_transporter::receive_messages(const std::vector &desti bitmessage_rpc::inbox_messages_response bitmessage_res; if (!epee::serialization::load_t_from_json(bitmessage_res, json)) { - oxen::log::error(logcat, "Failed to deserialize messages"); + log::error(logcat, "Failed to deserialize messages"); return true; } size_t size = bitmessage_res.inboxMessages.size(); @@ -148,7 +149,7 @@ bool message_transporter::receive_messages(const std::vector &desti } catch(const std::exception& e) { - oxen::log::error(logcat, "Failed to deserialize message: {}", e.what()); + log::error(logcat, "Failed to deserialize message: {}", e.what()); } } } @@ -235,7 +236,7 @@ void message_transporter::post_request(const std::string &request, std::string & auto res = m_http_client.post("", request, {{"Content-Type", "application/xml; charset=utf-8"}}); answer = res.text; } catch (const std::exception& e) { - oxen::log::error(logcat, "POST request to Bitmessage failed: {}", e.what()); + log::error(logcat, "POST request to Bitmessage failed: {}", e.what()); THROW_WALLET_EXCEPTION(tools::error::no_connection_to_bitmessage, m_http_client.get_base_url()); } diff --git a/src/wallet/node_rpc_proxy.cpp b/src/wallet/node_rpc_proxy.cpp index 36e1b1fdd..931315e32 100644 --- a/src/wallet/node_rpc_proxy.cpp +++ b/src/wallet/node_rpc_proxy.cpp @@ -38,7 +38,7 @@ using namespace std::literals; namespace tools { -static auto logcat = oxen::log::Cat("node_rpc_proxy"); +static auto logcat = log::Cat("node_rpc_proxy"); static constexpr std::chrono::seconds rpc_timeout{30}; @@ -229,7 +229,7 @@ bool NodeRPCProxy::get_fee_quantization_mask(uint64_t &fee_quantization_mask) co fee_quantization_mask = m_fee_quantization_mask; if (fee_quantization_mask == 0) { - oxen::log::error(logcat, "Fee quantization mask is 0, forcing to 1"); + log::error(logcat, "Fee quantization mask is 0, forcing to 1"); fee_quantization_mask = 1; } return true; diff --git a/src/wallet/node_rpc_proxy.h b/src/wallet/node_rpc_proxy.h index a77cdc8c1..cd29d6edf 100644 --- a/src/wallet/node_rpc_proxy.h +++ b/src/wallet/node_rpc_proxy.h @@ -80,12 +80,12 @@ private: try { result = m_http_client.json_rpc(RPC::names().front(), req); } catch (const std::exception& e) { - oxen::log::error(globallogcat, e.what()); + log::error(globallogcat, e.what()); throw; } if (result.status != cryptonote::rpc::STATUS_OK) { std::string error = "Request for " + std::string{RPC::names().front()} + " failed: " + (result.status == cryptonote::rpc::STATUS_BUSY ? "daemon is busy" : result.status); - oxen::log::error(globallogcat, error); + log::error(globallogcat, error); throw std::runtime_error{error}; } diff --git a/src/wallet/ringdb.cpp b/src/wallet/ringdb.cpp index 33d1b94c7..7e24b4952 100644 --- a/src/wallet/ringdb.cpp +++ b/src/wallet/ringdb.cpp @@ -37,12 +37,18 @@ #define V1TAG ((uint64_t)798237759845202) -static auto logcat = oxen::log::Cat("wallet.ringdb"); +namespace tools +{ -static const char zerokey[8] = {0}; -static const MDB_val zerokeyval = { sizeof(zerokey), (void *)zerokey }; +namespace +{ -static int compare_hash32(const MDB_val *a, const MDB_val *b) +auto logcat = log::Cat("wallet.ringdb"); + +const char zerokey[8] = {0}; +const MDB_val zerokeyval = { sizeof(zerokey), (void *)zerokey }; + +int compare_hash32(const MDB_val *a, const MDB_val *b) { uint32_t *va = (uint32_t*) a->mv_data; uint32_t *vb = (uint32_t*) b->mv_data; @@ -56,14 +62,14 @@ static int compare_hash32(const MDB_val *a, const MDB_val *b) return 0; } -static int compare_uint64(const MDB_val *a, const MDB_val *b) +int compare_uint64(const MDB_val *a, const MDB_val *b) { const uint64_t va = *(const uint64_t*) a->mv_data; const uint64_t vb = *(const uint64_t*) b->mv_data; return va < vb ? -1 : va > vb; } -static std::string compress_ring(const std::vector &ring, uint64_t tag) +std::string compress_ring(const std::vector &ring, uint64_t tag) { std::string s; s += tools::get_varint_data(tag); @@ -72,7 +78,7 @@ static std::string compress_ring(const std::vector &ring, uint64_t tag return s; } -static std::vector decompress_ring(const std::string &s, uint64_t tag) +std::vector decompress_ring(const std::string &s, uint64_t tag) { std::vector ring; int read = 0; @@ -101,7 +107,7 @@ fs::path get_rings_filename(fs::path filename) return filename; } -static crypto::chacha_iv make_iv(const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) +crypto::chacha_iv make_iv(const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) { uint8_t buffer[sizeof(key_image) + sizeof(key) + cryptonote::hashkey::RINGDB.size() + sizeof(field)]; memcpy(buffer, &key_image, sizeof(key_image)); @@ -117,7 +123,7 @@ static crypto::chacha_iv make_iv(const crypto::key_image &key_image, const crypt return iv; } -static std::string encrypt(const std::string &plaintext, const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) +std::string encrypt(const std::string &plaintext, const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) { const crypto::chacha_iv iv = make_iv(key_image, key, field); std::string ciphertext; @@ -127,12 +133,12 @@ static std::string encrypt(const std::string &plaintext, const crypto::key_image return ciphertext; } -static std::string encrypt(const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) +std::string encrypt(const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) { return encrypt(std::string((const char*)&key_image, sizeof(key_image)), key_image, key, field); } -static std::string decrypt(const std::string &ciphertext, const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) +std::string decrypt(const std::string &ciphertext, const crypto::key_image &key_image, const crypto::chacha_key &key, uint8_t field) { const crypto::chacha_iv iv = make_iv(key_image, key, field); std::string plaintext; @@ -142,7 +148,7 @@ static std::string decrypt(const std::string &ciphertext, const crypto::key_imag return plaintext; } -static void store_relative_ring(MDB_txn *txn, MDB_dbi &dbi, const crypto::key_image &key_image, const std::vector &relative_ring, const crypto::chacha_key &chacha_key) +void store_relative_ring(MDB_txn *txn, MDB_dbi &dbi, const crypto::key_image &key_image, const std::vector &relative_ring, const crypto::chacha_key &chacha_key) { MDB_val key, data; std::string key_ciphertext = encrypt(key_image, chacha_key, 0); @@ -156,7 +162,7 @@ static void store_relative_ring(MDB_txn *txn, MDB_dbi &dbi, const crypto::key_im THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set ring for key image in LMDB table: " + std::string(mdb_strerror(dbr))); } -static int resize_env(MDB_env *env, const fs::path& db_path, size_t needed) +int resize_env(MDB_env *env, const fs::path& db_path, size_t needed) { MDB_envinfo mei; MDB_stat mst; @@ -179,14 +185,14 @@ static int resize_env(MDB_env *env, const fs::path& db_path, size_t needed) auto si = fs::space(db_path); if(si.available < needed) { - oxen::log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); + log::error(logcat, "!! WARNING: Insufficient free space to extend database !!: {} MB available", (si.available / 1000000)); return ENOSPC; } } catch(...) { // print something but proceed. - oxen::log::warning(logcat, "Unable to query free disk space."); + log::warning(logcat, "Unable to query free disk space."); } mapsize += needed; @@ -194,15 +200,14 @@ static int resize_env(MDB_env *env, const fs::path& db_path, size_t needed) return mdb_env_set_mapsize(env, mapsize); } -static size_t get_ring_data_size(size_t n_entries) +size_t get_ring_data_size(size_t n_entries) { return n_entries * (32 + 1024); // highball 1kB for the ring data to make sure } enum { BLACKBALL_BLACKBALL, BLACKBALL_UNBLACKBALL, BLACKBALL_QUERY, BLACKBALL_CLEAR}; -namespace tools -{ +} // anonymous namespace ringdb::ringdb(fs::path fn_, const std::string &genesis) : filename_{std::move(fn_)} { @@ -212,7 +217,7 @@ ringdb::ringdb(fs::path fn_, const std::string &genesis) : filename_{std::move(f std::error_code ec; if (fs::create_directories(filename_, ec); ec) - oxen::log::warning(logcat, "Failed to create ringdb directory {}: {}", filename_, ec.message()); + log::warning(logcat, "Failed to create ringdb directory {}: {}", filename_, ec.message()); dbr = mdb_env_create(&env); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr))); @@ -314,7 +319,7 @@ bool ringdb::remove_rings(const crypto::chacha_key &chacha_key, const std::vecto continue; THROW_WALLET_EXCEPTION_IF(data.mv_size <= 0, tools::error::wallet_internal_error, "Invalid ring data size"); - oxen::log::debug(logcat, "Removing ring data for key image {}", key_image); + log::debug(logcat, "Removing ring data for key image {}", key_image); dbr = mdb_del(txn, dbi_rings, &key, NULL); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to remove ring to database: " + std::string(mdb_strerror(dbr))); } @@ -374,10 +379,10 @@ bool ringdb::get_ring(const crypto::chacha_key &chacha_key, const crypto::key_im data_plaintext = decrypt(std::string((const char*)data.mv_data, data.mv_size), key_image, chacha_key, 0); outs = decompress_ring(data_plaintext, 0); } - oxen::log::debug(logcat, "Found ring for key image {}:", key_image); - oxen::log::debug(logcat, "Relative: {}", tools::join(" ", outs)); + log::debug(logcat, "Found ring for key image {}:", key_image); + log::debug(logcat, "Relative: {}", tools::join(" ", outs)); outs = cryptonote::relative_output_offsets_to_absolute(outs); - oxen::log::debug(logcat, "Absolute: {}", tools::join(" ", outs)); + log::debug(logcat, "Absolute: {}", tools::join(" ", outs)); dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn getting ring from database: " + std::string(mdb_strerror(dbr))); @@ -437,13 +442,13 @@ bool ringdb::blackball_worker(const std::vector> & switch (op) { case BLACKBALL_BLACKBALL: - oxen::log::debug(logcat, "Marking output {}/{} as spent", output.first, output.second); + log::debug(logcat, "Marking output {}/{} as spent", output.first, output.second); dbr = mdb_cursor_put(cursor, &key, &data, MDB_NODUPDATA); if (dbr == MDB_KEYEXIST) dbr = 0; break; case BLACKBALL_UNBLACKBALL: - oxen::log::debug(logcat, "Marking output {}/{} as unspent", output.first, output.second); + log::debug(logcat, "Marking output {}/{} as unspent", output.first, output.second); dbr = mdb_cursor_get(cursor, &key, &data, MDB_GET_BOTH); if (dbr == 0) dbr = mdb_cursor_del(cursor, 0); diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index e1b5cf271..b89a0a37f 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -104,8 +104,11 @@ extern "C" using namespace crypto; using namespace cryptonote; +namespace tools +{ + namespace { - static auto logcat = oxen::log::Cat("wallet.wallet2"); + static auto logcat = log::Cat("wallet.wallet2"); constexpr std::string_view UNSIGNED_TX_PREFIX = "Loki unsigned tx set\004"sv; constexpr std::string_view SIGNED_TX_PREFIX = "Loki signed tx set\004"sv; @@ -391,7 +394,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl command_line::get_arg(vm, opts.daemon_login), false, [password_prompter](bool verify) { if (!password_prompter) { - oxen::log::error(logcat, "Password needed without prompt function"); + log::error(logcat, "Password needed without prompt function"); return std::optional(); } return password_prompter("Daemon client password", verify); @@ -443,7 +446,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl if (!command_line::is_arg_defaulted(vm, opts.trusted_daemon) || !command_line::is_arg_defaulted(vm, opts.untrusted_daemon)) trusted_daemon = command_line::get_arg(vm, opts.trusted_daemon) && !command_line::get_arg(vm, opts.untrusted_daemon); else if (trusted_daemon) - oxen::log::info(logcat, tools::wallet2::tr("Daemon is local, assuming trusted")); + log::info(logcat, tools::wallet2::tr("Daemon is local, assuming trusted")); auto wallet = std::make_unique(nettype, kdf_rounds, unattended); wallet->init(std::move(daemon_address), std::move(login), std::move(proxy), 0, trusted_daemon); @@ -479,7 +482,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to parse tx notify spec"); + log::error(logcat, "Failed to parse tx notify spec"); } return wallet; @@ -792,7 +795,7 @@ size_t estimate_rct_tx_size(int n_inputs, int mixin, int n_outputs, size_t extra // txnFee size += 4; - oxen::log::debug(logcat, "estimated bulletproof rct tx size for {} inputs with ring size {} and {} outputs: {} ({} saved)", n_inputs, (mixin+1), n_outputs, size, ((32 * n_inputs/*+1*/) + 2 * 32 * (mixin+1) * n_inputs + 32 * n_outputs)); + log::debug(logcat, "estimated bulletproof rct tx size for {} inputs with ring size {} and {} outputs: {} ({} saved)", n_inputs, (mixin+1), n_outputs, size, ((32 * n_inputs/*+1*/) + 2 * 32 * (mixin+1) * n_inputs + 32 * n_outputs)); return size; } @@ -808,7 +811,7 @@ uint64_t estimate_tx_weight(int n_inputs, int mixin, int n_outputs, size_t extra uint64_t nlr = 2 * (6 + log_padded_outputs); const uint64_t bp_size = 32 * (9 + nlr); const uint64_t bp_clawback = (bp_base * (1<::max(); // bad pick - oxen::log::trace(logcat, "Picking 1/{} in block {}", n_rct, index); + log::trace(logcat, "Picking 1/{} in block {}", n_rct, index); return first_rct + crypto::rand_idx(n_rct); }; @@ -1012,7 +1012,7 @@ wallet_keys_unlocker::~wallet_keys_unlocker() std::lock_guard lock{lockers_mutex}; if (lockers == 0) { - oxen::log::error(logcat, "There are no lockers in wallet_keys_unlocker dtor"); + log::error(logcat, "There are no lockers in wallet_keys_unlocker dtor"); return; } --lockers; @@ -1022,7 +1022,7 @@ wallet_keys_unlocker::~wallet_keys_unlocker() } catch (...) { - oxen::log::error(logcat, "Failed to re-encrypt wallet keys"); + log::error(logcat, "Failed to re-encrypt wallet keys"); // do not propagate through dtor, we'd crash } } @@ -1260,7 +1260,7 @@ bool wallet2::set_daemon(std::string daemon_address, std::optional auto [proto, host, port, uri] = rpc::http_client::parse_url(daemon_address); localhost = tools::is_local_address(host); } catch (const rpc::http_client_error& e) { - oxen::log::warning(logcat, "Invalid daemon URL: "s + e.what()); + log::warning(logcat, "Invalid daemon URL: "s + e.what()); return false; } @@ -1287,7 +1287,7 @@ bool wallet2::set_daemon(std::string daemon_address, std::optional m_node_rpc_proxy.invalidate(); std::string url = m_http_client.get_base_url(); - oxen::log::info(logcat, "set daemon to {}", (url.empty() ? "(none, offline)" : url)); + log::info(logcat, "set daemon to {}", (url.empty() ? "(none, offline)" : url)); { std::lock_guard lock{default_daemon_address_mutex}; default_daemon_address = std::move(url); @@ -1415,13 +1415,13 @@ bool wallet2::reconnect_device() hwdev.set_callback(get_device_callback()); r = hwdev.init(); if (!r){ - oxen::log::error(logcat, "Could not init device"); + log::error(logcat, "Could not init device"); return false; } r = hwdev.connect(); if (!r){ - oxen::log::error(logcat, "Could not connect to the device"); + log::error(logcat, "Could not connect to the device"); return false; } @@ -1545,7 +1545,7 @@ std::string wallet2::get_subaddress_label(const cryptonote::subaddress_index& in { if (index.major >= m_subaddress_labels.size() || index.minor >= m_subaddress_labels[index.major].size()) { - oxen::log::error(logcat, "Subaddress label doesn't exist"); + log::error(logcat, "Subaddress label doesn't exist"); return ""; } return m_subaddress_labels[index.major][index.minor]; @@ -1580,7 +1580,7 @@ void wallet2::set_spent(size_t idx, uint64_t height) { CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); transfer_details &td = m_transfers[idx]; - oxen::log::debug(logcat, "Setting SPENT at {}: ki {}, amount {}", height, td.m_key_image, print_money(td.m_amount)); + log::debug(logcat, "Setting SPENT at {}: ki {}, amount {}", height, td.m_key_image, print_money(td.m_amount)); td.m_spent = true; td.m_spent_height = height; } @@ -1589,7 +1589,7 @@ void wallet2::set_unspent(size_t idx) { CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); transfer_details &td = m_transfers[idx]; - oxen::log::debug(logcat, "Setting UNSPENT: ki {}, amount {}", td.m_key_image, print_money(td.m_amount)); + log::debug(logcat, "Setting UNSPENT: ki {}, amount {}", td.m_key_image, print_money(td.m_amount)); td.m_spent = false; td.m_spent_height = 0; } @@ -1673,7 +1673,7 @@ void wallet2::check_acc_out_precomp(const tx_out &o, const crypto::key_derivatio if (!std::holds_alternative(o.target)) { tx_scan_info.error = true; - oxen::log::error(logcat, "wrong type id in transaction out"); + log::error(logcat, "wrong type id in transaction out"); return; } tx_scan_info.received = is_out_to_acc_precomp(m_subaddresses, var::get(o.target).key, derivation, additional_derivations, i, hwdev); @@ -1731,13 +1731,13 @@ static uint64_t decodeRct(const rct::rctSig & rv, const crypto::key_derivation & case rct::RCTType::Full: return rct::decodeRct(rv, rct::sk2rct(scalar1), i, mask, hwdev); default: - oxen::log::error(logcat, "{}: Unsupported rct type: {}", __func__, (int)rv.type); + log::error(logcat, "{}: Unsupported rct type: {}", __func__, (int)rv.type); return 0; } } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to decode input {}", i); + log::error(logcat, "Failed to decode input {}", i); return 0; } } @@ -1791,7 +1791,7 @@ void wallet2::scan_output(const cryptonote::transaction &tx, bool miner_tx, cons if (tx_scan_info.money_transfered == 0) { - oxen::log::error(logcat, "Invalid output amount, skipping"); + log::error(logcat, "Invalid output amount, skipping"); tx_scan_info.error = true; return; } @@ -1823,7 +1823,7 @@ void wallet2::cache_tx_data(const cryptonote::transaction& tx, const crypto::has if(!parse_tx_extra(tx.extra, tx_cache_data.tx_extra_fields)) { // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key - oxen::log::warning(logcat, "Transaction extra has unsupported format: {}", txid); + log::warning(logcat, "Transaction extra has unsupported format: {}", txid); if (tx_cache_data.tx_extra_fields.empty()) return; } @@ -1861,7 +1861,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (!tx.is_transfer() || tx.version <= txversion::v1) return; - oxen::log::trace(logcat, "PROC NEW TX {}", txid); + log::trace(logcat, "PROC NEW TX {}", txid); // In this function, tx (probably) only contains the base information // (that is, the prunable stuff may or may not be included) confirmed_transfer_details* just_confirmed = nullptr; @@ -1883,7 +1883,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if(!parse_tx_extra(tx.extra, local_tx_extra_fields)) { // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key - oxen::log::warning(logcat, "Transaction extra has unsupported format: {}", txid); + log::warning(logcat, "Transaction extra has unsupported format: {}", txid); } } const auto& tx_extra_fields = tx_cache_data.tx_extra_fields.empty() ? local_tx_extra_fields : tx_cache_data.tx_extra_fields; @@ -1923,7 +1923,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if (pk_index > 1) break; - oxen::log::warning(logcat, "Public key wasn't found in the transaction extra. Skipping transaction {}", txid); + log::warning(logcat, "Public key wasn't found in the transaction extra. Skipping transaction {}", txid); if (m_callback) m_callback->on_skip_transaction(height, txid, tx); break; @@ -1952,7 +1952,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote hwdev.set_mode(hw::device::mode::TRANSACTION_PARSE); if (!hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation)) { - oxen::log::warning(logcat, "Failed to generate key derivation from tx pubkey in {}, skipping", txid); + log::warning(logcat, "Failed to generate key derivation from tx pubkey in {}, skipping", txid); static_assert(sizeof(derivation) == sizeof(rct::key), "Mismatched sizes of key_derivation and rct::key"); memcpy(&derivation, rct::identity().bytes, sizeof(derivation)); } @@ -1967,7 +1967,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote additional_derivations.push_back({}); if (!hwdev.generate_key_derivation(additional_tx_pub_keys.data[i], keys.m_view_secret_key, additional_derivations.back())) { - oxen::log::warning(logcat, "Failed to generate key derivation from additional tx pubkey in {}, skipping", txid); + log::warning(logcat, "Failed to generate key derivation from additional tx pubkey in {}, skipping", txid); memcpy(&additional_derivations.back(), rct::identity().bytes, sizeof(crypto::key_derivation)); } } @@ -2137,7 +2137,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (m_multisig_rescan_info && m_multisig_rescan_info->front().size() >= m_transfers.size()) update_multisig_rescan_info(*m_multisig_rescan_k, *m_multisig_rescan_info, m_transfers.size() - 1); } - oxen::log::warning(logcat, "Received money: {}, with tx: {}", print_money(td.amount()), txid); + log::warning(logcat, "Received money: {}, with tx: {}", print_money(td.amount()), txid); if (m_callback) m_callback->on_money_received(height, txid, tx, td.m_amount, td.m_subaddr_index, td.m_tx.unlock_time, blink); } @@ -2160,7 +2160,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if (transfer.amount() > tx_scan_info[o].amount) { - oxen::log::error(logcat, "Public key {} from received {} output already exists with {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspend"), print_money(transfer.amount()), transfer.m_txid); + log::error(logcat, "Public key {} from received {} output already exists with {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspend"), print_money(transfer.amount()), transfer.m_txid); } if (transfer.m_unmined_blink) @@ -2169,7 +2169,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote THROW_WALLET_EXCEPTION_IF(transfer.amount() != tx_scan_info[o].amount, error::wallet_internal_error, "A blink should credit the amount exactly as we recorded it when it arrived in the mempool"); THROW_WALLET_EXCEPTION_IF(transfer.m_spent, error::wallet_internal_error, "Blink can not be spent before it is mined, this should never happen"); - oxen::log::info(logcat, "Public key {} of blink tx {} (for {}) status updated: now mined in block {}", tools::type_to_hex(kit->first), transfer.m_txid, print_money(tx_scan_info[o].amount), height); + log::info(logcat, "Public key {} of blink tx {} (for {}) status updated: now mined in block {}", tools::type_to_hex(kit->first), transfer.m_txid, print_money(tx_scan_info[o].amount), height); // We previous had this as a blink, but now it's been mined so update the tx status with the height and output index transfer.m_block_height = height; @@ -2192,7 +2192,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else if (transfer.m_spent || transfer.amount() >= tx_scan_info[o].amount) { - oxen::log::error(logcat, "Public key {} from received {} output already exists with {} {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspent"), print_money(transfer.amount()), transfer.m_txid); + log::error(logcat, "Public key {} from received {} output already exists with {} {} in tx {}, received output ignored", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), (transfer.m_spent ? "spent" : "unspent"), print_money(transfer.amount()), transfer.m_txid); auto iter = std::find_if( tx_money_got_in_outs.begin(), @@ -2210,7 +2210,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else { - oxen::log::error(logcat, "Public key {} from received {} output already exists with {}, replacing with new output", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), print_money(transfer.amount())); + log::error(logcat, "Public key {} from received {} output already exists with {}, replacing with new output", tools::type_to_hex(kit->first), print_money(tx_scan_info[o].amount), print_money(transfer.amount())); // The new larger output replaced a previous smaller one auto unlock_time_it = pk_to_unlock_times.find(kit->first); @@ -2305,7 +2305,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote THROW_WALLET_EXCEPTION_IF(transfer.get_public_key() != tx_scan_info[o].in_ephemeral.pub, error::wallet_internal_error, "Inconsistent public keys"); THROW_WALLET_EXCEPTION_IF(transfer.m_spent, error::wallet_internal_error, "Inconsistent spent status"); - oxen::log::warning(logcat, "Received money: {}, with tx: {}", print_money(transfer.amount()), txid); + log::warning(logcat, "Received money: {}, with tx: {}", print_money(transfer.amount()), txid); if (m_callback) m_callback->on_money_received(height, txid, tx, transfer.m_amount, transfer.m_subaddr_index, transfer.m_tx.unlock_time, blink); } @@ -2334,7 +2334,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { if(amount != td.amount()) { - oxen::log::error(logcat, "Inconsistent amount in tx input: got {}, expected {}", print_money(amount), print_money(td.amount())); + log::error(logcat, "Inconsistent amount in tx input: got {}, expected {}", print_money(amount), print_money(td.amount())); // this means: // 1) the same output pub key was used as destination multiple times, // 2) the wallet set the highest amount among them to transfer_details::m_amount, and @@ -2348,12 +2348,12 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } tx_money_spent_in_ins += amount; if (subaddr_account && *subaddr_account != td.m_subaddr_index.major) - oxen::log::error(logcat, "spent funds are from different subaddress accounts; count of incoming/outgoing payments will be incorrect"); + log::error(logcat, "spent funds are from different subaddress accounts; count of incoming/outgoing payments will be incorrect"); subaddr_account = td.m_subaddr_index.major; subaddr_indices.insert(td.m_subaddr_index.minor); if (!pool) { - oxen::log::warning(logcat, "Spent money: {}, with tx: {}", print_money(amount), txid); + log::warning(logcat, "Spent money: {}, with tx: {}", print_money(amount), txid); set_spent(it->second, height); if (m_callback) m_callback->on_money_spent(height, txid, tx, amount, tx, td.m_subaddr_index); @@ -2436,17 +2436,17 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { // We got a payment ID to go with this tx - oxen::log::debug(logcat, "Found encrypted payment ID: {}", payment_id8); - oxen::log::info(logcat, "Consider using subaddresses instead of encrypted payment IDs"); + log::debug(logcat, "Found encrypted payment ID: {}", payment_id8); + log::info(logcat, "Consider using subaddresses instead of encrypted payment IDs"); if (tx_pub_key != null_pkey) { if (!m_account.get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_account.get_keys().m_view_secret_key)) { - oxen::log::warning(logcat, "Failed to decrypt payment ID: {}", payment_id8); + log::warning(logcat, "Failed to decrypt payment ID: {}", payment_id8); } else { - oxen::log::debug(logcat, "Decrypted payment ID: {}", payment_id8); + log::debug(logcat, "Decrypted payment ID: {}", payment_id8); // put the 64 bit decrypted payment id in the first 8 bytes memcpy(payment_id.data, payment_id8.data, 8); // rest is already 0, but guard against code changes above @@ -2455,7 +2455,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else { - oxen::log::info(logcat, "No public key found in tx, unable to decrypt payment id"); + log::info(logcat, "No public key found in tx, unable to decrypt payment id"); } } else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) @@ -2463,14 +2463,14 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote bool ignore = block_version >= IGNORE_LONG_PAYMENT_ID_FROM_BLOCK_VERSION; if (ignore) { - oxen::log::debug(logcat, "Found unencrypted payment ID in tx {} (ignored)", txid); - oxen::log::warning(logcat, "Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); + log::debug(logcat, "Found unencrypted payment ID in tx {} (ignored)", txid); + log::warning(logcat, "Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); payment_id = crypto::null_hash; } else { - oxen::log::debug(logcat, "Found unencrypted payment ID: {}", payment_id); - oxen::log::warning(logcat, "Found unencrypted payment ID: these are bad for privacy, consider using subaddresses instead"); + log::debug(logcat, "Found unencrypted payment ID: {}", payment_id); + log::warning(logcat, "Found unencrypted payment ID: these are bad for privacy, consider using subaddresses instead"); } } } @@ -2484,10 +2484,10 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (total_received_1 != total_received_2) { - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Consistency failure in amounts received")); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Check transaction {}", txid)); - oxen::log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Consistency failure in amounts received")); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Check transaction {}", txid)); + log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); exit(1); return; } @@ -2514,7 +2514,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote } else m_payments.emplace(payment_id, payment); - oxen::log::debug(logcat, "Payment found in {}: {} / {} / {}", (pool ? blink ? "blink pool" : "pool" : "block"), payment_id, payment.m_tx_hash, payment.m_amount); + log::debug(logcat, "Payment found in {}: {} / {} / {}", (pool ? blink ? "blink pool" : "pool" : "block"), payment_id, payment.m_tx_hash, payment.m_amount); } // if it's a pool tx and we already had it, don't notify again @@ -2586,7 +2586,7 @@ wallet2::confirmed_transfer_details* wallet2::process_unconfirmed(const crypto:: } catch (...) { // can fail if the tx has unexpected input types - oxen::log::warning(logcat, "Failed to add outgoing transaction to confirmed transaction map"); + log::warning(logcat, "Failed to add outgoing transaction to confirmed transaction map"); } } m_unconfirmed_txs.erase(unconf_it); @@ -2675,9 +2675,9 @@ void wallet2::process_new_blockchain_entry(const cryptonote::block& b, const cry m_last_block_reward = cryptonote::get_outs_money_amount(b.miner_tx); if (height > 0 && ((height % 2000) == 0)) - oxen::log::warning(logcat, "Blockchain sync progress: {}, height {}", bl_id, height); + log::warning(logcat, "Blockchain sync progress: {}, height {}", bl_id, height); - oxen::log::debug(logcat, "Processed block: {}, height {}, {}({}/{})", + log::debug(logcat, "Processed block: {}, height {}, {}({}/{})", bl_id, height, tools::friendly_duration(miner_tx_handle_time_duration + txs_handle_time_duration), @@ -2687,7 +2687,7 @@ void wallet2::process_new_blockchain_entry(const cryptonote::block& b, const cry }else { if (!(height % 128)) - oxen::log::debug(logcat, "Skipped block by timestamp, height: {}, block time {}, account time {}", height, b.timestamp, m_account.get_createtime()); + log::debug(logcat, "Skipped block by timestamp, height: {}, block time {}, account time {}", height, b.timestamp, m_account.get_createtime()); } m_blockchain.push_back(bl_id); m_cached_height++; @@ -2740,7 +2740,7 @@ void wallet2::pull_blocks(uint64_t start_height, uint64_t& blocks_start_height, cryptonote::rpc::GET_BLOCKS_BIN::response res{}; req.block_ids = short_chain_history; - oxen::log::debug(logcat, "Pulling blocks: start_height {}", start_height); + log::debug(logcat, "Pulling blocks: start_height {}", start_height); req.prune = true; req.start_height = start_height; @@ -2758,7 +2758,7 @@ void wallet2::pull_blocks(uint64_t start_height, uint64_t& blocks_start_height, o_indices = std::move(res.output_indices); current_height = res.current_height; - oxen::log::debug(logcat, "Pulled blocks: blocks_start_height {}, count {}, height {}, node height {}", blocks_start_height, blocks.size(), blocks_start_height + blocks.size(), res.current_height); + log::debug(logcat, "Pulled blocks: blocks_start_height {}, count {}, height {}, node height {}", blocks_start_height, blocks.size(), blocks_start_height + blocks.size(), res.current_height); } //---------------------------------------------------------------------------------------------------- void wallet2::pull_hashes(uint64_t start_height, uint64_t &blocks_start_height, const std::list &short_chain_history, std::vector &hashes) @@ -2823,7 +2823,7 @@ void wallet2::process_parsed_blocks(uint64_t start_height, const std::vector &tx_hashe auto pit = uit++; if (!found) { - oxen::log::debug(logcat, "Removing {} from unconfirmed payments, not found in pool", txid); + log::debug(logcat, "Removing {} from unconfirmed payments, not found in pool", txid); m_unconfirmed_payments.erase(pit); if (m_callback) m_callback->on_pool_tx_removed(txid); @@ -3056,10 +3056,10 @@ bool wallet2::long_poll_pool_state() res = m_long_poll_client.binary(GET_TRANSACTION_POOL_HASHES_BIN::names()[0], req); } catch (const std::exception& e) { if (m_long_poll_disabled) - oxen::log::debug(logcat, "Long poll request cancelled"); + log::debug(logcat, "Long poll request cancelled"); else { - oxen::log::warning(logcat, "Long poll request failed: {}", e.what()); + log::warning(logcat, "Long poll request failed: {}", e.what()); std::this_thread::sleep_for(error_sleep); } throw; @@ -3067,7 +3067,7 @@ bool wallet2::long_poll_pool_state() if (res.status == rpc::STATUS_TX_LONG_POLL_TIMED_OUT) { - oxen::log::debug(logcat, "Long poll replied with no pool change"); + log::debug(logcat, "Long poll replied with no pool change"); return false; } @@ -3106,7 +3106,7 @@ static std::vector hashes_to_hex(It begin, It end) std::vector wallet2::get_pool_state(bool refreshed) { std::vector process_txs; - oxen::log::trace(logcat, "get_pool_state: take hashes from cache"); + log::trace(logcat, "get_pool_state: take hashes from cache"); std::vector blink_hashes, pool_hashes; { // We make two requests here: one for all pool txes, and then (assuming there are any) a second @@ -3117,7 +3117,7 @@ std::vector wallet2::get_pool_state(bool refreshed) THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status == rpc::STATUS_BUSY, error::daemon_busy, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status != rpc::STATUS_OK, error::get_tx_pool_error); - oxen::log::trace(logcat, "get_pool_state got full pool"); + log::trace(logcat, "get_pool_state got full pool"); pool_hashes = std::move(res.tx_hashes); // NOTE: Only request blinked transactions, normal transactions will appear @@ -3130,7 +3130,7 @@ std::vector wallet2::get_pool_state(bool refreshed) THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status == rpc::STATUS_BUSY, error::daemon_busy, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status != rpc::STATUS_OK, error::get_tx_pool_error); - oxen::log::trace(logcat, "get_pool_state got blinks"); + log::trace(logcat, "get_pool_state got blinks"); blink_hashes = std::move(res.tx_hashes); } @@ -3159,12 +3159,12 @@ std::vector wallet2::get_pool_state(bool refreshed) // we're sure we've seen the blockchain state first) if (pit->second.m_state == wallet2::unconfirmed_transfer_details::pending) { - oxen::log::info(logcat, "Pending txid {} not in pool, marking as not in pool", txid); + log::info(logcat, "Pending txid {} not in pool, marking as not in pool", txid); pit->second.m_state = wallet2::unconfirmed_transfer_details::pending_not_in_pool; } else if (pit->second.m_state == wallet2::unconfirmed_transfer_details::pending_not_in_pool && refreshed) { - oxen::log::info(logcat, "Pending txid {} not in pool, marking as failed", txid); + log::info(logcat, "Pending txid {} not in pool, marking as failed", txid); pit->second.m_state = wallet2::unconfirmed_transfer_details::failed; // the inputs aren't spent anymore, since the tx failed @@ -3177,7 +3177,7 @@ std::vector wallet2::get_pool_state(bool refreshed) const transfer_details &td = m_transfers[i]; if (td.m_key_image == tx_in_to_key->k_image) { - oxen::log::info(logcat, "Resetting spent status for output {}: {}", vini, td.m_key_image); + log::info(logcat, "Resetting spent status for output {}: {}", vini, td.m_key_image); set_unspent(i); break; } @@ -3187,7 +3187,7 @@ std::vector wallet2::get_pool_state(bool refreshed) } } } - oxen::log::trace(logcat, "get_pool_state done first loop"); + log::trace(logcat, "get_pool_state done first loop"); // remove pool txes to us that aren't in the pool anymore // but only if we just refreshed, so that the tx can go in @@ -3196,7 +3196,7 @@ std::vector wallet2::get_pool_state(bool refreshed) if (refreshed) remove_obsolete_pool_txs(pool_hashes); - oxen::log::trace(logcat, "get_pool_state done second loop"); + log::trace(logcat, "get_pool_state done second loop"); // gather txids of new blink txes to us. We just ignore non-blinks here (we pick them up when they // get mined into a block). @@ -3217,13 +3217,13 @@ std::vector wallet2::get_pool_state(bool refreshed) // if it's for us, we want to keep track of whether we saw a double spend, so don't bail out if (!txid_found_in_up) { - oxen::log::debug(logcat, "Already seen {}, and not for us, skipped", txid); + log::debug(logcat, "Already seen {}, and not for us, skipped", txid); continue; } } if (!txid_found_in_up) { - oxen::log::info(logcat, "Found new pool tx: {}", txid); + log::info(logcat, "Found new pool tx: {}", txid); bool found = false; for (const auto &i: m_unconfirmed_txs) { @@ -3252,7 +3252,7 @@ std::vector wallet2::get_pool_state(bool refreshed) } else { - oxen::log::info(logcat, "We sent that one"); + log::info(logcat, "We sent that one"); } } } @@ -3272,7 +3272,7 @@ std::vector wallet2::get_pool_state(bool refreshed) }; auto res = m_http_client.json_rpc("get_transactions", get_transactions_params); } catch (const std::exception& e) { - oxen::log::warning(logcat, "Failed to retrieve transactions: {}", e.what()); + log::warning(logcat, "Failed to retrieve transactions: {}", e.what()); return process_txs; } for (const auto &tx_entry: res["txs"]) @@ -3293,21 +3293,21 @@ std::vector wallet2::get_pool_state(bool refreshed) } else { - oxen::log::error(logcat, "Got txid {} which we did not ask for", tx_hash); + log::error(logcat, "Got txid {} which we did not ask for", tx_hash); } } else { - oxen::log::warning(logcat, "Failed to parse transaction from daemon"); + log::warning(logcat, "Failed to parse transaction from daemon"); } } else { - oxen::log::info(logcat, "Transaction from daemon was in pool, but is no more"); + log::info(logcat, "Transaction from daemon was in pool, but is no more"); } } } - oxen::log::trace(logcat, "get_pool_state end"); + log::trace(logcat, "get_pool_state end"); return process_txs; } //---------------------------------------------------------------------------------------------------- @@ -3353,7 +3353,7 @@ void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, return; if (blocks_start_height < m_blockchain.offset()) { - oxen::log::error(logcat, "Blocks start before blockchain offset: {} {}", blocks_start_height, m_blockchain.offset()); + log::error(logcat, "Blocks start before blockchain offset: {} {}", blocks_start_height, m_blockchain.offset()); return; } current_index = blocks_start_height; @@ -3371,7 +3371,7 @@ void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, if(current_index >= m_blockchain.size()) { if (!(current_index % 1024)) - oxen::log::debug(logcat, "Skipped block by height: {}", current_index); + log::debug(logcat, "Skipped block by height: {}", current_index); m_blockchain.push_back(bl_id); m_cached_height++; @@ -3540,7 +3540,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (const tools::error::out_of_hashchain_bounds_error&) { - oxen::log::info(logcat, "Daemon claims next refresh block is out of hash chain bounds, resetting hash chain"); + log::info(logcat, "Daemon claims next refresh block is out of hash chain bounds, resetting hash chain"); uint64_t stop_height = m_blockchain.offset(); std::vector tip(m_blockchain.size() - m_blockchain.offset()); for (size_t i = m_blockchain.offset(); i < m_blockchain.size(); ++i) @@ -3565,7 +3565,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (const std::exception &e) { - oxen::log::error(logcat, "Error parsing blocks: {}", e.what()); + log::error(logcat, "Error parsing blocks: {}", e.what()); error = true; } blocks_fetched += added_blocks; @@ -3607,7 +3607,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo waiter.wait(&tpool); if(try_count < 3) { - oxen::log::info(logcat, "Another try pull_blocks (try_count={})...", try_count); + log::info(logcat, "Another try pull_blocks (try_count={})...", try_count); first = true; start_height = 0; blocks.clear(); @@ -3618,7 +3618,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } else { - oxen::log::error(logcat, "pull_blocks failed, try_count={}", try_count); + log::error(logcat, "pull_blocks failed, try_count={}", try_count); throw; } } @@ -3638,14 +3638,14 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } catch (...) { - oxen::log::info(logcat, "Failed to check pending transactions"); + log::info(logcat, "Failed to check pending transactions"); } refresh_batching_cache(); m_first_refresh_done = true; - oxen::log::info(logcat, "Refresh done, blocks received: {}, balance (all accounts): {}, unlocked: {}", blocks_fetched, print_money(balance_all(false)), print_money(unlocked_balance_all(false))); + log::info(logcat, "Refresh done, blocks received: {}, balance (all accounts): {}, unlocked: {}", blocks_fetched, print_money(balance_all(false)), print_money(unlocked_balance_all(false))); } //---------------------------------------------------------------------------------------------------- bool wallet2::refresh(bool trusted_daemon, uint64_t & blocks_fetched, bool& received_money, bool& ok) @@ -3670,10 +3670,10 @@ bool wallet2::get_rct_distribution(uint64_t &start_height, std::vector if (rpc_version < rpc::version_t{1, 19}) { - oxen::log::warning(logcat, "Daemon is too old, not requesting rct distribution"); + log::warning(logcat, "Daemon is too old, not requesting rct distribution"); return false; } - oxen::log::debug(logcat, "Daemon is recent enough, requesting rct distribution"); + log::debug(logcat, "Daemon is recent enough, requesting rct distribution"); cryptonote::rpc::GET_OUTPUT_DISTRIBUTION_BIN::request req{}; cryptonote::rpc::GET_OUTPUT_DISTRIBUTION_BIN::response res{}; @@ -3685,27 +3685,27 @@ bool wallet2::get_rct_distribution(uint64_t &start_height, std::vector bool r = invoke_http(req, res); if (!r) { - oxen::log::warning(logcat, "Failed to request output distribution: no connection to daemon"); + log::warning(logcat, "Failed to request output distribution: no connection to daemon"); return false; } if (res.status == rpc::STATUS_BUSY) { - oxen::log::warning(logcat, "Failed to request output distribution: daemon is busy"); + log::warning(logcat, "Failed to request output distribution: daemon is busy"); return false; } if (res.status != rpc::STATUS_OK) { - oxen::log::warning(logcat, "Failed to request output distribution: {}", res.status); + log::warning(logcat, "Failed to request output distribution: {}", res.status); return false; } if (res.distributions.size() != 1) { - oxen::log::warning(logcat, "Failed to request output distribution: not the expected single result"); + log::warning(logcat, "Failed to request output distribution: not the expected single result"); return false; } if (res.distributions[0].amount != 0) { - oxen::log::warning(logcat, "Failed to request output distribution: results are not for amount 0"); + log::warning(logcat, "Failed to request output distribution: results are not for amount 0"); return false; } for (size_t i = 1; i < res.distributions[0].data.distribution.size(); ++i) @@ -3724,17 +3724,17 @@ bool wallet2::get_output_blacklist(std::vector &blacklist) } if (rpc_version < rpc::version_t{2, 3}) { - oxen::log::warning(logcat, "Daemon is too old, not requesting output blacklist"); + log::warning(logcat, "Daemon is too old, not requesting output blacklist"); return false; } - oxen::log::debug(logcat, "Daemon is recent enough, requesting output blacklist"); + log::debug(logcat, "Daemon is recent enough, requesting output blacklist"); try { auto res = m_http_client.json_rpc("get_output_blacklist", {}); blacklist = std::move(res["blacklist"].get>()); } catch (...) { - oxen::log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); - oxen::log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); + log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); + log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); return false; } @@ -3743,7 +3743,7 @@ bool wallet2::get_output_blacklist(std::vector &blacklist) //---------------------------------------------------------------------------------------------------- void wallet2::detach_blockchain(uint64_t height, std::map, size_t> *output_tracker_cache) { - oxen::log::warning(logcat, "Detaching blockchain on height {}", height); + log::warning(logcat, "Detaching blockchain on height {}", height); // size 1 2 3 4 5 6 7 8 9 // block 0 1 2 3 4 5 6 7 8 @@ -3758,7 +3758,7 @@ void wallet2::detach_blockchain(uint64_t height, std::map= height) { - oxen::log::info(logcat, "Resetting spent/frozen status for output {}: {}", i, td.m_key_image); + log::info(logcat, "Resetting spent/frozen status for output {}: {}", i, td.m_key_image); set_unspent(i); thaw(i); } @@ -3814,7 +3814,7 @@ void wallet2::detach_blockchain(uint64_t height, std::map wallet2::get_keys_file_data(const epee::w try { multisig_signers = serialization::dump_binary(m_multisig_signers); } catch (const std::exception& e) { - oxen::log::error(logcat, "failed to serialize wallet multisig signers: {}", e.what()); + log::error(logcat, "failed to serialize wallet multisig signers: {}", e.what()); return std::nullopt; } value.SetString(multisig_signers.c_str(), multisig_signers.length()); @@ -3974,7 +3974,7 @@ std::optional wallet2::get_keys_file_data(const epee::w try { multisig_derivations = serialization::dump_binary(m_multisig_derivations); } catch (const std::exception& e) { - oxen::log::error(logcat, "failed to serialize wallet multisig derivations"); + log::error(logcat, "failed to serialize wallet multisig derivations"); return std::nullopt; } value.SetString(multisig_derivations.c_str(), multisig_derivations.length()); @@ -4154,7 +4154,7 @@ bool wallet2::load_keys(const fs::path& keys_file_name, const epee::wipeable_str if (!saved_ret) { // just moan a bit, but not fatal - oxen::log::error(logcat, "Error saving keys file with encrypted keys, not fatal"); + log::error(logcat, "Error saving keys file with encrypted keys, not fatal"); } if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) decrypt_keys(*keys_to_encrypt); @@ -4230,12 +4230,12 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json.HasMember("key_data")) { - oxen::log::error(logcat, "Field key_data not found in JSON"); + log::error(logcat, "Field key_data not found in JSON"); return false; } if (!json["key_data"].IsString()) { - oxen::log::error(logcat, "Field key_data found in JSON, but not String"); + log::error(logcat, "Field key_data found in JSON, but not String"); return false; } const char *field_key_data = json["key_data"].GetString(); @@ -4264,12 +4264,12 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json.HasMember("multisig_signers")) { - oxen::log::error(logcat, "Field multisig_signers not found in JSON"); + log::error(logcat, "Field multisig_signers not found in JSON"); return false; } if (!json["multisig_signers"].IsString()) { - oxen::log::error(logcat, "Field multisig_signers found in JSON, but not String"); + log::error(logcat, "Field multisig_signers found in JSON, but not String"); return false; } const char *field_multisig_signers = json["multisig_signers"].GetString(); @@ -4277,7 +4277,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st try { serialization::parse_binary(multisig_signers, m_multisig_signers); } catch (const std::exception& e) { - oxen::log::error(logcat, "Field multisig_signers found in JSON, but failed to parse: {}", e.what()); + log::error(logcat, "Field multisig_signers found in JSON, but failed to parse: {}", e.what()); return false; } @@ -4286,7 +4286,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st { if (!json["multisig_derivations"].IsString()) { - oxen::log::error(logcat, "Field multisig_derivations found in JSON, but not String"); + log::error(logcat, "Field multisig_derivations found in JSON, but not String"); return false; } const char *field_multisig_derivations = json["multisig_derivations"].GetString(); @@ -4294,7 +4294,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st try { serialization::parse_binary(multisig_derivations, m_multisig_derivations); } catch (const std::exception& e) { - oxen::log::error(logcat, "Field multisig_derivations found in JSON, but failed to parse: {}", e.what()); + log::error(logcat, "Field multisig_derivations found in JSON, but failed to parse: {}", e.what()); return false; } } @@ -4337,7 +4337,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st if (field_refresh_type == RefreshFull || field_refresh_type == RefreshOptimizeCoinbase || field_refresh_type == RefreshNoCoinbase) m_refresh_type = (RefreshType)field_refresh_type; else - oxen::log::warning(logcat, "Unknown refresh-type value ({}), using default", field_refresh_type); + log::warning(logcat, "Unknown refresh-type value ({}), using default", field_refresh_type); } GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, refresh_height, uint64_t, Uint64, false, 0); m_refresh_from_block_height = field_refresh_height; @@ -4413,7 +4413,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st bool ok = get_account_address_from_str(info, m_nettype, field_original_address); if (!ok) { - oxen::log::error(logcat, "Failed to parse original_address from JSON"); + log::error(logcat, "Failed to parse original_address from JSON"); return false; } m_original_address = info.address; @@ -4421,7 +4421,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st ok = tools::hex_to_type(field_original_view_secret_key, m_original_view_secret_key); if (!ok) { - oxen::log::error(logcat, "Failed to parse original_view_secret_key from JSON"); + log::error(logcat, "Failed to parse original_view_secret_key from JSON"); return false; } } @@ -4440,7 +4440,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st bool r = epee::serialization::load_t_from_binary(m_account, account_data); THROW_WALLET_EXCEPTION_IF(!r, error::invalid_password); if (m_key_device_type == hw::device::type::LEDGER || m_key_device_type == hw::device::type::TREZOR) { - oxen::log::warning(logcat, "Account on device. Initing device..."); + log::warning(logcat, "Account on device. Initing device..."); hw::device &hwdev = lookup_device(m_device_name); THROW_WALLET_EXCEPTION_IF(!hwdev.set_name(m_device_name), error::wallet_internal_error, "Could not set device name " + m_device_name); hwdev.set_network_type(m_nettype); @@ -4456,7 +4456,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st "Device wallet does not match wallet address. " "Device address: " + cryptonote::get_account_address_as_str(m_nettype, false, device_account_public_address) + ", wallet address: " + m_account.get_public_address_str(m_nettype)); - oxen::log::warning(logcat, "Device initialized..."); + log::warning(logcat, "Device initialized..."); } else if (key_on_device()) { THROW_WALLET_EXCEPTION(error::wallet_internal_error, "hardware device not supported"); } @@ -4622,7 +4622,7 @@ void wallet2::create_keys_file(const fs::path &wallet_, bool watch_only, const e auto addrfile = m_wallet_file; addrfile += ".address.txt"; r = tools::dump_file(addrfile, m_account.get_public_address_str(m_nettype)); - if(!r) oxen::log::error(logcat, "String with address text not saved"); + if(!r) log::error(logcat, "String with address text not saved"); } } } @@ -4970,7 +4970,7 @@ void wallet2::restore_from_device(const fs::path& wallet_, const epee::wipeable_ hwdev_filename += ".hwdev.txt"; std::string hwdev_text = hwdev_label.value_or(""); if (!tools::dump_file(hwdev_filename, hwdev_text)) - oxen::log::error(logcat, "failed to write .hwdev.txt comment file"); + log::error(logcat, "failed to write .hwdev.txt comment file"); if (progress_callback) progress_callback(tr("Setting up account and subaddresses")); setup_new_blockchain(); @@ -5032,7 +5032,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, if (threshold == spend_keys.size() + 1) { // In N / N case we only need to do one round and calculate secret multisig keys and new secret spend key - oxen::log::info(logcat, "Creating spend key..."); + log::info(logcat, "Creating spend key..."); // Calculates all multisig keys and spend key cryptonote::generate_multisig_N_N(get_account().get_keys(), spend_keys, multisig_keys, spend_skey, spend_pkey); @@ -5056,7 +5056,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, // We need an extra step, so we package all the composite public keys // we know about, and make a signed string out of them - oxen::log::info(logcat, "Creating spend key..."); + log::info(logcat, "Creating spend key..."); // Calculating set of our secret multisig keys as follows: mi = H(Mi), // where mi - secret multisig key, Mi - others' participants public multisig key @@ -5074,7 +5074,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, else { // M / N case - oxen::log::info(logcat, "Preparing keys for next exchange round..."); + log::info(logcat, "Preparing keys for next exchange round..."); // Preparing data for middle round - packing new public multisig keys to exchage with others. extra_multisig_info = pack_multisignature_keys(derivations, m_account.get_keys().m_spend_secret_key); @@ -5095,10 +5095,10 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, } clear(); - oxen::log::info(logcat, "Creating view key..."); + log::info(logcat, "Creating view key..."); crypto::secret_key view_skey = cryptonote::generate_multisig_view_secret_key(get_account().get_keys().m_view_secret_key, view_keys); - oxen::log::info(logcat, "Creating multisig address..."); + log::info(logcat, "Creating multisig address..."); CHECK_AND_ASSERT_THROW_MES(m_account.make_multisig(view_skey, rct::rct2sk(spend_skey), rct::rct2pk(spend_pkey), multisig_keys), "Failed to create multisig wallet due to bad keys"); memwipe(&spend_skey, sizeof(rct::key)); @@ -5216,7 +5216,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor if (fs::exists(addrfile)) { r = tools::dump_file(addrfile, m_account.get_public_address_str(m_nettype)); - if(!r) oxen::log::error(logcat, "String with address text not saved"); + if(!r) log::error(logcat, "String with address text not saved"); } } @@ -5242,7 +5242,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor if (m_multisig_rounds_passed == multisig_rounds_required(m_multisig_signers.size(), m_multisig_threshold) - 2) // next round is last { // Next round is last therefore we are performing secret spend establishment round as described above. - oxen::log::info(logcat, "Creating spend key..."); + log::info(logcat, "Creating spend key..."); // Calculating our secret multisig keys by hashing our public multisig keys. auto multisig_keys = cryptonote::calculate_multisig_keys(std::vector(new_derivations.begin(), new_derivations.end())); @@ -5257,7 +5257,7 @@ std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &passwor else { // This is just middle round - oxen::log::info(logcat, "Preparing keys for next exchange round..."); + log::info(logcat, "Preparing keys for next exchange round..."); extra_multisig_info = pack_multisignature_keys(new_derivations, m_account.get_keys().m_spend_secret_key); m_multisig_derivations = new_derivations; } @@ -5294,7 +5294,7 @@ void wallet2::unpack_multisig_info(const std::vector& info, { if (rct::sk2rct(secret_keys[i]) == rct::sk2rct(secret_keys[j])) { - oxen::log::debug(logcat, "Duplicate key found, ignoring"); + log::debug(logcat, "Duplicate key found, ignoring"); secret_keys[j] = secret_keys.back(); public_keys[j] = public_keys.back(); secret_keys.pop_back(); @@ -5311,7 +5311,7 @@ void wallet2::unpack_multisig_info(const std::vector& info, { if (secret_keys[i] == local_skey) { - oxen::log::debug(logcat, "Local key is present, ignoring"); + log::debug(logcat, "Local key is present, ignoring"); secret_keys[i] = secret_keys.back(); public_keys[i] = public_keys.back(); secret_keys.pop_back(); @@ -5342,17 +5342,17 @@ bool wallet2::finalize_multisig(const epee::wipeable_string &password, const std uint32_t threshold, total; if (!multisig(&ready, &threshold, &total)) { - oxen::log::error(logcat, "This is not a multisig wallet"); + log::error(logcat, "This is not a multisig wallet"); return false; } if (ready) { - oxen::log::error(logcat, "This multisig wallet is already finalized"); + log::error(logcat, "This multisig wallet is already finalized"); return false; } if (threshold + 1 != total) { - oxen::log::error(logcat, "finalize_multisig should only be used for N-1/N wallets, use exchange_multisig_keys instead"); + log::error(logcat, "finalize_multisig should only be used for N-1/N wallets, use exchange_multisig_keys instead"); return false; } exchange_multisig_keys(password, pkeys, signers); @@ -5382,7 +5382,7 @@ bool wallet2::finalize_multisig(const epee::wipeable_string &password, const std std::vector signers; if (!unpack_extra_multisig_info(info, signers, public_keys)) { - oxen::log::error(logcat, "Bad multisig info"); + log::error(logcat, "Bad multisig info"); return false; } @@ -5412,18 +5412,18 @@ bool wallet2::verify_multisig_info(const std::string &data, crypto::secret_key & { if (!tools::starts_with(data, MULTISIG_MAGIC)) { - oxen::log::error(logcat, "Multisig info header check error"); + log::error(logcat, "Multisig info header check error"); return false; } std::string decoded; if (!tools::base58::decode(data.substr(MULTISIG_MAGIC.size()), decoded)) { - oxen::log::error(logcat, "Multisig info decoding error"); + log::error(logcat, "Multisig info decoding error"); return false; } if (decoded.size() != sizeof(crypto::secret_key) + sizeof(crypto::public_key) + sizeof(crypto::signature)) { - oxen::log::error(logcat, "Multisig info is corrupt"); + log::error(logcat, "Multisig info is corrupt"); return false; } @@ -5438,7 +5438,7 @@ bool wallet2::verify_multisig_info(const std::string &data, crypto::secret_key & crypto::cn_fast_hash(decoded.data(), decoded.size() - sizeof(signature), hash); if (!crypto::check_signature(hash, pkey, signature)) { - oxen::log::error(logcat, "Multisig info signature is invalid"); + log::error(logcat, "Multisig info signature is invalid"); return false; } @@ -5449,23 +5449,23 @@ bool wallet2::verify_extra_multisig_info(const std::string &data, std::unordered { if (!tools::starts_with(data, MULTISIG_EXTRA_INFO_MAGIC)) { - oxen::log::error(logcat, "Multisig info header check error"); + log::error(logcat, "Multisig info header check error"); return false; } std::string decoded; if (!tools::base58::decode(data.substr(MULTISIG_EXTRA_INFO_MAGIC.size()), decoded)) { - oxen::log::error(logcat, "Multisig info decoding error"); + log::error(logcat, "Multisig info decoding error"); return false; } if (decoded.size() < sizeof(crypto::public_key) + sizeof(crypto::signature)) { - oxen::log::error(logcat, "Multisig info is corrupt"); + log::error(logcat, "Multisig info is corrupt"); return false; } if ((decoded.size() - (sizeof(crypto::public_key) + sizeof(crypto::signature))) % sizeof(crypto::public_key)) { - oxen::log::error(logcat, "Multisig info is corrupt"); + log::error(logcat, "Multisig info is corrupt"); return false; } @@ -5479,7 +5479,7 @@ bool wallet2::verify_extra_multisig_info(const std::string &data, std::unordered crypto::cn_fast_hash(decoded.data(), decoded.size() - sizeof(signature), hash); if (!crypto::check_signature(hash, signer, signature)) { - oxen::log::error(logcat, "Multisig info signature is invalid"); + log::error(logcat, "Multisig info signature is invalid"); return false; } @@ -5670,7 +5670,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor { THROW_WALLET_EXCEPTION_IF(true, error::file_read_error, m_keys_file); } - oxen::log::warning(logcat, "Loaded wallet keys file, with public address: {}", m_account.get_public_address_str(m_nettype)); + log::warning(logcat, "Loaded wallet keys file, with public address: {}", m_account.get_public_address_str(m_nettype)); lock_keys_file(); } else if (!load_keys_buf(keys_buf, password)) @@ -5684,7 +5684,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor //try to load wallet file. but even if we failed, it is not big problem if (use_fs && (!fs::exists(m_wallet_file, e) || e)) { - oxen::log::warning(logcat, "file not found: {}, starting with empty blockchain", m_wallet_file); + log::warning(logcat, "file not found: {}, starting with empty blockchain", m_wallet_file); m_account_public_address = m_account.get_keys().m_account_address; } else if (use_fs || !cache_buf.empty()) @@ -5701,7 +5701,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor // try to read it as an encrypted cache try { - oxen::log::info(logcat, "Trying to decrypt cache data"); + log::info(logcat, "Trying to decrypt cache data"); try { serialization::parse_binary(use_fs ? cache_file_buf : cache_buf, cache_file_data); @@ -5742,7 +5742,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - oxen::log::warning(logcat, "Failed to open portable binary, trying unportable"); + log::warning(logcat, "Failed to open portable binary, trying unportable"); auto unportable = m_wallet_file; unportable += ".unportable"; if (use_fs) fs::copy_file(m_wallet_file, unportable, fs::copy_options::overwrite_existing); @@ -5756,7 +5756,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - oxen::log::info(logcat, "Failed to load encrypted cache, trying unencrypted"); + log::info(logcat, "Failed to load encrypted cache, trying unencrypted"); try { std::stringstream iss; iss << cache_file_buf; @@ -5765,7 +5765,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (...) { - oxen::log::warning(logcat, "Failed to open portable binary, trying unportable"); + log::warning(logcat, "Failed to open portable binary, trying unportable"); auto unportable = m_wallet_file; unportable += ".unportable"; if (use_fs) fs::copy_file(m_wallet_file, unportable, fs::copy_options::overwrite_existing); @@ -5813,7 +5813,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to save rings, will try again next time"); + log::error(logcat, "Failed to save rings, will try again next time"); } #ifdef WALLET_ENABLE_MMS @@ -5824,7 +5824,7 @@ void wallet2::load(const fs::path& wallet_, const epee::wipeable_string& passwor } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to initialize MMS, it will be unusable"); + log::error(logcat, "Failed to initialize MMS, it will be unusable"); } #endif } @@ -5840,7 +5840,7 @@ void wallet2::trim_hashchain() if (!m_blockchain.empty() && m_blockchain.size() == m_blockchain.offset()) { - oxen::log::info(logcat, "Fixing empty hashchain"); + log::info(logcat, "Fixing empty hashchain"); nlohmann::json req_params{ {"height", m_blockchain.size() - 1} }; @@ -5854,19 +5854,19 @@ void wallet2::trim_hashchain() } else { - oxen::log::error(logcat, "Failed to request block header from daemon, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); + log::error(logcat, "Failed to request block header from daemon, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); } } catch (const std::exception &e) { - oxen::log::error(logcat, "Failed to request block header from daemon when requesting get_block_header_by_height, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); + log::error(logcat, "Failed to request block header from daemon when requesting get_block_header_by_height, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); } } if (height > 0 && m_blockchain.size() > height) { --height; - oxen::log::debug(logcat, "trimming to {}, offset {}", height, m_blockchain.offset()); + log::debug(logcat, "trimming to {}, offset {}", height, m_blockchain.offset()); m_blockchain.trim(height); } m_cached_height = m_blockchain.size(); @@ -5936,18 +5936,18 @@ void wallet2::store_to(const fs::path &path, const epee::wipeable_string &passwo THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_wallet_file); // remove old address file if (!fs::remove(old_address_file, ec)) - oxen::log::error(logcat, "error removing file: {}: {}", old_address_file, ec.message()); + log::error(logcat, "error removing file: {}: {}", old_address_file, ec.message()); } // remove old wallet file if (!fs::remove(old_file, ec)) - oxen::log::error(logcat, "error removing file: {}: {}", old_file, ec.message()); + log::error(logcat, "error removing file: {}: {}", old_file, ec.message()); // remove old keys file if (!fs::remove(old_keys_file, ec)) - oxen::log::error(logcat, "error removing file: {}: {}", old_keys_file, ec.message()); + log::error(logcat, "error removing file: {}: {}", old_keys_file, ec.message()); #ifdef WALLET_ENABLE_MMS // remove old message store file if (fs::exists(m_mms_file, ec) && !fs::remove(m_mms_file, ec)) - oxen::log::error(logcat, "error removing file: {}: {}", m_mms_file, ec.message()); + log::error(logcat, "error removing file: {}: {}", m_mms_file, ec.message()); #endif } else { // save to new file @@ -6302,7 +6302,7 @@ void wallet2::get_transfers(get_transfers_args_t args, std::vector> pending_or_failed; std::list> pool; - oxen::log::debug(logcat, "Getting transfers of type(s) {}{}{}{}{} for heights in[{},{}]", (args.in ? "in " : ""), (args.out ? "out " : ""), (args.pending ? "pending " : ""), (args.failed ? "failed " : ""), (args.pool ? "pool " : ""), args.min_height, args.max_height); + log::debug(logcat, "Getting transfers of type(s) {}{}{}{}{} for heights in[{},{}]", (args.in ? "in " : ""), (args.out ? "out " : ""), (args.pending ? "pending " : ""), (args.failed ? "failed " : ""), (args.pool ? "pool " : ""), args.min_height, args.max_height); size_t size = 0; if (args.in) @@ -6401,7 +6401,7 @@ std::string wallet2::transfers_to_csv(const std::vector& running_balance -= transfer.amount + transfer.fee; break; default: - oxen::log::error(logcat, "Warning: Unhandled pay type, this is most likely a developer error, please report it to the Oxen developers."); + log::error(logcat, "Warning: Unhandled pay type, this is most likely a developer error, please report it to the Oxen developers."); break; } @@ -6520,12 +6520,12 @@ std::optional wallet2::resolve_address(std::string address, uint64_ { info = std::move(*addr_info); result = true; - oxen::log::debug(logcat, "Resolved ONS name: {} to address: {}", address, get_account_address_as_str(m_nettype, info.is_subaddress, info.address)); + log::debug(logcat, "Resolved ONS name: {} to address: {}", address, get_account_address_as_str(m_nettype, info.is_subaddress, info.address)); } } } else { - oxen::log::debug(logcat, "Invalid address format, could not resolve {}", address); + log::debug(logcat, "Invalid address format, could not resolve {}", address); } } @@ -6554,7 +6554,7 @@ void wallet2::rescan_spent() for (size_t start_offset = 0; start_offset < m_transfers.size(); start_offset += chunk_size) { const size_t n_outputs = std::min(chunk_size, m_transfers.size() - start_offset); - oxen::log::debug(logcat, "Calling is_key_image_spent on {} - {}, out of {}", start_offset, (start_offset + n_outputs - 1), m_transfers.size()); + log::debug(logcat, "Calling is_key_image_spent on {} - {}, out of {}", start_offset, (start_offset + n_outputs - 1), m_transfers.size()); std::vector key_images; key_images.reserve(n_outputs); for (size_t n = start_offset; n < start_offset + n_outputs; ++n) @@ -6583,13 +6583,13 @@ void wallet2::rescan_spent() { if (td.m_spent) { - oxen::log::warning(logcat, "Marking output {}({}) as unspent, it was marked as spent", i, td.m_key_image); + log::warning(logcat, "Marking output {}({}) as unspent, it was marked as spent", i, td.m_key_image); set_unspent(i); td.m_spent_height = 0; } else { - oxen::log::warning(logcat, "Marking output {}({}) as spent, it was marked as unspent", i, td.m_key_image); + log::warning(logcat, "Marking output {}({}) as spent, it was marked as unspent", i, td.m_key_image); set_spent(i, td.m_spent_height); // unknown height, if this gets reorged, it might still be missed } @@ -6660,7 +6660,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, if (!success) { // We'll already have a log message printed containing the request failure reason - oxen::log::info(logcat, "Failed to query service node for blacklisted transfers, assuming transfer not blacklisted"); + log::info(logcat, "Failed to query service node for blacklisted transfers, assuming transfer not blacklisted"); return true; } @@ -6669,7 +6669,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, crypto::key_image check_image; if(!tools::hex_to_type(entry["key_image"].get(), check_image)) { - oxen::log::error(logcat, "Failed to parse hex representation of key image: {}", entry["key_image"]); + log::error(logcat, "Failed to parse hex representation of key image: {}", entry["key_image"]); break; } @@ -6684,7 +6684,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, auto [success, service_nodes_states] = m_node_rpc_proxy.get_contributed_service_nodes(primary_address); if (!success) { - oxen::log::info(logcat, "Failed to query service node for locked transfers, assuming transfer not locked"); + log::info(logcat, "Failed to query service node for locked transfers, assuming transfer not locked"); return true; } @@ -6700,7 +6700,7 @@ bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height, crypto::key_image check_image; if(!tools::hex_to_type(contribution["key_image"].get(), check_image)) { - oxen::log::error(logcat, "Failed to parse hex representation of key image: {}", contribution["key_image"]); + log::error(logcat, "Failed to parse hex representation of key image: {}", contribution["key_image"]); break; } @@ -6913,7 +6913,7 @@ crypto::hash wallet2::get_payment_id(const pending_tx &ptx) const { if (ptx.dests.empty()) { - oxen::log::warning(logcat, "Encrypted payment id found, but no destinations public key, cannot decrypt"); + log::warning(logcat, "Encrypted payment id found, but no destinations public key, cannot decrypt"); return crypto::null_hash; } if (m_account.get_device().decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key)) @@ -6992,7 +6992,7 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) m_additional_tx_keys.insert(std::make_pair(txid, ptx.additional_tx_keys)); } - oxen::log::debug(logcat, "transaction {} generated ok and sent to daemon, key_images: [{}]", txid, ptx.key_images); + log::debug(logcat, "transaction {} generated ok and sent to daemon, key_images: [{}]", txid, ptx.key_images); for(size_t idx: ptx.selected_transfers) { @@ -7004,7 +7004,7 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) memwipe(m_transfers[idx].m_multisig_k.data(), m_transfers[idx].m_multisig_k.size() * sizeof(m_transfers[idx].m_multisig_k[0])); //fee includes dust if dust policy specified it. - oxen::log::info(logcat, "Transaction successfully {}{} \ + log::info(logcat, "Transaction successfully {}{} \ \nCommission: {} (dust sent to dust addr: {})\ \nBalance: {} \ \nUnlocked: {} \ @@ -7022,7 +7022,7 @@ void wallet2::commit_tx(std::vector& ptx_vector, bool blink) //---------------------------------------------------------------------------------------------------- bool wallet2::save_tx(const std::vector& ptx_vector, const fs::path& filename) const { - oxen::log::warning(logcat, "saving {} transactions", ptx_vector.size()); + log::warning(logcat, "saving {} transactions", ptx_vector.size()); std::string ciphertext = dump_tx_to_str(ptx_vector); if (ciphertext.empty()) return false; @@ -7031,7 +7031,7 @@ bool wallet2::save_tx(const std::vector& ptx_vector, const fs::path& //---------------------------------------------------------------------------------------------------- std::string wallet2::dump_tx_to_str(const std::vector &ptx_vector) const { - oxen::log::warning(logcat, "saving {} transactions", ptx_vector.size()); + log::warning(logcat, "saving {} transactions", ptx_vector.size()); unsigned_tx_set txs; for (auto &tx: ptx_vector) { @@ -7053,7 +7053,7 @@ std::string wallet2::dump_tx_to_str(const std::vector &ptx_vector) c { return std::string(); } - oxen::log::debug(logcat, "Saving unsigned tx data: {}", oss.str()); + log::debug(logcat, "Saving unsigned tx data: {}", oss.str()); std::string ciphertext = encrypt_with_view_secret_key(oss.str()); return std::string(UNSIGNED_TX_PREFIX) + ciphertext; } @@ -7062,14 +7062,14 @@ bool wallet2::load_unsigned_tx(const fs::path& unsigned_filename, unsigned_tx_se { if (std::error_code ec; !fs::exists(unsigned_filename, ec)) { - oxen::log::warning(logcat, "File {} does not exist: {}", unsigned_filename, ec.message()); + log::warning(logcat, "File {} does not exist: {}", unsigned_filename, ec.message()); return false; } std::string s; if (!tools::slurp_file(unsigned_filename, s)) { - oxen::log::warning(logcat, "Failed to load from {}", unsigned_filename); + log::warning(logcat, "Failed to load from {}", unsigned_filename); return false; } @@ -7080,7 +7080,7 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex { if (!tools::starts_with(s, UNSIGNED_TX_PREFIX_NOVER)) { - oxen::log::warning(logcat, "Bad magic from unsigned tx"); + log::warning(logcat, "Bad magic from unsigned tx"); return false; } s.remove_prefix(UNSIGNED_TX_PREFIX_NOVER.size()); @@ -7097,7 +7097,7 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex } catch (...) { - oxen::log::warning(logcat, "Failed to parse data from unsigned tx"); + log::warning(logcat, "Failed to parse data from unsigned tx"); return false; } } @@ -7114,22 +7114,22 @@ bool wallet2::parse_unsigned_tx_from_str(std::string_view s, unsigned_tx_set &ex } catch (...) { - oxen::log::warning(logcat, "Failed to parse data from unsigned tx"); + log::warning(logcat, "Failed to parse data from unsigned tx"); return false; } } catch (const std::exception &e) { - oxen::log::warning(logcat, "Failed to decrypt unsigned tx: {}", e.what()); + log::warning(logcat, "Failed to decrypt unsigned tx: {}", e.what()); return false; } } else { - oxen::log::warning(logcat, "Unsupported version in unsigned tx"); + log::warning(logcat, "Unsupported version in unsigned tx"); return false; } - oxen::log::info(logcat, "Loaded tx unsigned data from binary: {} transactions", exported_txs.txes.size()); + log::info(logcat, "Loaded tx unsigned data from binary: {} transactions", exported_txs.txes.size()); return true; } @@ -7142,7 +7142,7 @@ bool wallet2::sign_tx(const fs::path& unsigned_filename, const fs::path& signed_ if (accept_func && !accept_func(exported_txs)) { - oxen::log::info(logcat, "Transactions rejected by callback"); + log::info(logcat, "Transactions rejected by callback"); return false; } return sign_tx(exported_txs, signed_filename, txs, export_raw); @@ -7157,7 +7157,7 @@ bool wallet2::sign_tx(unsigned_tx_set &exported_txs, std::vector 1) raw_filename += "_" + std::to_string(i); if (!tools::dump_file(raw_filename, tx_as_hex)) { - oxen::log::warning(logcat, "Failed to save file to {}", raw_filename); + log::warning(logcat, "Failed to save file to {}", raw_filename); return false; } } @@ -7321,7 +7321,7 @@ std::string wallet2::sign_tx_dump_to_str(unsigned_tx_set &exported_txs, std::vec bool r = sign_tx(exported_txs, ptx, signed_txes); if (!r) { - oxen::log::warning(logcat, "Failed to sign unsigned_tx_set"); + log::warning(logcat, "Failed to sign unsigned_tx_set"); return std::string(); } @@ -7336,7 +7336,7 @@ std::string wallet2::sign_tx_dump_to_str(unsigned_tx_set &exported_txs, std::vec { return std::string(); } - oxen::log::trace(logcat, "Saving signed tx data (with encryption): {}", oss.str()); + log::trace(logcat, "Saving signed tx data (with encryption): {}", oss.str()); std::string ciphertext = encrypt_with_view_secret_key(oss.str()); return std::string(SIGNED_TX_PREFIX) + ciphertext; } @@ -7345,14 +7345,14 @@ bool wallet2::load_tx(const fs::path& signed_filename, std::vector txs_hashes; @@ -8008,7 +8008,7 @@ bool wallet2::find_and_save_rings(bool force) for (const auto& [txid, details]: payments) txs_hashes.push_back(txid); - oxen::log::debug(logcat, "Found {} transactions", std::to_string(txs_hashes.size())); + log::debug(logcat, "Found {} transactions", std::to_string(txs_hashes.size())); // get those transactions from the daemon auto it = txs_hashes.begin(); @@ -8021,7 +8021,7 @@ bool wallet2::find_and_save_rings(bool force) }; auto res = m_http_client.json_rpc("get_transactions", get_transactions_params); - oxen::log::debug(logcat, "Scanning {} transactions", res["txs"].size()); + log::debug(logcat, "Scanning {} transactions", res["txs"].size()); for (size_t i = 0; i < res["txs"].size(); ++i, ++it) { const auto &tx_info = res["txs"][i]; @@ -8034,7 +8034,7 @@ bool wallet2::find_and_save_rings(bool force) } } - oxen::log::info(logcat, "Found and saved rings for {} transactions", txs_hashes.size()); + log::info(logcat, "Found and saved rings for {} transactions", txs_hashes.size()); m_ring_history_saved = true; return true; } @@ -8985,7 +8985,7 @@ bool wallet2::lock_keys_file() return true; if (m_keys_file_locker) { - oxen::log::debug(logcat, "{} is already locked.", m_keys_file); + log::debug(logcat, "{} is already locked.", m_keys_file); return false; } m_keys_file_locker.reset(new tools::file_locker(m_keys_file)); @@ -8998,7 +8998,7 @@ bool wallet2::unlock_keys_file() return true; if (!m_keys_file_locker) { - oxen::log::debug(logcat, "{} is already unlocked.", m_keys_file); + log::debug(logcat, "{} is already unlocked.", m_keys_file); return false; } m_keys_file_locker.reset(); @@ -9070,13 +9070,13 @@ bool wallet2::tx_add_fake_output(std::vector> void wallet2::get_outs(std::vector> &outs, const std::vector &selected_transfers, size_t fake_outputs_count, std::vector &rct_offsets, bool has_rct) { - oxen::log::debug(logcat, "fake_outputs_count: {}", fake_outputs_count); + log::debug(logcat, "fake_outputs_count: {}", fake_outputs_count); outs.clear(); #ifdef ENABLE_LIGHT_WALLET @@ -9189,7 +9189,7 @@ void wallet2::get_outs(std::vector> std::sort(output_blacklist.begin(), output_blacklist.end()); if (output_blacklist.size() * 0.05 > (double)rct_offsets.size()) { - oxen::log::warning(logcat, "More than 5% of outputs are blacklisted ({}/{}), please notify the Oxen developers", output_blacklist.size(), rct_offsets.size()); + log::warning(logcat, "More than 5% of outputs are blacklisted ({}/{}), please notify the Oxen developers", output_blacklist.size(), rct_offsets.size()); } nlohmann::json res; @@ -9256,7 +9256,7 @@ void wallet2::get_outs(std::vector> // we ask for more, to have spares if some outputs are still locked size_t base_requested_outputs_count = (size_t)((fake_outputs_count + 1) * 1.5 + 1); - oxen::log::debug(logcat, "base_requested_outputs_count: {}", base_requested_outputs_count); + log::debug(logcat, "base_requested_outputs_count: {}", base_requested_outputs_count); // generate output indices to request rpc::GET_OUTPUTS_BIN::request req{}; @@ -9297,7 +9297,7 @@ void wallet2::get_outs(std::vector> { if (he["amount"].get() == amount) { - oxen::log::debug(logcat, "Found {}: {} total, {} unlocked, {} recent", print_money(amount), he["total_instances"], he["unlocked_instances"], he["recent_instances"]); + log::debug(logcat, "Found {}: {} total, {} unlocked, {} recent", print_money(amount), he["total_instances"], he["unlocked_instances"], he["recent_instances"]); num_outs = he["unlocked_instances"].get(); num_recent_outs = he["recent_instances"].get(); break; @@ -9333,7 +9333,7 @@ void wallet2::get_outs(std::vector> if (use_histogram) { - oxen::log::info(logcat, "{} unlocked outputs of size {}", num_outs, print_money(amount)); + log::info(logcat, "{} unlocked outputs of size {}", num_outs, print_money(amount)); THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, "histogram reports no unlocked outputs for " + std::to_string(amount) + ", not even ours"); THROW_WALLET_EXCEPTION_IF(num_recent_outs > num_outs, error::wallet_internal_error, @@ -9343,7 +9343,7 @@ void wallet2::get_outs(std::vector> { // the base offset of the first rct output in the first unlocked block (or the one to be if there's none) num_outs = rct_offsets[rct_offsets.size() - DEFAULT_TX_SPENDABLE_AGE]; - oxen::log::info(logcat, "{} unlocked rct outputs", num_outs); + log::info(logcat, "{} unlocked rct outputs", num_outs); THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, "histogram reports no unlocked rct outputs, not even ours"); } @@ -9366,7 +9366,7 @@ void wallet2::get_outs(std::vector> if (td.m_global_output_index >= num_outs - num_recent_outs && recent_outputs_count > 0) --recent_outputs_count; // if the real out is recent, pick one less recent fake out } - oxen::log::info(logcat, "Fake output makeup: {} requested: {} recent, {} pre-fork, {} post-fork, {} full-chain", requested_outputs_count, recent_outputs_count, pre_fork_outputs_count, post_fork_outputs_count, (requested_outputs_count - recent_outputs_count - pre_fork_outputs_count - post_fork_outputs_count)); + log::info(logcat, "Fake output makeup: {} requested: {} recent, {} pre-fork, {} post-fork, {} full-chain", requested_outputs_count, recent_outputs_count, pre_fork_outputs_count, post_fork_outputs_count, (requested_outputs_count - recent_outputs_count - pre_fork_outputs_count - post_fork_outputs_count)); uint64_t num_found = 0; @@ -9376,7 +9376,7 @@ void wallet2::get_outs(std::vector> std::vector ring; if (get_ring(get_ringdb_key(), td.m_key_image, ring)) { - oxen::log::info(logcat, "This output has a known ring, reusing (size {})", ring.size()); + log::info(logcat, "This output has a known ring, reusing (size {})", ring.size()); THROW_WALLET_EXCEPTION_IF(ring.size() > fake_outputs_count + 1, error::wallet_internal_error, "An output in this transaction was previously spent on another chain with ring size " + std::to_string(ring.size()) + ", it cannot be spent now with ring size " + @@ -9384,22 +9384,22 @@ void wallet2::get_outs(std::vector> bool own_found = false; for (const auto &out: ring) { - oxen::log::info(logcat, "Ring has output {}", out); + log::info(logcat, "Ring has output {}", out); if (out < num_outs) { - oxen::log::info(logcat, "Using it"); + log::info(logcat, "Using it"); get_outputs.push_back({amount, out}); ++num_found; seen_indices.emplace(out); if (out == td.m_global_output_index) { - oxen::log::info(logcat, "This is the real output"); + log::info(logcat, "This is the real output"); own_found = true; } } else { - oxen::log::info(logcat, "Ignoring output {}, too recent", out); + log::info(logcat, "Ignoring output {}, too recent", out); } } THROW_WALLET_EXCEPTION_IF(!own_found, error::wallet_internal_error, @@ -9425,7 +9425,7 @@ void wallet2::get_outs(std::vector> num_found = 1; seen_indices.emplace(td.m_global_output_index); get_outputs.push_back({amount, td.m_global_output_index}); - oxen::log::info(logcat, "Selecting real output: {} for {}", td.m_global_output_index, print_money(amount)); + log::info(logcat, "Selecting real output: {} for {}", td.m_global_output_index, print_money(amount)); } std::unordered_map> picks; @@ -9433,7 +9433,7 @@ void wallet2::get_outs(std::vector> // while we still need more mixins uint64_t num_usable_outs = num_outs; bool allow_blackballed_or_blacklisted = false; - oxen::log::debug(logcat, "Starting gamma picking with {}, num_usable_outs {}, requested_outputs_count {}", num_outs, num_usable_outs, requested_outputs_count); + log::debug(logcat, "Starting gamma picking with {}, num_usable_outs {}, requested_outputs_count {}", num_outs, num_usable_outs, requested_outputs_count); while (num_found < requested_outputs_count) { // if we've gone through every possible output, we've gotten all we can @@ -9445,7 +9445,7 @@ void wallet2::get_outs(std::vector> // outputs, we still need to reach the minimum ring size) if (allow_blackballed_or_blacklisted) break; - oxen::log::info(logcat, "Not enough output not marked as spent, we'll allow outputs marked as spent and outputs with known destinations and amounts"); + log::info(logcat, "Not enough output not marked as spent, we'll allow outputs marked as spent and outputs with known destinations and amounts"); allow_blackballed_or_blacklisted = true; num_usable_outs = num_outs; } @@ -9537,7 +9537,7 @@ void wallet2::get_outs(std::vector> picks[type].insert(i); get_outputs.push_back({amount, i}); ++num_found; - oxen::log::debug(logcat, "picked {}, {} now picked", i, num_found); + log::debug(logcat, "picked {}, {} now picked", i, num_found); } if (OXEN_LOG_ENABLED(debug)) @@ -9547,7 +9547,7 @@ void wallet2::get_outs(std::vector> std::string outputs; for (const auto& out : pick.second) outputs += " " + std::to_string(out); - oxen::log::debug(logcat, "picking {} outputs:{}", pick.first, outputs); + log::debug(logcat, "picking {} outputs:{}", pick.first, outputs); } } @@ -9578,7 +9578,7 @@ void wallet2::get_outs(std::vector> std::string outputs; for (const auto& out : o.second) outputs += " " + std::to_string(out); - oxen::log::debug(logcat, "asking for outputs with amount {}:{}", print_money(o.first), outputs); + log::debug(logcat, "asking for outputs with amount {}:{}", print_money(o.first), outputs); } } } @@ -9680,7 +9680,7 @@ void wallet2::get_outs(std::vector> size_t i = base + o; if (get_outputs[i].index == out) { - oxen::log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {} (from existing ring)", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); + log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {} (from existing ring)", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); tx_add_fake_output(outs, get_outputs[i].index, got_outs[i].key, got_outs[i].mask, td.m_global_output_index, got_outs[i].unlocked); found = true; break; @@ -9701,11 +9701,11 @@ void wallet2::get_outs(std::vector> order[n] = n; std::shuffle(order.begin(), order.end(), crypto::random_device{}); - oxen::log::debug(logcat, "Looking for {} outputs of size {}", (fake_outputs_count+1), print_money(td.is_rct() ? 0 : td.amount())); + log::debug(logcat, "Looking for {} outputs of size {}", (fake_outputs_count+1), print_money(td.is_rct() ? 0 : td.amount())); for (size_t o = 0; o < requested_outputs_count && outs.back().size() < fake_outputs_count + 1; ++o) { size_t i = base + order[o]; - oxen::log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {}", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); + log::debug(logcat, "Index {}/{}: idx {} (real {}), unlocked {}, key {}", i, requested_outputs_count, get_outputs[i].index, td.m_global_output_index, got_outs[i].unlocked, got_outs[i].key); tx_add_fake_output(outs, get_outputs[i].index, got_outs[i].key, got_outs[i].mask, td.m_global_output_index, got_outs[i].unlocked); } if (outs.back().size() < fake_outputs_count + 1) @@ -9744,7 +9744,7 @@ void wallet2::get_outs(std::vector> for (const auto &e: outs[i]) ring.push_back(std::get<0>(e)); if (!set_ring(td.m_key_image, ring, false)) - oxen::log::error(logcat, "Failed to set ring for {}", td.m_key_image); + log::error(logcat, "Failed to set ring for {}", td.m_key_image); } } @@ -9757,8 +9757,8 @@ void wallet2::transfer_selected_rct(std::vector m_multisig_threshold) { @@ -9823,7 +9823,7 @@ void wallet2::transfer_selected_rct(std::vector sources; std::unordered_set used_L; @@ -9904,12 +9904,12 @@ void wallet2::transfer_selected_rct(std::vector splitted_dsts = dsts; @@ -9925,10 +9925,10 @@ void wallet2::transfer_selected_rct(std::vector additional_tx_keys; rct::multisig_out msout; - oxen::log::debug(logcat, "constructing tx"); + log::debug(logcat, "constructing tx"); auto sources_copy = sources; bool r = cryptonote::construct_tx_and_get_tx_key( m_account.get_keys(), @@ -9978,7 +9978,7 @@ void wallet2::transfer_selected_rct(std::vector bool { @@ -10058,7 +10058,7 @@ void wallet2::transfer_selected_rct(std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, uint32_t subaddr_account, const std::set &subaddr_indices) const @@ -10099,7 +10099,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui std::vector picks; float current_output_relatdness = 1.0f; - oxen::log::debug(logcat, "pick_preferred_rct_inputs: needed_money {}", print_money(needed_money)); + log::debug(logcat, "pick_preferred_rct_inputs: needed_money {}", print_money(needed_money)); // try to find a rct input of enough size for (size_t i = 0; i < m_transfers.size(); ++i) @@ -10109,10 +10109,10 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui { if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); + log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } - oxen::log::debug(logcat, "We can use {} alone: {}", i, print_money(td.amount())); + log::debug(logcat, "We can use {} alone: {}", i, print_money(td.amount())); picks.push_back(i); return picks; } @@ -10129,16 +10129,16 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui { if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); + log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } - oxen::log::debug(logcat, "Considering input {}, {}", i, print_money(td.amount())); + log::debug(logcat, "Considering input {}, {}", i, print_money(td.amount())); for (size_t j = i + 1; j < m_transfers.size(); ++j) { const transfer_details& td2 = m_transfers[j]; if (td2.amount() > m_ignore_outputs_above || td2.amount() < m_ignore_outputs_below) { - oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", j, print_money(td2.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); + log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", j, print_money(td2.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } if (!is_spent(td2, false) && !td2.m_frozen && !td.m_key_image_partial && td2.is_rct() && td.amount() + td2.amount() >= needed_money && is_transfer_unlocked(td2) && td2.m_subaddr_index == td.m_subaddr_index) @@ -10147,7 +10147,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui // already found. If the same, don't update, and oldest suitable outputs // will be used in preference. float relatedness = get_output_relatedness(td, td2); - oxen::log::debug(logcat, " with input {}, {}, relatedness {}", j, print_money(td2.amount()), relatedness); + log::debug(logcat, " with input {}, {}, relatedness {}", j, print_money(td2.amount()), relatedness); if (relatedness < current_output_relatdness) { // reset the current picks with those, and return them directly @@ -10156,7 +10156,7 @@ std::vector wallet2::pick_preferred_rct_inputs(uint64_t needed_money, ui picks.clear(); picks.push_back(i); picks.push_back(j); - oxen::log::warning(logcat, "we could use {} and {}", i, j); + log::warning(logcat, "we could use {} and {}", i, j); if (relatedness == 0.0f) return picks; current_output_relatdness = relatedness; @@ -10224,7 +10224,7 @@ static uint32_t get_count_above(const std::vector &tr #ifdef ENABLE_LIGHT_WALLET void wallet2::light_wallet_get_outs(std::vector> &outs, const std::vector &selected_transfers, size_t fake_outputs_count) { - oxen::log::debug(logcat, "LIGHTWALLET - Getting random outs"); + log::debug(logcat, "LIGHTWALLET - Getting random outs"); light_rpc::GET_RANDOM_OUTS::request oreq{}; light_rpc::GET_RANDOM_OUTS::response ores{}; @@ -10248,10 +10248,10 @@ void wallet2::light_wallet_get_outs(std::vector order; @@ -10273,8 +10273,8 @@ void wallet2::light_wallet_get_outs(std::vector(a) < std::get<0>(b); }); // Print output order for(auto added_out: outs.back()) - oxen::log::trace( std::get<0>(added_out)); + log::trace( std::get<0>(added_out)); } } bool wallet2::light_wallet_login(bool &new_address) { - oxen::log::debug(logcat, "Light wallet login request"); + log::debug(logcat, "Light wallet login request"); m_light_wallet_connected = false; light_rpc::LOGIN::request request{}; light_rpc::LOGIN::response response{}; @@ -10338,9 +10338,9 @@ bool wallet2::light_wallet_login(bool &new_address) // MyMonero doesn't send any status message. OpenMonero does. m_light_wallet_connected = connected && (response.status.empty() || response.status == "success"); new_address = response.new_address; - oxen::log::debug(logcat, "Status: {}", response.status); - oxen::log::debug(logcat, "Reason: {}", response.reason); - oxen::log::debug(logcat, "New wallet: {}", response.new_address); + log::debug(logcat, "Status: {}", response.status); + log::debug(logcat, "Reason: {}", response.reason); + log::debug(logcat, "New wallet: {}", response.new_address); if(m_light_wallet_connected) { // Clear old data on successful login. @@ -10353,7 +10353,7 @@ bool wallet2::light_wallet_login(bool &new_address) bool wallet2::light_wallet_import_wallet_request(light_rpc::IMPORT_WALLET_REQUEST::response &response) { - oxen::log::debug(logcat, "Light wallet import wallet request"); + log::debug(logcat, "Light wallet import wallet request"); light_rpc::IMPORT_WALLET_REQUEST::request oreq{}; oreq.address = get_account().get_public_address_str(m_nettype); oreq.view_key = tools::type_to_hex(get_account().get_keys().m_view_secret_key); @@ -10366,7 +10366,7 @@ bool wallet2::light_wallet_import_wallet_request(light_rpc::IMPORT_WALLET_REQUES void wallet2::light_wallet_get_unspent_outs() { - oxen::log::debug(logcat, "Getting unspent outs"); + log::debug(logcat, "Getting unspent outs"); light_rpc::GET_UNSPENT_OUTS::request oreq{}; light_rpc::GET_UNSPENT_OUTS::response ores{}; @@ -10391,7 +10391,7 @@ void wallet2::light_wallet_get_unspent_outs() for(const auto &t: m_transfers) transfers_txs.emplace(t.m_txid,t.m_spent); - oxen::log::debug(logcat, "FOUND {} outputs", ores.outputs.size()); + log::debug(logcat, "FOUND {} outputs", ores.outputs.size()); // return if no outputs found if(ores.outputs.empty()) @@ -10415,11 +10415,11 @@ void wallet2::light_wallet_get_unspent_outs() THROW_WALLET_EXCEPTION_IF(ski.size() != 64 || !oxenc::is_hex(ski), error::wallet_internal_error, "Invalid key image"); tools::hex_to_type(ski, unspent_key_image); if(light_wallet_key_image_is_ours(unspent_key_image, tx_public_key, o.index)){ - oxen::log::trace(logcat, "Output {} is spent. Key image: {}", o.public_key, ski); + log::trace(logcat, "Output {} is spent. Key image: {}", o.public_key, ski); spent = true; break; } { - oxen::log::trace(logcat, "Unspent output found. {}", o.public_key); + log::trace(logcat, "Unspent output found. {}", o.public_key); } } @@ -10496,11 +10496,11 @@ void wallet2::light_wallet_get_unspent_outs() bool valid_commit = (rct_commit == rct::commit(td.amount(), td.m_mask)); if(!valid_commit) { - oxen::log::debug(logcat, "output index: {}", o.global_index); - oxen::log::debug(logcat, "mask: " + tools::type_to_hex(td.m_mask)); - oxen::log::debug(logcat, "calculated commit: " + tools::type_to_hex(rct::commit(td.amount(), td.m_mask))); - oxen::log::debug(logcat, "expected commit: " + tools::type_to_hex(rct_commit)); - oxen::log::debug(logcat, "amount: {}", td.amount()); + log::debug(logcat, "output index: {}", o.global_index); + log::debug(logcat, "mask: " + tools::type_to_hex(td.m_mask)); + log::debug(logcat, "calculated commit: " + tools::type_to_hex(rct::commit(td.amount(), td.m_mask))); + log::debug(logcat, "expected commit: " + tools::type_to_hex(rct_commit)); + log::debug(logcat, "amount: {}", td.amount()); } THROW_WALLET_EXCEPTION_IF(!valid_commit, error::wallet_internal_error, "Lightwallet: rct commit hash mismatch!"); } @@ -10520,7 +10520,7 @@ void wallet2::light_wallet_get_unspent_outs() bool wallet2::light_wallet_get_address_info(light_rpc::GET_ADDRESS_INFO::response &response) { - oxen::log::trace( __FUNCTION__); + log::trace( __FUNCTION__); light_rpc::GET_ADDRESS_INFO::request request{}; @@ -10534,7 +10534,7 @@ bool wallet2::light_wallet_get_address_info(light_rpc::GET_ADDRESS_INFO::respons void wallet2::light_wallet_get_address_txs() { - oxen::log::debug(logcat, "Refreshing light wallet"); + log::debug(logcat, "Refreshing light wallet"); light_rpc::GET_ADDRESS_TXS::request ireq{}; light_rpc::GET_ADDRESS_TXS::response ires{}; @@ -10695,7 +10695,7 @@ void wallet2::light_wallet_get_address_txs() { if(confirmed_tx->second.m_amount_in != amount_sent || confirmed_tx->second.m_amount_out != amount_sent) { - oxen::log::debug(logcat, "Adjusting amount sent/received for tx: <" + t.hash + ">. Is tx sent to own wallet? {} != {}", print_money(amount_sent), print_money(confirmed_tx->second.m_amount_in)); + log::debug(logcat, "Adjusting amount sent/received for tx: <" + t.hash + ">. Is tx sent to own wallet? {} != {}", print_money(amount_sent), print_money(confirmed_tx->second.m_amount_in)); confirmed_tx->second.m_amount_in = amount_sent; confirmed_tx->second.m_amount_out = amount_sent; confirmed_tx->second.m_change = 0; @@ -10902,7 +10902,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) { - oxen::log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); + log::debug(logcat, "Ignoring output {} of amount {} which is outside prescribed range [{}, {}]", i, print_money(td.amount()), print_money(m_ignore_outputs_below), print_money(m_ignore_outputs_above)); continue; } const uint32_t index_minor = td.m_subaddr_index.minor; @@ -11007,7 +11007,7 @@ std::vector wallet2::create_transactions_2(std::vector(); @@ -11031,7 +11031,7 @@ std::vector wallet2::create_transactions_2(std::vector preferred_inputs; { // this is used to build a tx that's 1 or 2 inputs, and 1 or 2 outputs, which will get us a known fee. @@ -11041,7 +11041,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector 0) || adding_fee || !preferred_inputs.empty() || should_pick_a_second_output(txes.back().selected_transfers.size(), *unused_transfers_indices, *unused_dust_indices)) { TX &tx = txes.back(); - oxen::log::debug(logcat, "Start of loop with {} {}, tx.dsts.size() {}", unused_transfers_indices->size(), unused_dust_indices->size(), tx.dsts.size()); - oxen::log::debug(logcat, "unused_transfers_indices: {}", tools::join(" ", *unused_transfers_indices)); - oxen::log::debug(logcat, "unused_dust_indices: {}", tools::join(" ", *unused_dust_indices)); - oxen::log::debug(logcat, "dsts size {}, first {}", dsts.size(), (dsts.empty() ? "-" : cryptonote::print_money(dsts[0].amount))); - oxen::log::debug(logcat, "adding_fee {}", adding_fee); + log::debug(logcat, "Start of loop with {} {}, tx.dsts.size() {}", unused_transfers_indices->size(), unused_dust_indices->size(), tx.dsts.size()); + log::debug(logcat, "unused_transfers_indices: {}", tools::join(" ", *unused_transfers_indices)); + log::debug(logcat, "unused_dust_indices: {}", tools::join(" ", *unused_dust_indices)); + log::debug(logcat, "dsts size {}, first {}", dsts.size(), (dsts.empty() ? "-" : cryptonote::print_money(dsts[0].amount))); + log::debug(logcat, "adding_fee {}", adding_fee); // if we need to spend money and don't have any left, we fail if (unused_dust_indices->empty() && unused_transfers_indices->empty()) { - oxen::log::debug(logcat, "No more outputs to choose from"); + log::debug(logcat, "No more outputs to choose from"); THROW_WALLET_EXCEPTION_IF(1, error::tx_not_possible, unlocked_balance(subaddr_account, false), needed_money, accumulated_fee + needed_fee); } @@ -11116,7 +11116,7 @@ std::vector wallet2::create_transactions_2(std::vector= min_output_value) { if (get_count_above(m_transfers, *unused_transfers_indices, min_output_value) < min_output_count) { - oxen::log::debug(logcat, "Second output was not strictly needed, and we're running out of outputs above {}, not adding", print_money(min_output_value)); + log::debug(logcat, "Second output was not strictly needed, and we're running out of outputs above {}, not adding", print_money(min_output_value)); break; } } @@ -11126,7 +11126,7 @@ std::vector wallet2::create_transactions_2(std::vector SECOND_OUTPUT_RELATEDNESS_THRESHOLD) { - oxen::log::debug(logcat, "Second output was not strictly needed, and relatedness {}, not adding", relatedness); + log::debug(logcat, "Second output was not strictly needed, and relatedness {}, not adding", relatedness); break; } pop_if_present(*unused_transfers_indices, idx); @@ -11135,7 +11135,7 @@ std::vector wallet2::create_transactions_2(std::vectorempty() ? *unused_dust_indices : *unused_transfers_indices, tx.selected_transfers); const transfer_details &td = m_transfers[idx]; - oxen::log::debug(logcat, "Picking output {}, amount {}, ki {}", idx, print_money(td.amount()), td.m_key_image); + log::debug(logcat, "Picking output {}, amount {}, ki {}", idx, print_money(td.amount()), td.m_key_image); // add this output to the list to spend tx.selected_transfers.push_back(idx); @@ -11146,7 +11146,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector 0 && !dsts.empty() && estimate_tx_weight(tx.selected_transfers.size(), fake_outs_count, tx.dsts.size()+1, extra.size(), clsag) < tx_weight_target(upper_transaction_weight_limit)) { // we can partially fill that destination - oxen::log::debug(logcat, "We can partially pay {} for {}/{}", get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr), print_money(available_amount), print_money(dsts[0].amount)); + log::debug(logcat, "We can partially pay {} for {}/{}", get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr), print_money(available_amount), print_money(dsts[0].amount)); tx.add(dsts[0], available_amount, original_output_index, m_merge_destinations); dsts[0].amount -= available_amount; available_amount = 0; @@ -11172,7 +11172,7 @@ std::vector wallet2::create_transactions_2(std::vector wallet2::create_transactions_2(std::vector available_for_fee && !dsts.empty() && dsts[0].amount > 0) { @@ -11226,7 +11226,7 @@ std::vector wallet2::create_transactions_2(std::vectoramount > needed_fee) { uint64_t new_paid_amount = i->amount /*+ test_ptx.fee*/ - needed_fee; - oxen::log::debug(logcat, "Adjusting amount paid to {} from {} to {} to accomodate {} fee", get_account_address_as_str(m_nettype, i->is_subaddress, i->addr), print_money(i->amount), print_money(new_paid_amount), print_money(needed_fee)); + log::debug(logcat, "Adjusting amount paid to {} from {} to {} to accomodate {} fee", get_account_address_as_str(m_nettype, i->is_subaddress, i->addr), print_money(i->amount), print_money(new_paid_amount), print_money(needed_fee)); dsts[0].amount += i->amount - new_paid_amount; i->amount = new_paid_amount; test_ptx.fee = needed_fee; @@ -11236,22 +11236,22 @@ std::vector wallet2::create_transactions_2(std::vector available_for_fee) { - oxen::log::debug(logcat, "We could not make a tx, switching to fee accumulation"); + log::debug(logcat, "We could not make a tx, switching to fee accumulation"); adding_fee = true; } else { - oxen::log::debug(logcat, "We made a tx, adjusting fee and saving it, we need {} and we have {}", print_money(needed_fee), print_money(test_ptx.fee)); + log::debug(logcat, "We made a tx, adjusting fee and saving it, we need {} and we have {}", print_money(needed_fee), print_money(test_ptx.fee)); while (needed_fee > test_ptx.fee) { transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx, rct_config, tx_params); txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(test_ptx.tx, txBlob.size(), base_fee, fee_percent, fixed_fee, fee_quantization_mask); - oxen::log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); + log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); } - oxen::log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); + log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); tx.tx = test_tx; tx.ptx = test_ptx; @@ -11263,7 +11263,7 @@ std::vector wallet2::create_transactions_2(std::vector &ptx_vector, std::vector dsts) const { - oxen::log::debug(logcat, "sanity_check: {} txes, {} destinations", ptx_vector.size(), dsts.size()); + log::debug(logcat, "sanity_check: {} txes, {} destinations", ptx_vector.size(), dsts.size()); hw::device &hwdev = m_account.get_device(); @@ -11367,7 +11367,7 @@ bool wallet2::sanity_check(const std::vector &ptx_vector, s } for (const auto &r: required) change -= r.second.first; - oxen::log::debug(logcat, "Adding {} expected change", cryptonote::print_money(change)); + log::debug(logcat, "Adding {} expected change", cryptonote::print_money(change)); // for all txes that have actual change, check change is coming back to the sending wallet for (const pending_tx &ptx: ptx_vector) @@ -11401,7 +11401,7 @@ bool wallet2::sanity_check(const std::vector &ptx_vector, s std::stringstream ss; ss << "Total received by " << cryptonote::get_account_address_as_str(m_nettype, r.second.second, address) << ": " << cryptonote::print_money(total_received) << ", expected " << cryptonote::print_money(r.second.first); - oxen::log::debug(logcat, ss.str()); + log::debug(logcat, ss.str()); THROW_WALLET_EXCEPTION_IF(total_received < r.second.first, error::wallet_internal_error, ss.str()); } @@ -11449,7 +11449,7 @@ std::vector wallet2::create_transactions_all(uint64_t below std::advance(i, crypto::rand_idx(unused_transfer_dust_indices_per_subaddr.size())); unused_transfers_indices = i->second.first; unused_dust_indices = i->second.second; - oxen::log::debug(logcat, "Spending from subaddress index {}", i->first); + log::debug(logcat, "Spending from subaddress index {}", i->first); } else { @@ -11457,7 +11457,7 @@ std::vector wallet2::create_transactions_all(uint64_t below { unused_transfers_indices.insert(unused_transfers_indices.end(), p.second.first.begin(), p.second.first.end()); unused_dust_indices.insert(unused_dust_indices.end(), p.second.second.begin(), p.second.second.end()); - oxen::log::debug(logcat, "Spending from subaddress index {}", p.first); + log::debug(logcat, "Spending from subaddress index {}", p.first); } } @@ -11537,7 +11537,7 @@ std::vector wallet2::create_transactions_from(const crypton THROW_WALLET_EXCEPTION_IF(burn_percent > fee_percent, error::wallet_internal_error, "invalid burn fees: cannot burn more than the tx fee"); } - oxen::log::debug(logcat, "Starting with {} non-dust outputs and {} dust outputs", unused_transfers_indices.size(), unused_dust_indices.size()); + log::debug(logcat, "Starting with {} non-dust outputs and {} dust outputs", unused_transfers_indices.size(), unused_dust_indices.size()); if (unused_dust_indices.empty() && unused_transfers_indices.empty()) return std::vector(); @@ -11573,7 +11573,7 @@ std::vector wallet2::create_transactions_from(const crypton : pop_best_value(unused_transfers_indices, tx.selected_transfers); const transfer_details &td = m_transfers[idx]; - oxen::log::debug(logcat, "Picking output {}, amount {}", idx, print_money(td.amount())); + log::debug(logcat, "Picking output {}, amount {}", idx, print_money(td.amount())); // add this output to the list to spend tx.selected_transfers.push_back(idx); @@ -11584,7 +11584,7 @@ std::vector wallet2::create_transactions_from(const crypton outs.clear(); // here, check if we need to sent tx and start a new one - oxen::log::debug(logcat, "Considering whether to create a tx now, {} inputs, tx limit {}", tx.selected_transfers.size(), upper_transaction_weight_limit); + log::debug(logcat, "Considering whether to create a tx now, {} inputs, tx limit {}", tx.selected_transfers.size(), upper_transaction_weight_limit); const size_t estimated_rct_tx_weight = estimate_tx_weight(tx.selected_transfers.size(), fake_outs_count, tx.dsts.size() + 2, extra.size(), clsag); bool try_tx = (unused_dust_indices.empty() && unused_transfers_indices.empty()) || ( estimated_rct_tx_weight >= tx_weight_target(upper_transaction_weight_limit)); @@ -11599,7 +11599,7 @@ std::vector wallet2::create_transactions_from(const crypton for (size_t i = 0; i < ((outputs > 1) ? outputs - 1 : outputs); ++i) tx.dsts.push_back(tx_destination_entry(1, address, is_subaddress)); - oxen::log::debug(logcat, "Trying to create a tx now, with {} destinations and {} outputs", tx.dsts.size(), tx.selected_transfers.size()); + log::debug(logcat, "Trying to create a tx now, with {} destinations and {} outputs", tx.dsts.size(), tx.selected_transfers.size()); transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx, rct_config, oxen_tx_params); auto txBlob = t_serializable_object_to_blob(test_ptx.tx); @@ -11607,7 +11607,7 @@ std::vector wallet2::create_transactions_from(const crypton available_for_fee = test_ptx.fee + test_ptx.change_dts.amount; for (auto &dt: test_ptx.dests) available_for_fee += dt.amount; - oxen::log::debug(logcat, "Made a {} tx, with {} available for fee ({} needed)", get_weight_string(test_ptx.tx, txBlob.size()), print_money(available_for_fee), print_money(needed_fee)); + log::debug(logcat, "Made a {} tx, with {} available for fee ({} needed)", get_weight_string(test_ptx.tx, txBlob.size()), print_money(available_for_fee), print_money(needed_fee)); // add last output, missed for fee estimation if (outputs > 1) @@ -11616,7 +11616,7 @@ std::vector wallet2::create_transactions_from(const crypton THROW_WALLET_EXCEPTION_IF(needed_fee > available_for_fee, error::wallet_internal_error, "Transaction cannot pay for itself"); do { - oxen::log::debug(logcat, "We made a tx, adjusting fee and saving it"); + log::debug(logcat, "We made a tx, adjusting fee and saving it"); // distribute total transferred amount between outputs uint64_t amount_transferred = available_for_fee - needed_fee; uint64_t dt_amount = amount_transferred / outputs; @@ -11636,10 +11636,10 @@ std::vector wallet2::create_transactions_from(const crypton test_tx, test_ptx, rct_config, oxen_tx_params); txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(test_ptx.tx, txBlob.size(), base_fee, fee_percent, fixed_fee, fee_quantization_mask); - oxen::log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); + log::debug(logcat, "Made an attempt at a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); } while (needed_fee > test_ptx.fee); - oxen::log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); + log::debug(logcat, "Made a final {} tx, with {} fee and {} change", get_weight_string(test_ptx.tx, txBlob.size()), print_money(test_ptx.fee), print_money(test_ptx.change_dts.amount)); tx.tx = test_tx; tx.ptx = test_ptx; @@ -11650,13 +11650,13 @@ std::vector wallet2::create_transactions_from(const crypton accumulated_change += test_ptx.change_dts.amount; if (!unused_transfers_indices.empty() || !unused_dust_indices.empty()) { - oxen::log::debug(logcat, "We have more to pay, starting another tx"); + log::debug(logcat, "We have more to pay, starting another tx"); txes.push_back(TX()); } } } - oxen::log::info(logcat, "Done creating {} transactions, {} total fee, {} total change", txes.size(), print_money(accumulated_fee), print_money(accumulated_change)); + log::info(logcat, "Done creating {} transactions, {} total fee, {} total change", txes.size(), print_money(accumulated_fee), print_money(accumulated_change)); hwdev.set_mode(hw::device::mode::TRANSACTION_CREATE_REAL); for (auto &tx : txes) @@ -11683,7 +11683,7 @@ std::vector wallet2::create_transactions_from(const crypton uint64_t tx_money = 0; for (size_t idx: tx.selected_transfers) tx_money += m_transfers[idx].amount(); - oxen::log::info(logcat, " Transaction {}/{} {}: {}, sending {} in {} outputs to {} destinations(s), including {} fee, {} change", (1+std::distance(txes.begin(), i)), txes.size(), get_transaction_hash(tx.ptx.tx), get_weight_string(tx.weight), print_money(tx_money), tx.selected_transfers.size(), tx.dsts.size(), print_money(tx.ptx.fee), print_money(tx.ptx.change_dts.amount)); + log::info(logcat, " Transaction {}/{} {}: {}, sending {} in {} outputs to {} destinations(s), including {} fee, {} change", (1+std::distance(txes.begin(), i)), txes.size(), get_transaction_hash(tx.ptx.tx), get_weight_string(tx.weight), print_money(tx_money), tx.selected_transfers.size(), tx.dsts.size(), print_money(tx.ptx.fee), print_money(tx.ptx.change_dts.amount)); ptx_vector.push_back(tx.ptx); } @@ -11741,8 +11741,8 @@ void wallet2::cold_sign_tx(const std::vector& ptx_vector, signed_tx_ dev_cold->tx_sign(&wallet_shim, txs, exported_txs, aux_data); tx_device_aux = aux_data.tx_device_aux; - oxen::log::debug(logcat, "Signed tx data from hw: {} transactions", exported_txs.ptx.size()); - for (auto &c_ptx: exported_txs.ptx) oxen::log::warning(logcat, cryptonote::obj_to_json_str(c_ptx.tx)); + log::debug(logcat, "Signed tx data from hw: {} transactions", exported_txs.ptx.size()); + for (auto &c_ptx: exported_txs.ptx) log::warning(logcat, cryptonote::obj_to_json_str(c_ptx.tx)); } //---------------------------------------------------------------------------------------------------- uint64_t wallet2::cold_key_image_sync(uint64_t &spent, uint64_t &unspent) { @@ -11800,9 +11800,9 @@ bool wallet2::use_fork_rules(hf version, uint64_t early_blocks) const close_enough = true; if (close_enough) - oxen::log::debug(logcat, "Using v{} rules", (unsigned)version); + log::debug(logcat, "Using v{} rules", (unsigned)version); else - oxen::log::debug(logcat, "Not using v{} rules", (unsigned)version); + log::debug(logcat, "Not using v{} rules", (unsigned)version); return close_enough; } //---------------------------------------------------------------------------------------------------- @@ -11979,7 +11979,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s bool r = get_tx_key_cached(txid, tx_key, additional_tx_keys); if (r) { - oxen::log::debug(logcat, "tx key cached for txid: {}", txid); + log::debug(logcat, "tx key cached for txid: {}", txid); return true; } @@ -11994,7 +11994,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s const auto tx_data_it = m_tx_device.find(txid); if (tx_data_it == m_tx_device.end()) { - oxen::log::debug(logcat, "Aux data not found for txid: {}", txid); + log::debug(logcat, "Aux data not found for txid: {}", txid); return false; } @@ -12002,7 +12002,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); if (!dev_cold->is_get_tx_key_supported()) { - oxen::log::debug(logcat, "get_tx_key not supported by the device"); + log::debug(logcat, "get_tx_key not supported by the device"); return false; } @@ -12037,7 +12037,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s dev_cold->get_tx_key(tx_keys, tx_key_data, m_account.get_keys().m_view_secret_key); if (tx_keys.empty()) { - oxen::log::debug(logcat, "Empty tx keys for txid: {}", txid); + log::debug(logcat, "Empty tx keys for txid: {}", txid); return false; } @@ -12966,7 +12966,7 @@ uint64_t wallet2::get_approximate_blockchain_height() const uint64_t approx_blockchain_height = netconf.HEIGHT_ESTIMATE_HEIGHT + (since_ts > 0 ? (uint64_t)since_ts / tools::to_seconds(TARGET_BLOCK_TIME) : 0) - BLOCKS_PER_DAY * 7; // subtract a week's worth of blocks to be conservative - oxen::log::debug(logcat, "Calculated blockchain height: {}", approx_blockchain_height); + log::debug(logcat, "Calculated blockchain height: {}", approx_blockchain_height); return approx_blockchain_height; } @@ -13101,7 +13101,7 @@ void wallet2::set_account_tag(const std::set &account_indices, const s { THROW_WALLET_EXCEPTION_IF(account_index >= get_num_subaddress_accounts(), error::wallet_internal_error, "Account index out of bound"); if (m_account_tags.second[account_index] == tag) - oxen::log::debug(logcat, "This tag is already assigned to this account"); + log::debug(logcat, "This tag is already assigned to this account"); else m_account_tags.second[account_index] = tag; } @@ -13144,19 +13144,19 @@ std::string wallet2::sign(std::string_view data, cryptonote::subaddress_index in bool wallet2::verify(std::string_view data, const cryptonote::account_public_address &address, std::string_view signature) { if (!tools::starts_with(signature, SIG_MAGIC)) { - oxen::log::warning(logcat, "Signature header check error"); + log::warning(logcat, "Signature header check error"); return false; } crypto::hash hash; crypto::cn_fast_hash(data.data(), data.size(), hash); std::string decoded; if (!tools::base58::decode(signature.substr(SIG_MAGIC.size()), decoded)) { - oxen::log::warning(logcat, "Signature decoding error"); + log::warning(logcat, "Signature decoding error"); return false; } crypto::signature s; if (sizeof(s) != decoded.size()) { - oxen::log::warning(logcat, "Signature decoding error"); + log::warning(logcat, "Signature decoding error"); return false; } memcpy(&s, decoded.data(), sizeof(s)); @@ -13180,19 +13180,19 @@ std::string wallet2::sign_multisig_participant(std::string_view data) const bool wallet2::verify_with_public_key(std::string_view data, const crypto::public_key &public_key, std::string_view signature) const { if (!tools::starts_with(signature, MULTISIG_SIGNATURE_MAGIC)) { - oxen::log::error(logcat, "Signature header check error"); + log::error(logcat, "Signature header check error"); return false; } crypto::hash hash; crypto::cn_fast_hash(data.data(), data.size(), hash); std::string decoded; if (!tools::base58::decode(signature.substr(MULTISIG_SIGNATURE_MAGIC.size()), decoded)) { - oxen::log::error(logcat, "Signature decoding error"); + log::error(logcat, "Signature decoding error"); return false; } crypto::signature s; if (sizeof(s) != decoded.size()) { - oxen::log::error(logcat, "Signature decoding error"); + log::error(logcat, "Signature decoding error"); return false; } memcpy(&s, decoded.data(), sizeof(s)); @@ -13526,7 +13526,7 @@ uint64_t wallet2::import_key_images(const std::vectorsecond, e["block_height"]); if (m_callback) m_callback->on_money_spent(e["block_height"], *spent_txid, spent_tx, amount, spent_tx, td.m_subaddr_index); if (subaddr_account != (uint32_t)-1 && subaddr_account != td.m_subaddr_index.major) - oxen::log::warning(logcat, "WARNING: This tx spends outputs received by different subaddress accounts, which isn't supposed to happen"); + log::warning(logcat, "WARNING: This tx spends outputs received by different subaddress accounts, which isn't supposed to happen"); subaddr_account = td.m_subaddr_index.major; subaddr_indices.insert(td.m_subaddr_index.minor); } @@ -13668,7 +13668,7 @@ bool wallet2::import_key_images(std::vector key_images, size_ { if (key_images.size() + offset > m_transfers.size()) { - oxen::log::info(logcat, "More key images returned that we know outputs for"); + log::info(logcat, "More key images returned that we know outputs for"); return false; } for (size_t ki_idx = 0; ki_idx < key_images.size(); ++ki_idx) @@ -13679,7 +13679,7 @@ bool wallet2::import_key_images(std::vector key_images, size_ transfer_details &td = m_transfers[transfer_idx]; if (td.m_key_image_known && !td.m_key_image_partial && td.m_key_image != key_images[ki_idx]) - oxen::log::warning(logcat, "WARNING: imported key image differs from previously known key image at index {}: trusting imported one", ki_idx); + log::warning(logcat, "WARNING: imported key image differs from previously known key image at index {}: trusting imported one", ki_idx); td.m_key_image = key_images[ki_idx]; m_key_images[td.m_key_image] = transfer_idx; td.m_key_image_known = true; @@ -14093,7 +14093,7 @@ void wallet2::update_multisig_rescan_info(const std::vector= m_transfers.size(), "Mismatched sizes of multisig_k and info"); - oxen::log::debug(logcat, "update_multisig_rescan_info: updating index {}", n); + log::debug(logcat, "update_multisig_rescan_info: updating index {}", n); transfer_details &td = m_transfers[n]; td.m_multisig_info.clear(); for (const auto &pi: info) @@ -14134,12 +14134,12 @@ size_t wallet2::import_multisig(std::vector blobs) error::wallet_internal_error, "Multisig info is for a different account"); if (get_multisig_signer_public_key() == signer) { - oxen::log::info(logcat, "Multisig info from this wallet ignored"); + log::info(logcat, "Multisig info from this wallet ignored"); continue; } if (seen.find(signer) != seen.end()) { - oxen::log::info(logcat, "Duplicate multisig info ignored"); + log::info(logcat, "Duplicate multisig info ignored"); continue; } seen.insert(signer); @@ -14151,7 +14151,7 @@ size_t wallet2::import_multisig(std::vector blobs) std::vector i; boost::archive::portable_binary_iarchive ar(iss); ar >> i; - oxen::log::info(logcat, "{} outputs found", i.size()); + log::info(logcat, "{} outputs found", i.size()); info.push_back(std::move(i)); } @@ -14200,7 +14200,7 @@ size_t wallet2::import_multisig(std::vector blobs) const transfer_details &td = m_transfers[n]; if (!td.m_key_image_partial) continue; - oxen::log::info(logcat, "Multisig info importing from block height {}", td.m_block_height); + log::info(logcat, "Multisig info importing from block height {}", td.m_block_height); detach_blockchain(td.m_block_height); break; } diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 8430078cc..1720fed61 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -1330,12 +1330,12 @@ private: if (throw_on_error) throw; else - oxen::log::error(oxen::log::Cat("wallet.wallet2"), "HTTP request failed: {}", e.what()); + log::error(log::Cat("wallet.wallet2"), "HTTP request failed: {}", e.what()); } catch (...) { if (throw_on_error) throw; else - oxen::log::error(oxen::log::Cat("wallet.wallet2"), "HTTP request failed: unknown error"); + log::error(log::Cat("wallet.wallet2"), "HTTP request failed: unknown error"); } return false; } diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index 82bd25c47..bb17eaf68 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -50,9 +50,14 @@ #define DEFAULT_MAX_CONCURRENCY 0 #endif +namespace wallet_args +{ + + namespace log = oxen::log; + namespace { - static auto logcat = oxen::log::Cat("wallet.wallet2"); + static auto logcat = log::Cat("wallet.wallet2"); class Print { @@ -66,8 +71,6 @@ namespace }; } -namespace wallet_args -{ // Create on-demand to prevent static initialization order fiasco issues. command_line::arg_descriptor arg_generate_from_json() { @@ -168,7 +171,7 @@ namespace wallet_args } else { - oxen::log::error(logcat, "{}{}", wallet_args::tr("Can't find config file "), config); + log::error(logcat, "{}{}", wallet_args::tr("Can't find config file "), config); return false; } } @@ -187,7 +190,7 @@ namespace wallet_args log_path = command_line::get_arg(vm, arg_log_file); else log_path = epee::string_tools::get_current_module_name() + ".log"; - oxen::log::Level log_level; + log::Level log_level; if (auto level = oxen::logging::parse_level(command_line::get_arg(vm, arg_log_level).c_str())) { log_level = *level; } else { @@ -206,13 +209,13 @@ namespace wallet_args Print(print) << "Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")"; if (!command_line::is_arg_defaulted(vm, arg_log_level)) - oxen::log::info(logcat, "Setting log level = {}", command_line::get_arg(vm, arg_log_level)); + log::info(logcat, "Setting log level = {}", command_line::get_arg(vm, arg_log_level)); else { const char *logs = getenv("OXEN_LOGS"); - oxen::log::info(logcat, "Setting log levels = {}", (logs ? logs : "")); + log::info(logcat, "Setting log levels = {}", (logs ? logs : "")); } - //oxen::log::info(logcat, "{}{}", wallet_args::tr("Logging to: "), log_path); + //log::info(logcat, "{}{}", wallet_args::tr("Logging to: "), log_path); //Print(print) << boost::format(wallet_args::tr("Logging to %s")) % log_path; diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 3d667b8fd..47f4ff5da 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -61,9 +61,12 @@ namespace rpc = cryptonote::rpc; using namespace tools::wallet_rpc; +namespace tools +{ + namespace { - static auto logcat = oxen::log::Cat("wallet.rpc"); + auto logcat = log::Cat("wallet.rpc"); constexpr auto DEFAULT_AUTO_REFRESH_PERIOD = 20s; @@ -80,7 +83,7 @@ namespace auto pwd_container = tools::password_container::prompt(verify, prompt); if (!pwd_container) { - oxen::log::error(logcat, "failed to read wallet password"); + log::error(logcat, "failed to read wallet password"); } return pwd_container; } @@ -168,8 +171,6 @@ namespace } // anon namespace -namespace tools -{ const char* wallet_rpc_server::tr(const char* str) { return i18n_translate(str, "tools::wallet_rpc_server"); @@ -196,7 +197,7 @@ namespace tools http.any("/*", [this](HttpResponse* res, HttpRequest* req) { if (m_login && !check_auth(*req, *res)) return; - oxen::log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); + log::info(logcat, "Invalid HTTP request for {} {}", req->getMethod(), req->getUrl()); error_response(*res, HTTP_NOT_FOUND); }); } @@ -231,23 +232,23 @@ namespace tools std::string method; if(!ps.get_value("method", method, nullptr)) { - oxen::log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", get_remote_address(res)); + log::info(logcat, "Invalid JSON RPC request from {}: no 'method' in request", get_remote_address(res)); return jsonrpc_error_response(res, -32600, "Invalid Request", id); } auto it = rpc_commands.find(method); if (it == rpc_commands.end()) { - oxen::log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", get_remote_address(res), method); + log::info(logcat, "Invalid JSON RPC request from {}: method '{}' is invalid", get_remote_address(res), method); return jsonrpc_error_response(res, -32601, "Method not found", id); } - oxen::log::debug(logcat, "Incoming JSON RPC request for {} from {}", method, get_remote_address(res)); + log::debug(logcat, "Incoming JSON RPC request for {} from {}", method, get_remote_address(res)); const auto& [restricted, invoke_ptr] = it->second; // If it's a restricted command and we're in restricted mode then deny it if (restricted && m_restricted) { - oxen::log::warning(logcat, "JSON RPC request for restricted command {} in restricted mode from {}", method, get_remote_address(res)); + log::warning(logcat, "JSON RPC request for restricted command {} in restricted mode from {}", method, get_remote_address(res)); return jsonrpc_error_response(res, error_code::DENIED, method + " is not available in restricted mode.", {}); } @@ -400,7 +401,7 @@ namespace tools try { if (m_wallet) m_wallet->refresh(m_wallet->is_trusted_daemon()); } catch (const std::exception& ex) { - oxen::log::error(logcat, "Exception while refreshing: {}", ex.what()); + log::error(logcat, "Exception while refreshing: {}", ex.what()); } m_last_auto_refresh_time = std::chrono::steady_clock::now(); @@ -411,8 +412,8 @@ namespace tools std::this_thread::sleep_for(250ms); } - oxen::log::info(logcat, "Stopping wallet rpc server"); - oxen::log::info(logcat, "Shutting down listening HTTP RPC sockets"); + log::info(logcat, "Stopping wallet rpc server"); + log::info(logcat, "Shutting down listening HTTP RPC sockets"); // Stopped: close the sockets, cancel the long poll, and rejoin the threads for (auto* s : m_listen_socks) us_listen_socket_close(/*ssl=*/false, s); @@ -420,23 +421,23 @@ namespace tools stop_long_poll_thread(); - oxen::log::debug(logcat, "Joining uws thread"); + log::debug(logcat, "Joining uws thread"); uws_thread.join(); - oxen::log::info(logcat, "Storing wallet..."); + log::info(logcat, "Storing wallet..."); if (m_wallet) m_wallet->store(); - oxen::log::info(logcat, "Wallet stopped."); + log::info(logcat, "Wallet stopped."); } void wallet_rpc_server::start_long_poll_thread() { assert(m_wallet); if (m_long_poll_thread.joinable() || m_long_poll_disabled) { - oxen::log::debug(logcat, "Not starting long poll thread: {}", (m_long_poll_thread.joinable() ? "already running" : "long polling disabled")); + log::debug(logcat, "Not starting long poll thread: {}", (m_long_poll_thread.joinable() ? "already running" : "long polling disabled")); return; } - oxen::log::info(logcat, "Starting long poll thread"); + log::info(logcat, "Starting long poll thread"); m_long_poll_thread = std::thread{[this] { for (;;) { @@ -464,10 +465,10 @@ namespace tools assert(m_wallet); if (!m_long_poll_thread.joinable()) { - oxen::log::debug(logcat, "Not stopping long poll thread: not running"); + log::debug(logcat, "Not stopping long poll thread: not running"); return; } - oxen::log::info(logcat, "Stopping long poll thread"); + log::info(logcat, "Stopping long poll thread"); m_wallet->cancel_long_poll(); // Store this to revert it afterwards to its original state bool disabled_state = m_long_poll_disabled; @@ -482,14 +483,14 @@ namespace tools try { rpc_config = cryptonote::rpc_args::process(m_vm); } catch (const std::exception& e) { - oxen::log::error(logcat, "Failed to process rpc arguments: {}", e.what()); + log::error(logcat, "Failed to process rpc arguments: {}", e.what()); return false; } const uint16_t port = command_line::get_arg(m_vm, arg_rpc_bind_port); if (!port) { - oxen::log::error(logcat, "Invalid port {} specified", port); + log::error(logcat, "Invalid port {} specified", port); return false; } @@ -510,7 +511,7 @@ namespace tools { if (!command_line::is_arg_defaulted(m_vm, wallet_args::arg_wallet_file())) { - oxen::log::error(logcat, "{} and {} are incompatible, use only one of them", arg_wallet_dir.name, wallet_args::arg_wallet_file().name); + log::error(logcat, "{} and {} are incompatible, use only one of them", arg_wallet_dir.name, wallet_args::arg_wallet_file().name); return false; } m_wallet_dir = fs::u8path(command_line::get_arg(m_vm, arg_wallet_dir)); @@ -521,7 +522,7 @@ namespace tools fs::permissions(m_wallet_dir, fs::perms::owner_all, ec); else if (ec) { - oxen::log::error(logcat, "{}{}: {}", tr("Failed to create directory "), m_wallet_dir, ec.message()); + log::error(logcat, "{}{}: {}", tr("Failed to create directory "), m_wallet_dir, ec.message()); return false; } } @@ -532,7 +533,7 @@ namespace tools if (rpc_config.login) { const cryptonote::rpc_args::descriptors arg{}; - oxen::log::error(logcat, "{}{}{}{}", tr("Cannot specify --"), arg_disable_rpc_login.name, tr(" and --"), arg.rpc_login.name); + log::error(logcat, "{}{}{}{}", tr("Cannot specify --"), arg_disable_rpc_login.name, tr(" and --"), arg.rpc_login.name); return false; } m_login = std::nullopt; @@ -552,7 +553,7 @@ namespace tools rpc_login_file = tools::private_file::create(temp); if (!rpc_login_file.handle()) { - oxen::log::error(logcat, "{}{}{}", tr("Failed to create file "), temp, tr(". Check permissions or remove file")); + log::error(logcat, "{}{}{}", tr("Failed to create file "), temp, tr(". Check permissions or remove file")); return false; } std::fputs(m_login->username.c_str(), rpc_login_file.handle()); @@ -563,10 +564,10 @@ namespace tools std::fflush(rpc_login_file.handle()); if (std::ferror(rpc_login_file.handle())) { - oxen::log::error(logcat, "{}{}", tr("Error writing to file "), temp); + log::error(logcat, "{}{}", tr("Error writing to file "), temp); return false; } - oxen::log::warning(logcat, "{}{}", tr("RPC username/password is stored in file "), temp); + log::warning(logcat, "{}{}", tr("RPC username/password is stored in file "), temp); } else // chosen user/pass { @@ -590,17 +591,17 @@ namespace tools { if (m_wallet) { - oxen::log::debug(logcat, tools::wallet_rpc_server::tr("Closing wallet...")); + log::debug(logcat, tools::wallet_rpc_server::tr("Closing wallet...")); stop_long_poll_thread(); if (save_current) { - oxen::log::debug(logcat, tools::wallet_rpc_server::tr("Saving wallet...")); + log::debug(logcat, tools::wallet_rpc_server::tr("Saving wallet...")); m_wallet->store(); - oxen::log::info(logcat, tools::wallet_rpc_server::tr("Wallet saved")); + log::info(logcat, tools::wallet_rpc_server::tr("Wallet saved")); } m_wallet->deinit(); m_wallet.reset(); - oxen::log::info(logcat, tools::wallet_rpc_server::tr("Wallet closed")); + log::info(logcat, tools::wallet_rpc_server::tr("Wallet closed")); } } //------------------------------------------------------------------------------------------------------------------------------ @@ -926,8 +927,11 @@ namespace tools if (!payment_id.empty()) throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead"}; } + + namespace { + //------------------------------------------------------------------------------------------------------------------------------ - static std::string ptx_to_string(const wallet::pending_tx &ptx) + std::string ptx_to_string(const wallet::pending_tx &ptx) { std::ostringstream oss; boost::archive::portable_binary_oarchive ar(oss); @@ -943,14 +947,14 @@ namespace tools } //------------------------------------------------------------------------------------------------------------------------------ template - static bool is_empty_string(const T &val) { + bool is_empty_string(const T &val) { if constexpr (std::is_same_v) return val.empty(); return false; } //------------------------------------------------------------------------------------------------------------------------------ template - static bool fill(T& where, V&& s) + bool fill(T& where, V&& s) { if (is_empty_string(s)) return false; where = std::forward(s); @@ -958,35 +962,37 @@ namespace tools } //------------------------------------------------------------------------------------------------------------------------------ template - static bool fill(std::list& where, V&& s) + bool fill(std::list& where, V&& s) { if (is_empty_string(s)) return false; where.push_back(std::forward(s)); return true; } //------------------------------------------------------------------------------------------------------------------------------ - static uint64_t total_amount(const wallet::pending_tx &ptx) + uint64_t total_amount(const wallet::pending_tx &ptx) { uint64_t amount = 0; for (const auto &dest: ptx.dests) amount += dest.amount; return amount; } - static void append_hex_tx_keys(std::string& to, const crypto::secret_key& k, const std::vector& more) { + void append_hex_tx_keys(std::string& to, const crypto::secret_key& k, const std::vector& more) { to.reserve(to.size() + oxenc::to_hex_size(sizeof(k.data) * (1 + more.size()))); oxenc::to_hex(std::begin(k.data), std::end(k.data), std::back_inserter(to)); for (const auto& key : more) oxenc::to_hex(std::begin(key.data), std::end(key.data), std::back_inserter(to)); } - static std::string hex_tx_keys(const crypto::secret_key& k, const std::vector& more) { + std::string hex_tx_keys(const crypto::secret_key& k, const std::vector& more) { std::string s; append_hex_tx_keys(s, k, more); return s; } - static std::string hex_tx_keys(const wallet::pending_tx& ptx) { + std::string hex_tx_keys(const wallet::pending_tx& ptx) { return hex_tx_keys(ptx.tx_key, ptx.additional_tx_keys); } + } // anonymous namespace + //------------------------------------------------------------------------------------------------------------------------------ template void wallet_rpc_server::fill_response(std::vector &ptx_vector, @@ -1040,7 +1046,7 @@ namespace tools std::vector dsts; std::vector extra; - oxen::log::trace(logcat, "on_transfer starts"); + log::trace(logcat, "on_transfer starts"); require_open(); // validate the transfer requested and populate dsts & extra @@ -1087,9 +1093,9 @@ namespace tools throw wallet_rpc_error{error_code::HF_QUERY_FAILED, tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED}; cryptonote::oxen_construct_tx_params tx_params = tools::wallet2::construct_params(*hf_version, cryptonote::txtype::standard, priority); - oxen::log::debug(logcat, "on_transfer_split calling create_transactions_2"); + log::debug(logcat, "on_transfer_split calling create_transactions_2"); std::vector ptx_vector = m_wallet->create_transactions_2(dsts, cryptonote::TX_OUTPUT_DECOYS, req.unlock_time, priority, extra, req.account_index, req.subaddr_indices, tx_params); - oxen::log::debug(logcat, "on_transfer_split called create_transactions_2"); + log::debug(logcat, "on_transfer_split called create_transactions_2"); if (ptx_vector.empty()) throw wallet_rpc_error{error_code::TX_NOT_POSSIBLE, "No transaction created"}; @@ -2310,7 +2316,7 @@ namespace tools AUTO_REFRESH::response wallet_rpc_server::invoke(AUTO_REFRESH::request&& req) { m_auto_refresh_period = req.enable ? req.period ? std::chrono::seconds{req.period} : DEFAULT_AUTO_REFRESH_PERIOD : 0s; - oxen::log::info(logcat, "Auto refresh now {}", (m_auto_refresh_period != 0s ? std::to_string(std::chrono::duration(m_auto_refresh_period).count()) + " seconds" : std::string("disabled"))); + log::info(logcat, "Auto refresh now {}", (m_auto_refresh_period != 0s ? std::to_string(std::chrono::duration(m_auto_refresh_period).count()) + " seconds" : std::string("disabled"))); return {}; } //------------------------------------------------------------------------------------------------------------------------------ @@ -2491,7 +2497,7 @@ namespace { if (m_wallet->verify_password(req.old_password)) { m_wallet->change_password(m_wallet->get_wallet_file(), req.old_password, req.new_password); - oxen::log::warning(logcat, "Wallet password changed."); + log::warning(logcat, "Wallet password changed."); } else throw wallet_rpc_error{error_code::INVALID_PASSWORD, "Invalid original password."}; @@ -2559,7 +2565,7 @@ namespace { wal->generate(wallet_file, std::move(rc.second).password(), info.address, viewkey, false); res.info = "Watch-only wallet has been generated successfully."; } - oxen::log::info(logcat, "Wallet has been generated.\n"); + log::info(logcat, "Wallet has been generated.\n"); } if (!wal) @@ -2641,7 +2647,7 @@ namespace { wal->set_seed_language(mnemonic_language); crypto::secret_key recovery_val = wal->generate(wallet_file, std::move(rc.second).password(), recovery_key, true, false, false); - oxen::log::info(logcat, "Wallet has been restored.\n"); + log::info(logcat, "Wallet has been restored.\n"); // // Convert the secret key back to seed epee::wipeable_string electrum_words; @@ -2942,7 +2948,7 @@ namespace { throw wallet_rpc_error{error_code::INVALID_LOG_LEVEL, "Error: log level not valid"}; auto log_level = oxen::logging::parse_level(req.level); if (log_level.has_value()) - oxen::log::reset_level(*log_level); + log::reset_level(*log_level); return {}; } //------------------------------------------------------------------------------------------------------------------------------ @@ -3291,7 +3297,7 @@ namespace { { if (rec["entry_index"].get() >= num_entries) { - oxen::log::warning(logcat, "Got back invalid entry_index {} for a request for {} entries", rec["entry_index"], num_entries); + log::warning(logcat, "Got back invalid entry_index {} for a request for {} entries", rec["entry_index"], num_entries); continue; } @@ -3314,7 +3320,7 @@ namespace { && value.decrypt(res_e.name, type)) res_e.value = value.to_readable_value(nettype, type); else - oxen::log::warning(logcat, "Failed to decrypt ONS value for {}{}", res_e.name, (errmsg.empty() ? ""s : ": " + errmsg)); + log::warning(logcat, "Failed to decrypt ONS value for {}{}", res_e.name, (errmsg.empty() ? ""s : ": " + errmsg)); } } } @@ -3468,7 +3474,7 @@ namespace { if (wallet_file.empty() && from_json.empty()) throw std::logic_error{tr("Must specify --wallet-file or --generate-from-json or --wallet-dir")}; - oxen::log::warning(logcat, tools::wallet_rpc_server::tr("Loading wallet...")); + log::warning(logcat, tools::wallet_rpc_server::tr("Loading wallet...")); if(!wallet_file.empty()) wal = tools::wallet2::make_from_file(m_vm, true, wallet_file, password_prompt).first; else @@ -3488,12 +3494,12 @@ namespace { // if we ^C during potentially length load/refresh, there's no server loop yet if (quit) { - oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Saving wallet...")); + log::info(globallogcat, tools::wallet_rpc_server::tr("Saving wallet...")); wal->store(); - oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully saved")); + log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully saved")); throw std::runtime_error{tr("Wallet loading cancelled before initial refresh completed")}; } - oxen::log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully loaded")); + log::info(globallogcat, tools::wallet_rpc_server::tr("Successfully loaded")); } return wal; } @@ -3507,7 +3513,7 @@ namespace { } catch (const std::exception& e) { - oxen::log::error(logcat, "{}{}", tr("Wallet initialization failed: "), e.what()); + log::error(logcat, "{}{}", tr("Wallet initialization failed: "), e.what()); return false; } @@ -3516,28 +3522,28 @@ namespace { bool r = init(); CHECK_AND_ASSERT_MES(r, false, tools::wallet_rpc_server::tr("Failed to initialize wallet RPC server")); tools::signal_handler::install([this](int) { - oxen::log::warning(logcat, "Shutting down..."); + log::warning(logcat, "Shutting down..."); m_stop = true; }); - oxen::log::warning(globallogcat, tools::wallet_rpc_server::tr("Starting wallet RPC server")); + log::warning(globallogcat, tools::wallet_rpc_server::tr("Starting wallet RPC server")); try { run_loop(); } catch (const std::exception &e) { - oxen::log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to run wallet: "), e.what()); + log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to run wallet: "), e.what()); return false; } - oxen::log::warning(globallogcat, tools::wallet_rpc_server::tr("Stopped wallet RPC server")); + log::warning(globallogcat, tools::wallet_rpc_server::tr("Stopped wallet RPC server")); try { close_wallet(true); } catch (const std::exception& e) { - oxen::log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to save wallet: "), e.what()); + log::error(logcat, "{}{}", tools::wallet_rpc_server::tr("Failed to save wallet: "), e.what()); return false; } return true; @@ -3564,14 +3570,14 @@ int main(int argc, char **argv) po::options_description desc_params(wallet_args::tr("Wallet options"), opt_size.first, opt_size.second); po::options_description hidden_params("Hidden"); tools::wallet2::init_options(desc_params, hidden_params); - command_line::add_arg(desc_params, arg_rpc_bind_port); - command_line::add_arg(desc_params, arg_disable_rpc_login); - command_line::add_arg(desc_params, arg_restricted); + command_line::add_arg(desc_params, tools::arg_rpc_bind_port); + command_line::add_arg(desc_params, tools::arg_disable_rpc_login); + command_line::add_arg(desc_params, tools::arg_restricted); cryptonote::rpc_args::init_options(desc_params, hidden_params); command_line::add_arg(desc_params, arg_wallet_file); command_line::add_arg(desc_params, arg_from_json); - command_line::add_arg(desc_params, arg_wallet_dir); - command_line::add_arg(desc_params, arg_prompt_for_password); + command_line::add_arg(desc_params, tools::arg_wallet_dir); + command_line::add_arg(desc_params, tools::arg_prompt_for_password); daemonizer::init_options(hidden_params, desc_params); diff --git a/src/wallet/wallet_rpc_server.h b/src/wallet/wallet_rpc_server.h index 5d486289f..afd15d0b6 100644 --- a/src/wallet/wallet_rpc_server.h +++ b/src/wallet/wallet_rpc_server.h @@ -46,8 +46,6 @@ namespace tools { - static auto logcat = oxen::log::Cat("wallet.rpc"); - using HttpRequest = uWS::HttpRequest; using HttpResponse = uWS::HttpResponse; diff --git a/src/wallet/wallet_rpc_server_commands_defs.h b/src/wallet/wallet_rpc_server_commands_defs.h index dccd80fb0..9839b066e 100644 --- a/src/wallet/wallet_rpc_server_commands_defs.h +++ b/src/wallet/wallet_rpc_server_commands_defs.h @@ -59,8 +59,6 @@ namespace tools::wallet_rpc { - static auto logcat = oxen::log::Cat("wallet.rpc"); - /// Base class that all wallet rpc commands inherit from struct RPC_COMMAND {}; diff --git a/src/wallet3/transaction_scanner.cpp b/src/wallet3/transaction_scanner.cpp index 1256e032f..f2a9a1ee6 100644 --- a/src/wallet3/transaction_scanner.cpp +++ b/src/wallet3/transaction_scanner.cpp @@ -9,7 +9,8 @@ namespace wallet { - static auto logcat = oxen::log::Cat("wallet.wallet3"); + namespace log = oxen::log; + static auto logcat = log::Cat("wallet.wallet3"); std::vector TransactionScanner::scan_received( @@ -21,7 +22,7 @@ namespace wallet if (tx_public_keys.empty()) { - oxen::log::warning(logcat, "TransactionScanner found no tx public keys in transaction with hash <{}>.", tx.hash); + log::warning(logcat, "TransactionScanner found no tx public keys in transaction with hash <{}>.", tx.hash); return {}; } if (tx.tx.vout.size() != tx.global_indices.size()) From 085e9ba9634f8098916c163a6d938154c4685c1c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 21:35:35 -0300 Subject: [PATCH 06/32] Unwrap fmt::format with a style argument oxen::logging handles a style argument now (it is also safer e.g. if the final formatted string itself intentionally contains {}). --- src/blockchain_db/lmdb/db_lmdb.cpp | 16 ++-- .../blockchain_import.cpp | 4 +- src/common/scoped_message_writer.cpp | 2 +- src/common/signal_handler.h | 2 +- src/common/util.cpp | 2 +- src/cryptonote_basic/miner.cpp | 2 +- src/cryptonote_core/blockchain.cpp | 73 ++++++++++--------- src/cryptonote_core/cryptonote_core.cpp | 47 ++++++------ src/cryptonote_core/service_node_list.cpp | 20 ++--- .../cryptonote_protocol_handler.inl | 36 ++++----- src/daemon/daemon.cpp | 16 ++-- src/p2p/net_node.inl | 18 ++--- src/rpc/core_rpc_server.cpp | 2 +- src/wallet/wallet2.cpp | 8 +- 14 files changed, 127 insertions(+), 121 deletions(-) diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index 5e28a79f4..ffde9a961 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -1429,7 +1429,7 @@ void BlockchainLMDB::open(const fs::path& filename, cryptonote::network_type net #ifdef __OpenBSD__ if ((mdb_flags & MDB_WRITEMAP) == 0) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Running on OpenBSD: forcing WRITEMAP")); + log::info(logcat, fg(fmt::terminal_color::red), "Running on OpenBSD: forcing WRITEMAP"); mdb_flags |= MDB_WRITEMAP; } #endif @@ -4848,7 +4848,7 @@ void BlockchainLMDB::migrate_0_1() MDB_val k, v; char *ptr; - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 0 to 1 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 0 to 1 - this may take a while:"); log::info(logcat, "updating blocks, hf_versions, outputs, txs, and spent_keys tables..."); do { @@ -5382,7 +5382,7 @@ void BlockchainLMDB::migrate_1_2() MDB_val k, v; char *ptr; - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 1 to 2 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 1 to 2 - this may take a while:"); log::info(logcat, "updating txs_pruned and txs_prunable tables..."); do { @@ -5517,7 +5517,7 @@ void BlockchainLMDB::migrate_2_3() MDB_val k, v; char *ptr; - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 2 to 3 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 2 to 3 - this may take a while:"); do { log::info(logcat, "migrating block info:"); @@ -5633,7 +5633,7 @@ void BlockchainLMDB::migrate_2_3() void BlockchainLMDB::migrate_3_4() { log::trace(logcat, "BlockchainLMDB::{}", __func__); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 3 to 4 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 3 to 4 - this may take a while:"); // Migrate output blacklist { @@ -5862,7 +5862,7 @@ void BlockchainLMDB::migrate_3_4() void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) { log::trace(logcat, "BlockchainLMDB::{}", __func__); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 4 to 5 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 4 to 5 - this may take a while:"); mdb_txn_safe txn(false); { @@ -5935,7 +5935,7 @@ void BlockchainLMDB::migrate_4_5(cryptonote::network_type nettype) void BlockchainLMDB::migrate_5_6() { log::trace(logcat, "BlockchainLMDB::{}", __func__); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 5 to 6 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 5 to 6 - this may take a while:"); mdb_txn_safe txn(false); { @@ -6044,7 +6044,7 @@ void BlockchainLMDB::migrate_5_6() void BlockchainLMDB::migrate_6_7() { log::trace(logcat, "BlockchainLMDB::{}", __func__); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 6 to 7 - this may take a while:")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Migrating blockchain from DB version 6 to 7 - this may take a while:"); std::vector checkpoints; checkpoints.reserve(1024); diff --git a/src/blockchain_utilities/blockchain_import.cpp b/src/blockchain_utilities/blockchain_import.cpp index 75a46a988..be367a26b 100644 --- a/src/blockchain_utilities/blockchain_import.cpp +++ b/src/blockchain_utilities/blockchain_import.cpp @@ -678,13 +678,13 @@ int main(int argc, char* argv[]) if (!opt_verify) { - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "\n\ + log::warning(logcat, fg(fmt::terminal_color::red), "\n\ Import is set to proceed WITHOUT VERIFICATION.\n\ This is a DANGEROUS operation: if the file was tampered with in transit, or obtained from a malicious source,\n\ you could end up with a compromised database. It is recommended to NOT use {}.\n\ *****************************************************************************************\n\ You have 90 seconds to press ^C or terminate this program before unverified import starts\n\ - *****************************************************************************************", arg_noverify.name)); + *****************************************************************************************", arg_noverify.name); sleep(90); } diff --git a/src/common/scoped_message_writer.cpp b/src/common/scoped_message_writer.cpp index b24e3bc47..aefcc2942 100644 --- a/src/common/scoped_message_writer.cpp +++ b/src/common/scoped_message_writer.cpp @@ -12,7 +12,7 @@ scoped_message_writer::~scoped_message_writer() if (fmt::terminal_color::white == m_color) logcat->log(m_log_level, m_oss.str()); else - logcat->log(m_log_level, fmt::format(fg(m_color),m_oss.str())); + logcat->log(m_log_level, "{}", fmt::format(fg(m_color), m_oss.str())); std::cout << std::endl; } } diff --git a/src/common/signal_handler.h b/src/common/signal_handler.h index 176842065..c37f40a48 100644 --- a/src/common/signal_handler.h +++ b/src/common/signal_handler.h @@ -48,7 +48,7 @@ namespace tools { } else { - log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Got control signal {}. Exiting without saving...", type); + log::info(globallogcat, fg(fmt::terminal_color::red), "Got control signal {}. Exiting without saving...", type); return FALSE; } return TRUE; diff --git a/src/common/util.cpp b/src/common/util.cpp index 66185eedb..10a06f9b1 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -92,7 +92,7 @@ namespace tools #ifdef __GLIBC__ const char *ver = ::gnu_get_libc_version(); if (!strcmp(ver, "2.25")) - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Running with glibc {}, hangs may occur - change glibc version if possible", ver)); + log::warning(logcat, fg(fmt::terminal_color::red), "Running with glibc {}, hangs may occur - change glibc version if possible", ver); #endif return true; diff --git a/src/cryptonote_basic/miner.cpp b/src/cryptonote_basic/miner.cpp index caf5a1dd7..3409125bf 100644 --- a/src/cryptonote_basic/miner.cpp +++ b/src/cryptonote_basic/miner.cpp @@ -345,7 +345,7 @@ namespace cryptonote if(check_hash(h, local_diff)) { //we lucky! - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Found block {} at height {} for difficulty: {}", get_block_hash(b), height, local_diff)); + log::info(logcat, fg(fmt::terminal_color::green), "Found block {} at height {} for difficulty: {}", get_block_hash(b), height, local_diff); cryptonote::block_verification_context bvc; m_phandler->handle_block_found(b, bvc); } diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 1917e0493..583cc0eff 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -1181,7 +1181,7 @@ bool Blockchain::switch_to_alternative_blockchain(const std::listheight())); + log::info(logcat, fg(fmt::terminal_color::green), "REORGANIZE SUCCESS! on height: {}, new blockchain size: {}", split_height, m_db->height()); return true; } //------------------------------------------------------------------ @@ -1379,7 +1379,7 @@ bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_bl try { hook(hook_data); } catch (const std::exception& e) { - log::info(globallogcat, fmt::format(fg(fmt::terminal_color::red), "Miner tx failed validation: {}", e.what())); + log::info(globallogcat, fg(fmt::terminal_color::red), "Miner tx failed validation: {}", e.what()); return false; } } @@ -2161,12 +2161,11 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - std::stringstream stream; - stream << "----- " << block_type << " BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << blk_height << "\n" << "id: " << id; - if (!pulse_block) stream << " PoW: " << blk_pow.proof_of_work; - stream << " difficulty: " << current_diff; + std::string msg = fmt::format("----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid: {}", block_type, blk_height, id); + if (!pulse_block) fmt::format_to(std::back_inserter(msg), " PoW: {}", blk_pow.proof_of_work); + fmt::format_to(std::back_inserter(msg), " difficulty {}", current_diff); - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "{}", stream.str())); + log::info(logcat, fg(fmt::terminal_color::blue), "{}", msg); return true; } } @@ -2182,12 +2181,12 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id bool keep_alt_chain = false; if (alt_chain_has_more_checkpoints) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {}, checkpoint is found in alternative chain on height {}", alt_chain.front().height, m_db->height() - 1, blk_height)); + log::info(logcat, fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {}, checkpoint is found in alternative chain on height {}", alt_chain.front().height, m_db->height() - 1, blk_height); } else { keep_alt_chain = true; - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); + log::info(logcat, fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty); } bool r = switch_to_alternative_blockchain(alt_chain, keep_alt_chain); @@ -2199,7 +2198,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); + log::info(logcat, fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff); return true; } } @@ -2207,7 +2206,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id { if (alt_chain_has_greater_pow) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty)); + log::info(logcat, fg(fmt::terminal_color::green), "###### REORGANIZE on height: {} of {} with cum_difficulty {}\n alternative blockchain size: {} with cum_difficulty {}", alt_chain.front().height, m_db->height() - 1, m_db->get_block_cumulative_difficulty(m_db->height() - 1), alt_chain.size(), alt_data.cumulative_difficulty); bool r = switch_to_alternative_blockchain(alt_chain, true); if (r) bvc.m_added_to_main_chain = true; @@ -2217,7 +2216,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff)); + log::info(logcat, fg(fmt::terminal_color::blue), "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid:\t{}\nPoW:\t{}\ndifficulty:\t{}", block_type, blk_height, id, blk_pow.proof_of_work, current_diff); return true; } } @@ -4150,7 +4149,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co // validate proof_of_work versus difficulty target result.valid = check_hash(result.proof_of_work, difficulty); if (!result.valid) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} with id: {}\n does not have enough proof of work: {} at height {}, required difficulty: {}", (alt_block ? "Alternative block" : "Block"), blk_hash, result.proof_of_work, blk_height, difficulty)); + log::info(logcat, fg(fmt::terminal_color::red), "{} with id: {}\n does not have enough proof of work: {} at height {}, required difficulty: {}", (alt_block ? "Alternative block" : "Block"), blk_hash, result.proof_of_work, blk_height, difficulty); } return result; @@ -4191,7 +4190,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block crypto::hash top_hash = get_tail_id(); if(blk.prev_id != top_hash) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has wrong prev_id: {}, expected: {}", blk_hash, blk.prev_id, top_hash)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {}, has wrong prev_id: {}, expected: {}", blk_hash, blk.prev_id, top_hash); return false; } @@ -4203,11 +4202,13 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (auto now = std::chrono::steady_clock::now(); now > last_outdated_warning + 5min) { last_outdated_warning = now; - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "A block was seen on the network with a version higher than the last")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "known one. This may be an old version of the daemon, and a software")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "update may be required to sync further. Try running: update check")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + for (const auto* msg : { + "**********************************************************************", + "A block was seen on the network with a version higher than the last", + "known one. This may be an old version of the daemon, and a software", + "update may be required to sync further. Try running: update check", + "**********************************************************************"}) + log::warning(logcat, fg(fmt::terminal_color::red), msg); } } @@ -4215,7 +4216,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block if (blk.major_version != required_major_version || (blk.major_version < hf::hf19_reward_batching && blk.minor_version < static_cast(required_major_version))) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(required_major_version), static_cast(required_major_version), blk_height)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {}, has invalid version {}.{}; current: {}.{} for height {}", blk_hash, static_cast(blk.major_version), +blk.minor_version, static_cast(required_major_version), static_cast(required_major_version), blk_height); return false; } @@ -4228,7 +4229,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block { if (!service_node_checkpoint || (service_node_checkpoint && blk.major_version >= hf::hf13_enforce_checkpoints)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "CHECKPOINT VALIDATION FAILED")); + log::info(logcat, fg(fmt::terminal_color::red), "CHECKPOINT VALIDATION FAILED"); return false; } } @@ -4238,7 +4239,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // number of the most recent blocks. if(!check_block_timestamp(blk)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {}, has invalid timestamp: {}", blk_hash, blk.timestamp)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {}, has invalid timestamp: {}", blk_hash, blk.timestamp); return false; } } @@ -4248,7 +4249,7 @@ bool Blockchain::basic_block_checks(cryptonote::block const &blk, bool alt_block // sanity check basic miner tx properties; if(!prevalidate_miner_transaction(blk, alt_block ? blk_height : chain_height, hf_version)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} failed to pass prevalidation", blk_hash)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {} failed to pass prevalidation", blk_hash); return false; } @@ -4338,7 +4339,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& if (m_db->tx_exists(tx_id)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} attempting to add transaction already in blockchain with id: {}", id, tx_id)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {} attempting to add transaction already in blockchain with id: {}", id, tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4350,7 +4351,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // get transaction with hash from tx_pool if(!m_tx_pool.take_tx(tx_id, tx_tmp, txblob, tx_weight, fee, relayed, do_not_relay, double_spend_seen)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one unknown transaction with id: {}", id, tx_id)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {} has at least one unknown transaction with id: {}", id, tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4388,11 +4389,11 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& tx_verification_context tvc{}; if(!check_tx_inputs(tx, tvc)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id)); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id: {} has at least one transaction (id: {}) with wrong inputs.", id, tx_id); add_block_as_invalid(bl); - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block with id {} added as invalid because of wrong inputs in transactions", id)); - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "tx_index {}, m_blocks_txs_check {}:", tx_index, m_blocks_txs_check.size())); + log::info(logcat, fg(fmt::terminal_color::red), "Block with id {} added as invalid because of wrong inputs in transactions", id); + log::info(logcat, fg(fmt::terminal_color::red), "tx_index {}, m_blocks_txs_check {}:", tx_index, m_blocks_txs_check.size()); for (const auto &h: m_blocks_txs_check) log::error(log::Cat("verify"), " {}", h); bvc.m_verifivation_failed = true; @@ -4428,7 +4429,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& uint64_t already_generated_coins = chain_height ? m_db->get_block_already_generated_coins(chain_height - 1) : 0; if(!validate_miner_transaction(bl, cumulative_block_weight, fee_summary, base_reward, already_generated_coins, get_network_version())) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block {} with id: {} has incorrect miner transaction", (chain_height - 1), id)); + log::info(logcat, fg(fmt::terminal_color::red), "Block {} with id: {} has incorrect miner transaction", (chain_height - 1), id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; @@ -4464,7 +4465,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } catch (const KEY_IMAGE_EXISTS& e) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); + log::info(logcat, fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what()); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4473,7 +4474,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& catch (const std::exception& e) { //TODO: figure out the best way to deal with this failure - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what())); + log::info(logcat, fg(fmt::terminal_color::red), "Error adding block with hash: {} to blockchain, what = {}", id, e.what()); m_batch_success = false; bvc.m_verifivation_failed = true; return_tx_to_pool(txs); @@ -4482,7 +4483,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& } else { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Blocks that failed verification should not reach here")); + log::info(logcat, fg(fmt::terminal_color::red), "Blocks that failed verification should not reach here"); } auto abort_block = oxen::defer([&]() { @@ -4507,14 +4508,14 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { m_service_node_list.block_add(bl, only_txs, checkpoint); } catch (const std::exception& e) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to Service Node List: {}", e.what())); + log::info(logcat, fg(fmt::terminal_color::red), "Failed to add block to Service Node List: {}", e.what()); bvc.m_verifivation_failed = true; return false; } if (!m_ons_db.add_block(bl, only_txs)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to add block to ONS DB.")); + log::info(logcat, fg(fmt::terminal_color::red), "Failed to add block to ONS DB."); bvc.m_verifivation_failed = true; return false; } @@ -4537,7 +4538,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& try { hook(hook_data); } catch (const std::exception& e) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Block added hook failed with exception: ", e.what())); + log::info(logcat, fg(fmt::terminal_color::red), "Block added hook failed with exception: ", e.what()); bvc.m_verifivation_failed = true; return false; } @@ -4548,7 +4549,7 @@ bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& // do this after updating the hard fork state since the weight limit may change due to fork if (!update_next_cumulative_weight_limit()) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Failed to update next cumulative weight limit")); + log::info(logcat, fg(fmt::terminal_color::red), "Failed to update next cumulative weight limit"); return false; } diff --git a/src/cryptonote_core/cryptonote_core.cpp b/src/cryptonote_core/cryptonote_core.cpp index 4a51ef9d6..839f21c63 100644 --- a/src/cryptonote_core/cryptonote_core.cpp +++ b/src/cryptonote_core/cryptonote_core.cpp @@ -942,16 +942,16 @@ namespace cryptonote } if (m_service_node) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Service node public keys:")); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- primary: {}", tools::type_to_hex(keys.pub))); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- ed25519: {}", tools::type_to_hex(keys.pub_ed25519))); + log::info(logcat, fg(fmt::terminal_color::yellow), "Service node public keys:"); + log::info(logcat, fg(fmt::terminal_color::yellow), "- primary: {}", tools::type_to_hex(keys.pub)); + log::info(logcat, fg(fmt::terminal_color::yellow), "- ed25519: {}", tools::type_to_hex(keys.pub_ed25519)); // .snode address is the ed25519 pubkey, encoded with base32z and with .snode appended: - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- lokinet: {}.snode", oxenc::to_base32z(tools::view_guts(keys.pub_ed25519)))); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "- x25519: {}", tools::type_to_hex(keys.pub_x25519))); + log::info(logcat, fg(fmt::terminal_color::yellow), "- lokinet: {}.snode", oxenc::to_base32z(tools::view_guts(keys.pub_ed25519))); + log::info(logcat, fg(fmt::terminal_color::yellow), "- x25519: {}", tools::type_to_hex(keys.pub_x25519)); } else { // Only print the x25519 version because it's the only thing useful for a non-SN (for // encrypted LMQ RPC connections). - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "x25519 public key: {}", tools::type_to_hex(keys.pub_x25519))); + log::info(logcat, fg(fmt::terminal_color::yellow), "x25519 public key: {}", tools::type_to_hex(keys.pub_x25519)); } return true; @@ -2268,8 +2268,8 @@ namespace cryptonote auto pubkey = m_service_node_list.get_pubkey_from_x25519(m_service_keys.pub_x25519); if (pubkey != crypto::null_pkey && pubkey != m_service_keys.pub && m_service_node_list.is_service_node(pubkey, false /*don't require active*/)) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), - "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as this service node. This typically means both have the same 'key_ed25519' private key file.")); + log::info(logcat, fg(fmt::terminal_color::red), + "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as this service node. This typically means both have the same 'key_ed25519' private key file."); return; } @@ -2284,7 +2284,7 @@ namespace cryptonote if (pk != m_service_keys.pub && proof.proof->public_ip == m_sn_public_ip && (proof.proof->qnet_port == m_quorumnet_port || ( m_nettype != network_type::DEVNET && (proof.proof->storage_https_port == storage_https_port() || proof.proof->storage_omq_port == storage_omq_port())))) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Another service node ({}) is broadcasting the same public IP and ports as this service node ({}:{}[qnet], :{}[SS-HTTP], :{}[SS-LMQ]). This will lead to deregistration of one or both service nodes if not corrected. (Do both service nodes have the correct IP for the service-node-public-ip setting?)", pk, epee::string_tools::get_ip_string_from_int32(m_sn_public_ip), proof.proof->qnet_port, proof.proof->storage_https_port, proof.proof->storage_omq_port)); + log::info(logcat, fg(fmt::terminal_color::red), "Another service node ({}) is broadcasting the same public IP and ports as this service node ({}:{}[qnet], :{}[SS-HTTP], :{}[SS-LMQ]). This will lead to deregistration of one or both service nodes if not corrected. (Do both service nodes have the correct IP for the service-node-public-ip setting?)", pk, epee::string_tools::get_ip_string_from_int32(m_sn_public_ip), proof.proof->qnet_port, proof.proof->storage_https_port, proof.proof->storage_omq_port); }); } @@ -2292,14 +2292,14 @@ namespace cryptonote { if (!check_external_ping(m_last_storage_server_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "the storage server")) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), - "Failed to submit uptime proof: have not heard from the storage server recently. Make sure that it is running! It is required to run alongside the Loki daemon")); + log::info(logcat, fg(fmt::terminal_color::red), + "Failed to submit uptime proof: have not heard from the storage server recently. Make sure that it is running! It is required to run alongside the Loki daemon"); return; } if (!check_external_ping(m_last_lokinet_ping, get_net_config().UPTIME_PROOF_FREQUENCY, "Lokinet")) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), - "Failed to submit uptime proof: have not heard from lokinet recently. Make sure that it is running! It is required to run alongside the Loki daemon")); + log::info(logcat, fg(fmt::terminal_color::red), + "Failed to submit uptime proof: have not heard from lokinet recently. Make sure that it is running! It is required to run alongside the Loki daemon"); return; } } @@ -2323,14 +2323,17 @@ namespace cryptonote main_message = "The daemon is running offline and will not attempt to sync to the Loki network."; else main_message = "The daemon will start synchronizing with the network. This may take a long time to complete."; - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ -{}\n\n\ -You can set the level of process detailization through \"set_log \" command,\n\ -where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING).\n\ -\n\ -Use the \"help\" command to see the list of available commands.\n\ -Use \"help \" to see a command's documentation.\n\ -**********************************************************************\n", main_message)); + log::info(logcat, fg(fmt::terminal_color::yellow), R"( +********************************************************************** +{} + +You can set the level of process detailization through "set_log " command, +where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING). + +Use the "help" command to see the list of available commands. +Use "help " to see a command's documentation. +********************************************************************** +)", main_message); m_starter_message_showed = true; } @@ -2361,7 +2364,7 @@ Use \"help \" to see a command's documentation.\n\ { uint64_t free_space = get_free_space(); if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Free space is below 1 GB on {}", m_config_folder)); + log::warning(logcat, fg(fmt::terminal_color::red), "Free space is below 1 GB on {}", m_config_folder); return true; } //----------------------------------------------------------------------------------------------- diff --git a/src/cryptonote_core/service_node_list.cpp b/src/cryptonote_core/service_node_list.cpp index 171f19e59..dda30d2e7 100644 --- a/src/cryptonote_core/service_node_list.cpp +++ b/src/cryptonote_core/service_node_list.cpp @@ -740,7 +740,7 @@ namespace service_nodes switch (state_change.state) { case new_state::deregister: if (is_me) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Deregistration for service node (yours): {}", key)); + log::info(logcat, fg(fmt::terminal_color::red), "Deregistration for service node (yours): {}", key); else log::info(logcat, "Deregistration for service node: {}", key); @@ -774,7 +774,7 @@ namespace service_nodes } if (is_me) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Temporary decommission for service node (yours): {}", key)); + log::info(logcat, fg(fmt::terminal_color::red), "Temporary decommission for service node (yours): {}", key); else log::info(logcat, "Temporary decommission for service node: {}", key); @@ -812,7 +812,7 @@ namespace service_nodes } if (is_me) - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Recommission for service node (yours): {}", key)); + log::info(logcat, fg(fmt::terminal_color::green), "Recommission for service node (yours): {}", key); else log::info(logcat, "Recommission for service node: {}", key); @@ -857,7 +857,7 @@ namespace service_nodes } if (is_me) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Reward position reset for service node (yours): {}", key)); + log::info(logcat, fg(fmt::terminal_color::red), "Reward position reset for service node (yours): {}", key); else log::info(logcat, "Reward position reset for service node: {}", key); @@ -1144,7 +1144,7 @@ namespace service_nodes } if (my_keys && my_keys->pub == key) - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} on height: {}", key, block_height)); + log::info(logcat, fg(fmt::terminal_color::green), "Service node registered (yours): {} on height: {}", key, block_height); else log::info(logcat, "New service node registered: {} on height: {}", key, block_height); } @@ -1178,11 +1178,11 @@ namespace service_nodes { if (registered_during_grace_period) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node re-registered (yours): {} at block height: {}", key, block_height)); + log::info(logcat, fg(fmt::terminal_color::green), "Service node re-registered (yours): {} at block height: {}", key, block_height); } else { - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node registered (yours): {} at block height: {}", key, block_height)); + log::info(logcat, fg(fmt::terminal_color::green), "Service node registered (yours): {} at block height: {}", key, block_height); } } else @@ -2193,7 +2193,7 @@ namespace service_nodes if (i != service_nodes_infos.end()) { if (my_keys && my_keys->pub == pubkey) - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Service node expired (yours): {} at block height: {}", pubkey, block_height)); + log::info(logcat, fg(fmt::terminal_color::green), "Service node expired (yours): {} at block height: {}", pubkey, block_height); else log::info(logcat, "Service node expired: {} at block height: {}", pubkey, block_height); @@ -3176,7 +3176,7 @@ namespace service_nodes log::debug(logcat, "Accepted uptime proof from {}", proof.pubkey); if (m_service_node_keys && proof.pubkey_ed25519 == m_service_node_keys->pub_ed25519) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof.pubkey)); + log::info(logcat, fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof.pubkey); } auto old_x25519 = iproof.pubkey_x25519; @@ -3305,7 +3305,7 @@ namespace service_nodes log::debug(logcat, "Accepted uptime proof from {}", proof->pubkey); if (m_service_node_keys && proof->pubkey_ed25519 == m_service_node_keys->pub_ed25519) - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof->pubkey)); + log::info(logcat, fg(fmt::terminal_color::red), "Uptime proof from SN {} is not us, but is using our ed/x25519 keys; this is likely to lead to deregistration of one or both service nodes.", proof->pubkey); } auto old_x25519 = iproof.pubkey_x25519; diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.inl b/src/cryptonote_protocol/cryptonote_protocol_handler.inl index 9e2c4b23f..bfd48fe13 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.inl +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.inl @@ -331,7 +331,7 @@ namespace cryptonote if (version != hshd.top_version) { if (version < hshd.top_version && version == get_network_version(nettype, m_core.get_current_blockchain_height())) - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "{} peer claims higher version than we think ({} for {} instead of {}) 0 we may be forked from the network and a software upgrade may be needed", context, (unsigned)hshd.top_version, (hshd.current_height - 1), (unsigned)version)); + log::warning(logcat, fg(fmt::terminal_color::red), "{} peer claims higher version than we think ({} for {} instead of {}) 0 we may be forked from the network and a software upgrade may be needed", context, (unsigned)hshd.top_version, (hshd.current_height - 1), (unsigned)version); return false; } } @@ -448,7 +448,7 @@ namespace cryptonote uint64_t max_block_height = std::max(hshd.current_height, curr_height); std::string sync_msg = fmt::format("{}Sync data returned a new top block candidate: {} -> {} [Your node is {} blocks ({} {})]\nSYNCHRONIZATION started", context, curr_height, hshd.current_height, abs_diff, tools::get_human_readable_timespan(abs_diff*TARGET_BLOCK_TIME), (0 <= diff ? "behind" : "ahead")); if (is_initial) - log::info(globallogcat, fmt::format(fg(fmt::terminal_color::cyan), sync_msg)); + log::info(globallogcat, fg(fmt::terminal_color::cyan), sync_msg); else log::debug(globallogcat, sync_msg); @@ -1220,7 +1220,7 @@ namespace cryptonote } { - log::debug(globallogcat, fmt::format(fg(fmt::terminal_color::yellow), "{} Got NEW BLOCKS inside of {}: size: {}, blocks: {} - {} (pruning seed {})", context, __FUNCTION__, arg.blocks.size(), start_height, (start_height + arg.blocks.size() - 1), epee::string_tools::to_string_hex(context.m_pruning_seed))); + log::debug(globallogcat, fg(fmt::terminal_color::yellow), "{} Got NEW BLOCKS inside of {}: size: {}, blocks: {} - {} (pruning seed {})", context, __FUNCTION__, arg.blocks.size(), start_height, (start_height + arg.blocks.size() - 1), epee::string_tools::to_string_hex(context.m_pruning_seed)); // add that new span to the block queue seconds_f dt = now - request_time; @@ -1561,7 +1561,7 @@ namespace cryptonote + std::to_string(previous_stripe) + " -> " + std::to_string(current_stripe); if (OXEN_LOG_ENABLED(debug)) timing_message += std::string(": ") + m_block_queue.get_overview(current_blockchain_height); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {}/{} {} {}", current_blockchain_height, target_blockchain_height, progress_message, timing_message)); + log::info(logcat, fg(fmt::terminal_color::yellow), "Synced {}/{} {} {}", current_blockchain_height, target_blockchain_height, progress_message, timing_message); if (previous_stripe != current_stripe) notify_new_stripe(context, current_stripe); } @@ -2226,7 +2226,7 @@ skip: { if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height()) { - log::info(globallogcat, fmt::format(fg(fmt::terminal_color::green), "SYNCHRONIZED OK")); + log::info(globallogcat, fg(fmt::terminal_color::green), "SYNCHRONIZED OK"); on_connection_synchronized(); } } @@ -2255,22 +2255,24 @@ skip: if (synced_seconds == 0s) synced_seconds = 1s; float blocks_per_second = synced_blocks / (float)synced_seconds.count(); - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Synced {} blocks in {} ({} blocks per second)", synced_blocks, tools::get_human_readable_timespan(synced_seconds), blocks_per_second)); + log::info(logcat, fg(fmt::terminal_color::yellow), "Synced {} blocks in {} ({} blocks per second)", synced_blocks, tools::get_human_readable_timespan(synced_seconds), blocks_per_second); } } - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "\n**********************************************************************\n\ -You are now synchronized with the network. You may now start oxen-wallet-cli.\n\ -\n\ -Use the \"help\" command to see the list of available commands.\n\ -**********************************************************************")); + log::info(logcat, fg(fmt::terminal_color::yellow), R"( +********************************************************************** +You are now synchronized with the network. You may now start oxen-wallet-cli. + +Use the "help" command to see the list of available commands. +**********************************************************************)"); if (OXEN_LOG_ENABLED(info)) { const std::chrono::duration sync_time{std::chrono::steady_clock::now() - m_sync_timer}; - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Sync time: {:.0f} min, {} + {} MB downloaded, {}% old spans, {}% bad spans", sync_time.count()/1e9/60, - (10 * m_sync_download_objects_size / 1024 / 1024) / 10.f, - (10 * m_sync_download_chain_size / 1024 / 1024) / 10.f, - 100.0f * m_sync_old_spans_downloaded / m_sync_spans_downloaded, - 100.0f * m_sync_bad_spans_downloaded / m_sync_spans_downloaded)); + log::info(logcat, fg(fmt::terminal_color::yellow), "Sync time: {:.1f} min, {:.1f} + {:.1f} MB downloaded, {:.2f}% old spans, {:.2f}% bad spans", + sync_time.count()/60.0, + m_sync_download_objects_size / 1000.0 / 1000.0, + m_sync_download_chain_size / 1000.0 / 1000.0, + 100.0 * m_sync_old_spans_downloaded / m_sync_spans_downloaded, + 100.0 * m_sync_bad_spans_downloaded / m_sync_spans_downloaded); } m_core.on_synchronized(); } @@ -2611,7 +2613,7 @@ Use the \"help\" command to see the list of available commands.\n\ log::info(logcat, "Target height decreasing from {} to {}", previous_target, target); m_core.set_target_blockchain_height(target); if (target == 0 && context.m_state > cryptonote_connection_context::state_before_handshake && !m_stopping) - log::warning(logcat, fmt::format(fg(fmt::terminal_color::yellow), "oxend is now disconnected from the network")); + log::warning(logcat, fg(fmt::terminal_color::yellow), "oxend is now disconnected from the network"); } m_block_queue.flush_spans(context.m_connection_id, false); diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index ffbf9e737..2cda7c212 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -111,7 +111,7 @@ daemon::daemon(boost::program_options::variables_map vm_) : p2p{std::make_unique(*protocol)}, rpc{std::make_unique(*core, *p2p)} { - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Initializing daemon objects...")); + log::info(logcat, fg(fmt::terminal_color::blue), "Initializing daemon objects..."); log::info(logcat, "- cryptonote protocol"); if (!protocol->init(vm)) @@ -146,7 +146,7 @@ daemon::daemon(boost::program_options::variables_map vm_) : std::vector> rpc_listen_admin, rpc_listen_public; if (deprecated_rpc_options) { - log::info(logcat, fmt::format(fg(fmt::terminal_color::red), "{} options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead", deprecated_option_names)); + log::info(logcat, fg(fmt::terminal_color::red), "{} options are deprecated and will be removed from a future oxend version; use --rpc-public/--rpc-admin instead", deprecated_option_names); // These old options from Monero are really janky: --restricted-rpc turns the main port // restricted, but then we also have --rpc-restricted-bind-port but both are stuck with @@ -219,12 +219,12 @@ daemon::daemon(boost::program_options::variables_map vm_) : http_rpc_public.emplace(*rpc, rpc_config, true /*restricted*/, std::move(rpc_listen_public)); } - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Done daemon object initialization")); + log::info(logcat, fg(fmt::terminal_color::blue), "Done daemon object initialization"); } daemon::~daemon() { - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitializing daemon objects...")); + log::info(logcat, fg(fmt::terminal_color::blue), "Deinitializing daemon objects..."); if (http_rpc_public) { log::info(logcat, "- public HTTP RPC server"); @@ -257,7 +257,7 @@ daemon::~daemon() } catch (const std::exception& e) { log::error(logcat, "Failed to stop cryptonote protocol: {}", e.what()); } - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Deinitialization complete")); + log::info(logcat, fg(fmt::terminal_color::blue), "Deinitialization complete"); } void daemon::init_options(boost::program_options::options_description& option_spec, boost::program_options::options_description& hidden) @@ -298,7 +298,7 @@ bool daemon::run(bool interactive) try { - log::info(logcat, fmt::format(fg(fmt::terminal_color::blue), "Starting up oxend services...")); + log::info(logcat, fg(fmt::terminal_color::blue), "Starting up oxend services..."); cryptonote::GetCheckpointsCallback get_checkpoints; #if defined(PER_BLOCK_CHECKPOINT) get_checkpoints = blocks::GetCheckpointsData; @@ -342,14 +342,14 @@ bool daemon::run(bool interactive) rpc_commands->start_handling([this] { stop(); }); } - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Starting up main network")); + log::info(logcat, fg(fmt::terminal_color::green), "Starting up main network"); #ifdef ENABLE_SYSTEMD sd_notify(0, ("READY=1\nSTATUS=" + core->get_status_string()).c_str()); #endif p2p->run(); // blocks until p2p goes down - log::info(logcat, fmt::format(fg(fmt::terminal_color::yellow), "Main network stopped")); + log::info(logcat, fg(fmt::terminal_color::yellow), "Main network stopped"); if (rpc_commands) { diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index cf76ab6d5..4a75d79a7 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -167,7 +167,7 @@ namespace nodetool if (now >= it->second) { m_blocked_hosts.erase(it); - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked.", address.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Host {} unblocked.", address.host_str()); it = m_blocked_hosts.end(); } else @@ -188,7 +188,7 @@ namespace nodetool if (now >= it->second) { it = m_blocked_subnets.erase(it); - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} unblocked", it->first.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Subnet {} unblocked", it->first.host_str()); continue; } if (it->first.matches(ipv4_address)) @@ -241,7 +241,7 @@ namespace nodetool conns.clear(); } - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} blocked", addr.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Host {} blocked", addr.host_str()); return true; } //----------------------------------------------------------------------------------- @@ -253,7 +253,7 @@ namespace nodetool if (i == m_blocked_hosts.end()) return false; m_blocked_hosts.erase(i); - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Host {} unblocked", address.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Host {} unblocked", address.host_str()); return true; } //----------------------------------------------------------------------------------- @@ -293,7 +293,7 @@ namespace nodetool conns.clear(); } - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {} blocked.", subnet.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Subnet {} blocked.", subnet.host_str()); return true; } //----------------------------------------------------------------------------------- @@ -305,7 +305,7 @@ namespace nodetool if (i == m_blocked_subnets.end()) return false; m_blocked_subnets.erase(i); - log::info(logcat, fmt::format(fg(fmt::terminal_color::cyan), "Subnet {}", subnet.host_str())); + log::info(logcat, fg(fmt::terminal_color::cyan), "Subnet {}", subnet.host_str()); return true; } //----------------------------------------------------------------------------------- @@ -718,11 +718,11 @@ namespace nodetool } m_listening_port = public_zone.m_net_server.get_binded_port(); - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv4) to {}:{}", public_zone.m_bind_ip, m_listening_port)); + log::info(logcat, fg(fmt::terminal_color::green), "Net service bound (IPv4) to {}:{}", public_zone.m_bind_ip, m_listening_port); if (m_use_ipv6) { m_listening_port_ipv6 = public_zone.m_net_server.get_binded_port_ipv6(); - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), "Net service bound (IPv6) to {}:{}", public_zone.m_bind_ipv6_address, m_listening_port_ipv6)); + log::info(logcat, fg(fmt::terminal_color::green), "Net service bound (IPv6) to {}:{}", public_zone.m_bind_ipv6_address, m_listening_port_ipv6); } if(m_external_port) log::debug(logcat, "External port defined as {}", m_external_port); @@ -1681,7 +1681,7 @@ namespace nodetool } else { - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "No incoming connections - check firewalls/routers allow port {}", get_this_peer_port())); + log::warning(logcat, fg(fmt::terminal_color::red), "No incoming connections - check firewalls/routers allow port {}", get_this_peer_port()); } } return true; diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 60e20c623..1816d2403 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -2662,7 +2662,7 @@ namespace cryptonote::rpc { bool significant = std::chrono::seconds{now - old} > lifetime; // Print loudly for the first ping after startup/expiry auto msg = fmt::format("Received ping from {} {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2]); if (significant) - log::info(logcat, fmt::format(fg(fmt::terminal_color::green), msg)); + log::info(logcat, fg(fmt::terminal_color::green), "{}", msg); else log::debug(logcat, msg); success(significant); diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index b89a0a37f..26a7a7993 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -2484,10 +2484,10 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote if (total_received_1 != total_received_2) { - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Consistency failure in amounts received")); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "Check transaction {}", txid)); - log::warning(logcat, fmt::format(fg(fmt::terminal_color::red), "**********************************************************************")); + log::warning(logcat, fg(fmt::terminal_color::red), "**********************************************************************"); + log::warning(logcat, fg(fmt::terminal_color::red), "Consistency failure in amounts received"); + log::warning(logcat, fg(fmt::terminal_color::red), "Check transaction {}", txid); + log::warning(logcat, fg(fmt::terminal_color::red), "**********************************************************************"); exit(1); return; } From 5806fd78251e11e52d6206c4d6fb5a955719bd50 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 22 Sep 2022 23:40:30 -0300 Subject: [PATCH 07/32] Change simple fmt::format calls to new "..."_format(...) --- external/oxen-logging | 2 +- src/common/format.h | 6 ++ src/common/notify.h | 3 +- src/common/scoped_message_writer.cpp | 4 +- src/crypto/fmt.h | 91 ++++++------------ src/cryptonote_basic/connection_context.h | 8 +- src/cryptonote_basic/cryptonote_basic.h | 13 +-- .../cryptonote_format_utils.cpp | 4 +- src/cryptonote_core/blockchain.cpp | 4 +- src/cryptonote_core/oxen_name_system.h | 12 +-- src/cryptonote_core/service_node_list.cpp | 56 +++++------ src/cryptonote_core/service_node_quorum_cop.h | 3 +- src/cryptonote_core/service_node_voting.h | 7 +- .../cryptonote_protocol_handler.h | 2 +- .../cryptonote_protocol_handler.inl | 7 +- src/daemon/rpc_command_executor.cpp | 92 ++++++++++--------- src/p2p/net_node.inl | 2 +- src/p2p/p2p_protocol_defs.cpp | 2 +- src/rpc/core_rpc_server.cpp | 13 ++- src/rpc/lmq_server.cpp | 2 +- src/simplewallet/simplewallet.cpp | 24 ++--- src/wallet/wallet2.cpp | 2 +- src/wallet3/db_schema.cpp | 2 +- 23 files changed, 172 insertions(+), 189 deletions(-) create mode 100644 src/common/format.h diff --git a/external/oxen-logging b/external/oxen-logging index f54003ea4..1c00cfa9a 160000 --- a/external/oxen-logging +++ b/external/oxen-logging @@ -1 +1 @@ -Subproject commit f54003ea4d44388b66045009facc762747e7bfba +Subproject commit 1c00cfa9aef0b8e449a1746e6d2af87881910c45 diff --git a/src/common/format.h b/src/common/format.h new file mode 100644 index 000000000..59d76218a --- /dev/null +++ b/src/common/format.h @@ -0,0 +1,6 @@ +#pragma once + +#include + +// Make ""_format available globally: +using namespace oxen::log::literals; diff --git a/src/common/notify.h b/src/common/notify.h index 135315ad0..7c5f96918 100644 --- a/src/common/notify.h +++ b/src/common/notify.h @@ -32,6 +32,7 @@ #include #include #include +#include "common/format.h" #include "fs.h" namespace tools @@ -57,7 +58,7 @@ private: template static void replace_tags(std::vector& margs, std::string_view tag, const T& value, MoreTags&&... more) { - replace_tag(margs, tag, fmt::format("{}", value)); + replace_tag(margs, tag, "{}"_format(value)); if constexpr (sizeof...(MoreTags) > 0) replace_tags(margs, std::forward(more)...); } diff --git a/src/common/scoped_message_writer.cpp b/src/common/scoped_message_writer.cpp index aefcc2942..8d62d4055 100644 --- a/src/common/scoped_message_writer.cpp +++ b/src/common/scoped_message_writer.cpp @@ -1,4 +1,5 @@ #include "scoped_message_writer.h" +#include "common/format.h" namespace tools { @@ -12,7 +13,8 @@ scoped_message_writer::~scoped_message_writer() if (fmt::terminal_color::white == m_color) logcat->log(m_log_level, m_oss.str()); else - logcat->log(m_log_level, "{}", fmt::format(fg(m_color), m_oss.str())); + logcat->log(m_log_level, "{}", + log::detail::text_style_wrapper{fg(m_color), "{}", m_oss.str()}); std::cout << std::endl; } } diff --git a/src/crypto/fmt.h b/src/crypto/fmt.h index 5f9616e90..a8ad8a6e0 100644 --- a/src/crypto/fmt.h +++ b/src/crypto/fmt.h @@ -1,69 +1,38 @@ #pragma once #include +#include "common/format.h" #include "crypto.h" #include "hash.h" -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::public_key v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::secret_key v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::key_derivation v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::key_image v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::signature v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::ed25519_public_key v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::x25519_public_key v, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(v)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::hash h, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(h)), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(crypto::hash8 h, format_context& ctx) { - return formatter::format( - fmt::format("<{}>", tools::type_to_hex(h)), ctx); +namespace crypto { + template + constexpr bool is_hex_printable = false; + + template + constexpr bool is_hex_printable && sizeof(T) == sizeof(ec_point)>> = true; + + template <> inline constexpr bool is_hex_printable = true; + template <> inline constexpr bool is_hex_printable = true; + template <> inline constexpr bool is_hex_printable = true; + template <> inline constexpr bool is_hex_printable = true; + template <> inline constexpr bool is_hex_printable = true; + + template inline constexpr bool is_hex_printable = is_hex_printable; + template inline constexpr bool is_hex_printable = is_hex_printable; + template inline constexpr bool is_hex_printable = is_hex_printable; + + // Helper for when you are really sure you want to print a secret key (which is not printable by + // default so that you have to be explicit and can't accidentally expose one in a log + // statement). + inline std::string expose_secret(const ec_scalar& secret) { + return "<{}>"_format(tools::type_to_hex(secret)); + } +} + +template +struct fmt::formatter>> : fmt::formatter { + auto format(const T& v, format_context& ctx) { + return formatter::format("<{}>"_format(tools::type_to_hex(v)), ctx); } }; diff --git a/src/cryptonote_basic/connection_context.h b/src/cryptonote_basic/connection_context.h index d60e83c30..db67094f7 100644 --- a/src/cryptonote_basic/connection_context.h +++ b/src/cryptonote_basic/connection_context.h @@ -36,6 +36,7 @@ #include "epee/copyable_atomic.h" #include "crypto/hash.h" #include "fmt/format.h" +#include "common/format.h" using namespace std::literals; @@ -94,10 +95,11 @@ namespace cryptonote } -template -struct fmt::formatter>> : fmt::formatter { +template +struct fmt::formatter>> + : fmt::formatter { auto format(epee::net_utils::connection_context_base connection_context, format_context& ctx) { return formatter::format( - fmt::format("[{}]", epee::net_utils::print_connection_context_short(connection_context)), ctx); + "[{}]"_format(epee::net_utils::print_connection_context_short(connection_context)), ctx); } }; diff --git a/src/cryptonote_basic/cryptonote_basic.h b/src/cryptonote_basic/cryptonote_basic.h index b76e53bfa..83a69ac24 100644 --- a/src/cryptonote_basic/cryptonote_basic.h +++ b/src/cryptonote_basic/cryptonote_basic.h @@ -46,6 +46,7 @@ #include "device/device.hpp" #include "txtypes.h" #include "logging/oxen_logger.h" +#include "common/format.h" #include namespace service_nodes @@ -606,17 +607,17 @@ namespace cryptonote } template <> -struct fmt::formatter : fmt::formatter { +struct fmt::formatter : fmt::formatter { auto format(cryptonote::txtype t, format_context& ctx) { - return formatter::format( - fmt::format("{}", cryptonote::transaction::type_to_string(t)), ctx); + return formatter::format( + cryptonote::transaction::type_to_string(t), ctx); } }; template <> -struct fmt::formatter : fmt::formatter { +struct fmt::formatter : fmt::formatter { auto format(cryptonote::txversion v, format_context& ctx) { - return formatter::format( - fmt::format("{}", cryptonote::transaction::version_to_string(v)), ctx); + return formatter::format( + cryptonote::transaction::version_to_string(v), ctx); } }; diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index d016b8f11..3db50ba6c 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -270,7 +270,7 @@ namespace cryptonote bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); if (!r) { - log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", tx_public_key, ack.m_view_secret_key); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, <{}>)", tx_public_key, expose_secret(ack.m_view_secret_key)); memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation)); } @@ -281,7 +281,7 @@ namespace cryptonote r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); if (!r) { - log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], ack.m_view_secret_key); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], expose_secret(ack.m_view_secret_key)); } else { diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 583cc0eff..7759cef24 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -356,7 +356,7 @@ bool Blockchain::load_missing_blocks_into_oxen_subsystems() #ifdef ENABLE_SYSTEMD // Tell systemd that we're doing something so that it should let us continue starting up // (giving us 120s until we have to send the next notification): - sd_notify(0, ("EXTEND_TIMEOUT_USEC=120000000\nSTATUS=Recanning blockchain; height " + std::to_string(start_height + (index * BLOCK_COUNT))).c_str()); + sd_notify(0, "EXTEND_TIMEOUT_USEC=120000000\nSTATUS=Recanning blockchain; height {}"_format(start_height + (index * BLOCK_COUNT)).c_str()); #endif work_start = clock::now(); @@ -2161,7 +2161,7 @@ bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id } else { - std::string msg = fmt::format("----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid: {}", block_type, blk_height, id); + std::string msg = "----- {} BLOCK ADDED AS ALTERNATIVE ON HEIGHT {}\nid: {}"_format(block_type, blk_height, id); if (!pulse_block) fmt::format_to(std::back_inserter(msg), " PoW: {}", blk_pow.proof_of_work); fmt::format_to(std::back_inserter(msg), " difficulty {}", current_diff); diff --git a/src/cryptonote_core/oxen_name_system.h b/src/cryptonote_core/oxen_name_system.h index b12a251d4..b038c08b3 100644 --- a/src/cryptonote_core/oxen_name_system.h +++ b/src/cryptonote_core/oxen_name_system.h @@ -344,16 +344,16 @@ private: template <> struct fmt::formatter : fmt::formatter { - auto format(ons::mapping_value v, format_context& ctx) { + auto format(const ons::mapping_value& v, format_context& ctx) { return formatter::format( - fmt::format("{}", oxenc::to_hex(v.to_view())), ctx); + oxenc::to_hex(v.to_view()), ctx); } }; template <> -struct fmt::formatter : fmt::formatter { - auto format(ons::mapping_type t, format_context& ctx) { - return formatter::format( - fmt::format("{}", ons::mapping_type_str(t)), ctx); +struct fmt::formatter : fmt::formatter { + auto format(const ons::mapping_type& t, format_context& ctx) { + return formatter::format( + ons::mapping_type_str(t), ctx); } }; diff --git a/src/cryptonote_core/service_node_list.cpp b/src/cryptonote_core/service_node_list.cpp index dda30d2e7..c574de0bd 100644 --- a/src/cryptonote_core/service_node_list.cpp +++ b/src/cryptonote_core/service_node_list.cpp @@ -359,9 +359,9 @@ namespace service_nodes { // If not using portions then the hf value must be >= 19 and equal to the current blockchain hf: if (hf_version < hf::hf19_reward_batching || reg.hf != static_cast(hf_version)) - throw invalid_registration{fmt::format( + throw invalid_registration{ "Wrong registration hardfork {}; you likely need to regenerate " - "the registration for compatibility with hardfork {}", + "the registration for compatibility with hardfork {}"_format( reg.hf, static_cast(hf_version))}; } @@ -387,7 +387,7 @@ namespace service_nodes } if (!valid_fee) - throw invalid_registration{fmt::format("Operator fee is too high ({} > {})", reg.fee, + throw invalid_registration{"Operator fee is too high ({} > {})"_format(reg.fee, reg.uses_portions ? cryptonote::old::STAKING_PORTIONS : cryptonote::STAKING_FEE_BASIS)}; if (!valid_stakes) { @@ -1594,7 +1594,7 @@ namespace service_nodes std::shared_ptr quorum = get_quorum(quorum_type::checkpointing, checkpoint->height, false, alt_block ? &alt_quorums : nullptr); if (!quorum) - throw std::runtime_error{fmt::format("Failed to get testing quorum checkpoint for {} {}", block_type, cryptonote::get_block_hash(block))}; + throw std::runtime_error{"Failed to get testing quorum checkpoint for {} {}"_format(block_type, cryptonote::get_block_hash(block))}; bool failed_checkpoint_verify = !service_nodes::verify_checkpoint(block.major_version, *checkpoint, *quorum); if (alt_block && failed_checkpoint_verify) @@ -1610,7 +1610,7 @@ namespace service_nodes } if (failed_checkpoint_verify) - throw std::runtime_error{fmt::format("Service node checkpoint failed verification for {} {}", block_type, cryptonote::get_block_hash(block))}; + throw std::runtime_error{"Service node checkpoint failed verification for {} {}"_format(block_type, cryptonote::get_block_hash(block))}; } // @@ -1625,8 +1625,8 @@ namespace service_nodes { cryptonote::block prev_block; if (!find_block_in_db(m_blockchain.get_db(), block.prev_id, prev_block)) - throw std::runtime_error{fmt::format( - "Alt block {} references previous block {} not available in DB.", + throw std::runtime_error{ + "Alt block {} references previous block {} not available in DB."_format( cryptonote::get_block_hash(block), block.prev_id)}; prev_timestamp = prev_block.timestamp; @@ -1638,8 +1638,8 @@ namespace service_nodes } if (!pulse::get_round_timings(m_blockchain, height, prev_timestamp, timings)) - throw std::runtime_error{fmt::format( - "Failed to query the block data for Pulse timings to validate incoming {} at height {}", + throw std::runtime_error{ + "Failed to query the block data for Pulse timings to validate incoming {} at height {}"_format( block_type, height)}; } @@ -1699,7 +1699,7 @@ namespace service_nodes } if (!result) - throw std::runtime_error{fmt::format("Failed to verify block components for incoming {} at height {}", + throw std::runtime_error{"Failed to verify block components for incoming {} at height {}"_format( block_type, height)}; } @@ -1726,9 +1726,10 @@ namespace service_nodes if (newest_block && (now >= earliest_time && now <= latest_time)) { std::shared_ptr quorum = get_quorum(quorum_type::pulse, block_height, false, nullptr); - if (!quorum || quorum->validators.empty()) - throw std::runtime_error{fmt::format( - "Unexpected Pulse error: {}", quorum ? " quorum was not generated" : " quorum was empty")}; + if (!quorum) + throw std::runtime_error{"Unexpected Pulse error: quorum was not generated"}; + if (quorum->validators.empty()) + throw std::runtime_error{"Unexpected Pulse error: quorum was empty"}; for (size_t validator_index = 0; validator_index < service_nodes::PULSE_QUORUM_NUM_VALIDATORS; validator_index++) { @@ -2478,7 +2479,7 @@ namespace service_nodes uint64_t reward) { if (output_index >= miner_tx.vout.size()) - throw std::out_of_range{fmt::format("Output Index: {} , indexes out of bounds in vout array with size: ", + throw std::out_of_range{"Output Index: {}, indexes out of bounds in vout array with size: {}"_format( output_index, miner_tx.vout.size())}; cryptonote::tx_out const &output = miner_tx.vout[output_index]; @@ -2488,7 +2489,7 @@ namespace service_nodes // 1 ULP difference in the reward calculations. // TODO(oxen): eliminate all FP math from reward calculations if (!within_one(output.amount, reward)) - throw std::runtime_error{fmt::format("Service node reward amount incorrect. Should be {}, is: {}", cryptonote::print_money(reward), cryptonote::print_money(output.amount))}; + throw std::runtime_error{"Service node reward amount incorrect. Should be {}, is: {}"_format(cryptonote::print_money(reward), cryptonote::print_money(output.amount))}; if (!std::holds_alternative(output.target)) throw std::runtime_error{"Service node output target type should be txout_to_key"}; @@ -2505,7 +2506,7 @@ namespace service_nodes throw std::runtime_error{"Failed derive public key"}; if (var::get(output.target).key != out_eph_public_key) - throw std::runtime_error{fmt::format("Invalid service node reward at output: {}, output key, specifies wrong key", output_index)}; + throw std::runtime_error{"Invalid service node reward at output: {}, output key, specifies wrong key"_format(output_index)}; } void service_node_list::validate_miner_tx(const cryptonote::miner_tx_info& info) const @@ -2530,7 +2531,7 @@ namespace service_nodes { auto const check_block_leader_pubkey = cryptonote::get_service_node_winner_from_tx_extra(miner_tx.extra); if (block_leader.key != check_block_leader_pubkey) - throw std::runtime_error{fmt::format("Service node reward winner is incorrect! Expected {}, block has {}", block_leader.key, check_block_leader_pubkey)}; + throw std::runtime_error{"Service node reward winner is incorrect! Expected {}, block has {}"_format(block_leader.key, check_block_leader_pubkey)}; } enum struct verify_mode @@ -2552,14 +2553,14 @@ namespace service_nodes std::vector entropy = get_pulse_entropy_for_next_block(m_blockchain.get_db(), block.prev_id, block.pulse.round); quorum pulse_quorum = generate_pulse_quorum(m_blockchain.nettype(), block_leader.key, hf_version, m_state.active_service_nodes_infos(), entropy, block.pulse.round); if (!verify_pulse_quorum_sizes(pulse_quorum)) - throw std::runtime_error{fmt::format("Pulse block received but Pulse has insufficient nodes for quorum, block hash {}, height {}", cryptonote::get_block_hash(block), height)}; + throw std::runtime_error{"Pulse block received but Pulse has insufficient nodes for quorum, block hash {}, height {}"_format(cryptonote::get_block_hash(block), height)}; block_producer_key = pulse_quorum.workers[0]; mode = (block_producer_key == block_leader.key) ? verify_mode::pulse_block_leader_is_producer : verify_mode::pulse_different_block_producer; if (block.pulse.round == 0 && (mode == verify_mode::pulse_different_block_producer)) - throw std::runtime_error{fmt::format("The block producer in pulse round 0 should be the same node as the block leader: {}, actual producer: {}", block_leader.key, block_producer_key)}; + throw std::runtime_error{"The block producer in pulse round 0 should be the same node as the block leader: {}, actual producer: {}"_format(block_leader.key, block_producer_key)}; } // NOTE: Verify miner tx vout composition @@ -2595,7 +2596,7 @@ namespace service_nodes { auto info_it = m_state.service_nodes_infos.find(block_producer_key); if (info_it == m_state.service_nodes_infos.end()) - throw std::runtime_error{fmt::format("The pulse block producer for round {:d} is not current a Service Node: {}", block.pulse.round, block_producer_key)}; + throw std::runtime_error{"The pulse block producer for round {:d} is not current a Service Node: {}"_format(block.pulse.round, block_producer_key)}; block_producer = info_it->second; expected_vouts_size = mode == verify_mode::pulse_different_block_producer && reward_parts.miner_fee > 0 @@ -2617,7 +2618,7 @@ namespace service_nodes } if (miner_tx.vout.size() != expected_vouts_size) - throw std::runtime_error{fmt::format("Expected {} block, the miner TX specifies a different amount of outputs vs the expected: {}, miner tx outputs: {}", + throw std::runtime_error{"Expected {} block, the miner TX specifies a different amount of outputs vs the expected: {}, miner tx outputs: {}"_format( mode == verify_mode::miner ? "miner"sv : mode == verify_mode::batched_sn_rewards ? "batch reward"sv : mode == verify_mode::pulse_block_leader_is_producer ? "pulse"sv : @@ -2626,7 +2627,8 @@ namespace service_nodes miner_tx.vout.size())}; if (hf_version >= hf::hf16_pulse && reward_parts.base_miner != 0) - throw std::runtime_error{fmt::format("Miner reward is incorrect expected 0 reward, block specified {}", cryptonote::print_money(reward_parts.base_miner))}; + throw std::runtime_error{"Miner reward is incorrect expected 0 reward, block specified {}"_format( + cryptonote::print_money(reward_parts.base_miner))}; // NOTE: Verify Coinbase Amounts switch(mode) @@ -2731,7 +2733,7 @@ namespace service_nodes auto paid_amount = vout.amount * cryptonote::BATCH_REWARD_FACTOR; total_payout_in_vouts += paid_amount; if (paid_amount != batch_payment.amount) - throw std::runtime_error{fmt::format("Batched reward payout incorrect: expected {}, not {}", batch_payment.amount, paid_amount)}; + throw std::runtime_error{"Batched reward payout incorrect: expected {}, not {}"_format(batch_payment.amount, paid_amount)}; crypto::public_key out_eph_public_key{}; if (!cryptonote::get_deterministic_output_key(batch_payment.address_info.address, deterministic_keypair, vout_index, out_eph_public_key)) @@ -2742,7 +2744,7 @@ namespace service_nodes throw std::runtime_error{"Output Ephermeral Public Key does not match (payment to wrong recipient)"}; } if (total_payout_in_vouts != total_payout_in_our_db) - throw std::runtime_error{fmt::format("Total service node reward amount incorrect: expected {}, not {}", total_payout_in_our_db, total_payout_in_vouts)}; + throw std::runtime_error{"Total service node reward amount incorrect: expected {}, not {}"_format(total_payout_in_our_db, total_payout_in_vouts)}; } break; } @@ -2789,7 +2791,7 @@ namespace service_nodes throw std::runtime_error{"Received alt block but couldn't find parent state in historical state"}; if (starting_state->block_hash != block.prev_id) - throw std::runtime_error{fmt::format("Unexpected state_t's hash: {}, does not match the block prev hash: {}", + throw std::runtime_error{"Unexpected state_t's hash: {}, does not match the block prev hash: {}"_format( starting_state->block_hash, block.prev_id)}; // NOTE: Generate the next Service Node list state from this Alt block. @@ -3960,11 +3962,11 @@ namespace service_nodes cmd.clear(); if (make_friendly) - cmd += fmt::format("{} ({}):\n\n", + cmd += "{} ({}):\n\n"_format( tr("Run this command in the operator's wallet"), cryptonote::get_account_address_as_str(nettype, false, reg.reserved[0].first)); - cmd += fmt::format("register_service_node {} {} {} {}", + cmd += "register_service_node {} {} {} {}"_format( tools::join(" ", args), reg.hf, tools::type_to_hex(reg.service_node_pubkey), diff --git a/src/cryptonote_core/service_node_quorum_cop.h b/src/cryptonote_core/service_node_quorum_cop.h index 0d44fc3ea..9fdfcf116 100644 --- a/src/cryptonote_core/service_node_quorum_cop.h +++ b/src/cryptonote_core/service_node_quorum_cop.h @@ -169,7 +169,6 @@ namespace service_nodes template <> struct fmt::formatter : fmt::formatter { auto format(service_nodes::quorum quorum, format_context& ctx) { - return formatter::format( - fmt::format("{}", quorum.to_string()), ctx); + return formatter::format(quorum.to_string(), ctx); } }; diff --git a/src/cryptonote_core/service_node_voting.h b/src/cryptonote_core/service_node_voting.h index 6092489df..3245bbe64 100644 --- a/src/cryptonote_core/service_node_voting.h +++ b/src/cryptonote_core/service_node_voting.h @@ -63,7 +63,7 @@ namespace service_nodes _count }; - inline std::string to_string(const quorum_type& q) + inline constexpr std::string_view to_string(const quorum_type& q) { switch(q) { @@ -178,10 +178,9 @@ namespace service_nodes }; // namespace service_nodes // template <> -struct fmt::formatter : fmt::formatter { +struct fmt::formatter : fmt::formatter { auto format(service_nodes::quorum_type quorum, format_context& ctx) { - return formatter::format( - fmt::format("{}", to_string(quorum)), ctx); + return formatter::format(to_string(quorum), ctx); } }; diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.h b/src/cryptonote_protocol/cryptonote_protocol_handler.h index e3044dd70..715deff9b 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.h +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.h @@ -59,7 +59,7 @@ template <> struct fmt::formatter : fmt::formatter { auto format(cryptonote::cryptonote_connection_context connection_context, format_context& ctx) { return formatter::format( - fmt::format("[{}]", epee::net_utils::print_connection_context_short(connection_context)), ctx); + "[{}]"_format(epee::net_utils::print_connection_context_short(connection_context)), ctx); } }; diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.inl b/src/cryptonote_protocol/cryptonote_protocol_handler.inl index bfd48fe13..cc5a8dd39 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.inl +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.inl @@ -213,7 +213,7 @@ namespace cryptonote seconds_f connection_time{now - cntxt.m_started}; ss << std::setw(30) << std::left << std::string(cntxt.m_is_income ? " [INC]":"[OUT]") + cntxt.m_remote_address.str() - << std::setw(20) << fmt::format("{:016x}", peer_id) + << std::setw(20) << "{:016x}"_format(peer_id) << std::setw(30) << std::to_string(cntxt.m_recv_cnt) + "(" + std::to_string(tools::to_seconds(now - cntxt.m_last_recv)) + ")" + "/" + std::to_string(cntxt.m_send_cnt) + "(" + std::to_string(tools::to_seconds(now - cntxt.m_last_send)) + ")" << std::setw(25) << get_protocol_state_string(cntxt.m_state) @@ -270,7 +270,7 @@ namespace cryptonote cnx.ip = cnx.host; cnx.port = std::to_string(cntxt.m_remote_address.as().port()); } - cnx.peer_id = fmt::format("{:016x}", peer_id); + cnx.peer_id = "{:016x}"_format(peer_id); cnx.live_time = std::chrono::duration_cast(now - cntxt.m_started); cnx.recv_idle_time = std::chrono::duration_cast(now - std::max(cntxt.m_started, cntxt.m_last_recv)); @@ -446,7 +446,8 @@ namespace cryptonote int64_t diff = static_cast(hshd.current_height) - static_cast(curr_height); uint64_t abs_diff = std::abs(diff); uint64_t max_block_height = std::max(hshd.current_height, curr_height); - std::string sync_msg = fmt::format("{}Sync data returned a new top block candidate: {} -> {} [Your node is {} blocks ({} {})]\nSYNCHRONIZATION started", context, curr_height, hshd.current_height, abs_diff, tools::get_human_readable_timespan(abs_diff*TARGET_BLOCK_TIME), (0 <= diff ? "behind" : "ahead")); + std::string sync_msg = "{}Sync data returned a new top block candidate: {} -> {} [Your node is {} blocks ({} {})]\nSYNCHRONIZATION started"_format( + context, curr_height, hshd.current_height, abs_diff, tools::get_human_readable_timespan(abs_diff*TARGET_BLOCK_TIME), (0 <= diff ? "behind" : "ahead")); if (is_initial) log::info(globallogcat, fg(fmt::terminal_color::cyan), sync_msg); else diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index 5a3ead82a..fc4bc9712 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -145,17 +145,19 @@ namespace { if (dt < 90s) s = std::to_string(dt.count()) + (abbreviate ? "sec" : dt == 1s ? " second" : " seconds"); else if (dt < 90min) - s = fmt::format("{:.1f}{:s}", ((float)dt.count()/60), abbreviate ? "min" : " minutes"); + s = "{:.1f}{:s}"_format(dt.count()/60.0, abbreviate ? "min" : " minutes"); else if (dt < 36h) - s = fmt::format("{:.1f}{:s}", ((float)dt.count()/3600), abbreviate ? "hr" : " hours"); + s = "{:.1f}{:s}"_format(dt.count()/3600.0, abbreviate ? "hr" : " hours"); else - s = fmt::format("{:.1f} days", ((float)dt.count()/86400)); + s = "{:.1f} days"_format(dt.count()/86400.0); if (abbreviate) { if (ago < 0s) - return s + " (in fut.)"; - return s; + s += " (in fut.)"; + } else { + s += ' '; + s += (ago < 0s ? "in the future" : "ago"); } - return s + " " + (ago < 0s ? "in the future" : "ago"); + return s; } std::string get_human_time_ago(std::time_t t, std::time_t now, bool abbreviate = false) { @@ -171,10 +173,10 @@ namespace { time_t now = std::time(nullptr); time_t last_seen = peer.value("last_seen", 0); - tools::msg_writer() << fmt::format("{:<10} {:016x} {:<30} {}", + tools::msg_writer() << "{:<10} {:016x} {:<30} {}"_format( prefix, peer["id"].get(), - fmt::format("{}:{}", peer["host"].get(), peer["port"].get()), + "{}:{}"_format(peer["host"].get(), peer["port"].get()), last_seen == 0 ? "never" : get_human_time_ago(last_seen, now)); return true; } @@ -182,7 +184,7 @@ namespace { template void print_peers(std::string_view prefix, const json& peers, size_t& limit, Args&&... args) { if (limit > 0) - tools::msg_writer() << fmt::format("{:<10} {:<16} {:<30} {}", + tools::msg_writer() << "{:<10} {:<16} {:<30} {}"_format( "Type", "Peer id", "Remote address", "Last seen"); for (auto it = peers.begin(); it != peers.end() && limit > 0; it++) if (print_peer(prefix, *it, std::forward(args)...)) @@ -393,10 +395,10 @@ bool rpc_command_executor::show_difficulty() { static std::string get_mining_speed(uint64_t hr) { - if (hr >= 1e9) return fmt::format("{:.2f} GH/s", hr*1e-9); - if (hr >= 1e6) return fmt::format("{:.2f} MH/s", hr*1e-6); - if (hr >= 1e3) return fmt::format("{:.2f} kH/s", hr*1e-3); - return fmt::format("{:d} H/s", hr); + if (hr >= 1e9) return "{:.2f} GH/s"_format(hr*1e-9); + if (hr >= 1e6) return "{:.2f} MH/s"_format(hr*1e-6); + if (hr >= 1e3) return "{:.2f} kH/s"_format(hr*1e-3); + return "{:d} H/s"_format(hr); } static std::ostream& print_fork_extra_info(std::ostream& o, uint64_t t, uint64_t now, std::chrono::seconds block_time) @@ -414,8 +416,8 @@ static std::ostream& print_fork_extra_info(std::ostream& o, uint64_t t, uint64_t if (dblocks <= 30) return o << dblocks << " blocks)"; if (dblocks <= blocks_per_day / 2) - return o << fmt::format("{:.1f} hours)", dblocks / blocks_per_day * 24); - return o << fmt::format("{:.1f} days)", dblocks / blocks_per_day); + return o << "{:.1f} hours)"_format(dblocks / blocks_per_day * 24); + return o << "{:.1f} days)"_format(dblocks / blocks_per_day); } static float get_sync_percentage(uint64_t height, uint64_t target_height) @@ -497,7 +499,7 @@ bool rpc_command_executor::show_status() { std::ostringstream str; str << "Height: " << height; if (height != net_height) - str << fmt::format("/{} ({:.1f}%)", net_height, get_sync_percentage(height, net_height)); + str << "/{} ({:.1f}%)"_format(net_height, get_sync_percentage(height, net_height)); auto net = info["nettype"].get(); if (net == "testnet") str << " ON TESTNET"; @@ -633,7 +635,7 @@ bool rpc_command_executor::print_connections() { address, get_address_type_name(info["address_type"].get()), info["peer_id"].get(), - fmt::format("{}({}/{})", info["recv_count"].get(), + "{}({}/{})"_format(info["recv_count"].get(), tools::friendly_duration(1ms * info["recv_idle_ms"].get()), tools::friendly_duration(1ms * info["send_idle_ms"].get())), info["state"].get(), @@ -663,7 +665,7 @@ bool rpc_command_executor::print_net_stats() auto bytes = stats[in ? "total_bytes_in" : "total_bytes_out"].get(); double average = uptime > 0 ? bytes / (double) uptime : 0.0; uint64_t lim = limit[in ? "limit_down" : "limit_up"].get() * 1024; // convert to bytes, as limits are always kB/s - tools::success_msg_writer() << fmt::format("{} {} in {} packets, average {}/s = {:.2f}% of the limit of {}/s", + tools::success_msg_writer() << "{} {} in {} packets, average {}/s = {:.2f}% of the limit of {}/s"_format( in ? "Received" : "Sent", tools::get_human_readable_bytes(bytes), stats[in ? "total_packets_in" : "total_packets_out"].get(), @@ -931,14 +933,14 @@ static void print_pool(const json& txs) { lines.clear(); lines.push_back(tx["tx_hash"].get_ref() + ":"s); - lines.push_back(fmt::format("size/weight: {}/{}", tx["size"].get(), tx["weight"].get())); - lines.push_back(fmt::format("fee: {} ({}/byte)", + lines.push_back("size/weight: {}/{}"_format(tx["size"].get(), tx["weight"].get())); + lines.push_back("fee: {} ({}/byte)"_format( cryptonote::print_money(tx["fee"].get()), cryptonote::print_money(tx["fee"].get() / tx["weight"].get()))); - lines.push_back(fmt::format("received: {} ({})", tx["received_timestamp"].get(), get_human_time_ago(tx["received_timestamp"].get(), now))); + lines.push_back("received: {} ({})"_format(tx["received_timestamp"].get(), get_human_time_ago(tx["received_timestamp"].get(), now))); lines.push_back("status: " + tools::join(", ", status)); - lines.push_back(fmt::format("top required block: {} ({})", tx["max_used_height"].get(), tx["max_used_block"])); + lines.push_back("top required block: {} ({})"_format(tx["max_used_height"].get(), tx["max_used_block"])); if (tx.count("last_failed_height")) - lines.push_back(fmt::format("last failed block: {} ({})", tx["last_failed_height"].get(), tx["last_failed_block"].get())); + lines.push_back("last failed block: {} ({})"_format(tx["last_failed_height"].get(), tx["last_failed_block"].get())); if (auto extra = tx.find("extra"); extra != tx.end()) { lines.push_back("transaction extra: "); for (auto c : extra->dump(2)) { @@ -979,7 +981,7 @@ bool rpc_command_executor::print_transaction_pool(bool long_format) { tools::msg_writer() << " WARNING: spent key image has no txs associated!"; else { - tools::msg_writer() << fmt::format(" NOTE: key image for multiple transactions ({}):", tx_hashes.size()); + tools::msg_writer() << " NOTE: key image for multiple transactions ({}):"_format(tx_hashes.size()); for (const auto& txid : tx_hashes) tools::msg_writer() << " - " << txid.get(); } @@ -1015,7 +1017,7 @@ bool rpc_command_executor::print_transaction_pool_stats() { if (bytes_total > *full_reward_zone) { uint64_t backlog = (bytes_total + *full_reward_zone - 1) / *full_reward_zone; - backlog_message = fmt::format("estimated {} block ({} minutes) backlog", backlog, (backlog * cryptonote::TARGET_BLOCK_TIME / 1min)); + backlog_message = "estimated {} block ({} minutes) backlog"_format(backlog, (backlog * cryptonote::TARGET_BLOCK_TIME / 1min)); } uint64_t fee_total = pstats["fee_total"].get(); @@ -1054,7 +1056,7 @@ bool rpc_command_executor::print_transaction_pool_stats() { } constexpr auto hist_fmt = "{:>10} - {:<14} {:>7} {:>11}"sv; - tools::msg_writer() << fmt::format("{:^23} {:>7} {:>11}", "Age", "Txes", "Bytes"); + tools::msg_writer() << "{:^23} {:>7} {:>11}"_format("Age", "Txes", "Bytes"); for (size_t i = 0; i < 10; i++) tools::msg_writer() << fmt::format(hist_fmt, @@ -1077,8 +1079,8 @@ bool rpc_command_executor::start_mining(const cryptonote::account_public_address return false; tools::success_msg_writer() - << fmt::format("Mining started with {} thread(s).", std::max(num_threads, 1)) - << (num_blocks ? fmt::format(" Will stop after {} blocks", num_blocks) : ""); + << "Mining started with {} thread(s)."_format(std::max(num_threads, 1)) + << (num_blocks ? " Will stop after {} blocks"_format(num_blocks) : ""); return true; } @@ -1098,7 +1100,7 @@ bool rpc_command_executor::get_limit() return false; auto& limit = *maybe_limit; - tools::msg_writer() << fmt::format("Current limits are {} kiB/s down, {} kiB/s up", + tools::msg_writer() << "Current limits are {} kiB/s down, {} kiB/s up"_format( limit["limit_down"].get(), limit["limit_up"].get()); return true; } @@ -1113,7 +1115,7 @@ bool rpc_command_executor::set_limit(int64_t limit_down, int64_t limit_up) return false; auto& limit = *maybe_limit; - tools::success_msg_writer() << fmt::format("New limits are {} kiB/s down, {} kiB/s up", + tools::success_msg_writer() << "New limits are {} kiB/s down, {} kiB/s up"_format( limit["limit_down"].get(), limit["limit_up"].get()); return true; } @@ -1927,7 +1929,7 @@ std::optional is_invalid_staking_address( } std::string highlight_money(uint64_t amount) { - return fmt::format("\x1b[36;1m{}\x1b[0m", cryptonote::format_money(amount)); + return "\x1b[36;1m{}\x1b[0m"_format(cryptonote::format_money(amount)); }; } // anon. namespace @@ -2135,12 +2137,12 @@ bool rpc_command_executor::prepare_registration(bool force_registration) state.contributions.size() - 1 /* -1 because we already added this address to the list */); auto [result, contribution_str] = input_line_value(fmt::format( - "\n\nThe {} must stake between {} and {}.\n\n" - "How much OXEN does {} want to stake?", - is_operator ? "operator" : "next contributor", - highlight_money(min_contribution), - highlight_money(amount_left), - is_operator ? "the operator" : fmt::format("contributor {}", state.contributions.size() - 1)), + "\n\nThe {} must stake between {} and {}.\n\n" + "How much OXEN does {} want to stake?", + is_operator ? "operator" : "next contributor", + highlight_money(min_contribution), + highlight_money(amount_left), + is_operator ? "the operator" : "contributor {}"_format(state.contributions.size() - 1)), true, "/\x1b[36;1mmax\x1b[0m/\x1b[36;1mmin\x1b[0m", "max" @@ -2170,15 +2172,15 @@ bool rpc_command_executor::prepare_registration(bool force_registration) if (contribution > amount_left) { - tools::fail_msg_writer() << fmt::format( - "Invalid amount: The contribution exceeds the remaining staking requirement ({}).\n", + tools::fail_msg_writer() << + "Invalid amount: The contribution exceeds the remaining staking requirement ({}).\n"_format( highlight_money(amount_left)); break; } else if (contribution < min_contribution) { - tools::fail_msg_writer() << fmt::format( - "Invalid amount: The contribution does not meet the minimum staking requirement ({}).\n", + tools::fail_msg_writer() << + "Invalid amount: The contribution does not meet the minimum staking requirement ({}).\n"_format( highlight_money(min_contribution)); break; } @@ -2247,7 +2249,7 @@ The Service Node will not activate until the entire stake has been contributed. highlight_money(state.total_reserved_contributions), highlight_money(staking_requirement), highlight_money(amount_left), - open_spots > 1 ? fmt::format("1-{} public contributors", open_spots) : "1 public contributor" + open_spots > 1 ? "1-{} public contributors"_format(open_spots) : "1 public contributor" ); auto result = input_line_ask("Is this acceptable?"); @@ -2284,7 +2286,7 @@ The Service Node will not activate until the entire stake has been contributed. (i==0) ? "Operator" : "Contributor " + std::to_string(i), addr.substr(0, 9) + ".." + addr.substr(addr.size() - 2), cryptonote::print_money(amount), - fmt::format("{:.2f}%", amount * 100.0 / (double)staking_requirement)); + "{:.2f}%"_format(amount * 100.0 / staking_requirement)); } if (amount_left > 0) @@ -2297,8 +2299,8 @@ The Service Node will not activate until the entire stake has been contributed. i == 0 && open_spots == 1 ? cryptonote::print_money(amount_left) : i == 0 ? ">=" + cryptonote::print_money((amount_left + open_spots - 1) / open_spots) : "", - i == 0 && open_spots == 1 ? fmt::format("{:.2f}%", amount_left * 100.0 / staking_requirement) : - i == 0 ? fmt::format(">={:.2f}%", amount_left * 100.0 / staking_requirement / open_spots) : + i == 0 && open_spots == 1 ? "{:.2f}%"_format(amount_left * 100.0 / staking_requirement) : + i == 0 ? ">={:.2f}%"_format(amount_left * 100.0 / staking_requirement / open_spots) : ""); } diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index 4a75d79a7..fa41928d0 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -1209,7 +1209,7 @@ namespace nodetool static std::string peerid_to_string(peerid_type peer_id) { - return fmt::format("{:016x}", peer_id); + return "{:016x}"_format(peer_id); } //----------------------------------------------------------------------------------- diff --git a/src/p2p/p2p_protocol_defs.cpp b/src/p2p/p2p_protocol_defs.cpp index e7e7b51c8..8f223f107 100644 --- a/src/p2p/p2p_protocol_defs.cpp +++ b/src/p2p/p2p_protocol_defs.cpp @@ -12,7 +12,7 @@ namespace nodetool { time_t now = time(nullptr); std::string result; for (const auto& pe : pl) { - result += fmt::format("{:016x}\t{}\tpruning seed {}\tlast_seen {}", + result += "{:016x}\t{}\tpruning seed {}\tlast_seen {}"_format( pe.id, pe.adr.str(), pe.pruning_seed, (pe.last_seen == 0 ? std::string("never") : epee::misc_utils::get_time_interval_string(now - pe.last_seen))); } diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 1816d2403..2922057b9 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -2643,24 +2643,23 @@ namespace cryptonote::rpc { std::string our_ed25519_pubkey = tools::type_to_hex(core.get_service_keys().pub_ed25519); if (!error.empty()) { status = fmt::format("Error: {}", error); - MERROR(fmt::format("{0} reported an error: {1}. Check {0} logs for more details.", name, error)); + log::error(logcat, "{0} reported an error: {1}. Check {0} logs for more details.", name, error); update = 0; // Reset our last ping time to 0 so that we won't send a ping until we get // success back again (even if we had an earlier acceptable ping within the // cutoff time). - else if (cur_version < required) { - status = fmt::format("Outdated {}. Current: {}.{}.{} Required: {}.{}.{}", name, - cur_version[0], cur_version[1], cur_version[2], - required[0], required[1], required[2]); + } else if (cur_version < required) { + status = "Outdated {}. Current: {} Required: {}"_format( + name, fmt::join(cur_version, "."), fmt::join(required, ".")); log::error(logcat, status); } else if (!ed25519_pubkey.empty() // TODO: once lokinet & ss are always sending this we can remove this empty bypass && ed25519_pubkey != our_ed25519_pubkey) { - status = fmt::format("Invalid {} pubkey: expected {}, received {}", name, our_ed25519_pubkey, ed25519_pubkey); + status = "Invalid {} pubkey: expected {}, received {}"_format(name, our_ed25519_pubkey, ed25519_pubkey); log::error(logcat, status); } else { auto now = std::time(nullptr); auto old = update.exchange(now); bool significant = std::chrono::seconds{now - old} > lifetime; // Print loudly for the first ping after startup/expiry - auto msg = fmt::format("Received ping from {} {}.{}.{}", name, cur_version[0], cur_version[1], cur_version[2]); + auto msg = "Received ping from {} {}"_format(name, fmt::join(cur_version, ".")); if (significant) log::info(logcat, fg(fmt::terminal_color::green), "{}", msg); else diff --git a/src/rpc/lmq_server.cpp b/src/rpc/lmq_server.cpp index 9bd5a9c97..c1ce4af3b 100644 --- a/src/rpc/lmq_server.cpp +++ b/src/rpc/lmq_server.cpp @@ -309,7 +309,7 @@ static void send_notifies(Mutex& mutex, Subs& subs, const char* desc, Call call) void omq_rpc::send_block_notifications(const block& block) { auto& omq = core_.get_omq(); - std::string height = fmt::format("{}", get_block_height(block)); + std::string height = "{}"_format(get_block_height(block)); send_notifies(subs_mutex_, block_subs_, "block", [&](auto& conn, auto& sub) { omq.send(conn, "notify.block", height, std::string_view{block.hash.data, sizeof(block.hash.data)}); }); diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index ee6dc9ca1..72ad94a78 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -6406,15 +6406,15 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image // // If we aren't showing key images then all the key image details get omitted. - msg += fmt::format("Service Node: {}\n", node_info.service_node_pubkey); + msg += "Service Node: {}\n"_format(node_info.service_node_pubkey); if (node_info.requested_unlock_height != service_nodes::KEY_IMAGE_AWAITING_UNLOCK_HEIGHT) - msg += fmt::format("Unlock height: {}\n", node_info.requested_unlock_height); + msg += "Unlock height: {}\n"_format(node_info.requested_unlock_height); bool just_me = contributors.size() == 1; - auto required = fmt::format(" of {} required", cryptonote::format_money(node_info.staking_requirement)); + auto required = " of {} required"_format(cryptonote::format_money(node_info.staking_requirement)); if (!just_me) { - msg += fmt::format("Total Contributions: {}{}\n", cryptonote::format_money(total), required); + msg += "Total Contributions: {}{}\n"_format(cryptonote::format_money(total), required); required.clear(); } @@ -6423,7 +6423,7 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image msg += "Your Contribution: "; else { - msg += fmt::format("Your Contributions: {}{} in {} contributions:\n ‣ ", + msg += "Your Contributions: {}{} in {} contributions:\n ‣ "_format( cryptonote::format_money(my_total), required, me.locked_contributions.size()); @@ -6441,13 +6441,13 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image required.clear(); } if (print_key_images) - msg += fmt::format(" (Key image: {})", c.key_image); + msg += " (Key image: {})"_format(c.key_image); msg += '\n'; } if (contributors.size() > 1) { - msg += fmt::format("Other Contributions: {} from {} contributor{}:\n", + msg += "Other Contributions: {} from {} contributor{}:\n"_format( cryptonote::format_money(total - my_total), contributors.size() - 1, contributors.size() == 2 ? "" : "s"); @@ -6455,12 +6455,12 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image { const auto& contributor = contributors[i]; const auto& locked = contributor.locked_contributions; - msg += fmt::format(" • {} ({})\n", + msg += " • {} ({})\n"_format( cryptonote::format_money(contributor.amount), contributor.address); if (locked.size() == 1) { if (print_key_images) - msg += fmt::format(" Key image: {}\n", locked[0].key_image); + msg += " Key image: {}\n"_format(locked[0].key_image); } else { @@ -6469,7 +6469,7 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image msg += " ‣ "; msg += cryptonote::format_money(c.amount); if (print_key_images) - msg += fmt::format(" (Key image: {})\n", c.key_image); + msg += " (Key image: {})\n"_format(c.key_image); else msg += '\n'; } @@ -6531,9 +6531,9 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image for (const auto& black : blacklisted) { - msg += fmt::format(" • {} (Unlock height {}", cryptonote::format_money(black.amount), black.unlock_height); + msg += " • {} (Unlock height {}"_format(cryptonote::format_money(black.amount), black.unlock_height); if (print_key_images) - msg += fmt::format("; Key image: {})\n", black.key_image); + msg += "; Key image: {})\n"_format(black.key_image); else msg += ")\n"; } diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 26a7a7993..f8f9b9d29 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -4360,7 +4360,7 @@ bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_st GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, nettype, uint8_t, Uint, false, static_cast(m_nettype)); // The network type given in the program argument is inconsistent with the network type saved in the wallet THROW_WALLET_EXCEPTION_IF(static_cast(m_nettype) != field_nettype, error::wallet_internal_error, - fmt::format("{:s} wallet cannot be opened as {:s} wallet", + "{:s} wallet cannot be opened as {:s} wallet"_format( field_nettype == 0 ? "Mainnet" : field_nettype == 1 ? "Testnet" : "Devnet", m_nettype == network_type::MAINNET ? "mainnet" : m_nettype == network_type::TESTNET ? "testnet" : "devnet")); GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, segregate_pre_fork_outputs, int, Int, false, true); diff --git a/src/wallet3/db_schema.cpp b/src/wallet3/db_schema.cpp index 105ec6441..c1e23019b 100644 --- a/src/wallet3/db_schema.cpp +++ b/src/wallet3/db_schema.cpp @@ -22,7 +22,7 @@ namespace wallet { if (auto stored_nettype = this->network_type(); stored_nettype != nettype) { - std::string err = fmt::format("Loaded wallet on network type \"{}\" but db has network type \"{}\"", + std::string err = "Loaded wallet on network type \"{}\" but db has network type \"{}\""_format( cryptonote::network_type_to_string(nettype), cryptonote::network_type_to_string(stored_nettype)); //TODO: log error as well From a91774f2fc6ad6cad858151ca3657a759e6c7386 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 23 Sep 2022 12:51:57 -0300 Subject: [PATCH 08/32] Add formattable helper header This allows types to more easily opt-in to being to_string formattable without having to do a full fmt specialization. --- src/common/formattable.h | 91 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/common/formattable.h diff --git a/src/common/formattable.h b/src/common/formattable.h new file mode 100644 index 000000000..5a9e1efef --- /dev/null +++ b/src/common/formattable.h @@ -0,0 +1,91 @@ +#include +#include +#include +#include + +namespace formattable { + + // Types can opt-in to being formattable as a string by specializing this to true. Such a type + // must have one of: + // + // - a `to_string()` method on the type; when formatted we will call `val.to_string()` to format + // it as a string. + // - a `to_string(val)` function in the same namespace as the type; we will call it to format it + // as a string. + // - a `to_string(val)` function defined in the `formattable` namespace. (Prefer its own + // namespace, but sometimes that may be ugly/infeasible, e.g. if making some external library + // type printable). + // + // The function should return something string-like (string, string_view, const char*). + // + // For instance to opt-in MyType for such string formatting, use: + // + // template <> inline constexpr bool formattable::via_to_string = true; + // + // You can also partially specialize; for instance to make all derived classes of a common base + // type formattable via to_string you could do: + // + // template inline constexpr bool formattable::via_to_string>> = true; + // + template + constexpr bool via_to_string = false; + + // Scoped enums can alternatively be formatted as their underlying integer value by specializing + // this function to true: + template + constexpr bool via_underlying = false; + + namespace detail { + + template + constexpr bool has_to_string_method = false; + + template + inline constexpr bool has_to_string_method().to_string())> + > = true; + + } // namespace detail + +} // namespace formattable + + + +namespace fmt { + + template + struct formatter>> + : formatter + { + template + auto format(const T& val, FormatContext& ctx) const { + if constexpr (::formattable::detail::has_to_string_method) + return formatter::format(val.to_string(), ctx); + else { + // This `using namespace` is so that you can also put the to_string function in the + // formattable namespace if it can't go in its own namespace for some reason: + using namespace formattable; + return formatter::format(to_string(val), ctx); + } + } + }; + + template + struct formatter>> + : formatter> + { +#ifdef __cpp_lib_is_scoped_enum // C++23 + static_assert(std::is_scoped_enum_v); +#else + static_assert(std::is_enum_v && !std::is_convertible_v>, + "formattable::via_underlying type is not a scoped enum"); +#endif + template + auto format(const T& val, FormatContext& ctx) const { + using Underlying = std::underlying_type_t; + return formatter::format(static_cast(val), ctx); + } + }; + +} // namespace fmt From cec9d5db1cc5480d02f57b79b479be09e61171a2 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 23 Sep 2022 15:14:03 -0300 Subject: [PATCH 09/32] Simplify arg printing; move out of header --- src/common/command_line.cpp | 19 +++++++++++ src/common/command_line.h | 63 ++++++++++--------------------------- 2 files changed, 36 insertions(+), 46 deletions(-) diff --git a/src/common/command_line.cpp b/src/common/command_line.cpp index 24a0b45b0..b6e6028c2 100644 --- a/src/common/command_line.cpp +++ b/src/common/command_line.cpp @@ -34,6 +34,7 @@ #ifdef HAVE_READLINE # include "epee/readline_buffer.h" #endif +#include namespace command_line { @@ -104,5 +105,23 @@ void clear_screen() #endif } +bool handle_error_helper(const boost::program_options::options_description& desc, std::function parser) { + try + { + return parser(); + } + catch (const std::exception& e) + { + std::cerr << "Failed to parse arguments: " << e.what() << std::endl; + std::cerr << desc << std::endl; + return false; + } + catch (...) + { + std::cerr << "Failed to parse arguments: unknown exception" << std::endl; + std::cerr << desc << std::endl; + return false; + } +} } diff --git a/src/common/command_line.h b/src/common/command_line.h index b64f1c9ba..693b34b61 100644 --- a/src/common/command_line.h +++ b/src/common/command_line.h @@ -34,13 +34,13 @@ #include #include #include -#include #include #include #include #include "common/string_util.h" #include "common/i18n.h" +#include "common/format.h" #include "logging/oxen_logger.h" namespace command_line @@ -140,24 +140,12 @@ namespace command_line namespace { template - struct arg_stringify { - const T& v; - arg_stringify(const T& val) : v{val} {} - }; - template - std::ostream& operator<<(std::ostream& o, const arg_stringify& a) { - return o << a.v; + std::string arg_stringify(const T& a) { + return "{}"_format(a); } template - std::ostream& operator<<(std::ostream& o, const arg_stringify>& a) { - o << '{'; - bool first = true; - for (auto& x : a.v) { - if (first) first = false; - else o << ","; - o << x; - } - return o << '}'; + std::string arg_stringify(const std::vector& v) { + return "{{{}}}"_format(fmt::join(v, ",")); } } @@ -166,11 +154,11 @@ namespace command_line { auto semantic = boost::program_options::value(); if (!arg.not_use_default) { - std::ostringstream format; - format << arg_stringify{arg.depf(false, true, arg.default_value)} << ", " - << arg_stringify{arg.depf(true, true, arg.default_value)} << " if '" - << arg.ref.name << "'"; - semantic->default_value(arg.depf(arg.ref.default_value, true, arg.default_value), format.str()); + auto default_display = "{}, {} if '{}'"_format( + arg_stringify(arg.depf(false, true, arg.default_value)), + arg_stringify(arg.depf(true, true, arg.default_value)), + arg.ref.name); + semantic->default_value(arg.depf(arg.ref.default_value, true, arg.default_value), default_display); } return semantic; } @@ -182,17 +170,19 @@ namespace command_line if (!arg.not_use_default) { std::array depval; depval.fill(false); - std::ostringstream format; - format << arg_stringify{arg.depf(depval, true, arg.default_value)}; + auto default_display = arg_stringify(arg.depf(depval, true, arg.default_value)); for (size_t i = 0; i < depval.size(); ++i) { depval.fill(false); depval[i] = true; - format << ", " << arg_stringify{arg.depf(depval, true, arg.default_value)} << " if '" << arg.ref[i]->name << "'"; + fmt::format_to(std::back_inserter(default_display), + ", {} if '{}'", + arg_stringify(arg.depf(depval, true, arg.default_value)), + arg.ref[i]->name); } for (size_t i = 0; i < depval.size(); ++i) depval[i] = arg.ref[i]->default_value; - semantic->default_value(arg.depf(depval, true, arg.default_value), format.str()); + semantic->default_value(arg.depf(depval, true, arg.default_value), default_display); } return semantic; } @@ -266,26 +256,7 @@ namespace command_line return parser.run(); } - template - bool handle_error_helper(const boost::program_options::options_description& desc, F parser) - { - try - { - return parser(); - } - catch (const std::exception& e) - { - std::cerr << "Failed to parse arguments: " << e.what() << std::endl; - std::cerr << desc << std::endl; - return false; - } - catch (...) - { - std::cerr << "Failed to parse arguments: unknown exception" << std::endl; - std::cerr << desc << std::endl; - return false; - } - } + bool handle_error_helper(const boost::program_options::options_description& desc, std::function parser); template std::enable_if_t, bool> has_arg(const boost::program_options::variables_map& vm, const arg_descriptor& arg) From 4f701feaea05eeb315a6b64546964c03c98f16e7 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 23 Sep 2022 15:30:24 -0300 Subject: [PATCH 10/32] Remove nasty print-on-destruction wrapper; more fmt --- src/wallet/wallet_args.cpp | 59 ++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index bb17eaf68..61d39cd74 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -28,8 +28,8 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "wallet/wallet_args.h" -#include #include +#include #include "common/i18n.h" #include "common/util.h" #include "common/file.h" @@ -55,22 +55,8 @@ namespace wallet_args namespace log = oxen::log; -namespace -{ static auto logcat = log::Cat("wallet.wallet2"); - class Print - { - public: - Print(const std::function &p): print(p) {} - ~Print() { print(ss.str()); } - template std::ostream &operator<<(const T &t) { ss << t; return ss; } - private: - const std::function &print; - std::stringstream ss; - }; -} - // Create on-demand to prevent static initialization order fiasco issues. command_line::arg_descriptor arg_generate_from_json() { @@ -142,19 +128,24 @@ namespace auto parser = po::command_line_parser(argc, argv).options(desc_all).positional(positional_options); po::store(parser.run(), vm); - if (command_line::get_arg(vm, command_line::arg_help)) + bool help = command_line::get_arg(vm, command_line::arg_help); + bool version = command_line::get_arg(vm, command_line::arg_version); + if (help or version) { - Print(print) << "Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")\n"; - Print(print) << wallet_args::tr("This is the command line oxen wallet. It needs to connect to a oxen\n" - "daemon to work correctly.") << "\n"; - Print(print) << wallet_args::tr("Usage:") << "\n " << usage; - Print(print) << desc_visible; - should_terminate = true; - return true; - } - else if (command_line::get_arg(vm, command_line::arg_version)) - { - Print(print) << "Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")"; + print("Oxen '{}' (v{})\n"_format(OXEN_RELEASE_NAME, OXEN_VERSION_FULL)); + + if (help) + { + print("{}\n"_format(wallet_args::tr("This is the command line oxen wallet. It needs to connect to a oxen\n" + "daemon to work correctly."))); + print("{}\n {}"_format(wallet_args::tr("Usage:"), usage)); + + // Yuck. Need to replace boost::po. + std::ostringstream s; + s << desc_visible; + print(s.str()); + } + should_terminate = true; return true; } @@ -201,12 +192,12 @@ namespace oxen::logging::init(log_path, log_level); if (notice) - Print(print) << notice << "\n"; + print("{}\n"_format(notice)); if (!command_line::is_arg_defaulted(vm, arg_max_concurrency)) tools::set_max_concurrency(command_line::get_arg(vm, arg_max_concurrency)); - Print(print) << "Oxen '" << OXEN_RELEASE_NAME << "' (v" << OXEN_VERSION_FULL << ")"; + print("Oxen '{}' (v{})\n"_format(OXEN_RELEASE_NAME, OXEN_VERSION_FULL)); if (!command_line::is_arg_defaulted(vm, arg_log_level)) log::info(logcat, "Setting log level = {}", command_line::get_arg(vm, arg_log_level)); @@ -215,17 +206,15 @@ namespace const char *logs = getenv("OXEN_LOGS"); log::info(logcat, "Setting log levels = {}", (logs ? logs : "")); } - //log::info(logcat, "{}{}", wallet_args::tr("Logging to: "), log_path); - - //Print(print) << boost::format(wallet_args::tr("Logging to %s")) % log_path; + print("{}{}"_format(tr("Logging to: "), log_path)); const ssize_t lockable_memory = tools::get_lockable_memory(); if (lockable_memory >= 0 && lockable_memory < 256 * 4096) // 256 pages -> at least 256 secret keys and other such small/medium objects - Print(print) << tr("WARNING: You may not have a high enough lockable memory limit") + print(tr("WARNING: You may not have a high enough lockable memory limit") #ifdef ELPP_OS_UNIX - << ", " << tr("see ulimit -l") + + ", "s + tr("see ulimit -l") #endif - ; + ); return {std::move(vm), should_terminate}; } From 9461cfc67428e95b02fe73cf3e960aeb190c78f0 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Mon, 26 Sep 2022 10:17:41 +1000 Subject: [PATCH 11/32] wallet_api updated to use new json_rpc and logging --- src/cryptonote_basic/subaddress_index.h | 6 ++ src/wallet/api/pending_transaction.cpp | 4 +- src/wallet/api/utils.cpp | 3 +- src/wallet/api/wallet.cpp | 80 ++++++++++++------------- src/wallet/api/wallet_manager.cpp | 33 ++++------ src/wallet/wallet_args.cpp | 2 +- 6 files changed, 62 insertions(+), 66 deletions(-) diff --git a/src/cryptonote_basic/subaddress_index.h b/src/cryptonote_basic/subaddress_index.h index be82e4ae5..197a4913e 100644 --- a/src/cryptonote_basic/subaddress_index.h +++ b/src/cryptonote_basic/subaddress_index.h @@ -46,6 +46,11 @@ namespace cryptonote bool operator!=(const subaddress_index& rhs) const { return !(*this == rhs); } bool is_zero() const { return major == 0 && minor == 0; } + std::string to_string() const + { + return std::to_string(major) + '/' + std::to_string(minor); + } + BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(major) KV_SERIALIZE(minor) @@ -62,6 +67,7 @@ namespace cryptonote { return out << subaddr_index.major << '/' << subaddr_index.minor; } + } namespace std diff --git a/src/wallet/api/pending_transaction.cpp b/src/wallet/api/pending_transaction.cpp index 07f933a8b..08ec0dbac 100644 --- a/src/wallet/api/pending_transaction.cpp +++ b/src/wallet/api/pending_transaction.cpp @@ -93,7 +93,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, if (!filename.empty()) { if (std::error_code ec_ignore; fs::exists(filename, ec_ignore) && !overwrite){ m_status = {Status_Error, tr("Attempting to save transaction to file, but specified file(s) exist. Exiting to not risk overwriting. File:") + filename.u8string()}; - log::error(m_status.second); + log::error(logcat, m_status.second); return false; } bool r = w->save_tx(m_pending_tx, filename); @@ -147,7 +147,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, m_status = {Status_Error, std::string(tr("Unknown exception: ")) + e.what()}; } catch (...) { m_status = {Status_Error, tr("Unhandled exception")}; - log::error(m_status.second); + log::error(logcat, m_status.second); } return good(); diff --git a/src/wallet/api/utils.cpp b/src/wallet/api/utils.cpp index f5046bd4b..ea7247763 100644 --- a/src/wallet/api/utils.cpp +++ b/src/wallet/api/utils.cpp @@ -28,10 +28,9 @@ // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers -#include "common_defines.h" -#include "epee/misc_log_ex.h" #include "common/util.h" #include "wallet.h" +#include "common_defines.h" namespace Wallet { namespace Utils { diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index 87ae124a1..0a8e0bba3 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -153,10 +153,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { std::string tx_hash = tools::type_to_hex(txid); - log::trace(logcat, "{}: money received.{}{}", __FUNCTION__, (blink ? "blink: " : "height: "), height - << ", tx: " << tx_hash - << ", amount: " << print_money(amount) - << ", idx: " << subaddr_index); + log::trace(logcat, "{}: money received.{}{}, tx: {}, amount: {}, idx: {}", __FUNCTION__, (blink ? "blink: " : "height: "), height, tx_hash, print_money(amount), subaddr_index.to_string()); // do not signal on received tx if wallet is not syncronized completely if (m_listener && m_wallet->synchronized()) { m_listener->moneyReceived(tx_hash, amount); @@ -170,10 +167,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback std::string tx_hash = tools::type_to_hex(txid); - log::trace(logcat, "{}: unconfirmed money received. height: {}", __FUNCTION__, height - << ", tx: " << tx_hash - << ", amount: " << print_money(amount) - << ", idx: " << subaddr_index); + log::trace(logcat, "{}: unconfirmed money received. height: {}, tx: {}, amount: {}, idx: {}", __FUNCTION__, height, tx_hash, print_money(amount), subaddr_index.to_string()); // do not signal on received tx if wallet is not syncronized completely if (m_listener && m_wallet->synchronized()) { m_listener->unconfirmedMoneyReceived(tx_hash, amount); @@ -191,10 +185,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback { // TODO; std::string tx_hash = tools::type_to_hex(txid); - log::trace(logcat, "{}: money spent. height: {}", __FUNCTION__, height - << ", tx: " << tx_hash - << ", amount: " << print_money(amount) - << ", idx: " << subaddr_index); + log::trace(logcat, "{}: money spent. height: {}, tx: {}, amount: {}, idx: {}", __FUNCTION__, height, tx_hash, print_money(amount), subaddr_index.to_string()); // do not signal on sent tx if wallet is not syncronized completely if (m_listener && m_wallet->synchronized()) { m_listener->moneySpent(tx_hash, amount); @@ -409,27 +400,39 @@ uint64_t Wallet::maximumAllowedAmount() EXPORT void Wallet::init(const char *argv0, const char *default_log_base_name, const std::string& log_path, bool console) { epee::string_tools::set_module_name_and_folder(argv0); - mlog_configure(log_path.empty() ? mlog_get_default_log_path(default_log_base_name) : log_path, console); + oxen::logging::init(log_path.empty() ? default_log_base_name : log_path, log::Level::info); } EXPORT void Wallet::debug(const std::string &category, const std::string &str) { - log::debug(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + if (category.empty()) + log::debug(logcat, str); + else + log::debug(log::Cat(category), str); } EXPORT void Wallet::info(const std::string &category, const std::string &str) { - log::info(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + if (category.empty()) + log::info(logcat, str); + else + log::info(log::Cat(category), str); } EXPORT void Wallet::warning(const std::string &category, const std::string &str) { - log::warning(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + if (category.empty()) + log::warning(logcat, str); + else + log::warning(log::Cat(category), str); } EXPORT void Wallet::error(const std::string &category, const std::string &str) { - oxenlog::error(category.empty() ? logcat : oxenlog::Category(category.c_str()), str); + if (category.empty()) + log::error(logcat, str); + else + log::error(log::Cat(category), str); } ///////////////////////// WalletImpl implementation //////////////////////// @@ -479,7 +482,7 @@ EXPORT WalletImpl::~WalletImpl() { - log::info(__FUNCTION__); + log::info(logcat, "{}", __FUNCTION__); m_wallet_ptr->callback(nullptr); // Stop refresh and long poll threads stopRefresh(); @@ -508,15 +511,13 @@ bool WalletImpl::create(std::string_view path_, const std::string &password, con bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - log::trace(logcat, "wallet_path: {}", path); - log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha - << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); - + log::trace(logcat, "wallet_path: {}", path.string()); + log::trace(logcat, "keys_file_exists: {} wallet_file_exists: {}", keys_file_exists, wallet_file_exists); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting."; - log::error(error); + log::error(logcat, error); setStatusCritical(error); return false; } @@ -551,14 +552,13 @@ bool WalletImpl::createWatchOnly(std::string_view path_, const std::string &pass bool keys_file_exists; bool wallet_file_exists; tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists); - log::trace(logcat, "wallet_path: {}", path); - log::trace(logcat, "keys_file_exists: {}{}{}", std::boolalpha, keys_file_exists, std::noboolalpha - << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha); + log::trace(logcat, "wallet_path: {}", path.string()); + log::trace(logcat, "keys_file_exists: {} wallet_file_exists: {}", keys_file_exists, wallet_file_exists); // add logic to error out if new wallet requested but named wallet file exists if (keys_file_exists || wallet_file_exists) { std::string error = "attempting to generate view only wallet, but specified file(s) exist. Exiting to not risk overwriting."; - log::error(error); + log::error(logcat, error); setStatusError(error); return false; } @@ -1082,15 +1082,15 @@ std::vector* WalletImpl::listCurrentStakes() const auto main_addr = mainAddress(); for (const auto& node_info : response) - for (const auto& contributor : node_info.contributors) - if (contributor.address == main_addr) { + for (const auto& contributor : node_info["contributors"]) + if (contributor["address"] == main_addr) { auto& info = stakes->emplace_back(); - info.sn_pubkey = node_info.service_node_pubkey; - info.stake = contributor.amount; - if (node_info.requested_unlock_height != 0) - info.unlock_height = node_info.requested_unlock_height; - info.awaiting = !node_info.funded; - info.decommissioned = node_info.funded && !node_info.active; + info.sn_pubkey = node_info["service_node_pubkey"]; + info.stake = contributor["amount"]; + if (node_info["requested_unlock_height"] != 0) + info.unlock_height = node_info["requested_unlock_height"]; + info.awaiting = !node_info["funded"]; + info.decommissioned = node_info["funded"] && !node_info["active"]; } return stakes; @@ -1234,8 +1234,7 @@ EXPORT void WalletImpl::setAutoRefreshInterval(int millis) { if (millis > MAX_REFRESH_INTERVAL_MILLIS) { - log::error(logcat, "{}: invalid refresh interval {}", __FUNCTION__, millis - << " ms, maximum allowed is " << MAX_REFRESH_INTERVAL_MILLIS << " ms"); + log::error(logcat, "{}: invalid refresh interval {} ms, maximum allowed is {} ms", __FUNCTION__, millis, MAX_REFRESH_INTERVAL_MILLIS); m_refreshIntervalMillis = MAX_REFRESH_INTERVAL_MILLIS; } else { m_refreshIntervalMillis = millis; @@ -1330,8 +1329,7 @@ bool WalletImpl::importKeyImages(std::string_view filename_) { uint64_t spent = 0, unspent = 0; uint64_t height = wallet()->import_key_images_from_file(filename, spent, unspent); - log::debug(logcat, "Signed key images imported to height {}, ", height - << print_money(spent) << " spent, " << print_money(unspent) << " unspent"); + log::debug(logcat, "Signed key images imported to height {}, {} spent, {} unspent", height, print_money(spent), print_money(unspent)); } catch (const std::exception &e) { @@ -2678,7 +2676,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (!tools::hex_to_type(sn_key_str, sn_key)) { error_msg = "Failed to parse service node pubkey"; - log::error(error_msg); + log::error(logcat, error_msg); transaction->setError(error_msg); return transaction; } @@ -2687,7 +2685,7 @@ PendingTransaction* WalletImpl::stakePending(const std::string& sn_key_str, cons if (stake_result.status != tools::wallet2::stake_result_status::success) { error_msg = "Failed to create a stake transaction: " + stake_result.msg; - log::error(error_msg); + log::error(logcat, error_msg); transaction->setError(error_msg); return transaction; } diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 8ae2057a4..5db6ef118 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -188,13 +188,13 @@ std::vector WalletManagerImpl::findWallets(std::string_view path_) continue; auto filename = p.path(); - log::trace(logcat, "Checking filename: {}", filename); + log::trace(logcat, "Checking filename: {}", filename.string()); if (filename.extension() == ".keys") { // if keys file found, checking if there's wallet file itself filename.replace_extension(); if (fs::exists(filename)) { - log::trace(logcat, "Found wallet: {}", filename); + log::trace(logcat, "Found wallet: {}", filename.string()); result.push_back(filename.u8string()); } } @@ -221,26 +221,17 @@ bool WalletManagerImpl::connected(uint32_t *version) { using namespace cryptonote::rpc; try { - auto res = m_http_client.json_rpc(GET_VERSION::names()[0], {}); - if (version) *version = res.version; + auto res = m_http_client.json_rpc("get_version"); + if (version) *version = res["version"]; return true; } catch (...) {} return false; } -template -static std::optional json_rpc(cryptonote::rpc::http_client& http, const typename RPC::request& req = {}) +static nlohmann::json get_info(cryptonote::rpc::http_client& http) { - using namespace cryptonote::rpc; - try { return http.json_rpc(RPC::names()[0], req); } - catch (...) {} - return std::nullopt; -} - -static std::optional get_info(cryptonote::rpc::http_client& http) -{ - return json_rpc(http); + return http.json_rpc("get_info"); } @@ -248,7 +239,7 @@ EXPORT uint64_t WalletManagerImpl::blockchainHeight() { auto res = get_info(m_http_client); - return res ? res->height : 0; + return res ? res["height"].get() : 0; } EXPORT @@ -257,14 +248,14 @@ uint64_t WalletManagerImpl::blockchainTargetHeight() auto res = get_info(m_http_client); if (!res) return 0; - return std::max(res->target_height, res->height); + return std::max(res["target_height"].get(), res["height"].get()); } EXPORT uint64_t WalletManagerImpl::blockTarget() { auto res = get_info(m_http_client); - return res ? res->target : 0; + return res ? res["target"].get() : 0; } ///////////////////// WalletManagerFactory implementation ////////////////////// @@ -284,13 +275,15 @@ WalletManagerBase *WalletManagerFactory::getWalletManager() EXPORT void WalletManagerFactory::setLogLevel(int level) { - mlog_set_log_level(level); + auto log_level = oxen::logging::parse_level(level); + if (log_level.has_value()) + log::reset_level(*log_level); } EXPORT void WalletManagerFactory::setLogCategories(const std::string &categories) { - mlog_set_log(categories.c_str()); + oxen::logging::process_categories_string(categories); } diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index 61d39cd74..d98e0d913 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -89,7 +89,7 @@ namespace wallet_args _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif - const command_line::arg_descriptor arg_log_level = {"log-level", "0-4 or categories", ""}; + const command_line::arg_descriptor arg_log_level = {"log-level", "0-4 or categories", "warning"}; const command_line::arg_descriptor arg_max_log_file_size = {"max-log-file-size", "Specify maximum log file size [B]", 50}; const command_line::arg_descriptor arg_max_log_files = {"max-log-files", "Specify maximum number of rotated log files to be saved (no limit by setting to 0)", 50}; const command_line::arg_descriptor arg_max_concurrency = {"max-concurrency", wallet_args::tr("Max number of threads to use for a parallel job"), DEFAULT_MAX_CONCURRENCY}; From 9d093f1c5a71297bc83d9ad4199aa21d049e4ff4 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Mon, 26 Sep 2022 12:09:54 +1000 Subject: [PATCH 12/32] update windows builds --- src/common/command_line.cpp | 3 +++ src/common/expect.cpp | 2 +- src/common/file.cpp | 4 ++-- src/common/signal_handler.h | 6 +++++- src/daemon/main.cpp | 2 +- src/daemonizer/CMakeLists.txt | 1 + 6 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/common/command_line.cpp b/src/common/command_line.cpp index b6e6028c2..a6a7a5550 100644 --- a/src/common/command_line.cpp +++ b/src/common/command_line.cpp @@ -35,6 +35,9 @@ # include "epee/readline_buffer.h" #endif #include +#ifdef _WIN32 +#include "windows.h" +#endif namespace command_line { diff --git a/src/common/expect.cpp b/src/common/expect.cpp index 6bb7d2a02..79f8b266a 100644 --- a/src/common/expect.cpp +++ b/src/common/expect.cpp @@ -48,7 +48,7 @@ namespace detail error_msg.append("thrown at "); // remove path, get just filename + extension - error_msg.append(fs::path(file).filename().c_str()); + error_msg.append(fs::path(file).filename().string()); error_msg.push_back(':'); error_msg.append(std::to_string(line)); diff --git a/src/common/file.cpp b/src/common/file.cpp index 037991f1b..87f8b2355 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -208,14 +208,14 @@ namespace tools { memset(&ov, 0, sizeof(ov)); if (!LockFileEx(m_fd, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ov)) { - log::error(logcat, "Failed to lock {}: {}", filename, std::error_code(GetLastError(), std::system_category())); + log::error(logcat, "Failed to lock {}: {}", filename, std::error_code(GetLastError(), std::system_category()).message()); CloseHandle(m_fd); m_fd = INVALID_HANDLE_VALUE; } } else { - log::error(logcat, "Failed to open {}: {}", filename, std::error_code(GetLastError(), std::system_category())); + log::error(logcat, "Failed to open {}: {}", filename, std::error_code(GetLastError(), std::system_category()).message()); } #else m_fd = open(filename.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666); diff --git a/src/common/signal_handler.h b/src/common/signal_handler.h index c37f40a48..f1588854a 100644 --- a/src/common/signal_handler.h +++ b/src/common/signal_handler.h @@ -4,6 +4,10 @@ #include #include #include "logging/oxen_logger.h" +#ifdef _WIN32 +#include "windows.h" +#endif + namespace tools { @@ -16,7 +20,7 @@ namespace tools { template static bool install(T t) { -#if defined(WIN32) +#ifdef _WIN32 bool r = TRUE == ::SetConsoleCtrlHandler(&win_handler, TRUE); if (r) { diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp index fe146670d..6103d001a 100644 --- a/src/daemon/main.cpp +++ b/src/daemon/main.cpp @@ -310,7 +310,7 @@ int main(int argc, char const * argv[]) if (log_file_path.is_relative()) log_file_path = fs::absolute(data_dir / log_file_path); - oxen::logging::init(log_file_path, log_level); + oxen::logging::init(log_file_path.string(), log_level); logs_initialized = true; diff --git a/src/daemonizer/CMakeLists.txt b/src/daemonizer/CMakeLists.txt index e33108fe7..6f8c2f3b5 100644 --- a/src/daemonizer/CMakeLists.txt +++ b/src/daemonizer/CMakeLists.txt @@ -38,6 +38,7 @@ if(MSVC OR MINGW) filesystem Boost::program_options PRIVATE + logging extra) else() # Do-nothing library target From 23dc129dc7687b36fab4789b05cc56bc0bbb05a3 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Mon, 26 Sep 2022 14:58:46 +1000 Subject: [PATCH 13/32] silence unused variable error for if constexpr --- src/rpc/core_rpc_server.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 2922057b9..921ce7ae6 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -548,7 +548,7 @@ namespace cryptonote::rpc { // a single one we want just the value itself; this does that. Returns a reference to the // assigned value (whether as a top-level value or array element). template - json& set(const std::string& key, T&& value, bool binary = is_binary_parameter || is_binary_container) { + json& set(const std::string& key, T&& value, [[maybe_unused]] bool binary = is_binary_parameter || is_binary_container) { auto* x = &entry[key]; if (!x->is_null() && !x->is_array()) x = &(entry[key] = json::array({std::move(*x)})); From 1217a43e4f40a4c90515d9ddc12e3f7f6e70e261 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Tue, 27 Sep 2022 07:35:11 +1000 Subject: [PATCH 14/32] bump readme copyright --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6735a9785..d85c0cf01 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Oxen -Copyright (c) 2018-2021 The Oxen Project. +Copyright (c) 2018-2022 The Oxen Project. Portions Copyright (c) 2014-2019 The Monero Project. Portions Copyright (c) 2012-2013 The Cryptonote developers. From a86995c0572b528fba87029262924ff777324c37 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 26 Sep 2022 18:47:38 -0300 Subject: [PATCH 15/32] sqlite3: update to latest; run autoreconf before configure At some point the default automake version changed to 1.16, which bionic doesn't support, so run autoreconf first to make sure it'll work. --- cmake/StaticBuild.cmake | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cmake/StaticBuild.cmake b/cmake/StaticBuild.cmake index 16d406897..485ea72da 100644 --- a/cmake/StaticBuild.cmake +++ b/cmake/StaticBuild.cmake @@ -27,11 +27,11 @@ set(READLINE_SOURCE readline-${READLINE_VERSION}.tar.gz) set(READLINE_HASH SHA512=27790d0461da3093a7fee6e89a51dcab5dc61928ec42e9228ab36493b17220641d5e481ea3d8fee5ee0044c70bf960f55c7d3f1a704cf6b9c42e5c269b797e00 CACHE STRING "readline source hash") -set(SQLITE3_VERSION 3390200 CACHE STRING "sqlite3 version") +set(SQLITE3_VERSION 3390300 CACHE STRING "sqlite3 version") set(SQLITE3_MIRROR ${LOCAL_MIRROR} https://www.sqlite.org/2022 CACHE STRING "sqlite3 download mirror(s)") set(SQLITE3_SOURCE sqlite-autoconf-${SQLITE3_VERSION}.tar.gz) -set(SQLITE3_HASH SHA512=c16b50ade3c182d5473014ac0a51e2bb8a5cfc46e532c2bda77ae4d530336e2b57aa4f12dccb6aa2148d60e9289305bf20842ac95dc52f2d31df8eb5f0599de6 +set(SQLITE3_HASH SHA512=f5f1f275ca7def6e1971d0152852468b89f2759d6fc2dda42b6e47646d65c7d8c454a9accd4ac900e171908114a9164c722314b90fb2ca422b99603158f9ce3e CACHE STRING "sqlite3 source hash") if(SQLITE3_VERSION MATCHES "^([0-9]+)(0([0-9])|([1-9][0-9]))(0([0-9])|([1-9][0-9]))[0-9][0-9]$") @@ -346,6 +346,8 @@ set(Boost_VERSION ${BOOST_VERSION}) build_external(sqlite3 BUILD_COMMAND true + CONFIGURE_COMMAND autoreconf -ivf && ./configure ${cross_host} --disable-shared --prefix=${DEPS_DESTDIR} --with-pic + "CC=${deps_cc}" "CXX=${deps_cxx}" "CFLAGS=${deps_CFLAGS}" "CXXFLAGS=${deps_CXXFLAGS}" ${cross_extra} INSTALL_COMMAND make install-includeHEADERS install-libLTLIBRARIES) add_static_target( SQLite::SQLite3 sqlite3_external libsqlite3.a) From e23514e093a25bef6d13ae776297668693fc8390 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 26 Sep 2022 23:37:09 -0300 Subject: [PATCH 16/32] Fix cmake 3.24 idiotic behaviour cmake 3.24 defaults to ignoring all archive timestamps, which completely breaks autotools packages (which rely on timestamps to know when they need to be autoreconf'd). Override this stupid default. --- cmake/StaticBuild.cmake | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/cmake/StaticBuild.cmake b/cmake/StaticBuild.cmake index 485ea72da..84ddc0084 100644 --- a/cmake/StaticBuild.cmake +++ b/cmake/StaticBuild.cmake @@ -223,6 +223,14 @@ function(build_external target) endforeach() string(REPLACE ___TARGET___ ${target} arg_BUILD_BYPRODUCTS "${arg_BUILD_BYPRODUCTS}") + set(externalproject_extra) + if(NOT CMAKE_VERSION VERSION_LESS 3.24) + # Default in cmake 3.24+ is to not extract timestamps for ExternalProject, which breaks pretty + # much every autotools package (which thinks it must reconfigure) because timestamps got + # updated). + list(APPEND externalproject_extra DOWNLOAD_EXTRACT_TIMESTAMP ON) + endif() + string(TOUPPER "${target}" prefix) expand_urls(urls ${${prefix}_SOURCE} ${${prefix}_MIRROR}) ExternalProject_Add("${target}${arg_TARGET_SUFFIX}_external" @@ -237,6 +245,7 @@ function(build_external target) BUILD_COMMAND ${arg_BUILD_COMMAND} INSTALL_COMMAND ${arg_INSTALL_COMMAND} BUILD_BYPRODUCTS ${arg_BUILD_BYPRODUCTS} + ${externalproject_extra} ) endfunction() @@ -346,8 +355,6 @@ set(Boost_VERSION ${BOOST_VERSION}) build_external(sqlite3 BUILD_COMMAND true - CONFIGURE_COMMAND autoreconf -ivf && ./configure ${cross_host} --disable-shared --prefix=${DEPS_DESTDIR} --with-pic - "CC=${deps_cc}" "CXX=${deps_cxx}" "CFLAGS=${deps_CFLAGS}" "CXXFLAGS=${deps_CXXFLAGS}" ${cross_extra} INSTALL_COMMAND make install-includeHEADERS install-libLTLIBRARIES) add_static_target( SQLite::SQLite3 sqlite3_external libsqlite3.a) From c5157aa15ca1e25211e07c25e9059a6a44a3b54a Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 27 Sep 2022 00:09:03 -0300 Subject: [PATCH 17/32] For submodules for fmt/spdlog on macos builds The system-installed versions apparently have some issues. --- .drone.jsonnet | 1 + 1 file changed, 1 insertion(+) diff --git a/.drone.jsonnet b/.drone.jsonnet index e834bea9c..70b0cebac 100644 --- a/.drone.jsonnet +++ b/.drone.jsonnet @@ -144,6 +144,7 @@ local mac_builder(name, 'mkdir build', 'cd build', 'cmake .. -G Ninja -DCMAKE_CXX_FLAGS=-fcolor-diagnostics -DCMAKE_BUILD_TYPE=' + build_type + ' ' + + '-DOXEN_LOGGING_FORCE_SUBMODULES=ON' + '-DLOCAL_MIRROR=https://builds.lokinet.dev/deps -DUSE_LTO=' + (if lto then 'ON ' else 'OFF ') + (if werror then '-DWARNINGS_AS_ERRORS=ON ' else '') + (if build_tests || run_tests then '-DBUILD_TESTS=ON ' else '') + From 7eb357971bba81dd64576afac0e8f910145dac24 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 27 Sep 2022 00:11:54 -0300 Subject: [PATCH 18/32] Make sure we are using fmt/spdlog submodules for static builds Otherwise we can end up linking against libfmt and/or libspdlog --- external/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 60671626e..b9b80aa9e 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -69,6 +69,9 @@ add_subdirectory(date EXCLUDE_FROM_ALL) set(JSON_BuildTests OFF CACHE INTERNAL "") set(JSON_MultipleHeaders ON CACHE BOOL "") # Allows multi-header nlohmann use add_subdirectory(nlohmann-json EXCLUDE_FROM_ALL) +if(BUILD_STATIC_DEPS) + set(OXEN_LOGGING_FORCE_SUBMODULES TRUE CACHE BOOL "" FORCE) +endif() add_subdirectory(oxen-logging) # uSockets doesn't really have a proper build system (just a very simple Makefile) so build it From 86dff557a53c781f7b6aea4c0181bc979872f839 Mon Sep 17 00:00:00 2001 From: Sean Darcy Date: Tue, 27 Sep 2022 15:33:01 +1000 Subject: [PATCH 19/32] trace noop in release build --- tests/unit_tests/logging.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit_tests/logging.cpp b/tests/unit_tests/logging.cpp index c67d951ef..bdffb7e11 100644 --- a/tests/unit_tests/logging.cpp +++ b/tests/unit_tests/logging.cpp @@ -138,7 +138,9 @@ TEST(logging, all) ASSERT_TRUE(str.find("fatal") != std::string::npos); ASSERT_TRUE(str.find("error") != std::string::npos); ASSERT_TRUE(str.find("debug") != std::string::npos); + #ifndef NDEBUG ASSERT_TRUE(str.find("trace") != std::string::npos); + #endif cleanup(); } From dbf6c2dd4513c448b16f30b6562bdc7a2a5fee32 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 27 Sep 2022 17:27:18 -0300 Subject: [PATCH 20/32] Make ghc::filesystem fmt-formattable --- src/common/fs.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/common/fs.h b/src/common/fs.h index ebb27ea7b..456b96eb3 100644 --- a/src/common/fs.h +++ b/src/common/fs.h @@ -20,6 +20,16 @@ namespace fs { #else #include +#include "formattable.h" + namespace fs = ghc::filesystem; +namespace formattable { + template <> inline constexpr bool via_to_string = true; + + std::string to_string(const ghc::filesystem::path& path) { + return path.string(); + } +} + #endif From 72a356798d53d8b44a109168149dc61686ce9158 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 27 Sep 2022 19:21:55 -0300 Subject: [PATCH 21/32] apple now links everything to libobjc.dylib now, hurray for great success! --- utils/build_scripts/drone-check-static-libs.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/build_scripts/drone-check-static-libs.sh b/utils/build_scripts/drone-check-static-libs.sh index 3f15c2b05..4d2e17ef5 100755 --- a/utils/build_scripts/drone-check-static-libs.sh +++ b/utils/build_scripts/drone-check-static-libs.sh @@ -9,7 +9,7 @@ anybad= for bin in oxend oxen-{wallet-{cli,rpc},gen-trusted-multisig,blockchain-{ancestry,depth,export,import,mark-spent-outputs,stats,usage}}; do bad= if [ "$DRONE_STAGE_OS" == "darwin" ]; then - if otool -L bin/$bin | grep -Ev '^bin/'$bin':|^\t(/usr/lib/libSystem\.|/usr/lib/libc\+\+\.|/System/Library/Frameworks/(AppKit|CoreFoundation|IOKit|SystemConfiguration))'; then + if otool -L bin/$bin | grep -Ev '^bin/'$bin':|^\t(/usr/lib/lib(System|c\+\+|objc)\.|/System/Library/Frameworks/(AppKit|CoreFoundation|IOKit|SystemConfiguration))'; then bad=1 fi elif [ "$DRONE_STAGE_OS" == "linux" ]; then From 9e4e4976fae013b59358690ef6907c93285055ef Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 27 Sep 2022 20:38:26 -0300 Subject: [PATCH 22/32] Remove unnecessary move gcc is (rightly) warning: the value here is already a temporary, so moving doesn't do anything useful (but also prevents copy elision). --- src/wallet/wallet2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index f8f9b9d29..ff2167c39 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -3731,7 +3731,7 @@ bool wallet2::get_output_blacklist(std::vector &blacklist) try { auto res = m_http_client.json_rpc("get_output_blacklist", {}); - blacklist = std::move(res["blacklist"].get>()); + blacklist = res["blacklist"].get>(); } catch (...) { log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); log::warning(logcat, "Failed to request output blacklist: no connection to daemon"); From 6b5a05d3f6f652e0c2caaa3ef091bc03197351b1 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 29 Sep 2022 18:54:38 -0300 Subject: [PATCH 23/32] Remove unused variable --- src/cryptonote_basic/miner.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cryptonote_basic/miner.h b/src/cryptonote_basic/miner.h index fb7a905bd..d5ab80250 100644 --- a/src/cryptonote_basic/miner.h +++ b/src/cryptonote_basic/miner.h @@ -106,7 +106,6 @@ namespace cryptonote std::atomic m_starter_nonce; difficulty_type m_diffic = 0; uint64_t m_height = 0; - std::atomic m_thread_index; std::atomic m_threads_total = 0; std::atomic m_pausers_count = 0; std::mutex m_miners_count_mutex; From 0cf55f39455264afa8aebfbd6fd0cfd729450af7 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Wed, 28 Sep 2022 13:05:05 -0300 Subject: [PATCH 24/32] Add garbage to make it work on a garbage OS - Don't touch because it touches std::filesystem which makes macOS throw a hissy fit and refuse to compile. - int_to_string is broken on macOS because it uses std::to_chars which makes macos throw a hissy fit like a cranky old female cat seeing a kitten if it sees it. - wallet3 was using std::filesystem and std::visit, both of which make macos throw a hissy fit. (There is a pattern here). Apply the dumb fs::path and var::visit workarounds needed to appease this garbage OS. - use var::get (from oxenc/variant.h) instead of std::get because, oh yeah, we need to support a garbage OS that Apple themselves don't even properly support. Yay! --- src/blockchain_db/lmdb/db_lmdb.cpp | 1 - src/blockchain_utilities/CMakeLists.txt | 2 +- src/blockchain_utilities/blockchain_ancestry.cpp | 1 - .../blockchain_blackball.cpp | 1 - src/blockchain_utilities/blockchain_depth.cpp | 1 - src/blockchain_utilities/blockchain_export.cpp | 1 - src/blockchain_utilities/blockchain_import.cpp | 1 - src/blockchain_utilities/blockchain_stats.cpp | 1 - src/blockchain_utilities/blockchain_usage.cpp | 1 - src/blockchain_utilities/blocksdat_file.cpp | 1 - src/blockchain_utilities/bootstrap_file.cpp | 1 - src/checkpoints/checkpoints.cpp | 1 - src/common/file.cpp | 1 - src/common/fs.h | 2 +- src/common/string_util.h | 9 --------- src/cryptonote_basic/cryptonote_format_utils.cpp | 1 - src/cryptonote_basic/miner.cpp | 1 - src/cryptonote_core/blockchain.cpp | 1 - src/cryptonote_core/cryptonote_core.cpp | 1 - src/cryptonote_core/oxen_name_system.cpp | 1 - src/daemon/rpc_command_executor.cpp | 16 ++++++++-------- src/logging/oxen_logger.cpp | 1 - src/p2p/net_node.inl | 1 - src/rpc/common/param_parser.hpp | 4 +++- src/rpc/core_rpc_server.cpp | 7 ++++--- src/rpc/http_client.cpp | 1 - src/simplewallet/simplewallet.cpp | 1 - src/wallet/ringdb.cpp | 1 - src/wallet/wallet2.cpp | 1 - src/wallet/wallet_args.cpp | 1 - src/wallet/wallet_rpc_server.cpp | 1 - src/wallet3/default_daemon_comms.cpp | 1 - src/wallet3/rpc/command_parser.cpp | 2 +- src/wallet3/rpc/omq_server.cpp | 3 ++- src/wallet3/wallet.cpp | 4 ++-- 35 files changed, 22 insertions(+), 53 deletions(-) diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index ffde9a961..1f7de43a3 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -35,7 +35,6 @@ #include #include #include -#include #include #include "common/string_util.h" diff --git a/src/blockchain_utilities/CMakeLists.txt b/src/blockchain_utilities/CMakeLists.txt index 36c8c25cb..ad60a5c30 100644 --- a/src/blockchain_utilities/CMakeLists.txt +++ b/src/blockchain_utilities/CMakeLists.txt @@ -112,7 +112,7 @@ target_link_libraries(blockchain_stats PRIVATE blockchain_tools_common_libs date if (TARGET sodium_vendor OR NOT SODIUM_VERSION VERSION_LESS 1.0.17) oxen_add_executable(sn_key_tool "oxen-sn-keys" sn_key_tool.cpp) - target_link_libraries(sn_key_tool PRIVATE sodium oxenmq filesystem) + target_link_libraries(sn_key_tool PRIVATE sodium oxenmq filesystem fmt::fmt) else() message(STATUS "Not building oxen-sn-keys tool (requires libsodium >= 1.0.17)") endif() diff --git a/src/blockchain_utilities/blockchain_ancestry.cpp b/src/blockchain_utilities/blockchain_ancestry.cpp index 7563fb966..2efd4165d 100644 --- a/src/blockchain_utilities/blockchain_ancestry.cpp +++ b/src/blockchain_utilities/blockchain_ancestry.cpp @@ -47,7 +47,6 @@ #include "blockchain_db/blockchain_db.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" -#include namespace po = boost::program_options; using namespace cryptonote; diff --git a/src/blockchain_utilities/blockchain_blackball.cpp b/src/blockchain_utilities/blockchain_blackball.cpp index fa63b28ce..bdee392ab 100644 --- a/src/blockchain_utilities/blockchain_blackball.cpp +++ b/src/blockchain_utilities/blockchain_blackball.cpp @@ -46,7 +46,6 @@ #include "wallet/ringdb.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" -#include namespace po = boost::program_options; using namespace cryptonote; diff --git a/src/blockchain_utilities/blockchain_depth.cpp b/src/blockchain_utilities/blockchain_depth.cpp index bf4de31c3..519bd491b 100644 --- a/src/blockchain_utilities/blockchain_depth.cpp +++ b/src/blockchain_utilities/blockchain_depth.cpp @@ -34,7 +34,6 @@ #include "blockchain_db/blockchain_db.h" #include "cryptonote_core/uptime_proof.h" #include "version.h" -#include namespace po = boost::program_options; using namespace cryptonote; diff --git a/src/blockchain_utilities/blockchain_export.cpp b/src/blockchain_utilities/blockchain_export.cpp index 72d293dd6..56759560a 100644 --- a/src/blockchain_utilities/blockchain_export.cpp +++ b/src/blockchain_utilities/blockchain_export.cpp @@ -34,7 +34,6 @@ #include "blockchain_objects.h" #include "version.h" #include "cryptonote_core/uptime_proof.h" -#include namespace po = boost::program_options; diff --git a/src/blockchain_utilities/blockchain_import.cpp b/src/blockchain_utilities/blockchain_import.cpp index be367a26b..0b9e7c3a4 100644 --- a/src/blockchain_utilities/blockchain_import.cpp +++ b/src/blockchain_utilities/blockchain_import.cpp @@ -45,7 +45,6 @@ #include "cryptonote_core/uptime_proof.h" #include "cryptonote_core/cryptonote_core.h" #include "common/hex.h" -#include #include namespace diff --git a/src/blockchain_utilities/blockchain_stats.cpp b/src/blockchain_utilities/blockchain_stats.cpp index 1baab0cad..59f543923 100644 --- a/src/blockchain_utilities/blockchain_stats.cpp +++ b/src/blockchain_utilities/blockchain_stats.cpp @@ -38,7 +38,6 @@ #include "version.h" #include "cryptonote_core/uptime_proof.h" #include -#include namespace po = boost::program_options; using namespace cryptonote; diff --git a/src/blockchain_utilities/blockchain_usage.cpp b/src/blockchain_utilities/blockchain_usage.cpp index 688e1ea17..dbe07c3ca 100644 --- a/src/blockchain_utilities/blockchain_usage.cpp +++ b/src/blockchain_utilities/blockchain_usage.cpp @@ -34,7 +34,6 @@ #include "blockchain_db/blockchain_db.h" #include "cryptonote_core/uptime_proof.h" #include "version.h" -#include namespace po = boost::program_options; using namespace cryptonote; diff --git a/src/blockchain_utilities/blocksdat_file.cpp b/src/blockchain_utilities/blocksdat_file.cpp index 192b64135..9939c9971 100644 --- a/src/blockchain_utilities/blocksdat_file.cpp +++ b/src/blockchain_utilities/blocksdat_file.cpp @@ -28,7 +28,6 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "blocksdat_file.h" -#include using namespace cryptonote; diff --git a/src/blockchain_utilities/bootstrap_file.cpp b/src/blockchain_utilities/bootstrap_file.cpp index 0d53c2348..aa5d99ffa 100644 --- a/src/blockchain_utilities/bootstrap_file.cpp +++ b/src/blockchain_utilities/bootstrap_file.cpp @@ -29,7 +29,6 @@ #include "bootstrap_serialization.h" #include "serialization/binary_utils.h" // dump_binary(), parse_binary() -#include #include "bootstrap_file.h" diff --git a/src/checkpoints/checkpoints.cpp b/src/checkpoints/checkpoints.cpp index 4630269db..ac73192c5 100644 --- a/src/checkpoints/checkpoints.cpp +++ b/src/checkpoints/checkpoints.cpp @@ -42,7 +42,6 @@ #include "common/oxen.h" #include "common/file.h" #include "common/hex.h" -#include namespace cryptonote { diff --git a/src/common/file.cpp b/src/common/file.cpp index 87f8b2355..530bd222b 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -31,7 +31,6 @@ // #include "file.h" #include "logging/oxen_logger.h" -#include #include #include #include diff --git a/src/common/fs.h b/src/common/fs.h index 456b96eb3..49ee63afb 100644 --- a/src/common/fs.h +++ b/src/common/fs.h @@ -27,7 +27,7 @@ namespace fs = ghc::filesystem; namespace formattable { template <> inline constexpr bool via_to_string = true; - std::string to_string(const ghc::filesystem::path& path) { + inline std::string to_string(const ghc::filesystem::path& path) { return path.string(); } } diff --git a/src/common/string_util.h b/src/common/string_util.h index 3fada5396..2e9725baa 100644 --- a/src/common/string_util.h +++ b/src/common/string_util.h @@ -128,15 +128,6 @@ bool parse_int(const std::string_view str, T& value, int base = 10) { return true; } -/// Converts an integer value into a string via std::to_chars (i.e. without locale). -template >> -std::string int_to_string(const T& value, int base = 10) { - char buf[8*sizeof(T) + std::is_signed_v]; // maximum possible size with smallest possible base (2) - auto [p, ec] = std::to_chars(std::begin(buf), std::end(buf), value, base); - assert(ec == std::errc{}); // Our buffer should be big enough for anything - return {buf, p}; -} - /// Returns a string_view that views the data of the given object; this is not something you want to /// do unless the struct is specifically design to be used this way. The value must be a standard /// layout type; it should really require is_trivial, too, but we have classes (like crypto keys) diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index 3db50ba6c..b12ef8559 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -51,7 +51,6 @@ #include "cryptonote_basic/verification_context.h" #include "cryptonote_core/service_node_voting.h" #include "cryptonote_core/oxen_name_system.h" -#include using namespace crypto; diff --git a/src/cryptonote_basic/miner.cpp b/src/cryptonote_basic/miner.cpp index 3409125bf..337a2de6f 100644 --- a/src/cryptonote_basic/miner.cpp +++ b/src/cryptonote_basic/miner.cpp @@ -40,7 +40,6 @@ #include "epee/string_tools.h" #include "epee/storages/portable_storage_template_helper.h" #include -#include #include #define AUTODETECT_WINDOW 10 // seconds diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 7759cef24..7ce54979c 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include "common/rules.h" #include "common/hex.h" diff --git a/src/cryptonote_core/cryptonote_core.cpp b/src/cryptonote_core/cryptonote_core.cpp index 839f21c63..bcfdad16c 100644 --- a/src/cryptonote_core/cryptonote_core.cpp +++ b/src/cryptonote_core/cryptonote_core.cpp @@ -71,7 +71,6 @@ extern "C" { #include "common/i18n.h" #include "epee/net/local_ip.h" #include "logging/oxen_logger.h" -#include #include #include diff --git a/src/cryptonote_core/oxen_name_system.cpp b/src/cryptonote_core/oxen_name_system.cpp index a7bef7cde..2a12b9a03 100644 --- a/src/cryptonote_core/oxen_name_system.cpp +++ b/src/cryptonote_core/oxen_name_system.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include "common/hex.h" #include "cryptonote_config.h" #include "oxen_name_system.h" diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index fc4bc9712..e11e6d69d 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -199,7 +200,7 @@ rpc_command_executor::rpc_command_executor( : m_rpc{std::in_place_type, http_url} { if (login) - std::get(m_rpc).set_auth( + var::get(m_rpc).set_auth( login->username, std::string{login->password.password().view()}); } @@ -229,7 +230,7 @@ json rpc_command_executor::invoke( result = rpc_client->json_rpc(method, std::move(params)); } else { assert(m_omq); - auto conn = std::get(m_rpc); + auto conn = var::get(m_rpc); auto endpoint = (public_method ? "rpc." : "admin.") + std::string{method}; std::promise result_p; m_omq->request(conn, endpoint, [&result_p](bool success, auto data) { @@ -627,12 +628,11 @@ bool rpc_command_executor::print_connections() { for (auto& info : conns) { - std::string address = info["incoming"].get() ? "INC " : "OUT "; - address += info["ip"].get(); - address += ':'; - address += tools::int_to_string(info["port"].get()); tools::msg_writer() << fmt::format(row_fmt, - address, + "{} {}:{}"_format( + info["incoming"].get() ? "INC" : "OUT", + info["ip"].get(), + info["port"].get()), get_address_type_name(info["address_type"].get()), info["peer_id"].get(), "{}({}/{})"_format(info["recv_count"].get(), @@ -1663,7 +1663,7 @@ static void append_printable_service_node_list_entry(cryptonote::network_type ne stream << '\n' << indent2 << "Pulse blocks: "; print_votes>(stream, entry, "pulse_votes", - [](const auto& val) { return tools::int_to_string(val.first) + (val.second ? " " + tools::int_to_string(val.second) : ""); }); + [](const auto& val) { return fmt::format(val.second ? "{} {}" : "{}", val.first, val.second); }); auto print_pass_fail = [&stream, &entry](const std::string& key) { std::pair val; diff --git a/src/logging/oxen_logger.cpp b/src/logging/oxen_logger.cpp index 335d1b8d2..29e653a91 100644 --- a/src/logging/oxen_logger.cpp +++ b/src/logging/oxen_logger.cpp @@ -1,6 +1,5 @@ #include "oxen_logger.h" #include -#include #include #include diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index fa41928d0..2f508e3f7 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -41,7 +41,6 @@ #include #include #include -#include #include "cryptonote_config.h" #include "version.h" diff --git a/src/rpc/common/param_parser.hpp b/src/rpc/common/param_parser.hpp index 8f65d6e57..36d5d4466 100644 --- a/src/rpc/common/param_parser.hpp +++ b/src/rpc/common/param_parser.hpp @@ -1,8 +1,10 @@ #pragma once -#include "oxenmq/bt_serialize.h" +#include +#include "rpc/common/rpc_binary.h" #include +#include #include #include #include diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 921ce7ae6..aca8d5eff 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -1314,8 +1314,9 @@ namespace cryptonote::rpc { for (auto h : get.request.heights) { if (h >= curr_height) throw rpc_error{ERROR_TOO_BIG_HEIGHT, - "Requested block height: " + tools::int_to_string(h) + " greater than current top block height: " + tools::int_to_string(curr_height - 1)}; - get.response_hex[tools::int_to_string(h)] = m_core.get_block_id_by_height(h); + "Requested block height {} greater than current top block height {}"_format( + h, curr_height - 1)}; + get.response_hex["{}"_format(h)] = m_core.get_block_id_by_height(h); } get.response["status"] = STATUS_OK; } @@ -2433,7 +2434,7 @@ namespace cryptonote::rpc { "operator_fee", microportion(info.portions_for_operator), "operator_address", cryptonote::get_account_address_as_str(m_core.get_nettype(), false/*subaddress*/, info.operator_address), "swarm_id", info.swarm_id, - "swarm", tools::int_to_string(info.swarm_id, 16), + "swarm", "{:x}"_format(info.swarm_id), "registration_hf_version", info.registration_hf_version ); diff --git a/src/rpc/http_client.cpp b/src/rpc/http_client.cpp index bfad10f6c..50e55d7fb 100644 --- a/src/rpc/http_client.cpp +++ b/src/rpc/http_client.cpp @@ -6,7 +6,6 @@ #include #include #include "logging/oxen_logger.h" -#include namespace cryptonote::rpc { diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 72ad94a78..59835ec29 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -56,7 +56,6 @@ #include #include #include -#include #include "epee/console_handler.h" #include "common/i18n.h" #include "common/command_line.h" diff --git a/src/wallet/ringdb.cpp b/src/wallet/ringdb.cpp index 7e24b4952..bdd3cfb37 100644 --- a/src/wallet/ringdb.cpp +++ b/src/wallet/ringdb.cpp @@ -33,7 +33,6 @@ #include "wallet_errors.h" #include "ringdb.h" #include "cryptonote_config.h" -#include #define V1TAG ((uint64_t)798237759845202) diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index ff2167c39..942770b5c 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -88,7 +88,6 @@ #include "oxen_economy.h" #include "logging/oxen_logger.h" #include -#include extern "C" { diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index d98e0d913..76ad15b20 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -37,7 +37,6 @@ #include "epee/string_tools.h" #include "version.h" #include "logging/oxen_logger.h" -#include #if defined(WIN32) #include diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 47f4ff5da..20cdb5e8c 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include "wallet_rpc_server_error_codes.h" #include "wallet_rpc_server.h" diff --git a/src/wallet3/default_daemon_comms.cpp b/src/wallet3/default_daemon_comms.cpp index 8b085e128..192b80027 100644 --- a/src/wallet3/default_daemon_comms.cpp +++ b/src/wallet3/default_daemon_comms.cpp @@ -8,7 +8,6 @@ #include #include #include -#include "oxenmq/oxenmq.h" #include diff --git a/src/wallet3/rpc/command_parser.cpp b/src/wallet3/rpc/command_parser.cpp index c4a2e1f24..9aab70a43 100644 --- a/src/wallet3/rpc/command_parser.cpp +++ b/src/wallet3/rpc/command_parser.cpp @@ -11,7 +11,7 @@ using nlohmann::json; using cryptonote::rpc::required; using cryptonote::rpc::get_values; -using rpc_input = std::variant; +using rpc_input = var::variant; void parse_request(GET_BALANCE& req, rpc_input in) { diff --git a/src/wallet3/rpc/omq_server.cpp b/src/wallet3/rpc/omq_server.cpp index 513031671..3006fcd36 100644 --- a/src/wallet3/rpc/omq_server.cpp +++ b/src/wallet3/rpc/omq_server.cpp @@ -4,6 +4,7 @@ #include "commands.h" #include +#include #include #include @@ -56,7 +57,7 @@ OmqServer::set_omq(std::shared_ptr omq_in, wallet::rpc::Config c request.body = m.data[0]; try { - auto result = std::visit([](auto&& v) -> std::string { + auto result = var::visit([](auto&& v) -> std::string { using T = decltype(v); if constexpr (std::is_same_v) return bt_serialize(std::move(v)); diff --git a/src/wallet3/wallet.cpp b/src/wallet3/wallet.cpp index 06f21a4d8..884f38db2 100644 --- a/src/wallet3/wallet.cpp +++ b/src/wallet3/wallet.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include "common/fs.h" #include #include #include @@ -30,7 +30,7 @@ namespace wallet std::string_view dbPassword, wallet::Config config_in) : omq(omq) - , db{std::make_shared(std::filesystem::path(dbFilename), dbPassword)} + , db{std::make_shared(fs::path(dbFilename), dbPassword)} , keys{keys} , tx_scanner{keys, db} , tx_constructor{tx_constructor} From c4f4bfc87e5be055b0ee266b8df63ffbee6bf645 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Wed, 28 Sep 2022 13:13:37 -0300 Subject: [PATCH 25/32] Fix deprecated oxenmq::* usage Some of this is just obsolete, some slipped in recent feature branches. --- src/rpc/common/json_bt.cpp | 6 +++--- src/rpc/common/json_bt.h | 4 ++-- src/rpc/common/param_parser.hpp | 22 ++++++++++------------ src/rpc/common/rpc_binary.cpp | 16 ++++++++-------- src/rpc/common/rpc_command.h | 7 ++++--- src/rpc/core_rpc_server.h | 2 +- src/rpc/core_rpc_server_command_parser.cpp | 14 +++++++------- src/rpc/core_rpc_server_command_parser.h | 4 ++-- src/rpc/core_rpc_server_commands_defs.cpp | 1 - src/rpc/core_rpc_server_commands_defs.h | 2 +- src/rpc/lmq_server.cpp | 10 +++++----- src/wallet3/CMakeLists.txt | 1 + src/wallet3/default_daemon_comms.cpp | 22 +++++++++++----------- src/wallet3/rpc/CMakeLists.txt | 1 + src/wallet3/rpc/command_parser.cpp | 5 ++--- src/wallet3/rpc/command_parser.h | 4 ++-- src/wallet3/rpc/omq_server.cpp | 2 +- src/wallet3/rpc/request_handler.h | 4 ++-- tests/wallet3_tests/jank_wallet.cpp | 8 ++++---- 19 files changed, 67 insertions(+), 68 deletions(-) diff --git a/src/rpc/common/json_bt.cpp b/src/rpc/common/json_bt.cpp index a45b73c6a..04aa90c2d 100644 --- a/src/rpc/common/json_bt.cpp +++ b/src/rpc/common/json_bt.cpp @@ -2,9 +2,9 @@ namespace oxen { -oxenmq::bt_value json_to_bt(json&& j) { +oxenc::bt_value json_to_bt(json&& j) { if (j.is_object()) { - oxenmq::bt_dict res; + oxenc::bt_dict res; for (auto& [k, v] : j.items()) { if (v.is_null()) continue; // skip k-v pairs with a null v (for other nulls we fail). @@ -13,7 +13,7 @@ oxenmq::bt_value json_to_bt(json&& j) { return res; } if (j.is_array()) { - oxenmq::bt_list res; + oxenc::bt_list res; for (auto& v : j) res.push_back(json_to_bt(std::move(v))); return res; diff --git a/src/rpc/common/json_bt.h b/src/rpc/common/json_bt.h index 79f9862ba..881ef3707 100644 --- a/src/rpc/common/json_bt.h +++ b/src/rpc/common/json_bt.h @@ -1,12 +1,12 @@ #pragma once #include -#include +#include using nlohmann::json; namespace oxen { -oxenmq::bt_value json_to_bt(json&& j); +oxenc::bt_value json_to_bt(json&& j); } // namespace oxen diff --git a/src/rpc/common/param_parser.hpp b/src/rpc/common/param_parser.hpp index 36d5d4466..5bfdbac89 100644 --- a/src/rpc/common/param_parser.hpp +++ b/src/rpc/common/param_parser.hpp @@ -1,18 +1,18 @@ #pragma once -#include #include "rpc/common/rpc_binary.h" #include +#include #include -#include -#include #include #include namespace cryptonote::rpc { using nlohmann::json; - using rpc_input = std::variant; + using oxenc::bt_dict_consumer; + using oxenc::bt_list_consumer; + using rpc_input = std::variant; // Checks that key names are given in ascending order template @@ -45,15 +45,13 @@ namespace cryptonote::rpc { template constexpr bool is_std_optional> = true; - using oxenmq::bt_dict_consumer; - using json_range = std::pair; // Advances the dict consumer to the first element >= the given name. Returns true if found, // false if it advanced beyond the requested name. This is exactly the same as // `d.skip_until(name)`, but is here so we can also overload an equivalent function for json // iteration. - inline bool skip_until(oxenmq::bt_dict_consumer& d, std::string_view name) { + inline bool skip_until(bt_dict_consumer& d, std::string_view name) { return d.skip_until(name); } // Equivalent to the above but for a json object iterator. @@ -80,13 +78,13 @@ namespace cryptonote::rpc { template constexpr bool is_tuple_like> = true; template - void load_tuple_values(oxenmq::bt_list_consumer&, TupleLike&, std::index_sequence); + void load_tuple_values(bt_list_consumer&, TupleLike&, std::index_sequence); // Consumes the next value from the dict consumer into `val` template - || std::is_same_v, + std::is_same_v + || std::is_same_v, int> = 0> void load_value(BTConsumer& c, T& val) { if constexpr (std::is_integral_v) @@ -158,7 +156,7 @@ namespace cryptonote::rpc { } template - void load_tuple_values(oxenmq::bt_list_consumer& c, TupleLike& val, std::index_sequence) { + void load_tuple_values(bt_list_consumer& c, TupleLike& val, std::index_sequence) { (load_value(c, std::get(val)), ...); } @@ -203,7 +201,7 @@ namespace cryptonote::rpc { { if (in.front() == 'd') { - oxenmq::bt_dict_consumer d{in}; + bt_dict_consumer d{in}; get_values(d, name, val, std::forward(more)...); } else diff --git a/src/rpc/common/rpc_binary.cpp b/src/rpc/common/rpc_binary.cpp index 80bd382a7..74aaa2154 100644 --- a/src/rpc/common/rpc_binary.cpp +++ b/src/rpc/common/rpc_binary.cpp @@ -1,6 +1,6 @@ #include "rpc_binary.h" -#include -#include +#include +#include namespace cryptonote::rpc { @@ -9,8 +9,8 @@ namespace cryptonote::rpc { std::memcpy(val_data, bytes.data(), bytes.size()); return; } else if (bytes.size() == raw_size * 2) { - if (oxenmq::is_hex(bytes)) { - oxenmq::from_hex(bytes.begin(), bytes.end(), val_data); + if (oxenc::is_hex(bytes)) { + oxenc::from_hex(bytes.begin(), bytes.end(), val_data); return; } } else { @@ -20,8 +20,8 @@ namespace cryptonote::rpc { const std::string_view b64_padding_string = b64_padding == 2 ? "=="sv : b64_padding == 1 ? "="sv : ""sv; if (bytes.size() == b64_unpadded || (b64_padding > 0 && bytes.size() == b64_padded && bytes.substr(b64_unpadded) == b64_padding_string)) { - if (oxenmq::is_base64(bytes)) { - oxenmq::from_base64(bytes.begin(), bytes.end(), val_data); + if (oxenc::is_base64(bytes)) { + oxenc::from_base64(bytes.begin(), bytes.end(), val_data); return; } } @@ -33,8 +33,8 @@ namespace cryptonote::rpc { nlohmann::json& json_binary_proxy::operator=(std::string_view binary_data) { switch (format) { case fmt::bt: return e = binary_data; - case fmt::hex: return e = oxenmq::to_hex(binary_data); - case fmt::base64: return e = oxenmq::to_base64(binary_data); + case fmt::hex: return e = oxenc::to_hex(binary_data); + case fmt::base64: return e = oxenc::to_base64(binary_data); } throw std::runtime_error{"Internal error: invalid binary encoding"}; } diff --git a/src/rpc/common/rpc_command.h b/src/rpc/common/rpc_command.h index c968fce18..e55423de8 100644 --- a/src/rpc/common/rpc_command.h +++ b/src/rpc/common/rpc_command.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include "json_bt.h" @@ -9,8 +9,9 @@ namespace cryptonote::rpc { using nlohmann::json; using oxen::json_to_bt; +using namespace std::literals; -using rpc_input = std::variant; +using rpc_input = std::variant; /// Exception when trying to invoke an RPC command that indicate a parameter parse failure (will /// give an invalid params error for JSON-RPC, for example). @@ -97,7 +98,7 @@ auto make_invoke() { if (auto body = request.body_view()) { if (body->front() == 'd') { // Looks like a bt dict rpc.set_bt(); - parse_request(rpc, oxenmq::bt_dict_consumer{*body}); + parse_request(rpc, oxenc::bt_dict_consumer{*body}); } else parse_request(rpc, json::parse(*body)); diff --git a/src/rpc/core_rpc_server.h b/src/rpc/core_rpc_server.h index ac3eea71c..4856c397b 100644 --- a/src/rpc/core_rpc_server.h +++ b/src/rpc/core_rpc_server.h @@ -66,7 +66,7 @@ namespace cryptonote::rpc { /// Stores an RPC command callback. These are set up in core_rpc_server.cpp. struct rpc_command { - using result_type = std::variant; + using result_type = std::variant; // Called with the incoming command data; returns the response body if all goes well, // otherwise throws an exception. result_type(*invoke)(rpc_request&&, core_rpc_server&); diff --git a/src/rpc/core_rpc_server_command_parser.cpp b/src/rpc/core_rpc_server_command_parser.cpp index 23c47d64a..77b2cb520 100644 --- a/src/rpc/core_rpc_server_command_parser.cpp +++ b/src/rpc/core_rpc_server_command_parser.cpp @@ -1,10 +1,10 @@ #include "core_rpc_server_command_parser.h" -#include "oxenmq/bt_serialize.h" #include "rpc/common/param_parser.hpp" #include -#include -#include +#include +#include +#include #include #include @@ -172,14 +172,14 @@ namespace cryptonote::rpc { if (tx0 <= 0x2f) { good = true; } else if (tx0 >= 'A' && tx0 <= 'L') { - if (oxenmq::is_base64(tx_data)) { - auto end = oxenmq::from_base64(tx_data.begin(), tx_data.end(), tx_data.begin()); + if (oxenc::is_base64(tx_data)) { + auto end = oxenc::from_base64(tx_data.begin(), tx_data.end(), tx_data.begin()); tx_data.erase(end, tx_data.end()); good = true; } } else if (tx0 >= '0' && tx0 <= '2') { - if (oxenmq::is_hex(tx_data)) { - auto end = oxenmq::from_hex(tx_data.begin(), tx_data.end(), tx_data.begin()); + if (oxenc::is_hex(tx_data)) { + auto end = oxenc::from_hex(tx_data.begin(), tx_data.end(), tx_data.begin()); tx_data.erase(end, tx_data.end()); good = true; } diff --git a/src/rpc/core_rpc_server_command_parser.h b/src/rpc/core_rpc_server_command_parser.h index a22ddfe95..724410db4 100644 --- a/src/rpc/core_rpc_server_command_parser.h +++ b/src/rpc/core_rpc_server_command_parser.h @@ -2,11 +2,11 @@ #include "core_rpc_server_commands_defs.h" #include -#include +#include namespace cryptonote::rpc { - using rpc_input = std::variant; + using rpc_input = std::variant; inline void parse_request(NO_ARGS&, rpc_input) {} diff --git a/src/rpc/core_rpc_server_commands_defs.cpp b/src/rpc/core_rpc_server_commands_defs.cpp index 861975c0b..ba8ed34cc 100644 --- a/src/rpc/core_rpc_server_commands_defs.cpp +++ b/src/rpc/core_rpc_server_commands_defs.cpp @@ -1,6 +1,5 @@ #include "core_rpc_server_commands_defs.h" #include -#include namespace nlohmann { diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index 938c84acf..e7a64fe32 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -70,7 +70,7 @@ #include "common/oxen.h" #include -#include +#include #include #include diff --git a/src/rpc/lmq_server.cpp b/src/rpc/lmq_server.cpp index c1ce4af3b..b4a350bd7 100644 --- a/src/rpc/lmq_server.cpp +++ b/src/rpc/lmq_server.cpp @@ -2,10 +2,10 @@ #include "lmq_server.h" #include "rpc/common/param_parser.hpp" #include "cryptonote_config.h" -#include "oxenmq/oxenmq.h" +#include +#include +#include #include -#include "oxenc/bt.h" -#include "oxenmq/fmt.h" // FIXME: Rename this to omq_server.{h,cpp} @@ -207,9 +207,9 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog request.body = m.data[0]; try { - auto result = std::visit([](auto&& v) -> std::string { + auto result = var::visit([](auto&& v) -> std::string { using T = decltype(v); - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) return bt_serialize(std::move(v)); else if constexpr (std::is_same_v) return v.dump(); diff --git a/src/wallet3/CMakeLists.txt b/src/wallet3/CMakeLists.txt index b6aed22e9..c42de13ae 100644 --- a/src/wallet3/CMakeLists.txt +++ b/src/wallet3/CMakeLists.txt @@ -19,6 +19,7 @@ target_link_libraries(wallet3 common nlohmann_json::nlohmann_json oxenmq::oxenmq + oxenc::oxenc PRIVATE cryptonote_protocol cryptonote_basic diff --git a/src/wallet3/default_daemon_comms.cpp b/src/wallet3/default_daemon_comms.cpp index 192b80027..85a9c0855 100644 --- a/src/wallet3/default_daemon_comms.cpp +++ b/src/wallet3/default_daemon_comms.cpp @@ -47,7 +47,7 @@ namespace wallet while( itr != response.cend()) { const auto& block_str = *itr; - auto block_dict = oxenmq::bt_dict_consumer{block_str}; + auto block_dict = oxenc::bt_dict_consumer{block_str}; Block& b = blocks.emplace_back(); @@ -161,7 +161,7 @@ namespace wallet if (not ok or response.size() != 2 or response[0] != "200") return; - oxenmq::bt_dict_consumer dc{response[1]}; + oxenc::bt_dict_consumer dc{response[1]}; int64_t new_height = 0; crypto::hash new_hash; @@ -199,7 +199,7 @@ namespace wallet if (not ok or response.size() != 2 or response[0] != "200") return; - oxenmq::bt_dict_consumer dc{response[1]}; + oxenc::bt_dict_consumer dc{response[1]}; int64_t new_fee_per_byte = 0; int64_t new_fee_per_output = 0; @@ -282,7 +282,7 @@ namespace wallet {"size_limit", max_response_size}, {"start_height", sync_from_height}}; - omq->request(conn, "rpc.get_blocks", req_cb, oxenmq::bt_serialize(req_params_dict)); + omq->request(conn, "rpc.get_blocks", req_cb, oxenc::bt_serialize(req_params_dict)); } std::future> @@ -320,7 +320,7 @@ namespace wallet size_t i=0; try { - auto outer_dict = oxenmq::bt_dict_consumer(response[1]); + auto outer_dict = oxenc::bt_dict_consumer(response[1]); if (outer_dict.key() != "outs") return; @@ -378,15 +378,15 @@ namespace wallet p->set_value(std::move(outputs)); }; // req_cb - oxenmq::bt_dict req_params_dict; - oxenmq::bt_list decoy_list_bt; + oxenc::bt_dict req_params_dict; + oxenc::bt_list decoy_list_bt; for (auto index : indexes) { decoy_list_bt.push_back(index); } req_params_dict["get_txid"] = with_txid; req_params_dict["outputs"] = std::move(decoy_list_bt); - omq->request(conn, "rpc.get_outs", req_cb, oxenmq::bt_serialize(req_params_dict)); + omq->request(conn, "rpc.get_outs", req_cb, oxenc::bt_serialize(req_params_dict)); return fut; } @@ -406,7 +406,7 @@ namespace wallet } else { - oxenmq::bt_dict_consumer dc{response[1]}; + oxenc::bt_dict_consumer dc{response[1]}; if (dc.skip_until("reason")) { auto reason = dc.consume_string(); @@ -433,12 +433,12 @@ namespace wallet if (not cryptonote::tx_to_blob(tx, tx_str)) throw std::runtime_error{"wallet daemon comms, failed to serialize transaction"}; - oxenmq::bt_dict req_params_dict; + oxenc::bt_dict req_params_dict; req_params_dict["blink"] = blink; req_params_dict["tx"] = tx_str; - omq->request(conn, "rpc.submit_transaction", req_cb, oxenmq::bt_serialize(req_params_dict)); + omq->request(conn, "rpc.submit_transaction", req_cb, oxenc::bt_serialize(req_params_dict)); return fut; } diff --git a/src/wallet3/rpc/CMakeLists.txt b/src/wallet3/rpc/CMakeLists.txt index a39c08d70..d037b2943 100644 --- a/src/wallet3/rpc/CMakeLists.txt +++ b/src/wallet3/rpc/CMakeLists.txt @@ -39,6 +39,7 @@ target_link_libraries(wallet3_rpc common nlohmann_json::nlohmann_json oxenmq::oxenmq + oxenc::oxenc PRIVATE cryptonote_protocol extra) diff --git a/src/wallet3/rpc/command_parser.cpp b/src/wallet3/rpc/command_parser.cpp index 9aab70a43..93b8d2d72 100644 --- a/src/wallet3/rpc/command_parser.cpp +++ b/src/wallet3/rpc/command_parser.cpp @@ -1,6 +1,5 @@ #include "command_parser.h" -#include "oxenmq/bt_serialize.h" #include "rpc/common/param_parser.hpp" #include @@ -11,7 +10,7 @@ using nlohmann::json; using cryptonote::rpc::required; using cryptonote::rpc::get_values; -using rpc_input = var::variant; +using rpc_input = std::variant; void parse_request(GET_BALANCE& req, rpc_input in) { @@ -83,7 +82,7 @@ std::cout << "parse_request(TRANSFER)\n"; else throw std::runtime_error{"Required key 'destinations' not found or invalid"}; } - else if (auto* bt_in = std::get_if(&in)) + else if (auto* bt_in = std::get_if(&in)) { if (bt_in->key() != "destinations") throw std::runtime_error{"Required key 'destinations' not found"}; diff --git a/src/wallet3/rpc/command_parser.h b/src/wallet3/rpc/command_parser.h index 5fbc67ae8..82dd31b61 100644 --- a/src/wallet3/rpc/command_parser.h +++ b/src/wallet3/rpc/command_parser.h @@ -2,11 +2,11 @@ #include "commands.h" #include -#include +#include namespace wallet::rpc { -using rpc_input = std::variant; +using rpc_input = std::variant; inline void parse_request(NO_ARGS&, rpc_input) {} diff --git a/src/wallet3/rpc/omq_server.cpp b/src/wallet3/rpc/omq_server.cpp index 3006fcd36..8c1f06eb1 100644 --- a/src/wallet3/rpc/omq_server.cpp +++ b/src/wallet3/rpc/omq_server.cpp @@ -59,7 +59,7 @@ OmqServer::set_omq(std::shared_ptr omq_in, wallet::rpc::Config c try { auto result = var::visit([](auto&& v) -> std::string { using T = decltype(v); - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) return bt_serialize(std::move(v)); else if constexpr (std::is_same_v) return v.dump(); diff --git a/src/wallet3/rpc/request_handler.h b/src/wallet3/rpc/request_handler.h index 584128bab..645ff9af2 100644 --- a/src/wallet3/rpc/request_handler.h +++ b/src/wallet3/rpc/request_handler.h @@ -5,7 +5,7 @@ #include "rpc/common/rpc_command.h" #include -#include +#include #include #include @@ -25,7 +25,7 @@ using cryptonote::rpc::rpc_request; /// Stores an RPC command callback. These are set up in request_handler.cpp. struct rpc_command { - using result_type = std::variant; + using result_type = std::variant; // Called with the incoming command data; returns the response body if all goes well, // otherwise throws an exception. result_type(*invoke)(rpc_request&&, RequestHandler&); diff --git a/tests/wallet3_tests/jank_wallet.cpp b/tests/wallet3_tests/jank_wallet.cpp index 4658e01a5..4d4c5e5cd 100644 --- a/tests/wallet3_tests/jank_wallet.cpp +++ b/tests/wallet3_tests/jank_wallet.cpp @@ -64,9 +64,9 @@ int main(int argc, char** argv) conn = oxenmq->connect_remote(remote, [](auto){}, [](auto,auto){}); auto send_func = [&](std::string_view dest, std::string_view amount){ - oxenmq::bt_dict req; - oxenmq::bt_list dests; - oxenmq::bt_dict d; + oxenc::bt_dict req; + oxenc::bt_list dests; + oxenc::bt_dict d; d["address"] = dest; uint64_t amount_int = stoi(std::string(amount)); d["amount"] = amount_int; @@ -87,7 +87,7 @@ int main(int argc, char** argv) p.set_value(ok); }; - oxenmq->request(conn, "restricted.transfer", req_cb, oxenmq::bt_serialize(req)); + oxenmq->request(conn, "restricted.transfer", req_cb, oxenc::bt_serialize(req)); f.wait(); }; From 463590ad5c2fb4e2dd9aa54e33ed51c484cb99a5 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 7 Oct 2022 23:30:29 -0300 Subject: [PATCH 26/32] Eliminate most << output operators Replace (nearly) everything with fmt formatting. Some crap in wallet2 remains that I'm not going to bother with. --- contrib/epee/include/epee/string_tools.h | 12 - src/blockchain_db/lmdb/db_lmdb.cpp | 1 + src/blockchain_db/sqlite/db_sqlite.cpp | 1 - .../blockchain_ancestry.cpp | 2 +- .../blockchain_blackball.cpp | 1 + src/blockchain_utilities/blockchain_depth.cpp | 1 + .../blockchain_export.cpp | 1 + .../blockchain_import.cpp | 1 + src/blockchain_utilities/blockchain_stats.cpp | 1 + src/blockchain_utilities/blockchain_usage.cpp | 1 + src/blockchain_utilities/blocksdat_file.cpp | 1 + src/blockchain_utilities/bootstrap_file.cpp | 2 +- src/checkpoints/checkpoints.cpp | 1 + src/common/CMakeLists.txt | 1 + src/common/command_line.h | 1 - src/common/file.cpp | 1 + src/common/formattable.h | 30 + src/common/fs.h | 9 - src/common/scoped_message_writer.cpp | 28 +- src/common/scoped_message_writer.h | 123 +++- src/common/string_util.cpp | 52 +- src/common/string_util.h | 45 +- src/crypto/crypto.h | 33 +- src/crypto/fmt.h | 38 -- src/crypto/hash.h | 14 +- src/cryptonote_basic/cryptonote_basic.h | 57 +- .../cryptonote_format_utils.cpp | 11 +- .../cryptonote_format_utils.h | 6 +- src/cryptonote_basic/subaddress_index.h | 12 +- src/cryptonote_basic/tx_extra.h | 4 +- src/cryptonote_basic/txtypes.h | 34 +- src/cryptonote_core/blockchain.cpp | 1 + src/cryptonote_core/cryptonote_core.cpp | 10 +- src/cryptonote_core/cryptonote_tx_utils.cpp | 1 - src/cryptonote_core/oxen_name_system.cpp | 216 +++--- src/cryptonote_core/oxen_name_system.h | 4 +- src/cryptonote_core/service_node_quorum_cop.h | 12 +- src/cryptonote_core/service_node_voting.h | 12 +- src/daemon/command_parser_executor.cpp | 14 +- src/daemon/rpc_command_executor.cpp | 636 +++++++++--------- src/daemon/rpc_command_executor.h | 6 +- src/device/device_ledger.cpp | 3 +- src/device_trezor/trezor/transport.cpp | 7 +- src/gen_multisig/gen_multisig.cpp | 34 +- src/p2p/net_node.inl | 1 + src/ringct/rctTypes.h | 11 +- src/simplewallet/simplewallet.cpp | 115 ++-- src/wallet/api/pending_transaction.cpp | 1 - src/wallet/api/unsigned_transaction.cpp | 1 - src/wallet/ringdb.cpp | 1 + src/wallet/wallet2.cpp | 3 +- src/wallet/wallet2.h | 1 - src/wallet/wallet_args.cpp | 1 + src/wallet/wallet_rpc_server.cpp | 1 + tests/difficulty/CMakeLists.txt | 1 + tests/unit_tests/crypto.cpp | 6 +- tests/unit_tests/oxen_name_system.cpp | 2 +- tests/unit_tests/ringct.cpp | 5 +- 58 files changed, 804 insertions(+), 827 deletions(-) delete mode 100644 src/crypto/fmt.h diff --git a/contrib/epee/include/epee/string_tools.h b/contrib/epee/include/epee/string_tools.h index c476b6ec5..eed2df99c 100644 --- a/contrib/epee/include/epee/string_tools.h +++ b/contrib/epee/include/epee/string_tools.h @@ -215,18 +215,6 @@ POP_WARNINGS trim(str); return str; } - //---------------------------------------------------------------------------- - inline std::string pad_string(std::string s, size_t n, char c = ' ', bool prepend = false) - { - if (s.size() < n) - { - if (prepend) - s = std::string(n - s.size(), c) + s; - else - s.append(n - s.size(), c); - } - return s; - } } } #endif //_STRING_TOOLS_H_ diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index 1f7de43a3..8d0fe916b 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -41,6 +41,7 @@ #include "cryptonote_basic/hardfork.h" #include "epee/string_tools.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/pruning.h" #include "common/hex.h" #include "common/median.h" diff --git a/src/blockchain_db/sqlite/db_sqlite.cpp b/src/blockchain_db/sqlite/db_sqlite.cpp index 75dd9e80e..9b4af09ac 100644 --- a/src/blockchain_db/sqlite/db_sqlite.cpp +++ b/src/blockchain_db/sqlite/db_sqlite.cpp @@ -31,7 +31,6 @@ #include #include -#include #include #include "cryptonote_config.h" diff --git a/src/blockchain_utilities/blockchain_ancestry.cpp b/src/blockchain_utilities/blockchain_ancestry.cpp index 2efd4165d..cc0f5c199 100644 --- a/src/blockchain_utilities/blockchain_ancestry.cpp +++ b/src/blockchain_utilities/blockchain_ancestry.cpp @@ -39,7 +39,7 @@ #include "common/command_line.h" #include "common/varint.h" #include "common/signal_handler.h" -#include "common/fs.h" +#include "common/fs-format.h" #include "serialization/boost_std_variant.h" #include "cryptonote_basic/cryptonote_boost_serialization.h" #include "cryptonote_core/cryptonote_core.h" diff --git a/src/blockchain_utilities/blockchain_blackball.cpp b/src/blockchain_utilities/blockchain_blackball.cpp index bdee392ab..86dfc2ce0 100644 --- a/src/blockchain_utilities/blockchain_blackball.cpp +++ b/src/blockchain_utilities/blockchain_blackball.cpp @@ -36,6 +36,7 @@ #include "common/string_util.h" #include "common/varint.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/signal_handler.h" #include "common/hex.h" #include "serialization/crypto.h" diff --git a/src/blockchain_utilities/blockchain_depth.cpp b/src/blockchain_utilities/blockchain_depth.cpp index 519bd491b..f7fa2e051 100644 --- a/src/blockchain_utilities/blockchain_depth.cpp +++ b/src/blockchain_utilities/blockchain_depth.cpp @@ -29,6 +29,7 @@ #include "common/command_line.h" #include "common/varint.h" #include "common/median.h" +#include "common/fs-format.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" #include "blockchain_db/blockchain_db.h" diff --git a/src/blockchain_utilities/blockchain_export.cpp b/src/blockchain_utilities/blockchain_export.cpp index 56759560a..8b10456d5 100644 --- a/src/blockchain_utilities/blockchain_export.cpp +++ b/src/blockchain_utilities/blockchain_export.cpp @@ -30,6 +30,7 @@ #include "bootstrap_file.h" #include "blocksdat_file.h" #include "common/command_line.h" +#include "common/fs-format.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" #include "version.h" diff --git a/src/blockchain_utilities/blockchain_import.cpp b/src/blockchain_utilities/blockchain_import.cpp index 0b9e7c3a4..446305e03 100644 --- a/src/blockchain_utilities/blockchain_import.cpp +++ b/src/blockchain_utilities/blockchain_import.cpp @@ -45,6 +45,7 @@ #include "cryptonote_core/uptime_proof.h" #include "cryptonote_core/cryptonote_core.h" #include "common/hex.h" +#include "common/fs-format.h" #include namespace diff --git a/src/blockchain_utilities/blockchain_stats.cpp b/src/blockchain_utilities/blockchain_stats.cpp index 59f543923..00e44e4ca 100644 --- a/src/blockchain_utilities/blockchain_stats.cpp +++ b/src/blockchain_utilities/blockchain_stats.cpp @@ -31,6 +31,7 @@ #include "common/command_line.h" #include "common/varint.h" #include "common/signal_handler.h" +#include "common/fs-format.h" #include "cryptonote_basic/cryptonote_boost_serialization.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" diff --git a/src/blockchain_utilities/blockchain_usage.cpp b/src/blockchain_utilities/blockchain_usage.cpp index dbe07c3ca..931c505d0 100644 --- a/src/blockchain_utilities/blockchain_usage.cpp +++ b/src/blockchain_utilities/blockchain_usage.cpp @@ -29,6 +29,7 @@ #include "common/command_line.h" #include "common/varint.h" +#include "common/fs-format.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" #include "blockchain_db/blockchain_db.h" diff --git a/src/blockchain_utilities/blocksdat_file.cpp b/src/blockchain_utilities/blocksdat_file.cpp index 9939c9971..294a81465 100644 --- a/src/blockchain_utilities/blocksdat_file.cpp +++ b/src/blockchain_utilities/blocksdat_file.cpp @@ -28,6 +28,7 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "blocksdat_file.h" +#include "common/fs-format.h" using namespace cryptonote; diff --git a/src/blockchain_utilities/bootstrap_file.cpp b/src/blockchain_utilities/bootstrap_file.cpp index aa5d99ffa..2ec128aa2 100644 --- a/src/blockchain_utilities/bootstrap_file.cpp +++ b/src/blockchain_utilities/bootstrap_file.cpp @@ -32,7 +32,7 @@ #include "bootstrap_file.h" -namespace po = boost::program_options; +#include "common/fs-format.h" using namespace cryptonote; diff --git a/src/checkpoints/checkpoints.cpp b/src/checkpoints/checkpoints.cpp index ac73192c5..3af900c9a 100644 --- a/src/checkpoints/checkpoints.cpp +++ b/src/checkpoints/checkpoints.cpp @@ -41,6 +41,7 @@ #include "common/oxen.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/hex.h" namespace cryptonote diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 21ccfa6d4..41d919584 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -64,6 +64,7 @@ target_link_libraries(common cncrypto oxenmq::oxenmq filesystem + oxen::logging fmt::fmt date::date PRIVATE diff --git a/src/common/command_line.h b/src/common/command_line.h index 693b34b61..9e046cdd6 100644 --- a/src/common/command_line.h +++ b/src/common/command_line.h @@ -31,7 +31,6 @@ #pragma once #include -#include #include #include diff --git a/src/common/file.cpp b/src/common/file.cpp index 530bd222b..c28d4fc41 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -30,6 +30,7 @@ // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers // #include "file.h" +#include "fs-format.h" #include "logging/oxen_logger.h" #include #include diff --git a/src/common/formattable.h b/src/common/formattable.h index 5a9e1efef..cb0eb3f4c 100644 --- a/src/common/formattable.h +++ b/src/common/formattable.h @@ -1,3 +1,5 @@ +#pragma once + #include #include #include @@ -31,6 +33,11 @@ namespace formattable { template constexpr bool via_to_string = false; + // Same as above, but looks for a to_hex_string() instead of to_string(), for types that get + // dumped as hex. + template + constexpr bool via_to_hex_string = false; + // Scoped enums can alternatively be formatted as their underlying integer value by specializing // this function to true: template @@ -40,12 +47,19 @@ namespace formattable { template constexpr bool has_to_string_method = false; + template + constexpr bool has_to_hex_string_method = false; template inline constexpr bool has_to_string_method().to_string())> > = true; + template + inline constexpr bool has_to_hex_string_method().to_hex_string())> + > = true; + } // namespace detail } // namespace formattable @@ -70,6 +84,22 @@ namespace fmt { } } }; + + template + struct formatter>> + : formatter + { + template + auto format(const T& val, FormatContext& ctx) const { + if constexpr (::formattable::detail::has_to_hex_string_method) + return formatter::format(val.to_hex_string(), ctx); + else { + using namespace formattable; + return formatter::format(to_hex_string(val), ctx); + } + } + }; + template struct formatter>> diff --git a/src/common/fs.h b/src/common/fs.h index 49ee63afb..bc6ce7054 100644 --- a/src/common/fs.h +++ b/src/common/fs.h @@ -20,16 +20,7 @@ namespace fs { #else #include -#include "formattable.h" namespace fs = ghc::filesystem; -namespace formattable { - template <> inline constexpr bool via_to_string = true; - - inline std::string to_string(const ghc::filesystem::path& path) { - return path.string(); - } -} - #endif diff --git a/src/common/scoped_message_writer.cpp b/src/common/scoped_message_writer.cpp index 8d62d4055..c027687ec 100644 --- a/src/common/scoped_message_writer.cpp +++ b/src/common/scoped_message_writer.cpp @@ -5,18 +5,26 @@ namespace tools { static auto logcat = log::Cat("msgwriter"); +scoped_message_writer& scoped_message_writer::flush() +{ + if (!m_content.empty()) + { + logcat->log(m_log_level, "{}{}", m_prefix, m_content); + + if (m_color) { + rdln::suspend_readline pause_readline; + fmt::print(fg(*m_color), "{}{}\n", m_prefix, m_content); + } + else + fmt::print("{}{}\n", m_prefix, m_content); + + m_content.clear(); + } + return *this; +} scoped_message_writer::~scoped_message_writer() { - if (m_flush) - { - m_flush = false; - if (fmt::terminal_color::white == m_color) - logcat->log(m_log_level, m_oss.str()); - else - logcat->log(m_log_level, "{}", - log::detail::text_style_wrapper{fg(m_color), "{}", m_oss.str()}); - std::cout << std::endl; - } + flush(); } } diff --git a/src/common/scoped_message_writer.h b/src/common/scoped_message_writer.h index c89c6f1a0..ab1a5ef62 100644 --- a/src/common/scoped_message_writer.h +++ b/src/common/scoped_message_writer.h @@ -43,59 +43,116 @@ namespace tools class scoped_message_writer { private: - bool m_flush; - std::ostringstream m_oss; - fmt::terminal_color m_color; + std::string m_prefix; + std::string m_content; + std::optional m_color; oxen::log::Level m_log_level; public: - scoped_message_writer( - fmt::terminal_color color = fmt::terminal_color::white - , std::string prefix = {} - , spdlog::level::level_enum log_level = spdlog::level::info - ) - : m_flush(true) - , m_color(color) - , m_log_level(log_level) + explicit scoped_message_writer( + std::optional color = std::nullopt, + std::string prefix = "", + log::Level log_level = log::Level::info + ) + : m_color{color}, m_log_level{log_level}, m_prefix{std::move(prefix)} + {} + + scoped_message_writer(scoped_message_writer&& o) + : m_prefix{std::move(o.m_prefix)}, + m_content{std::move(o.m_content)}, + m_color{o.m_color}, + m_log_level{o.m_log_level} { - m_oss << prefix; + o.m_content.clear(); } - scoped_message_writer(scoped_message_writer&& rhs) - : m_flush(std::move(rhs.m_flush)) - , m_oss(std::move(rhs.m_oss)) - , m_color(std::move(rhs.m_color)) - , m_log_level(std::move(rhs.m_log_level)) - { - rhs.m_flush = false; - } - - scoped_message_writer(scoped_message_writer& rhs) = delete; - scoped_message_writer& operator=(scoped_message_writer& rhs) = delete; + scoped_message_writer(const scoped_message_writer& rhs) = delete; + scoped_message_writer& operator=(const scoped_message_writer& rhs) = delete; scoped_message_writer& operator=(scoped_message_writer&& rhs) = delete; - template - std::ostream& operator<<(const T& val) + /// Appends a message and returns *this (so that it can be chained). If called with more than 1 + /// argument then the first argument is fmt::format'ed with the remaining arguments. + template + scoped_message_writer& append(std::string_view msg, T&&... args) { - m_oss << val; - return m_oss; + if constexpr (sizeof...(T)) + fmt::format_to(std::back_inserter(m_content), msg, std::forward(args)...); + else + m_content.append(msg); + return *this; } + /// Same as .append(msg). (Doesn't format, just like the single-argument .append(msg)). + scoped_message_writer& operator+=(std::string_view msg) { return append(msg); } + + /// Essentially the same as +=, but can only be used on an rvalue instance of the object, so that + /// you can do things like: `scoped_message_writer{} + "abc"`, which feels more natural than + /// `scoped_message_writer{} += "abc"`. + scoped_message_writer&& operator+(std::string_view msg) && { append(msg); return std::move(*this); } + + /// Flushes the current message to output and resets it. This is normally not called explicitly + /// but rather implicitly when the object is destroyed. + scoped_message_writer& flush(); + + /// Prints the complete message on destruction. ~scoped_message_writer(); }; -inline scoped_message_writer success_msg_writer(bool color = true) +template +scoped_message_writer msg_writer(std::optional color = std::nullopt, T&&... args) { - return scoped_message_writer(color ? fmt::terminal_color::green : fmt::terminal_color::white, std::string(), spdlog::level::info); + scoped_message_writer writer{color}; + if constexpr (sizeof...(T)) + writer.append(std::forward(args)...); + return writer; } -inline scoped_message_writer msg_writer(fmt::terminal_color color = fmt::terminal_color::white) +template +scoped_message_writer msg_writer(std::string_view msg, T&&... args) { - return scoped_message_writer(color, std::string(), spdlog::level::info); + return msg_writer(std::nullopt, msg, std::forward(args)...); } -inline scoped_message_writer fail_msg_writer() + +constexpr std::optional success_color{fmt::terminal_color::green}; +constexpr std::optional fail_color{fmt::terminal_color::red}; + +/// Constructs and returns a scoped_message_writer for a typical success message, with or without +/// color, as specified by the first argument. If additional arguments are provided they will be +/// passed to append(...) to set a message (or formatted message, if multiple arguments are given). +/// +/// (We deduce the Bool argument here to avoid implicit conversion to bool from non-bool values). +template , int> = 0> +scoped_message_writer success_msg_writer(Bool color, T&&... args) { - return scoped_message_writer(fmt::terminal_color::red, "Error: ", spdlog::level::err); + auto writer = msg_writer(color ? success_color : std::nullopt); + if constexpr (sizeof...(T)) + writer.append(std::forward(args)...); + return writer; +} + +inline scoped_message_writer success_msg_writer() +{ + return success_msg_writer(true); +} + +/// Same as above, but for calling without just a message (with a bool). Color will be true. +template +scoped_message_writer success_msg_writer(std::string_view msg, T&&... args) +{ + return success_msg_writer(true, msg, std::forward(args)...); +} + +/// Constructs and returns a scoped_message_writer for a typical error message. Color will be +/// enabled and the message will be prefixed with "Error: ". Given arguments, if any, are passed to +/// .append() and so can specify either a single unformatted string, or a format string + format +/// arguments. +template +scoped_message_writer fail_msg_writer(T&&... args) +{ + scoped_message_writer writer{fail_color, "Error: ", spdlog::level::err}; + if constexpr (sizeof...(T)) + writer.append(std::forward(args)...); + return writer; } } // namespace tools diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp index f81db17d0..9d09b01e1 100644 --- a/src/common/string_util.cpp +++ b/src/common/string_util.cpp @@ -1,7 +1,6 @@ #include "string_util.h" +#include #include -#include -#include namespace tools { @@ -80,66 +79,39 @@ std::string lowercase_ascii_string(std::string_view src) } std::string friendly_duration(std::chrono::nanoseconds dur) { - std::ostringstream os; + std::string friendly; + auto append = std::back_inserter(friendly); bool some = false; if (dur >= 24h) { - os << dur / 24h << 'd'; + fmt::format_to(append, "{}d", dur / 24h); dur %= 24h; some = true; } if (dur >= 1h || some) { - os << dur / 1h << 'h'; + fmt::format_to(append, "{}h", dur / 1h); dur %= 1h; some = true; } if (dur >= 1min || some) { - os << dur / 1min << 'm'; + fmt::format_to(append, "{}m", dur / 1min); dur %= 1min; some = true; } if (some || dur == 0s) { // If we have >= minutes or its exactly 0 seconds then don't bother with fractional seconds - os << dur / 1s << 's'; + fmt::format_to(append, "{}s", dur / 1s); } else { double seconds = std::chrono::duration(dur).count(); - os.precision(3); if (dur >= 1s) - os << seconds << "s"; + fmt::format_to(append, "{:.3f}s", seconds); else if (dur >= 1ms) - os << seconds * 1000 << "ms"; + fmt::format_to(append, "{:.3f}ms", seconds * 1000); else if (dur >= 1us) - os << seconds * 1'000'000 << u8"µs"; + fmt::format_to(append, "{:.3f}µs", seconds * 1'000'000); else - os << seconds * 1'000'000'000 << "ns"; + fmt::format_to(append, "{:.0f}ns", seconds * 1'000'000'000); } - return os.str(); + return friendly; } -std::string short_duration(std::chrono::duration dur) { - std::ostringstream os; - os << std::fixed << std::setprecision(1); - if (dur >= 36h) - os << dur / 24h; - else if (dur >= 90min) - os << dur / 1h; - else if (dur >= 90s) - os << dur / 1min; - else if (dur >= 1s) - os << dur / 1s; - else if (dur >= 100ms) - os << std::setprecision(0) << dur / 1ms; - else if (dur >= 1ms) - os << dur / 1ms; - else if (dur >= 100us) - os << std::setprecision(0) << dur / 1us; - else if (dur >= 1us) - os << dur / 1us; - else if (dur >= 1ns) - os << std::setprecision(0) << dur / 1ns; - else - os << "0s"; - return os.str(); -} - - } diff --git a/src/common/string_util.h b/src/common/string_util.h index 2e9725baa..165338e00 100644 --- a/src/common/string_util.h +++ b/src/common/string_util.h @@ -4,9 +4,9 @@ #include #include #include -#include #include #include +#include #include "epee/span.h" // epee namespace tools { @@ -60,30 +60,28 @@ std::vector split(std::string_view str, std::string_view delim std::vector split_any(std::string_view str, std::string_view delims, bool trim = false); /// Joins [begin, end) with a delimiter and returns the resulting string. Elements can be anything -/// that can be sent to an ostream via `<<`. +/// that can be formatted. Semi-deprecated: this just uses fmt to join. template std::string join(std::string_view delimiter, It begin, It end) { - std::ostringstream o; - if (begin != end) - o << *begin++; - while (begin != end) - o << delimiter << *begin++; - return o.str(); + return fmt::format("{}", fmt::join(begin, end, delimiter)); } -/// Wrapper around the above that takes a container and passes c.begin(), c.end() to the above. +/// Same as the above, but works on a container. Just use fmt::join. template -std::string join(std::string_view delimiter, const Container& c) { return join(delimiter, c.begin(), c.end()); } +std::string join(std::string_view delimiter, const Container& c) { + return fmt::format("{}", fmt::join(c, delimiter)); +} /// Similar to join(), but first applies a transformation to each element. template std::string join_transform(std::string_view delimiter, It begin, It end, UnaryOperation transform) { - std::ostringstream o; + std::string result; + auto append = std::back_inserter(result); if (begin != end) - o << transform(*begin++); + result = fmt::format("{}", transform(*begin++)); while (begin != end) - o << delimiter << transform(*begin++); - return o.str(); + fmt::format_to(append, "{}{}", delimiter, transform(*begin++)); + return result; } /// Wrapper around the above that takes a container and passes c.begin(), c.end(). @@ -92,22 +90,23 @@ std::string join_transform(std::string_view delimiter, const Container& c, Unary return join_transform(delimiter, c.begin(), c.end(), std::forward(transform)); } -/// Concatenates a bunch of random values together with delim as a separator via << operator. +/// Concatenates a bunch of random values together with delim as a separator via fmt::format. /// Returns the result as a string. template std::string join_stuff(std::string_view delim, T&& first, Ts&&... stuff) { - std::ostringstream o; - o << std::forward(first); - ((o << delim << std::forward(stuff)), ...); - return o.str(); + std::string result = fmt::format(std::forward(first)); + auto append = std::back_inserter(result); + (fmt::format_to(append, "{}{}", delim, std::forward(stuff)), ...); + return result; } -/// Concatenates arguments via << operator, returns as a string. +/// Concatenates arguments via fmt::format operator, returns as a string. template std::string concat(T&&... stuff) { - std::ostringstream o; - (o << ... << std::forward(stuff)); - return o.str(); + std::string result; + auto append = std::back_inserter(result); + (fmt::format_to(append, "{}", std::forward(stuff)), ...); + return result; } /// Simple version of whitespace trimming: mutates the given string view to remove leading diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h index 9f99f8d88..7670fba3c 100644 --- a/src/crypto/crypto.h +++ b/src/crypto/crypto.h @@ -41,6 +41,8 @@ #include "epee/mlocker.h" #include "generic-ops.h" #include "common/hex.h" +#include "common/format.h" +#include "common/formattable.h" #include "hash.h" namespace crypto { @@ -284,27 +286,11 @@ namespace crypto { const public_key& pub, const signature& sig); - inline std::ostream &operator <<(std::ostream &o, const crypto::public_key &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::secret_key &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::key_derivation &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::key_image &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::signature &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::ed25519_public_key &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::x25519_public_key &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } + inline std::string to_string(const ec_point& P) { return "<{}>"_format(tools::type_to_hex(P)); } + inline std::string to_string(const signature& s) { return "<{}>"_format(tools::type_to_hex(s)); } + inline std::string to_string(const ed25519_public_key& P) { return "<{}>"_format(tools::type_to_hex(P)); } + inline std::string to_string(const x25519_public_key& P) { return "<{}>"_format(tools::type_to_hex(P)); } + constexpr inline crypto::public_key null_pkey{}; const inline crypto::secret_key null_skey{}; } @@ -315,3 +301,8 @@ CRYPTO_MAKE_HASHABLE(key_image) CRYPTO_MAKE_HASHABLE(signature) CRYPTO_MAKE_HASHABLE(ed25519_public_key) CRYPTO_MAKE_HASHABLE(x25519_public_key) + +template <> inline constexpr bool formattable::via_to_string = true; +template <> inline constexpr bool formattable::via_to_string = true; +template <> inline constexpr bool formattable::via_to_string = true; +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/crypto/fmt.h b/src/crypto/fmt.h deleted file mode 100644 index a8ad8a6e0..000000000 --- a/src/crypto/fmt.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include "common/format.h" -#include "crypto.h" -#include "hash.h" - -namespace crypto { - template - constexpr bool is_hex_printable = false; - - template - constexpr bool is_hex_printable && sizeof(T) == sizeof(ec_point)>> = true; - - template <> inline constexpr bool is_hex_printable = true; - template <> inline constexpr bool is_hex_printable = true; - template <> inline constexpr bool is_hex_printable = true; - template <> inline constexpr bool is_hex_printable = true; - template <> inline constexpr bool is_hex_printable = true; - - template inline constexpr bool is_hex_printable = is_hex_printable; - template inline constexpr bool is_hex_printable = is_hex_printable; - template inline constexpr bool is_hex_printable = is_hex_printable; - - // Helper for when you are really sure you want to print a secret key (which is not printable by - // default so that you have to be explicit and can't accidentally expose one in a log - // statement). - inline std::string expose_secret(const ec_scalar& secret) { - return "<{}>"_format(tools::type_to_hex(secret)); - } -} - -template -struct fmt::formatter>> : fmt::formatter { - auto format(const T& v, format_context& ctx) { - return formatter::format("<{}>"_format(tools::type_to_hex(v)), ctx); - } -}; diff --git a/src/crypto/hash.h b/src/crypto/hash.h index e950842f4..c74e979bc 100644 --- a/src/crypto/hash.h +++ b/src/crypto/hash.h @@ -35,6 +35,8 @@ #include "generic-ops.h" #include "common/hex.h" +#include "common/formattable.h" +#include "common/format.h" #include "crypto/cn_heavy_hash.hpp" namespace crypto { @@ -156,12 +158,9 @@ namespace crypto { return c; } - inline std::ostream &operator <<(std::ostream &o, const crypto::hash &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } - inline std::ostream &operator <<(std::ostream &o, const crypto::hash8 &v) { - return o << '<' << tools::type_to_hex(v) << '>'; - } + + inline std::string to_hex_string(const crypto::hash& h) { return "<{}>"_format(tools::type_to_hex(h)); } + inline std::string to_hex_string(const crypto::hash8& h) { return "<{}>"_format(tools::type_to_hex(h)); } constexpr inline crypto::hash null_hash = {}; constexpr inline crypto::hash8 null_hash8 = {}; @@ -169,3 +168,6 @@ namespace crypto { CRYPTO_MAKE_HASHABLE(hash) CRYPTO_MAKE_COMPARABLE(hash8) + +template <> inline constexpr bool formattable::via_to_hex_string = true; +template <> inline constexpr bool formattable::via_to_hex_string = true; diff --git a/src/cryptonote_basic/cryptonote_basic.h b/src/cryptonote_basic/cryptonote_basic.h index 83a69ac24..3d014eda9 100644 --- a/src/cryptonote_basic/cryptonote_basic.h +++ b/src/cryptonote_basic/cryptonote_basic.h @@ -31,7 +31,6 @@ #pragma once #include -#include #include #include "serialization/variant.h" #include "serialization/vector.h" @@ -176,9 +175,6 @@ namespace cryptonote { public: - static char const* version_to_string(txversion v); - static char const* type_to_string(txtype type); - static constexpr txversion get_min_version_for_hf(hf hf_version); static txversion get_max_version_for_hf(hf hf_version); static constexpr txtype get_max_type_for_hf (hf hf_version); @@ -560,42 +556,6 @@ namespace cryptonote return result; } - inline const char* transaction_prefix::version_to_string(txversion v) - { - switch(v) - { - case txversion::v1: return "1"; - case txversion::v2_ringct: return "2_ringct"; - case txversion::v3_per_output_unlock_times: return "3_per_output_unlock_times"; - case txversion::v4_tx_types: return "4_tx_types"; - default: assert(false); return "xx_unhandled_version"; - } - } - - inline const char* transaction_prefix::type_to_string(txtype type) - { - switch(type) - { - case txtype::standard: return "standard"; - case txtype::state_change: return "state_change"; - case txtype::key_image_unlock: return "key_image_unlock"; - case txtype::stake: return "stake"; - case txtype::oxen_name_system: return "oxen_name_system"; - default: assert(false); return "xx_unhandled_type"; - } - } - - inline std::ostream& operator<<(std::ostream& os, txtype t) { - return os << transaction::type_to_string(t); - } - inline std::ostream& operator<<(std::ostream& os, txversion v) { - return os << transaction::version_to_string(v); - } - - inline std::ostream& operator<<(std::ostream& os, hf v) = delete;/*{ - return os << "HF" << static_cast(v); - }*/ - // Serialization for the `hf` type; this is simply writing/reading the underlying uint8_t value template void serialize_value(Archive& ar, hf& x) { @@ -606,21 +566,6 @@ namespace cryptonote } } -template <> -struct fmt::formatter : fmt::formatter { - auto format(cryptonote::txtype t, format_context& ctx) { - return formatter::format( - cryptonote::transaction::type_to_string(t), ctx); - } -}; -template <> -struct fmt::formatter : fmt::formatter { - auto format(cryptonote::txversion v, format_context& ctx) { - return formatter::format( - cryptonote::transaction::version_to_string(v), ctx); - } -}; - namespace std { template <> struct hash @@ -648,3 +593,5 @@ VARIANT_TAG(cryptonote::txout_to_scripthash, "scripthash", 0x1); VARIANT_TAG(cryptonote::txout_to_key, "key", 0x2); VARIANT_TAG(cryptonote::transaction, "tx", 0xcc); VARIANT_TAG(cryptonote::block, "block", 0xbb); + +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index b12ef8559..9f5320efe 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -46,7 +46,6 @@ #include "cryptonote_config.h" #include "crypto/crypto.h" #include "crypto/hash.h" -#include "crypto/fmt.h" #include "ringct/rctSigs.h" #include "cryptonote_basic/verification_context.h" #include "cryptonote_core/service_node_voting.h" @@ -269,7 +268,7 @@ namespace cryptonote bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); if (!r) { - log::warning(logcat, "key image helper: failed to generate_key_derivation({}, <{}>)", tx_public_key, expose_secret(ack.m_view_secret_key)); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, <{}>)", tx_public_key, tools::type_to_hex(ack.m_view_secret_key)); memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation)); } @@ -280,7 +279,7 @@ namespace cryptonote r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); if (!r) { - log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], expose_secret(ack.m_view_secret_key)); + log::warning(logcat, "key image helper: failed to generate_key_derivation({}, {})", additional_tx_public_keys[i], tools::type_to_hex(ack.m_view_secret_key)); } else { @@ -902,13 +901,13 @@ namespace cryptonote { if (!tx.is_transfer() && tx.vout.size() != 0) { - log::warning(logcat, "tx type: {} must have 0 outputs, received: {}, id={}", transaction::type_to_string(tx.type), tx.vout.size(), get_transaction_hash(tx)); + log::warning(logcat, "tx type: {} must have 0 outputs, received: {}, id={}", tx.type, tx.vout.size(), get_transaction_hash(tx)); return false; } if (tx.version >= txversion::v3_per_output_unlock_times && tx.vout.size() != tx.output_unlock_times.size()) { - log::warning(logcat, "tx version: {} must have equal number of output unlock times and outputs", transaction::version_to_string(tx.version)); + log::warning(logcat, "tx version: {} must have equal number of output unlock times and outputs", tx.version); return false; } @@ -1104,7 +1103,7 @@ namespace cryptonote if (tvc.m_key_image_blacklisted) os << "Key image is blacklisted on the service node network, "; if (tx) - os << "TX Version: " << tx->version << ", Type: " << tx->type; + os << "TX Version: {}, Type: {}"_format(tx->version, tx->type); std::string buf = os.str(); if (buf.size() >= 2 && buf[buf.size() - 2] == ',') diff --git a/src/cryptonote_basic/cryptonote_format_utils.h b/src/cryptonote_basic/cryptonote_format_utils.h index ac71e511a..1be774a75 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.h +++ b/src/cryptonote_basic/cryptonote_format_utils.h @@ -248,12 +248,10 @@ namespace cryptonote bool is_valid_address(const std::string address, cryptonote::network_type nettype, bool allow_subaddress = true, bool allow_integrated = true); - inline std::ostream &operator<<(std::ostream &stream, transaction const &tx) + inline std::string to_string(const transaction& tx) { - stream << "tx={version=" << tx.version << ", type=" << tx.type << ", hash=" << get_transaction_hash(tx) << "}"; - return stream; + return "tx={{version={}, type={}, hash={}}}"_format(tx.version, tx.type, get_transaction_hash(tx)); } - //--------------------------------------------------------------- template bool t_serializable_object_from_blob(T& to, const std::string& blob) diff --git a/src/cryptonote_basic/subaddress_index.h b/src/cryptonote_basic/subaddress_index.h index 197a4913e..a96b53a0f 100644 --- a/src/cryptonote_basic/subaddress_index.h +++ b/src/cryptonote_basic/subaddress_index.h @@ -34,6 +34,8 @@ #include #include "common/oxen.h" +#include "common/formattable.h" +#include "common/format.h" namespace cryptonote { @@ -48,7 +50,7 @@ namespace cryptonote std::string to_string() const { - return std::to_string(major) + '/' + std::to_string(minor); + return "{}/{}"_format(major, minor); } BEGIN_KV_SERIALIZE_MAP() @@ -62,14 +64,10 @@ namespace cryptonote field(ar, "major", x.major); field(ar, "minor", x.minor); } - - inline std::ostream& operator<<(std::ostream& out, const cryptonote::subaddress_index& subaddr_index) - { - return out << subaddr_index.major << '/' << subaddr_index.minor; - } - } +template <> inline constexpr bool formattable::via_to_string = true; + namespace std { template <> diff --git a/src/cryptonote_basic/tx_extra.h b/src/cryptonote_basic/tx_extra.h index 59d95a215..52e86e183 100644 --- a/src/cryptonote_basic/tx_extra.h +++ b/src/cryptonote_basic/tx_extra.h @@ -113,6 +113,7 @@ struct alignas(size_t) generic_owner std::string to_string(cryptonote::network_type nettype) const; explicit operator bool() const { return (type == generic_owner_sig_type::monero) ? wallet.address != cryptonote::null_address : ed25519; } bool operator==(generic_owner const &other) const; + bool operator!=(generic_owner const &other) const { return !(*this == other); } BEGIN_SERIALIZE() ENUM_FIELD(type, type < generic_owner_sig_type::_count) @@ -149,9 +150,6 @@ struct generic_signature }; static_assert(sizeof(crypto::ed25519_signature) == sizeof(crypto::signature), "ONS allows storing either ed25519 or monero style signatures, we store all signatures into crypto::signature in ONS"); -inline std::ostream &operator<<(std::ostream &o, const generic_signature &v) { - return o << '<' << tools::type_to_hex(v.data) << '>'; -} } // namespace ons diff --git a/src/cryptonote_basic/txtypes.h b/src/cryptonote_basic/txtypes.h index 4e6fdd387..308f8cf30 100644 --- a/src/cryptonote_basic/txtypes.h +++ b/src/cryptonote_basic/txtypes.h @@ -1,10 +1,15 @@ #pragma once #include +#include +#include +#include "common/formattable.h" namespace cryptonote { -enum class txversion : uint16_t { + using namespace std::literals; + + enum class txversion : uint16_t { v0 = 0, v1, v2_ringct, @@ -21,4 +26,31 @@ enum class txversion : uint16_t { _count }; + inline constexpr std::string_view to_string(txversion v) { + switch(v) + { + case txversion::v1: return "1"sv; + case txversion::v2_ringct: return "2_ringct"sv; + case txversion::v3_per_output_unlock_times: return "3_per_output_unlock_times"sv; + case txversion::v4_tx_types: return "4_tx_types"sv; + default: assert(false); return "xx_unhandled_version"sv; + } + } + + inline constexpr std::string_view to_string(txtype type) + { + switch(type) + { + case txtype::standard: return "standard"sv; + case txtype::state_change: return "state_change"sv; + case txtype::key_image_unlock: return "key_image_unlock"sv; + case txtype::stake: return "stake"sv; + case txtype::oxen_name_system: return "oxen_name_system"sv; + default: assert(false); return "xx_unhandled_type"sv; + } + } + } + +template <> inline constexpr bool formattable::via_to_string = true; +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 7ce54979c..d11233436 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -41,6 +41,7 @@ #include "common/hex.h" #include "common/string_util.h" #include "common/median.h" +#include "common/fs-format.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_basic_impl.h" #include "cryptonote_basic/hardfork.h" diff --git a/src/cryptonote_core/cryptonote_core.cpp b/src/cryptonote_core/cryptonote_core.cpp index bcfdad16c..72cc4a7eb 100644 --- a/src/cryptonote_core/cryptonote_core.cpp +++ b/src/cryptonote_core/cryptonote_core.cpp @@ -34,7 +34,6 @@ #include "epee/string_tools.h" #include -#include #include #include @@ -50,6 +49,7 @@ extern "C" { #include "cryptonote_core.h" #include "uptime_proof.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/sha256sum.h" #include "common/threadpool.h" #include "common/command_line.h" @@ -1488,11 +1488,11 @@ namespace cryptonote } else { - std::ostringstream os; - os << "Blink validation failed:"; + std::string blink_error = "Blink validation failed:"; + auto append = std::back_inserter(blink_error); for (auto &f : failures) - os << " [" << int(bdata.quorum[f.first]) << ":" << int(bdata.position[f.first]) << "]: " << f.second; - log::info(logcat, "Invalid blink tx {}: {}", bdata.tx_hash, os.str()); + fmt::format_to(append, " [{}:{}]: {}", int(bdata.quorum[f.first]), int(bdata.position[f.first]), f.second); + log::info(logcat, "Invalid blink tx {}: {}", bdata.tx_hash, blink_error); } } diff --git a/src/cryptonote_core/cryptonote_tx_utils.cpp b/src/cryptonote_core/cryptonote_tx_utils.cpp index 18e6fb16a..9ef7bcd4d 100644 --- a/src/cryptonote_core/cryptonote_tx_utils.cpp +++ b/src/cryptonote_core/cryptonote_tx_utils.cpp @@ -41,7 +41,6 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "crypto/crypto.h" #include "crypto/hash.h" -#include "crypto/fmt.h" #include "ringct/rctSigs.h" #include "multisig/multisig.h" #include "epee/int-util.h" diff --git a/src/cryptonote_core/oxen_name_system.cpp b/src/cryptonote_core/oxen_name_system.cpp index 2a12b9a03..6c13f4ad0 100644 --- a/src/cryptonote_core/oxen_name_system.cpp +++ b/src/cryptonote_core/oxen_name_system.cpp @@ -9,6 +9,7 @@ #include "common/oxen.h" #include "common/string_util.h" +#include "common/fs-format.h" #include "crypto/hash.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_basic_impl.h" @@ -132,20 +133,18 @@ namespace { std::string ons_extra_string(cryptonote::network_type nettype, cryptonote::tx_extra_oxen_name_system const &data) { - std::stringstream stream; - stream << "ONS Extra={"; + std::string extra = "ONS Extra={"; + auto append = std::back_inserter(extra); if (data.is_buying()) - { - stream << "owner=" << data.owner.to_string(nettype); - stream << ", backup_owner=" << (data.backup_owner ? data.backup_owner.to_string(nettype) : "(none)"); - } + fmt::format_to(append, "owner={}, backup_owner={}", + data.owner.to_string(nettype), (data.backup_owner ? data.backup_owner.to_string(nettype) : "(none)")); else if (data.is_renewing()) - stream << "renewal"; + extra += "renewal"; else - stream << "signature=" << tools::type_to_hex(data.signature.data); + fmt::format_to(append, "signature={}", tools::type_to_hex(data.signature.data)); - stream << ", type=" << data.type << ", name_hash=" << data.name_hash << "}"; - return stream.str(); + fmt::format_to(append, ", type={}, name_hash={}}}", data.type, data.name_hash); + return extra; } /// Clears any existing bindings @@ -742,13 +741,9 @@ static constexpr bool char_is_alphanum_or(char c) static constexpr bool char_is_alphanum(char c) { return char_is_alphanum_or<>(c); } template -static bool check_condition(bool condition, std::string* reason, T&&... args) { +static bool check_condition(bool condition, std::string* reason, std::string_view format, T&&... args) { if (condition && reason) - { - std::ostringstream os; - (os << ... << std::forward(args)); - *reason = os.str(); - } + *reason = fmt::format(format, std::forward(args)...); return condition; } @@ -766,17 +761,15 @@ bool validate_ons_name(mapping_type type, std::string name, std::string *reason) else { if (reason) - { - std::stringstream err_stream; - err_stream << "ONS type=" << mapping_type_str(type) << ", specifies unhandled mapping type in name validation"; - *reason = err_stream.str(); - } + *reason = "ONS type={} specifies unhandled mapping type in name validation"_format(type); return false; } // NOTE: Validate name length name = tools::lowercase_ascii_string(name); - if (check_condition((name.empty() || name.size() > max_name_len), reason, "ONS type=", type, ", specifies mapping from name->value where the name's length=", name.size(), " is 0 or exceeds the maximum length=", max_name_len, ", given name=", name)) + if (check_condition((name.empty() || name.size() > max_name_len), reason, + "ONS type={} specifies mapping from name->value where the name's length={} is 0 or exceeds the maximum length={}, given name={}", + type, name.size(), max_name_len, name)) return false; std::string_view name_view{name}; // Will chop this down as we validate each part @@ -796,41 +789,46 @@ bool validate_ons_name(mapping_type type, std::string name, std::string *reason) // domains (in which case the user looking up "foo.loki" would try end up trying to resolve // "foo.loki.loki"). for (auto& reserved : {"localhost.loki"sv, "loki.loki"sv, "snode.loki"sv}) - if (check_condition(name == reserved, reason, "ONS type=", type, ", specifies mapping from name->value using protocol reserved name=", name)) + if (check_condition(name == reserved, reason, + "ONS type={} specifies mapping from name->value using protocol reserved name={}", type, name)) return false; auto constexpr SHORTEST_DOMAIN = "a.loki"sv; - if (check_condition(name.size() < SHORTEST_DOMAIN.size(), reason, "ONS type=", type, ", specifies mapping from name->value where the name is shorter than the shortest possible name=", SHORTEST_DOMAIN, ", given name=", name)) + if (check_condition(name.size() < SHORTEST_DOMAIN.size(), reason, + "ONS type={} specifies mapping from name->value where the name is shorter than the shortest possible name={}, given name={}", type, SHORTEST_DOMAIN, name)) return false; // Must end with .loki auto constexpr SUFFIX = ".loki"sv; - if (check_condition(!tools::ends_with(name_view, SUFFIX), reason, "ONS type=", type, ", specifies mapping from name->value where the name does not end with the domain .loki, name=", name)) + if (check_condition(!tools::ends_with(name_view, SUFFIX), reason, + "ONS type={} specifies mapping from name->value where the name does not end with the domain .loki, name={}", type, name)) return false; name_view.remove_suffix(SUFFIX.size()); // All domains containing '--' as 3rd/4th letter are reserved except for xn-- punycode domains if (check_condition(name_view.size() >= 4 && name_view.substr(2, 2) == "--"sv && !tools::starts_with(name_view, "xn--"sv), - reason, "ONS type=", type, ", specifies reserved name `?\?--*.loki': ", name)) + reason, "ONS type={} specifies reserved name `?\?--*.loki': {}", type, name)) return false; // Must start with alphanumeric - if (check_condition(!char_is_alphanum(name_view.front()), reason, "ONS type=", type, ", specifies mapping from name->value where the name does not start with an alphanumeric character, name=", name)) + if (check_condition(!char_is_alphanum(name_view.front()), reason, + "ONS type={} specifies mapping from name->value where the name does not start with an alphanumeric character, name={}", type, name)) return false; name_view.remove_prefix(1); if (!name_view.empty()) { // Character preceding .loki must be alphanumeric - if (check_condition(!char_is_alphanum(name_view.back()), reason, "ONS type=", type ,", specifies mapping from name->value where the character preceding the .loki is not alphanumeric, char=", name_view.back(), ", name=", name)) + if (check_condition(!char_is_alphanum(name_view.back()), reason, + "ONS type={} specifies mapping from name->value where the character preceding the .loki is not alphanumeric, char={}, name={}", type, name_view.back(), name)) return false; name_view.remove_suffix(1); } // Inbetween start and preceding suffix, (alphanumeric or hyphen) characters permitted if (check_condition(!std::all_of(name_view.begin(), name_view.end(), char_is_alphanum_or<'-'>), - reason, "ONS type=", type, ", specifies mapping from name->value where the domain name contains more than the permitted alphanumeric or hyphen characters, name=", name)) + reason, "ONS type={} specifies mapping from name->value where the domain name contains more than the permitted alphanumeric or hyphen characters, name={}", type, name)) return false; } else if (type == mapping_type::session || type == mapping_type::wallet) @@ -840,20 +838,22 @@ bool validate_ons_name(mapping_type type, std::string name, std::string *reason) // ^[a-z0-9_]([a-z0-9-_]*[a-z0-9_])?$ // Must start with (alphanumeric or underscore) - if (check_condition(!char_is_alphanum_or<'_'>(name_view.front()), reason, "ONS type=", type, ", specifies mapping from name->value where the name does not start with an alphanumeric or underscore character, name=", name)) + if (check_condition(!char_is_alphanum_or<'_'>(name_view.front()), reason, + "ONS type={} specifies mapping from name->value where the name does not start with an alphanumeric or underscore character, name={}", type, name)) return false; name_view.remove_prefix(1); if (!name_view.empty()) { // Must NOT end with a hyphen '-' - if (check_condition(!char_is_alphanum_or<'_'>(name_view.back()), reason, "ONS type=", type, ", specifies mapping from name->value where the last character is a hyphen '-' which is disallowed, name=", name)) + if (check_condition(!char_is_alphanum_or<'_'>(name_view.back()), reason, + "ONS type={} specifies mapping from name->value where the last character is a hyphen '-' which is disallowed, name={}", type, name)) return false; name_view.remove_suffix(1); } // Inbetween start and preceding suffix, (alphanumeric, hyphen or underscore) characters permitted if (check_condition(!std::all_of(name_view.begin(), name_view.end(), char_is_alphanum_or<'-', '_'>), - reason, "ONS type=", type, ", specifies mapping from name->value where the name contains more than the permitted alphanumeric, underscore or hyphen characters, name=", name)) + reason, "ONS type={} specifies mapping from name->value where the name contains more than the permitted alphanumeric, underscore or hyphen characters, name={}", type, name)) return false; } else @@ -886,11 +886,8 @@ static bool check_lengths(mapping_type type, std::string_view value, size_t max, { if (reason) { - std::stringstream err_stream; - err_stream << "ONS type=" << type << ", specifies mapping from name_hash->encrypted_value where the value's length=" << value.size() << ", does not equal the required length=" << max << ", given value="; - if (binary_val) err_stream << oxenc::to_hex(value); - else err_stream << value; - *reason = err_stream.str(); + *reason = "ONS type={} specifies mapping from name_hash->encrypted_value where the value's length={} does not equal the required length={}, given value={}"_format( + type, value.size(), max, binary_val ? oxenc::to_hex(value) : value); } } @@ -903,7 +900,6 @@ bool mapping_value::validate(cryptonote::network_type nettype, mapping_type type if (blob) *blob = {}; // Check length of the value - std::stringstream err_stream; cryptonote::address_parse_info addr_info = {}; if (type == mapping_type::wallet) { @@ -912,15 +908,9 @@ bool mapping_value::validate(cryptonote::network_type nettype, mapping_type type if (reason) { if (value.empty()) - { - err_stream << "The value=" << value; - err_stream << ", mapping into the wallet address, specifies a wallet address of 0 length"; - } + *reason = "The value={}, mapping into the wallet address, specifies a wallet address of 0 length"_format(value); else - { - err_stream << "Could not convert the wallet address string, check it is correct, value=" << value; - } - *reason = err_stream.str(); + *reason = "Could not convert the wallet address string, check it is correct, value={}"_format(value); } return false; } @@ -955,7 +945,7 @@ bool mapping_value::validate(cryptonote::network_type nettype, mapping_type type // 51 base32z chars (=255 bits) followed by a 1-bit value ('y'=0, or 'o'=0b10000); anything else // in the last spot isn't a valid lokinet address. if (check_condition(value.size() != 57 || !tools::ends_with(value, ".loki") || !oxenc::is_base32z(value.substr(0, 52)) || !(value[51] == 'y' || value[51] == 'o'), - reason, "'", value, "' is not a valid lokinet address")) + reason, "'{}' is not a valid lokinet address", value)) return false; if (blob) @@ -968,14 +958,17 @@ bool mapping_value::validate(cryptonote::network_type nettype, mapping_type type { assert(type == mapping_type::session); // NOTE: Check value is hex of the right size - if (check_condition(value.size() != 2*SESSION_PUBLIC_KEY_BINARY_LENGTH, reason, "The value=", value, " is not the required ", 2*SESSION_PUBLIC_KEY_BINARY_LENGTH, "-character hex string session public key, length=", value.size())) + if (check_condition(value.size() != 2*SESSION_PUBLIC_KEY_BINARY_LENGTH, reason, + "The value={} is not the required {}-character hex string session public key, length={}", value, 2*SESSION_PUBLIC_KEY_BINARY_LENGTH, value.size())) return false; - if (check_condition(!oxenc::is_hex(value), reason, ", specifies name -> value mapping where the value is not a hex string given value=")) + if (check_condition(!oxenc::is_hex(value), reason, + "value={} specifies name -> value mapping where the value is not a hex string", value)) return false; // NOTE: Session public keys are 33 bytes, with the first byte being 0x05 and the remaining 32 being the public key. - if (check_condition(!tools::starts_with(value, "05"), reason, "ONS type=session, specifies mapping from name -> ed25519 key where the key is not prefixed with 05, given ed25519=", value)) + if (check_condition(!tools::starts_with(value, "05"), reason, + "ONS type=session specifies mapping from name -> ed25519 key where the key is not prefixed with 05, given ed25519={}", value)) return false; if (blob) // NOTE: Given blob, write the binary output @@ -995,7 +988,6 @@ static_assert(SODIUM_ENCRYPTION_EXTRA_BYTES >= crypto_secretbox_MACBYTES); bool mapping_value::validate_encrypted(mapping_type type, std::string_view value, mapping_value* blob, std::string *reason) { if (blob) *blob = {}; - std::stringstream err_stream; int value_len = crypto_aead_xchacha20poly1305_ietf_ABYTES + crypto_aead_xchacha20poly1305_ietf_NPUBBYTES; @@ -1017,10 +1009,7 @@ bool mapping_value::validate_encrypted(mapping_type type, std::string_view value else { if (reason) - { - err_stream << "Unhandled type passed into " << __func__; - *reason = err_stream.str(); - } + *reason = "Unhandled type passed into {}"_format(__func__); return false; } @@ -1090,9 +1079,6 @@ static bool verify_ons_signature(crypto::hash const &hash, ons::generic_signatur static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint64_t blockchain_height, cryptonote::transaction const &tx, cryptonote::tx_extra_oxen_name_system const &ons_extra, std::string *reason) { - std::stringstream err_stream; - OXEN_DEFER { if (reason && reason->empty()) *reason = err_stream.str(); }; - crypto::hash expected_prev_txid = crypto::null_hash; std::string name_hash = hash_to_base64(ons_extra.name_hash); ons::mapping_record mapping = ons_db.get_mapping(ons_extra.type, name_hash); @@ -1102,20 +1088,25 @@ static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint6 // Updating: the mapping must exist and be active, the updated fields must actually change from // the current value, and a valid signature over the updated values must be present. - if (check_condition(!mapping, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " update requested but mapping does not exist.")) + if (check_condition(!mapping, reason, + "{}, {} update requested but mapping does not exist.", tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; - if (check_condition(!mapping.active(blockchain_height), reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " TX requested to update mapping that has already expired")) + if (check_condition(!mapping.active(blockchain_height), reason, + "{}, {} TX requested to update mapping that has already expired", tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; expected_prev_txid = mapping.txid; - constexpr auto SPECIFYING_SAME_VALUE_ERR = " field to update is specifying the same mapping "sv; - if (check_condition(ons_extra.field_is_set(ons::extra_field::encrypted_value) && ons_extra.encrypted_value == mapping.encrypted_value.to_view(), reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), SPECIFYING_SAME_VALUE_ERR, "value")) + constexpr auto SPECIFYING_SAME_VALUE_ERR = "{}, {} field to update is specifying the same mapping {}"sv; + if (check_condition(ons_extra.field_is_set(ons::extra_field::encrypted_value) && ons_extra.encrypted_value == mapping.encrypted_value.to_view(), reason, + SPECIFYING_SAME_VALUE_ERR, tx, ons_extra_string(ons_db.network_type(), ons_extra), "value")) return false; - if (check_condition(ons_extra.field_is_set(ons::extra_field::owner) && ons_extra.owner == mapping.owner, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), SPECIFYING_SAME_VALUE_ERR, "owner")) + if (check_condition(ons_extra.field_is_set(ons::extra_field::owner) && ons_extra.owner == mapping.owner, reason, + SPECIFYING_SAME_VALUE_ERR, tx, ons_extra_string(ons_db.network_type(), ons_extra), "owner")) return false; - if (check_condition(ons_extra.field_is_set(ons::extra_field::backup_owner) && ons_extra.backup_owner == mapping.backup_owner, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), SPECIFYING_SAME_VALUE_ERR, "backup_owner")) + if (check_condition(ons_extra.field_is_set(ons::extra_field::backup_owner) && ons_extra.backup_owner == mapping.backup_owner, reason, + SPECIFYING_SAME_VALUE_ERR, tx, ons_extra_string(ons_db.network_type(), ons_extra), "backup_owner")) return false; // Validate signature @@ -1124,7 +1115,8 @@ static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint6 ons_extra.field_is_set(ons::extra_field::owner) ? &ons_extra.owner : nullptr, ons_extra.field_is_set(ons::extra_field::backup_owner) ? &ons_extra.backup_owner : nullptr, expected_prev_txid); - if (check_condition(data.empty(), reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " unexpectedly failed to generate signature, please inform the Loki developers")) + if (check_condition(data.empty(), reason, + "{}, {} unexpectedly failed to generate signature, please inform the Oxen developers", tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; crypto::hash hash; @@ -1132,52 +1124,65 @@ static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint6 if (check_condition(!verify_ons_signature(hash, ons_extra.signature, mapping.owner) && !verify_ons_signature(hash, ons_extra.signature, mapping.backup_owner), reason, - tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " failed to verify signature for ONS update, current owner=", mapping.owner.to_string(ons_db.network_type()), ", backup owner=", mapping.backup_owner.to_string(ons_db.network_type()))) + "{}, {} failed to verify signature for ONS update, current owner={}, backup owner={}", + tx, ons_extra_string(ons_db.network_type(), ons_extra), mapping.owner.to_string(ons_db.network_type()), mapping.backup_owner.to_string(ons_db.network_type()))) return false; } else if (ons_extra.is_buying()) { // If buying a new name then the existing name must not be active if (check_condition(mapping.active(blockchain_height), reason, - "Cannot buy an ONS name that is already registered: name_hash=", mapping.name_hash, ", type=", mapping.type, - "; TX: ", tx, "; ", ons_extra_string(ons_db.network_type(), ons_extra))) + "Cannot buy an ONS name that is already registered: name_hash={}, type={}; TX: {}; {}", + mapping.name_hash, mapping.type, tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; // If buying a new wallet name then the existing session name must not be active and vice versa // The owner of an existing name but different type is allowed to register but the owner and backup owners // of the new mapping must be from the same owners and backup owners of the previous mapping ie no // new addresses are allowed to be added as owner or backup owner. - if (ons_extra.type == mapping_type::wallet) + if (ons_extra.type == mapping_type::wallet || ons_extra.type == mapping_type::session) { - ons::mapping_record session_mapping = ons_db.get_mapping(mapping_type::session, name_hash); - if (check_condition(session_mapping.active(blockchain_height) && (!(session_mapping.owner == ons_extra.owner || session_mapping.backup_owner == ons_extra.owner) || !(!ons_extra.field_is_set(ons::extra_field::backup_owner) || session_mapping.backup_owner == ons_extra.backup_owner || session_mapping.owner == ons_extra.backup_owner)), reason, - "Cannot buy an ONS wallet name that has an already registered session name: name_hash=", mapping.name_hash, ", type=", mapping.type, - "; TX: ", tx, "; ", ons_extra_string(ons_db.network_type(), ons_extra))) - return false; - } else if (ons_extra.type == mapping_type::session) { - ons::mapping_record wallet_mapping = ons_db.get_mapping(mapping_type::wallet, name_hash); - if (check_condition(wallet_mapping.active(blockchain_height) && (!(wallet_mapping.owner == ons_extra.owner || wallet_mapping.backup_owner == ons_extra.owner) || !(!ons_extra.field_is_set(ons::extra_field::backup_owner) || wallet_mapping.backup_owner == ons_extra.backup_owner || wallet_mapping.owner == ons_extra.backup_owner)), reason, - "Cannot buy an ONS session name that has an already registered wallet name: name_hash=", mapping.name_hash, ", type=", mapping.type, - "; TX: ", tx, "; ", ons_extra_string(ons_db.network_type(), ons_extra))) + auto buy_type_name = ons_extra.type == mapping_type::wallet ? "wallet"sv : "session"sv; + auto alt_type_name = ons_extra.type == mapping_type::wallet ? "session"sv : "wallet"sv; + auto alt_type = ons_extra.type == mapping_type::wallet ? mapping_type::session : mapping_type::wallet; + + ons::mapping_record alt_mapping = ons_db.get_mapping(alt_type, name_hash); + + auto is_alt_record_owner = [&alt_mapping](const auto& new_owner) { + return new_owner == alt_mapping.owner || new_owner == alt_mapping.backup_owner; + }; + + if (check_condition( + alt_mapping.active(blockchain_height) && // alternative mapping exists + ( + !is_alt_record_owner(ons_extra.owner) || + (ons_extra.field_is_set(ons::extra_field::backup_owner) && !is_alt_record_owner(ons_extra.backup_owner)) + ), + reason, + "Cannot buy an ONS {} name that has an already registered {} name: name_hash={}, type={}; TX: {}; {}", + buy_type_name, alt_type_name, mapping.name_hash, mapping.type, tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; } } else if (ons_extra.is_renewing()) { // We allow anyone to renew a name, but it has to exist and be currently active - if (check_condition(!mapping, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " renewal requested but mapping does not exist.")) + if (check_condition(!mapping, reason, "{}, {} renewal requested but mapping does not exist.", tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; - if (check_condition(!mapping.active(blockchain_height), reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " TX requested to renew mapping that has already expired")) + if (check_condition(!mapping.active(blockchain_height), reason, + "{}, {} TX requested to renew mapping that has already expired", tx, ons_extra_string(ons_db.network_type(), ons_extra))) return false; expected_prev_txid = mapping.txid; } else { - check_condition(true, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " is not a valid buy, update, or renew ONS tx"); + check_condition(true, reason, "{}, {} is not a valid buy, update, or renew ONS tx", tx, ons_extra_string(ons_db.network_type(), ons_extra)); return false; } - if (check_condition(ons_extra.prev_txid != expected_prev_txid, reason, tx, ", ", ons_extra_string(ons_db.network_type(), ons_extra), " specified prior txid=", ons_extra.prev_txid, ", but ONS DB reports=", expected_prev_txid, ", possible competing TX was submitted and accepted before this TX was processed")) + if (check_condition(ons_extra.prev_txid != expected_prev_txid, reason, + "{}, {} specified prior txid {} but expected {}; perhaps a competing ONS TX was submitted and accepted before this ONS update TX was processed?", + tx, ons_extra_string(ons_db.network_type(), ons_extra), ons_extra.prev_txid, expected_prev_txid)) return false; return true; @@ -1192,10 +1197,12 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, // Pull out ONS Extra from TX // ----------------------------------------------------------------------------------------------- { - if (check_condition(tx.type != cryptonote::txtype::oxen_name_system, reason, tx, ", uses wrong tx type, expected=", cryptonote::txtype::oxen_name_system)) + if (check_condition(tx.type != cryptonote::txtype::oxen_name_system, reason, + "{} uses wrong tx type, expected={}", tx, cryptonote::txtype::oxen_name_system)) return false; - if (check_condition(!cryptonote::get_field_from_tx_extra(tx.extra, ons_extra), reason, tx, ", didn't have oxen name service in the tx_extra")) + if (check_condition(!cryptonote::get_field_from_tx_extra(tx.extra, ons_extra), reason, + "{} didn't have oxen name service in the tx_extra", tx)) return false; } @@ -1204,17 +1211,21 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, // Check TX ONS Serialized Fields are NULL if they are not specified // ----------------------------------------------------------------------------------------------- { - constexpr auto VALUE_SPECIFIED_BUT_NOT_REQUESTED = ", given field but field is not requested to be serialised="sv; - if (check_condition(!ons_extra.field_is_set(ons::extra_field::encrypted_value) && ons_extra.encrypted_value.size(), reason, tx, ", ", ons_extra_string(nettype, ons_extra), VALUE_SPECIFIED_BUT_NOT_REQUESTED, "encrypted_value")) + constexpr auto VALUE_SPECIFIED_BUT_NOT_REQUESTED = "{}, {} given field {} but field is not requested to be serialised"sv; + if (check_condition(!ons_extra.field_is_set(ons::extra_field::encrypted_value) && ons_extra.encrypted_value.size(), reason, + VALUE_SPECIFIED_BUT_NOT_REQUESTED, tx, ons_extra_string(nettype, ons_extra), "encrypted_value")) return false; - if (check_condition(!ons_extra.field_is_set(ons::extra_field::owner) && ons_extra.owner, reason, tx, ", ", ons_extra_string(nettype, ons_extra), VALUE_SPECIFIED_BUT_NOT_REQUESTED, "owner")) + if (check_condition(!ons_extra.field_is_set(ons::extra_field::owner) && ons_extra.owner, reason, + VALUE_SPECIFIED_BUT_NOT_REQUESTED, tx, ons_extra_string(nettype, ons_extra), "owner")) return false; - if (check_condition(!ons_extra.field_is_set(ons::extra_field::backup_owner) && ons_extra.backup_owner, reason, tx, ", ", ons_extra_string(nettype, ons_extra), VALUE_SPECIFIED_BUT_NOT_REQUESTED, "backup_owner")) + if (check_condition(!ons_extra.field_is_set(ons::extra_field::backup_owner) && ons_extra.backup_owner, reason, + VALUE_SPECIFIED_BUT_NOT_REQUESTED, tx, ons_extra_string(nettype, ons_extra), "backup_owner")) return false; - if (check_condition(!ons_extra.field_is_set(ons::extra_field::signature) && ons_extra.signature, reason, tx, ", ", ons_extra_string(nettype, ons_extra), VALUE_SPECIFIED_BUT_NOT_REQUESTED, "signature")) + if (check_condition(!ons_extra.field_is_set(ons::extra_field::signature) && ons_extra.signature, reason, + VALUE_SPECIFIED_BUT_NOT_REQUESTED, tx, ons_extra_string(nettype, ons_extra), "signature")) return false; } @@ -1222,22 +1233,28 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, // Simple ONS Extra Validation // ----------------------------------------------------------------------------------------------- { - if (check_condition(ons_extra.version != 0, reason, tx, ", ", ons_extra_string(nettype, ons_extra), " unexpected version=", std::to_string(ons_extra.version), ", expected=0")) + if (check_condition(ons_extra.version != 0, reason, + "{}, {} unexpected version={:d}, expected 0", tx, ons_extra_string(nettype, ons_extra), ons_extra.version)) return false; - if (check_condition(!ons::mapping_type_allowed(hf_version, ons_extra.type), reason, tx, ", ", ons_extra_string(nettype, ons_extra), " specifying type=", ons_extra.type, " is disallowed in HF", +static_cast(hf_version))) + if (check_condition(!ons::mapping_type_allowed(hf_version, ons_extra.type), reason, + "{}, {} specifying type={} is disallowed in HF{:d}", tx, ons_extra_string(nettype, ons_extra), ons_extra.type, static_cast(hf_version))) return false; // ----------------------------------------------------------------------------------------------- // Serialized Values Check // ----------------------------------------------------------------------------------------------- - if (check_condition(!ons_extra.is_buying() && !ons_extra.is_updating() && !ons_extra.is_renewing(), reason, tx, ", ", ons_extra_string(nettype, ons_extra), " TX extra does not specify valid combination of bits for serialized fields=", std::bitset(static_cast(ons_extra.fields)).to_string())) + if (check_condition(!ons_extra.is_buying() && !ons_extra.is_updating() && !ons_extra.is_renewing(), reason, + "{}, {} TX extra does not specify valid combination of bits for serialized fields={}", + tx, ons_extra_string(nettype, ons_extra), std::bitset(static_cast(ons_extra.fields)).to_string())) return false; if (check_condition(ons_extra.field_is_set(ons::extra_field::owner) && ons_extra.field_is_set(ons::extra_field::backup_owner) && ons_extra.owner == ons_extra.backup_owner, - reason, tx, ", ", ons_extra_string(nettype, ons_extra), " specifying owner the same as the backup owner=", ons_extra.backup_owner.to_string(nettype))) + reason, + "{}, {} specifying owner the same as the backup owner={}", + tx, ons_extra_string(nettype, ons_extra), ons_extra.backup_owner.to_string(nettype))) { return false; } @@ -1247,7 +1264,8 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, // ONS Field(s) Validation // ----------------------------------------------------------------------------------------------- { - if (check_condition((ons_extra.name_hash == null_name_hash || ons_extra.name_hash == crypto::null_hash), reason, tx, ", ", ons_extra_string(nettype, ons_extra), " specified the null name hash")) + if (check_condition((ons_extra.name_hash == null_name_hash || ons_extra.name_hash == crypto::null_hash), reason, + "{}, {} specified the null name hash", tx, ons_extra_string(nettype, ons_extra))) return false; if (ons_extra.field_is_set(ons::extra_field::encrypted_value)) @@ -1275,12 +1293,10 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, burn = burn_required; } - if (burn != burn_required) - { - char const *over_or_under = burn > burn_required ? "too much " : "insufficient "; - if (check_condition(true, reason, tx, ", ", ons_extra_string(nettype, ons_extra), " burned ", over_or_under, "oxen=", burn, ", require=", burn_required)) + if (check_condition(burn != burn_required, reason, + "{}, {} burned {} OXEN={}, required={}", + tx, ons_extra_string(nettype, ons_extra), burn > burn_required ? "too much" : "insufficient", burn, burn_required)) return false; - } } return true; diff --git a/src/cryptonote_core/oxen_name_system.h b/src/cryptonote_core/oxen_name_system.h index b038c08b3..7841c66ca 100644 --- a/src/cryptonote_core/oxen_name_system.h +++ b/src/cryptonote_core/oxen_name_system.h @@ -115,9 +115,8 @@ struct mapping_value mapping_value(); mapping_value(std::string encrypted_value, std::string nonce); }; -inline std::ostream &operator<<(std::ostream &os, mapping_value const &v) { return os << oxenc::to_hex(v.to_view()); } -inline std::string_view mapping_type_str(mapping_type type) +inline constexpr std::string_view mapping_type_str(mapping_type type) { switch(type) { @@ -130,7 +129,6 @@ inline std::string_view mapping_type_str(mapping_type type) default: assert(false); return "xx_unhandled_type"sv; } } -inline std::ostream &operator<<(std::ostream &os, mapping_type type) { return os << mapping_type_str(type); } constexpr bool mapping_type_allowed(cryptonote::hf hf_version, mapping_type type) { return (type == mapping_type::session && hf_version >= cryptonote::hf::hf15_ons) diff --git a/src/cryptonote_core/service_node_quorum_cop.h b/src/cryptonote_core/service_node_quorum_cop.h index 9fdfcf116..5f6e28e47 100644 --- a/src/cryptonote_core/service_node_quorum_cop.h +++ b/src/cryptonote_core/service_node_quorum_cop.h @@ -68,11 +68,6 @@ namespace service_nodes END_SERIALIZE() }; - inline std::ostream &operator<<(std::ostream &os, quorum const &q) - { - return os << q.to_string(); - } - struct quorum_manager { @@ -166,9 +161,4 @@ namespace service_nodes uint64_t quorum_checksum(const std::vector &pubkeys, size_t offset = 0); } -template <> -struct fmt::formatter : fmt::formatter { - auto format(service_nodes::quorum quorum, format_context& ctx) { - return formatter::format(quorum.to_string(), ctx); - } -}; +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/cryptonote_core/service_node_voting.h b/src/cryptonote_core/service_node_voting.h index 3245bbe64..a6d26d7a8 100644 --- a/src/cryptonote_core/service_node_voting.h +++ b/src/cryptonote_core/service_node_voting.h @@ -75,10 +75,6 @@ namespace service_nodes } }; - inline std::ostream &operator<<(std::ostream &os, quorum_type q) { - return os << to_string(q); - } - enum struct quorum_group : uint8_t { invalid, validator, worker, _count }; struct quorum_vote_t { @@ -176,11 +172,5 @@ namespace service_nodes mutable std::recursive_mutex m_lock; }; }; // namespace service_nodes - // -template <> -struct fmt::formatter : fmt::formatter { - auto format(service_nodes::quorum_type quorum, format_context& ctx) { - return formatter::format(to_string(quorum), ctx); - } -}; +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/daemon/command_parser_executor.cpp b/src/daemon/command_parser_executor.cpp index 69fef0aed..eb34ccb0b 100644 --- a/src/daemon/command_parser_executor.cpp +++ b/src/daemon/command_parser_executor.cpp @@ -406,14 +406,14 @@ bool command_parser_executor::is_key_image_spent(const std::vector& { if (args.empty()) { - tools::fail_msg_writer() << "Invalid arguments. Expected: is_key_image_spent [ ...]\n"; + tools::fail_msg_writer("Invalid arguments. Expected: is_key_image_spent [ ...]\n"); return true; } std::vector kis; for (const auto& hex : args) { if (!tools::hex_to_type(hex, kis.emplace_back())) { - tools::fail_msg_writer() << "Invalid key image: '" << hex << "'"; + tools::fail_msg_writer("Invalid key image: '{}'", hex); return true; } } @@ -466,7 +466,7 @@ bool command_parser_executor::start_mining(const std::vector& args) } if (info.is_subaddress) { - tools::fail_msg_writer() << "subaddress for mining reward is not yet supported!"; + tools::fail_msg_writer("subaddress for mining reward is not yet supported!"); return true; } @@ -476,7 +476,7 @@ bool command_parser_executor::start_mining(const std::vector& args) unsigned int threads_count = 1, num_blocks = 0; if (threads_val.size() && !tools::parse_int(threads_val, threads_count)) { - tools::fail_msg_writer() << "Failed to parse threads value" << threads_val; + tools::fail_msg_writer("Failed to parse threads value {}", threads_val); return false; } @@ -510,14 +510,14 @@ bool command_parser_executor::set_limit(const std::vector& args) return m_executor.get_limit(); if (args.size() > 2) { - tools::fail_msg_writer() << "Too many arguments: expected 0-2 values"; + tools::fail_msg_writer("Too many arguments ({}): expected 0-2 values", args.size()); return false; } int64_t limit_down; if (args[0] == "default") // Accept "default" as a string because getting -1 through the cli arg parsing is a nuissance limit_down = -1; else if (!tools::parse_int(args[0], limit_down)) { - tools::fail_msg_writer() << "Failed to parse '" << args[0] << "' as a limit"; + tools::fail_msg_writer("Failed to parse '{}' as a limit", args[0]); return false; } @@ -527,7 +527,7 @@ bool command_parser_executor::set_limit(const std::vector& args) else if (args[1] == "default") limit_up = -1; else if (!tools::parse_int(args[1], limit_up)) { - tools::fail_msg_writer() << "Failed to parse '" << args[1] << "' as a limit"; + tools::fail_msg_writer("Failed to parse '{}' as a limit", args[1]); return false; } diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index e11e6d69d..6b0c2401d 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -114,25 +115,43 @@ namespace { void print_block_header(block_header_response const & header) { - tools::success_msg_writer() - << "timestamp: " << header.timestamp << " (" << tools::get_human_readable_timestamp(header.timestamp) << ")" << "\n" - << "previous hash: " << header.prev_hash << "\n" - << "nonce: " << header.nonce << "\n" - << "is orphan: " << header.orphan_status << "\n" - << "height: " << header.height << "\n" - << "depth: " << header.depth << "\n" - << "hash: " << header.hash << "\n" - << "difficulty: " << header.difficulty << "\n" - << "cumulative_difficulty: " << header.cumulative_difficulty << "\n" - << "POW hash: " << header.pow_hash.value_or("N/A") << "\n" - << "block size: " << header.block_size << "\n" - << "block weight: " << header.block_weight << "\n" - << "long term weight: " << header.long_term_weight << "\n" - << "num txes: " << header.num_txes << "\n" - << "reward: " << cryptonote::print_money(header.reward) << "\n" - << "coinbase payouts: " << cryptonote::print_money(header.coinbase_payouts) << "\n" - << "service node winner: " << header.service_node_winner << "\n" - << "miner tx hash: " << header.miner_tx_hash; + tools::success_msg_writer( +R"(timestamp: {} ({}) +previous hash: {} +nonce: {} +is orphan: {} +height: {} +depth: {} +hash: {} +difficulty: {} +cumulative_difficulty: {} +POW hash: {} +block size: {} +block weight: {} +long term weight: {} +num txes: {} +reward: {} +coinbase payouts: {} +service node winner: {} +miner tx hash: {})", + header.timestamp, tools::get_human_readable_timestamp(header.timestamp), + header.prev_hash, + header.nonce, + header.orphan_status, + header.height, + header.depth, + header.hash, + header.difficulty, + header.cumulative_difficulty, + header.pow_hash.value_or("N/A"), + header.block_size, + header.block_weight, + header.long_term_weight, + header.num_txes, + cryptonote::print_money(header.reward), + cryptonote::print_money(header.coinbase_payouts), + header.service_node_winner, + header.miner_tx_hash); } template @@ -174,7 +193,7 @@ namespace { time_t now = std::time(nullptr); time_t last_seen = peer.value("last_seen", 0); - tools::msg_writer() << "{:<10} {:016x} {:<30} {}"_format( + tools::msg_writer("{:<10} {:016x} {:<30} {}", prefix, peer["id"].get(), "{}:{}"_format(peer["host"].get(), peer["port"].get()), @@ -185,7 +204,7 @@ namespace { template void print_peers(std::string_view prefix, const json& peers, size_t& limit, Args&&... args) { if (limit > 0) - tools::msg_writer() << "{:<10} {:<16} {:<30} {}"_format( + tools::msg_writer("{:<10} {:<16} {:<30} {}", "Type", "Peer id", "Remote address", "Last seen"); for (auto it = peers.begin(); it != peers.end() && limit > 0; it++) if (print_peer(prefix, *it, std::forward(args)...)) @@ -213,7 +232,7 @@ static auto try_running(Callback code, std::string_view error_prefix) -> std::op try { return code(); } catch (const std::exception& e) { - tools::fail_msg_writer() << error_prefix << ": " << e.what(); + tools::fail_msg_writer("{}: {}", error_prefix, e.what()); return std::nullopt; } } @@ -284,30 +303,22 @@ bool rpc_command_executor::print_checkpoints(uint64_t start_height, uint64_t end auto checkpoints = *maybe_checkpoints; std::string entry; + auto entry_append = std::back_inserter(entry); if (print_json) entry.append(checkpoints.dump()); else { for (size_t i = 0; i < checkpoints.size(); i++) { - entry.append("["); - entry.append(std::to_string(i)); - entry.append("]"); - - entry.append(" Type: "); - entry.append(checkpoints[i]["type"]); - - entry.append(" Height: "); - entry.append(checkpoints[i]["height"]); - - entry.append(" Hash: "); - entry.append(checkpoints[i]["block_hash"]); - entry.append("\n"); + auto& cp = checkpoints[i]; + fmt::format_to(entry_append, + "[{}] Type: {} Height: {} Hash: {}\n", + i, cp["type"], cp["height"], cp["block_hash"]); } if (entry.empty()) entry.append("No Checkpoints"); } - tools::success_msg_writer() << entry; + tools::success_msg_writer(entry); return true; } @@ -319,16 +330,15 @@ bool rpc_command_executor::print_sn_state_changes(uint64_t start_height, uint64_ auto sn_state_changes = *maybe_sn_state; - std::stringstream output; + auto writer = tools::success_msg_writer(); - output << "Service Node State Changes (blocks " << sn_state_changes["start_height"].get() << "-" << sn_state_changes["end_height"].get() << ")" << std::endl; - output << " Recommissions:\t\t" << sn_state_changes["total_recommission"].get() << std::endl; - output << " Unlocks:\t\t" << sn_state_changes["total_unlock"].get() << std::endl; - output << " Decommissions:\t\t" << sn_state_changes["total_decommission"].get() << std::endl; - output << " Deregistrations:\t" << sn_state_changes["total_deregister"].get() << std::endl; - output << " IP change penalties:\t" << sn_state_changes["total_ip_change_penalty"].get() << std::endl; + writer.append("Service Node State Changes (blocks {}-{})\n", sn_state_changes["start_height"].get(), sn_state_changes["end_height"].get()); + writer.append(" Recommissions: {}", sn_state_changes["total_recommission"].get()); + writer.append(" Unlocks: {}", sn_state_changes["total_unlock"].get()); + writer.append(" Decommissions: {}", sn_state_changes["total_decommission"].get()); + writer.append(" Deregistrations: {}", sn_state_changes["total_deregister"].get()); + writer.append(" IP change penalties: {}", sn_state_changes["total_ip_change_penalty"].get()); - tools::success_msg_writer() << output.str(); return true; } @@ -340,11 +350,11 @@ bool rpc_command_executor::print_peer_list(bool white, bool gray, size_t limit, if (!limit) limit = std::numeric_limits::max(); if (white) { - tools::success_msg_writer() << pl["white_list"].size() << " whitelist peers:"; + tools::success_msg_writer("{} whitelist peers:", pl["white_list"].size()); print_peers("white", pl["white_list"], limit, pruned_only); } if (gray) { - tools::success_msg_writer() << pl["gray_list"].size() << " graylist peers:"; + tools::success_msg_writer("{} graylist peers:", pl["gray_list"].size()); print_peers("gray", pl["gray_list"], limit, pruned_only); } @@ -360,13 +370,13 @@ bool rpc_command_executor::print_peer_list_stats() { auto wls = info.find("white_peerlist_size"); auto gls = info.find("grey_peerlist_size"); if (wls == info.end() || gls == info.end()) { - tools::fail_msg_writer() << "Failed to retrieve whitelist info"; + tools::fail_msg_writer("Failed to retrieve whitelist info"); return false; } - tools::msg_writer() - << "White list size: " << wls->get() << "/" << cryptonote::p2p::LOCAL_WHITE_PEERLIST_LIMIT << " (" << wls->get() * 100.0 / cryptonote::p2p::LOCAL_WHITE_PEERLIST_LIMIT << "%)\n" - << "Gray list size: " << gls->get() << "/" << cryptonote::p2p::LOCAL_GRAY_PEERLIST_LIMIT << " (" << gls->get() * 100.0 / cryptonote::p2p::LOCAL_GRAY_PEERLIST_LIMIT << "%)"; + tools::msg_writer("White list size: {}/{} ({:.1f}%)\nGray list size: {}/{} ({:.1f}%)", + wls->get(), cryptonote::p2p::LOCAL_WHITE_PEERLIST_LIMIT, wls->get() * 100.0 / cryptonote::p2p::LOCAL_WHITE_PEERLIST_LIMIT, + gls->get(), cryptonote::p2p::LOCAL_GRAY_PEERLIST_LIMIT, gls->get() * 100.0 / cryptonote::p2p::LOCAL_GRAY_PEERLIST_LIMIT); return true; } @@ -381,15 +391,15 @@ bool rpc_command_executor::show_difficulty() { return false; auto& info = *maybe_info; - auto msg = tools::success_msg_writer(); - msg << "HEIGHT: " << info["height"].get() - << ", HASH: " << info["top_block_hash"].get(); + auto msg = tools::success_msg_writer("HEIGHT: {}, HASH: {}", + info["height"].get(), info["top_block_hash"].get()); if (info.value("pulse", false)) - msg << ", PULSE"; + msg += ", PULSE"; else - msg << ", DIFF: " << info["difficulty"].get() - << ", CUM_DIFF: " << info["cumulative_difficulty"].get() - << ", HR: " << info["difficulty"].get() / info["target"].get() << " H/s"; + msg.append(", DIFF: {}, CUM_DIFF: {}, HR: {} H/s", + info["difficulty"].get(), + info["cumulative_difficulty"].get(), + info["difficulty"].get() / info["target"].get()); return true; } @@ -402,23 +412,23 @@ static std::string get_mining_speed(uint64_t hr) return "{:d} H/s"_format(hr); } -static std::ostream& print_fork_extra_info(std::ostream& o, uint64_t t, uint64_t now, std::chrono::seconds block_time) +static tools::scoped_message_writer& print_fork_extra_info(tools::scoped_message_writer& msg, uint64_t t, uint64_t now, std::chrono::seconds block_time) { double blocks_per_day = 24h / block_time; if (t == now) - return o << " (forking now)"; + return msg += " (forking now)"; if (t < now) - return o; + return msg; uint64_t dblocks = t - now; if (dblocks > blocks_per_day * 30) - return o; - o << " (next fork in "; + return msg; + msg.append(" (next fork in "); if (dblocks <= 30) - return o << dblocks << " blocks)"; + return msg.append("{} blocks)", dblocks); if (dblocks <= blocks_per_day / 2) - return o << "{:.1f} hours)"_format(dblocks / blocks_per_day * 24); - return o << "{:.1f} days)"_format(dblocks / blocks_per_day); + return msg.append("{:.1f} hours)", dblocks / blocks_per_day * 24); + return msg.append("{:.1f} days)", dblocks / blocks_per_day); } static float get_sync_percentage(uint64_t height, uint64_t target_height) @@ -455,7 +465,7 @@ bool rpc_command_executor::show_status() { if (mres["status"] == STATUS_BUSY) mining_busy = true; else if (mres["status"] != STATUS_OK) { - tools::fail_msg_writer() << "Failed to retrieve mining info"; + tools::fail_msg_writer("Failed to retrieve mining info"); return false; } else { mining_active = mres["active"].get(); @@ -497,78 +507,70 @@ bool rpc_command_executor::show_status() { uint64_t height = info["height"].get(); uint64_t net_height = std::max(info["target_height"].get(), height); - std::ostringstream str; - str << "Height: " << height; + auto msg = tools::success_msg_writer("Height: {}", height); if (height != net_height) - str << "/{} ({:.1f}%)"_format(net_height, get_sync_percentage(height, net_height)); + msg.append("/{} ({:.1f}%)", net_height, get_sync_percentage(height, net_height)); auto net = info["nettype"].get(); - if (net == "testnet") str << " ON TESTNET"; - else if (net == "devnet") str << " ON DEVNET"; + if (net == "testnet") msg += " ON TESTNET"; + else if (net == "devnet") msg += " ON DEVNET"; if (height < net_height) - str << ", syncing"; + msg += ", syncing"; auto hf_version = hfinfo["version"].get(); if (hf_version < cryptonote::feature::PULSE && !has_mining_info) - str << ", mining info unavailable"; + msg += ", mining info unavailable"; if (has_mining_info && !mining_busy && mining_active) - str << ", mining at " << get_mining_speed(mining_hashrate); + msg.append(", mining at {}", get_mining_speed(mining_hashrate)); if (hf_version < cryptonote::feature::PULSE) - str << ", net hash " << get_mining_speed(info["difficulty"].get() / info["target"].get()); + msg.append(", net hash {}", get_mining_speed(info["difficulty"].get() / info["target"].get())); - str << ", v" << info["version"].get(); - str << "(net v" << static_cast(hf_version) << ')'; + msg.append(", v{}(net v{})", info["version"].get(), static_cast(hf_version)); auto earliest = hfinfo.value("earliest_height", uint64_t{0}); if (earliest) - print_fork_extra_info(str, earliest, net_height, 1s * info["target"].get()); + print_fork_extra_info(msg, earliest, net_height, 1s * info["target"].get()); std::time_t now = std::time(nullptr); if (restricted_response) { std::chrono::seconds uptime{now - info["start_time"].get()}; - str << ", " << info["outgoing_connections_count"].get() << "(out)+" << info["incoming_connections_count"].get() << "(in) connections" - << ", uptime " - << tools::friendly_duration(uptime); + msg.append(", {}(out)+{}(in) connections, uptime {}", + info["outgoing_connections_count"].get(), + info["incoming_connections_count"].get(), + tools::friendly_duration(uptime)); } - tools::success_msg_writer() << str.str(); - if (!my_sn_key.empty()) { - str.str(""); - str << "SN: " << my_sn_key << ' '; + msg.flush().append("SN: {} ", my_sn_key); if (!my_sn_registered) - str << "not registered"; + msg += "not registered"; + else if (!my_sn_staked) + msg += "awaiting"; + else if (my_sn_active) + msg += "active"; else - str << (!my_sn_staked ? "awaiting" : my_sn_active ? "active" : "DECOMMISSIONED (" + std::to_string(my_decomm_remaining) + " blocks credit)") - << ", proof: " << (my_sn_last_uptime ? get_human_time_ago(my_sn_last_uptime, now) : "(never)"); - str << ", last pings: "; - if (auto last_ss_ping = info["last_storage_server_ping"].get(); last_ss_ping > 0) - str << get_human_time_ago(last_ss_ping, now, true /*abbreviate*/); - else - str << "NOT RECEIVED"; - str << " (storage), "; + msg.append("DECOMMISSIONED ({} blocks credit)", my_decomm_remaining); - if (auto last_lokinet_ping = info["last_lokinet_ping"].get(); last_lokinet_ping > 0) - str << get_human_time_ago(last_lokinet_ping, now, true /*abbreviate*/); - else - str << "NOT RECEIVED"; - str << " (lokinet)"; + auto last_ss_ping = info["last_storage_server_ping"].get(); + auto last_lokinet_ping = info["last_lokinet_ping"].get(); - tools::success_msg_writer() << str.str(); + msg.append(", proof: {}, last pings: {} (storage), {} (lokinet)", + my_sn_last_uptime ? get_human_time_ago(my_sn_last_uptime, now) : "(never)", + last_ss_ping > 0 ? get_human_time_ago(last_ss_ping, now, true /*abbreviate*/) : "NOT RECEIVED", + last_lokinet_ping > 0 ? get_human_time_ago(last_lokinet_ping, now, true /*abbreviate*/) : "NOT RECEIVED"); if (my_sn_registered && my_sn_staked && !my_sn_active && (my_reason_all | my_reason_any)) { - str.str("Decomm reasons: "); + msg.flush().append("Decomm reasons: "); if (auto reasons = cryptonote::readable_reasons(my_reason_all); !reasons.empty()) - str << tools::join(", ", reasons); + msg.append("{}", fmt::join(reasons, ", ")); if (auto reasons = cryptonote::readable_reasons(my_reason_any & ~my_reason_all); !reasons.empty()) { for (auto& r : reasons) r += "(some)"; - str << (my_reason_all ? ", " : "") << tools::join(", ", reasons); + msg.append("{}{}", my_reason_all ? ", " : "", fmt::join(reasons, ", ")); } - tools::fail_msg_writer() << str.str(); } } @@ -585,18 +587,18 @@ bool rpc_command_executor::mining_status() { if (mres["status"] == STATUS_BUSY) mining_busy = true; else if (mres["status"] != STATUS_OK) { - tools::fail_msg_writer() << "Failed to retrieve mining info"; + tools::fail_msg_writer("Failed to retrieve mining info"); return false; } bool active = mres["active"].get(); long speed = mres["speed"].get(); if (mining_busy || !active) - tools::msg_writer() << "Not currently mining"; + tools::msg_writer("Not currently mining"); else { - tools::msg_writer() << "Mining at " << get_mining_speed(speed) << " with " << mres["threads_count"].get() << " threads"; - tools::msg_writer() << "Mining address: " << mres["address"].get(); + tools::msg_writer("Mining at {} with {} threads", get_mining_speed(speed), mres["threads_count"].get()); + tools::msg_writer("Mining address: {}", mres["address"].get()); } - tools::msg_writer() << "PoW algorithm: " << mres["pow_algorithm"].get(); + tools::msg_writer("PoW algorithm: {}", mres["pow_algorithm"].get()); return true; } @@ -622,13 +624,13 @@ bool rpc_command_executor::print_connections() { constexpr auto hdr_fmt = "{:<30}{:<8}{:<20}{:<30}{:<25}{:<20}{:<12s}{:<14s}{:<10s}{:<13s}"sv; constexpr auto row_fmt = "{:<30}{:<8}{:<20}{:<30}{:<25}{:<20}{:<12.1f}{:<14.1f}{:<10.1f}{:<13.1f}{}{}"sv; - tools::msg_writer() << fmt::format(hdr_fmt, + tools::msg_writer(hdr_fmt, "Remote Host", "Type", "Peer id", "Recv/Sent (inactive,sec)", "State", "Livetime(sec)", "Down (kB/sec)", "Down(now)", "Up (kB/s)", "Up(now)"); for (auto& info : conns) { - tools::msg_writer() << fmt::format(row_fmt, + tools::msg_writer(row_fmt, "{} {}:{}"_format( info["incoming"].get() ? "INC" : "OUT", info["ip"].get(), @@ -665,7 +667,7 @@ bool rpc_command_executor::print_net_stats() auto bytes = stats[in ? "total_bytes_in" : "total_bytes_out"].get(); double average = uptime > 0 ? bytes / (double) uptime : 0.0; uint64_t lim = limit[in ? "limit_down" : "limit_up"].get() * 1024; // convert to bytes, as limits are always kB/s - tools::success_msg_writer() << "{} {} in {} packets, average {}/s = {:.2f}% of the limit of {}/s"_format( + tools::success_msg_writer("{} {} in {} packets, average {}/s = {:.2f}% of the limit of {}/s", in ? "Received" : "Sent", tools::get_human_readable_bytes(bytes), stats[in ? "total_packets_in" : "total_packets_out"].get(), @@ -688,7 +690,7 @@ bool rpc_command_executor::print_blockchain_info(int64_t start_block_index, uint if (start_block_index < 0 && -start_block_index >= info["height"].get()) { - tools::fail_msg_writer() << "start offset is larger than blockchain height"; + tools::fail_msg_writer("start offset is larger than blockchain height"); return false; } @@ -701,20 +703,19 @@ bool rpc_command_executor::print_blockchain_info(int64_t start_block_index, uint return false; auto& block_headers = *maybe_block_headers; - bool first = true; + auto writer = tools::msg_writer("\n"); for (auto & header : block_headers["headers"]) { - if (first) - first = false; - else - tools::msg_writer() << "\n"; - - tools::msg_writer() - << "height: " << header["height"] << ", timestamp: " << header["timestamp"] << " (" << tools::get_human_readable_timestamp(header["timestamp"].get()) << ")" - << ", size: " << header["block_size"] << ", weight: " << header["block_weight"] << " (long term " << header["long_term_weight"] << "), transactions: " << header["num_txes"] - << "\nmajor version: " << header["major_version"] << ", minor version: " << header["minor_version"] - << "\nblock id: " << header["hash"] << ", previous block id: " << header["prev_hash"] - << "\ndifficulty: " << header["difficulty"] << ", nonce " << header["nonce"] << ", reward " << cryptonote::print_money(header["reward"].get()) << "\n"; + writer.flush().append( + "height: {}, timestamp: {} ({}), size: {}, weight: {} (long term {}), transactions: {}\n" + "major version: {}, minor version: {}\n" + "block id: {}, previous block id: {}\n" + "difficulty: {}, nonce {}, reward {}\n", + header["height"], header["timestamp"], tools::get_human_readable_timestamp(header["timestamp"].get()), + header["block_size"], header["block_weight"], header["long_term_weight"], header["num_txes"], + header["major_version"], header["minor_version"], + header["hash"], header["prev_hash"], + header["difficulty"], header["nonce"], cryptonote::print_money(header["reward"].get())); } return true; @@ -732,16 +733,7 @@ bool rpc_command_executor::print_quorum_state(uint64_t start_height, uint64_t en return false; auto& quorums = *maybe_quorums; - std::string output; - output.append("{\n\"quorums\": ["); - for (auto const& quorum : quorums["quorums"]) - { - output.append("\n"); - output.append(quorum); - output.append(",\n"); - } - output.append("]\n}"); - tools::success_msg_writer() << output; + tools::success_msg_writer("{{\n\"quorums\": [\n{}\n]\n}}", fmt::join(quorums["quorums"], ",\n")); return true; } @@ -750,7 +742,7 @@ bool rpc_command_executor::set_log_level(int8_t level) { if (!invoke(json{{"level", level}})) return false; - tools::success_msg_writer() << "Log level is now " << std::to_string(level); + tools::success_msg_writer("Log level is now {:d}", level); return true; } @@ -762,7 +754,7 @@ bool rpc_command_executor::set_log_categories(std::string categories) { //auto& categories_response = *maybe_categories; auto categories_response = make_request(json{{"categories", std::move(categories)}}); - tools::success_msg_writer() << "Log categories are now " << categories_response["categories"].get(); + tools::success_msg_writer("Log categories are now {}", categories_response["categories"].get()); return true; } @@ -771,7 +763,7 @@ bool rpc_command_executor::print_height() { if (auto height = try_running([this] { return invoke().at("height").get(); }, "Failed to retrieve height")) { - tools::success_msg_writer() << *height; + tools::success_msg_writer("{}", *height); return true; } return false; @@ -788,9 +780,9 @@ bool rpc_command_executor::print_block_by_hash(const crypto::hash& block_hash, b auto& block = *maybe_block; if (include_hex) - tools::success_msg_writer() << block["blob"] << std::endl; + tools::success_msg_writer(block["blob"].get()) + "\n"; print_block_header(block["block_header"]); - tools::success_msg_writer() << block["json"] << "\n"; + tools::success_msg_writer(block["json"].get()) + "\n"; return true; } @@ -806,9 +798,9 @@ bool rpc_command_executor::print_block_by_height(uint64_t height, bool include_h auto& block = *maybe_block; if (include_hex) - tools::success_msg_writer() << block["blob"] << std::endl; + tools::success_msg_writer("{}\n", block["blob"]); print_block_header(block["block_header"]); - tools::success_msg_writer() << block["json"] << "\n"; + tools::success_msg_writer("{}\n", block["json"]); return true; } @@ -829,7 +821,7 @@ bool rpc_command_executor::print_transaction(const crypto::hash& transaction_has auto& txi = *maybe_tx; auto txs = txi["txs"]; if (txs.size() != 1) { - tools::fail_msg_writer() << "Transaction wasn't found: " << transaction_hash << "\n"; + tools::fail_msg_writer("Transaction wasn't found: {}\n", transaction_hash); return true; } @@ -840,9 +832,9 @@ bool rpc_command_executor::print_transaction(const crypto::hash& transaction_has bool in_pool = tx["in_pool"].get(); if (in_pool) - tools::success_msg_writer() << "Found in pool"; + tools::success_msg_writer("Found in pool"); else - tools::success_msg_writer() << "Found in blockchain at height " << tx["block_height"].get() << (pruned ? " (pruned)" : ""); + tools::success_msg_writer("Found in blockchain at height {}{}", tx["block_height"].get(), pruned ? " (pruned)" : ""); auto pruned_hex = tx["pruned"].get(); // Always included with req.split=true @@ -860,7 +852,7 @@ bool rpc_command_executor::print_transaction(const crypto::hash& transaction_has : cryptonote::parse_and_validate_tx_from_blob(blob, t.emplace()); if (!parsed) { - tools::fail_msg_writer() << "Failed to parse transaction data"; + tools::fail_msg_writer("Failed to parse transaction data"); t.reset(); } } @@ -871,20 +863,20 @@ bool rpc_command_executor::print_transaction(const crypto::hash& transaction_has { if (!in_pool) { auto ts = tx["block_timestamp"].get(); - tools::msg_writer() << "Block timestamp: " << ts << " (" << tools::get_human_readable_timestamp(ts) << ")"; + tools::msg_writer("Block timestamp: {} ({})", ts, tools::get_human_readable_timestamp(ts)); } - tools::msg_writer() << "Size: " << tx["size"].get(); + tools::msg_writer("Size: {}", tx["size"].get()); if (t) - tools::msg_writer() << "Weight: " << cryptonote::get_transaction_weight(*t); + tools::msg_writer("Weight: {}", cryptonote::get_transaction_weight(*t)); } // Print raw hex if requested if (include_hex) - tools::success_msg_writer() << pruned_hex << prunable_hex << '\n'; + tools::success_msg_writer("{}{}\n", pruned_hex, prunable_hex); // Print json if requested if (include_json && t) - tools::success_msg_writer() << cryptonote::obj_to_json_str(*t) << '\n'; + tools::success_msg_writer("{}\n", cryptonote::obj_to_json_str(*t)); return true; } @@ -901,14 +893,14 @@ bool rpc_command_executor::is_key_image_spent(const std::vector(); - tools::success_msg_writer() << ki[i] << ": " - << (status == 0 ? "unspent" : status == 1 ? "spent" : status == 2 ? "spent (in pool)" : "unknown"); + tools::success_msg_writer("{}: {}", + ki[i], status == 0 ? "unspent" : status == 1 ? "spent" : status == 2 ? "spent (in pool)" : "unknown"); } return true; } @@ -916,12 +908,11 @@ bool rpc_command_executor::is_key_image_spent(const std::vector lines; + auto msg = tools::msg_writer("{} Transactions:\n", txs.size()); for (auto &tx : txs) { std::vector status; @@ -931,26 +922,21 @@ static void print_pool(const json& txs) { if (tx.value("double_spend_seen", false)) status.push_back("double spend"sv); if (tx.value("kept_by_block", false)) status.push_back("from popped block"sv); - lines.clear(); - lines.push_back(tx["tx_hash"].get_ref() + ":"s); - lines.push_back("size/weight: {}/{}"_format(tx["size"].get(), tx["weight"].get())); - lines.push_back("fee: {} ({}/byte)"_format( - cryptonote::print_money(tx["fee"].get()), cryptonote::print_money(tx["fee"].get() / tx["weight"].get()))); - lines.push_back("received: {} ({})"_format(tx["received_timestamp"].get(), get_human_time_ago(tx["received_timestamp"].get(), now))); - lines.push_back("status: " + tools::join(", ", status)); - lines.push_back("top required block: {} ({})"_format(tx["max_used_height"].get(), tx["max_used_block"])); + msg.flush().append("{}:\n", tx["tx_hash"].get_ref()); + msg.append(" size/weight: {}/{}\n", tx["size"].get(), tx["weight"].get()); + msg.append(" fee: {} ({}/byte)\n", + cryptonote::print_money(tx["fee"].get()), cryptonote::print_money(tx["fee"].get() / tx["weight"].get())); + msg.append(" received: {} ({})\n", tx["received_timestamp"].get(), get_human_time_ago(tx["received_timestamp"].get(), now)); + msg.append(" status: {}\n", fmt::join(status, ", ")); + msg.append(" top required block: {} ({})\n", tx["max_used_height"].get(), tx["max_used_block"]); if (tx.count("last_failed_height")) - lines.push_back("last failed block: {} ({})"_format(tx["last_failed_height"].get(), tx["last_failed_block"].get())); + msg.append(" last failed block: {} ({})\n", tx["last_failed_height"].get(), tx["last_failed_block"].get()); if (auto extra = tx.find("extra"); extra != tx.end()) { - lines.push_back("transaction extra: "); - for (auto c : extra->dump(2)) { - if (c == '\n') - lines.back() += "\n "sv; - else - lines.back() += c; - } + msg.append(" transaction extra: "); + for (auto line : tools::split(extra->dump(2), "\n", true)) + msg.append(" {}\n", line); } - tools::msg_writer() << tools::join("\n ", lines) << "\n"; + msg.append("\n"); } } @@ -965,30 +951,25 @@ bool rpc_command_executor::print_transaction_pool(bool long_format) { print_pool(pool["txs"]); - if (long_format) { - // We used to have a warning here when we had transactions but no key_images; but that can - // happen on Oxen with 0-output tx state change transactions. - - if (!pool["mempool_key_images"].empty()) + if (long_format && !pool["mempool_key_images"].empty()) + { + auto msg = tools::msg_writer("\nSpent key images:"); + for (const auto& [key, tx_hashes] : pool["mempool_key_images"].items()) { - tools::msg_writer() << "\nSpent key images: "; - for (const auto& [key, tx_hashes] : pool["mempool_key_images"].items()) + msg.flush().append("key image: {}\n", key); + if (tx_hashes.size() == 1) + msg.append(" tx: {}\n", tx_hashes.front().get()); + else if (tx_hashes.empty()) + msg.append(" WARNING: spent key image has no txs associated!\n"); + else { - tools::msg_writer() << "key image: " << key; - if (tx_hashes.size() == 1) - tools::msg_writer() << " tx: " << tx_hashes.front().get(); - else if (tx_hashes.empty()) - tools::msg_writer() << " WARNING: spent key image has no txs associated!"; - else - { - tools::msg_writer() << " NOTE: key image for multiple transactions ({}):"_format(tx_hashes.size()); - for (const auto& txid : tx_hashes) - tools::msg_writer() << " - " << txid.get(); - } + msg.append(" NOTE: key image for multiple transactions ({}):\n", tx_hashes.size()); + for (const auto& txid : tx_hashes) + msg.append(" - {}\n", txid.get()); } - if (pool["txs"].empty()) - tools::msg_writer() << "WARNING: Inconsistent pool state - key images but no no transactions"; } + if (pool["txs"].empty()) + msg.flush().append("WARNING: Inconsistent pool state - key images but no no transactions"); } return true; @@ -1022,19 +1003,25 @@ bool rpc_command_executor::print_transaction_pool_stats() { uint64_t fee_total = pstats["fee_total"].get(); std::time_t oldest = pstats["oldest"].get(); - tools::msg_writer() << n_transactions << " tx(es), " - << bytes_total << " bytes total (min " << pstats["bytes_min"].get() << ", max " << pstats["bytes_max"].get() - << ", avg " << avg_bytes << ", median " << pstats["bytes_med"].get() << ')' - << '\n' - << "fees " << cryptonote::print_money(fee_total) << " (avg " << cryptonote::print_money(n_transactions ? fee_total / n_transactions : 0) << " per tx, " - << cryptonote::print_money(bytes_total ? fee_total / bytes_total : 0) << " per byte)" - << '\n' - << pstats["num_double_spends"].get() << " double spends, " - << pstats["num_not_relayed"].get() << " not relayed, " - << pstats["num_failing"].get() << " failing, " - << pstats["num_10m"].get() << " older than 10 minutes (oldest " - << (oldest == 0 ? "-" : get_human_time_ago(oldest, now)) << "), " - << backlog_message; + tools::msg_writer( + "{} tx(s), {} bytes total (min {}, max {}, avg {}, median {})\n" + "fees {} (avg {} per tx, {} per byte)\n" + "{} double spends, {} not relayed, {} failing, {} older than 10 minutes (oldest {}), {}", + n_transactions, + bytes_total, + pstats["bytes_min"].get(), + pstats["bytes_max"].get(), + avg_bytes, + pstats["bytes_med"].get(), + cryptonote::print_money(fee_total), + cryptonote::print_money(n_transactions ? fee_total / n_transactions : 0), + cryptonote::print_money(bytes_total ? fee_total / bytes_total : 0), + pstats["num_double_spends"].get(), + pstats["num_not_relayed"].get(), + pstats["num_failing"].get(), + pstats["num_10m"].get(), + oldest == 0 ? "-" : get_human_time_ago(oldest, now), + backlog_message); auto histo = pstats["histo"].get>>(); if (n_transactions > 1 && !histo.empty()) @@ -1056,14 +1043,13 @@ bool rpc_command_executor::print_transaction_pool_stats() { } constexpr auto hist_fmt = "{:>10} - {:<14} {:>7} {:>11}"sv; - tools::msg_writer() << "{:^23} {:>7} {:>11}"_format("Age", "Txes", "Bytes"); + tools::msg_writer("{:^23} {:>7} {:>11}", "Age", "Txes", "Bytes"); for (size_t i = 0; i < 10; i++) - tools::msg_writer() - << fmt::format(hist_fmt, - get_human_time_ago(times[i] * 1s, true), - (last_is_gt && i == 10 ? "" : get_human_time_ago(times[i+1] * 1s, true) + " ago"), - histo[i].first, - histo[i].second); + tools::msg_writer(hist_fmt, + get_human_time_ago(times[i] * 1s, true), + (last_is_gt && i == 10 ? "" : get_human_time_ago(times[i+1] * 1s, true) + " ago"), + histo[i].first, + histo[i].second); } tools::msg_writer(); @@ -1078,9 +1064,9 @@ bool rpc_command_executor::start_mining(const cryptonote::account_public_address if (!try_running([this, &args] { return invoke(args); }, "Unable to start mining")) return false; - tools::success_msg_writer() - << "Mining started with {} thread(s)."_format(std::max(num_threads, 1)) - << (num_blocks ? " Will stop after {} blocks"_format(num_blocks) : ""); + tools::success_msg_writer("Mining started with {} thread(s).{}", + std::max(num_threads, 1), + num_blocks ? " Will stop after {} blocks"_format(num_blocks) : ""); return true; } @@ -1100,7 +1086,7 @@ bool rpc_command_executor::get_limit() return false; auto& limit = *maybe_limit; - tools::msg_writer() << "Current limits are {} kiB/s down, {} kiB/s up"_format( + tools::msg_writer("Current limits are {} kiB/s down, {} kiB/s up", limit["limit_down"].get(), limit["limit_up"].get()); return true; } @@ -1115,7 +1101,7 @@ bool rpc_command_executor::set_limit(int64_t limit_down, int64_t limit_up) return false; auto& limit = *maybe_limit; - tools::success_msg_writer() << "New limits are {} kiB/s down, {} kiB/s up"_format( + tools::success_msg_writer("New limits are {} kiB/s down, {} kiB/s up", limit["limit_down"].get(), limit["limit_up"].get()); return true; } @@ -1129,7 +1115,7 @@ bool rpc_command_executor::out_peers(bool set, uint32_t limit) auto& out_peers = *maybe_out_peers; const std::string s = out_peers["out_peers"] == (uint32_t)-1 ? "unlimited" : out_peers["out_peers"].get(); - tools::msg_writer() << "Max number of out peers set to " << s << std::endl; + tools::msg_writer().append("Max number of out peers set to {}\n", s); return true; } @@ -1142,7 +1128,7 @@ bool rpc_command_executor::in_peers(bool set, uint32_t limit) auto& in_peers = *maybe_in_peers; const std::string s = in_peers["in_peers"] == (uint32_t)-1 ? "unlimited" : in_peers["in_peers"].get(); - tools::msg_writer() << "Max number of in peers set to " << s << std::endl; + tools::msg_writer().append("Max number of in peers set to {}\n", s); return true; } @@ -1158,11 +1144,11 @@ bool rpc_command_executor::print_bans() { for (auto i = bans.begin(); i != bans.end(); ++i) { - tools::msg_writer() << (*i)["host"] << " banned for " << (*i)["seconds"] << " seconds"; + tools::msg_writer("{} banned for {} seconds", (*i)["host"], (*i)["seconds"]); } } else - tools::msg_writer() << "No IPs are banned"; + tools::msg_writer("No IPs are banned"); return true; } @@ -1189,9 +1175,9 @@ bool rpc_command_executor::banned(const std::string &address) auto& banned_response = *maybe_banned; if (banned_response["banned"].get()) - tools::msg_writer() << address << " is banned for " << banned_response["seconds"].get() << " seconds"; + tools::msg_writer("{} is banned for {} seconds", address, banned_response["seconds"].get()); else - tools::msg_writer() << address << " is not banned"; + tools::msg_writer("{} is not banned", address); return true; } @@ -1204,11 +1190,11 @@ bool rpc_command_executor::flush_txpool(std::string txid) if (!invoke(json{{txids, std::move(txids)}})) { - tools::fail_msg_writer() << "Failed to flush tx pool"; + tools::fail_msg_writer("Failed to flush tx pool"); return false; } - tools::success_msg_writer() << "Pool successfully flushed"; + tools::success_msg_writer("Pool successfully flushed"); return true; } @@ -1228,7 +1214,7 @@ bool rpc_command_executor::output_histogram(const std::vector &amounts std::sort(histogram.begin(), histogram.end(), [](const auto& e1, const auto& e2)->bool { return e1.total_instances < e2.total_instances; }); for (const auto &e: histogram) - tools::msg_writer() << e.total_instances << " " << cryptonote::print_money(e.amount); + tools::msg_writer("{} {}", e.total_instances, cryptonote::print_money(e.amount)); return true; } @@ -1240,11 +1226,11 @@ bool rpc_command_executor::print_coinbase_tx_sum(uint64_t height, uint64_t count return false; auto& coinbase = *maybe_coinbase; - tools::msg_writer() << "Sum of coinbase transactions between block heights [" - << height << ", " << (height + count) << ") is " - << cryptonote::print_money(coinbase["emission_amount"].get() + coinbase["fee_amount"].get()) << " " - << "consisting of " << cryptonote::print_money(coinbase["emission_amount"]) - << " in emissions, and " << cryptonote::print_money(coinbase["fee_amount"]) << " in fees"; + tools::msg_writer("Sum of coinbase transactions between block heights [{}, {}) is {} consisting of {} in emissions and {} in fees", + height, height + count, + cryptonote::print_money(coinbase["emission_amount"].get() + coinbase["fee_amount"].get()), + cryptonote::print_money(coinbase["emission_amount"]), + cryptonote::print_money(coinbase["fee_amount"])); return true; } @@ -1277,13 +1263,13 @@ bool rpc_command_executor::alt_chain_info(const std::string &tip, size_t above, continue; display.push_back(i); } - tools::msg_writer() << display.size() << " alternate chains found:"; + tools::msg_writer("{} alternate chains found:", display.size()); for (const size_t idx: display) { const auto &chain = chains[idx]; const uint64_t start_height = (chain.height - chain.length + 1); - tools::msg_writer() << chain.length << " blocks long, from height " << start_height << " (" << (*height - start_height - 1) - << " deep), diff " << chain.difficulty << ": " << chain.block_hash; + tools::msg_writer("{} blocks long, from height {} ({} deep), diff {}: {}", + chain.length, start_height, *height - start_height - 1, chain.difficulty, chain.block_hash); } } else @@ -1293,13 +1279,14 @@ bool rpc_command_executor::alt_chain_info(const std::string &tip, size_t above, if (i != chains.end()) { const auto &chain = *i; - tools::success_msg_writer() << "Found alternate chain with tip " << tip; + tools::success_msg_writer("Found alternate chain with tip {}", tip); uint64_t start_height = (chain.height - chain.length + 1); - tools::msg_writer() << chain.length << " blocks long, from height " << start_height << " (" << (*height - start_height - 1) - << " deep), diff " << chain.difficulty << ":"; + auto msg = tools::msg_writer("{} blocks long, from height {} ({} deep), diff {}:", + chain.length, start_height, *height - start_height - 1, chain.difficulty); for (const std::string &block_id: chain.block_hashes) - tools::msg_writer() << " " << block_id; - tools::msg_writer() << "Chain parent on main chain: " << chain.main_chain_parent_block; + msg.append("\n {}", block_id); + msg.append("\nChain parent on main chain: {}", chain.main_chain_parent_block); + msg.flush(); std::vector hashes{chain.block_hashes}; hashes.push_back(chain.main_chain_parent_block); @@ -1310,7 +1297,7 @@ bool rpc_command_executor::alt_chain_info(const std::string &tip, size_t above, if (headers["block_headers"].size() != chain.length + 1) { - tools::fail_msg_writer() << "Failed to get block header info for alt chain"; + tools::fail_msg_writer("Failed to get block header info for alt chain"); return true; } uint64_t t0 = std::numeric_limits::max(), @@ -1323,19 +1310,19 @@ bool rpc_command_executor::alt_chain_info(const std::string &tip, size_t above, } const uint64_t dt = t1 - t0; const uint64_t age = std::max(dt, t0 < now ? now - t0 : 0); - tools::msg_writer() << "Age: " << tools::get_human_readable_timespan(std::chrono::seconds(age)); + tools::msg_writer("Age: {}", tools::get_human_readable_timespan(std::chrono::seconds(age))); if (chain.length > 1) { - tools::msg_writer() << "Time span: " << tools::get_human_readable_timespan(std::chrono::seconds(dt)); + tools::msg_writer("Time span: {}", tools::get_human_readable_timespan(std::chrono::seconds(dt))); cryptonote::difficulty_type start_difficulty = headers["block_headers"].back()["difficulty"]; if (start_difficulty > 0) - tools::msg_writer() << "Approximated " << 100.f * tools::to_seconds(cryptonote::TARGET_BLOCK_TIME) * chain.length / dt << "% of network hash rate"; + tools::msg_writer("Approximately {:.2f}% of network hash rate", 100.0 * tools::to_seconds(cryptonote::TARGET_BLOCK_TIME) * chain.length / dt); else - tools::fail_msg_writer() << "Bad cumulative difficulty reported by dameon"; + tools::fail_msg_writer("Bad cumulative difficulty reported by dameon"); } } else - tools::fail_msg_writer() << "Block hash " << tip << " is not the tip of any known alternate chain"; + tools::fail_msg_writer("Block hash {} is not the tip of any known alternate chain", tip); } return true; } @@ -1359,9 +1346,11 @@ bool rpc_command_executor::print_blockchain_dynamic_stats(uint64_t nblocks) auto& feres = *maybe_fees; auto height = info["height"].get(); - tools::msg_writer() << "Height: " << height << ", diff " << info["difficulty"].get() << ", cum. diff " << info["cumulative_difficulty"].get() - << ", target " << info["target"].get() << " sec" << ", dyn fee " << cryptonote::print_money(feres["fee_per_byte"]) << "/" << (hfinfo["enabled"].get() ? "byte" : "kB") - << " + " << cryptonote::print_money(feres["fee_per_output"]) << "/out"; + tools::msg_writer( + "Height: {}, diff {}, cum. diff {}, target {} sec, dyn fee {}/{} + {}/out", + height, info["difficulty"].get(), info["cumulative_difficulty"].get(), info["target"].get(), + cryptonote::print_money(feres["fee_per_byte"]), hfinfo["enabled"].get() ? "byte" : "kB", + cryptonote::print_money(feres["fee_per_output"])); if (nblocks > 0) { @@ -1395,18 +1384,18 @@ bool rpc_command_executor::print_blockchain_dynamic_stats(uint64_t nblocks) avgnumtxes /= nblocks; avgreward /= nblocks; uint64_t median_block_weight = tools::median(std::move(weights)); - tools::msg_writer() << "Last " << nblocks << ": avg. diff " << (uint64_t)avgdiff << ", " << (latest - earliest) / nblocks << " avg sec/block, avg num txes " << avgnumtxes - << ", avg. reward " << cryptonote::print_money(avgreward) << ", median block weight " << median_block_weight; + tools::msg_writer("Last {}: avg. diff {}, {} avg sec/block, avg num txes {}, avg. reward {}, median block weight {}", + nblocks, (uint64_t)avgdiff, (latest - earliest) / nblocks, avgnumtxes, + cryptonote::print_money(avgreward), median_block_weight); - std::ostringstream s; + auto msg = tools::msg_writer("Block versions (major/minor): "); bool first = true; for (auto& v : versions) { if (first) first = false; - else s << "; "; - s << "v" << v.first << " (" << v.second.first << "/" << v.second.second << ")"; + else msg.append("; "); + msg.append("v{} ({}/{})", v.first, v.second.first, v.second.second); } - tools::msg_writer() << "Block versions (major/minor): " << s.str(); } return true; } @@ -1418,7 +1407,7 @@ bool rpc_command_executor::relay_tx(const std::string &txid) if (!maybe_relay) return false; - tools::success_msg_writer() << "Transaction successfully relayed"; + tools::success_msg_writer("Transaction successfully relayed"); return true; } @@ -1431,20 +1420,20 @@ bool rpc_command_executor::sync_info() uint64_t height = sync["height"].get(); uint64_t target = std::max(sync.value("target_height", height), height); - tools::success_msg_writer() << "Height: " << height << ", target: " << target << " (" << (100.0 * height / target) << "%)"; + auto msg = tools::success_msg_writer("Height: {}, target: {} ({}%)", height, target, 100.0 * height / target); auto& spans = sync["spans"]; auto& peers = sync["peers"]; uint64_t current_download = 0; for (const auto& p: peers) current_download += p["current_download"].get(); - tools::success_msg_writer() << "Downloading at " << current_download/1000.0 << " kB/s"; + msg.append("\nDownloading at {:.1f} kB/s", current_download/1000.0); if (auto nnps = sync.value("next_needed_pruning_seed", 0)) - tools::success_msg_writer() << "Next needed pruning seed: " << nnps; + msg.append("\nNext needed pruning seed: {}", nnps); - tools::success_msg_writer() << std::to_string(peers.size()) << " peers"; + msg.append("\n{} peers", peers.size()); for (const auto& [cid, p]: peers.items()) { - std::string address = epee::string_tools::pad_string(p["ip"].get() + ":" + std::to_string(p["port"].get()), 24); + std::string address = "{}:{}"_format(p["ip"].get(), p["port"].get()); uint64_t nblocks = 0, size = 0; for (const auto& s: spans) { if (s["connection_id"] == cid) { @@ -1452,39 +1441,35 @@ bool rpc_command_executor::sync_info() size += s["size"].get(); } } - tools::success_msg_writer() << address << " " << p["peer_id"].get() << " " << - epee::string_tools::pad_string(p["state"].get(), 16) << " " << - //epee::string_tools::pad_string(epee::string_tools::to_string_hex(p.info.pruning_seed), 8) << " " << - p["height"].get() << " " << - p["current_download"].get() / 1000. << " kB/s, " << - nblocks << " blocks / " << size/1'000'000. << " MB queued"; + msg.append("\n{:<24s} {} {:<16s} {} {:.1f} kB/s, {} blocks / {:.2f} MB queued", + address, p["peer_id"].get(), p["state"].get(), + p["height"].get(), + p["current_download"].get() / 1000.0, + nblocks, + size/1'000'000.0); } uint64_t total_size = 0; for (const auto& s: spans) total_size += s["size"].get(); - tools::success_msg_writer() << std::to_string(spans.size()) << " spans, " << total_size/1e6 << " MB"; + msg.append("\n{} spans, {:.2f} MB", spans.size(), total_size/1'000'000.0); if (auto overview = sync["overview"].get(); overview != "[]"sv) - tools::success_msg_writer() << overview; + msg.append("\n{}", overview); for (const auto& s: spans) { auto& c = peers[s["connection_id"].get_ref()]; std::string address = "(unknown)"; if (c.is_object()) - address = c["ip"].get() + ":" + std::to_string(c["port"].get()); - address = epee::string_tools::pad_string(std::move(address), 24); - //std::string pruning_seed = epee::string_tools::to_string_hex(tools::get_pruning_seed(s.start_block_height, std::numeric_limits::max(), cryptonote::PRUNING_LOG_STRIPES)); + address = "{}:{}"_format(c["ip"].get(), c["port"].get()); auto size = s["size"].get(); auto start = s["start_block_height"].get(); auto nblocks = s["nblocks"].get(); - { - auto writer = tools::success_msg_writer(); - writer << address << " " << nblocks << /*"/" << pruning_seed <<*/ " (" << start << " - " << (start + nblocks - 1); - if (size == 0) - writer << ") -"; - else - writer << ", " << size/1000. << " kB) " << s["rate"].get() / 1000. << " kB/s (" << s["speed"].get() / 100. << ")"; - } + msg.append("\n{:<24s} {} ({} - {}", + address, nblocks, start, start + nblocks - 1); + if (size == 0) + msg.append(") -"); + else + msg.append(", {:.1f} kB) {} kB/s ({})", size/1000.0, s["rate"].get() / 1000.0, s["speed"].get() / 100.0); } return true; @@ -1752,11 +1737,11 @@ bool rpc_command_executor::print_sn(const std::vector &args, bool s for (auto& arg : args) { if (arg == "+json") - tools::fail_msg_writer() << "+json is no longer supported"; + tools::fail_msg_writer("+json is no longer supported"); else if (arg == "+detail") detailed_view = true; else if (self) { - tools::fail_msg_writer() << "print_sn_status takes no pubkey arguments"; + tools::fail_msg_writer("print_sn_status takes no pubkey arguments"); return false; } else pubkeys.push_back(arg); @@ -1809,11 +1794,11 @@ bool rpc_command_executor::print_sn(const std::vector &args, bool s if (awaiting.size() == 0 && registered.size() == 0) { if (pubkeys.size() > 0) - tools::msg_writer() << "No service node is currently known on the network: " << tools::join(", ", pubkeys); + tools::msg_writer("No service node is currently known on the network: {}", fmt::join(pubkeys, ", ")); else if (self) - tools::msg_writer() << "Service node " << my_sn_pk << " is not currently registered on the network"; + tools::msg_writer("Service node {} is not currently registered on the network", my_sn_pk); else - tools::msg_writer() << "No service nodes are currently known on the network"; + tools::msg_writer("No service nodes are currently known on the network"); return true; } @@ -1853,10 +1838,10 @@ bool rpc_command_executor::print_sn(const std::vector &args, bool s } if (awaiting.size() > 0) - tools::msg_writer() << "Service Node Awaiting State [" << awaiting.size() << "]\n" << awaiting_print_data; + tools::msg_writer("Service Node Awaiting State [{}]\n{}", awaiting.size(), awaiting_print_data); if (registered.size() > 0) - tools::msg_writer() << "Service Node Registration State [" << registered.size() << "]\n" << registered_print_data; + tools::msg_writer("Service Node Registration State [{}]\n{}", registered.size(), registered_print_data); return true; } @@ -1880,7 +1865,7 @@ bool rpc_command_executor::print_sr(uint64_t height) return false; auto& staking_requirement = *maybe_staking_requirement; - tools::success_msg_writer() << "Staking Requirement: " << cryptonote::print_money(staking_requirement["staking_requirement"]); + tools::success_msg_writer("Staking Requirement: {}", cryptonote::print_money(staking_requirement["staking_requirement"])); return true; } @@ -1891,7 +1876,7 @@ bool rpc_command_executor::pop_blocks(uint64_t num_blocks) return false; auto& pop_blocks = *maybe_pop_blocks; - tools::success_msg_writer() << "new height: " << pop_blocks["height"]; + tools::success_msg_writer("new height: {}", pop_blocks["height"]); return true; } @@ -1904,10 +1889,13 @@ bool rpc_command_executor::print_sn_key() auto my_sn_keys = *maybe_service_keys; - tools::success_msg_writer() - << "Service Node Public Key: " << my_sn_keys["service_node_pubkey"] - << "\n Ed25519 Public Key: " << my_sn_keys["service_node_ed25519_pubkey"] - << "\n X25519 Public Key: " << my_sn_keys["service_node_x25519_pubkey"]; + tools::success_msg_writer( + "Service Node Public Key: {}\n" + " Ed25519 Public Key: {}\n" + " X25519 Public Key: {}", + my_sn_keys["service_node_pubkey"], + my_sn_keys["service_node_ed25519_pubkey"], + my_sn_keys["service_node_x25519_pubkey"]); return true; } @@ -1944,7 +1932,7 @@ bool rpc_command_executor::prepare_registration(bool force_registration) // Check if the daemon was started in Service Node or not if (!info.value("service_node", false)) { - tools::fail_msg_writer() << "Unable to prepare registration: this daemon is not running in --service-node mode"; + tools::fail_msg_writer("Unable to prepare registration: this daemon is not running in --service-node mode"); return false; } @@ -1955,7 +1943,7 @@ bool rpc_command_executor::prepare_registration(bool force_registration) auto& hfinfo = *maybe_hf; auto hf_version = hfinfo["version"].get(); if (hf_version < hf::hf19_reward_batching) { - tools::fail_msg_writer() << "Error: this command only supports HF19+"; + tools::fail_msg_writer("Error: this command only supports HF19+"); return false; } @@ -1972,16 +1960,16 @@ bool rpc_command_executor::prepare_registration(bool force_registration) if (auto last_lokinet_ping = std::chrono::system_clock::from_time_t(last_lokinet_ping_timet); last_lokinet_ping < now - 1min && !force_registration) { - tools::fail_msg_writer() << "Unable to prepare registration: this daemon has not received a ping from lokinet " - << (last_lokinet_ping_timet == 0 ? "yet" : "since " + get_human_time_ago(now - last_lokinet_ping)); + tools::fail_msg_writer("Unable to prepare registration: this daemon has not received a ping from lokinet {}", + last_lokinet_ping_timet == 0 ? "yet" : "since " + get_human_time_ago(now - last_lokinet_ping)); return false; } auto last_ss_ping_timet = info.value("last_storage_server_ping", 0); if (auto last_storage_server_ping = std::chrono::system_clock::from_time_t(last_ss_ping_timet); last_storage_server_ping < now - 1min && !force_registration) { - tools::fail_msg_writer() << "Unable to prepare registration: this daemon has not received a ping from the storage server " - << (last_ss_ping_timet == 0 ? "yet" : "since " + get_human_time_ago(now - last_storage_server_ping)); + tools::fail_msg_writer("Unable to prepare registration: this daemon has not received a ping from the storage server {}", + last_ss_ping_timet == 0 ? "yet" : "since " + get_human_time_ago(now - last_storage_server_ping)); return false; } } @@ -2009,9 +1997,11 @@ bool rpc_command_executor::prepare_registration(bool force_registration) if (now - block_ts >= 10min) { - tools::fail_msg_writer() << "The last block this Service Node knows about was at least " << get_human_time_ago(now - block_ts) - << "\nYour node is possibly desynced from the network or still syncing to the network." - << "\n\nRegistering this node may result in a deregistration due to being out of date with the network\n"; + tools::fail_msg_writer( + "The last block this Service Node knows about was at least {}\n" + "Your node is possibly desynced from the network or still syncing to the network.\n\n" + "Registering this node may result in a deregistration due to being out of date with the network\n", + get_human_time_ago(now - block_ts)); } if (auto synced_height = header.height; block_height >= synced_height) @@ -2019,8 +2009,10 @@ bool rpc_command_executor::prepare_registration(bool force_registration) uint64_t delta = block_height - header.height; if (delta > 5) { - tools::fail_msg_writer() << "The last block this Service Node synced is " << delta << " blocks away from the longest chain we know about." - << "\n\nRegistering this node may result in a deregistration due to being out of date with the network\n"; + tools::fail_msg_writer( + "The last block this Service Node synced is {} blocks away from the longest chain we know about.\n\n" + "Registering this node may result in a deregistration due to being out of date with the network\n", + delta); } } } @@ -2115,9 +2107,9 @@ bool rpc_command_executor::prepare_registration(bool force_registration) if (!is_operator && address_str.empty()) next_step(register_step::get_operator_fee); else if (auto bad = is_invalid_staking_address(address_str, nettype)) - tools::fail_msg_writer() << *bad << std::endl; + tools::fail_msg_writer("{}\n", *bad); else if (std::any_of(state.contributions.begin(), state.contributions.end(), [a=address_str](auto& b) { return b.first == a; })) - tools::fail_msg_writer() << "Invalid OXEN address: you cannot provide the same address twice" << std::endl; + tools::fail_msg_writer("Invalid OXEN address: you cannot provide the same address twice\n"); else { state.contributions.emplace_back(std::move(address_str), 0); @@ -2166,21 +2158,21 @@ bool rpc_command_executor::prepare_registration(bool force_registration) contribution = *c; else { - tools::fail_msg_writer() << "Invalid amount." << std::endl; + tools::fail_msg_writer("Invalid amount.\n"); break; } if (contribution > amount_left) { - tools::fail_msg_writer() << - "Invalid amount: The contribution exceeds the remaining staking requirement ({}).\n"_format( + tools::fail_msg_writer( + "Invalid amount: The contribution exceeds the remaining staking requirement ({}).\n", highlight_money(amount_left)); break; } else if (contribution < min_contribution) { - tools::fail_msg_writer() << - "Invalid amount: The contribution does not meet the minimum staking requirement ({}).\n"_format( + tools::fail_msg_writer( + "Invalid amount: The contribution does not meet the minimum staking requirement ({}).\n", highlight_money(min_contribution)); break; } @@ -2221,7 +2213,7 @@ Enter the operator fee as a percentage [0.00-100.00])"); state.operator_fee = service_nodes::percent_to_basis_points(operator_fee_str); next_step(register_step::summary_info); } catch(const std::exception &e) { - tools::fail_msg_writer() << "Invalid value: " << operator_fee_str << ". Fee must be between 0 and 100%" << std::endl; + tools::fail_msg_writer().append("Invalid value: {}. Fee must be between 0 and 100%", operator_fee_str); } } break; @@ -2316,7 +2308,7 @@ The Service Node will not activate until the entire stake has been contributed. case register_step::cancelled_by_user: { - tools::fail_msg_writer() << "Registration preparation cancelled." << std::endl; + tools::fail_msg_writer("Registration preparation cancelled.\n"); return true; } } @@ -2338,9 +2330,7 @@ The Service Node will not activate until the entire stake has been contributed. return false; auto& registration = *maybe_registration; - std::cout << "\n\n"; - tools::success_msg_writer() << registration["registration_cmd"]; - std::cout << "\n\n"; + tools::success_msg_writer("\n\n{}\n\n", registration["registration_cmd"]); return true; } @@ -2349,13 +2339,7 @@ The Service Node will not activate until the entire stake has been contributed. bool rpc_command_executor::prune_blockchain() { -#if 0 - if (!invoke(json{{"check", false}}, "Failed to prune blockchain")) - return false; - tools::success_msg_writer() << "Blockchain pruned"; -#else - tools::fail_msg_writer() << "Blockchain pruning is not supported in Oxen yet"; -#endif + tools::fail_msg_writer("Blockchain pruning is not supported in Oxen yet"); return true; } @@ -2366,7 +2350,7 @@ bool rpc_command_executor::check_blockchain_pruning() return false; auto& pruning = *maybe_pruning; - tools::success_msg_writer() << "Blockchain is" << (pruning["pruning_seed"] ? "" : " not") << " pruned"; + tools::success_msg_writer("Blockchain {} pruned", pruning["pruning_seed"] ? "is" : "is not"); return true; } @@ -2377,7 +2361,7 @@ bool rpc_command_executor::version() }, "Failed to retrieve node info"); if (!version) return false; - tools::success_msg_writer() << *version; + tools::success_msg_writer(*version); return true; } diff --git a/src/daemon/rpc_command_executor.h b/src/daemon/rpc_command_executor.h index 8af0b6fe8..7f777ac43 100644 --- a/src/daemon/rpc_command_executor.h +++ b/src/daemon/rpc_command_executor.h @@ -83,11 +83,11 @@ public: return true; } catch (const std::exception& e) { if (!error.empty()) - tools::fail_msg_writer() << error << ": " << e.what(); + tools::fail_msg_writer("{}: {}", error, e.what()); return false; } catch (...) {} if (!error.empty()) - tools::fail_msg_writer() << error; + tools::fail_msg_writer(error); return false; } @@ -133,7 +133,7 @@ public: if (!try_running([this] { return invoke(); }, error_prefix)) return false; - tools::success_msg_writer() << success_msg; + tools::success_msg_writer(success_msg); return true; } diff --git a/src/device/device_ledger.cpp b/src/device/device_ledger.cpp index 2d6e38dcd..65ab8bb5c 100644 --- a/src/device/device_ledger.cpp +++ b/src/device/device_ledger.cpp @@ -28,6 +28,7 @@ // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +#include "common/string_util.h" #include "device/io_ledger_tcp.hpp" #include "io_hid.hpp" #include "version.h" @@ -388,7 +389,7 @@ namespace hw::ledger { void device_ledger::logRESP() { if (apdu_verbose) - log::debug(logcat, "RESP (+{}): {} {}", tools::short_duration(std::chrono::steady_clock::now() - last_cmd), oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}), oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); + log::debug(logcat, "RESP (+{}): {} {}", tools::friendly_duration(std::chrono::steady_clock::now() - last_cmd), oxenc::to_hex(std::string_view{reinterpret_cast(&sw), sizeof(sw)}), oxenc::to_hex(buffer_recv, buffer_recv + length_recv)); } int device_ledger::set_command_header(unsigned char ins, unsigned char p1, unsigned char p2) { diff --git a/src/device_trezor/trezor/transport.cpp b/src/device_trezor/trezor/transport.cpp index e66d074a2..034bdf584 100644 --- a/src/device_trezor/trezor/transport.cpp +++ b/src/device_trezor/trezor/transport.cpp @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -877,11 +876,7 @@ namespace trezor{ } static std::string get_usb_path(uint8_t bus_id, const std::vector &path){ - std::ostringstream ss; - ss << WebUsbTransport::PATH_PREFIX << std::setw(3) << std::setfill('0') << (int)bus_id; - for (int port : path) - ss << ':' << port; - return ss.str(); + return fmt::format("{}{:03d}:{:d}", WebUsbTransport::PATH_PREFIX, bus_id, fmt::join(path, ":")); } const char * WebUsbTransport::PATH_PREFIX = "webusb:"; diff --git a/src/gen_multisig/gen_multisig.cpp b/src/gen_multisig/gen_multisig.cpp index 4b428bef0..dbe192c50 100644 --- a/src/gen_multisig/gen_multisig.cpp +++ b/src/gen_multisig/gen_multisig.cpp @@ -35,11 +35,11 @@ * \brief Generates a set of multisig wallets */ #include -#include #include #include #include #include "crypto/crypto.h" // for crypto::secret_key definition +#include "common/fs-format.h" #include "common/i18n.h" #include "common/command_line.h" #include "common/util.h" @@ -75,7 +75,7 @@ namespace static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path& basename, network_type nettype, bool create_address_file) { - tools::msg_writer() << fmt::format(genms::tr("Generating {:d} {:d}/{:d} multisig wallets"), total, threshold, total); + tools::msg_writer(genms::tr("Generating {:d} {:d}/{:d} multisig wallets"), total, threshold, total); const auto pwd_container = tools::password_container::prompt(true, "Enter password for new multisig wallets"); @@ -100,7 +100,7 @@ static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path wallets[n]->decrypt_keys(pwd_container->password()); if (!tools::wallet2::verify_multisig_info(wallets[n]->get_multisig_info(), sk[n], pk[n])) { - tools::fail_msg_writer() << genms::tr("Failed to verify multisig info"); + tools::fail_msg_writer(genms::tr("Failed to verify multisig info")); return false; } wallets[n]->encrypt_keys(pwd_container->password()); @@ -108,10 +108,10 @@ static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path // make the wallets multisig std::vector extra_info(total); - std::stringstream ss; + std::vector filenames; for (size_t n = 0; n < total; ++n) { - fs::path name = basename; + auto& name = filenames.emplace_back(basename); name += "-" + std::to_string(n + 1); std::vector skn; std::vector pkn; @@ -124,7 +124,6 @@ static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path } } extra_info[n] = wallets[n]->make_multisig(pwd_container->password(), skn, pkn, threshold); - ss << " " << name << std::endl; } //exchange keys unless exchange_multisig_keys returns no extra info @@ -136,7 +135,7 @@ static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path { if (!tools::wallet2::verify_extra_multisig_info(extra_info[n], pkeys, signers[n])) { - tools::fail_msg_writer() << genms::tr("Error verifying multisig extra info"); + tools::fail_msg_writer(genms::tr("Error verifying multisig extra info")); return false; } } @@ -146,12 +145,13 @@ static bool generate_multisig(uint32_t threshold, uint32_t total, const fs::path } } - std::string address = wallets[0]->get_account().get_public_address_str(wallets[0]->nettype()); - tools::success_msg_writer() << genms::tr("Generated multisig wallets for address ") << address << std::endl << ss.str(); + tools::success_msg_writer("{}{}\n{}", genms::tr("Generated multisig wallets for address "), + wallets[0]->get_account().get_public_address_str(wallets[0]->nettype()), + fmt::join(filenames, " ")); } catch (const std::exception &e) { - tools::fail_msg_writer() << genms::tr("Error creating multisig wallets: ") << e.what(); + tools::fail_msg_writer("{}{}", genms::tr("Error creating multisig wallets: "), e.what()); return false; } @@ -178,7 +178,7 @@ int main(int argc, char* argv[]) desc_params, po::options_description{}, boost::program_options::positional_options_description(), - [](const std::string &s){ tools::scoped_message_writer() << s; }, + [](const std::string &s){ tools::msg_writer(s); }, "oxen-gen-multisig.log" ); if (!vm) @@ -193,14 +193,14 @@ int main(int argc, char* argv[]) devnet = command_line::get_arg(*vm, arg_devnet); if (testnet && devnet) { - tools::fail_msg_writer() << genms::tr("Error: Can't specify more than one of --testnet and --devnet"); + tools::fail_msg_writer(genms::tr("Error: Can't specify more than one of --testnet and --devnet")); return 1; } if (command_line::has_arg(*vm, arg_scheme)) { if (sscanf(command_line::get_arg(*vm, arg_scheme).c_str(), "%u/%u", &threshold, &total) != 2) { - tools::fail_msg_writer() << genms::tr("Error: expected N/M, but got: ") << command_line::get_arg(*vm, arg_scheme); + tools::fail_msg_writer("{}{}", genms::tr("Error: expected N/M, but got: "), command_line::get_arg(*vm, arg_scheme)); return 1; } } @@ -208,7 +208,7 @@ int main(int argc, char* argv[]) { if (threshold) { - tools::fail_msg_writer() << genms::tr("Error: either --scheme or both of --threshold and --participants may be given"); + tools::fail_msg_writer(genms::tr("Error: either --scheme or both of --threshold and --participants may be given")); return 1; } threshold = command_line::get_arg(*vm, arg_threshold); @@ -217,14 +217,14 @@ int main(int argc, char* argv[]) { if (total) { - tools::fail_msg_writer() << genms::tr("Error: either --scheme or both of --threshold and --participants may be given"); + tools::fail_msg_writer(genms::tr("Error: either --scheme or both of --threshold and --participants may be given")); return 1; } total = command_line::get_arg(*vm, arg_participants); } if (threshold <= 1 || threshold > total) { - tools::fail_msg_writer() << fmt::format(genms::tr("Error: expected N > 1 and N <= M, but got N=={:d} and M=={:d}"), threshold, total); + tools::fail_msg_writer(genms::tr("Error: expected N > 1 and N <= M, but got N=={:d} and M=={:d}"), threshold, total); return 1; } fs::path basename; @@ -234,7 +234,7 @@ int main(int argc, char* argv[]) } else { - tools::fail_msg_writer() << genms::tr("Error: --filename-base is required"); + tools::fail_msg_writer(genms::tr("Error: --filename-base is required")); return 1; } diff --git a/src/p2p/net_node.inl b/src/p2p/net_node.inl index 2f508e3f7..e0921a388 100644 --- a/src/p2p/net_node.inl +++ b/src/p2p/net_node.inl @@ -47,6 +47,7 @@ #include "epee/string_tools.h" #include "epee/time_helper.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/pruning.h" #include "net/error.h" #include "common/periodic_task.h" diff --git a/src/ringct/rctTypes.h b/src/ringct/rctTypes.h index 98d3c8362..4cebd028c 100644 --- a/src/ringct/rctTypes.h +++ b/src/ringct/rctTypes.h @@ -560,8 +560,13 @@ namespace rct { inline const crypto::hash &rct2hash(const rct::key &k) { return (const crypto::hash&)k; } inline bool operator==(const rct::key &k0, const crypto::public_key &k1) { return !crypto_verify_32(k0.bytes, (const unsigned char*)&k1); } inline bool operator!=(const rct::key &k0, const crypto::public_key &k1) { return crypto_verify_32(k0.bytes, (const unsigned char*)&k1); } + + inline std::string to_hex_string(const rct::key& v) { + return "<{}>"_format(tools::type_to_hex(v)); + } } +template <> inline constexpr bool formattable::via_to_hex_string = true; namespace cryptonote { inline bool operator==(const crypto::public_key &k0, const rct::key &k1) { return !crypto_verify_32((const unsigned char*)&k0, k1.bytes); } @@ -570,12 +575,6 @@ namespace cryptonote { inline bool operator!=(const crypto::secret_key &k0, const rct::key &k1) { return crypto_verify_32((const unsigned char*)&k0, k1.bytes); } } -namespace rct { -inline std::ostream &operator <<(std::ostream &o, const rct::key &v) { - return o << '<' << tools::type_to_hex(v) << '>'; -} -} - namespace std { template<> struct hash { std::size_t operator()(const rct::key &k) const { return reinterpret_cast(k); } }; diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 59835ec29..537401a32 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -35,6 +35,7 @@ * \brief Source file that defines simple_wallet class. */ +#include #include "common/string_util.h" #include "oxen_economy.h" #include @@ -63,6 +64,7 @@ #include "common/signal_handler.h" #include "common/base58.h" #include "common/scoped_message_writer.h" +#include "common/fs-format.h" #include "cryptonote_protocol/cryptonote_protocol_handler.h" #include "cryptonote_core/service_node_voting.h" #include "cryptonote_core/service_node_list.h" @@ -91,6 +93,12 @@ extern "C" #include } +// grumble, grumble +namespace formattable { + std::string to_string(const boost::basic_format& f) { return f.str(); } + template <> constexpr bool via_to_string> = true; +} + namespace cryptonote { @@ -302,22 +310,6 @@ namespace return buf; } - std::optional password_prompter(const char *prompt, bool verify) - { - rdln::suspend_readline pause_readline; - auto pwd_container = tools::password_container::prompt(verify, prompt); - if (!pwd_container) - { - tools::fail_msg_writer() << sw::tr("failed to read wallet password"); - } - return pwd_container; - } - - std::optional default_password_prompter(bool verify) - { - return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify); - } - inline std::string interpret_rpc_response(bool ok, const std::string& status) { std::string err; @@ -339,26 +331,59 @@ namespace return err; } - tools::scoped_message_writer success_msg_writer(bool color = false) + // Replacing all the << in here with proper formatting is just too painful, so make a crappy + // subclass that provides a << that just slams it through a basic format. + class simplewallet_crappy_message_writer : public tools::scoped_message_writer { + public: + using tools::scoped_message_writer::scoped_message_writer; + + template + auto& operator<<(T&& val) { + append("{}", std::forward(val)); + return *this; + } + }; + + simplewallet_crappy_message_writer success_msg_writer(bool color = false) { - return tools::scoped_message_writer(color ? fmt::terminal_color::green : fmt::terminal_color::white, std::string{}, spdlog::level::info); + std::optional c = std::nullopt; + if (color) + c = fmt::terminal_color::green; + return simplewallet_crappy_message_writer(c, std::string{}, spdlog::level::info); } - tools::scoped_message_writer message_writer(fmt::terminal_color color = fmt::terminal_color::white) + simplewallet_crappy_message_writer message_writer(std::optional color = std::nullopt) { - return tools::scoped_message_writer(color); + return simplewallet_crappy_message_writer(color); } - tools::scoped_message_writer fail_msg_writer() + simplewallet_crappy_message_writer fail_msg_writer() { - return tools::scoped_message_writer(fmt::terminal_color::red, sw::tr("Error: "), spdlog::level::err); + return simplewallet_crappy_message_writer(fmt::terminal_color::red, sw::tr("Error: "), spdlog::level::err); } - tools::scoped_message_writer warn_msg_writer() + simplewallet_crappy_message_writer warn_msg_writer() { - return tools::scoped_message_writer(fmt::terminal_color::red, sw::tr("Warning: "), spdlog::level::warn); + return simplewallet_crappy_message_writer(fmt::terminal_color::red, sw::tr("Warning: "), spdlog::level::warn); } + std::optional password_prompter(const char *prompt, bool verify) + { + rdln::suspend_readline pause_readline; + auto pwd_container = tools::password_container::prompt(verify, prompt); + if (!pwd_container) + { + fail_msg_writer() << sw::tr("failed to read wallet password"); + } + return pwd_container; + } + + std::optional default_password_prompter(bool verify) + { + return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify); + } + + bool parse_bool(const std::string& s, bool& result) { if (command_line::is_yes(s, "1", "true", simple_wallet::tr("true"))) @@ -498,7 +523,7 @@ namespace } catch (const tools::error::tx_rejected& e) { - fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx())); + fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx())).str(); std::string reason = e.reason(); if (!reason.empty()) fail_msg_writer() << sw::tr("Reason: ") << reason; @@ -2468,7 +2493,7 @@ bool simple_wallet::set_track_uses(const std::vector &args/* = std: bool simple_wallet::set_inactivity_lock_timeout(const std::vector &args/* = std::vector()*/) { #ifdef _WIN32 - tools::fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows"); + fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows"); return true; #endif const auto pwd_container = get_and_verify_password(); @@ -2482,7 +2507,7 @@ bool simple_wallet::set_inactivity_lock_timeout(const std::vector & } else { - tools::fail_msg_writer() << tr("Invalid number of seconds"); + fail_msg_writer() << tr("Invalid number of seconds"); } } return true; @@ -5608,7 +5633,7 @@ void simple_wallet::check_for_inactivity_lock(bool user) m_in_command = true; if (!user) { - tools::msg_writer() << R"( + message_writer() << R"( ........... ............... ....OOOOOOOOOOO.... Your Oxen Wallet was locked to @@ -5624,7 +5649,7 @@ void simple_wallet::check_for_inactivity_lock(bool user) while (1) { const char *inactivity_msg = user ? "" : tr("Locked due to inactivity."); - tools::msg_writer() << inactivity_msg << (inactivity_msg[0] ? " " : "") << tr("The wallet password is required to unlock the console."); + message_writer() << inactivity_msg << (inactivity_msg[0] ? " " : "") << tr("The wallet password is required to unlock the console."); try { if (get_and_verify_password()) @@ -6178,7 +6203,7 @@ bool simple_wallet::stake(const std::vector &args_) } if (!stake_result.msg.empty()) // i.e. warnings - tools::msg_writer() << stake_result.msg; + message_writer() << stake_result.msg; std::vector ptx_vector = {stake_result.ptx}; cryptonote::address_parse_info info = {}; @@ -6233,7 +6258,7 @@ bool simple_wallet::request_stake_unlock(const std::vector &args_) tools::wallet2::request_stake_unlock_result unlock_result = m_wallet->can_request_stake_unlock(snode_key); if (unlock_result.success) { - tools::msg_writer() << unlock_result.msg; + message_writer() << unlock_result.msg; } else { @@ -6542,7 +6567,7 @@ bool simple_wallet::query_locked_stakes(bool print_details, bool print_key_image if (msg.empty() && print_details) msg = "No locked stakes known for this wallet on the network"; if (!msg.empty()) - tools::msg_writer() << msg; + message_writer() << msg; return has_locked_stakes; } @@ -6574,7 +6599,7 @@ static std::optional guess_ons_type(tools::wallet2& wallet, s auto hf_version = wallet.get_hard_fork_version(); if (!hf_version) { - tools::fail_msg_writer() << tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED; + fail_msg_writer() << tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED; return std::nullopt; } @@ -6633,7 +6658,7 @@ bool simple_wallet::ons_buy_mapping(std::vector args) if (ptx_vector.empty()) { - tools::fail_msg_writer() << reason; + fail_msg_writer() << reason; return true; } @@ -6731,7 +6756,7 @@ bool simple_wallet::ons_renew_mapping(std::vector args) &response); if (ptx_vector.empty()) { - tools::fail_msg_writer() << reason; + fail_msg_writer() << reason; return true; } @@ -6816,7 +6841,7 @@ bool simple_wallet::ons_update_mapping(std::vector args) &response); if (ptx_vector.empty()) { - tools::fail_msg_writer() << reason; + fail_msg_writer() << reason; return true; } @@ -6929,32 +6954,32 @@ bool simple_wallet::ons_encrypt(std::vector args) auto hf_version = m_wallet->get_hard_fork_version(); if (!hf_version) { - tools::fail_msg_writer() << tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED; + fail_msg_writer() << tools::wallet2::ERR_MSG_NETWORK_VERSION_QUERY_FAILED; return false; } std::string reason; if (!ons::validate_ons_name(type, name, &reason)) { - tools::fail_msg_writer() << "Invalid ONS name '" << name << "': " << reason; + fail_msg_writer() << "Invalid ONS name '" << name << "': " << reason; return false; } ons::mapping_value mval; if (!ons::mapping_value::validate(m_wallet->nettype(), type, value, &mval, &reason)) { - tools::fail_msg_writer() << "Invalid ONS value '" << value << "': " << reason; + fail_msg_writer() << "Invalid ONS value '" << value << "': " << reason; return false; } bool old_argon2 = type == ons::mapping_type::session && hf_version < hf::hf16_pulse; if (!mval.encrypt(name, nullptr, old_argon2)) { - tools::fail_msg_writer() << "Value encryption failed"; + fail_msg_writer() << "Value encryption failed"; return false; } - tools::success_msg_writer() << "encrypted value=" << oxenc::to_hex(mval.to_view()); + success_msg_writer() << "encrypted value=" << oxenc::to_hex(mval.to_view()); return true; } //---------------------------------------------------------------------------------------------------- @@ -6984,7 +7009,7 @@ bool simple_wallet::ons_make_update_mapping_signature(std::vector a signature_binary, m_current_subaddress_account, &reason)) - tools::success_msg_writer() << "signature=" << tools::type_to_hex(signature_binary.ed25519); + success_msg_writer() << "signature=" << tools::type_to_hex(signature_binary.ed25519); else fail_msg_writer() << reason; @@ -7091,7 +7116,7 @@ bool simple_wallet::ons_lookup(std::vector args) return false; } - auto writer = tools::msg_writer(); + auto writer = message_writer(); writer << "Name: " << name << "\n Type: " << static_cast(mapping["type"]) @@ -7182,7 +7207,7 @@ bool simple_wallet::ons_by_owner(const std::vector& args) value = mv.to_readable_value(nettype, ons_type); } - auto writer = tools::msg_writer(); + auto writer = message_writer(); writer << "Name (hashed): " << entry["name_hash"]; if (!name.empty()) writer @@ -10336,7 +10361,7 @@ int main(int argc, char* argv[]) desc_params, hidden_params, positional_options, - [](const std::string &s){ tools::scoped_message_writer(fmt::terminal_color::white) << s; }, + [](const std::string &s){ tools::scoped_message_writer() + s; }, "oxen-wallet-cli.log" ); diff --git a/src/wallet/api/pending_transaction.cpp b/src/wallet/api/pending_transaction.cpp index 08ec0dbac..83cd82d7c 100644 --- a/src/wallet/api/pending_transaction.cpp +++ b/src/wallet/api/pending_transaction.cpp @@ -39,7 +39,6 @@ #include #include -#include #include namespace Wallet { diff --git a/src/wallet/api/unsigned_transaction.cpp b/src/wallet/api/unsigned_transaction.cpp index af9566ee0..14378b418 100644 --- a/src/wallet/api/unsigned_transaction.cpp +++ b/src/wallet/api/unsigned_transaction.cpp @@ -37,7 +37,6 @@ #include #include -#include #include namespace Wallet { diff --git a/src/wallet/ringdb.cpp b/src/wallet/ringdb.cpp index bdd3cfb37..915599b96 100644 --- a/src/wallet/ringdb.cpp +++ b/src/wallet/ringdb.cpp @@ -29,6 +29,7 @@ #include #include "common/file.h" +#include "common/fs-format.h" #include "epee/misc_log_ex.h" #include "wallet_errors.h" #include "ringdb.h" diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 942770b5c..44fd9e537 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -64,6 +64,7 @@ #include "common/i18n.h" #include "common/util.h" #include "common/file.h" +#include "common/fs-format.h" #include "common/apply_permutation.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" @@ -249,7 +250,7 @@ namespace { if (auto got = m_vote_ctx.find("m_votes_not_sorted"); got != m_vote_ctx.end()) os << "Votes are not stored in ascending order"; if (tx) - os << "TX Version: " << tx->version << ", Type: " << tx->type; + os << "TX Version: {}, Type: {}"_format(tx->version, tx->type); std::string buf = os.str(); if (buf.size() >= 2 && buf[buf.size() - 2] == ',') diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 1720fed61..8588789e6 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -54,7 +54,6 @@ #include "common/file.h" #include "crypto/chacha.h" #include "crypto/hash.h" -#include "crypto/fmt.h" #include "ringct/rctTypes.h" #include "ringct/rctOps.h" #include "checkpoints/checkpoints.h" diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index 76ad15b20..9ec4e14f9 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -33,6 +33,7 @@ #include "common/i18n.h" #include "common/util.h" #include "common/file.h" +#include "common/fs-format.h" #include "epee/misc_log_ex.h" #include "epee/string_tools.h" #include "version.h" diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 20cdb5e8c..7a67078fd 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -43,6 +43,7 @@ #include "common/command_line.h" #include "common/i18n.h" #include "common/signal_handler.h" +#include "common/fs-format.h" #include "cryptonote_config.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "cryptonote_basic/account.h" diff --git a/tests/difficulty/CMakeLists.txt b/tests/difficulty/CMakeLists.txt index c858c2e08..5b9ca05ab 100644 --- a/tests/difficulty/CMakeLists.txt +++ b/tests/difficulty/CMakeLists.txt @@ -33,6 +33,7 @@ target_link_libraries(difficulty-tests cncrypto epee cryptonote_basic + common extra) set_property(TARGET difficulty-tests PROPERTY diff --git a/tests/unit_tests/crypto.cpp b/tests/unit_tests/crypto.cpp index e9ada7579..627d853cf 100644 --- a/tests/unit_tests/crypto.cpp +++ b/tests/unit_tests/crypto.cpp @@ -48,7 +48,6 @@ namespace "6c7251d54154cfa92c173a0dd39c1f948b655970153799af2aeadc9ff1add0ea"; template void *addressof(T &t) { return &t; } - template<> void *addressof(crypto::secret_key &k) { return addressof(unwrap(unwrap(k))); } template bool is_formatted() @@ -60,9 +59,7 @@ namespace static_assert(sizeof(T) * 2 <= sizeof(expected), "T is too large for destination"); std::memcpy(addressof(value), source, sizeof(T)); - std::stringstream out; - out << "BEGIN" << value << "END"; - return out.str() == "BEGIN<" + std::string{expected, sizeof(T) * 2} + ">END"; + return "{}"_format(value) == "<{}>"_format(std::string{expected, sizeof(T) * 2}); } } @@ -71,7 +68,6 @@ TEST(Crypto, Ostream) EXPECT_TRUE(is_formatted()); EXPECT_TRUE(is_formatted()); EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); EXPECT_TRUE(is_formatted()); EXPECT_TRUE(is_formatted()); EXPECT_TRUE(is_formatted()); diff --git a/tests/unit_tests/oxen_name_system.cpp b/tests/unit_tests/oxen_name_system.cpp index 47237bc07..872cf470c 100644 --- a/tests/unit_tests/oxen_name_system.cpp +++ b/tests/unit_tests/oxen_name_system.cpp @@ -78,7 +78,7 @@ TEST(oxen_name_system, name_tests) for (size_t i = 0; i < names_count; i++) { name_test const &entry = names[i]; - ASSERT_EQ(ons::validate_ons_name(type, entry.name), entry.allowed) << "Values were {type=" << type << ", name=\"" << entry.name << "\"}"; + ASSERT_EQ(ons::validate_ons_name(type, entry.name), entry.allowed) << "Values were {{type={}, name=\"{}\"}}"_format(type, entry.name); } } } diff --git a/tests/unit_tests/ringct.cpp b/tests/unit_tests/ringct.cpp index c91cdf9ae..286280a95 100644 --- a/tests/unit_tests/ringct.cpp +++ b/tests/unit_tests/ringct.cpp @@ -778,11 +778,10 @@ TEST(ringct, reject_gen_simple_ver_non_simple) TEST(ringct, key_ostream) { - std::stringstream out; - out << "BEGIN" << rct::H << "END"; + auto out = "BEGIN{}END"_format(rct::H); EXPECT_EQ( std::string{"BEGIN<8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94>END"}, - out.str() + out ); } From 661a0c089c3dff5aae062c20cf51fa35b464e102 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Sat, 8 Oct 2022 00:25:49 -0300 Subject: [PATCH 27/32] Fix slurp_file potentially reading in non-binary mode I'm not sure if this gets used on Windows, but if it does, this could do windows linefeed conversions, which it isn't supposed to. --- src/common/file.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/file.cpp b/src/common/file.cpp index c28d4fc41..e45a27630 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -305,7 +305,7 @@ namespace tools { { try { - fs::ifstream in(filename); + fs::ifstream in(filename, std::ios::binary); std::string content((std::istreambuf_iterator(in)), (std::istreambuf_iterator())); contents = std::move(content); return true; From cd386836194499147f9c1ec2db1f2be2de1cfeb0 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 10 Oct 2022 20:25:23 -0300 Subject: [PATCH 28/32] Add missing header --- src/common/fs-format.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/common/fs-format.h diff --git a/src/common/fs-format.h b/src/common/fs-format.h new file mode 100644 index 000000000..f5c1e6b80 --- /dev/null +++ b/src/common/fs-format.h @@ -0,0 +1,17 @@ +#pragma once + +#include "fs.h" + +#ifndef USE_GHC_FILESYSTEM +#include +#else +#include "formattable.h" + +namespace formattable { + template <> inline constexpr bool via_to_string = true; + + inline std::string to_string(const ghc::filesystem::path& path) { + return path.string(); + } +} +#endif From 43343f3b905e8e3ff47bedca26c4f75c2885df60 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 10 Oct 2022 21:06:16 -0300 Subject: [PATCH 29/32] Fix ec_point sub-types not being formattable; fix crappy test code Fixed a bug where ec_point subclasses were not getting formatted via to_string(ec_point). Also fixed the crappy test code that was incapable of reporting the actual test failure. --- src/crypto/crypto.h | 6 +++++- tests/unit_tests/crypto.cpp | 39 ++++++++++++++++++------------------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h index 7670fba3c..25d750f78 100644 --- a/src/crypto/crypto.h +++ b/src/crypto/crypto.h @@ -302,7 +302,11 @@ CRYPTO_MAKE_HASHABLE(signature) CRYPTO_MAKE_HASHABLE(ed25519_public_key) CRYPTO_MAKE_HASHABLE(x25519_public_key) -template <> inline constexpr bool formattable::via_to_string = true; +// ec_point is formattable via to_string, as are any subclasses (such as public_key): +template +inline constexpr bool formattable::via_to_string> +> = true; template <> inline constexpr bool formattable::via_to_string = true; template <> inline constexpr bool formattable::via_to_string = true; template <> inline constexpr bool formattable::via_to_string = true; diff --git a/tests/unit_tests/crypto.cpp b/tests/unit_tests/crypto.cpp index 627d853cf..444ed2789 100644 --- a/tests/unit_tests/crypto.cpp +++ b/tests/unit_tests/crypto.cpp @@ -36,41 +36,40 @@ namespace { - alignas(size_t) static constexpr const std::uint8_t source[] = { + constexpr const std::array source = { 0x8b, 0x65, 0x59, 0x70, 0x15, 0x37, 0x99, 0xaf, 0x2a, 0xea, 0xdc, 0x9f, 0xf1, 0xad, 0xd0, 0xea, 0x6c, 0x72, 0x51, 0xd5, 0x41, 0x54, 0xcf, 0xa9, 0x2c, 0x17, 0x3a, 0x0d, 0xd3, 0x9c, 0x1f, 0x94, 0x6c, 0x72, 0x51, 0xd5, 0x41, 0x54, 0xcf, 0xa9, 0x2c, 0x17, 0x3a, 0x0d, 0xd3, 0x9c, 0x1f, 0x94, 0x8b, 0x65, 0x59, 0x70, 0x15, 0x37, 0x99, 0xaf, 0x2a, 0xea, 0xdc, 0x9f, 0xf1, 0xad, 0xd0, 0xea }; - static constexpr const char expected[] = + constexpr std::string_view hex_full = "8b655970153799af2aeadc9ff1add0ea6c7251d54154cfa92c173a0dd39c1f94" - "6c7251d54154cfa92c173a0dd39c1f948b655970153799af2aeadc9ff1add0ea"; + "6c7251d54154cfa92c173a0dd39c1f948b655970153799af2aeadc9ff1add0ea"sv; - template void *addressof(T &t) { return &t; } + template = 0> + constexpr std::string_view hex_data = hex_full.substr(0, 2*Size); - template - bool is_formatted() - { - T value{}; - static_assert(alignof(T) <= alignof(size_t), "T must have size_t-or-smaller alignment"); - static_assert(sizeof(T) <= sizeof(source), "T is too large for source"); - static_assert(sizeof(T) * 2 <= sizeof(expected), "T is too large for destination"); - std::memcpy(addressof(value), source, sizeof(T)); + template + T shove_into() { + T val; + static_assert(alignof(T) <= alignof(size_t), "T must have size_t (or smaller) alignment"); + static_assert(sizeof(T) <= source.size(), "T is too large for this test"); - return "{}"_format(value) == "<{}>"_format(std::string{expected, sizeof(T) * 2}); + std::memcpy(&val, source.data(), sizeof(T)); + return val; } } -TEST(Crypto, Ostream) +TEST(Crypto, Format) { - EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); - EXPECT_TRUE(is_formatted()); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<8>)); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<32>)); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<32>)); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<64>)); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<32>)); + EXPECT_EQ("{}"_format(shove_into()), "<{}>"_format(hex_data<32>)); } TEST(Crypto, null_keys) From 5b4a60b412f06042a1b9e09e549ddd9b23f220d8 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 13 Oct 2022 13:37:23 -0300 Subject: [PATCH 30/32] Update variant header from oxenmq to oxenc The latest oxenmq dropped the long-deprecated compat header. --- contrib/epee/include/epee/storages/portable_storage_to_bin.h | 2 +- contrib/epee/src/portable_storage.cpp | 2 +- src/common/meta.h | 2 +- src/rpc/http_server.cpp | 2 +- src/serialization/boost_std_variant.h | 2 +- src/serialization/variant.h | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/epee/include/epee/storages/portable_storage_to_bin.h b/contrib/epee/include/epee/storages/portable_storage_to_bin.h index 8b5de9911..0861cb89c 100644 --- a/contrib/epee/include/epee/storages/portable_storage_to_bin.h +++ b/contrib/epee/include/epee/storages/portable_storage_to_bin.h @@ -31,7 +31,7 @@ #include "../pragma_comp_defs.h" #include "portable_storage_base.h" #include -#include +#include #include namespace epee diff --git a/contrib/epee/src/portable_storage.cpp b/contrib/epee/src/portable_storage.cpp index 7338f5be2..e14002964 100644 --- a/contrib/epee/src/portable_storage.cpp +++ b/contrib/epee/src/portable_storage.cpp @@ -1,6 +1,6 @@ #include "epee/storages/portable_storage_to_json.h" #include "epee/storages/portable_storage.h" -#include +#include namespace epee { namespace serialization { diff --git a/src/common/meta.h b/src/common/meta.h index 4ca051a5f..da72975d8 100644 --- a/src/common/meta.h +++ b/src/common/meta.h @@ -1,6 +1,6 @@ #pragma once #include -#include +#include #include #include #ifdef __GNUG__ diff --git a/src/rpc/http_server.cpp b/src/rpc/http_server.cpp index f780444f5..056d3167c 100644 --- a/src/rpc/http_server.cpp +++ b/src/rpc/http_server.cpp @@ -2,7 +2,7 @@ #include "http_server.h" #include #include -#include +#include #include "common/command_line.h" #include "common/string_util.h" #include "cryptonote_config.h" diff --git a/src/serialization/boost_std_variant.h b/src/serialization/boost_std_variant.h index dd150d24b..13b95fbdd 100644 --- a/src/serialization/boost_std_variant.h +++ b/src/serialization/boost_std_variant.h @@ -5,7 +5,7 @@ // interchangeable). // -#include +#include #include diff --git a/src/serialization/variant.h b/src/serialization/variant.h index 1dcf6b294..d43460299 100644 --- a/src/serialization/variant.h +++ b/src/serialization/variant.h @@ -36,7 +36,7 @@ */ #pragma once -#include +#include #include "serialization.h" #include "common/meta.h" From 6aa9db95383a5214165d6675d2589f57aff06766 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 14 Oct 2022 22:22:44 -0300 Subject: [PATCH 31/32] Overhaul and fix crypto::{public_key,ec_point,etc.} types - Remove implicit `operator bool` from ec_point/public_key/etc. which was causing all sorts of implicit conversion mess and bugs. - Change ec_point/public_key/etc. to use a `std::array` (via a base type) rather than a C-array of char that has to be reinterpret_cast<>'ed all over the place. - Add methods to ec_point/public_key/etc. that make it work more like a container of bytes (`.data()`, `.size()`, `operator[]`, `begin()`, `end()`). - Make a generic `crypto::null` that is a constexpr all-0 `T`, rather than the mishmash `crypto::null_hash`, crypto::null_pkey, crypto::hash::null(), and so on. - Replace three metric tons of `crypto::hash blahblah = crypto::null_hash;` with the much simpler `crypto::hash blahblah{};`, because there's no need to make a copy of a null hash in all these cases. (Likewise for a few other null_whatevers). - Remove a whole bunch of `if (blahblah == crypto::null_hash)` and `if (blahblah != crypto::null_hash)` with the more concise `if (!blahblah)` and `if (blahblah)` (which are fine via the newly *explicit* bool conversion operators). - `crypto::signature` becomes a 64-byte container (as above) but with `c()` and `r()` to get the c() and r() data pointers. (Previously `.c` and `.r` were `ec_scalar`s). - Delete with great prejudice CRYPTO_MAKE_COMPARABLE and CRYPTO_MAKE_HASHABLE and all the other utter trash in `crypto/generic-ops.h`. - De-inline functions in very common crypto/*.h files so that they don't have to get compiled 300 times. - Remove the disgusting include-a-C-header-inside-a-C++-namespace garbage from some crypto headers trying to be both a C and *different* C++ header at once. - Remove the toxic, disgusting, shameful `operator&` on ec_scalar, etc. that replace `&x` with `reinterpret_cast x into an unsigned char*`. This was pure toxic waste. - changed some `<<` outputs to fmt - Random other small changes encountered while fixing everything that cascaded out of the above changes. --- .drone.jsonnet | 2 +- contrib/epee/include/epee/mlocker.h | 2 +- src/blockchain_db/blockchain_db.cpp | 2 +- src/blockchain_db/lmdb/db_lmdb.cpp | 10 +- src/blockchain_db/sqlite/db_sqlite.cpp | 2 +- .../blockchain_ancestry.cpp | 3 +- src/blockchain_utilities/blockchain_depth.cpp | 2 +- src/blockchain_utilities/blockchain_stats.cpp | 4 +- src/blockchain_utilities/blocksdat_file.cpp | 3 +- src/blockchain_utilities/bootstrap_file.cpp | 4 +- src/checkpoints/checkpoints.cpp | 4 +- src/common/sha256sum.cpp | 4 +- src/common/util.h | 26 +- src/crypto/CMakeLists.txt | 2 + src/crypto/base.h | 82 ++++ src/crypto/chacha.cpp | 43 +++ src/crypto/chacha.h | 57 +-- src/crypto/cn_monero_slow_hash.c | 8 +- src/crypto/cn_turtle_hash-amd64.inl | 4 +- src/crypto/cn_turtle_hash-arm.inl | 8 +- src/crypto/cn_turtle_hash-portable.inl | 4 +- src/crypto/crypto.cpp | 362 +++++++++--------- src/crypto/crypto.h | 128 +++---- src/crypto/generic-ops.h | 81 ---- src/crypto/hash-extra-jh.c | 4 +- src/crypto/hash-extra-skein.c | 4 +- src/crypto/hash-ops.h | 22 +- src/crypto/hash.c | 2 +- src/crypto/hash.cpp | 85 ++++ src/crypto/hash.h | 134 ++----- src/crypto/random.c | 4 +- src/crypto/rx-slow-hash.c | 4 +- src/crypto/tree-hash.c | 4 +- src/cryptonote_basic/account.cpp | 8 +- src/cryptonote_basic/connection_context.h | 2 +- src/cryptonote_basic/cryptonote_basic.cpp | 2 +- .../cryptonote_format_utils.cpp | 49 +-- src/cryptonote_basic/tx_extra.cpp | 24 ++ src/cryptonote_basic/tx_extra.h | 10 +- src/cryptonote_core/blockchain.cpp | 31 +- src/cryptonote_core/blockchain.h | 2 +- src/cryptonote_core/cryptonote_core.cpp | 25 +- src/cryptonote_core/cryptonote_core.h | 2 +- src/cryptonote_core/cryptonote_tx_utils.cpp | 37 +- src/cryptonote_core/oxen_name_system.cpp | 48 +-- src/cryptonote_core/oxen_name_system.h | 2 +- src/cryptonote_core/pulse.cpp | 66 ++-- src/cryptonote_core/pulse.h | 5 +- src/cryptonote_core/service_node_list.cpp | 85 ++-- src/cryptonote_core/service_node_list.h | 8 +- .../service_node_quorum_cop.cpp | 10 + src/cryptonote_core/service_node_quorum_cop.h | 10 +- src/cryptonote_core/service_node_rules.cpp | 2 +- src/cryptonote_core/service_node_voting.cpp | 4 +- src/cryptonote_core/tx_blink.cpp | 6 +- src/cryptonote_core/tx_pool.cpp | 16 +- src/cryptonote_core/uptime_proof.cpp | 4 +- src/cryptonote_protocol/block_queue.cpp | 2 +- .../cryptonote_protocol_handler.inl | 4 +- src/cryptonote_protocol/quorumnet.cpp | 18 +- src/daemonizer/windows_service.cpp | 40 +- src/debug_utilities/cn_deserialize.cpp | 90 +++-- src/device/device_default.cpp | 25 +- src/device/device_ledger.cpp | 322 ++++++++-------- src/mnemonics/electrum-words.cpp | 6 +- src/mnemonics/electrum-words.h | 2 +- src/multisig/multisig.cpp | 6 +- src/ringct/rctOps.h | 2 - src/ringct/rctSigs.h | 2 - src/ringct/rctTypes.h | 1 - src/rpc/core_rpc_server.cpp | 23 +- src/rpc/core_rpc_server_commands_defs.h | 2 +- src/rpc/lmq_server.cpp | 12 +- src/simplewallet/simplewallet.cpp | 61 +-- src/wallet/api/pending_transaction.cpp | 2 +- src/wallet/api/unsigned_transaction.cpp | 12 +- src/wallet/api/wallet.cpp | 5 +- src/wallet/message_store.cpp | 6 +- src/wallet/message_store.h | 4 +- src/wallet/ringdb.cpp | 2 +- src/wallet/wallet2.cpp | 113 +++--- src/wallet/wallet2.h | 12 +- src/wallet/wallet_rpc_server.cpp | 32 +- src/wallet3/keyring.cpp | 2 +- tests/block_weight/block_weight.cpp | 6 +- tests/core_proxy/core_proxy.cpp | 26 +- tests/core_proxy/core_proxy.h | 4 +- tests/core_tests/bulletproofs.cpp | 6 +- tests/core_tests/chaingen.cpp | 27 +- tests/core_tests/chaingen.h | 22 +- tests/core_tests/multisig.cpp | 10 +- tests/core_tests/oxen_tests.cpp | 22 +- tests/core_tests/rct.cpp | 18 +- tests/core_tests/wallet_tools.cpp | 8 +- tests/crypto/crypto.cpp | 12 +- tests/crypto/main.cpp | 12 - tests/hash/main.cpp | 83 ++-- tests/io.h | 10 +- tests/trezor/trezor_tests.cpp | 2 +- tests/unit_tests/crypto.cpp | 33 +- tests/unit_tests/hashchain.cpp | 11 +- tests/unit_tests/long_term_block_weight.cpp | 8 +- tests/unit_tests/mnemonics.cpp | 2 +- tests/unit_tests/node_server.cpp | 4 +- tests/unit_tests/output_distribution.cpp | 4 +- tests/unit_tests/output_selection.cpp | 10 +- tests/unit_tests/serialization.cpp | 2 +- tests/unit_tests/test_tx_utils.cpp | 2 +- tests/wallet3_tests/db_schema.cpp | 4 +- tests/wallet3_tests/tx_creation.cpp | 2 - 110 files changed, 1339 insertions(+), 1387 deletions(-) create mode 100644 src/crypto/base.h create mode 100644 src/crypto/chacha.cpp delete mode 100644 src/crypto/generic-ops.h create mode 100644 src/crypto/hash.cpp diff --git a/.drone.jsonnet b/.drone.jsonnet index 70b0cebac..0f5d5695c 100644 --- a/.drone.jsonnet +++ b/.drone.jsonnet @@ -144,7 +144,7 @@ local mac_builder(name, 'mkdir build', 'cd build', 'cmake .. -G Ninja -DCMAKE_CXX_FLAGS=-fcolor-diagnostics -DCMAKE_BUILD_TYPE=' + build_type + ' ' + - '-DOXEN_LOGGING_FORCE_SUBMODULES=ON' + + '-DOXEN_LOGGING_FORCE_SUBMODULES=ON ' + '-DLOCAL_MIRROR=https://builds.lokinet.dev/deps -DUSE_LTO=' + (if lto then 'ON ' else 'OFF ') + (if werror then '-DWARNINGS_AS_ERRORS=ON ' else '') + (if build_tests || run_tests then '-DBUILD_TESTS=ON ' else '') + diff --git a/contrib/epee/include/epee/mlocker.h b/contrib/epee/include/epee/mlocker.h index 725d19642..6a48a7ad9 100644 --- a/contrib/epee/include/epee/mlocker.h +++ b/contrib/epee/include/epee/mlocker.h @@ -86,5 +86,5 @@ namespace epee template using mlocked_arr = mlocked>; - template constexpr bool is_byte_spannable> = is_byte_spannable; + template inline constexpr bool is_byte_spannable> = is_byte_spannable; } diff --git a/src/blockchain_db/blockchain_db.cpp b/src/blockchain_db/blockchain_db.cpp index 179debe52..adeb57bda 100644 --- a/src/blockchain_db/blockchain_db.cpp +++ b/src/blockchain_db/blockchain_db.cpp @@ -201,7 +201,7 @@ uint64_t BlockchainDB::add_block( const std::pair& blck num_rct_outs += blk.miner_tx.vout.size(); int tx_i = 0; - crypto::hash tx_hash = crypto::null_hash; + crypto::hash tx_hash{}; for (const std::pair& tx : txs) { tx_hash = blk.tx_hashes[tx_i]; diff --git a/src/blockchain_db/lmdb/db_lmdb.cpp b/src/blockchain_db/lmdb/db_lmdb.cpp index 8d0fe916b..b14559bd2 100644 --- a/src/blockchain_db/lmdb/db_lmdb.cpp +++ b/src/blockchain_db/lmdb/db_lmdb.cpp @@ -3008,7 +3008,7 @@ crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const return get_block_hash_from_height(m_height - 1); } - return null_hash; + return null; } block BlockchainLMDB::get_top_block() const @@ -5334,7 +5334,7 @@ void BlockchainLMDB::migrate_0_1() if (!parse_and_validate_block_from_blob(bd, b)) throw0(DB_ERROR("Failed to parse block from blob retrieved from the db")); - add_transaction(null_hash, std::make_pair(b.miner_tx, tx_to_blob(b.miner_tx))); + add_transaction(null, std::make_pair(b.miner_tx, tx_to_blob(b.miner_tx))); for (unsigned int j = 0; j(v.mv_data), v.mv_size); if (!parse_and_validate_tx_from_blob(bd, tx)) throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db")); - add_transaction(null_hash, std::make_pair(std::move(tx), bd), &b.tx_hashes[j]); + add_transaction(null, std::make_pair(std::move(tx), bd), &b.tx_hashes[j]); result = mdb_cursor_del(c_txs, 0); if (result) throw0(DB_ERROR(lmdb_error("Failed to get record from txs: ", result).c_str())); @@ -6016,8 +6016,8 @@ void BlockchainLMDB::migrate_5_6() auto const &unaligned = unaligned_signatures[i]; service_nodes::quorum_signature aligned = {}; aligned.voter_index = unaligned.voter_index; - memcpy(aligned.signature.c.data, unaligned.signature.c, sizeof(aligned.signature.c)); - memcpy(aligned.signature.r.data, unaligned.signature.r, sizeof(aligned.signature.r)); + memcpy(aligned.signature.c(), unaligned.signature.c, sizeof(unaligned.signature.c)); + memcpy(aligned.signature.r(), unaligned.signature.r, sizeof(unaligned.signature.r)); checkpoint.signatures.push_back(aligned); } } diff --git a/src/blockchain_db/sqlite/db_sqlite.cpp b/src/blockchain_db/sqlite/db_sqlite.cpp index 9b4af09ac..a4775ebdf 100644 --- a/src/blockchain_db/sqlite/db_sqlite.cpp +++ b/src/blockchain_db/sqlite/db_sqlite.cpp @@ -373,7 +373,7 @@ namespace cryptonote { if (uint64_t tx_fees = block_reward - service_node_reward; tx_fees > 0 && block.service_node_winner_key // "service_node_winner_key" tracks the pulse winner; 0 if a mined block - && crypto_core_ed25519_is_valid_point(reinterpret_cast(block.service_node_winner_key.data)) + && crypto_core_ed25519_is_valid_point(block.service_node_winner_key.data()) ) { if (auto service_node_winner = service_nodes_state.service_nodes_infos.find(block.service_node_winner_key); diff --git a/src/blockchain_utilities/blockchain_ancestry.cpp b/src/blockchain_utilities/blockchain_ancestry.cpp index cc0f5c199..cbfe8b29b 100644 --- a/src/blockchain_utilities/blockchain_ancestry.cpp +++ b/src/blockchain_utilities/blockchain_ancestry.cpp @@ -30,6 +30,7 @@ #define __STDC_FORMAT_MACROS // NOTE(oxen): Explicitly define the SCNu64 macro on Mingw #endif +#include #include #include #include @@ -417,7 +418,7 @@ int main(int argc, char* argv[]) std::cerr << "Only one of --txid, --height, --output can be given" << std::endl; return 1; } - crypto::hash opt_txid = crypto::null_hash; + crypto::hash opt_txid{}; uint64_t output_amount = 0, output_offset = 0; if (!opt_txid_string.empty()) { diff --git a/src/blockchain_utilities/blockchain_depth.cpp b/src/blockchain_utilities/blockchain_depth.cpp index f7fa2e051..ceab8055d 100644 --- a/src/blockchain_utilities/blockchain_depth.cpp +++ b/src/blockchain_utilities/blockchain_depth.cpp @@ -111,7 +111,7 @@ int main(int argc, char* argv[]) std::cerr << "txid and height cannot be given at the same time" << std::endl; return 1; } - crypto::hash opt_txid = crypto::null_hash; + crypto::hash opt_txid{}; if (!opt_txid_string.empty()) { if (!tools::hex_to_type(opt_txid_string, opt_txid)) diff --git a/src/blockchain_utilities/blockchain_stats.cpp b/src/blockchain_utilities/blockchain_stats.cpp index 00e44e4ca..bea7b749d 100644 --- a/src/blockchain_utilities/blockchain_stats.cpp +++ b/src/blockchain_utilities/blockchain_stats.cpp @@ -262,9 +262,9 @@ skip: currsz += bd.size(); for (const auto& tx_id : blk.tx_hashes) { - if (tx_id == crypto::null_hash) + if (!tx_id) { - throw std::runtime_error("Aborting: tx == null_hash"); + throw std::runtime_error("Aborting: null txid"); } if (!db->get_pruned_tx_blob(tx_id, bd)) { diff --git a/src/blockchain_utilities/blocksdat_file.cpp b/src/blockchain_utilities/blocksdat_file.cpp index 294a81465..9d8161f9e 100644 --- a/src/blockchain_utilities/blocksdat_file.cpp +++ b/src/blockchain_utilities/blocksdat_file.cpp @@ -106,8 +106,7 @@ void BlocksdatFile::write_block(const crypto::hash& block_hash) crypto::cn_fast_hash(m_hashes.data(), HASH_OF_HASHES_STEP * sizeof(crypto::hash), hash); memmove(m_hashes.data(), m_hashes.data() + HASH_OF_HASHES_STEP, (m_hashes.size() - HASH_OF_HASHES_STEP) * sizeof(crypto::hash)); m_hashes.resize(m_hashes.size() - HASH_OF_HASHES_STEP); - const std::string data(hash.data, sizeof(hash)); - *m_raw_data_file << data; + m_raw_data_file->write(reinterpret_cast(hash.data()), hash.size()); } } diff --git a/src/blockchain_utilities/bootstrap_file.cpp b/src/blockchain_utilities/bootstrap_file.cpp index 2ec128aa2..e821a0595 100644 --- a/src/blockchain_utilities/bootstrap_file.cpp +++ b/src/blockchain_utilities/bootstrap_file.cpp @@ -221,9 +221,9 @@ void BootstrapFile::write_block(block& block) // now add all regular transactions for (const auto& tx_id : block.tx_hashes) { - if (tx_id == crypto::null_hash) + if (!tx_id) { - throw std::runtime_error("Aborting: tx == null_hash"); + throw std::runtime_error("Aborting: null txid"); } transaction tx = m_blockchain_storage->get_db().get_tx(tx_id); diff --git a/src/checkpoints/checkpoints.cpp b/src/checkpoints/checkpoints.cpp index 3af900c9a..1aa99d4c7 100644 --- a/src/checkpoints/checkpoints.cpp +++ b/src/checkpoints/checkpoints.cpp @@ -76,7 +76,7 @@ namespace cryptonote crypto::hash get_newest_hardcoded_checkpoint(cryptonote::network_type nettype, uint64_t *height) { - crypto::hash result = crypto::null_hash; + crypto::hash result{}; *height = 0; if (nettype != network_type::MAINNET && nettype != network_type::TESTNET) return result; @@ -129,7 +129,7 @@ namespace cryptonote //--------------------------------------------------------------------------- bool checkpoints::add_checkpoint(uint64_t height, const std::string& hash_str) { - crypto::hash h = crypto::null_hash; + crypto::hash h{}; bool r = tools::hex_to_type(hash_str, h); CHECK_AND_ASSERT_MES(r, false, "Failed to parse checkpoint hash string into binary representation!"); diff --git a/src/common/sha256sum.cpp b/src/common/sha256sum.cpp index 6b77a70a3..3b2b2b604 100644 --- a/src/common/sha256sum.cpp +++ b/src/common/sha256sum.cpp @@ -10,7 +10,7 @@ namespace tools { bool sha256sum_str(std::string_view data, crypto::hash &hash) { crypto_hash_sha256( - reinterpret_cast(hash.data), + hash.data(), reinterpret_cast(data.data()), data.size()); return true; @@ -42,7 +42,7 @@ namespace tools { size_left -= read_size; } f.close(); - crypto_hash_sha256_final(&st, reinterpret_cast(hash.data)); + crypto_hash_sha256_final(&st, hash.data()); return true; } diff --git a/src/common/util.h b/src/common/util.h index 1a3a3a706..8e16a5cd1 100644 --- a/src/common/util.h +++ b/src/common/util.h @@ -90,8 +90,23 @@ namespace tools dest += sizeof(T); } + struct crypto_bytes_base_helper { + template + static std::true_type check(crypto::bytes*); + static std::false_type check(...); + }; + template + constexpr bool is_crypto_bytes_derived = decltype(crypto_bytes_base_helper::check((T*) nullptr))::value; + + // Copy the data out of a crypto::bytes-derived type. + template , int> = 0> + void memcpy_one(char*& dest, const T& t) { + std::memcpy(dest, t.data(), t.size()); + dest += t.size(); + } + // Copy a class byte-for-byte (but only if it is standard layout and has byte alignment) - template ::value, int> = 0> + template ::value && !is_crypto_bytes_derived, int> = 0> void memcpy_one(char*& dest, const T& t) { // We don't *actually* require byte alignment here but it's quite possibly an error (i.e. // passing in a type containing integer members) so disallow it. @@ -106,6 +121,13 @@ namespace tools for (const T &t : arr) memcpy_one(dest, t); } + + template + constexpr size_t memcpy_size = sizeof(T); + + template + inline constexpr size_t memcpy_size>> + = T::size(); } // Does a memcpy of one or more values into a char array; for any given values that are basic @@ -118,7 +140,7 @@ namespace tools // you have a contained type with a larger alignment, which is probably an integer. template auto memcpy_le(const T &...t) { - std::array r; + std::array)> r; char* dest = r.data(); (..., detail::memcpy_one(dest, t)); return r; diff --git a/src/crypto/CMakeLists.txt b/src/crypto/CMakeLists.txt index 215dcc390..8068450c5 100644 --- a/src/crypto/CMakeLists.txt +++ b/src/crypto/CMakeLists.txt @@ -31,6 +31,7 @@ add_library(cncrypto aesb.c blake256.c chacha.c + chacha.cpp crypto-ops-data.c crypto-ops.c crypto.cpp @@ -40,6 +41,7 @@ add_library(cncrypto hash-extra-jh.c hash-extra-skein.c hash.c + hash.cpp hmac-keccak.c jh.c keccak.c diff --git a/src/crypto/base.h b/src/crypto/base.h new file mode 100644 index 000000000..07fb1986a --- /dev/null +++ b/src/crypto/base.h @@ -0,0 +1,82 @@ +#pragma once + +#include "common/format.h" +#include "common/formattable.h" +#include "common/hex.h" +#include +#include + + +namespace crypto { + + /// constexpr null (all-0) value for various crypto types; use as `crypto::null`. + template && std::is_default_constructible_v>> + constexpr T null{}; + + // Base type for fixed-byte quantities (points, scalars, signatures, hashes). The bool controls + // whether the type should have ==, !=, std::hash, and to_hex_string. + template + struct alignas(size_t) bytes { + std::array data_; + + unsigned char* data() { return data_.data(); } + const unsigned char* data() const { return data_.data(); } + static constexpr size_t size() { return Bytes; } + auto begin() { return data_.begin(); } + auto begin() const { return data_.begin(); } + auto cbegin() const { return data_.cbegin(); } + auto end() { return data_.end(); } + auto end() const { return data_.end(); } + auto cend() const { return data_.cend(); } + + // Set the bytes to all 0's + void zero() { data_.fill(0); } + + unsigned char& operator[](size_t i) { return data_[i]; } + const unsigned char& operator[](size_t i) const { return data_[i]; } + + static constexpr bool compare_hash_hex = MemcmpHashHex; + }; + + template + constexpr bool has_compare_hash_hex = false; + template + inline constexpr bool has_compare_hash_hex> = true; + + template + constexpr bool are_comparable_v = false; + template + inline constexpr bool are_comparable_v && has_compare_hash_hex>> = true; + + template , int> = 0> + bool operator==(const L& left, const R& right) { + return left.data_ == right.data_; + } + template , int> = 0> + bool operator!=(const L& left, const R& right) { + return left.data_ != right.data_; + } + template , int> = 0> + bool operator<(const L& left, const R& right) { + return left.data_ < right.data_; + } + + template >> + std::string to_hex_string(const T& val) { return "<{}>"_format(tools::type_to_hex(val)); } + + template + struct raw_hasher { + static_assert(T::compare_hash_hex); + static_assert(std::is_standard_layout_v); + static_assert(sizeof(T) >= sizeof(size_t)); + static_assert(alignof(T) >= sizeof(size_t)); + + size_t operator()(const T& val) const { + return *reinterpret_cast(val.data()); + } + }; +} + +template +inline constexpr bool formattable::via_to_hex_string>> + = true; diff --git a/src/crypto/chacha.cpp b/src/crypto/chacha.cpp new file mode 100644 index 000000000..5ce23cf32 --- /dev/null +++ b/src/crypto/chacha.cpp @@ -0,0 +1,43 @@ +#include "chacha.h" + +#include "hash.h" +#include "cn_heavy_hash.hpp" + + +namespace crypto { + + static_assert(sizeof(chacha_key) == CHACHA_KEY_SIZE && sizeof(chacha_iv) == CHACHA_IV_SIZE, "Invalid structure size"); + + void chacha8(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher) { + chacha8(data, length, key.data(), reinterpret_cast(&iv), cipher); + } + + void chacha20(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher) { + chacha20(data, length, key.data(), reinterpret_cast(&iv), cipher); + } + + void generate_chacha_key(std::string password, chacha_key& key, uint64_t kdf_rounds) { + return generate_chacha_key(password.data(), password.size(), key, kdf_rounds); + } + + void generate_chacha_key(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds) { + static_assert(sizeof(chacha_key) <= hash::size(), "Size of hash must be at least that of chacha_key"); + epee::mlocked> pwd_hash; + static thread_local cn_heavy_hash_v1 ctx; + ctx.hash(data, size, pwd_hash.data()); + for (uint64_t n = 1; n < kdf_rounds; ++n) + ctx.hash(pwd_hash.data(), pwd_hash.size(), pwd_hash.data()); + memcpy(&unwrap(unwrap(key)), pwd_hash.data(), sizeof(key)); + } + + void generate_chacha_key_prehashed(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds) { + static_assert(sizeof(chacha_key) <= hash::size(), "Size of hash must be at least that of chacha_key"); + epee::mlocked> pwd_hash; + static thread_local cn_heavy_hash_v1 ctx; + ctx.hash(data, size, pwd_hash.data(), true); + for (uint64_t n = 1; n < kdf_rounds; ++n) + ctx.hash(pwd_hash.data(), pwd_hash.size(), pwd_hash.data()); + memcpy(&unwrap(unwrap(key)), pwd_hash.data(), sizeof(key)); + } + +} diff --git a/src/crypto/chacha.h b/src/crypto/chacha.h index f24be3dcb..533e27080 100644 --- a/src/crypto/chacha.h +++ b/src/crypto/chacha.h @@ -36,21 +36,20 @@ #define CHACHA_KEY_SIZE 32 #define CHACHA_IV_SIZE 8 -#if defined(__cplusplus) -#include +#ifdef __cplusplus +extern "C" { +#endif + +void chacha8(const void* data, size_t length, const uint8_t* key, const uint8_t* iv, char* cipher); +void chacha20(const void* data, size_t length, const uint8_t* key, const uint8_t* iv, char* cipher); + +#ifdef __cplusplus +} #include "epee/memwipe.h" #include "epee/mlocker.h" -#include "hash.h" -#include "cn_heavy_hash.hpp" namespace crypto { - extern "C" { -#endif - void chacha8(const void* data, size_t length, const uint8_t* key, const uint8_t* iv, char* cipher); - void chacha20(const void* data, size_t length, const uint8_t* key, const uint8_t* iv, char* cipher); -#if defined(__cplusplus) - } using chacha_key = epee::mlocked>; @@ -58,39 +57,15 @@ namespace crypto { uint8_t data[CHACHA_IV_SIZE]; }; - static_assert(sizeof(chacha_key) == CHACHA_KEY_SIZE && sizeof(chacha_iv) == CHACHA_IV_SIZE, "Invalid structure size"); + using ::chacha8; + using ::chacha20; - inline void chacha8(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher) { - chacha8(data, length, key.data(), reinterpret_cast(&iv), cipher); - } + void chacha8(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher); + void chacha20(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher); - inline void chacha20(const void* data, std::size_t length, const chacha_key& key, const chacha_iv& iv, char* cipher) { - chacha20(data, length, key.data(), reinterpret_cast(&iv), cipher); - } - - inline void generate_chacha_key(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds) { - static_assert(sizeof(chacha_key) <= sizeof(hash), "Size of hash must be at least that of chacha_key"); - epee::mlocked> pwd_hash; - static thread_local cn_heavy_hash_v1 ctx; - ctx.hash(data, size, pwd_hash.data()); - for (uint64_t n = 1; n < kdf_rounds; ++n) - ctx.hash(pwd_hash.data(), pwd_hash.size(), pwd_hash.data()); - memcpy(&unwrap(unwrap(key)), pwd_hash.data(), sizeof(key)); - } - - inline void generate_chacha_key_prehashed(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds) { - static_assert(sizeof(chacha_key) <= sizeof(hash), "Size of hash must be at least that of chacha_key"); - epee::mlocked> pwd_hash; - static thread_local cn_heavy_hash_v1 ctx; - ctx.hash(data, size, pwd_hash.data(), true); - for (uint64_t n = 1; n < kdf_rounds; ++n) - ctx.hash(pwd_hash.data(), pwd_hash.size(), pwd_hash.data()); - memcpy(&unwrap(unwrap(key)), pwd_hash.data(), sizeof(key)); - } - - inline void generate_chacha_key(std::string password, chacha_key& key, uint64_t kdf_rounds) { - return generate_chacha_key(password.data(), password.size(), key, kdf_rounds); - } + void generate_chacha_key(std::string password, chacha_key& key, uint64_t kdf_rounds); + void generate_chacha_key(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds); + void generate_chacha_key_prehashed(const void *data, size_t size, chacha_key& key, uint64_t kdf_rounds); } #endif diff --git a/src/crypto/cn_monero_slow_hash.c b/src/crypto/cn_monero_slow_hash.c index 8c7fc71a8..b91611081 100644 --- a/src/crypto/cn_monero_slow_hash.c +++ b/src/crypto/cn_monero_slow_hash.c @@ -695,7 +695,7 @@ void monero_hash_free_state(void) * @param length the length in bytes of the data * @param hash a pointer to a buffer in which the final 256 bit hash will be stored */ -void cn_monero_hash(const void *data, size_t length, char *hash, int variant, int prehashed) +void cn_monero_hash(const void *data, size_t length, unsigned char *hash, int variant, int prehashed) { RDATA_ALIGN16 uint8_t expandedKey[AES_EXPANDED_KEY_SIZE]; /* These buffers are aligned to use later with SSE functions */ @@ -1061,7 +1061,7 @@ STATIC INLINE void aligned_free(void *ptr) } #endif /* FORCE_USE_HEAP */ -void cn_monero_hash(const void *data, size_t length, char *hash, int variant, int prehashed) +void cn_monero_hash(const void *data, size_t length, unsigned char *hash, int variant, int prehashed) { RDATA_ALIGN16 uint8_t expandedKey[240]; @@ -1276,7 +1276,7 @@ STATIC INLINE void xor_blocks(uint8_t* a, const uint8_t* b) U64(a)[1] ^= U64(b)[1]; } -void cn_monero_hash(const void *data, size_t length, char *hash, int variant, int prehashed) +void cn_monero_hash(const void *data, size_t length, unsigned char *hash, int variant, int prehashed) { uint8_t text[INIT_SIZE_BYTE]; uint8_t a[AES_BLOCK_SIZE]; @@ -1468,7 +1468,7 @@ union cn_monero_hash_state { }; #pragma pack(pop) -void cn_monero_hash(const void *data, size_t length, char *hash, int variant, int prehashed) { +void cn_monero_hash(const void *data, size_t length, unsigned char *hash, int variant, int prehashed) { #ifndef FORCE_USE_HEAP uint8_t long_state[MEMORY]; #else diff --git a/src/crypto/cn_turtle_hash-amd64.inl b/src/crypto/cn_turtle_hash-amd64.inl index dd7192425..0f56f4d97 100644 --- a/src/crypto/cn_turtle_hash-amd64.inl +++ b/src/crypto/cn_turtle_hash-amd64.inl @@ -408,7 +408,7 @@ void slow_hash_free_state(uint32_t page_size) * @param length the length in bytes of the data * @param hash a pointer to a buffer in which the final 256 bit hash will be stored */ -void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) +void cn_turtle_hash(const void *data, size_t length, unsigned char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) { uint32_t TOTALBLOCKS = (CN_TURTLE_PAGE_SIZE / AES_BLOCK_SIZE); uint32_t init_rounds = (scratchpad / INIT_SIZE_BYTE); @@ -428,7 +428,7 @@ void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int size_t i, j; uint64_t *p = NULL; - static void (*const extra_hashes[4])(const void *, size_t, char *) = + static void (*const extra_hashes[4])(const void *, size_t, unsigned char *) = { hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein }; diff --git a/src/crypto/cn_turtle_hash-arm.inl b/src/crypto/cn_turtle_hash-arm.inl index 1480c4e3e..fcdecad38 100644 --- a/src/crypto/cn_turtle_hash-arm.inl +++ b/src/crypto/cn_turtle_hash-arm.inl @@ -217,7 +217,7 @@ STATIC INLINE void aligned_free(void *ptr) } #endif /* FORCE_USE_HEAP */ -void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) +void cn_turtle_hash(const void *data, size_t length, unsigned char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) { uint32_t TOTALBLOCKS = (CN_TURTLE_PAGE_SIZE / AES_BLOCK_SIZE); uint32_t init_rounds = (scratchpad / INIT_SIZE_BYTE); @@ -244,7 +244,7 @@ void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int size_t i, j; uint64_t *p = NULL; - static void (*const extra_hashes[4])(const void *, size_t, char *) = + static void (*const extra_hashes[4])(const void *, size_t, unsigned char *) = { hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein }; @@ -438,7 +438,7 @@ STATIC INLINE void xor_blocks(uint8_t* a, const uint8_t* b) U64(a)[1] ^= U64(b)[1]; } -void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) +void cn_turtle_hash(const void *data, size_t length, unsigned char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) { fprintf(stderr, "%s:%d OMG", __FILE__, __LINE__); uint32_t init_rounds = (scratchpad / INIT_SIZE_BYTE); @@ -458,7 +458,7 @@ void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int size_t i, j; uint8_t *p = NULL; - static void (*const extra_hashes[4])(const void *, size_t, char *) = + static void (*const extra_hashes[4])(const void *, size_t, unsigned char *) = { hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein }; diff --git a/src/crypto/cn_turtle_hash-portable.inl b/src/crypto/cn_turtle_hash-portable.inl index 618ba3b1d..64ac8b7d5 100644 --- a/src/crypto/cn_turtle_hash-portable.inl +++ b/src/crypto/cn_turtle_hash-portable.inl @@ -1,6 +1,6 @@ // Portable implementation as a fallback -static void (*const extra_hashes[4])(const void *, size_t, char *) = { +static void (*const extra_hashes[4])(const void *, size_t, unsigned char *) = { hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein }; @@ -72,7 +72,7 @@ union cn_turtle_hash_state { }; #pragma pack(pop) -void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) +void cn_turtle_hash(const void *data, size_t length, unsigned char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations) { uint32_t init_rounds = (scratchpad / INIT_SIZE_BYTE); uint32_t aes_rounds = (iterations / 2); diff --git a/src/crypto/crypto.cpp b/src/crypto/crypto.cpp index d802cd0f9..444707928 100644 --- a/src/crypto/crypto.cpp +++ b/src/crypto/crypto.cpp @@ -38,11 +38,17 @@ #include #include +#include +#include +#include + #include "common/varint.h" #include "epee/warnings.h" #include "crypto.h" extern "C" { #include "keccak.h" +#include "crypto-ops.h" +#include "random.h" } #include "hash.h" @@ -60,43 +66,26 @@ namespace { namespace crypto { - using std::abort; - using std::int32_t; - using std::int64_t; - using std::size_t; - using std::uint32_t; - using std::uint64_t; + static_assert(sizeof(bytes<32>) == 32 && std::has_unique_object_representations_v>); + static_assert(sizeof(bytes<64>) == 64 && std::has_unique_object_representations_v>); + static_assert(sizeof(ec_point) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(ec_scalar) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(public_key) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(secret_key_) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(secret_key) == sizeof(secret_key_)); + static_assert(sizeof(key_derivation) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(key_image) == 32 && std::has_unique_object_representations_v); + static_assert(sizeof(signature) == 64 && std::has_unique_object_representations_v); + static_assert(sizeof(ed25519_public_key) == crypto_sign_ed25519_PUBLICKEYBYTES && std::has_unique_object_representations_v); + static_assert(sizeof(ed25519_secret_key_) == crypto_sign_ed25519_SECRETKEYBYTES && std::has_unique_object_representations_v); + static_assert(sizeof(ed25519_signature) == 64 && std::has_unique_object_representations_v); - extern "C" { -#include "crypto-ops.h" -#include "random.h" + + bool ec_scalar::operator==(const ec_scalar& x) const { + return crypto_verify_32(data(), x.data()) == 0; } - - // These nasty dirty hacks are unspeakable disgusting. This is only here because all of these - // have a `.data` element, but it is a `char` instead of an `unsigned char`. So rather than - // change it to `unsigned char`, the author decided that he should overload `&` to do a - // reinterpret_cast. WTF. - // - // TODO: fix this garbage by making the ec_ types use unsigned char instead of char. - - // EW! - static inline unsigned char *operator &(ec_point &point) { - return &reinterpret_cast(point); - } - - // EW! - static inline const unsigned char *operator &(const ec_point &point) { - return &reinterpret_cast(point); - } - - // EW! - static inline unsigned char *operator &(ec_scalar &scalar) { - return &reinterpret_cast(scalar); - } - - // EW! - static inline const unsigned char *operator &(const ec_scalar &scalar) { - return &reinterpret_cast(scalar); + ec_scalar::operator bool() const { + return !sodium_is_zero(data(), size()); } static std::mutex random_mutex; @@ -144,7 +133,7 @@ namespace crypto { } /* generate a random ]0..L[ scalar */ void random_scalar(ec_scalar &res) { - random_scalar(reinterpret_cast(res.data)); + random_scalar(res.data()); } ec_scalar random_scalar() { @@ -154,8 +143,14 @@ namespace crypto { } void hash_to_scalar(const void *data, size_t length, ec_scalar &res) { - cn_fast_hash(data, length, reinterpret_cast(res)); - sc_reduce32(&res); + cn_fast_hash(data, length, res.data()); + sc_reduce32(res.data()); + } + + ec_scalar hash_to_scalar(const void *data, size_t length) { + ec_scalar x; + hash_to_scalar(data, length, x); + return x; } /* @@ -175,26 +170,26 @@ namespace crypto { random_scalar(rng); } sec = rng; - sc_reduce32(&unwrap(sec)); // reduce in case second round of keys (sendkeys) + sc_reduce32(sec.data()); // reduce in case second round of keys (sendkeys) - ge_scalarmult_base(&point, &unwrap(sec)); - ge_p3_tobytes(&pub, &point); + ge_scalarmult_base(&point, sec.data()); + ge_p3_tobytes(pub.data(), &point); return rng; } bool check_key(const public_key &key) { ge_p3 point; - return ge_frombytes_vartime(&point, &key) == 0; + return ge_frombytes_vartime(&point, key.data()) == 0; } bool secret_key_to_public_key(const secret_key &sec, public_key &pub) { ge_p3 point; - if (sc_check(&unwrap(sec)) != 0) { + if (sc_check(sec.data()) != 0) { return false; } - ge_scalarmult_base(&point, &unwrap(sec)); - ge_p3_tobytes(&pub, &point); + ge_scalarmult_base(&point, sec.data()); + ge_p3_tobytes(pub.data(), &point); return true; } @@ -209,14 +204,14 @@ namespace crypto { ge_p3 point; ge_p2 point2; ge_p1p1 point3; - assert(sc_check(&key2) == 0); - if (ge_frombytes_vartime(&point, &key1) != 0) { + assert(sc_check(key2.data()) == 0); + if (ge_frombytes_vartime(&point, key1.data()) != 0) { return false; } - ge_scalarmult(&point2, &unwrap(key2), &point); + ge_scalarmult(&point2, key2.data(), &point); ge_mul8(&point3, &point2); ge_p1p1_to_p2(&point2, &point3); - ge_tobytes(&derivation, &point2); + ge_tobytes(derivation.data(), &point2); return true; } @@ -228,7 +223,7 @@ namespace crypto { char *end = buf.output_index; buf.derivation = derivation; tools::write_varint(end, output_index); - hash_to_scalar(&buf, end - reinterpret_cast(&buf), res); + res = hash_to_scalar(&buf, end - reinterpret_cast(&buf)); } bool derive_public_key(const key_derivation &derivation, size_t output_index, @@ -239,24 +234,24 @@ namespace crypto { ge_cached point3; ge_p1p1 point4; ge_p2 point5; - if (ge_frombytes_vartime(&point1, &base) != 0) { + if (ge_frombytes_vartime(&point1, base.data()) != 0) { return false; } derivation_to_scalar(derivation, output_index, scalar); - ge_scalarmult_base(&point2, &scalar); + ge_scalarmult_base(&point2, scalar.data()); ge_p3_to_cached(&point3, &point2); ge_add(&point4, &point1, &point3); ge_p1p1_to_p2(&point5, &point4); - ge_tobytes(&derived_key, &point5); + ge_tobytes(derived_key.data(), &point5); return true; } void derive_secret_key(const key_derivation &derivation, size_t output_index, const secret_key &base, secret_key &derived_key) { ec_scalar scalar; - assert(sc_check(&base) == 0); + assert(sc_check(base.data()) == 0); derivation_to_scalar(derivation, output_index, scalar); - sc_add(&unwrap(derived_key), &unwrap(base), &scalar); + sc_add(derived_key.data(), base.data(), scalar.data()); } bool derive_subaddress_public_key(const public_key &out_key, const key_derivation &derivation, std::size_t output_index, public_key &derived_key) { @@ -266,15 +261,15 @@ namespace crypto { ge_cached point3; ge_p1p1 point4; ge_p2 point5; - if (ge_frombytes_vartime(&point1, &out_key) != 0) { + if (ge_frombytes_vartime(&point1, out_key.data()) != 0) { return false; } derivation_to_scalar(derivation, output_index, scalar); - ge_scalarmult_base(&point2, &scalar); + ge_scalarmult_base(&point2, scalar.data()); ge_p3_to_cached(&point3, &point2); ge_sub(&point4, &point1, &point3); ge_p1p1_to_p2(&point5, &point4); - ge_tobytes(&derived_key, &point5); + ge_tobytes(derived_key.data(), &point5); return true; } @@ -299,56 +294,64 @@ namespace crypto { { ge_p3 t; public_key t2; - assert(sc_check(&sec) == 0); - ge_scalarmult_base(&t, &sec); - ge_p3_tobytes(&t2, &t); + assert(sc_check(sec.data()) == 0); + ge_scalarmult_base(&t, sec.data()); + ge_p3_tobytes(t2.data(), &t); assert(pub == t2); } #endif buf.h = prefix_hash; buf.key = pub; signature sig; - try_again: - random_scalar(k); - ge_scalarmult_base(&tmp3, &k); - ge_p3_tobytes(&buf.comm, &tmp3); - hash_to_scalar(&buf, sizeof(s_comm), sig.c); - if (!sc_isnonzero((const unsigned char*)sig.c.data)) - goto try_again; - sc_mulsub(&sig.r, &sig.c, &unwrap(sec), &k); - if (!sc_isnonzero((const unsigned char*)sig.r.data)) - goto try_again; - memwipe(&k, sizeof(k)); - return sig; + + while (true) + { + random_scalar(k); + ge_scalarmult_base(&tmp3, k.data()); + ge_p3_tobytes(buf.comm.data(), &tmp3); + sig.c(hash_to_scalar(&buf, sizeof(s_comm))); + if (!sc_isnonzero(sig.c())) + continue; + sc_mulsub(sig.r(), sig.c(), sec.data(), k.data()); + if (!sc_isnonzero(sig.r())) + continue; + memwipe(k.data(), k.size()); + return sig; + } } void generate_signature(const hash &prefix_hash, const public_key &pub, const secret_key &sec, signature &sig) { sig = generate_signature(prefix_hash, pub, sec); } - static constexpr ec_point infinity = {{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; + static constexpr ec_point get_infinity() { + ec_point inf{}; + inf.data_[0] = 1; + return inf; + } + constexpr ec_point infinity = get_infinity(); + bool check_signature(const hash &prefix_hash, const public_key &pub, const signature &sig) { ge_p2 tmp2; ge_p3 tmp3; - ec_scalar c; s_comm buf; assert(check_key(pub)); buf.h = prefix_hash; buf.key = pub; - if (ge_frombytes_vartime(&tmp3, &pub) != 0) { + if (ge_frombytes_vartime(&tmp3, pub.data()) != 0) { return false; } - if (sc_check(&sig.c) != 0 || sc_check(&sig.r) != 0 || !sc_isnonzero(&sig.c)) { + if (sc_check(sig.c()) != 0 || sc_check(sig.r()) != 0 || !sc_isnonzero(sig.c())) { return false; } - ge_double_scalarmult_base_vartime(&tmp2, &sig.c, &tmp3, &sig.r); // tmp2 = sig.c A + sig.r G - ge_tobytes(&buf.comm, &tmp2); - if (memcmp(&buf.comm, &infinity, 32) == 0) + ge_double_scalarmult_base_vartime(&tmp2, sig.c(), &tmp3, sig.r()); // tmp2 = sig.c A + sig.r G + ge_tobytes(buf.comm.data(), &tmp2); + if (memcmp(buf.comm.data(), infinity.data(), 32) == 0) return false; - hash_to_scalar(&buf, sizeof(s_comm), c); - sc_sub(&c, &c, &sig.c); - return sc_isnonzero(&c) == 0; + ec_scalar c = hash_to_scalar(&buf, sizeof(s_comm)); + sc_sub(c.data(), c.data(), sig.c()); + return sc_isnonzero(c.data()) == 0; } void generate_tx_proof(const hash &prefix_hash, const public_key &R, const public_key &A, const std::optional &B, const public_key &D, const secret_key &r, signature &sig) { @@ -357,33 +360,33 @@ namespace crypto { ge_p3 A_p3; ge_p3 B_p3; ge_p3 D_p3; - if (ge_frombytes_vartime(&R_p3, &R) != 0) throw std::runtime_error("tx pubkey is invalid"); - if (ge_frombytes_vartime(&A_p3, &A) != 0) throw std::runtime_error("recipient view pubkey is invalid"); - if (B && ge_frombytes_vartime(&B_p3, &*B) != 0) throw std::runtime_error("recipient spend pubkey is invalid"); - if (ge_frombytes_vartime(&D_p3, &D) != 0) throw std::runtime_error("key derivation is invalid"); + if (ge_frombytes_vartime(&R_p3, R.data()) != 0) throw std::runtime_error("tx pubkey is invalid"); + if (ge_frombytes_vartime(&A_p3, A.data()) != 0) throw std::runtime_error("recipient view pubkey is invalid"); + if (B && ge_frombytes_vartime(&B_p3, B->data()) != 0) throw std::runtime_error("recipient spend pubkey is invalid"); + if (ge_frombytes_vartime(&D_p3, D.data()) != 0) throw std::runtime_error("key derivation is invalid"); #if !defined(NDEBUG) { - assert(sc_check(&r) == 0); + assert(sc_check(r.data()) == 0); // check R == r*G or R == r*B public_key dbg_R; if (B) { ge_p2 dbg_R_p2; - ge_scalarmult(&dbg_R_p2, &r, &B_p3); - ge_tobytes(&dbg_R, &dbg_R_p2); + ge_scalarmult(&dbg_R_p2, r.data(), &B_p3); + ge_tobytes(dbg_R.data(), &dbg_R_p2); } else { ge_p3 dbg_R_p3; - ge_scalarmult_base(&dbg_R_p3, &r); - ge_p3_tobytes(&dbg_R, &dbg_R_p3); + ge_scalarmult_base(&dbg_R_p3, r.data()); + ge_p3_tobytes(dbg_R.data(), &dbg_R_p3); } assert(R == dbg_R); // check D == r*A ge_p2 dbg_D_p2; - ge_scalarmult(&dbg_D_p2, &r, &A_p3); + ge_scalarmult(&dbg_D_p2, r.data(), &A_p3); public_key dbg_D; - ge_tobytes(&dbg_D, &dbg_D_p2); + ge_tobytes(dbg_D.data(), &dbg_D_p2); assert(D == dbg_D); } #endif @@ -399,29 +402,29 @@ namespace crypto { { // compute X = k*B ge_p2 X_p2; - ge_scalarmult(&X_p2, &k, &B_p3); - ge_tobytes(&buf.X, &X_p2); + ge_scalarmult(&X_p2, k.data(), &B_p3); + ge_tobytes(buf.X.data(), &X_p2); } else { // compute X = k*G ge_p3 X_p3; - ge_scalarmult_base(&X_p3, &k); - ge_p3_tobytes(&buf.X, &X_p3); + ge_scalarmult_base(&X_p3, k.data()); + ge_p3_tobytes(buf.X.data(), &X_p3); } // compute Y = k*A ge_p2 Y_p2; - ge_scalarmult(&Y_p2, &k, &A_p3); - ge_tobytes(&buf.Y, &Y_p2); + ge_scalarmult(&Y_p2, k.data(), &A_p3); + ge_tobytes(buf.Y.data(), &Y_p2); // sig.c = Hs(Msg || D || X || Y) - hash_to_scalar(&buf, sizeof(buf), sig.c); + sig.c(hash_to_scalar(&buf, sizeof(buf))); // sig.r = k - sig.c*r - sc_mulsub(&sig.r, &sig.c, &unwrap(r), &k); + sc_mulsub(sig.r(), sig.c(), r.data(), k.data()); - memwipe(&k, sizeof(k)); + memwipe(k.data(), k.size()); } bool check_tx_proof(const hash &prefix_hash, const public_key &R, const public_key &A, const std::optional &B, const public_key &D, const signature &sig) { @@ -430,20 +433,20 @@ namespace crypto { ge_p3 A_p3; ge_p3 B_p3; ge_p3 D_p3; - if (ge_frombytes_vartime(&R_p3, &R) != 0) return false; - if (ge_frombytes_vartime(&A_p3, &A) != 0) return false; - if (B && ge_frombytes_vartime(&B_p3, &*B) != 0) return false; - if (ge_frombytes_vartime(&D_p3, &D) != 0) return false; - if (sc_check(&sig.c) != 0 || sc_check(&sig.r) != 0) return false; + if (ge_frombytes_vartime(&R_p3, R.data()) != 0) return false; + if (ge_frombytes_vartime(&A_p3, A.data()) != 0) return false; + if (B && ge_frombytes_vartime(&B_p3, B->data()) != 0) return false; + if (ge_frombytes_vartime(&D_p3, D.data()) != 0) return false; + if (sc_check(sig.c()) != 0 || sc_check(sig.r()) != 0) return false; // compute sig.c*R ge_p3 cR_p3; { ge_p2 cR_p2; - ge_scalarmult(&cR_p2, &sig.c, &R_p3); + ge_scalarmult(&cR_p2, sig.c(), &R_p3); public_key cR; - ge_tobytes(&cR, &cR_p2); - if (ge_frombytes_vartime(&cR_p3, &cR) != 0) return false; + ge_tobytes(cR.data(), &cR_p2); + if (ge_frombytes_vartime(&cR_p3, cR.data()) != 0) return false; } ge_p1p1 X_p1p1; @@ -451,11 +454,11 @@ namespace crypto { { // compute X = sig.c*R + sig.r*B ge_p2 rB_p2; - ge_scalarmult(&rB_p2, &sig.r, &B_p3); + ge_scalarmult(&rB_p2, sig.r(), &B_p3); public_key rB; - ge_tobytes(&rB, &rB_p2); + ge_tobytes(rB.data(), &rB_p2); ge_p3 rB_p3; - if (ge_frombytes_vartime(&rB_p3, &rB) != 0) return false; + if (ge_frombytes_vartime(&rB_p3, rB.data()) != 0) return false; ge_cached rB_cached; ge_p3_to_cached(&rB_cached, &rB_p3); ge_add(&X_p1p1, &cR_p3, &rB_cached); @@ -464,7 +467,7 @@ namespace crypto { { // compute X = sig.c*R + sig.r*G ge_p3 rG_p3; - ge_scalarmult_base(&rG_p3, &sig.r); + ge_scalarmult_base(&rG_p3, sig.r()); ge_cached rG_cached; ge_p3_to_cached(&rG_cached, &rG_p3); ge_add(&X_p1p1, &cR_p3, &rG_cached); @@ -474,21 +477,21 @@ namespace crypto { // compute sig.c*D ge_p2 cD_p2; - ge_scalarmult(&cD_p2, &sig.c, &D_p3); + ge_scalarmult(&cD_p2, sig.c(), &D_p3); // compute sig.r*A ge_p2 rA_p2; - ge_scalarmult(&rA_p2, &sig.r, &A_p3); + ge_scalarmult(&rA_p2, sig.r(), &A_p3); // compute Y = sig.c*D + sig.r*A public_key cD; public_key rA; - ge_tobytes(&cD, &cD_p2); - ge_tobytes(&rA, &rA_p2); + ge_tobytes(cD.data(), &cD_p2); + ge_tobytes(rA.data(), &rA_p2); ge_p3 cD_p3; ge_p3 rA_p3; - if (ge_frombytes_vartime(&cD_p3, &cD) != 0) return false; - if (ge_frombytes_vartime(&rA_p3, &rA) != 0) return false; + if (ge_frombytes_vartime(&cD_p3, cD.data()) != 0) return false; + if (ge_frombytes_vartime(&rA_p3, rA.data()) != 0) return false; ge_cached rA_cached; ge_p3_to_cached(&rA_cached, &rA_p3); ge_p1p1 Y_p1p1; @@ -500,14 +503,13 @@ namespace crypto { s_comm_2 buf; buf.msg = prefix_hash; buf.D = D; - ge_tobytes(&buf.X, &X_p2); - ge_tobytes(&buf.Y, &Y_p2); - ec_scalar c2; - hash_to_scalar(&buf, sizeof(s_comm_2), c2); + ge_tobytes(buf.X.data(), &X_p2); + ge_tobytes(buf.Y.data(), &Y_p2); + ec_scalar c2 = hash_to_scalar(&buf, sizeof(s_comm_2)); // test if c2 == sig.c - sc_sub(&c2, &c2, &sig.c); - return sc_isnonzero(&c2) == 0; + sc_sub(c2.data(), c2.data(), sig.c()); + return sc_isnonzero(c2.data()) == 0; } static void hash_to_ec(const public_key &key, ge_p3 &res) { @@ -523,10 +525,10 @@ namespace crypto { void generate_key_image(const public_key &pub, const secret_key &sec, key_image &image) { ge_p3 point; ge_p2 point2; - assert(sc_check(&sec) == 0); + assert(sc_check(sec.data()) == 0); hash_to_ec(pub, point); - ge_scalarmult(&point2, &unwrap(sec), &point); - ge_tobytes(&image, &point2); + ge_scalarmult(&point2, sec.data(), &point); + ge_tobytes(image.data(), &point2); } struct rs_comm { @@ -542,8 +544,8 @@ namespace crypto { static_assert(sizeof(ab[0]) == 64); // Ensure no padding keccak_update(&state, reinterpret_cast(ab.data()), 64*ab.size()); ec_scalar result; - keccak_finish(&state, reinterpret_cast(&result)); - sc_reduce32(&result); + keccak_finish(&state, result.data()); + sc_reduce32(result.data()); return result; }; }; @@ -563,9 +565,9 @@ namespace crypto { ge_p3 t; public_key t2; key_image t3; - assert(sc_check(&sec) == 0); - ge_scalarmult_base(&t, &sec); - ge_p3_tobytes(&t2, &t); + assert(sc_check(sec.data()) == 0); + ge_scalarmult_base(&t, sec.data()); + ge_p3_tobytes(t2.data(), &t); assert(*pubs[sec_index] == t2); generate_key_image(*pubs[sec_index], sec, t3); assert(image == t3); @@ -575,13 +577,12 @@ namespace crypto { } #endif ge_p3 image_unp; // I - if (ge_frombytes_vartime(&image_unp, &image) != 0) { + if (ge_frombytes_vartime(&image_unp, image.data()) != 0) { local_abort("invalid key image"); } ge_dsmp image_pre; ge_dsm_precomp(image_pre, &image_unp); - ec_scalar sum; - sc_0(&sum); // will be sum of cj, j≠s + ec_scalar sum = null; // will be sum of cj, j≠s rs_comm rs{prefix_hash, pubs.size()}; ec_scalar qs; @@ -590,32 +591,32 @@ namespace crypto { ge_p3 tmp3; if (i == sec_index) { // this is the true key image random_scalar(qs); // qs = random - ge_scalarmult_base(&tmp3, &qs); // Ls = qs G - ge_p3_tobytes(&rs.ab[i].first, &tmp3); + ge_scalarmult_base(&tmp3, qs.data()); // Ls = qs G + ge_p3_tobytes(rs.ab[i].first.data(), &tmp3); hash_to_ec(*pubs[i], tmp3); // Hp(Ps) - ge_scalarmult(&tmp2, &qs, &tmp3); // Rs = qs Hp(Ps) - ge_tobytes(&rs.ab[i].second, &tmp2); + ge_scalarmult(&tmp2, qs.data(), &tmp3); // Rs = qs Hp(Ps) + ge_tobytes(rs.ab[i].second.data(), &tmp2); // We don't set ci, ri yet because we first need the sum of all the other cj's/rj's } else { - random_scalar(sig[i].c); // ci = wi = random - random_scalar(sig[i].r); // ri = qi = random - if (ge_frombytes_vartime(&tmp3, &*pubs[i]) != 0) { - memwipe(&qs, sizeof(qs)); + random_scalar(sig[i].c()); // ci = wi = random + random_scalar(sig[i].r()); // ri = qi = random + if (ge_frombytes_vartime(&tmp3, pubs[i]->data()) != 0) { + memwipe(qs.data(), qs.size()); local_abort("invalid pubkey"); } - ge_double_scalarmult_base_vartime(&tmp2, &sig[i].c, &tmp3, &sig[i].r); // Li = cj Pj + rj G = qj G + wj Pj - ge_tobytes(&rs.ab[i].first, &tmp2); + ge_double_scalarmult_base_vartime(&tmp2, sig[i].c(), &tmp3, sig[i].r()); // Li = cj Pj + rj G = qj G + wj Pj + ge_tobytes(rs.ab[i].first.data(), &tmp2); hash_to_ec(*pubs[i], tmp3); // Hp(Pj) - ge_double_scalarmult_precomp_vartime(&tmp2, &sig[i].r, &tmp3, &sig[i].c, image_pre); // Ri = qj Hp(Pj) + wj I - ge_tobytes(&rs.ab[i].second, &tmp2); - sc_add(&sum, &sum, &sig[i].c); + ge_double_scalarmult_precomp_vartime(&tmp2, sig[i].r(), &tmp3, sig[i].c(), image_pre); // Ri = qj Hp(Pj) + wj I + ge_tobytes(rs.ab[i].second.data(), &tmp2); + sc_add(sum.data(), sum.data(), sig[i].c()); } } ec_scalar c = rs.hash_to_scalar(); // c = Hs(prefix_hash || L0 || ... || L{n-1} || R0 || ... || R{n-1}) - sc_sub(&sig[sec_index].c, &c, &sum); // cs = c - sum(ci, i≠s) = c - sum(wi) - sc_mulsub(&sig[sec_index].r, &sig[sec_index].c, &unwrap(sec), &qs); // rs = qs - cs*x + sc_sub(sig[sec_index].c(), c.data(), sum.data()); // cs = c - sum(ci, i≠s) = c - sum(wi) + sc_mulsub(sig[sec_index].r(), sig[sec_index].c(), sec.data(), qs.data()); // rs = qs - cs*x - memwipe(&qs, sizeof(qs)); + memwipe(qs.data(), qs.size()); } bool check_ring_signature( @@ -629,34 +630,33 @@ namespace crypto { } #endif ge_p3 image_unp; - if (ge_frombytes_vartime(&image_unp, &image) != 0) { + if (ge_frombytes_vartime(&image_unp, image.data()) != 0) { return false; } ge_dsmp image_pre; ge_dsm_precomp(image_pre, &image_unp); - ec_scalar sum; - sc_0(&sum); + ec_scalar sum = null; rs_comm rs{prefix_hash, pubs.size()}; for (size_t i = 0; i < pubs.size(); i++) { ge_p2 tmp2; ge_p3 tmp3; - if (sc_check(&sig[i].c) != 0 || sc_check(&sig[i].r) != 0) { + if (sc_check(sig[i].c()) != 0 || sc_check(sig[i].r()) != 0) { return false; } - if (ge_frombytes_vartime(&tmp3, &*pubs[i]) != 0) { + if (ge_frombytes_vartime(&tmp3, pubs[i]->data()) != 0) { return false; } - ge_double_scalarmult_base_vartime(&tmp2, &sig[i].c, &tmp3, &sig[i].r); - ge_tobytes(&rs.ab[i].first, &tmp2); + ge_double_scalarmult_base_vartime(&tmp2, sig[i].c(), &tmp3, sig[i].r()); + ge_tobytes(rs.ab[i].first.data(), &tmp2); hash_to_ec(*pubs[i], tmp3); - ge_double_scalarmult_precomp_vartime(&tmp2, &sig[i].r, &tmp3, &sig[i].c, image_pre); - ge_tobytes(&rs.ab[i].second, &tmp2); - sc_add(&sum, &sum, &sig[i].c); + ge_double_scalarmult_precomp_vartime(&tmp2, sig[i].r(), &tmp3, sig[i].c(), image_pre); + ge_tobytes(rs.ab[i].second.data(), &tmp2); + sc_add(sum.data(), sum.data(), sig[i].c()); } ec_scalar h = rs.hash_to_scalar(); - sc_sub(&h, &h, &sum); - return sc_isnonzero(&h) == 0; + sc_sub(h.data(), h.data(), sum.data()); + return sc_isnonzero(h.data()) == 0; } void generate_key_image_signature( @@ -669,19 +669,19 @@ namespace crypto { rs_comm rs{reinterpret_cast(image), 1}; ge_p3 tmp3; - ge_scalarmult_base(&tmp3, &k); // L = kG - ge_p3_tobytes(&rs.ab[0].first, &tmp3); // store L + ge_scalarmult_base(&tmp3, k.data()); // L = kG + ge_p3_tobytes(rs.ab[0].first.data(), &tmp3); // store L hash_to_ec(pub, tmp3); // H(A) ge_p2 tmp2; - ge_scalarmult(&tmp2, &k, &tmp3); // R = kH(A) - ge_tobytes(&rs.ab[0].second, &tmp2); // store R + ge_scalarmult(&tmp2, k.data(), &tmp3); // R = kH(A) + ge_tobytes(rs.ab[0].second.data(), &tmp2); // store R - sig.c = rs.hash_to_scalar(); // c = H(I || L || R) = H(I || kG || kH(A)) - sc_mulsub(&sig.r, &sig.c, &unwrap(sec), &k); // r = k - ac = k - aH(I || kG || kH(A)) + sig.c(rs.hash_to_scalar()); // c = H(I || L || R) = H(I || kG || kH(A)) + sc_mulsub(sig.r(), sig.c(), sec.data(), k.data()); // r = k - ac = k - aH(I || kG || kH(A)) - memwipe(&k, sizeof(k)); + memwipe(k.data(), k.size()); } bool check_key_image_signature( @@ -691,14 +691,14 @@ namespace crypto { assert(check_key(pub)); ge_p3 image_unp; - if (ge_frombytes_vartime(&image_unp, &image) != 0 || sc_check(&sig.c) != 0 || sc_check(&sig.r) != 0) + if (ge_frombytes_vartime(&image_unp, image.data()) != 0 || sc_check(sig.c()) != 0 || sc_check(sig.r()) != 0) return false; ge_dsmp image_pre; ge_dsm_precomp(image_pre, &image_unp); rs_comm rs{reinterpret_cast(image), 1}; ge_p3 tmp3; - if (ge_frombytes_vartime(&tmp3, &pub) != 0) + if (ge_frombytes_vartime(&tmp3, pub.data()) != 0) return false; ge_p2 tmp2; @@ -706,8 +706,8 @@ namespace crypto { // The signature r was constructed as r = k - ac, so: // k = ac + r // kG = cA + rG = L - ge_double_scalarmult_base_vartime(&tmp2, &sig.c, &tmp3, &sig.r); // L = cA + rG - ge_tobytes(&rs.ab[0].first, &tmp2); // store L + ge_double_scalarmult_base_vartime(&tmp2, sig.c(), &tmp3, sig.r()); // L = cA + rG + ge_tobytes(rs.ab[0].first.data(), &tmp2); // store L // Step two: reconstruct the signer's R = kH(A) // The signature r was constructed as r = k - ac, so: @@ -715,14 +715,14 @@ namespace crypto { // and since aH(A) == I (the key image, by definition): // kH(A) = rH(A) + cI = R hash_to_ec(pub, tmp3); // H(A) - ge_double_scalarmult_precomp_vartime(&tmp2, &sig.r, &tmp3, &sig.c, image_pre); // R = rH(A) + cI - ge_tobytes(&rs.ab[0].second, &tmp2); // store R + ge_double_scalarmult_precomp_vartime(&tmp2, sig.r(), &tmp3, sig.c(), image_pre); // R = rH(A) + cI + ge_tobytes(rs.ab[0].second.data(), &tmp2); // store R // Now we can calculate our own H(I || L || R), and compare it to the signature's c (which was // set to the signer's H(I || L || R) calculation). ec_scalar h = rs.hash_to_scalar(); - sc_sub(&h, &h, &sig.c); - return sc_isnonzero(&h) == 0; + sc_sub(h.data(), h.data(), sig.c()); + return sc_isnonzero(h.data()) == 0; } } diff --git a/src/crypto/crypto.h b/src/crypto/crypto.h index 25d750f78..d2b97a94b 100644 --- a/src/crypto/crypto.h +++ b/src/crypto/crypto.h @@ -39,103 +39,76 @@ #include "epee/memwipe.h" #include "epee/mlocker.h" -#include "generic-ops.h" -#include "common/hex.h" -#include "common/format.h" -#include "common/formattable.h" #include "hash.h" +#include "base.h" + +extern "C" { +#include "random.h" +} + namespace crypto { - extern "C" { -#include "random.h" - } - - struct alignas(size_t) ec_point { - char data[32]; - // Returns true if non-null, i.e. not 0. - operator bool() const { static constexpr char null[32] = {0}; return memcmp(data, null, sizeof(data)); } + struct ec_point : bytes<32, true> { + // Returns true if non-null, i.e. not all 0. + explicit operator bool() const { return data_ != null.data_; } }; - struct alignas(size_t) ec_scalar { - char data[32]; + struct ec_scalar : bytes<32> { + // constant-time (via libsodium) + bool operator==(const ec_scalar& x) const; + bool operator!=(const ec_scalar& x) const { return !(*this == x); } + // constant-time returns true if not all 0. + explicit operator bool() const; }; struct public_key : ec_point {}; - using secret_key = epee::mlocked>; + struct secret_key_ : ec_scalar {}; + using secret_key = epee::mlocked>; - struct public_keyV { - std::vector keys; - int rows; - }; - - struct secret_keyV { - std::vector keys; - int rows; - }; - - struct public_keyM { - int cols; - int rows; - std::vector column_vectors; - }; + template <> inline const secret_key null{}; struct key_derivation: ec_point {}; struct key_image: ec_point {}; - struct signature { - ec_scalar c, r; + struct signature : bytes<64, true> { + // Returns or sets the "c" part of the signature bytes + unsigned char* c() { return data(); } + const unsigned char* c() const { return data(); } + void c(const ec_scalar& c) { std::copy(c.data(), c.data() + c.size(), data()); } + // Returns or sets the "r" part of the signature bytes + unsigned char* r() { return data() + 32; } + const unsigned char* r() const { return data() + 32; } + void r(const ec_scalar& r) { std::copy(r.data(), r.data() + r.size(), data()); } // Returns true if non-null, i.e. not 0. - operator bool() const { static constexpr char null[64] = {0}; return memcmp(this, null, sizeof(null)); } + explicit operator bool() const { return data_ != null.data_; } }; - // The sizes below are all provided by sodium.h, but we don't want to depend on it here; we check - // that they agree with the actual constants from sodium.h when compiling cryptonote_core.cpp. - struct alignas(size_t) ed25519_public_key { - unsigned char data[32]; // 32 = crypto_sign_ed25519_PUBLICKEYBYTES - static constexpr ed25519_public_key null() { return {0}; } - /// Returns true if non-null - operator bool() const { return memcmp(data, null().data, sizeof(data)); } - }; + struct ed25519_public_key : ec_point {}; - struct alignas(size_t) ed25519_secret_key_ { - // 64 = crypto_sign_ed25519_SECRETKEYBYTES (but we don't depend on libsodium header here) - unsigned char data[64]; - }; + // 64 = crypto_sign_ed25519_SECRETKEYBYTES (but we don't depend on libsodium header here) + struct ed25519_secret_key_ : bytes<64> {}; using ed25519_secret_key = epee::mlocked>; - struct alignas(size_t) ed25519_signature { - unsigned char data[64]; // 64 = crypto_sign_BYTES - static constexpr ed25519_signature null() { return {0}; } + struct ed25519_signature : bytes<64, true> { // Returns true if non-null, i.e. not 0. - operator bool() const { auto z = null(); return memcmp(this, &z, sizeof(z)); } + explicit operator bool() const { return data_ != null.data_; } }; - struct alignas(size_t) x25519_public_key { - unsigned char data[32]; // crypto_scalarmult_curve25519_BYTES - static constexpr x25519_public_key null() { return {0}; } - /// Returns true if non-null - operator bool() const { return memcmp(data, null().data, sizeof(data)); } - }; + struct x25519_public_key : ec_point {}; - struct alignas(size_t) x25519_secret_key_ { - unsigned char data[32]; // crypto_scalarmult_curve25519_BYTES - }; + struct x25519_secret_key_ : bytes<32> {}; using x25519_secret_key = epee::mlocked>; void hash_to_scalar(const void *data, size_t length, ec_scalar &res); + ec_scalar hash_to_scalar(const void* data, size_t length); void random_scalar(unsigned char* bytes); void random_scalar(ec_scalar& res); ec_scalar random_scalar(); - static_assert(sizeof(ec_point) == 32 && sizeof(ec_scalar) == 32 && - sizeof(public_key) == 32 && sizeof(secret_key) == 32 && - sizeof(key_derivation) == 32 && sizeof(key_image) == 32 && - sizeof(signature) == 64, "Invalid structure size"); - void generate_random_bytes_thread_safe(size_t N, uint8_t *bytes); void add_extra_entropy_thread_safe(const void *ptr, size_t bytes); @@ -286,27 +259,12 @@ namespace crypto { const public_key& pub, const signature& sig); - inline std::string to_string(const ec_point& P) { return "<{}>"_format(tools::type_to_hex(P)); } - inline std::string to_string(const signature& s) { return "<{}>"_format(tools::type_to_hex(s)); } - inline std::string to_string(const ed25519_public_key& P) { return "<{}>"_format(tools::type_to_hex(P)); } - inline std::string to_string(const x25519_public_key& P) { return "<{}>"_format(tools::type_to_hex(P)); } - - constexpr inline crypto::public_key null_pkey{}; - const inline crypto::secret_key null_skey{}; } -CRYPTO_MAKE_HASHABLE(public_key) -CRYPTO_MAKE_HASHABLE_CONSTANT_TIME(secret_key) -CRYPTO_MAKE_HASHABLE(key_image) -CRYPTO_MAKE_HASHABLE(signature) -CRYPTO_MAKE_HASHABLE(ed25519_public_key) -CRYPTO_MAKE_HASHABLE(x25519_public_key) - -// ec_point is formattable via to_string, as are any subclasses (such as public_key): -template -inline constexpr bool formattable::via_to_string> -> = true; -template <> inline constexpr bool formattable::via_to_string = true; -template <> inline constexpr bool formattable::via_to_string = true; -template <> inline constexpr bool formattable::via_to_string = true; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; diff --git a/src/crypto/generic-ops.h b/src/crypto/generic-ops.h deleted file mode 100644 index 3b1786be3..000000000 --- a/src/crypto/generic-ops.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2014-2019, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 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. -// -// 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. -// -// 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. -// -// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -#pragma once - -#include -#include -#include -#include - -#define CRYPTO_MAKE_COMPARABLE(type) \ -namespace crypto { \ - inline bool operator==(const type &_v1, const type &_v2) { \ - return !memcmp(&_v1, &_v2, sizeof(_v1)); \ - } \ - inline bool operator!=(const type &_v1, const type &_v2) { \ - return !operator==(_v1, _v2); \ - } \ - inline bool operator<(const type &_v1, const type &_v2) { \ - return memcmp(&_v1, &_v2, sizeof(_v1)) < 0; \ - } \ -} - -#define CRYPTO_MAKE_COMPARABLE_CONSTANT_TIME(type) \ -namespace crypto { \ - inline bool operator==(const type &_v1, const type &_v2) { \ - static_assert(sizeof(_v1) == 32, "constant time comparison is only implenmted for 32 bytes"); \ - return crypto_verify_32((const unsigned char*)&_v1, (const unsigned char*)&_v2) == 0; \ - } \ - inline bool operator!=(const type &_v1, const type &_v2) { \ - return !operator==(_v1, _v2); \ - } \ -} - -#define CRYPTO_DEFINE_HASH_FUNCTIONS(type) \ -namespace std { \ - template<> \ - struct hash { \ - static_assert(sizeof(crypto::type) >= sizeof(std::size_t) && alignof(crypto::type) >= alignof(std::size_t), \ - "Size and alignment of " #type " must be at least that of size_t"); \ - std::size_t operator()(const crypto::type &_v) const { \ - return reinterpret_cast(_v); \ - } \ - }; \ -} - -#define CRYPTO_MAKE_HASHABLE(type) \ -CRYPTO_MAKE_COMPARABLE(type) \ -CRYPTO_DEFINE_HASH_FUNCTIONS(type) - -#define CRYPTO_MAKE_HASHABLE_CONSTANT_TIME(type) \ -CRYPTO_MAKE_COMPARABLE_CONSTANT_TIME(type) \ -CRYPTO_DEFINE_HASH_FUNCTIONS(type) - diff --git a/src/crypto/hash-extra-jh.c b/src/crypto/hash-extra-jh.c index d5334a47f..793157636 100644 --- a/src/crypto/hash-extra-jh.c +++ b/src/crypto/hash-extra-jh.c @@ -35,7 +35,7 @@ #include "jh.h" #include "hash-ops.h" -void hash_extra_jh(const void *data, size_t length, char *hash) { - int r = jh_hash(HASH_SIZE * 8, data, 8 * length, (uint8_t*)hash); +void hash_extra_jh(const void *data, size_t length, unsigned char *hash) { + int r = jh_hash(HASH_SIZE * 8, data, 8 * length, hash); assert(SUCCESS == r); } diff --git a/src/crypto/hash-extra-skein.c b/src/crypto/hash-extra-skein.c index 6d0e09054..d438fa896 100644 --- a/src/crypto/hash-extra-skein.c +++ b/src/crypto/hash-extra-skein.c @@ -35,7 +35,7 @@ #include "hash-ops.h" #include "skein.h" -void hash_extra_skein(const void *data, size_t length, char *hash) { - int r = skein_hash(8 * HASH_SIZE, data, 8 * length, (uint8_t*)hash); +void hash_extra_skein(const void *data, size_t length, unsigned char *hash) { + int r = skein_hash(8 * HASH_SIZE, data, 8 * length, hash); assert(SKEIN_SUCCESS == r); } diff --git a/src/crypto/hash-ops.h b/src/crypto/hash-ops.h index 6962f5b89..c5611b800 100644 --- a/src/crypto/hash-ops.h +++ b/src/crypto/hash-ops.h @@ -37,10 +37,6 @@ #include #include -static inline void *padd(void *p, size_t i) { - return (char *) p + i; -} - #pragma pack(push, 1) union hash_state { uint8_t b[200]; @@ -61,22 +57,22 @@ enum }; #define CN_TURTLE_PAGE_SIZE 262144 -void cn_fast_hash(const void *data, size_t length, char *hash); -void cn_turtle_hash(const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations); +void cn_fast_hash(const void *data, size_t length, unsigned char *hash); +void cn_turtle_hash(const void *data, size_t length, unsigned char *hash, int light, int variant, int prehashed, uint32_t scratchpad, uint32_t iterations); #ifdef ENABLE_MONERO_SLOW_HASH -void cn_monero_hash(const void *data, size_t length, char *hash, int variant, int prehashed); +void cn_monero_hash(const void *data, size_t length, unsigned char *hash, int variant, int prehashed); #endif -void hash_extra_blake(const void *data, size_t length, char *hash); -void hash_extra_groestl(const void *data, size_t length, char *hash); -void hash_extra_jh(const void *data, size_t length, char *hash); -void hash_extra_skein(const void *data, size_t length, char *hash); +void hash_extra_blake(const void *data, size_t length, unsigned char *hash); +void hash_extra_groestl(const void *data, size_t length, unsigned char *hash); +void hash_extra_jh(const void *data, size_t length, unsigned char *hash); +void hash_extra_skein(const void *data, size_t length, unsigned char *hash); -void tree_hash(const char (*hashes)[HASH_SIZE], size_t count, char *root_hash); +void tree_hash(const unsigned char (*hashes)[HASH_SIZE], size_t count, unsigned char *root_hash); void rx_slow_hash_allocate_state(void); void rx_slow_hash_free_state(void); uint64_t rx_seedheight(const uint64_t height); void rx_seedheights(const uint64_t height, uint64_t *seed_height, uint64_t *next_height); -void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const char *seedhash, const void *data, size_t length, char *hash, int miners, int is_alt); +void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const unsigned char *seedhash, const void *data, size_t length, unsigned char *hash, int miners, int is_alt); void rx_reorg(const uint64_t split_height); diff --git a/src/crypto/hash.c b/src/crypto/hash.c index 61b0e17ae..244c981ad 100644 --- a/src/crypto/hash.c +++ b/src/crypto/hash.c @@ -51,7 +51,7 @@ void hash_process(union hash_state *state, const uint8_t *buf, size_t count) { keccak1600(buf, count, (uint8_t*)state); } -void cn_fast_hash(const void *data, size_t length, char *hash) { +void cn_fast_hash(const void *data, size_t length, unsigned char *hash) { union hash_state state; hash_process(&state, data, length); memcpy(hash, &state, HASH_SIZE); diff --git a/src/crypto/hash.cpp b/src/crypto/hash.cpp new file mode 100644 index 000000000..d89bfcbca --- /dev/null +++ b/src/crypto/hash.cpp @@ -0,0 +1,85 @@ +#include "hash.h" +#include "crypto/cn_heavy_hash.hpp" + +namespace crypto { + + static_assert(sizeof(hash) == HASH_SIZE, "Invalid structure size"); + static_assert(sizeof(hash8) == 8, "Invalid structure size"); + + constexpr size_t SIZE_TS_IN_HASH = crypto::hash::size() / sizeof(size_t); + static_assert(SIZE_TS_IN_HASH * sizeof(size_t) == sizeof(crypto::hash) && alignof(crypto::hash) >= alignof(size_t), + "Expected crypto::hash size/alignment not satisfied"); + + crypto::hash& crypto::hash::operator^=(const crypto::hash& b) { + const auto* src = reinterpret_cast(b.data()); + auto* dest = reinterpret_cast(data()); + for (size_t i = 0; i < SIZE_TS_IN_HASH; ++i) + dest[i] ^= src[i]; + return *this; + } + + crypto::hash crypto::hash::operator^(const crypto::hash& b) const { + crypto::hash c = *this; + c ^= b; + return c; + } + + crypto::hash& crypto::hash::operator=(const crypto::hash8& h) { + zero(); + std::copy(h.data(), h.data() + h.size(), data()); + return *this; + } + + void cn_slow_hash(const void* data, std::size_t length, hash& hash, cn_slow_hash_type type) { + switch(type) + { + case cn_slow_hash_type::heavy_v1: + case cn_slow_hash_type::heavy_v2: + { + static thread_local cn_heavy_hash_v2 v2; + static thread_local cn_heavy_hash_v1 v1 = cn_heavy_hash_v1::make_borrowed(v2); + + if (type == cn_slow_hash_type::heavy_v1) v1.hash(data, length, hash.data()); + else v2.hash(data, length, hash.data()); + } + break; + +#ifdef ENABLE_MONERO_SLOW_HASH + case cn_slow_hash_type::cryptonight_v0: + case cn_slow_hash_type::cryptonight_v1_prehashed: + { + int variant = 0, prehashed = 0; + if (type == cn_slow_hash_type::cryptonight_v1_prehashed) + { + prehashed = 1; + variant = 1; + } + else if (type == cn_slow_hash_type::cryptonight_v0_prehashed) + { + prehashed = 1; + } + + cn_monero_hash(data, length, hash.data(), variant, prehashed); + } + break; +#endif + + case cn_slow_hash_type::turtle_lite_v2: + default: + { + constexpr uint32_t CN_TURTLE_SCRATCHPAD = 262144; + constexpr uint32_t CN_TURTLE_ITERATIONS = 131072; + cn_turtle_hash(data, + length, + hash.data(), + 1, // light + 2, // variant + 0, // pre-hashed + CN_TURTLE_SCRATCHPAD, CN_TURTLE_ITERATIONS); + } + break; + } + } + + +} diff --git a/src/crypto/hash.h b/src/crypto/hash.h index c74e979bc..8c831a803 100644 --- a/src/crypto/hash.h +++ b/src/crypto/hash.h @@ -33,41 +33,42 @@ #include #include -#include "generic-ops.h" -#include "common/hex.h" -#include "common/formattable.h" -#include "common/format.h" -#include "crypto/cn_heavy_hash.hpp" +#include "base.h" + +extern "C" { +#include "hash-ops.h" +} namespace crypto { - extern "C" { -#include "hash-ops.h" - } - - struct alignas(size_t) hash { - char data[HASH_SIZE]; - static constexpr hash null() { return {0}; } - operator bool() const { return memcmp(data, null().data, sizeof(data)); } - }; - struct hash8 { - char data[8]; + struct hash8 : bytes<8, true> { + explicit operator bool() const { return data_ != null.data_; } }; - static_assert(sizeof(hash) == HASH_SIZE, "Invalid structure size"); - static_assert(sizeof(hash8) == 8, "Invalid structure size"); + struct hash : bytes { + explicit operator bool() const { return data_ != null.data_; } + + // Combine hashes together via XORs. + hash& operator^=(const crypto::hash& h); + hash operator^(const crypto::hash& h) const; + + // Assigning a hash8 copies the 8 bytes from the hash8 into the first 8 bytes of the hash and + // zeros the rest. + hash& operator=(const crypto::hash8& h); + }; /* Cryptonight hash functions */ - inline void cn_fast_hash(const void *data, std::size_t length, hash &hash) { - cn_fast_hash(data, length, reinterpret_cast(&hash)); + using ::cn_fast_hash; + inline void cn_fast_hash(const void* data, std::size_t length, hash& hash) { + cn_fast_hash(data, length, hash.data()); } - inline hash cn_fast_hash(const void *data, std::size_t length) { + inline hash cn_fast_hash(const void* data, std::size_t length) { hash h; - cn_fast_hash(data, length, reinterpret_cast(&h)); + cn_fast_hash(data, length, h); return h; } @@ -75,99 +76,24 @@ namespace crypto { { #ifdef ENABLE_MONERO_SLOW_HASH // NOTE: Monero's slow hash for Android only, we still use the old hashing algorithm for hashing the KeyStore containing private keys - cryptonight_v0, + cryptonight_v0 = 0, cryptonight_v0_prehashed, cryptonight_v1_prehashed, #endif - heavy_v1, + heavy_v1 = 3, heavy_v2, turtle_lite_v2, }; - inline void cn_slow_hash(const void *data, std::size_t length, hash &hash, cn_slow_hash_type type) { - switch(type) - { - case cn_slow_hash_type::heavy_v1: - case cn_slow_hash_type::heavy_v2: - { - static thread_local cn_heavy_hash_v2 v2; - static thread_local cn_heavy_hash_v1 v1 = cn_heavy_hash_v1::make_borrowed(v2); - - if (type == cn_slow_hash_type::heavy_v1) v1.hash(data, length, hash.data); - else v2.hash(data, length, hash.data); - } - break; - -#ifdef ENABLE_MONERO_SLOW_HASH - case cn_slow_hash_type::cryptonight_v0: - case cn_slow_hash_type::cryptonight_v1_prehashed: - { - int variant = 0, prehashed = 0; - if (type == cn_slow_hash_type::cryptonight_v1_prehashed) - { - prehashed = 1; - variant = 1; - } - else if (type == cn_slow_hash_type::cryptonight_v0_prehashed) - { - prehashed = 1; - } - - cn_monero_hash(data, length, hash.data, variant, prehashed); - } - break; -#endif - - case cn_slow_hash_type::turtle_lite_v2: - default: - { - const uint32_t CN_TURTLE_SCRATCHPAD = 262144; - const uint32_t CN_TURTLE_ITERATIONS = 131072; - cn_turtle_hash(data, - length, - hash.data, - 1, // light - 2, // variant - 0, // pre-hashed - CN_TURTLE_SCRATCHPAD, CN_TURTLE_ITERATIONS); - } - break; - } - } + void cn_slow_hash(const void* data, std::size_t length, hash& hash, cn_slow_hash_type type); + using ::tree_hash; inline void tree_hash(const hash *hashes, std::size_t count, hash &root_hash) { - tree_hash(reinterpret_cast(hashes), count, reinterpret_cast(&root_hash)); + tree_hash(reinterpret_cast(hashes), count, root_hash.data()); } - constexpr size_t SIZE_TS_IN_HASH = sizeof(crypto::hash) / sizeof(size_t); - static_assert(SIZE_TS_IN_HASH * sizeof(size_t) == sizeof(crypto::hash) && alignof(crypto::hash) >= alignof(size_t), - "Expected crypto::hash size/alignment not satisfied"); - - // Combine hashes together via XORs. - inline crypto::hash& operator^=(crypto::hash& a, const crypto::hash& b) { - size_t (&dest)[SIZE_TS_IN_HASH] = reinterpret_cast(a); - const size_t (&src)[SIZE_TS_IN_HASH] = reinterpret_cast(b); - for (size_t i = 0; i < SIZE_TS_IN_HASH; ++i) - dest[i] ^= src[i]; - return a; - } - inline crypto::hash operator^(const crypto::hash& a, const crypto::hash& b) { - crypto::hash c = a; - c ^= b; - return c; - } - - - inline std::string to_hex_string(const crypto::hash& h) { return "<{}>"_format(tools::type_to_hex(h)); } - inline std::string to_hex_string(const crypto::hash8& h) { return "<{}>"_format(tools::type_to_hex(h)); } - - constexpr inline crypto::hash null_hash = {}; - constexpr inline crypto::hash8 null_hash8 = {}; } -CRYPTO_MAKE_HASHABLE(hash) -CRYPTO_MAKE_COMPARABLE(hash8) - -template <> inline constexpr bool formattable::via_to_hex_string = true; -template <> inline constexpr bool formattable::via_to_hex_string = true; +template <> struct std::hash : crypto::raw_hasher {}; +template <> struct std::hash : crypto::raw_hasher {}; diff --git a/src/crypto/random.c b/src/crypto/random.c index 2a6d978d6..7e4205358 100644 --- a/src/crypto/random.c +++ b/src/crypto/random.c @@ -84,7 +84,7 @@ static void generate_system_random_bytes(size_t n, void *result) { } else if (res == 0) { errx(EXIT_FAILURE, "read /dev/urandom: end of file"); } else { - result = padd(result, (size_t) res); + result = (char *) result + res; n -= (size_t) res; } } @@ -141,7 +141,7 @@ void generate_random_bytes_not_thread_safe(size_t n, void *result) { return; } else { memcpy(result, &state, HASH_DATA_AREA); - result = padd(result, HASH_DATA_AREA); + result = (char *) result + HASH_DATA_AREA; n -= HASH_DATA_AREA; } } diff --git a/src/crypto/rx-slow-hash.c b/src/crypto/rx-slow-hash.c index fe4fc51d5..b4b6731d1 100644 --- a/src/crypto/rx-slow-hash.c +++ b/src/crypto/rx-slow-hash.c @@ -188,8 +188,8 @@ static void rx_initdata(randomx_cache *rs_cache, const int miners, const uint64_ rx_dataset_height = seedheight; } -void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const char *seedhash, const void *data, size_t length, - char *hash, int miners, int is_alt) { +void rx_slow_hash(const uint64_t mainheight, const uint64_t seedheight, const unsigned char *seedhash, const void *data, size_t length, + unsigned char *hash, int miners, int is_alt) { uint64_t s_height = rx_seedheight(mainheight); int toggle = (s_height & SEEDHASH_EPOCH_BLOCKS) != 0; randomx_flags flags = enabled_flags() & ~disabled_flags(); diff --git a/src/crypto/tree-hash.c b/src/crypto/tree-hash.c index 0a5860f3b..e84726305 100644 --- a/src/crypto/tree-hash.c +++ b/src/crypto/tree-hash.c @@ -59,7 +59,7 @@ size_t tree_hash_cnt(size_t count) { return pow >> 1; } -void tree_hash(const char (*hashes)[HASH_SIZE], size_t count, char *root_hash) { +void tree_hash(const unsigned char (*hashes)[HASH_SIZE], size_t count, unsigned char *root_hash) { // The blockchain block at height 202612 https://moneroblocks.info/block/202612 // contained 514 transactions, that triggered bad calculation of variable "cnt" in the original version of this function // as from CryptoNote code. @@ -83,7 +83,7 @@ void tree_hash(const char (*hashes)[HASH_SIZE], size_t count, char *root_hash) { size_t cnt = tree_hash_cnt( count ); - char *ints = calloc(cnt, HASH_SIZE); // zero out as extra protection for using uninitialized mem + unsigned char *ints = calloc(cnt, HASH_SIZE); // zero out as extra protection for using uninitialized mem assert(ints); memcpy(ints, hashes, (2 * cnt - count) * HASH_SIZE); diff --git a/src/cryptonote_basic/account.cpp b/src/cryptonote_basic/account.cpp index 4d0bfbe10..ab81b04f4 100644 --- a/src/cryptonote_basic/account.cpp +++ b/src/cryptonote_basic/account.cpp @@ -89,13 +89,13 @@ DISABLE_VS_WARNINGS(4244 4345) epee::wipeable_string key_stream = get_key_stream(key, m_encryption_iv, sizeof(crypto::secret_key) * (2 + m_multisig_keys.size())); const char *ptr = key_stream.data(); for (size_t i = 0; i < sizeof(crypto::secret_key); ++i) - m_spend_secret_key.data[i] ^= *ptr++; + m_spend_secret_key[i] ^= *ptr++; for (size_t i = 0; i < sizeof(crypto::secret_key); ++i) - m_view_secret_key.data[i] ^= *ptr++; + m_view_secret_key[i] ^= *ptr++; for (crypto::secret_key &k: m_multisig_keys) { for (size_t i = 0; i < sizeof(crypto::secret_key); ++i) - k.data[i] ^= *ptr++; + k[i] ^= *ptr++; } } //----------------------------------------------------------------- @@ -117,7 +117,7 @@ DISABLE_VS_WARNINGS(4244 4345) const char *ptr = key_stream.data(); ptr += sizeof(crypto::secret_key); for (size_t i = 0; i < sizeof(crypto::secret_key); ++i) - m_view_secret_key.data[i] ^= *ptr++; + m_view_secret_key[i] ^= *ptr++; } //----------------------------------------------------------------- void account_keys::decrypt_viewkey(const crypto::chacha_key &key) diff --git a/src/cryptonote_basic/connection_context.h b/src/cryptonote_basic/connection_context.h index db67094f7..2c9efae9c 100644 --- a/src/cryptonote_basic/connection_context.h +++ b/src/cryptonote_basic/connection_context.h @@ -63,7 +63,7 @@ namespace cryptonote uint64_t m_last_response_height{0}; std::optional m_last_request_time; epee::copyable_atomic m_callback_request_count{0}; //in debug purpose: problem with double callback rise - crypto::hash m_last_known_hash{crypto::null_hash}; + crypto::hash m_last_known_hash{}; uint32_t m_pruning_seed{0}; bool m_anchor{false}; //size_t m_score{0}; TODO: add score calculations diff --git a/src/cryptonote_basic/cryptonote_basic.cpp b/src/cryptonote_basic/cryptonote_basic.cpp index 12f4b0a31..aa1bd4dd8 100644 --- a/src/cryptonote_basic/cryptonote_basic.cpp +++ b/src/cryptonote_basic/cryptonote_basic.cpp @@ -165,7 +165,7 @@ void block::set_hash_valid(bool v) const uint64_t account_public_address::modulus(uint64_t interval) const { uint64_t address_as_integer = 0; - std::memcpy(&address_as_integer, m_view_public_key.data, sizeof(address_as_integer)); + std::memcpy(&address_as_integer, m_view_public_key.data(), sizeof(address_as_integer)); oxenc::host_to_little_inplace(address_as_integer); return address_as_integer % interval; } diff --git a/src/cryptonote_basic/cryptonote_format_utils.cpp b/src/cryptonote_basic/cryptonote_format_utils.cpp index 9f5320efe..04618514c 100644 --- a/src/cryptonote_basic/cryptonote_format_utils.cpp +++ b/src/cryptonote_basic/cryptonote_format_utils.cpp @@ -111,7 +111,7 @@ namespace cryptonote //--------------------------------------------------------------- crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx, hw::device &hwdev) { - crypto::hash h = null_hash; + crypto::hash h{}; get_transaction_prefix_hash(tx, h, hwdev); return h; } @@ -119,7 +119,7 @@ namespace cryptonote //--------------------------------------------------------------- crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx) { - crypto::hash h = null_hash; + crypto::hash h{}; get_transaction_prefix_hash(tx, h); return h; } @@ -300,11 +300,11 @@ namespace cryptonote return true; } - if (ack.m_spend_secret_key == crypto::null_skey) + if (!ack.m_spend_secret_key) { // for watch-only wallet, simply copy the known output pubkey in_ephemeral.pub = out_key; - in_ephemeral.sec = crypto::null_skey; + in_ephemeral.sec.zero(); } else { @@ -561,7 +561,7 @@ namespace cryptonote tx_extra_pub_key pub_key_field; if (get_field_from_tx_extra(tx_extra, pub_key_field, pk_index)) return pub_key_field.pub_key; - return null_pkey; + return null; } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const transaction_prefix& tx_prefix, size_t pk_index) @@ -765,7 +765,7 @@ namespace cryptonote tx_extra_service_node_winner winner; if (get_field_from_tx_extra(tx_extra, winner)) return winner.m_service_node_key; - return crypto::null_pkey; + return null; } //--------------------------------------------------------------- void add_oxen_name_system_to_tx_extra(std::vector &tx_extra, tx_extra_oxen_name_system const &entry) @@ -1022,7 +1022,7 @@ namespace cryptonote bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector& outs, uint64_t& money_transfered) { crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); - if(null_pkey == tx_pub_key) + if (!tx_pub_key) return false; std::vector additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered); @@ -1194,7 +1194,7 @@ namespace cryptonote //--------------------------------------------------------------- crypto::hash get_transaction_hash(const transaction& t) { - crypto::hash h = null_hash; + crypto::hash h{}; get_transaction_hash(t, h, NULL); CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(t, h, NULL), "Failed to calculate transaction hash"); return h; @@ -1265,7 +1265,7 @@ namespace cryptonote // prunable rct if (t.rct_signatures.type == rct::RCTType::Null) - hashes[2] = crypto::null_hash; + hashes[2].zero(); else hashes[2] = pruned_data_hash; @@ -1321,7 +1321,7 @@ namespace cryptonote // prunable rct if (t.rct_signatures.type == rct::RCTType::Null) { - hashes[2] = crypto::null_hash; + hashes[2].zero(); } else if (!calculate_transaction_prunable_hash(t, &blob, hashes[2])) { @@ -1412,7 +1412,7 @@ namespace cryptonote //--------------------------------------------------------------- crypto::hash get_block_hash(const block& b) { - crypto::hash p = null_hash; + crypto::hash p{}; get_block_hash(b, p); return p; } @@ -1496,7 +1496,7 @@ namespace cryptonote //--------------------------------------------------------------- crypto::hash get_tx_tree_hash(const std::vector& tx_hashes) { - crypto::hash h = null_hash; + crypto::hash h{}; get_tx_tree_hash(tx_hashes, h); return h; } @@ -1505,7 +1505,7 @@ namespace cryptonote { std::vector txs_ids; txs_ids.reserve(1 + b.tx_hashes.size()); - crypto::hash h = null_hash; + crypto::hash h{}; size_t bl_sz = 0; CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(b.miner_tx, h, bl_sz), "Failed to calculate transaction hash"); txs_ids.push_back(h); @@ -1518,7 +1518,7 @@ namespace cryptonote { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash, crypto::cn_slow_hash_type::heavy_v1); - sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); + sc_add(key.data(), key.data(), hash.data()); return key; } //--------------------------------------------------------------- @@ -1526,27 +1526,8 @@ namespace cryptonote { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash, crypto::cn_slow_hash_type::heavy_v1); - sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); + sc_sub(key.data(), key.data(), hash.data()); return key; } } - -std::string ons::generic_owner::to_string(cryptonote::network_type nettype) const -{ - if (type == ons::generic_owner_sig_type::monero) - return cryptonote::get_account_address_as_str(nettype, wallet.is_subaddress, wallet.address); - else - return tools::type_to_hex(ed25519); -} - -bool ons::generic_owner::operator==(generic_owner const &other) const -{ - if (type != other.type) - return false; - - if (type == ons::generic_owner_sig_type::monero) - return wallet.is_subaddress == other.wallet.is_subaddress && wallet.address == other.wallet.address; - else - return ed25519 == other.ed25519; -} diff --git a/src/cryptonote_basic/tx_extra.cpp b/src/cryptonote_basic/tx_extra.cpp index e6883489e..5bacdc18d 100644 --- a/src/cryptonote_basic/tx_extra.cpp +++ b/src/cryptonote_basic/tx_extra.cpp @@ -1,4 +1,5 @@ #include "tx_extra.h" +#include "cryptonote_basic/cryptonote_basic_impl.h" namespace cryptonote { @@ -101,3 +102,26 @@ std::vector coded_reasons(uint16_t decomm_reason) { } } + +namespace ons { + +std::string generic_owner::to_string(cryptonote::network_type nettype) const +{ + if (type == generic_owner_sig_type::monero) + return cryptonote::get_account_address_as_str(nettype, wallet.is_subaddress, wallet.address); + else + return tools::type_to_hex(ed25519); +} + +bool generic_owner::operator==(const generic_owner& other) const +{ + if (type != other.type) + return false; + + if (type == generic_owner_sig_type::monero) + return wallet.is_subaddress == other.wallet.is_subaddress && wallet.address == other.wallet.address; + else + return ed25519 == other.ed25519; +} + +} diff --git a/src/cryptonote_basic/tx_extra.h b/src/cryptonote_basic/tx_extra.h index 52e86e183..19bc21cd5 100644 --- a/src/cryptonote_basic/tx_extra.h +++ b/src/cryptonote_basic/tx_extra.h @@ -111,7 +111,7 @@ struct alignas(size_t) generic_owner char padding02_[7]; std::string to_string(cryptonote::network_type nettype) const; - explicit operator bool() const { return (type == generic_owner_sig_type::monero) ? wallet.address != cryptonote::null_address : ed25519; } + explicit operator bool() const { return (type == generic_owner_sig_type::monero) ? wallet.address != cryptonote::null_address : (bool) ed25519; } bool operator==(generic_owner const &other) const; bool operator!=(generic_owner const &other) const { return !(*this == other); } @@ -521,11 +521,11 @@ namespace cryptonote // The value we sign when signing an unlock request. For backwards compatibility we send this as a // "nonce" (although it isn't and never was a nonce), which is required to be an unsigned 32-bit - // value. We could just as easily sign with crypto::null_hash, but using a distinct value makes it + // value. We could just as easily sign with a null crypto::null, but using a distinct value makes it // slightly less likely that we could end up using the same message as some other signing process. - static constexpr crypto::hash HASH{ + static constexpr crypto::hash HASH{{ 'U','N','L','K','U','N','L','K','U','N','L','K','U','N','L','K', - 'U','N','L','K','U','N','L','K','U','N','L','K','U','N','L','K'}; + 'U','N','L','K','U','N','L','K','U','N','L','K','U','N','L','K'}}; // For now, we still have to send that (not a) "nonce" value in the unlock tx on the wire, but // future HF versions could remove it from the wire (though at 4 bytes it isn't worth doing // until we also need to make some other change to unlocks here). So for now, we always send @@ -556,7 +556,7 @@ namespace cryptonote uint8_t version = 0; ons::mapping_type type; crypto::hash name_hash; - crypto::hash prev_txid = crypto::null_hash; // previous txid that purchased the mapping + crypto::hash prev_txid = crypto::null; // previous txid that purchased the mapping ons::extra_field fields; ons::generic_owner owner = {}; ons::generic_owner backup_owner = {}; diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index d11233436..22f2cbd2f 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -42,6 +42,7 @@ #include "common/string_util.h" #include "common/median.h" #include "common/fs-format.h" +#include "crypto/crypto.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_basic_impl.h" #include "cryptonote_basic/hardfork.h" @@ -117,7 +118,7 @@ Blockchain::Blockchain(tx_memory_pool& tx_pool, service_nodes::service_node_list m_max_prepare_blocks_threads(4), m_db_sync_on_blocks(true), m_db_sync_threshold(1), m_db_sync_mode(db_async), m_db_default_sync(false), m_fast_sync(true), m_show_time_stats(false), m_sync_counter(0), m_bytes_to_sync(0), m_cancel(false), m_long_term_block_weights_window(LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE), m_long_term_effective_median_block_weight(0), - m_long_term_block_weights_cache_tip_hash(crypto::null_hash), + m_long_term_block_weights_cache_tip_hash{}, m_long_term_block_weights_cache_rolling_median(LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE), m_service_node_list(service_node_list), m_btc_valid(false), @@ -899,7 +900,7 @@ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const log::error(logcat, std::string("Something went wrong fetching block hash by height")); throw; } - return null_hash; + return null; } //------------------------------------------------------------------ crypto::hash Blockchain::get_pending_block_id_by_height(uint64_t height) const @@ -1470,7 +1471,7 @@ uint64_t Blockchain::get_long_term_block_weight_median(uint64_t start_height, si bool cached = false; uint64_t blockchain_height = m_db->height(); uint64_t tip_height = start_height + count - 1; - crypto::hash tip_hash = crypto::null_hash; + crypto::hash tip_hash{}; if (tip_height < blockchain_height && count == (size_t)m_long_term_block_weights_cache_rolling_median.size()) { tip_hash = m_db->get_block_hash_from_height(tip_height); @@ -1710,7 +1711,7 @@ bool Blockchain::create_block_template_internal(block& b, const crypto::hash *fr if (miner_tx_context.pulse) b.service_node_winner_key = miner_tx_context.pulse_block_producer.key; else - b.service_node_winner_key = {0}; + b.service_node_winner_key = crypto::null; b.reward = block_rewards; b.height = height; @@ -1783,7 +1784,7 @@ bool Blockchain::build_alt_chain(const crypto::hash &prev_id, int alt_checkpoint_count = 0; int checkpoint_count = 0; - crypto::hash prev_hash = crypto::null_hash; + crypto::hash prev_hash{}; block_extended_info bei = {}; std::string checkpoint_blob; for(bool found = m_db->get_alt_block(prev_id, &data, &blob, &checkpoint_blob); @@ -2507,7 +2508,7 @@ bool Blockchain::get_outs(const rpc::GET_OUTPUTS_BIN::request& req, rpc::GET_OUT return false; } for (const auto &t: data) - res.outs.push_back({t.pubkey, t.commitment, is_output_spendtime_unlocked(t.unlock_time), t.height, crypto::null_hash}); + res.outs.push_back({t.pubkey, t.commitment, is_output_spendtime_unlocked(t.unlock_time), t.height, crypto::null}); if (req.get_txid) { @@ -2752,7 +2753,7 @@ bool Blockchain::get_split_transactions_blobs(const std::vector& t std::string tx; if (m_db->get_pruned_tx_blob(tx_hash, tx)) { - auto& [hash, pruned, pruned_hash, prunable] = txs.emplace_back(tx_hash, std::move(tx), crypto::null_hash, std::string()); + auto& [hash, pruned, pruned_hash, prunable] = txs.emplace_back(tx_hash, std::move(tx), crypto::null, std::string()); if (!is_v1_tx(pruned) && !m_db->get_prunable_tx_hash(tx_hash, pruned_hash)) { log::error(logcat, "Prunable data hash not found for {}", tx_hash); @@ -2886,7 +2887,7 @@ bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, cons blocks.back().first.first = m_db->get_block_blob_from_height(i); block b; CHECK_AND_ASSERT_MES(parse_and_validate_block_from_blob(blocks.back().first.first, b), false, "internal error, invalid block"); - blocks.back().first.second = get_miner_tx_hash ? cryptonote::get_transaction_hash(b.miner_tx) : crypto::null_hash; + blocks.back().first.second = get_miner_tx_hash ? cryptonote::get_transaction_hash(b.miner_tx) : crypto::null; std::vector txs; if (pruned) { @@ -3082,7 +3083,7 @@ bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_heigh // check if we're doing per-block checkpointing if (m_db->height() < m_blocks_hash_check.size() && kept_by_block) { - max_used_block_id = null_hash; + max_used_block_id = null; max_used_block_height = 0; return true; } @@ -4065,7 +4066,7 @@ bool Blockchain::flush_txes_from_pool(const std::vector &txids) Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block const &blk, difficulty_type difficulty, uint64_t chain_height, bool alt_block) { block_pow_verified result = {}; - std::memset(result.proof_of_work.data, 0xff, sizeof(result.proof_of_work.data)); + std::memset(result.proof_of_work.data(), 0xff, result.proof_of_work.size()); crypto::hash const blk_hash = cryptonote::get_block_hash(blk); uint64_t const blk_height = cryptonote::get_block_height(blk); @@ -4109,7 +4110,7 @@ Blockchain::block_pow_verified Blockchain::verify_block_pow(cryptonote::block co if (chain_height < m_blocks_hash_check.size()) { const auto &expected_hash = m_blocks_hash_check[chain_height]; - if (expected_hash != crypto::null_hash) + if (expected_hash) { if (blk_hash != expected_hash) { @@ -5041,7 +5042,7 @@ uint64_t Blockchain::prevalidate_block_hashes(uint64_t height, const std::vector size_t end = n * HASH_OF_HASHES_STEP + HASH_OF_HASHES_STEP; for (size_t i = n * HASH_OF_HASHES_STEP; i < end; ++i) { - CHECK_AND_ASSERT_MES(m_blocks_hash_check[i] == crypto::null_hash || m_blocks_hash_check[i] == data[i - first_index * HASH_OF_HASHES_STEP], + CHECK_AND_ASSERT_MES(!m_blocks_hash_check[i] || m_blocks_hash_check[i] == data[i - first_index * HASH_OF_HASHES_STEP], 0, "Consistency failure in m_blocks_hash_check construction"); m_blocks_hash_check[i] = data[i - first_index * HASH_OF_HASHES_STEP]; } @@ -5702,10 +5703,10 @@ void Blockchain::load_compiled_in_block_hashes(const GetCheckpointsCallback& get for (uint32_t i = 0; i < nblocks; i++) { crypto::hash& hash = m_blocks_hash_of_hashes.emplace_back(); - std::memcpy(hash.data, checkpoints.data(), sizeof(hash.data)); - checkpoints.remove_prefix(sizeof(hash.data)); + std::memcpy(hash.data(), checkpoints.data(), hash.size()); + checkpoints.remove_prefix(hash.size()); } - m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, crypto::null_hash); + m_blocks_hash_check.resize(m_blocks_hash_of_hashes.size() * HASH_OF_HASHES_STEP, null); log::info(logcat, "{} block hashes loaded", nblocks); // FIXME: clear tx_pool because the process might have been diff --git a/src/cryptonote_core/blockchain.h b/src/cryptonote_core/blockchain.h index 07523f7cc..e300a1b8f 100644 --- a/src/cryptonote_core/blockchain.h +++ b/src/cryptonote_core/blockchain.h @@ -1112,7 +1112,7 @@ namespace cryptonote // NOTE: Cache Invalidation Checks uint64_t m_timestamps_and_difficulties_height{0}; - crypto::hash m_difficulty_for_next_block_top_hash{crypto::null_hash}; + crypto::hash m_difficulty_for_next_block_top_hash{}; difficulty_type m_difficulty_for_next_miner_block{1}; } m_cache; diff --git a/src/cryptonote_core/cryptonote_core.cpp b/src/cryptonote_core/cryptonote_core.cpp index 72cc4a7eb..ad41d2ab8 100644 --- a/src/cryptonote_core/cryptonote_core.cpp +++ b/src/cryptonote_core/cryptonote_core.cpp @@ -897,15 +897,15 @@ namespace cryptonote // Ed25519 signing). // if (!init_key(m_config_folder / "key_ed25519", keys.key_ed25519, keys.pub_ed25519, - [](crypto::ed25519_secret_key &sk, crypto::ed25519_public_key &pk) { crypto_sign_ed25519_sk_to_pk(pk.data, sk.data); return true; }, - [](crypto::ed25519_secret_key &sk, crypto::ed25519_public_key &pk) { crypto_sign_ed25519_keypair(pk.data, sk.data); }) + [](crypto::ed25519_secret_key &sk, crypto::ed25519_public_key &pk) { crypto_sign_ed25519_sk_to_pk(pk.data(), sk.data()); return true; }, + [](crypto::ed25519_secret_key &sk, crypto::ed25519_public_key &pk) { crypto_sign_ed25519_keypair(pk.data(), sk.data()); }) ) return false; // Standard x25519 keys generated from the ed25519 keypair, used for encrypted communication between SNs - int rc = crypto_sign_ed25519_pk_to_curve25519(keys.pub_x25519.data, keys.pub_ed25519.data); + int rc = crypto_sign_ed25519_pk_to_curve25519(keys.pub_x25519.data(), keys.pub_ed25519.data()); CHECK_AND_ASSERT_MES(rc == 0, false, "failed to convert ed25519 pubkey to x25519"); - crypto_sign_ed25519_sk_to_curve25519(keys.key_x25519.data, keys.key_ed25519.data); + crypto_sign_ed25519_sk_to_curve25519(keys.key_x25519.data(), keys.key_ed25519.data()); // Legacy primary SN key file; we only load this if it exists, otherwise we use `key_ed25519` // for the primary SN keypair. (This key predates the Ed25519 keys and so is needed for @@ -917,7 +917,7 @@ namespace cryptonote epee::wipeable_string privkey_signhash; privkey_signhash.resize(crypto_hash_sha512_BYTES); unsigned char* pk_sh_data = reinterpret_cast(privkey_signhash.data()); - crypto_hash_sha512(pk_sh_data, keys.key_ed25519.data, 32 /* first 32 bytes are the seed to be SHA512 hashed (the last 32 are just the pubkey) */); + crypto_hash_sha512(pk_sh_data, keys.key_ed25519.data(), 32 /* first 32 bytes are the seed to be SHA512 hashed (the last 32 are just the pubkey) */); // Clamp private key (as libsodium does and expects -- see https://www.jcraige.com/an-explainer-on-ed25519-clamping if you want the broader reasons) pk_sh_data[0] &= 248; pk_sh_data[31] &= 63; // (some implementations put 127 here, but with the |64 in the next line it is the same thing) @@ -925,10 +925,11 @@ namespace cryptonote // Monero crypto requires a pointless check that the secret key is < basepoint, so calculate // it mod basepoint to make it happy: sc_reduce32(pk_sh_data); - std::memcpy(keys.key.data, pk_sh_data, 32); + std::memcpy(keys.key.data(), pk_sh_data, 32); if (!crypto::secret_key_to_public_key(keys.key, keys.pub)) throw std::runtime_error{"Failed to derive primary key from ed25519 key"}; - assert(0 == std::memcmp(keys.pub.data, keys.pub_ed25519.data, 32)); + if (std::memcmp(keys.pub.data(), keys.pub_ed25519.data(), 32)) + throw std::runtime_error{"Internal error: unexpected primary pubkey and ed25519 pubkey mismatch"}; } else if (!init_key(m_config_folder / "key", keys.key, keys.pub, crypto::secret_key_to_public_key, [](crypto::secret_key &key, crypto::public_key &pubkey) { @@ -936,8 +937,8 @@ namespace cryptonote })) return false; } else { - keys.key = crypto::null_skey; - keys.pub = crypto::null_pkey; + keys.key.zero(); + keys.pub.zero(); } if (m_service_node) { @@ -979,7 +980,7 @@ namespace cryptonote AuthLevel auth = default_auth; if (x25519_pubkey_str.size() == sizeof(crypto::x25519_public_key)) { crypto::x25519_public_key x25519_pubkey; - std::memcpy(x25519_pubkey.data, x25519_pubkey_str.data(), x25519_pubkey_str.size()); + std::memcpy(x25519_pubkey.data(), x25519_pubkey_str.data(), x25519_pubkey_str.size()); auto user_auth = omq_check_access(x25519_pubkey); if (user_auth >= AuthLevel::basic) { if (user_auth > auth) @@ -1936,7 +1937,7 @@ namespace cryptonote if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash)) { log::error(logcat, "Failed to parse relayed transaction"); - return crypto::null_hash; + return crypto::null; } txs.push_back(std::make_pair(tx_hash, std::move(tx_blob))); m_mempool.set_relayed(txs); @@ -2265,7 +2266,7 @@ namespace cryptonote return; auto pubkey = m_service_node_list.get_pubkey_from_x25519(m_service_keys.pub_x25519); - if (pubkey != crypto::null_pkey && pubkey != m_service_keys.pub && m_service_node_list.is_service_node(pubkey, false /*don't require active*/)) + if (pubkey && pubkey != m_service_keys.pub && m_service_node_list.is_service_node(pubkey, false /*don't require active*/)) { log::info(logcat, fg(fmt::terminal_color::red), "Failed to submit uptime proof: another service node on the network is using the same ed/x25519 keys as this service node. This typically means both have the same 'key_ed25519' private key file."); diff --git a/src/cryptonote_core/cryptonote_core.h b/src/cryptonote_core/cryptonote_core.h index b01b14c84..5fe3dfca9 100644 --- a/src/cryptonote_core/cryptonote_core.h +++ b/src/cryptonote_core/cryptonote_core.h @@ -368,7 +368,7 @@ namespace cryptonote virtual bool create_miner_block_template(block& b, const crypto::hash *prev_block, const account_public_address& adr, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const std::string& ex_nonce); /** - * @brief called when a transaction is relayed; return the hash of the parsed tx, or null_hash + * @brief called when a transaction is relayed; return the hash of the parsed tx, or null hash * on parse failure. */ virtual crypto::hash on_transaction_relayed(const std::string& tx); diff --git a/src/cryptonote_core/cryptonote_tx_utils.cpp b/src/cryptonote_core/cryptonote_tx_utils.cpp index 9ef7bcd4d..e152c9210 100644 --- a/src/cryptonote_core/cryptonote_tx_utils.cpp +++ b/src/cryptonote_core/cryptonote_tx_utils.cpp @@ -90,11 +90,11 @@ namespace cryptonote { uint64_t height_byte = height & ((uint64_t)0xFF << (i*8)); uint8_t byte = height_byte >> i*8; - sec.data[i] = byte; + sec[i] = byte; } for (int i=8; i < 32; i++) { - sec.data[i] = 0x00; + sec[i] = 0x00; } generate_keys(k.pub, k.sec, k.sec, true); @@ -587,7 +587,7 @@ namespace cryptonote crypto::public_key get_destination_view_key_pub(const std::vector &destinations, const std::optional& change_addr) { - account_public_address addr = {null_pkey, null_pkey}; + account_public_address addr{}; size_t count = 0; bool found_change = false; for (const auto &i : destinations) @@ -602,7 +602,7 @@ namespace cryptonote if (i.addr == addr) continue; if (count > 0) - return null_pkey; + return null; addr = i.addr; ++count; } @@ -665,13 +665,13 @@ namespace cryptonote tx_extra_nonce extra_nonce; if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { - crypto::hash payment_id = null_hash; - crypto::hash8 payment_id8 = null_hash8; + crypto::hash payment_id{}; + crypto::hash8 payment_id8{}; if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { log::debug(globallogcat, "Encrypting payment id {}", payment_id8); crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); - if (view_key_pub == null_pkey) + if (!view_key_pub) { log::error(globallogcat, "Destinations have to have exactly one output to support encrypted payment ids"); return false; @@ -709,9 +709,9 @@ namespace cryptonote // if we have neither long nor short payment id, add a dummy short one, // this should end up being the vast majority of txes as time goes on std::string extra_nonce; - crypto::hash8 payment_id8 = null_hash8; + crypto::hash8 payment_id8{}; crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, change_addr); - if (view_key_pub == null_pkey) + if (!view_key_pub) { log::error(globallogcat, "Failed to get key to encrypt dummy payment id with"); } @@ -923,10 +923,7 @@ namespace cryptonote } // check for watch only wallet - bool zero_secret_key = true; - for (size_t i = 0; i < sizeof(sender_account_keys.m_spend_secret_key); ++i) - zero_secret_key &= (sender_account_keys.m_spend_secret_key.data[i] == 0); - if (zero_secret_key) + if (!sender_account_keys.m_spend_secret_key) { log::debug(globallogcat, "Null secret key, skipping signatures"); } @@ -1088,7 +1085,15 @@ namespace cryptonote else { std::string bd = get_block_hashing_blob(b); - rx_slow_hash(randomx_context.current_blockchain_height, randomx_context.seed_height, randomx_context.seed_block_hash.data, bd.data(), bd.size(), result.data, 0, 1); + rx_slow_hash( + randomx_context.current_blockchain_height, + randomx_context.seed_height, + randomx_context.seed_block_hash.data(), + bd.data(), + bd.size(), + result.data(), + 0, + 1); } return result; @@ -1127,10 +1132,10 @@ namespace cryptonote { rx_slow_hash(randomx_context.current_blockchain_height, randomx_context.seed_height, - randomx_context.seed_block_hash.data, + randomx_context.seed_block_hash.data(), bd.data(), bd.size(), - result.data, + result.data(), miners, 0); return result; diff --git a/src/cryptonote_core/oxen_name_system.cpp b/src/cryptonote_core/oxen_name_system.cpp index 6c13f4ad0..353865ee4 100644 --- a/src/cryptonote_core/oxen_name_system.cpp +++ b/src/cryptonote_core/oxen_name_system.cpp @@ -219,6 +219,7 @@ struct blob_view { std::string_view data; /// Constructor that simply forwards anything to the `data` (string_view) member constructor template explicit blob_view(T&&... args) : data{std::forward(args)...} {} + blob_view(const unsigned char* data, size_t size) : blob_view{reinterpret_cast(data), size} {} }; // Binds a blob wrapped in a blob_view decorator @@ -402,7 +403,7 @@ mapping_record sql_get_mapping_from_statement(sql_compiled_statement& statement) result.name_hash.append(value.data(), value.size()); } - if (!sql_copy_blob(statement, mapping_record_column::txid, result.txid.data, sizeof(result.txid))) + if (!sql_copy_blob(statement, mapping_record_column::txid, result.txid.data(), result.txid.size())) return result; int owner_column = tools::enum_count; @@ -451,7 +452,7 @@ bool sql_run_statement(ons_sql_type type, sql_compiled_statement& statement, voi { auto *entry = reinterpret_cast(context); get(statement, ons_db_setting_column::top_height, entry->top_height); - if (!sql_copy_blob(statement, ons_db_setting_column::top_hash, entry->top_hash.data, sizeof(entry->top_hash.data))) + if (!sql_copy_blob(statement, ons_db_setting_column::top_hash, entry->top_hash.data(), entry->top_hash.size())) return false; get(statement, ons_db_setting_column::version, entry->version); data_loaded = true; @@ -681,7 +682,7 @@ ons::generic_signature make_ed25519_signature(crypto::hash const &hash, crypto:: { ons::generic_signature result = {}; result.type = ons::generic_owner_sig_type::ed25519; - crypto_sign_detached(result.ed25519.data, NULL, reinterpret_cast(hash.data), sizeof(hash), skey.data); + crypto_sign_detached(result.ed25519.data(), NULL, hash.data(), hash.size(), skey.data()); return result; } @@ -710,9 +711,9 @@ bool parse_owner_to_generic_owner(cryptonote::network_type nettype, std::string_ { result = ons::make_monero_owner(parsed_addr.address, parsed_addr.is_subaddress); } - else if (owner.size() == 2*sizeof(ed_owner.data) && oxenc::is_hex(owner)) + else if (owner.size() == 2*ed_owner.size() && oxenc::is_hex(owner)) { - oxenc::from_hex(owner.begin(), owner.end(), ed_owner.data); + oxenc::from_hex(owner.begin(), owner.end(), ed_owner.data()); result = ons::make_ed25519_owner(ed_owner); } else @@ -926,13 +927,13 @@ bool mapping_value::validate(cryptonote::network_type nettype, mapping_type type identifier |= ONS_WALLET_TYPE_INTEGRATED; } iter = std::copy_n(&identifier, 1, iter); - iter = std::copy_n(addr_info.address.m_spend_public_key.data, sizeof(addr_info.address.m_spend_public_key.data), iter); - iter = std::copy_n(addr_info.address.m_view_public_key.data, sizeof(addr_info.address.m_view_public_key.data), iter); + iter = std::copy_n(addr_info.address.m_spend_public_key.data(), addr_info.address.m_spend_public_key.size(), iter); + iter = std::copy_n(addr_info.address.m_view_public_key.data(), addr_info.address.m_view_public_key.size(), iter); size_t counter = 65; assert(std::distance(blob->buffer.begin(), iter) == static_cast(counter)); if (addr_info.has_payment_id) { - std::copy_n(addr_info.payment_id.data, sizeof(addr_info.payment_id.data), iter); + std::copy_n(addr_info.payment_id.data(), addr_info.payment_id.size(), iter); counter+=sizeof(addr_info.payment_id); } @@ -1073,13 +1074,13 @@ static bool verify_ons_signature(crypto::hash const &hash, ons::generic_signatur } else { - return (crypto_sign_verify_detached(signature.data, reinterpret_cast(hash.data), sizeof(hash.data), owner.ed25519.data) == 0); + return (crypto_sign_verify_detached(signature.data, hash.data(), hash.size(), owner.ed25519.data()) == 0); } } static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint64_t blockchain_height, cryptonote::transaction const &tx, cryptonote::tx_extra_oxen_name_system const &ons_extra, std::string *reason) { - crypto::hash expected_prev_txid = crypto::null_hash; + crypto::hash expected_prev_txid{}; std::string name_hash = hash_to_base64(ons_extra.name_hash); ons::mapping_record mapping = ons_db.get_mapping(ons_extra.type, name_hash); @@ -1120,7 +1121,7 @@ static bool validate_against_previous_mapping(ons::name_system_db &ons_db, uint6 return false; crypto::hash hash; - crypto_generichash(reinterpret_cast(hash.data), sizeof(hash), reinterpret_cast(data.data()), data.size(), nullptr /*key*/, 0 /*key_len*/); + crypto_generichash(hash.data(), hash.size(), reinterpret_cast(data.data()), data.size(), nullptr /*key*/, 0 /*key_len*/); if (check_condition(!verify_ons_signature(hash, ons_extra.signature, mapping.owner) && !verify_ons_signature(hash, ons_extra.signature, mapping.backup_owner), reason, @@ -1264,7 +1265,7 @@ bool name_system_db::validate_ons_tx(hf hf_version, uint64_t blockchain_height, // ONS Field(s) Validation // ----------------------------------------------------------------------------------------------- { - if (check_condition((ons_extra.name_hash == null_name_hash || ons_extra.name_hash == crypto::null_hash), reason, + if (check_condition((ons_extra.name_hash == null_name_hash || !ons_extra.name_hash), reason, "{}, {} specified the null name hash", tx, ons_extra_string(nettype, ons_extra))) return false; @@ -1349,12 +1350,12 @@ crypto::hash name_to_hash(std::string_view name, const std::optional= crypto_generichash_BYTES, "Sodium can generate arbitrary length hashes, but recommend the minimum size for a secure hash must be >= crypto_generichash_BYTES"); - crypto_generichash_blake2b(reinterpret_cast(result.data), - sizeof(result), + crypto_generichash_blake2b(result.data(), + result.size(), reinterpret_cast(name.data()), static_cast(name.size()), - key ? reinterpret_cast(key->data) : nullptr, - key ? sizeof(key->data) : 0); + key ? key->data() : nullptr, + key ? key->size() : 0); return result; } @@ -1370,7 +1371,8 @@ struct alignas(size_t) secretbox_secret_key { secretbox_secret_key& operator=(const crypto::hash& h) { static_assert(sizeof(secretbox_secret_key::data) == crypto_aead_xchacha20poly1305_ietf_KEYBYTES); - std::memcpy(data, h.data, sizeof(data)); + static_assert(sizeof(secretbox_secret_key::data) == crypto::hash::size()); + std::memcpy(data, h.data(), sizeof(data)); return *this; } }; @@ -1558,12 +1560,12 @@ std::optional mapping_value::get_wallet_address_ cryptonote::address_parse_info addr_info{}; auto* bufpos = &buffer[1]; - std::memcpy(&addr_info.address.m_spend_public_key.data, bufpos, 32); + std::memcpy(addr_info.address.m_spend_public_key.data(), bufpos, 32); bufpos += 32; - std::memcpy(&addr_info.address.m_view_public_key.data, bufpos, 32); + std::memcpy(addr_info.address.m_view_public_key.data(), bufpos, 32); if (buffer[0] == ONS_WALLET_TYPE_INTEGRATED) { bufpos += 32; - std::copy_n(bufpos,8,addr_info.payment_id.data); + std::copy_n(bufpos, 8, addr_info.payment_id.data()); addr_info.has_payment_id = true; } else if (buffer[0] == ONS_WALLET_TYPE_SUBADDRESS) { addr_info.is_subaddress = true; @@ -1989,7 +1991,7 @@ std::pair> update_record_query(name_sys INSERT INTO mappings (type, name_hash, txid, update_height, expiration_height, owner_id, backup_owner_id, encrypted_value) SELECT type, name_hash, ?, ?)"; - bind.emplace_back(blob_view{tx_hash.data, sizeof(tx_hash)}); + bind.emplace_back(blob_view{tx_hash.data(), tx_hash.size()}); bind.emplace_back(height); constexpr auto suffix = " FROM mappings WHERE type = ? AND name_hash = ? ORDER BY update_height DESC LIMIT 1"sv; @@ -2222,7 +2224,7 @@ bool name_system_db::save_mapping(crypto::hash const &tx_hash, cryptonote::tx_ex bind(statement, mapping_record_column::type, db_mapping_type(src.type)); bind(statement, mapping_record_column::name_hash, name_hash); bind(statement, mapping_record_column::encrypted_value, blob_view{src.encrypted_value}); - bind(statement, mapping_record_column::txid, blob_view{tx_hash.data, sizeof(tx_hash)}); + bind(statement, mapping_record_column::txid, blob_view{tx_hash.data(), tx_hash.size()}); bind(statement, mapping_record_column::update_height, height); bind(statement, mapping_record_column::expiration_height, expiration); bind(statement, mapping_record_column::owner_id, owner_id); @@ -2236,7 +2238,7 @@ bool name_system_db::save_settings(uint64_t top_height, crypto::hash const &top_ { auto& statement = save_settings_sql; bind(statement, ons_db_setting_column::top_height, top_height); - bind(statement, ons_db_setting_column::top_hash, blob_view{top_hash.data, sizeof(top_hash)}); + bind(statement, ons_db_setting_column::top_hash, blob_view{top_hash.data(), top_hash.size()}); bind(statement, ons_db_setting_column::version, version); bool result = sql_run_statement(ons_sql_type::save_setting, statement, nullptr); return result; diff --git a/src/cryptonote_core/oxen_name_system.h b/src/cryptonote_core/oxen_name_system.h index 7841c66ca..f0028c230 100644 --- a/src/cryptonote_core/oxen_name_system.h +++ b/src/cryptonote_core/oxen_name_system.h @@ -322,7 +322,7 @@ struct name_system_db private: cryptonote::network_type nettype; uint64_t last_processed_height = 0; - crypto::hash last_processed_hash = crypto::null_hash; + crypto::hash last_processed_hash{}; sql_compiled_statement save_owner_sql{*this}; sql_compiled_statement save_mapping_sql{*this}; sql_compiled_statement save_settings_sql{*this}; diff --git a/src/cryptonote_core/pulse.cpp b/src/cryptonote_core/pulse.cpp index fbaf7eaff..5c00d38e3 100644 --- a/src/cryptonote_core/pulse.cpp +++ b/src/cryptonote_core/pulse.cpp @@ -228,23 +228,17 @@ crypto::hash blake2b_hash(void const *data, size_t size) { crypto::hash result = {}; static_assert(sizeof(result) == crypto_generichash_BYTES); - crypto_generichash(reinterpret_cast(result.data), sizeof(result), reinterpret_cast(data), size, nullptr /*key*/, 0 /*key length*/); + crypto_generichash(result.data(), result.size(), reinterpret_cast(data), size, nullptr /*key*/, 0 /*key length*/); return result; } std::string log_prefix(round_context const &context) { - std::stringstream result; - result << "Pulse B" << context.wait_for_next_block.height << " R"; - if (context.state >= round_state::prepare_for_round) - result << +context.prepare_for_round.round; - else - result << "0"; - result << ": "; - - if (context.prepare_for_round.node_name.size()) result << context.prepare_for_round.node_name << " "; - result << "'" << round_state_string(context.state) << "' "; - return result.str(); + return "Pulse B{} R{}: {}'{}' "_format( + context.wait_for_next_block.height, + context.state >= round_state::prepare_for_round ? +context.prepare_for_round.round : 0, + context.prepare_for_round.node_name.empty() ? "" : "{} "_format(context.prepare_for_round.node_name), + round_state_string(context.state)); } std::bitset bitset_view16(uint16_t val) @@ -278,14 +272,14 @@ crypto::hash msg_signature_hash(crypto::hash const &top_block_hash, pulse::messa case pulse::message_type::handshake: { - auto buf = tools::memcpy_le(top_block_hash.data, msg.quorum_position, msg.round); + auto buf = tools::memcpy_le(top_block_hash, msg.quorum_position, msg.round); result = blake2b_hash(buf.data(), buf.size()); } break; case pulse::message_type::handshake_bitset: { - auto buf = tools::memcpy_le(msg.handshakes.validator_bitset, top_block_hash.data, msg.quorum_position, msg.round); + auto buf = tools::memcpy_le(msg.handshakes.validator_bitset, top_block_hash, msg.quorum_position, msg.round); result = blake2b_hash(buf.data(), buf.size()); } break; @@ -293,21 +287,21 @@ crypto::hash msg_signature_hash(crypto::hash const &top_block_hash, pulse::messa case pulse::message_type::block_template: { crypto::hash block_hash = blake2b_hash(msg.block_template.blob.data(), msg.block_template.blob.size()); - auto buf = tools::memcpy_le(msg.round, block_hash.data); + auto buf = tools::memcpy_le(msg.round, block_hash); result = blake2b_hash(buf.data(), buf.size()); } break; case pulse::message_type::random_value_hash: { - auto buf = tools::memcpy_le(top_block_hash.data, msg.quorum_position, msg.round, msg.random_value_hash.hash.data); + auto buf = tools::memcpy_le(top_block_hash, msg.quorum_position, msg.round, msg.random_value_hash.hash); result = blake2b_hash(buf.data(), buf.size()); } break; case pulse::message_type::random_value: { - auto buf = tools::memcpy_le(top_block_hash.data, msg.quorum_position, msg.round, msg.random_value.value.data); + auto buf = tools::memcpy_le(top_block_hash, msg.quorum_position, msg.round, msg.random_value.value.data); result = blake2b_hash(buf.data(), buf.size()); } break; @@ -315,7 +309,7 @@ crypto::hash msg_signature_hash(crypto::hash const &top_block_hash, pulse::messa case pulse::message_type::signed_block: { crypto::signature const &final_signature = msg.signed_block.signature_of_final_block_hash; - auto buf = tools::memcpy_le(top_block_hash.data, msg.quorum_position, msg.round, final_signature.c.data, final_signature.r.data); + auto buf = tools::memcpy_le(top_block_hash, msg.quorum_position, msg.round, final_signature); result = blake2b_hash(buf.data(), buf.size()); } break; @@ -332,27 +326,14 @@ std::string msg_source_string(round_context const &context, pulse::message const { if (msg.quorum_position >= context.prepare_for_round.quorum.validators.size()) return "XX"; - std::stringstream stream; - stream << "'" << message_type_string(msg.type) << " at round " << +msg.round << " from " << msg.quorum_position; - if (context.state >= round_state::prepare_for_round) - { - if (msg.quorum_position < context.prepare_for_round.quorum.validators.size()) - { - crypto::public_key const &key = context.prepare_for_round.quorum.validators[msg.quorum_position]; - stream << ":" << key; - } - } - - return stream.str(); + return "'{}' at round {:d} from {:d}{}"_format( + msg.type, msg.round, msg.quorum_position, + context.state >= round_state::prepare_for_round && msg.quorum_position < context.prepare_for_round.quorum.validators.size() + ? ":{}"_format(context.prepare_for_round.quorum.validators[msg.quorum_position]) : ""); } bool msg_signature_check(pulse::message const &msg, crypto::hash const &top_block_hash, service_nodes::quorum const &quorum, std::string *error) { - std::stringstream stream; - OXEN_DEFER { - if (error) *error = stream.str(); - }; - // Get Service Node Key crypto::public_key const *key = nullptr; switch (msg.type) @@ -360,7 +341,7 @@ bool msg_signature_check(pulse::message const &msg, crypto::hash const &top_bloc case pulse::message_type::invalid: { assert("Invalid Code Path" == nullptr); - if (error) stream << log_prefix(context) << "Unhandled message type '" << pulse::message_type_string(msg.type) << "' can not verify signature."; + if (error) *error = "{}Unhandled message type '{}' can not verify signature."_format(log_prefix(context), msg.type); return false; } break; @@ -373,7 +354,7 @@ bool msg_signature_check(pulse::message const &msg, crypto::hash const &top_bloc { if (msg.quorum_position >= static_cast(quorum.validators.size())) { - if (error) stream << log_prefix(context) << "Quorum position " << msg.quorum_position << " in Pulse message indexes oob"; + if (error) *error = "{}Quorum position {} in Pulse message indexes oob"_format(log_prefix(context), msg.quorum_position); return false; } @@ -385,7 +366,7 @@ bool msg_signature_check(pulse::message const &msg, crypto::hash const &top_bloc { if (msg.quorum_position != 0) { - if (error) stream << log_prefix(context) << "Quorum position " << msg.quorum_position << " in Pulse message indexes oob"; + if (error) *error = "{}Quorum position {} in Pulse message indexes oob"_format(log_prefix(context), msg.quorum_position); return false; } @@ -396,7 +377,8 @@ bool msg_signature_check(pulse::message const &msg, crypto::hash const &top_bloc if (!crypto::check_signature(msg_signature_hash(top_block_hash, msg), *key, msg.signature)) { - if (error) stream << log_prefix(context) << "Signature for " << msg_source_string(context, msg) << " at height " << context.wait_for_next_block.height << "; is invalid"; + if (error) *error = "{}Signature for {} at height {} is invalid"_format( + log_prefix(context), msg_source_string(context, msg), context.wait_for_next_block.height); return false; } @@ -1055,7 +1037,7 @@ round_state wait_for_next_block(uint64_t hf16_height, round_context &context, cr } crypto::hash prev_hash = blockchain.get_block_id_by_height(chain_height - 1); - if (prev_hash == crypto::null_hash) + if (!prev_hash) { for (static uint64_t last_height = 0; last_height != chain_height; last_height = chain_height) log::debug(logcat, "{}Failed to query the block hash for height {}", log_prefix(context), chain_height - 1); @@ -1574,14 +1556,14 @@ round_state send_and_wait_for_random_value(round_context &context, service_nodes } } - crypto_generichash_final(&state, reinterpret_cast(final_hash.data), sizeof(final_hash)); + crypto_generichash_final(&state, final_hash.data(), final_hash.size()); } // Add final random value to the block context.transient.signed_block.final_block = std::move(context.transient.wait_for_block_template.block); cryptonote::block &final_block = context.transient.signed_block.final_block; static_assert(sizeof(final_hash) >= sizeof(final_block.pulse.random_value.data)); - std::memcpy(final_block.pulse.random_value.data, final_hash.data, sizeof(final_block.pulse.random_value.data)); + std::memcpy(final_block.pulse.random_value.data, final_hash.data(), sizeof(final_block.pulse.random_value.data)); // Generate the signature of the final block (without any of the other // Service Node signatures because we allow the first diff --git a/src/cryptonote_core/pulse.h b/src/cryptonote_core/pulse.h index a8f1b240a..81dc6c3b9 100644 --- a/src/cryptonote_core/pulse.h +++ b/src/cryptonote_core/pulse.h @@ -7,6 +7,7 @@ #include "cryptonote_basic/cryptonote_basic_impl.h" #include "crypto/crypto.h" +#include "common/formattable.h" namespace cryptonote { @@ -38,7 +39,7 @@ enum struct message_type : uint8_t signed_block, }; -constexpr std::string_view message_type_string(message_type type) +constexpr std::string_view to_string(message_type type) { switch(type) { @@ -107,3 +108,5 @@ bool convert_time_to_round(pulse::time_point const &time, pulse::time_point cons bool get_round_timings(cryptonote::Blockchain const &blockchain, uint64_t height, uint64_t prev_timestamp, pulse::timings ×); } // namespace pulse + +template <> inline constexpr bool formattable::via_to_string = true; diff --git a/src/cryptonote_core/service_node_list.cpp b/src/cryptonote_core/service_node_list.cpp index c574de0bd..20e394595 100644 --- a/src/cryptonote_core/service_node_list.cpp +++ b/src/cryptonote_core/service_node_list.cpp @@ -1358,31 +1358,24 @@ namespace service_nodes static std::string dump_pulse_block_data(cryptonote::block const &block, service_nodes::quorum const *quorum) { - std::stringstream stream; std::bitset<8 * sizeof(block.pulse.validator_bitset)> const validator_bitset = block.pulse.validator_bitset; - stream << "Block(" << cryptonote::get_block_height(block) << "): " << cryptonote::get_block_hash(block) << "\n"; - stream << "Leader: "; - if (quorum) stream << (quorum->workers.empty() ? "(invalid leader)" : oxenc::to_hex(tools::view_guts(quorum->workers[0]))) << "\n"; - else stream << "(invalid quorum)\n"; - stream << "Round: " << +block.pulse.round << "\n"; - stream << "Validator Bitset: " << validator_bitset << "\n"; - - stream << "Signatures: "; - if (block.signatures.empty()) stream << "(none)"; - - for (service_nodes::quorum_signature const &entry : block.signatures) + std::string s = "Block({}): {}\nLeader: {}\nRound: {:d}\nValidator Bitset: {}\nSignatures:"_format( + cryptonote::get_block_height(block), + cryptonote::get_block_hash(block), + !quorum ? "(invalid quorum)" : quorum->workers.empty() ? "(invalid leader)" : + oxenc::to_hex(tools::view_guts(quorum->workers[0])), + validator_bitset.to_string()); + auto append = std::back_inserter(s); + if (block.signatures.empty()) + fmt::format_to(append, " (none)"); + for (const auto& sig : block.signatures) { - stream << "\n"; - stream << " [" << +entry.voter_index << "] validator: "; - if (quorum) - { - stream << ((entry.voter_index >= quorum->validators.size()) ? "(invalid quorum index)" : oxenc::to_hex(tools::view_guts(quorum->validators[entry.voter_index]))); - stream << ", signature: " << oxenc::to_hex(tools::view_guts(entry.signature)); - } - else stream << "(invalid quorum)"; + fmt::format_to(append, "\n [{:d}] validator: {}", sig.voter_index, + !quorum ? "(invalid quorum)" : + sig.voter_index >= quorum->validators.size() ? "(invalid quorum index)" : + "{}: {}"_format(quorum->validators[sig.voter_index], sig.signature)); } - - return stream.str(); + return s; } static bool verify_block_components(cryptonote::network_type nettype, @@ -1790,7 +1783,7 @@ namespace service_nodes else { uint64_t seed = 0; - std::memcpy(&seed, hash.data, sizeof(seed)); + std::memcpy(&seed, hash.data(), sizeof(seed)); oxenc::little_to_host_inplace(seed); seed += static_cast(type); result.seed(seed); @@ -1853,17 +1846,17 @@ namespace service_nodes { std::array src = {pulse_round}; std::copy(std::begin(block.pulse.random_value.data), std::end(block.pulse.random_value.data), src.begin() + 1); - crypto::cn_fast_hash(src.data(), src.size(), hash.data); + crypto::cn_fast_hash(src.data(), src.size(), hash); } else { crypto::hash block_hash = cryptonote::get_block_hash(block); std::array src = {pulse_round}; - std::copy(std::begin(block_hash.data), std::end(block_hash.data), src.begin() + 1); - crypto::cn_fast_hash(src.data(), src.size(), hash.data); + std::copy(std::begin(block_hash), std::end(block_hash), src.begin() + 1); + crypto::cn_fast_hash(src.data(), src.size(), hash); } - assert(hash != crypto::null_hash); + assert(hash); result.push_back(hash); } @@ -2014,7 +2007,7 @@ namespace service_nodes static void generate_other_quorums(service_node_list::state_t &state, std::vector const &active_snode_list, cryptonote::network_type nettype, hf hf_version) { - assert(state.block_hash != crypto::null_hash); + assert(state.block_hash); // The two quorums here have different selection criteria: the entire checkpoint quorum and the // state change *validators* want only active service nodes, but the state change *workers* @@ -2247,7 +2240,7 @@ namespace service_nodes { crypto::hash const block_hash = cryptonote::get_block_hash(block); uint64_t seed = 0; - std::memcpy(&seed, block_hash.data, sizeof(seed)); + std::memcpy(&seed, block_hash.data(), sizeof(seed)); /// Gather existing swarms from infos swarm_snode_map_t existing_swarms; @@ -2441,10 +2434,10 @@ namespace service_nodes service_nodes::payout service_node_list::state_t::get_block_leader() const { - crypto::public_key key = crypto::null_pkey; + crypto::public_key key{}; service_node_info const *info = nullptr; { - auto oldest_waiting = std::make_tuple(std::numeric_limits::max(), std::numeric_limits::max(), crypto::null_pkey); + auto oldest_waiting = std::make_tuple(std::numeric_limits::max(), std::numeric_limits::max(), crypto::null); for (const auto &info_it : service_nodes_infos) { const auto &sninfo = *info_it.second; @@ -2461,7 +2454,7 @@ namespace service_nodes key = std::get<2>(oldest_waiting); } - if (key == crypto::null_pkey) + if (!key) return service_nodes::null_payout; return service_node_payout_portions(key, *info); } @@ -2929,7 +2922,7 @@ namespace service_nodes size_t buf_size; crypto::hash result; - auto buf = tools::memcpy_le(proof.pubkey.data, proof.timestamp, proof.public_ip, proof.storage_https_port, proof.pubkey_ed25519.data, proof.qnet_port, proof.storage_omq_port); + auto buf = tools::memcpy_le(proof.pubkey, proof.timestamp, proof.public_ip, proof.storage_https_port, proof.pubkey_ed25519, proof.qnet_port, proof.storage_omq_port); buf_size = buf.size(); crypto::cn_fast_hash(buf.data(), buf_size, result); return result; @@ -2952,7 +2945,7 @@ namespace service_nodes crypto::hash hash = hash_uptime_proof(result); crypto::generate_signature(hash, keys.pub, keys.key, result.sig); - crypto_sign_detached(result.sig_ed25519.data, NULL, reinterpret_cast(hash.data), sizeof(hash.data), keys.key_ed25519.data); + crypto_sign_detached(result.sig_ed25519.data(), NULL, hash.data(), hash.size(), keys.key_ed25519.data()); return result; } @@ -3069,12 +3062,12 @@ namespace service_nodes void proof_info::update_pubkey(const crypto::ed25519_public_key &pk) { if (pk == proof->pubkey_ed25519) return; - if (pk && 0 == crypto_sign_ed25519_pk_to_curve25519(pubkey_x25519.data, pk.data)) { + if (pk && 0 == crypto_sign_ed25519_pk_to_curve25519(pubkey_x25519.data(), pk.data())) { proof->pubkey_ed25519 = pk; } else { log::warning(logcat, "Failed to derive x25519 pubkey from ed25519 pubkey {}", proof->pubkey_ed25519); - pubkey_x25519 = crypto::x25519_public_key::null(); - proof->pubkey_ed25519 = crypto::ed25519_public_key::null(); + pubkey_x25519.zero(); + proof->pubkey_ed25519.zero(); } } @@ -3125,20 +3118,20 @@ namespace service_nodes return false; } - crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); + crypto::x25519_public_key derived_x25519_pubkey{}; if (!proof.pubkey_ed25519) { log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof.pubkey, proof.pubkey_ed25519); return false; } - if (0 != crypto_sign_verify_detached(proof.sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof.pubkey_ed25519.data)) + if (0 != crypto_sign_verify_detached(proof.sig_ed25519.data(), hash.data(), hash.size(), proof.pubkey_ed25519.data())) { log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof.pubkey); return false; } - if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof.pubkey_ed25519.data) || !derived_x25519_pubkey) + if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data(), proof.pubkey_ed25519.data()) || !derived_x25519_pubkey) { log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof.pubkey); return false; @@ -3255,20 +3248,20 @@ namespace service_nodes return false; } - crypto::x25519_public_key derived_x25519_pubkey = crypto::x25519_public_key::null(); + crypto::x25519_public_key derived_x25519_pubkey{}; if (!proof->pubkey_ed25519) { log::debug(logcat, "Rejecting uptime proof from {}: required ed25519 auxiliary pubkey {} not included in proof", proof->pubkey, proof->pubkey_ed25519); return false; } - if (0 != crypto_sign_verify_detached(proof->sig_ed25519.data, reinterpret_cast(hash.data), sizeof(hash.data), proof->pubkey_ed25519.data)) + if (0 != crypto_sign_verify_detached(proof->sig_ed25519.data(), hash.data(), hash.size(), proof->pubkey_ed25519.data())) { log::debug(logcat, "Rejecting uptime proof from {}: ed25519 signature validation failed", proof->pubkey); return false; } - if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data, proof->pubkey_ed25519.data) || !derived_x25519_pubkey) + if (0 != crypto_sign_ed25519_pk_to_curve25519(derived_x25519_pubkey.data(), proof->pubkey_ed25519.data()) || !derived_x25519_pubkey) { log::debug(logcat, "Rejecting uptime proof from {}: invalid ed25519 pubkey included in proof (x25519 derivation failed)", proof->pubkey); return false; @@ -3364,7 +3357,7 @@ namespace service_nodes auto it = x25519_to_pub.find(x25519); if (it != x25519_to_pub.end()) return it->second.first; - return crypto::null_pkey; + return crypto::null; } crypto::public_key service_node_list::get_random_pubkey() { @@ -3395,7 +3388,7 @@ namespace service_nodes if (xpk.size() != sizeof(crypto::x25519_public_key)) return ""; crypto::x25519_public_key x25519_pub; - std::memcpy(x25519_pub.data, xpk.data(), xpk.size()); + std::memcpy(x25519_pub.data(), xpk.data(), xpk.size()); auto pubkey = get_pubkey_from_x25519(x25519_pub); if (!pubkey) { @@ -3728,7 +3721,7 @@ namespace service_nodes for (size_t i = 0; i < last_index; i++) { state_serialized &entry = data_in.states[i]; - if (entry.block_hash == crypto::null_hash) entry.block_hash = m_blockchain.get_block_id_by_height(entry.height); + if (!entry.block_hash) entry.block_hash = m_blockchain.get_block_id_by_height(entry.height); m_transient.state_history.emplace_hint(m_transient.state_history.end(), this, std::move(entry)); } diff --git a/src/cryptonote_core/service_node_list.h b/src/cryptonote_core/service_node_list.h index c55e66fa1..1eb05b993 100644 --- a/src/cryptonote_core/service_node_list.h +++ b/src/cryptonote_core/service_node_list.h @@ -149,7 +149,7 @@ namespace service_nodes std::unique_ptr proof{}; // Derived from pubkey_ed25519, not serialized - crypto::x25519_public_key pubkey_x25519 = crypto::x25519_public_key::null(); + crypto::x25519_public_key pubkey_x25519 = crypto::null; // Updates pubkey_ed25519 to the given key, re-deriving the x25519 key if it actually changes // (does nothing if the key is the same as the current value). If x25519 derivation fails then @@ -316,7 +316,7 @@ namespace service_nodes if (version >= version_t::v1_add_registration_hf_version) VARINT_FIELD(registration_hf_version); if (version >= version_t::v2_ed25519 && version < version_t::v4_noproofs) { - crypto::ed25519_public_key fake_pk = crypto::ed25519_public_key::null(); + crypto::ed25519_public_key fake_pk = crypto::null; FIELD_N("pubkey_ed25519", fake_pk) if (version >= version_t::v3_quorumnet) { uint16_t fake_port = 0; @@ -647,7 +647,7 @@ namespace service_nodes using block_height = uint64_t; struct state_t { - crypto::hash block_hash{crypto::null_hash}; + crypto::hash block_hash{}; bool only_loaded_quorums{false}; service_nodes_infos_t service_nodes_infos; std::vector key_image_blacklist; @@ -823,5 +823,5 @@ namespace service_nodes payout service_node_payout_portions(const crypto::public_key& key, const service_node_info& info); const static payout_entry null_payout_entry = {cryptonote::null_address, cryptonote::old::STAKING_PORTIONS}; - const static payout null_payout = {crypto::null_pkey, {null_payout_entry}}; + const static payout null_payout = {crypto::null, {null_payout_entry}}; } diff --git a/src/cryptonote_core/service_node_quorum_cop.cpp b/src/cryptonote_core/service_node_quorum_cop.cpp index 1f62031a5..a0223fa63 100644 --- a/src/cryptonote_core/service_node_quorum_cop.cpp +++ b/src/cryptonote_core/service_node_quorum_cop.cpp @@ -45,6 +45,16 @@ namespace service_nodes { static auto logcat = log::Cat("quorum_cop"); + std::string quorum::to_string() const { + std::string result; + auto append = std::back_inserter(result); + for (size_t i = 0; i < validators.size(); i++) + fmt::format_to(append, "V[{}] {}\n", i, validators[i]); + for (size_t i = 0; i < workers.size(); i++) + fmt::format_to(append, "W[{}] {}\n", i, workers[i]); + return result; + } + std::optional> service_node_test_results::why() const { if (passed()) diff --git a/src/cryptonote_core/service_node_quorum_cop.h b/src/cryptonote_core/service_node_quorum_cop.h index 5f6e28e47..08b906e44 100644 --- a/src/cryptonote_core/service_node_quorum_cop.h +++ b/src/cryptonote_core/service_node_quorum_cop.h @@ -52,15 +52,7 @@ namespace service_nodes std::vector validators; // Array of public keys identifying service nodes who validate and sign. std::vector workers; // Array of public keys of tested service nodes (if applicable). // - inline std::string to_string() const - { - std::stringstream result; - for (size_t i = 0; i < validators.size(); i++) - result << "V[" << i << "] " << validators[i] << "\n"; - for (size_t i = 0; i < workers.size(); i++) - result << "W[" << std::to_string(i) + "] " << workers[i] << "\n"; - return result.str(); - }; + std::string to_string() const; BEGIN_SERIALIZE() FIELD(validators) diff --git a/src/cryptonote_core/service_node_rules.cpp b/src/cryptonote_core/service_node_rules.cpp index f7a312bd9..d79feeb67 100644 --- a/src/cryptonote_core/service_node_rules.cpp +++ b/src/cryptonote_core/service_node_rules.cpp @@ -184,7 +184,7 @@ crypto::hash generate_request_stake_unlock_hash(uint32_t nonce) crypto::hash result; oxenc::host_to_little_inplace(nonce); for (size_t i = 0; i < 8; i++) - reinterpret_cast(result.data)[i] = nonce; + reinterpret_cast(result.data())[i] = nonce; return result; } diff --git a/src/cryptonote_core/service_node_voting.cpp b/src/cryptonote_core/service_node_voting.cpp index c521ec571..b8c920681 100644 --- a/src/cryptonote_core/service_node_voting.cpp +++ b/src/cryptonote_core/service_node_voting.cpp @@ -458,8 +458,8 @@ namespace service_nodes if (!result) return result; - crypto::public_key key = crypto::null_pkey; - crypto::hash hash = crypto::null_hash; + crypto::public_key key{}; + crypto::hash hash{}; switch(vote.type) { diff --git a/src/cryptonote_core/tx_blink.cpp b/src/cryptonote_core/tx_blink.cpp index 71f55f685..06c528915 100644 --- a/src/cryptonote_core/tx_blink.cpp +++ b/src/cryptonote_core/tx_blink.cpp @@ -51,17 +51,17 @@ crypto::public_key blink_tx::get_sn_pubkey(subquorum q, int position, const serv // TODO FIXME XXX - we don't want a failure here; if this happens we need to go back into state // history to retrieve the state info. (Or maybe this can't happen?) log::error(globallogcat, "FIXME: could not get blink quorum for blink_tx"); - return crypto::null_pkey; + return crypto::null; } if (position < (int) blink_quorum->validators.size()) return blink_quorum->validators[position]; - return crypto::null_pkey; + return crypto::null; }; crypto::hash blink_tx::hash(bool approved) const { - auto buf = tools::memcpy_le(height, get_txhash().data, uint8_t{approved}); + auto buf = tools::memcpy_le(height, get_txhash(), uint8_t{approved}); crypto::hash blink_hash; crypto::cn_fast_hash(buf.data(), buf.size(), blink_hash); return blink_hash; diff --git a/src/cryptonote_core/tx_pool.cpp b/src/cryptonote_core/tx_pool.cpp index b2e66fd53..eea9eac80 100644 --- a/src/cryptonote_core/tx_pool.cpp +++ b/src/cryptonote_core/tx_pool.cpp @@ -362,7 +362,7 @@ namespace cryptonote time_t receive_time = time(nullptr); - crypto::hash max_used_block_id = null_hash; + crypto::hash max_used_block_id{}; uint64_t max_used_block_height = 0; cryptonote::txpool_tx_meta_t meta; bool inputs_okay = check_tx_inputs([&tx]()->cryptonote::transaction&{ return tx; }, id, max_used_block_height, max_used_block_id, tvc, opts.kept_by_block, @@ -376,10 +376,10 @@ namespace cryptonote { meta.weight = tx_weight; meta.fee = fee; - meta.max_used_block_id = null_hash; + meta.max_used_block_id = null; meta.max_used_block_height = 0; meta.last_failed_height = 0; - meta.last_failed_id = null_hash; + meta.last_failed_id = null; meta.kept_by_block = opts.kept_by_block; meta.receive_time = receive_time; meta.last_relayed_time = time(NULL); @@ -423,7 +423,7 @@ namespace cryptonote meta.max_used_block_id = max_used_block_id; meta.max_used_block_height = max_used_block_height; meta.last_failed_height = 0; - meta.last_failed_id = null_hash; + meta.last_failed_id = null; meta.receive_time = receive_time; meta.last_relayed_time = time(NULL); meta.relayed = opts.relayed; @@ -474,7 +474,7 @@ namespace cryptonote //--------------------------------------------------------------------------------- bool tx_memory_pool::add_tx(transaction &tx, tx_verification_context& tvc, const tx_pool_options &opts, hf version) { - crypto::hash h = null_hash; + crypto::hash h{}; size_t blob_size = 0; std::string bl; t_serializable_object_to_blob(tx, bl); @@ -1055,7 +1055,7 @@ namespace cryptonote tx_verification_context tvc; uint64_t max_used_block_height = 0; - crypto::hash max_used_block_id = null_hash; + crypto::hash max_used_block_id{}; if (!m_blockchain.check_tx_inputs(tx, max_used_block_height, max_used_block_id, tvc, /*kept_by_block*/ false)) { log::info(logcat, "TX type: {} considered for relaying failed tx inputs check, txid: {}, reason: {}", tx.type, txid, print_tx_verification_context(tvc, &tx)); @@ -1554,10 +1554,10 @@ end: //not the best implementation at this time, sorry :( //check is ring_signature already checked ? - if(txd.max_used_block_id == null_hash) + if(!txd.max_used_block_id) {//not checked, lets try to check - if(txd.last_failed_id != null_hash && m_blockchain.get_current_blockchain_height() > txd.last_failed_height && txd.last_failed_id == m_blockchain.get_block_id_by_height(txd.last_failed_height)) + if(txd.last_failed_id && m_blockchain.get_current_blockchain_height() > txd.last_failed_height && txd.last_failed_id == m_blockchain.get_block_id_by_height(txd.last_failed_height)) return false;//we already sure that this tx is broken for this height tx_verification_context tvc; diff --git a/src/cryptonote_core/uptime_proof.cpp b/src/cryptonote_core/uptime_proof.cpp index b1634399b..62dc89b9f 100644 --- a/src/cryptonote_core/uptime_proof.cpp +++ b/src/cryptonote_core/uptime_proof.cpp @@ -38,7 +38,7 @@ Proof::Proof( crypto::hash hash = hash_uptime_proof(); crypto::generate_signature(hash, keys.pub, keys.key, sig); - crypto_sign_detached(sig_ed25519.data, NULL, reinterpret_cast(hash.data), sizeof(hash.data), keys.key_ed25519.data); + crypto_sign_detached(sig_ed25519.data(), nullptr, hash.data(), hash.size(), keys.key_ed25519.data()); } //Deserialize from a btencoded string into our Proof instance @@ -66,7 +66,7 @@ Proof::Proof(const std::string& serialized_proof) if (auto it = bt_proof.find("pk"); it != bt_proof.end()) pubkey = tools::make_from_guts(var::get(bt_proof.at("pk"))); else - std::memcpy(pubkey.data, pubkey_ed25519.data, 32); + std::memcpy(pubkey.data(), pubkey_ed25519.data(), 32); //qnet_port qnet_port = get_int(bt_proof.at("q")); //storage_omq_port diff --git a/src/cryptonote_protocol/block_queue.cpp b/src/cryptonote_protocol/block_queue.cpp index 7ae677555..d40add824 100644 --- a/src/cryptonote_protocol/block_queue.cpp +++ b/src/cryptonote_protocol/block_queue.cpp @@ -406,7 +406,7 @@ size_t block_queue::get_num_filled_spans() const crypto::hash block_queue::get_last_known_hash(const boost::uuids::uuid &connection_id) const { std::unique_lock lock{mutex}; - crypto::hash hash = crypto::null_hash; + crypto::hash hash{}; uint64_t highest_height = 0; for (const auto &span: blocks) { diff --git a/src/cryptonote_protocol/cryptonote_protocol_handler.inl b/src/cryptonote_protocol/cryptonote_protocol_handler.inl index cc5a8dd39..6fe905fac 100644 --- a/src/cryptonote_protocol/cryptonote_protocol_handler.inl +++ b/src/cryptonote_protocol/cryptonote_protocol_handler.inl @@ -1139,7 +1139,7 @@ namespace cryptonote size_t size = blocks_size + others_size; for (const auto &element : arg.missed_ids) - size += sizeof(element.data); + size += element.size(); size += sizeof(arg.current_blockchain_height); { @@ -2203,7 +2203,7 @@ skip: if (!start_from_current_chain) { // we'll want to start off from where we are on that peer, which may not be added yet - if (context.m_last_known_hash != crypto::null_hash && r.block_ids.front() != context.m_last_known_hash) + if (context.m_last_known_hash && r.block_ids.front() != context.m_last_known_hash) r.block_ids.push_front(context.m_last_known_hash); } diff --git a/src/cryptonote_protocol/quorumnet.cpp b/src/cryptonote_protocol/quorumnet.cpp index 118b135b1..57cbd300d 100644 --- a/src/cryptonote_protocol/quorumnet.cpp +++ b/src/cryptonote_protocol/quorumnet.cpp @@ -113,9 +113,9 @@ std::string get_data_as_string(const T &key) { } crypto::x25519_public_key x25519_from_string(std::string_view pubkey) { - crypto::x25519_public_key x25519_pub = crypto::x25519_public_key::null(); + crypto::x25519_public_key x25519_pub{}; if (pubkey.size() == sizeof(crypto::x25519_public_key)) - std::memcpy(x25519_pub.data, pubkey.data(), pubkey.size()); + std::memcpy(x25519_pub.data(), pubkey.data(), pubkey.size()); return x25519_pub; } @@ -455,7 +455,7 @@ bt_dict serialize_vote(const quorum_vote_t &vote) { {"s", get_data_as_string(vote.signature)}, }; if (vote.type == quorum_type::checkpointing) - result["bh"] = std::string{vote.checkpoint.block_hash.data, sizeof(crypto::hash)}; + result["bh"] = std::string{tools::view_guts(vote.checkpoint.block_hash)}; else { result["wi"] = vote.state_change.worker_index; result["sc"] = static_cast>(vote.state_change.state); @@ -478,8 +478,8 @@ quorum_vote_t deserialize_vote(std::string_view v) { std::memcpy(&vote.signature, sig.data(), sizeof(vote.signature)); if (vote.type == quorum_type::checkpointing) { auto &bh = var::get(d.at("bh")); - if (bh.size() != sizeof(vote.checkpoint.block_hash.data)) throw std::invalid_argument("invalid vote checkpoint block hash"); - std::memcpy(vote.checkpoint.block_hash.data, bh.data(), sizeof(vote.checkpoint.block_hash.data)); + if (bh.size() != vote.checkpoint.block_hash.size()) throw std::invalid_argument("invalid vote checkpoint block hash"); + std::memcpy(vote.checkpoint.block_hash.data(), bh.data(), bh.size()); } else { vote.state_change.worker_index = get_int(d.at("wi")); vote.state_change.state = get_enum(d, "sc"); @@ -897,7 +897,7 @@ void handle_blink(Message& m, QnetState& qnet) { auto &tx_hash_str = var::get(data.at("#")); bool already_approved = false, already_rejected = false; if (tx_hash_str.size() == sizeof(crypto::hash)) { - std::memcpy(tx_hash.data, tx_hash_str.data(), sizeof(crypto::hash)); + std::memcpy(tx_hash.data(), tx_hash_str.data(), tx_hash_str.size()); std::shared_lock lock{qnet.mutex}; auto bit = qnet.blinks.find(blink_height); if (bit != qnet.blinks.end()) { @@ -927,7 +927,7 @@ void handle_blink(Message& m, QnetState& qnet) { } } } - log::trace(logcat, "Blink tx hash: {}", to_hex(tx_hash.data)); + log::trace(logcat, "Blink tx hash: {}", tx_hash); } else { log::info(logcat, "Rejecting blink tx: invalid tx hash included in request"); if (tag) @@ -1137,7 +1137,7 @@ void handle_blink_signature(Message& m, QnetState& qnet) { if (hash_str.size() != sizeof(crypto::hash)) throw std::invalid_argument("Invalid blink signature data: invalid tx hash"); crypto::hash tx_hash; - std::memcpy(tx_hash.data, hash_str.data(), sizeof(crypto::hash)); + std::memcpy(tx_hash.data(), hash_str.data(), hash_str.size()); // h - height if (!data.skip_until("h")) throw std::invalid_argument("Invalid blink signature data: missing required field 'h'"); @@ -1635,7 +1635,7 @@ void handle_pulse_random_value_hash(Message &m, QnetState &qnet) if (str.size() != sizeof(msg.random_value_hash.hash)) throw std::invalid_argument("Invalid hash data size: " + std::to_string(str.size())); - std::memcpy(msg.random_value_hash.hash.data, str.data(), str.size()); + std::memcpy(msg.random_value_hash.hash.data(), str.data(), str.size()); } else { throw std::invalid_argument(std::string(INVALID_ARG_PREFIX) + tag + "'"); } diff --git a/src/daemonizer/windows_service.cpp b/src/daemonizer/windows_service.cpp index 3e3eca269..7b851e691 100644 --- a/src/daemonizer/windows_service.cpp +++ b/src/daemonizer/windows_service.cpp @@ -89,7 +89,7 @@ namespace { info.nShow = SW_SHOWNORMAL; if (!ShellExecuteEx(&info)) { - tools::fail_msg_writer() << "Admin relaunch failed: " << get_last_error(); + tools::fail_msg_writer("Admin relaunch failed: {}", get_last_error()); return false; } else @@ -122,7 +122,7 @@ bool check_admin(bool & result) , &p_administrators_group )) { - tools::fail_msg_writer() << "Security Identifier creation failed: " << get_last_error(); + tools::fail_msg_writer("Security Identifier creation failed: {}", get_last_error()); return false; } @@ -132,7 +132,7 @@ bool check_admin(bool & result) , &is_admin )) { - tools::fail_msg_writer() << "Permissions check failed: " << get_last_error(); + tools::fail_msg_writer("Permissions check failed: {}", get_last_error()); return false; } @@ -179,7 +179,7 @@ bool install_service(char const *service_name, std::string const &arguments) }; if (p_manager == nullptr) { - tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error(); + tools::fail_msg_writer("Couldn't connect to service manager: {}", get_last_error()); return false; } @@ -205,11 +205,11 @@ bool install_service(char const *service_name, std::string const &arguments) }; if (p_service == nullptr) { - tools::fail_msg_writer() << "Couldn't create service: " << get_last_error(); + tools::fail_msg_writer("Couldn't create service: {}", get_last_error()); return false; } - tools::success_msg_writer() << "Service installed"; + tools::success_msg_writer("Service installed"); pause_to_display_admin_window_messages(); @@ -218,7 +218,7 @@ bool install_service(char const *service_name, std::string const &arguments) bool start_service(char const *service_name) { - tools::msg_writer() << "Starting service"; + tools::msg_writer("Starting service"); SERVICE_STATUS_PROCESS service_status = {}; DWORD unused = 0; @@ -233,7 +233,7 @@ bool start_service(char const *service_name) }; if (p_manager == nullptr) { - tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error(); + tools::fail_msg_writer("Couldn't connect to service manager: {}", get_last_error()); return false; } @@ -248,7 +248,7 @@ bool start_service(char const *service_name) }; if (p_service == nullptr) { - tools::fail_msg_writer() << "Couldn't find service: " << get_last_error(); + tools::fail_msg_writer("Couldn't find service: {}", get_last_error()); return false; } @@ -258,11 +258,11 @@ bool start_service(char const *service_name) , nullptr )) { - tools::fail_msg_writer() << "Service start request failed: " << get_last_error(); + tools::fail_msg_writer("Service start request failed: {}", get_last_error()); return false; } - tools::success_msg_writer() << "Service started"; + tools::success_msg_writer("Service started"); pause_to_display_admin_window_messages(); @@ -271,7 +271,7 @@ bool start_service(char const *service_name) bool stop_service(char const *service_name) { - tools::msg_writer() << "Stopping service"; + tools::msg_writer("Stopping service"); service_handle p_manager{ OpenSCManager( @@ -283,7 +283,7 @@ bool stop_service(char const *service_name) }; if (p_manager == nullptr) { - tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error(); + tools::fail_msg_writer("Couldn't connect to service manager: {}", get_last_error()); return false; } @@ -297,18 +297,18 @@ bool stop_service(char const *service_name) }; if (p_service == nullptr) { - tools::fail_msg_writer() << "Couldn't find service: " << get_last_error(); + tools::fail_msg_writer("Couldn't find service: {}", get_last_error()); return false; } SERVICE_STATUS status = {}; if (!ControlService(p_service.get(), SERVICE_CONTROL_STOP, &status)) { - tools::fail_msg_writer() << "Couldn't request service stop: " << get_last_error(); + tools::fail_msg_writer("Couldn't request service stop: {}", get_last_error()); return false; } - tools::success_msg_writer() << "Service stopped"; + tools::success_msg_writer("Service stopped"); pause_to_display_admin_window_messages(); @@ -327,7 +327,7 @@ bool uninstall_service(char const *service_name) }; if (p_manager == nullptr) { - tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error(); + tools::fail_msg_writer("Couldn't connect to service manager: {}", get_last_error()); return false; } @@ -341,18 +341,18 @@ bool uninstall_service(char const *service_name) }; if (p_service == nullptr) { - tools::fail_msg_writer() << "Couldn't find service: " << get_last_error(); + tools::fail_msg_writer("Couldn't find service: {}", get_last_error()); return false; } SERVICE_STATUS status = {}; if (!DeleteService(p_service.get())) { - tools::fail_msg_writer() << "Couldn't uninstall service: " << get_last_error(); + tools::fail_msg_writer("Couldn't uninstall service: {}", get_last_error()); return false; } - tools::success_msg_writer() << "Service uninstalled"; + tools::success_msg_writer("Service uninstalled"); pause_to_display_admin_window_messages(); diff --git a/src/debug_utilities/cn_deserialize.cpp b/src/debug_utilities/cn_deserialize.cpp index b32ad7585..6d806dcdb 100644 --- a/src/debug_utilities/cn_deserialize.cpp +++ b/src/debug_utilities/cn_deserialize.cpp @@ -52,57 +52,50 @@ static std::string extra_nonce_to_string(const cryptonote::tx_extra_nonce &extra } struct extra_printer { - void operator()(const tx_extra_padding& x) { std::cout << "padding: " << x.size << " bytes"; } - void operator()(const tx_extra_pub_key& x) { std::cout << "pub key: " << x.pub_key; } - void operator()(const tx_extra_nonce& x) { std::cout << "nonce: " << extra_nonce_to_string(x); } - void operator()(const tx_extra_merge_mining_tag& x) { std::cout << "merge mining tag: depth " << x.depth << ", merkle root " << x.merkle_root; } - void operator()(const tx_extra_additional_pub_keys& x) { - std::cout << "additional tx pubkeys: "; - bool first = true; - for (auto& pk : x.data) { - if (first) first = false; - else std::cout << ", "; - std::cout << pk; - } - } - void operator()(const tx_extra_mysterious_minergate& x) { std::cout << "minergate custom: " << oxenc::to_hex(x.data); } - void operator()(const tx_extra_service_node_winner& x) { std::cout << "SN reward winner: " << x.m_service_node_key; } - void operator()(const tx_extra_service_node_register& x) { std::cout << "SN registration data"; } // TODO: could parse this further - void operator()(const tx_extra_service_node_pubkey& x) { std::cout << "SN pubkey: " << x.m_service_node_key; } - void operator()(const tx_extra_service_node_contributor& x) { std::cout << "SN contribution"; } // Can't actually print the address without knowing the network type - void operator()(const tx_extra_service_node_deregister_old& x) { std::cout << "SN deregistration (pre-HF12)"; } - void operator()(const tx_extra_tx_secret_key& x) { std::cout << "TX secret key: " << tools::type_to_hex(x.key); } - void operator()(const tx_extra_tx_key_image_proofs& x) { std::cout << "TX key image proofs (" << x.proofs.size() << ")"; } - void operator()(const tx_extra_tx_key_image_unlock& x) { std::cout << "TX key image unlock: " << x.key_image; } - void operator()(const tx_extra_burn& x) { std::cout << "Transaction burned fee/payment: " << print_money(x.amount); } - void operator()(const tx_extra_oxen_name_system& x) { - std::cout << "ONS " << (x.is_buying() ? "registration" : x.is_updating() ? "update" : "(unknown)"); + std::string operator()(const tx_extra_padding& x) { return "padding: {} bytes"_format(x.size); } + std::string operator()(const tx_extra_pub_key& x) { return "pub key: {}"_format(x.pub_key); } + std::string operator()(const tx_extra_nonce& x) { return "nonce: {}"_format(extra_nonce_to_string(x)); } + std::string operator()(const tx_extra_merge_mining_tag& x) { return "merge mining tag: depth {}, markle root {}"_format(x.depth, x.merkle_root); } + std::string operator()(const tx_extra_additional_pub_keys& x) { return "additional tx pubkeys: {}"_format(fmt::join(x.data, ", ")); } + std::string operator()(const tx_extra_mysterious_minergate& x) { return "minergate custom: {}"_format(oxenc::to_hex(x.data)); } + std::string operator()(const tx_extra_service_node_winner& x) { return "SN reward winner: {}"_format(x.m_service_node_key); } + std::string operator()(const tx_extra_service_node_register& x) { return "SN registration data"; } // TODO: could parse this further + std::string operator()(const tx_extra_service_node_pubkey& x) { return "SN pubkey: {}"_format(x.m_service_node_key); } + std::string operator()(const tx_extra_service_node_contributor& x) { return "SN contribution"; } // Can't actually print the address without knowing the network type + std::string operator()(const tx_extra_service_node_deregister_old& x) { return "SN deregistration (pre-HF12)"; } + std::string operator()(const tx_extra_tx_secret_key& x) { return "TX secret key: {}" + tools::type_to_hex(x.key); } + std::string operator()(const tx_extra_tx_key_image_proofs& x) { return "TX key image proofs ({})"_format(x.proofs.size()); } + std::string operator()(const tx_extra_tx_key_image_unlock& x) { return "TX key image unlock: {}"_format(x.key_image); } + std::string operator()(const tx_extra_burn& x) { return "Transaction burned fee/payment: {}"_format(print_money(x.amount)); } + std::string operator()(const tx_extra_oxen_name_system& x) { + std::string val = "ONS {}"_format(x.is_buying() ? "registration" : x.is_updating() ? "update" : "(unknown)"); switch (x.type) { - case ons::mapping_type::lokinet: std::cout << " - Lokinet (1y)"; break; - case ons::mapping_type::lokinet_2years: std::cout << " - Lokinet (2y)"; break; - case ons::mapping_type::lokinet_5years: std::cout << " - Lokinet (5y)"; break; - case ons::mapping_type::lokinet_10years: std::cout << " - Lokinet (10y)"; break; - case ons::mapping_type::session: std::cout << " - Session address"; break; - case ons::mapping_type::wallet: std::cout << " - Wallet address"; break; + case ons::mapping_type::lokinet: val += " - Lokinet (1y)"; break; + case ons::mapping_type::lokinet_2years: val += " - Lokinet (2y)"; break; + case ons::mapping_type::lokinet_5years: val += " - Lokinet (5y)"; break; + case ons::mapping_type::lokinet_10years: val += " - Lokinet (10y)"; break; + case ons::mapping_type::session: val += " - Session address"; break; + case ons::mapping_type::wallet: val += " - Wallet address"; break; case ons::mapping_type::update_record_internal: case ons::mapping_type::_count: break; } + return val; } - void operator()(const tx_extra_service_node_state_change& x) { - std::cout << "SN state change: "; + std::string operator()(const tx_extra_service_node_state_change& x) { + std::string_view type; switch (x.state) { - case service_nodes::new_state::decommission: std::cout << "decommission"; break; - case service_nodes::new_state::recommission: std::cout << "recommission"; break; - case service_nodes::new_state::deregister: std::cout << "deregister"; break; - case service_nodes::new_state::ip_change_penalty: std::cout << "ip change penalty"; break; - case service_nodes::new_state::_count: std::cout << "(unknown)"; break; + case service_nodes::new_state::decommission: type = "decommission"; break; + case service_nodes::new_state::recommission: type = "recommission"; break; + case service_nodes::new_state::deregister: type = "deregister"; break; + case service_nodes::new_state::ip_change_penalty: type = "ip change penalty"; break; + case service_nodes::new_state::_count: type = "(unknown)"; break; } - std::cout << " for block height " << x.block_height << ", SN index " << x.service_node_index; + return "SN state change: {} for block height {}, SN index {}"_format( + type, x.block_height, x.service_node_index); } - template void operator()(const T&) { std::cout << "unknown"; } }; @@ -112,7 +105,7 @@ static void print_extra_fields(const std::vector &fi for (size_t n = 0; n < fields.size(); ++n) { std::cout << "- " << n << ": "; - var::visit(extra_printer{}, fields[n]); + std::cout << var::visit(extra_printer{}, fields[n]); std::cout << "\n"; } } @@ -246,12 +239,15 @@ int main(int argc, char* argv[]) { addr_decoded = true; cryptonote::account_public_address const &address = addr_info.address; - std::cout << "Network Type: " << network_type_str(static_cast(nettype)) << "\n"; - std::cout << "Address: " << input << "\n"; - std::cout << "Subaddress: " << (addr_info.is_subaddress ? "Yes" : "No") << "\n"; - std::cout << "Payment ID: " << (addr_info.has_payment_id ? tools::type_to_hex(addr_info.payment_id) : "(none)") << "\n"; - std::cout << "Spend Public Key: " << address.m_spend_public_key << "\n"; - std::cout << "View Public Key: " << address.m_view_public_key << "\n"; + fmt::print("Network Type: {}\n", network_type_str(nettype)); + fmt::print("Address: {}\n", input); + fmt::print("Subaddress: {}\n", addr_info.is_subaddress ? "Yes" : "No"); + if (addr_info.has_payment_id) + fmt::print("Payment ID: {}\n", addr_info.payment_id); + else + fmt::print("Payment ID: (none)\n"); + fmt::print("Spend Public Key: {}\n", address.m_spend_public_key); + fmt::print("View Public Key: {}\n", address.m_view_public_key); } } diff --git a/src/device/device_default.cpp b/src/device/device_default.cpp index 9e22c27e3..68bfa2ac4 100644 --- a/src/device/device_default.cpp +++ b/src/device/device_default.cpp @@ -42,19 +42,6 @@ namespace hw::core { - /* ===================================================================== */ - /* === Misc ==== */ - /* ===================================================================== */ - - // EW, this crap is NASTY. See the comment/TODO in crypto/crypto.cpp (which is where this - // nasty crap was copied from). - static inline unsigned char* operator &(crypto::ec_scalar &scalar) { - return &reinterpret_cast(scalar); - } - static inline const unsigned char *operator &(const crypto::ec_scalar &scalar) { - return &reinterpret_cast(scalar); - } - /* ======================================================================= */ /* SETUP/TEARDOWN */ /* ======================================================================= */ @@ -143,7 +130,7 @@ namespace hw::core { ge_p3 p3; ge_cached cached; - CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&p3, (const unsigned char*)keys.m_account_address.m_spend_public_key.data) == 0, + CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&p3, keys.m_account_address.m_spend_public_key.data()) == 0, "ge_frombytes_vartime failed to convert spend public key"); ge_p3_to_cached(&cached, &p3); @@ -158,14 +145,14 @@ namespace hw::core { crypto::secret_key m = get_subaddress_secret_key(keys.m_view_secret_key, index); // M = m*G - ge_scalarmult_base(&p3, (const unsigned char*)m.data); + ge_scalarmult_base(&p3, m.data()); // D = B + M crypto::public_key D; ge_p1p1 p1p1; ge_add(&p1p1, &p3, &cached); ge_p1p1_to_p3(&p3, &p1p1); - ge_p3_tobytes((unsigned char*)D.data, &p3); + ge_p3_tobytes(D.data(), &p3); pkeys.push_back(D); } @@ -222,7 +209,7 @@ namespace hw::core { } bool device_default::sc_secret_add(crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) { - sc_add(&r, &a, &b); + sc_add(r.data(), a.data(), b.data()); return true; } @@ -274,7 +261,7 @@ namespace hw::core { bool device_default::generate_ons_signature(std::string_view sig_data, const cryptonote::account_keys& keys, const cryptonote::subaddress_index& index, crypto::signature& sig) { crypto::hash hash; - crypto_generichash(reinterpret_cast(hash.data), sizeof(hash), reinterpret_cast(sig_data.data()), sig_data.size(), nullptr, 0); + crypto_generichash(hash.data(), hash.size(), reinterpret_cast(sig_data.data()), sig_data.size(), nullptr, 0); crypto::secret_key skey = keys.m_spend_secret_key; if (!index.is_zero()) @@ -383,7 +370,7 @@ namespace hw::core { cn_fast_hash(data, 33, hash); for (size_t b = 0; b < 8; ++b) - payment_id.data[b] ^= hash.data[b]; + payment_id[b] ^= hash[b]; return true; } diff --git a/src/device/device_ledger.cpp b/src/device/device_ledger.cpp index 65ab8bb5c..302e46333 100644 --- a/src/device/device_ledger.cpp +++ b/src/device/device_ledger.cpp @@ -227,7 +227,7 @@ namespace hw::ledger { /* === Internal Helpers ==== */ /* ===================================================================== */ static bool is_fake_view_key(const crypto::secret_key &sec) { - return sec == crypto::null_skey; + return !sec; } bool operator==(const crypto::key_derivation &d0, const crypto::key_derivation &d1) { @@ -699,8 +699,8 @@ namespace hw::ledger { send_simple(INS_GET_KEY, 1); int offset = 0; - receive_bytes(pubkey.m_view_public_key.data, 32, offset); - receive_bytes(pubkey.m_spend_public_key.data, 32, offset); + receive_bytes(pubkey.m_view_public_key.data(), 32, offset); + receive_bytes(pubkey.m_spend_public_key.data(), 32, offset); return true; } @@ -709,22 +709,22 @@ namespace hw::ledger { auto locks = tools::unique_locks(device_locker, command_locker); //secret key are represented as fake key on the wallet side - memcpy(vkey.data, dummy_view_key, 32); - memcpy(skey.data, dummy_spend_key, 32); + memcpy(vkey.data(), dummy_view_key, 32); + memcpy(skey.data(), dummy_spend_key, 32); //spcialkey, normal conf handled in decrypt send_simple(INS_GET_KEY, 0x02); //View key is retrieved, if allowed, to speed up blockchain parsing - receive_bytes(viewkey.data, 32); + receive_bytes(viewkey.data(), 32); has_view_key = !is_fake_view_key(viewkey); log::debug(logcat, "{}", (has_view_key ? "Have view key" : "Have no view key")); #ifdef DEBUG_HWDEVICE send_simple(INS_GET_KEY, 0x04); int offset = 0; - receive_bytes(dbg_viewkey.data, 32, offset); - receive_bytes(dbg_spendkey.data, 32, offset); + receive_bytes(dbg_viewkey.data(), 32, offset); + receive_bytes(dbg_spendkey.data(), 32, offset); #endif return true; @@ -759,7 +759,7 @@ namespace hw::ledger { send_bytes(&index, sizeof(index), offset); //payment ID - send_bytes(payment_id ? payment_id->data : crypto::null_hash8.data, 8, offset); + send_bytes(payment_id ? payment_id->data() : crypto::null.data(), 8, offset); CHECK_AND_ASSERT_THROW_MES(finish_and_exchange(offset, true) == SW_OK, "Timeout/Error on display address."); } @@ -774,12 +774,12 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE crypto::key_derivation derivation_x = (mode_ == mode::TRANSACTION_PARSE && has_view_key) ? derivation : decrypt(derivation); - log_hexbuffer("derive_subaddress_public_key: [[IN]] pub ", pub.data, 32); - log_hexbuffer("derive_subaddress_public_key: [[IN]] derivation", derivation_x.data, 32); + log_hexbuffer("derive_subaddress_public_key: [[IN]] pub ", pub.data(), 32); + log_hexbuffer("derive_subaddress_public_key: [[IN]] derivation", derivation_x.data(), 32); log_message( "derive_subaddress_public_key: [[IN]] index ", std::to_string(output_index)); crypto::public_key derived_pub_x; debug_device->derive_subaddress_public_key(pub, derivation_x, output_index, derived_pub_x); - log_hexbuffer("derive_subaddress_public_key: [[OUT]] derived_pub", derived_pub_x.data, 32); + log_hexbuffer("derive_subaddress_public_key: [[OUT]] derived_pub", derived_pub_x.data(), 32); #endif if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { @@ -791,19 +791,19 @@ namespace hw::ledger { int offset = set_command_header_noopt(INS_DERIVE_SUBADDRESS_PUBLIC_KEY); //pub - send_bytes(pub.data, 32, offset); + send_bytes(pub.data(), 32, offset); //derivation - send_secret(derivation.data, offset); + send_secret(derivation.data(), offset); //index send_u32(output_index, offset); finish_and_exchange(offset); //pub key - receive_bytes(derived_pub.data, 32); + receive_bytes(derived_pub.data(), 32); } #ifdef DEBUG_HWDEVICE - check32("derive_subaddress_public_key", "derived_pub", derived_pub_x.data, derived_pub.data); + check32("derive_subaddress_public_key", "derived_pub", derived_pub_x.data(), derived_pub.data()); #endif return true; @@ -815,11 +815,11 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = decrypt(keys); - log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data, 32); - log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_spend_secret_key", keys_x.m_spend_secret_key.data, 32); + log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data(), 32); + log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_spend_secret_key", keys_x.m_spend_secret_key.data(), 32); log_message ("get_subaddress_spend_public_key: [[IN]] index ", std::to_string(index.major)+"."+std::to_string(index.minor)); crypto::public_key D_x = debug_device->get_subaddress_spend_public_key(keys_x, index); - log_hexbuffer("get_subaddress_spend_public_key: [[OUT]] derivation ", D_x.data, 32); + log_hexbuffer("get_subaddress_spend_public_key: [[OUT]] derivation ", D_x.data(), 32); #endif if (index.is_zero()) { @@ -833,11 +833,11 @@ namespace hw::ledger { finish_and_exchange(offset); - receive_bytes(D.data, 32); + receive_bytes(D.data(), 32); } #ifdef DEBUG_HWDEVICE - check32("get_subaddress_spend_public_key", "D", D_x.data, D.data); + check32("get_subaddress_spend_public_key", "D", D_x.data(), D.data()); #endif return D; @@ -859,14 +859,14 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const cryptonote::account_keys keys_x = decrypt(keys); - log_hexbuffer("get_subaddress: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data, 32); - log_hexbuffer("get_subaddress: [[IN]] keys.m_view_public_key", keys_x.m_account_address.m_view_public_key.data, 32); - log_hexbuffer("get_subaddress: [[IN]] keys.m_spend_secret_key ", keys_x.m_spend_secret_key.data, 32); - log_hexbuffer("get_subaddress: [[IN]] keys.m_spend_public_key", keys_x.m_account_address.m_spend_public_key.data, 32); + log_hexbuffer("get_subaddress: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data(), 32); + log_hexbuffer("get_subaddress: [[IN]] keys.m_view_public_key", keys_x.m_account_address.m_view_public_key.data(), 32); + log_hexbuffer("get_subaddress: [[IN]] keys.m_spend_secret_key ", keys_x.m_spend_secret_key.data(), 32); + log_hexbuffer("get_subaddress: [[IN]] keys.m_spend_public_key", keys_x.m_account_address.m_spend_public_key.data(), 32); log_message( "get_subaddress: [[IN]] index ", std::to_string(index.major)+"."+std::to_string(index.minor)); cryptonote::account_public_address address_x = debug_device->get_subaddress(keys_x, index); - log_hexbuffer("get_subaddress: [[OUT]] keys.m_view_public_key ", address_x.m_view_public_key.data, 32); - log_hexbuffer("get_subaddress: [[OUT]] keys.m_spend_public_key", address_x.m_spend_public_key.data, 32); + log_hexbuffer("get_subaddress: [[OUT]] keys.m_view_public_key ", address_x.m_view_public_key.data(), 32); + log_hexbuffer("get_subaddress: [[OUT]] keys.m_spend_public_key", address_x.m_spend_public_key.data(), 32); #endif if (index.is_zero()) { @@ -880,13 +880,13 @@ namespace hw::ledger { finish_and_exchange(offset); offset = 0; - receive_bytes(address.m_view_public_key.data, 32, offset); - receive_bytes(address.m_spend_public_key.data, 32, offset); + receive_bytes(address.m_view_public_key.data(), 32, offset); + receive_bytes(address.m_spend_public_key.data(), 32, offset); } #ifdef DEBUG_HWDEVICE - check32("get_subaddress", "address.m_view_public_key.data", address_x.m_view_public_key.data, address.m_view_public_key.data); - check32("get_subaddress", "address.m_spend_public_key.data", address_x.m_spend_public_key.data, address.m_spend_public_key.data); + check32("get_subaddress", "address.m_view_public_key.data", address_x.m_view_public_key.data(), address.m_view_public_key.data()); + check32("get_subaddress", "address.m_spend_public_key.data", address_x.m_spend_public_key.data(), address.m_spend_public_key.data()); #endif return address; @@ -899,14 +899,14 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = decrypt(sec); log_message ("get_subaddress_secret_key: [[IN]] index ", std::to_string(index.major)+"."+std::to_string(index.minor)); - log_hexbuffer("get_subaddress_secret_key: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("get_subaddress_secret_key: [[IN]] sec ", sec_x.data(), 32); crypto::secret_key sub_sec_x = debug_device->get_subaddress_secret_key(sec_x, index); - log_hexbuffer("get_subaddress_secret_key: [[OUT]] sub_sec", sub_sec_x.data, 32); + log_hexbuffer("get_subaddress_secret_key: [[OUT]] sub_sec", sub_sec_x.data(), 32); #endif int offset = set_command_header_noopt(INS_GET_SUBADDRESS_SECRET_KEY); //sec - send_secret(sec.data, offset); + send_secret(sec.data(), offset); //index static_assert(sizeof(cryptonote::subaddress_index) == 8); send_bytes(&index, sizeof(index), offset); @@ -914,11 +914,11 @@ namespace hw::ledger { finish_and_exchange(offset); offset = 0; - receive_secret(sub_sec.data, offset); + receive_secret(sub_sec.data(), offset); #ifdef DEBUG_HWDEVICE crypto::secret_key sub_sec_clear = decrypt(sub_sec); - check32("get_subaddress_secret_key", "sub_sec", sub_sec_x.data, sub_sec_clear.data); + check32("get_subaddress_secret_key", "sub_sec", sub_sec_x.data(), sub_sec_clear.data()); #endif return sub_sec; @@ -934,9 +934,9 @@ namespace hw::ledger { offset = set_command_header_noopt(INS_VERIFY_KEY); //sec - send_secret(secret_key.data, offset); + send_secret(secret_key.data(), offset); //pub - send_bytes(public_key.data, 32, offset); + send_bytes(public_key.data(), 32, offset); finish_and_exchange(offset); @@ -1010,29 +1010,29 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::secret_key a_x = decrypt(a); const crypto::secret_key b_x = decrypt(b); - log_hexbuffer("sc_secret_add: [[IN]] a ", a_x.data, 32); - log_hexbuffer("sc_secret_add: [[IN]] b ", b_x.data, 32); + log_hexbuffer("sc_secret_add: [[IN]] a ", a_x.data(), 32); + log_hexbuffer("sc_secret_add: [[IN]] b ", b_x.data(), 32); crypto::secret_key r_x; rct::key aG_x; debug_device->sc_secret_add(r_x, a_x, b_x); - log_hexbuffer("sc_secret_add: [[OUT]] aG", r_x.data, 32); + log_hexbuffer("sc_secret_add: [[OUT]] aG", r_x.data(), 32); #endif offset = set_command_header_noopt(INS_SECRET_KEY_ADD); //sec key - send_secret(a.data, offset); + send_secret(a.data(), offset); //sec key - send_secret(b.data, offset); + send_secret(b.data(), offset); finish_and_exchange(offset); //sec key offset = 0; - receive_secret(r.data, offset); + receive_secret(r.data(), offset); #ifdef DEBUG_HWDEVICE crypto::secret_key r_clear = decrypt(r); - check32("sc_secret_add", "r", r_x.data, r_clear.data); + check32("sc_secret_add", "r", r_x.data(), r_clear.data()); #endif return true; @@ -1051,7 +1051,7 @@ namespace hw::ledger { crypto::secret_key recovery_key_x; if (recover) { recovery_key_x = decrypt(recovery_key); - log_hexbuffer("generate_keys: [[IN]] pub", recovery_key_x.data, 32); + log_hexbuffer("generate_keys: [[IN]] pub", recovery_key_x.data(), 32); } #endif @@ -1059,17 +1059,17 @@ namespace hw::ledger { offset = 0; //pub key - receive_bytes(pub.data, 32, offset); - receive_secret(sec.data, offset); + receive_bytes(pub.data(), 32, offset); + receive_secret(sec.data(), offset); #ifdef DEBUG_HWDEVICE crypto::secret_key sec_clear = decrypt(sec); sec_x = sec_clear; - log_hexbuffer("generate_keys: [[OUT]] pub", pub.data, 32); - log_hexbuffer("generate_keys: [[OUT]] sec", sec_clear.data, 32); + log_hexbuffer("generate_keys: [[OUT]] pub", pub.data(), 32); + log_hexbuffer("generate_keys: [[OUT]] sec", sec_clear.data(), 32); crypto::secret_key_to_public_key(sec_x,pub_x); - check32("generate_keys", "pub", pub_x.data, pub.data); + check32("generate_keys", "pub", pub_x.data(), pub.data()); #endif return sec; @@ -1088,12 +1088,12 @@ namespace hw::ledger { bool r = false; #ifdef DEBUG_HWDEVICE - log_hexbuffer("generate_key_derivation: [[IN]] pub ", pub.data, 32); + log_hexbuffer("generate_key_derivation: [[IN]] pub ", pub.data(), 32); const crypto::secret_key sec_x = (sec == rct::rct2sk(rct::I)) ? sec : decrypt(sec); - log_hexbuffer("generate_key_derivation: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("generate_key_derivation: [[IN]] sec ", sec_x.data(), 32); crypto::key_derivation derivation_x; debug_device->generate_key_derivation(pub, sec_x, derivation_x); - log_hexbuffer("generate_key_derivation: [[OUT]] derivation", derivation_x.data, 32); + log_hexbuffer("generate_key_derivation: [[OUT]] derivation", derivation_x.data(), 32); #endif if (mode_ == mode::TRANSACTION_PARSE && has_view_key) { @@ -1106,22 +1106,22 @@ namespace hw::ledger { } else { int offset = set_command_header_noopt(INS_GEN_KEY_DERIVATION); //pub - send_bytes(pub.data, 32, offset); + send_bytes(pub.data(), 32, offset); //sec - send_secret(sec.data, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); offset = 0; //derivation data - receive_secret(derivation.data, offset); + receive_secret(derivation.data(), offset); r = true; } #ifdef DEBUG_HWDEVICE crypto::key_derivation derivation_clear = (mode_ == mode::TRANSACTION_PARSE && has_view_key) ? derivation : decrypt(derivation); - check32("generate_key_derivation", "derivation", derivation_x.data, derivation_clear.data); + check32("generate_key_derivation", "derivation", derivation_x.data(), derivation_clear.data()); #endif return r; @@ -1142,7 +1142,7 @@ namespace hw::ledger { } } CHECK_AND_ASSERT_THROW_MES(pkey, "Mismatched derivation on scan info"); - return generate_key_derivation(*pkey, crypto::null_skey, derivation); + return generate_key_derivation(*pkey, crypto::null, derivation); } bool device_ledger::derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res) { @@ -1150,16 +1150,16 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = decrypt(derivation); - log_hexbuffer("derivation_to_scalar: [[IN]] derivation ", derivation_x.data, 32); + log_hexbuffer("derivation_to_scalar: [[IN]] derivation ", derivation_x.data(), 32); log_message ("derivation_to_scalar: [[IN]] output_index ", std::to_string(output_index)); crypto::ec_scalar res_x; debug_device->derivation_to_scalar(derivation_x, output_index, res_x); - log_hexbuffer("derivation_to_scalar: [[OUT]] res ", res_x.data, 32); + log_hexbuffer("derivation_to_scalar: [[OUT]] res ", res_x.data(), 32); #endif int offset = set_command_header_noopt(INS_DERIVATION_TO_SCALAR); //derivation - send_secret(derivation.data, offset); + send_secret(derivation.data(), offset); //index send_u32(output_index, offset); @@ -1168,11 +1168,11 @@ namespace hw::ledger { //derivation data offset = 0; - receive_secret(res.data, offset); + receive_secret(res.data(), offset); #ifdef DEBUG_HWDEVICE crypto::ec_scalar res_clear = decrypt(res); - check32("derivation_to_scalar", "res", res_x.data, res_clear.data); + check32("derivation_to_scalar", "res", res_x.data(), res_clear.data()); #endif return true; @@ -1184,31 +1184,31 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = decrypt(derivation); const crypto::secret_key sec_x = decrypt(sec); - log_hexbuffer("derive_secret_key: [[IN]] derivation ", derivation_x.data, 32); + log_hexbuffer("derive_secret_key: [[IN]] derivation ", derivation_x.data(), 32); log_message ("derive_secret_key: [[IN]] index ", std::to_string(output_index)); - log_hexbuffer("derive_secret_key: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("derive_secret_key: [[IN]] sec ", sec_x.data(), 32); crypto::secret_key derived_sec_x; debug_device->derive_secret_key(derivation_x, output_index, sec_x, derived_sec_x); - log_hexbuffer("derive_secret_key: [[OUT]] derived_sec", derived_sec_x.data, 32); + log_hexbuffer("derive_secret_key: [[OUT]] derived_sec", derived_sec_x.data(), 32); #endif int offset = set_command_header_noopt(INS_DERIVE_SECRET_KEY); //derivation - send_secret(derivation.data, offset); + send_secret(derivation.data(), offset); //index send_u32(output_index, offset); //sec - send_secret(sec.data, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); offset = 0; //sec key - receive_secret(derived_sec.data, offset); + receive_secret(derived_sec.data(), offset); #ifdef DEBUG_HWDEVICE crypto::secret_key derived_sec_clear = decrypt(derived_sec); - check32("derive_secret_key", "derived_sec", derived_sec_x.data, derived_sec_clear.data); + check32("derive_secret_key", "derived_sec", derived_sec_x.data(), derived_sec_clear.data()); #endif return true; @@ -1219,29 +1219,29 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::key_derivation derivation_x = decrypt(derivation); - log_hexbuffer("derive_public_key: [[IN]] derivation ", derivation_x.data, 32); + log_hexbuffer("derive_public_key: [[IN]] derivation ", derivation_x.data(), 32); log_message ("derive_public_key: [[IN]] output_index", std::to_string(output_index)); - log_hexbuffer("derive_public_key: [[IN]] pub ", pub.data, 32); + log_hexbuffer("derive_public_key: [[IN]] pub ", pub.data(), 32); crypto::public_key derived_pub_x; debug_device->derive_public_key(derivation_x, output_index, pub, derived_pub_x); - log_hexbuffer("derive_public_key: [[OUT]] derived_pub ", derived_pub_x.data, 32); + log_hexbuffer("derive_public_key: [[OUT]] derived_pub ", derived_pub_x.data(), 32); #endif int offset = set_command_header_noopt(INS_DERIVE_PUBLIC_KEY); //derivation - send_secret(derivation.data, offset); + send_secret(derivation.data(), offset); //index send_u32(output_index, offset); //pub - send_bytes(pub.data, 32, offset); + send_bytes(pub.data(), 32, offset); finish_and_exchange(offset); //pub key - receive_bytes(derived_pub.data, 32); + receive_bytes(derived_pub.data(), 32); #ifdef DEBUG_HWDEVICE - check32("derive_public_key", "derived_pub", derived_pub_x.data, derived_pub.data); + check32("derive_public_key", "derived_pub", derived_pub_x.data(), derived_pub.data()); #endif return true; @@ -1252,10 +1252,10 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = decrypt(sec); - log_hexbuffer("secret_key_to_public_key: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("secret_key_to_public_key: [[IN]] sec ", sec_x.data(), 32); crypto::public_key pub_x; bool rc = debug_device->secret_key_to_public_key(sec_x, pub_x); - log_hexbuffer("secret_key_to_public_key: [[OUT]] pub", pub_x.data, 32); + log_hexbuffer("secret_key_to_public_key: [[OUT]] pub", pub_x.data(), 32); if (!rc){ log_message("FAIL secret_key_to_public_key", "secret_key rejected"); } @@ -1263,15 +1263,15 @@ namespace hw::ledger { int offset = set_command_header_noopt(INS_SECRET_KEY_TO_PUBLIC_KEY); //sec key - send_secret(sec.data, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); //pub key - receive_bytes(pub.data, 32); + receive_bytes(pub.data(), 32); #ifdef DEBUG_HWDEVICE - check32("secret_key_to_public_key", "pub", pub_x.data, pub.data); + check32("secret_key_to_public_key", "pub", pub_x.data(), pub.data()); #endif return true; @@ -1282,26 +1282,26 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::secret_key sec_x = decrypt(sec); - log_hexbuffer("generate_key_image: [[IN]] pub ", pub.data, 32); - log_hexbuffer("generate_key_image: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("generate_key_image: [[IN]] pub ", pub.data(), 32); + log_hexbuffer("generate_key_image: [[IN]] sec ", sec_x.data(), 32); crypto::key_image image_x; debug_device->generate_key_image(pub, sec_x, image_x); - log_hexbuffer("generate_key_image: [[OUT]] image ", image_x.data, 32); + log_hexbuffer("generate_key_image: [[OUT]] image ", image_x.data(), 32); #endif int offset = set_command_header_noopt(INS_GEN_KEY_IMAGE); //pub - send_bytes(pub.data, 32, offset); + send_bytes(pub.data(), 32, offset); //sec - send_secret(sec.data, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); //key image - receive_bytes(image.data, 32); + receive_bytes(image.data(), 32); #ifdef DEBUG_HWDEVICE - check32("generate_key_image", "image", image_x.data, image.data); + check32("generate_key_image", "image", image_x.data(), image.data()); #endif return true; @@ -1311,9 +1311,9 @@ namespace hw::ledger { auto locks = tools::unique_locks(device_locker, command_locker); int offset = set_command_header_noopt(INS_GEN_KEY_IMAGE_SIGNATURE); - send_bytes(image.data, 32, offset); - send_bytes(pub.data, 32, offset); - send_secret(sec.data, offset); + send_bytes(image.data(), 32, offset); + send_bytes(pub.data(), 32, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); @@ -1323,10 +1323,10 @@ namespace hw::ledger { // We can't check the actual returned signature byte values because a random component is // involved, but we *can* attempt to verify the signature bool good = crypto::check_key_image_signature(image, pub, sig); - log_hexbuffer("generate_key_image_signature: key image", image.data, 32); - log_hexbuffer("generate_key_image_signature: pubkey", pub.data, 32); - log_hexbuffer("generate_key_image_signature: signature.c", sig.c.data, 32); - log_hexbuffer("generate_key_image_signature: signature.r", sig.r.data, 32); + log_hexbuffer("generate_key_image_signature: key image", image.data(), 32); + log_hexbuffer("generate_key_image_signature: pubkey", pub.data(), 32); + log_hexbuffer("generate_key_image_signature: signature.c", sig.c(), 32); + log_hexbuffer("generate_key_image_signature: signature.r", sig.r(), 32); log_message("generate_key_image_signature: signature returned from device", good ? "passed" : "FAILED"); #endif @@ -1337,9 +1337,9 @@ namespace hw::ledger { auto locks = tools::unique_locks(device_locker, command_locker); #ifdef DEBUG_HWDEVICE - log_hexbuffer("generate_unlock_signature: [[IN]] pub ", pub.data, 32); + log_hexbuffer("generate_unlock_signature: [[IN]] pub ", pub.data(), 32); const crypto::secret_key sec_x = decrypt(sec); - log_hexbuffer("generate_unlock_signature: [[IN]] sec ", sec_x.data, 32); + log_hexbuffer("generate_unlock_signature: [[IN]] sec ", sec_x.data(), 32); #endif // Ask for confirmation: @@ -1348,8 +1348,8 @@ namespace hw::ledger { // If we got permission then we can ask for the actual signature: offset = set_command_header_noopt(INS_GEN_UNLOCK_SIGNATURE, 1); - send_bytes(pub.data, 32, offset); - send_secret(sec.data, offset); + send_bytes(pub.data(), 32, offset); + send_secret(sec.data(), offset); finish_and_exchange(offset); receive_bytes(reinterpret_cast(&sig), 64); @@ -1358,8 +1358,8 @@ namespace hw::ledger { // We can't check the actual returned signature byte values because a random component is // involved, but we *can* attempt to verify the signature bool good = crypto::check_signature(cryptonote::tx_extra_tx_key_image_unlock::HASH, pub, sig); - log_hexbuffer("generate_unlock_signature: signature.c", sig.c.data, 32); - log_hexbuffer("generate_unlock_signature: signature.r", sig.r.data, 32); + log_hexbuffer("generate_unlock_signature: signature.c", sig.c(), 32); + log_hexbuffer("generate_unlock_signature: signature.r", sig.r(), 32); log_message("generate_unlock_signature: signature returned from device", good ? "passed" : "FAILED"); #endif @@ -1402,39 +1402,39 @@ namespace hw::ledger { const crypto::public_key D_x = D; const crypto::secret_key r_x = decrypt(r); crypto::signature sig_x; - log_hexbuffer("generate_tx_proof: [[IN]] prefix_hash ", prefix_hash_x.data, 32); - log_hexbuffer("generate_tx_proof: [[IN]] R ", R_x.data, 32); - log_hexbuffer("generate_tx_proof: [[IN]] A ", A_x.data, 32); + log_hexbuffer("generate_tx_proof: [[IN]] prefix_hash ", prefix_hash_x.data(), 32); + log_hexbuffer("generate_tx_proof: [[IN]] R ", R_x.data(), 32); + log_hexbuffer("generate_tx_proof: [[IN]] A ", A_x.data(), 32); if (B_x) - log_hexbuffer("generate_tx_proof: [[IN]] B ", B_x->data, 32); - log_hexbuffer("generate_tx_proof: [[IN]] D ", D_x.data, 32); - log_hexbuffer("generate_tx_proof: [[IN]] r ", r_x.data, 32); + log_hexbuffer("generate_tx_proof: [[IN]] B ", B_x->data(), 32); + log_hexbuffer("generate_tx_proof: [[IN]] D ", D_x.data(), 32); + log_hexbuffer("generate_tx_proof: [[IN]] r ", r_x.data(), 32); #endif int offset = set_command_header(INS_GET_TX_PROOF); //options buffer_send[offset++] = B ? 0x01 : 0x00; - send_bytes(prefix_hash.data, 32, offset); // prefix_hash - send_bytes(R.data, 32, offset); // R - send_bytes(A.data, 32, offset); // A - send_bytes(B ? B->data : crypto::null_pkey.data, 32, offset); // B - send_bytes(D.data, 32, offset); // D - send_secret(r.data, offset); // r + send_bytes(prefix_hash.data(), 32, offset); // prefix_hash + send_bytes(R.data(), 32, offset); // R + send_bytes(A.data(), 32, offset); // A + send_bytes(B ? B->data() : crypto::null.data(), 32, offset); // B + send_bytes(D.data(), 32, offset); // D + send_secret(r.data(), offset); // r finish_and_exchange(offset); offset = 0; - receive_bytes(sig.c.data, 32, offset); - receive_bytes(sig.r.data, 32, offset); + receive_bytes(sig.c(), 32, offset); + receive_bytes(sig.r(), 32, offset); #ifdef DEBUG_HWDEVICE - log_hexbuffer("GENERATE_TX_PROOF: **c** ", sig.c.data, sizeof(sig.c.data)); - log_hexbuffer("GENERATE_TX_PROOF: **r** ", sig.r.data, sizeof(sig.r.data)); + log_hexbuffer("GENERATE_TX_PROOF: **c** ", sig.c(), 32); + log_hexbuffer("GENERATE_TX_PROOF: **r** ", sig.r(), 32); debug_device->generate_tx_proof(prefix_hash_x, R_x, A_x, B_x, D_x, r_x, sig_x); log::debug(logcat, "FAIL is normal if random is not fixed in proof"); - check32("generate_tx_proof", "c", sig_x.c.data, sig.c.data); - check32("generate_tx_proof", "r", sig_x.r.data, sig.r.data); + check32("generate_tx_proof", "c", sig_x.c(), sig.c()); + check32("generate_tx_proof", "r", sig_x.r(), sig.r()); #endif } @@ -1455,14 +1455,14 @@ namespace hw::ledger { //skip R, receive: r, r_hmac, fake_a, a_hmac, fake_b, hmac_b unsigned char tmp[32]; offset = 32; - receive_secret(tx_key.data, offset); + receive_secret(tx_key.data(), offset); receive_secret(tmp, offset); receive_secret(tmp, offset); #ifdef DEBUG_HWDEVICE const crypto::secret_key r_x = decrypt(tx_key); log_hexbuffer("open_tx: [[OUT]] R ", buffer_recv, 32); - log_hexbuffer("open_tx: [[OUT]] r ", r_x.data, 32); + log_hexbuffer("open_tx: [[OUT]] r ", r_x.data(), 32); #endif return true; } @@ -1509,7 +1509,9 @@ namespace hw::ledger { try { tx_prefix = serialization::dump_binary(const_cast(tx)); } catch (const std::exception& e) { - ASSERT_MES_AND_THROW("unable to serialize transaction prefix: " << e.what()); + auto err = "unable to serialize transaction prefix: "_format(e.what()); + log::error(logcat, err); + throw std::runtime_error{err}; } unsigned char* send = buffer_send + set_command_header_noopt(INS_PREFIX_HASH, 1); @@ -1533,10 +1535,10 @@ namespace hw::ledger { // hash the full prefix exchange_multipart_data(INS_PREFIX_HASH, 2, tx_prefix, KECCAK_HASH_CHUNK_SIZE); - receive_bytes(h.data, 32); + receive_bytes(h.data(), 32); #ifdef DEBUG_HWDEVICE - check8("prefix_hash", "h", h_x.data, h.data); + check8("prefix_hash", "h", h_x.data(), h.data()); #endif } @@ -1545,24 +1547,24 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE const crypto::secret_key secret_key_x = decrypt(secret_key); - log_hexbuffer("encrypt_payment_id: [[IN]] payment_id ", payment_id.data, 32); - log_hexbuffer("encrypt_payment_id: [[IN]] public_key ", public_key.data, 32); - log_hexbuffer("encrypt_payment_id: [[IN]] secret_key ", secret_key_x.data, 32); + log_hexbuffer("encrypt_payment_id: [[IN]] payment_id ", payment_id.data(), 32); + log_hexbuffer("encrypt_payment_id: [[IN]] public_key ", public_key.data(), 32); + log_hexbuffer("encrypt_payment_id: [[IN]] secret_key ", secret_key_x.data(), 32); crypto::hash8 payment_id_x = payment_id; debug_device->encrypt_payment_id(payment_id_x, public_key, secret_key_x); - log_hexbuffer("encrypt_payment_id: [[OUT]] payment_id ", payment_id_x.data, 32); + log_hexbuffer("encrypt_payment_id: [[OUT]] payment_id ", payment_id_x.data(), 32); #endif int offset = set_command_header_noopt(INS_ENCRYPT_PAYMENT_ID); - send_bytes(public_key.data, 32, offset); // pub - send_secret(secret_key.data, offset); //sec - send_bytes(payment_id.data, 8, offset); //id + send_bytes(public_key.data(), 32, offset); // pub + send_secret(secret_key.data(), offset); //sec + send_bytes(payment_id.data(), 8, offset); //id finish_and_exchange(offset); - receive_bytes(payment_id.data, 8); + receive_bytes(payment_id.data(), 8); #ifdef DEBUG_HWDEVICE - check8("stealth", "payment_id", payment_id_x.data, payment_id.data); + check8("stealth", "payment_id", payment_id_x.data(), payment_id.data()); #endif return true; @@ -1588,7 +1590,7 @@ namespace hw::ledger { #ifdef DEBUG_HWDEVICE cryptonote::account_keys sender_account_keys_x = decrypt(sender_account_keys); - std::memmove(sender_account_keys_x.m_view_secret_key.data, dbg_viewkey.data, 32); + std::memmove(sender_account_keys_x.m_view_secret_key.data(), dbg_viewkey.data(), 32); const crypto::secret_key tx_key_x = decrypt(tx_key); @@ -1598,20 +1600,20 @@ namespace hw::ledger { } log_message("generate_output_ephemeral_keys: [[IN]] tx_version", std::to_string(tx_version)); - //log_hexbuffer("generate_output_ephemeral_keys: [[IN]] sender_account_keys.view", sender_account_keys.m_sview_secret_key.data, 32); - //log_hexbuffer("generate_output_ephemeral_keys: [[IN]] sender_account_keys.spend", sender_account_keys.m_spend_secret_key.data, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] txkey_pub", txkey_pub.data, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] tx_key", tx_key_x.data, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] dst_entr.view", dst_entr.addr.m_view_public_key.data, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] dst_entr.spend", dst_entr.addr.m_spend_public_key.data, 32); + //log_hexbuffer("generate_output_ephemeral_keys: [[IN]] sender_account_keys.view", sender_account_keys.m_sview_secret_key.data(), 32); + //log_hexbuffer("generate_output_ephemeral_keys: [[IN]] sender_account_keys.spend", sender_account_keys.m_spend_secret_key.data(), 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] txkey_pub", txkey_pub.data(), 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] tx_key", tx_key_x.data(), 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] dst_entr.view", dst_entr.addr.m_view_public_key.data(), 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] dst_entr.spend", dst_entr.addr.m_spend_public_key.data(), 32); if (change_addr) { - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] change_addr.view", change_addr->addr.m_view_public_key.data, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] change_addr.spend", change_addr->addr.m_spend_public_key.data, 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] change_addr.view", change_addr->addr.m_view_public_key.data(), 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] change_addr.spend", change_addr->addr.m_spend_public_key.data(), 32); } log_message("generate_output_ephemeral_keys: [[IN]] output_index", std::to_string(output_index)); log_message("generate_output_ephemeral_keys: [[IN]] need_additional_txkeys", std::to_string(need_additional_txkeys)); if (need_additional_txkeys) { - log_hexbuffer("generate_output_ephemeral_keys: [[IN]] additional_tx_keys[oi]", additional_tx_keys_x[output_index].data, 32); + log_hexbuffer("generate_output_ephemeral_keys: [[IN]] additional_tx_keys[oi]", additional_tx_keys_x[output_index].data(), 32); } std::vector additional_tx_public_keys_x; std::vector amount_keys_x; @@ -1619,10 +1621,10 @@ namespace hw::ledger { debug_device->generate_output_ephemeral_keys(tx_version, found_change, sender_account_keys_x, txkey_pub, tx_key_x, dst_entr, change_addr, output_index, need_additional_txkeys, additional_tx_keys_x, additional_tx_public_keys_x, amount_keys_x, out_eph_public_key_x); if(need_additional_txkeys) { - log_hexbuffer("additional_tx_public_keys_x: [[OUT]] additional_tx_public_keys_x", additional_tx_public_keys_x.back().data, 32); + log_hexbuffer("additional_tx_public_keys_x: [[OUT]] additional_tx_public_keys_x", additional_tx_public_keys_x.back().data(), 32); } log_hexbuffer("generate_output_ephemeral_keys: [[OUT]] amount_keys ", amount_keys_x.back().bytes, 32); - log_hexbuffer("generate_output_ephemeral_keys: [[OUT]] out_eph_public_key ", out_eph_public_key_x.data, 32); + log_hexbuffer("generate_output_ephemeral_keys: [[OUT]] out_eph_public_key ", out_eph_public_key_x.data(), 32); #endif CHECK_AND_ASSERT_THROW_MES(tx_version > 1, "TX version not supported"<=32, "Not enough data from device"); crypto::secret_key scalar1; - receive_secret(scalar1.data, offset); + receive_secret(scalar1.data(), offset); amount_keys.push_back(rct::sk2rct(scalar1)); recv_len -= 32; } CHECK_AND_ASSERT_THROW_MES(recv_len>=32, "Not enough data from device"); - receive_bytes(out_eph_public_key.data, 32, offset); + receive_bytes(out_eph_public_key.data(), 32, offset); recv_len -= 32; if (need_additional_txkeys) { CHECK_AND_ASSERT_THROW_MES(recv_len>=32, "Not enough data from device"); - receive_bytes(additional_txkey.pub.data, 32, offset); + receive_bytes(additional_txkey.pub.data(), 32, offset); additional_tx_public_keys.push_back(additional_txkey.pub); recv_len -= 32; } @@ -1687,9 +1689,9 @@ namespace hw::ledger { log_hexbuffer("generate_output_ephemeral_keys: clear amount_key", amount_back.bytes, 32); check32("generate_output_ephemeral_keys", "amount_key", amount_keys_x.back().bytes, amount_back.bytes); if (need_additional_txkeys) { - check32("generate_output_ephemeral_keys", "additional_tx_key", additional_tx_public_keys_x.back().data, additional_tx_public_keys.back().data); + check32("generate_output_ephemeral_keys", "additional_tx_key", additional_tx_public_keys_x.back().data(), additional_tx_public_keys.back().data()); } - check32("generate_output_ephemeral_keys", "out_eph_public_key", out_eph_public_key_x.data, out_eph_public_key.data); + check32("generate_output_ephemeral_keys", "out_eph_public_key", out_eph_public_key_x.data(), out_eph_public_key.data()); #endif return true; @@ -1841,10 +1843,10 @@ namespace hw::ledger { send_secret(outKeys.AKout.bytes, offset); //AKout send_bytes(&data[C_offset], 32, offset); //C C_offset += 32; - send_bytes(crypto::null_hash.data, 32, offset); // k + send_bytes(crypto::null.data(), 32, offset); // k send_bytes(&data[kv_offset], 8, offset); // v kv_offset += 8; - send_bytes(crypto::null_hash.data, 24, offset); // v padding + send_bytes(crypto::null.data(), 24, offset); // v padding // check transaction user input CHECK_AND_ASSERT_THROW_MES(finish_and_exchange(offset, true) == SW_OK, "Transaction denied on device."); @@ -1983,7 +1985,7 @@ namespace hw::ledger { // This will fail if this isn't an open stake tx. send_simple(INS_GET_TX_SECRET_KEY); // The ledger provides us with the (unencrypted) tx secret key if we're allowed to have it - receive_bytes(key.data, 32); + receive_bytes(key.data(), 32); return true; } diff --git a/src/mnemonics/electrum-words.cpp b/src/mnemonics/electrum-words.cpp index f460591d4..054959681 100644 --- a/src/mnemonics/electrum-words.cpp +++ b/src/mnemonics/electrum-words.cpp @@ -371,7 +371,7 @@ namespace * \param language_name Seed language name * \return true if successful false if not. Unsuccessful if wrong key size. */ - bool bytes_to_words(const char *src, size_t len, epee::wipeable_string& words, + bool bytes_to_words(const unsigned char *src, size_t len, epee::wipeable_string& words, const std::string &language_name) { @@ -424,14 +424,14 @@ namespace bool bytes_to_words(const crypto::secret_key& src, epee::wipeable_string& words, const std::string &language_name) { - return bytes_to_words(src.data, sizeof(src), words, language_name); + return bytes_to_words(src.data(), src.size(), words, language_name); } std::string bytes_to_words(const crypto::secret_key& src, const std::string &language_name) { epee::wipeable_string epee_words; - if (!bytes_to_words(src.data, sizeof(src), epee_words, language_name)) + if (!bytes_to_words(src.data(), src.size(), epee_words, language_name)) throw std::runtime_error("Failed to create seed from key for language: " + language_name); return std::string(epee_words.view()); } diff --git a/src/mnemonics/electrum-words.h b/src/mnemonics/electrum-words.h index 2b33ecf5c..e922d1b0c 100644 --- a/src/mnemonics/electrum-words.h +++ b/src/mnemonics/electrum-words.h @@ -91,7 +91,7 @@ namespace crypto * \param language_name Seed language name * \return true if successful false if not. Unsuccessful if wrong key size. */ - bool bytes_to_words(const char *src, size_t len, epee::wipeable_string& words, + bool bytes_to_words(const unsigned char *src, size_t len, epee::wipeable_string& words, const std::string &language_name); /*! diff --git a/src/multisig/multisig.cpp b/src/multisig/multisig.cpp index 16bc2880d..2043b9f90 100644 --- a/src/multisig/multisig.cpp +++ b/src/multisig/multisig.cpp @@ -81,7 +81,7 @@ namespace cryptonote crypto::secret_key msk = get_multisig_blinded_secret_key(rct::rct2sk(sk)); memwipe(&sk, sizeof(sk)); multisig_keys.push_back(msk); - sc_add(spend_skey.bytes, spend_skey.bytes, (const unsigned char*)msk.data); + sc_add(spend_skey.bytes, spend_skey.bytes, msk.data()); } } //----------------------------------------------------------------- @@ -103,7 +103,7 @@ namespace cryptonote rct::key secret_key = rct::zero(); for (const auto &k: multisig_keys) { - sc_add(secret_key.bytes, secret_key.bytes, (const unsigned char*)k.data); + sc_add(secret_key.bytes, secret_key.bytes, k.data()); } return rct::rct2sk(secret_key); @@ -126,7 +126,7 @@ namespace cryptonote { crypto::secret_key view_skey = get_multisig_blinded_secret_key(skey); for (const auto &k: skeys) - sc_add(reinterpret_cast(view_skey.data), rct::sk2rct(view_skey).bytes, rct::sk2rct(k).bytes); + sc_add(view_skey.data(), rct::sk2rct(view_skey).bytes, rct::sk2rct(k).bytes); return view_skey; } //----------------------------------------------------------------- diff --git a/src/ringct/rctOps.h b/src/ringct/rctOps.h index 679ed1441..f71fec341 100644 --- a/src/ringct/rctOps.h +++ b/src/ringct/rctOps.h @@ -37,8 +37,6 @@ #include #include -#include "crypto/generic-ops.h" - extern "C" { #include "crypto/random.h" #include "crypto/keccak.h" diff --git a/src/ringct/rctSigs.h b/src/ringct/rctSigs.h index f7f62e39d..44bf10497 100644 --- a/src/ringct/rctSigs.h +++ b/src/ringct/rctSigs.h @@ -36,8 +36,6 @@ #include #include -#include "crypto/generic-ops.h" - extern "C" { #include "crypto/random.h" #include "crypto/keccak.h" diff --git a/src/ringct/rctTypes.h b/src/ringct/rctTypes.h index 4cebd028c..da57321ee 100644 --- a/src/ringct/rctTypes.h +++ b/src/ringct/rctTypes.h @@ -40,7 +40,6 @@ extern "C" { #include "crypto/random.h" #include "crypto/keccak.h" } -#include "crypto/generic-ops.h" #include "crypto/crypto.h" #include "common/hex.h" diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index aca8d5eff..91bcd7e93 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -347,8 +347,7 @@ namespace cryptonote::rpc { res.blocks.back().txs.reserve(bd.second.size()); for (auto& [txhash, txdata] : bd.second) { - auto& entry = res.blocks.back().txs.emplace_back(std::move(txdata), crypto::null_hash); - size += entry.size(); + size += res.blocks.back().txs.emplace_back(std::move(txdata)).size(); } const size_t n_txes_to_lookup = bd.second.size() + (req.no_miner_tx ? 0 : 1); @@ -876,7 +875,7 @@ namespace cryptonote::rpc { // If the transaction was pruned then the prunable part will be empty but the prunable hash // will be non-null. (Some txes, like coinbase txes, are non-prunable and will have empty // *and* null prunable hash). - bool prunable = prunable_hash != crypto::null_hash; + bool prunable = (bool) prunable_hash; bool pruned = prunable && prunable_data.empty(); if (pruned || (prunable && (get.request.split || get.request.prune))) @@ -1972,8 +1971,8 @@ namespace cryptonote::rpc { std::mutex mutex; std::vector cached_distribution; std::uint64_t cached_from = 0, cached_to = 0, cached_start_height = 0, cached_base = 0; - crypto::hash cached_m10_hash = crypto::null_hash; - crypto::hash cached_top_hash = crypto::null_hash; + crypto::hash cached_m10_hash{}; + crypto::hash cached_top_hash{}; bool cached = false; } output_dist_cache; } @@ -1991,7 +1990,7 @@ namespace cryptonote::rpc { auto& d = output_dist_cache; const std::unique_lock lock{d.mutex}; - crypto::hash top_hash = crypto::null_hash; + crypto::hash top_hash{}; if (d.cached_to < blockchain_height) top_hash = get_hash(d.cached_to); if (d.cached && amount == 0 && d.cached_from == from_height && d.cached_to == to_height && d.cached_top_hash == top_hash) @@ -2013,7 +2012,7 @@ namespace cryptonote::rpc { { d.cached_to -= 10; d.cached_top_hash = hash10; - d.cached_m10_hash = crypto::null_hash; + d.cached_m10_hash = crypto::null; CHECK_AND_ASSERT_MES(d.cached_distribution.size() >= 10, std::nullopt, "Cached distribution size does not match cached bounds"); for (int p = 0; p < 10; ++p) d.cached_distribution.pop_back(); @@ -2051,7 +2050,7 @@ namespace cryptonote::rpc { d.cached_from = from_height; d.cached_to = to_height; d.cached_top_hash = get_hash(d.cached_to); - d.cached_m10_hash = d.cached_to >= 10 ? get_hash(d.cached_to - 10) : crypto::null_hash; + d.cached_m10_hash = d.cached_to >= 10 ? get_hash(d.cached_to - 10) : crypto::null; d.cached_distribution = distribution; d.cached_start_height = start_height; d.cached_base = base; @@ -2368,10 +2367,10 @@ namespace cryptonote::rpc { void core_rpc_server::invoke(GET_SERVICE_PRIVKEYS& get_service_privkeys, rpc_context context) { const auto& keys = m_core.get_service_keys(); - if (keys.key != crypto::null_skey) - get_service_privkeys.response["service_node_privkey"] = tools::type_to_hex(keys.key.data); - get_service_privkeys.response["service_node_ed25519_privkey"] = tools::type_to_hex(keys.key_ed25519.data); - get_service_privkeys.response["service_node_x25519_privkey"] = tools::type_to_hex(keys.key_x25519.data); + if (keys.key) + get_service_privkeys.response["service_node_privkey"] = tools::type_to_hex(keys.key); + get_service_privkeys.response["service_node_ed25519_privkey"] = tools::type_to_hex(keys.key_ed25519); + get_service_privkeys.response["service_node_x25519_privkey"] = tools::type_to_hex(keys.key_x25519); get_service_privkeys.response["status"] = STATUS_OK; return; } diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index e7a64fe32..66d0ad4bf 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -1823,7 +1823,7 @@ namespace cryptonote::rpc { /// If specified then only return results if the current top block hash is different than the /// hash given here. This is intended to allow quick polling of results without needing to do /// anything if the block (and thus SN registrations) have not changed since the last request. - crypto::hash poll_block_hash = crypto::hash::null(); + crypto::hash poll_block_hash{}; } request; }; diff --git a/src/rpc/lmq_server.cpp b/src/rpc/lmq_server.cpp index b4a350bd7..b3f193ebb 100644 --- a/src/rpc/lmq_server.cpp +++ b/src/rpc/lmq_server.cpp @@ -174,7 +174,7 @@ omq_rpc::omq_rpc(cryptonote::core& core, core_rpc_server& rpc, const boost::prog { crypto::x25519_public_key my_pubkey; const std::string& pk = omq.get_pubkey(); - std::copy(pk.begin(), pk.end(), my_pubkey.data); + std::copy(pk.begin(), pk.end(), my_pubkey.data()); auth.emplace(std::move(my_pubkey), AuthLevel::admin); } @@ -311,7 +311,7 @@ void omq_rpc::send_block_notifications(const block& block) auto& omq = core_.get_omq(); std::string height = "{}"_format(get_block_height(block)); send_notifies(subs_mutex_, block_subs_, "block", [&](auto& conn, auto& sub) { - omq.send(conn, "notify.block", height, std::string_view{block.hash.data, sizeof(block.hash.data)}); + omq.send(conn, "notify.block", height, tools::view_guts(block.hash)); }); } @@ -320,7 +320,7 @@ void omq_rpc::send_mempool_notifications(const crypto::hash& id, const transacti auto& omq = core_.get_omq(); send_notifies(subs_mutex_, mempool_subs_, "mempool", [&](auto& conn, auto& sub) { if (sub.type == mempool_sub_type::all || opts.approved_blink) - omq.send(conn, "notify.mempool", std::string_view{id.data, sizeof(id.data)}, blob); + omq.send(conn, "notify.mempool", tools::view_guts(id), blob); }); } @@ -413,7 +413,7 @@ void omq_rpc::on_get_blocks(oxenmq::Message& m) return; } - block_bt["hash"] = std::string_view{hash.data, sizeof(hash.data)}; + block_bt["hash"] = tools::view_guts(hash); block_bt["height"] = i; block_bt["timestamp"] = b.timestamp; @@ -442,7 +442,7 @@ void omq_rpc::on_get_blocks(oxenmq::Message& m) } tx_bt["global_indices"] = bt_list(indices.begin(), indices.end()); - tx_bt["hash"] = std::string{miner_tx_hash.data, sizeof(miner_tx_hash.data)}; + tx_bt["hash"] = std::string{tools::view_guts(miner_tx_hash)}; tx_bt["tx"] = tx_to_blob(b.miner_tx); tx_list_bt.push_back(std::move(tx_bt)); @@ -463,7 +463,7 @@ void omq_rpc::on_get_blocks(oxenmq::Message& m) } tx_bt["global_indices"] = bt_list(indices.begin(), indices.end()); - tx_bt["hash"] = std::string{txhash.data, sizeof(txhash.data)}; + tx_bt["hash"] = std::string{tools::view_guts(txhash)}; tx_bt["tx"] = std::move(txs[tx_index]); tx_list_bt.push_back(std::move(tx_bt)); diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 537401a32..a7b48a866 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -523,7 +523,7 @@ namespace } catch (const tools::error::tx_rejected& e) { - fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx())).str(); + fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % "{}"_format(get_transaction_hash(e.tx()))).str(); std::string reason = e.reason(); if (!reason.empty()) fail_msg_writer() << sw::tr("Reason: ") << reason; @@ -585,9 +585,8 @@ namespace void print_secret_key(const crypto::secret_key &k) { - std::string_view data{k.data, sizeof(k.data)}; std::ostream_iterator osi{std::cout}; - oxenc::to_hex(data.begin(), data.end(), osi); + oxenc::to_hex(k.begin(), k.end(), osi); } bool long_payment_id_failure(bool ret) @@ -3551,7 +3550,7 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) { crypto::secret_key key; crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key, crypto::cn_slow_hash_type::heavy_v1); - sc_reduce32((unsigned char*)key.data); + sc_reduce32(key.data()); multisig_keys = m_wallet->decrypt(std::string(multisig_keys.data(), multisig_keys.size()), key, true); } else @@ -4795,7 +4794,7 @@ void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, parse_tx_extra(tx.extra, tx_extra_fields); // failure ok tx_extra_nonce extra_nonce; tx_extra_pub_key extra_pub_key; - crypto::hash8 payment_id8 = crypto::null_hash8; + crypto::hash8 payment_id8{}; if (find_tx_extra_field_by_type(tx_extra_fields, extra_pub_key)) { const crypto::public_key &tx_pub_key = extra_pub_key.pub_key; @@ -4808,11 +4807,11 @@ void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, } } - if (payment_id8 != crypto::null_hash8) + if (payment_id8) message_writer() << tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead"); - crypto::hash payment_id = crypto::null_hash; + crypto::hash payment_id{}; if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) message_writer(fmt::terminal_color::red) << tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead."); @@ -5227,7 +5226,11 @@ bool simple_wallet::show_incoming_transfers(const std::vector& args } std::string extra_string; if (verbose) - extra_string += (boost::format("%68s%68s") % td.get_public_key() % (td.m_key_image_known ? tools::type_to_hex(td.m_key_image) : td.m_key_image_partial ? (tools::type_to_hex(td.m_key_image) + "/p") : std::string(64, '?'))).str(); + extra_string += "{:68}{:68}"_format( + td.get_public_key(), + (td.m_key_image_known ? tools::type_to_hex(td.m_key_image) : + td.m_key_image_partial ? tools::type_to_hex(td.m_key_image) + "/p" : + std::string(64, '?'))); if (uses) { std::vector heights; @@ -5242,15 +5245,15 @@ bool simple_wallet::show_incoming_transfers(const std::vector& args extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second; } message_writer(td.m_spent ? fmt::terminal_color::magenta : fmt::terminal_color::green) << - boost::format("%21s%8s%12s%8s%16u%68s%16u%s") % - print_money(td.amount()) % - (td.m_spent ? tr("T") : tr("F")) % - (m_wallet->frozen(td) ? tr("[frozen]") : m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) % - (td.is_rct() ? tr("RingCT") : tr("-")) % - td.m_global_output_index % - td.m_txid % - td.m_subaddr_index.minor % - extra_string; + "{:21}{:8}{:12}{:8}{:16d}{:68s}{:16d}{}"_format( + print_money(td.amount()), + td.m_spent ? tr("T") : tr("F"), + tr(m_wallet->frozen(td) ? "[frozen]" : m_wallet->is_transfer_unlocked(td) ? "unlocked" : "locked"), + tr(td.is_rct() ? "RingCT" : "-"), + td.m_global_output_index, + td.m_txid, + td.m_subaddr_index.minor, + extra_string); ++transfers_found; } } @@ -5290,8 +5293,9 @@ bool simple_wallet::show_payments(const std::vector &args) rdln::suspend_readline pause_readline; - message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") % - tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index"); + constexpr auto payment_format = "{:68}{:68}{:12}{:21}{:16}{:16}"sv; + message_writer() << fmt::format(payment_format, + tr("payment"), tr("transaction"), tr("height"), tr("amount"), tr("unlock time"), tr("addr index")); bool payments_found = false; for(std::string arg : args) @@ -5313,14 +5317,13 @@ bool simple_wallet::show_payments(const std::vector &args) { payments_found = true; } - success_msg_writer(true) << - boost::format("%68s%68s%12s%21s%16s%16s") % - payment_id % - pd.m_tx_hash % - pd.m_block_height % - print_money(pd.m_amount) % - pd.m_unlock_time % - pd.m_subaddr_index.minor; + success_msg_writer(true) << fmt::format(payment_format, + payment_id, + pd.m_tx_hash, + pd.m_block_height, + print_money(pd.m_amount), + pd.m_unlock_time, + pd.m_subaddr_index.minor); } } else @@ -5503,7 +5506,7 @@ bool simple_wallet::process_ring_members(const std::vector spent_key_height(tx.vin.size()); std::vector spent_key_txid (tx.vin.size()); @@ -7778,7 +7781,7 @@ bool simple_wallet::accept_loaded_tx(const std::function get_num_txes, std::vector tx_extra_fields; bool has_encrypted_payment_id = false; - crypto::hash8 payment_id8 = crypto::null_hash8; + crypto::hash8 payment_id8{}; if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields)) { tx_extra_nonce extra_nonce; diff --git a/src/wallet/api/pending_transaction.cpp b/src/wallet/api/pending_transaction.cpp index 83cd82d7c..443399c2b 100644 --- a/src/wallet/api/pending_transaction.cpp +++ b/src/wallet/api/pending_transaction.cpp @@ -138,7 +138,7 @@ bool PendingTransactionImpl::commit(std::string_view filename_, bool overwrite, m_status = {Status_Error, tr("no connection to daemon. Please make sure daemon is running.")}; } catch (const tools::error::tx_rejected& e) { m_status.first = Status_Error; - m_status.second += (boost::format(tr("transaction %s was rejected by daemon with status: ")) % get_transaction_hash(e.tx())).str(); + m_status.second += (boost::format(tr("transaction %s was rejected by daemon with status: ")) % "{}"_format(get_transaction_hash(e.tx()))).str(); m_status.second += e.status(); if (auto& reason = e.reason(); !reason.empty()) m_status.second += tr(". Reason: ") + reason; diff --git a/src/wallet/api/unsigned_transaction.cpp b/src/wallet/api/unsigned_transaction.cpp index 14378b418..93a59ca36 100644 --- a/src/wallet/api/unsigned_transaction.cpp +++ b/src/wallet/api/unsigned_transaction.cpp @@ -101,7 +101,7 @@ bool UnsignedTransactionImpl::checkLoadedTx(const std::function get_nu std::vector tx_extra_fields; bool has_encrypted_payment_id = false; - crypto::hash8 payment_id8 = crypto::null_hash8; + crypto::hash8 payment_id8{}; if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields)) { cryptonote::tx_extra_nonce extra_nonce; @@ -255,24 +255,24 @@ std::vector UnsignedTransactionImpl::paymentId() const { std::vector result; for (const auto &utx: m_unsigned_tx_set.txes) { - crypto::hash payment_id = crypto::null_hash; + crypto::hash payment_id{}; cryptonote::tx_extra_nonce extra_nonce; std::vector tx_extra_fields; cryptonote::parse_tx_extra(utx.extra, tx_extra_fields); if (cryptonote::find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { - crypto::hash8 payment_id8 = crypto::null_hash8; + crypto::hash8 payment_id8{}; if(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { // We can't decrypt short pid without recipient key. - memcpy(payment_id.data, payment_id8.data, 8); + memcpy(payment_id.data(), payment_id8.data(), payment_id8.size()); } else if (!cryptonote::get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) { - payment_id = crypto::null_hash; + payment_id.zero(); } } - if(payment_id != crypto::null_hash) + if (payment_id) result.push_back(tools::type_to_hex(payment_id)); else result.push_back(""); diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index 0a8e0bba3..fc0acd508 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -50,6 +50,7 @@ #include "mnemonics/electrum-words.h" #include "mnemonics/english.h" #include +#include #include #include #include @@ -1703,7 +1704,7 @@ PendingTransaction *WalletImpl::createTransactionMultDest(const std::vector; m_messages.push_back(m); // Save for every new message right away (at least while in beta) diff --git a/src/wallet/message_store.h b/src/wallet/message_store.h index 0fb911ec5..182925b49 100644 --- a/src/wallet/message_store.h +++ b/src/wallet/message_store.h @@ -139,8 +139,8 @@ namespace mms memset(&monero_address, 0, sizeof(cryptonote::account_public_address)); me = false; index = 0; - auto_config_public_key = crypto::null_pkey; - auto_config_secret_key = crypto::null_skey; + auto_config_public_key.zero(); + auto_config_secret_key.zero(); auto_config_running = false; }; }; diff --git a/src/wallet/ringdb.cpp b/src/wallet/ringdb.cpp index 915599b96..10e83a37b 100644 --- a/src/wallet/ringdb.cpp +++ b/src/wallet/ringdb.cpp @@ -116,7 +116,7 @@ crypto::chacha_iv make_iv(const crypto::key_image &key_image, const crypto::chac memcpy(buffer + sizeof(key_image) + sizeof(key) + cryptonote::hashkey::RINGDB.size(), &field, sizeof(field)); crypto::hash hash; // if field is 0, backward compat mode: hash without the field - crypto::cn_fast_hash(buffer, sizeof(buffer) - !field, hash.data); + crypto::cn_fast_hash(buffer, sizeof(buffer) - !field, hash.data()); static_assert(sizeof(hash) >= CHACHA_IV_SIZE, "Incompatible hash and chacha IV sizes"); crypto::chacha_iv iv; memcpy(&iv, &hash, CHACHA_IV_SIZE); diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 44fd9e537..5576380de 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -560,7 +560,7 @@ std::pair, tools::password_container> generate_f if(!tools::hex_to_type(field_viewkey, viewkey)) THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to parse view key secret key")); crypto::public_key pkey; - if (viewkey == crypto::null_skey) + if (!viewkey) THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("view secret key may not be all zeroes")); if (!crypto::secret_key_to_public_key(viewkey, pkey)) { THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify view key secret key")); @@ -574,7 +574,7 @@ std::pair, tools::password_container> generate_f if(!tools::hex_to_type(field_spendkey, spendkey)) THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to parse spend key secret key")); crypto::public_key pkey; - if (spendkey == crypto::null_skey) + if (!spendkey) THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("spend secret key may not be all zeroes")); if (!crypto::secret_key_to_public_key(spendkey, pkey)) { THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify spend key secret key")); @@ -851,7 +851,7 @@ bool get_short_payment_id(crypto::hash8 &payment_id8, const tools::wallet2::pend wallet::tx_construction_data get_construction_data_with_decrypted_short_payment_id(const tools::wallet2::pending_tx &ptx, hw::device &hwdev) { wallet::tx_construction_data construction_data = ptx.construction_data; - crypto::hash8 payment_id = null_hash8; + crypto::hash8 payment_id{}; if (get_short_payment_id(payment_id, ptx, hwdev)) { // Remove encrypted @@ -1101,7 +1101,7 @@ wallet2::wallet2(network_type nettype, uint64_t kdf_rounds, bool unattended): m_multisig(false), m_multisig_threshold(0), m_node_rpc_proxy(m_http_client), - m_account_public_address{crypto::null_pkey, crypto::null_pkey}, + m_account_public_address{crypto::null, crypto::null}, m_subaddress_lookahead_major(SUBADDRESS_LOOKAHEAD_MAJOR), m_subaddress_lookahead_minor(SUBADDRESS_LOOKAHEAD_MINOR), m_original_keys_available(false), @@ -1310,7 +1310,7 @@ bool wallet2::is_deterministic() const crypto::secret_key second; keccak((uint8_t *)&get_account().get_keys().m_spend_secret_key, sizeof(crypto::secret_key), (uint8_t *)&second, sizeof(crypto::secret_key)); sc_reduce32((uint8_t *)&second); - return memcmp(second.data,get_account().get_keys().m_view_secret_key.data, sizeof(crypto::secret_key)) == 0; + return second == get_account().get_keys().m_view_secret_key; } //---------------------------------------------------------------------------------------------------- bool wallet2::get_seed(epee::wipeable_string& electrum_words, const epee::wipeable_string &passphrase) const @@ -1382,7 +1382,7 @@ bool wallet2::get_multisig_seed(epee::wipeable_string& seed, const epee::wipeabl { crypto::secret_key key; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), (crypto::hash&)key, crypto::cn_slow_hash_type::heavy_v1); - sc_reduce32((unsigned char*)key.data); + sc_reduce32(key.data()); data = encrypt(data.view(), key, true); } @@ -1394,7 +1394,7 @@ bool wallet2::get_multisig_seed(epee::wipeable_string& seed, const epee::wipeabl } else { - if (!crypto::ElectrumWords::bytes_to_words(data.data(), data.size(), seed, seed_language)) + if (!crypto::ElectrumWords::bytes_to_words(reinterpret_cast(data.data()), data.size(), seed, seed_language)) { std::cout << "Failed to encode seed"; return false; @@ -1772,7 +1772,7 @@ void wallet2::scan_output(const cryptonote::transaction &tx, bool miner_tx, cons if (m_multisig) { tx_scan_info.in_ephemeral.pub = var::get(tx.vout[vout_index].target).key; - tx_scan_info.in_ephemeral.sec = crypto::null_skey; + tx_scan_info.in_ephemeral.sec.zero(); tx_scan_info.ki = rct::rct2ki(rct::zero()); } else @@ -1874,7 +1874,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote // i.e. duplicated key images std::vector tx_money_got_in_outs; tx_money_got_in_outs.reserve(tx.vout.size()); - crypto::public_key tx_pub_key = null_pkey; + crypto::public_key tx_pub_key = crypto::null; bool notify = false; std::vector local_tx_extra_fields; @@ -2426,19 +2426,19 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote just_confirmed->m_change = sub_change; // create payment_details for each incoming transfer to a subaddress index - crypto::hash payment_id = null_hash; + crypto::hash payment_id{}; if (tx_money_got_in_outs.size() > 0 || earliest_blink_got_mined_transfers_index != NO_BLINK_MINED_INDEX) { tx_extra_nonce extra_nonce; if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { - crypto::hash8 payment_id8 = null_hash8; + crypto::hash8 payment_id8{}; if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { // We got a payment ID to go with this tx log::debug(logcat, "Found encrypted payment ID: {}", payment_id8); log::info(logcat, "Consider using subaddresses instead of encrypted payment IDs"); - if (tx_pub_key != null_pkey) + if (tx_pub_key) { if (!m_account.get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_account.get_keys().m_view_secret_key)) { @@ -2447,10 +2447,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote else { log::debug(logcat, "Decrypted payment ID: {}", payment_id8); - // put the 64 bit decrypted payment id in the first 8 bytes - memcpy(payment_id.data, payment_id8.data, 8); - // rest is already 0, but guard against code changes above - memset(payment_id.data + 8, 0, 24); + payment_id = payment_id8; } } else @@ -2465,7 +2462,7 @@ void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote { log::debug(logcat, "Found unencrypted payment ID in tx {} (ignored)", txid); log::warning(logcat, "Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); - payment_id = crypto::null_hash; + payment_id = null; } else { @@ -3074,7 +3071,7 @@ bool wallet2::long_poll_pool_state() THROW_WALLET_EXCEPTION_IF(res.status == rpc::STATUS_BUSY, error::daemon_busy, "get_transaction_pool_hashes.bin"); THROW_WALLET_EXCEPTION_IF(res.status != rpc::STATUS_OK, error::get_tx_pool_error, res.status); - crypto::hash checksum = crypto::null_hash; + crypto::hash checksum{}; for (crypto::hash const &hash : res.tx_hashes) checksum ^= hash; { @@ -3082,7 +3079,7 @@ bool wallet2::long_poll_pool_state() m_long_poll_tx_pool_checksum = checksum; } - return checksum != crypto::null_hash; + return (bool) checksum; } void wallet2::cancel_long_poll() @@ -3337,7 +3334,7 @@ void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, // we will drop all these, so don't bother getting them uint64_t missing_blocks = checkpoint_height - m_blockchain.size(); while (missing_blocks-- > 0) - m_blockchain.push_back(crypto::null_hash); // maybe a bit suboptimal, but deque won't do huge reallocs like vector + m_blockchain.push_back(null); // maybe a bit suboptimal, but deque won't do huge reallocs like vector m_blockchain.push_back(checkpoint_hash); m_blockchain.trim(checkpoint_height); m_cached_height = m_blockchain.size(); @@ -3399,7 +3396,7 @@ bool wallet2::add_address_book_row(const cryptonote::account_public_address &add wallet2::address_book_row a; a.m_address = address; a.m_has_payment_id = !!payment_id; - a.m_payment_id = payment_id ? *payment_id : crypto::null_hash8; + a.m_payment_id = payment_id ? *payment_id : null; a.m_description = description; a.m_is_subaddress = is_subaddress; @@ -3415,7 +3412,7 @@ bool wallet2::set_address_book_row(size_t row_id, const cryptonote::account_publ wallet2::address_book_row a; a.m_address = address; a.m_has_payment_id = !!payment_id; - a.m_payment_id = payment_id ? *payment_id : crypto::null_hash8; + a.m_payment_id = payment_id ? *payment_id : null; a.m_description = description; a.m_is_subaddress = is_subaddress; @@ -3461,7 +3458,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo blocks_fetched = 0; uint64_t added_blocks = 0; size_t try_count = 0; - crypto::hash last_tx_hash_id = m_transfers.size() ? m_transfers.back().m_txid : null_hash; + crypto::hash last_tx_hash_id = m_transfers.size() ? m_transfers.back().m_txid : null; std::list short_chain_history; tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; @@ -3623,7 +3620,7 @@ void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blo } } } - if(last_tx_hash_id != (m_transfers.size() ? m_transfers.back().m_txid : null_hash)) + if(last_tx_hash_id != (m_transfers.size() ? m_transfers.back().m_txid : null)) received_money = true; uint64_t immutable_height = 0; @@ -5048,7 +5045,7 @@ std::string wallet2::make_multisig(const epee::wipeable_string &password, auto derivations = cryptonote::generate_multisig_derivations(get_account().get_keys(), spend_keys); spend_pkey = rct::identity(); - multisig_signers = std::vector(spend_keys.size() + 1, crypto::null_pkey); + multisig_signers = std::vector(spend_keys.size() + 1, crypto::null); if (threshold == spend_keys.size()) { @@ -5364,7 +5361,7 @@ bool wallet2::unpack_extra_multisig_info(const std::vector& info, std::unordered_set &pkeys) const { // parse all multisig info - signers.resize(info.size(), crypto::null_pkey); + signers.resize(info.size(), crypto::null); for (size_t i = 0; i < info.size(); ++i) { if (!verify_extra_multisig_info(info[i], pkeys, signers[i])) @@ -5578,8 +5575,7 @@ bool wallet2::parse_payment_id(std::string_view payment_id_str, crypto::hash& pa crypto::hash8 payment_id8; if (tools::hex_to_type(payment_id_str, payment_id8)) { - payment_id = crypto::null_hash; - std::memcpy(payment_id.data, payment_id8.data, sizeof(payment_id8)); + payment_id = payment_id8; return true; } return false; @@ -6905,25 +6901,25 @@ crypto::hash wallet2::get_payment_id(const pending_tx &ptx) const std::vector tx_extra_fields; parse_tx_extra(ptx.tx.extra, tx_extra_fields); // ok if partially parsed tx_extra_nonce extra_nonce; - crypto::hash payment_id = null_hash; + crypto::hash payment_id{}; if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) { - crypto::hash8 payment_id8 = null_hash8; + crypto::hash8 payment_id8{}; if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { if (ptx.dests.empty()) { log::warning(logcat, "Encrypted payment id found, but no destinations public key, cannot decrypt"); - return crypto::null_hash; + return null; } if (m_account.get_device().decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key)) { - memcpy(payment_id.data, payment_id8.data, 8); + payment_id = payment_id8; } } else if (!get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) { - payment_id = crypto::null_hash; + payment_id = null; } } return payment_id; @@ -6975,7 +6971,7 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) crypto::hash txid; txid = get_transaction_hash(ptx.tx); - crypto::hash payment_id = crypto::null_hash; + crypto::hash payment_id{}; std::vector dests; uint64_t amount_in = 0; if (store_tx_info()) @@ -6986,7 +6982,7 @@ void wallet2::commit_tx(pending_tx& ptx, bool blink) amount_in += m_transfers[idx].amount(); } add_unconfirmed_tx(ptx.tx, amount_in, dests, payment_id, ptx.change_dts.amount, ptx.construction_data.subaddr_account, ptx.construction_data.subaddr_indices); - if (store_tx_info() && ptx.tx_key != crypto::null_skey) + if (store_tx_info() && ptx.tx_key) { m_tx_keys.insert(std::make_pair(txid, ptx.tx_key)); m_additional_tx_keys.insert(std::make_pair(txid, ptx.additional_tx_keys)); @@ -7178,7 +7174,7 @@ bool wallet2::sign_tx(unsigned_tx_set &exported_txs, std::vector bool { CHECKED_GET_SPECIFIC_VARIANT(s_e, txin_to_key, in, false); - key_images << in.k_image << ' '; + key_images << "{} "_format(in.k_image); return true; }); THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, ptx.tx); @@ -9019,7 +9015,7 @@ bool wallet2::ons_make_update_mapping_signature(ons::mapping_type type, ons_prepared_args prepared_args = prepare_tx_extra_oxen_name_system_values(*this, type, tx_priority_unimportant, name, value, owner, backup_owner, make_signature, ons::ons_tx_type::update, account_index, reason, &response); if (!prepared_args) return false; - if (prepared_args.prev_txid == crypto::null_hash) + if (!prepared_args.prev_txid) { if (reason) *reason = "name=\"" + name + std::string("\" does not have a corresponding ONS record, the mapping is available for purchase, update signature is not required."); return false; @@ -10054,7 +10050,7 @@ void wallet2::transfer_selected_rct(std::vector bool { CHECKED_GET_SPECIFIC_VARIANT(s_e, txin_to_key, in, false); - key_images << in.k_image << ' '; + key_images << "{} "_format(in.k_image); return true; }); THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, tx); @@ -10588,7 +10584,7 @@ void wallet2::light_wallet_get_address_txs() if(total_sent == 0 && total_received == 0) continue; - crypto::hash payment_id = null_hash; + crypto::hash payment_id; crypto::hash tx_hash; THROW_WALLET_EXCEPTION_IF(t.payment_id.size() != 64 || !oxenc::is_hex(t.payment_id), error::wallet_internal_error, "Invalid payment_id field"); @@ -11966,7 +11962,7 @@ bool wallet2::get_tx_key_cached(const crypto::hash &txid, crypto::secret_key &tx if (i == m_tx_keys.end()) return false; tx_key = i->second; - if (tx_key == crypto::null_skey) + if (!tx_key) return false; const auto j = m_additional_tx_keys.find(txid); if (j != m_additional_tx_keys.end()) @@ -12030,7 +12026,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); - tx_key_data.tx_prefix_hash = std::string(tx_prefix_hash.data, 32); + tx_key_data.tx_prefix_hash = std::string{reinterpret_cast(tx_prefix_hash.data()), tx_prefix_hash.size()}; } std::vector tx_keys; @@ -12041,7 +12037,7 @@ bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, s return false; } - if (tx_keys[0] == crypto::null_skey) + if (!tx_keys[0]) { return false; } @@ -12390,7 +12386,7 @@ std::string wallet2::get_tx_proof(const crypto::hash &txid, const cryptonote::ac THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); // determine if the address is found in the subaddress hash table (i.e. whether the proof is outbound or inbound) - crypto::secret_key tx_key = crypto::null_skey; + crypto::secret_key tx_key{}; std::vector additional_tx_keys; const bool is_out = m_subaddresses.count(address.m_spend_public_key) == 0; if (is_out) @@ -12458,7 +12454,7 @@ std::string wallet2::get_tx_proof(const cryptonote::transaction &tx, const crypt else { crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); - THROW_WALLET_EXCEPTION_IF(tx_pub_key == null_pkey, error::wallet_internal_error, "Tx pubkey was not found"); + THROW_WALLET_EXCEPTION_IF(!tx_pub_key, error::wallet_internal_error, "Tx pubkey was not found"); std::vector additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); const size_t num_sigs = 1 + additional_tx_pub_keys.size(); @@ -12583,7 +12579,7 @@ bool wallet2::check_tx_proof(const cryptonote::transaction &tx, const cryptonote } crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); - THROW_WALLET_EXCEPTION_IF(tx_pub_key == null_pkey, error::wallet_internal_error, "Tx pubkey was not found"); + THROW_WALLET_EXCEPTION_IF(!tx_pub_key, error::wallet_internal_error, "Tx pubkey was not found"); std::vector additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); THROW_WALLET_EXCEPTION_IF(additional_tx_pub_keys.size() + 1 != num_sigs, error::wallet_internal_error, "Signature size mismatch with additional tx pubkeys"); @@ -12698,7 +12694,7 @@ std::string wallet2::get_reserve_proof(const std::optional additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); // determine which tx pub key was used for deriving the output key @@ -12866,7 +12862,7 @@ bool wallet2::check_reserve_proof(const cryptonote::account_public_address &addr else { const crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); - THROW_WALLET_EXCEPTION_IF(tx_pub_key == crypto::null_pkey, error::wallet_internal_error, "The tx public key isn't found"); + THROW_WALLET_EXCEPTION_IF(!tx_pub_key, error::wallet_internal_error, "The tx public key isn't found"); ok = crypto::check_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, std::nullopt, proof.shared_secret, proof.shared_secret_sig); } @@ -13653,10 +13649,9 @@ uint64_t wallet2::import_key_images(const std::vector, pd); } } @@ -13733,7 +13728,7 @@ std::tuple> wallet2::export_bloc std::tuple> bc; auto& [offset, genesis_hash, hashes] = bc; offset = m_blockchain.offset(); - genesis_hash = m_blockchain.empty() ? crypto::null_hash: m_blockchain.genesis(); + genesis_hash = m_blockchain.empty() ? null : m_blockchain.genesis(); for (size_t n = m_blockchain.offset(); n < m_blockchain.size(); ++n) hashes.push_back(m_blockchain[n]); return bc; @@ -14687,11 +14682,11 @@ void wallet2::hash_m_transfer(const transfer_details & transfer, crypto::hash &h { KECCAK_CTX state; keccak_init(&state); - keccak_update(&state, (const uint8_t *) transfer.m_txid.data, sizeof(transfer.m_txid.data)); - keccak_update(&state, (const uint8_t *) transfer.m_internal_output_index, sizeof(transfer.m_internal_output_index)); - keccak_update(&state, (const uint8_t *) transfer.m_global_output_index, sizeof(transfer.m_global_output_index)); - keccak_update(&state, (const uint8_t *) transfer.m_amount, sizeof(transfer.m_amount)); - keccak_finish(&state, (uint8_t *) hash.data); + keccak_update(&state, transfer.m_txid.data(), transfer.m_txid.size()); + keccak_update(&state, reinterpret_cast(&transfer.m_internal_output_index), sizeof(transfer.m_internal_output_index)); + keccak_update(&state, reinterpret_cast(&transfer.m_global_output_index), sizeof(transfer.m_global_output_index)); + keccak_update(&state, reinterpret_cast(&transfer.m_amount), sizeof(transfer.m_amount)); + keccak_finish(&state, hash.data()); } //---------------------------------------------------------------------------------------------------- uint64_t wallet2::hash_m_transfers(int64_t transfer_height, crypto::hash &hash) const @@ -14709,12 +14704,12 @@ uint64_t wallet2::hash_m_transfers(int64_t transfer_height, crypto::hash &hash) } hash_m_transfer(transfer, tmp_hash); - keccak_update(&state, (const uint8_t *) transfer.m_block_height, sizeof(transfer.m_block_height)); - keccak_update(&state, (const uint8_t *) tmp_hash.data, sizeof(tmp_hash.data)); + keccak_update(&state, reinterpret_cast(&transfer.m_block_height), sizeof(transfer.m_block_height)); + keccak_update(&state, reinterpret_cast(tmp_hash.data()), tmp_hash.size()); current_height += 1; } - keccak_finish(&state, (uint8_t *) hash.data); + keccak_finish(&state, hash.data()); return current_height; } diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 8588789e6..059b6708f 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -193,7 +193,7 @@ private: class hashchain { public: - hashchain(): m_genesis(crypto::null_hash), m_offset(0) {} + hashchain(): m_genesis(crypto::null), m_offset(0) {} size_t size() const { return m_blockchain.size() + m_offset; } size_t offset() const { return m_offset; } @@ -373,7 +373,7 @@ private: uint64_t m_change = std::numeric_limits::max(); uint64_t m_block_height = 0; std::vector m_dests; - crypto::hash m_payment_id = crypto::null_hash; + crypto::hash m_payment_id = crypto::null; uint64_t m_timestamp = 0; uint64_t m_unlock_time = 0; // NOTE(oxen): Not used after TX v2. std::vector m_unlock_times; @@ -1934,20 +1934,20 @@ namespace boost::serialization { crypto::hash payment_id; a & payment_id; - x.m_has_payment_id = !(payment_id == crypto::null_hash); + x.m_has_payment_id = (bool) payment_id; if (x.m_has_payment_id) { bool is_long = false; for (int i = 8; i < 32; ++i) - is_long |= payment_id.data[i]; + is_long |= payment_id[i]; if (is_long) { oxen::log::warning(oxen::log::Cat("wallet.wallet2"), "Long payment ID ignored on address book load"); - x.m_payment_id = crypto::null_hash8; + x.m_payment_id.zero(); x.m_has_payment_id = false; } else - memcpy(x.m_payment_id.data, payment_id.data, 8); + memcpy(x.m_payment_id.data(), payment_id.data(), 8); } } a & x.m_description; diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 7a67078fd..07e37e844 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -894,7 +894,7 @@ namespace //------------------------------------------------------------------------------------------------------------------------------ void wallet_rpc_server::validate_transfer(const std::list& destinations, const std::string& payment_id, std::vector& dsts, std::vector& extra, bool at_least_one_destination) { - crypto::hash8 integrated_payment_id = crypto::null_hash8; + crypto::hash8 integrated_payment_id{}; std::string extra_nonce; for (auto it = destinations.begin(); it != destinations.end(); it++) { @@ -910,7 +910,7 @@ namespace if (info.has_payment_id) { - if (!payment_id.empty() || integrated_payment_id != crypto::null_hash8) + if (!payment_id.empty() || integrated_payment_id) throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "A single payment id is allowed per transaction"}; integrated_payment_id = info.payment_id; cryptonote::set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, integrated_payment_id); @@ -977,10 +977,10 @@ namespace } void append_hex_tx_keys(std::string& to, const crypto::secret_key& k, const std::vector& more) { - to.reserve(to.size() + oxenc::to_hex_size(sizeof(k.data) * (1 + more.size()))); - oxenc::to_hex(std::begin(k.data), std::end(k.data), std::back_inserter(to)); + to.reserve(to.size() + oxenc::to_hex_size(k.size() * (1 + more.size()))); + oxenc::to_hex(k.begin(), k.end(), std::back_inserter(to)); for (const auto& key : more) - oxenc::to_hex(std::begin(key.data), std::end(key.data), std::back_inserter(to)); + oxenc::to_hex(key.begin(), key.end(), std::back_inserter(to)); } std::string hex_tx_keys(const crypto::secret_key& k, const std::vector& more) { std::string s; @@ -1205,7 +1205,7 @@ namespace std::vector tx_extra_fields; bool has_encrypted_payment_id = false; - crypto::hash8 payment_id8 = crypto::null_hash8; + crypto::hash8 payment_id8{}; if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields)) { cryptonote::tx_extra_nonce extra_nonce; @@ -1214,7 +1214,7 @@ namespace crypto::hash payment_id; if(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) { - if (payment_id8 != crypto::null_hash8) + if (payment_id8) { desc.payment_id = tools::type_to_hex(payment_id8); has_encrypted_payment_id = true; @@ -1529,8 +1529,7 @@ namespace std::string payment_id_blob; if (!tools::hex_to_type(req.payment_id, payment_id)) { if (crypto::hash8 payment_id8; tools::hex_to_type(req.payment_id, payment_id8)) { - memcpy(payment_id.data, payment_id8.data, 8); - memset(payment_id.data + 8, 0, 24); + payment_id = payment_id8; } else { throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "Payment ID has invalid format"}; } @@ -1598,8 +1597,7 @@ namespace r = tools::hex_to_type(payment_id_str, payment_id8); if (r) { - memcpy(payment_id.data, payment_id8.data, 8); - memset(payment_id.data + 8, 0, 24); + payment_id = payment_id8; } } else @@ -1703,16 +1701,16 @@ namespace else if (req.key_type == "view_key") { res.key.reserve(64); - const auto& vsk_data = m_wallet->get_account().get_keys().m_view_secret_key.data; - oxenc::to_hex(std::begin(vsk_data), std::end(vsk_data), std::back_inserter(res.key)); + const auto& vsk = m_wallet->get_account().get_keys().m_view_secret_key; + oxenc::to_hex(vsk.begin(), vsk.end(), std::back_inserter(res.key)); } else if (req.key_type == "spend_key") { if (m_wallet->watch_only()) throw wallet_rpc_error{error_code::WATCH_ONLY, "The wallet is watch-only. Cannot retrieve spend key."}; res.key.reserve(64); - const auto& ssk_data = m_wallet->get_account().get_keys().m_spend_secret_key.data; - oxenc::to_hex(std::begin(ssk_data), std::end(ssk_data), std::back_inserter(res.key)); + const auto& ssk = m_wallet->get_account().get_keys().m_spend_secret_key; + oxenc::to_hex(ssk.begin(), ssk.end(), std::back_inserter(res.key)); } else throw wallet_rpc_error{error_code::UNKNOWN_ERROR, "key_type " + req.key_type + " not found"}; @@ -1842,13 +1840,13 @@ namespace if (tx_keys.size() < 64 || tx_keys.size() % 64 || !oxenc::is_hex(tx_keys)) throw wallet_rpc_error{error_code::WRONG_KEY, "Tx key has invalid format"}; crypto::secret_key tx_key; - oxenc::from_hex(tx_keys.begin(), tx_keys.begin() + 64, tx_key.data); + oxenc::from_hex(tx_keys.begin(), tx_keys.begin() + 64, tx_key.begin()); tx_keys.remove_prefix(64); std::vector additional_tx_keys; while (!tx_keys.empty()) { - oxenc::from_hex(tx_keys.begin(), tx_keys.begin() + 64, additional_tx_keys.emplace_back().data); + oxenc::from_hex(tx_keys.begin(), tx_keys.begin() + 64, additional_tx_keys.emplace_back().begin()); tx_keys.remove_prefix(64); } diff --git a/src/wallet3/keyring.cpp b/src/wallet3/keyring.cpp index 2f19b93cb..be235d818 100644 --- a/src/wallet3/keyring.cpp +++ b/src/wallet3/keyring.cpp @@ -206,7 +206,7 @@ namespace wallet crypto::hash Keyring::get_transaction_prefix_hash(const cryptonote::transaction_prefix& tx) { - crypto::hash h = crypto::null_hash; + crypto::hash h{}; key_device.get_transaction_prefix_hash(tx, h); return h; } diff --git a/tests/block_weight/block_weight.cpp b/tests/block_weight/block_weight.cpp index 9c752ef8e..5fad6dd26 100644 --- a/tests/block_weight/block_weight.cpp +++ b/tests/block_weight/block_weight.cpp @@ -88,13 +88,13 @@ public: return ret; } virtual crypto::hash get_block_hash_from_height(const uint64_t &height) const override { - crypto::hash hash = crypto::null_hash; - *(uint64_t*)&hash = height; + crypto::hash hash{}; + *reinterpret_cast(hash.data()) = height; return hash; } virtual crypto::hash top_block_hash(uint64_t *block_height = NULL) const override { uint64_t h = height(); - crypto::hash top = crypto::null_hash; + crypto::hash top{}; if (h) *(uint64_t*)&top = h - 1; if (block_height) diff --git a/tests/core_proxy/core_proxy.cpp b/tests/core_proxy/core_proxy.cpp index 9ae654bf4..0faa26ded 100644 --- a/tests/core_proxy/core_proxy.cpp +++ b/tests/core_proxy/core_proxy.cpp @@ -164,17 +164,12 @@ std::vector tests::proxy_core::parse_inc for (size_t i = 0; i < tx_blobs.size(); i++) { auto &txi = tx_info[i]; - crypto::hash tx_prefix_hash = null_hash; + crypto::hash tx_prefix_hash{}; if (opts.kept_by_block) { txi.result = txi.parsed = true; } else if (parse_and_validate_tx_from_blob(tx_blobs[i], txi.tx, txi.tx_hash, tx_prefix_hash)) { - std::cout << "TX\n\n"; - std::cout << txi.tx_hash << "\n"; - std::cout << tx_prefix_hash << "\n"; - std::cout << tx_blobs[i].size() << "\n"; - //std::cout << oxenc::to_hex(tx_blob) << "\n\n"; - std::cout << obj_to_json_str(txi.tx) << "\n"; - std::cout << "\nENDTX\n"; + fmt::print("TX\n\n{}\n{}\n{}\n{}\n\nENDTX\n", + txi.tx_hash, tx_prefix_hash, tx_blobs[i].size(), obj_to_json_str(txi.tx)); txi.result = txi.parsed = true; txi.blob = &tx_blobs[i]; } else { @@ -228,13 +223,8 @@ bool tests::proxy_core::handle_incoming_block(const std::string& block_blob, con crypto::hash h = get_block_hash(b); crypto::hash lh = get_block_longhash_w_blockchain(network_type::FAKECHAIN, NULL, b, 0, 0); - std::cout << "BLOCK\n\n"; - std::cout << h << '\n'; - std::cout << lh << '\n'; - std::cout << get_transaction_hash(b.miner_tx) << '\n'; - std::cout << get_object_blobsize(b.miner_tx) << '\n'; - std::cout << obj_to_json_str(b) << '\n'; - std::cout << "\nENDBLOCK\n\n"; + fmt::print("BLOCK\n\n{}\n{}\n{}\n{}\n{}\n\nENDBLOCK\n\n", + h, lh, get_transaction_hash(b.miner_tx), get_object_blobsize(b.miner_tx), obj_to_json_str(b)); if (!add_block(h, lh, b, block_blob, checkpoint)) return false; @@ -284,7 +274,7 @@ void tests::proxy_core::build_short_history(std::list &m_history, m_history.push_front(cit->first); size_t n = 1 << m_history.size(); - while (m_hash2blkidx.end() != cit && crypto::null_hash != cit->second.blk.prev_id && n > 0) { + while (m_hash2blkidx.end() != cit && cit->second.blk.prev_id && n > 0) { n--; cit = m_hash2blkidx.find(cit->second.blk.prev_id); } @@ -294,10 +284,10 @@ void tests::proxy_core::build_short_history(std::list &m_history, bool tests::proxy_core::add_block(const crypto::hash &_id, const crypto::hash &_longhash, const cryptonote::block &_blk, const std::string &_blob, cryptonote::checkpoint_t const *) { size_t height = 0; - if (crypto::null_hash != _blk.prev_id) { + if (_blk.prev_id) { std::unordered_map::const_iterator cit = m_hash2blkidx.find(_blk.prev_id); if (m_hash2blkidx.end() == cit) { - std::cerr << "ERROR: can't find previous block with id \"" << _blk.prev_id << "\"\n"; + fmt::print(stderr, "ERROR: can't find previous block with id \"{}\"\n", _blk.prev_id); return false; } diff --git a/tests/core_proxy/core_proxy.h b/tests/core_proxy/core_proxy.h index 60a7711c0..8f05d7fab 100644 --- a/tests/core_proxy/core_proxy.h +++ b/tests/core_proxy/core_proxy.h @@ -50,7 +50,7 @@ namespace tests std::string blob; std::list txes; - block_index() : height(0), id(crypto::null_hash), longhash(crypto::null_hash) { } + block_index() : height(0), id{}, longhash{} { } block_index(size_t _height, const crypto::hash &_id, const crypto::hash &_longhash, const cryptonote::block &_blk, const std::string &_blob, const std::list &_txes) : height(_height), id(_id), longhash(_longhash), blk(_blk), blob(_blob), txes(_txes) { } }; @@ -99,7 +99,7 @@ namespace tests bool cleanup_handle_incoming_blocks(bool force_sync = false) { return true; } uint64_t get_target_blockchain_height() const { return 1; } size_t get_block_sync_size(uint64_t height) const { return cryptonote::BLOCKS_SYNCHRONIZING_DEFAULT_COUNT; } - virtual crypto::hash on_transaction_relayed(const std::string& tx) { return crypto::null_hash; } + virtual crypto::hash on_transaction_relayed(const std::string& tx) { return crypto::null; } cryptonote::network_type get_nettype() const { return cryptonote::network_type::MAINNET; } bool get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks, std::vector& txs) const { return false; } bool get_transactions(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs = nullptr) const { return false; } diff --git a/tests/core_tests/bulletproofs.cpp b/tests/core_tests/bulletproofs.cpp index 0e0adfc71..6fc698959 100644 --- a/tests/core_tests/bulletproofs.cpp +++ b/tests/core_tests/bulletproofs.cpp @@ -251,11 +251,11 @@ bool gen_bp_tx_validation_base::generate_with(std::vector& eve // that it looks obviously fake, then fill the rest with randomness (so that it is still // unique). for (size_t i = 0; i < 8; i++) - tx_hash.data[i] = 0x01 + (0x22 * i); + tx_hash[i] = 0x01 + (0x22 * i); static std::mt19937_64 rng{std::random_device{}()}; std::uniform_int_distribution unif{std::numeric_limits::min()}; - for (size_t i = 8; i < sizeof(tx_hash.data); i++) - tx_hash.data[i] = unif(rng); + for (size_t i = 8; i < tx_hash.size(); i++) + tx_hash[i] = unif(rng); } starting_rct_tx_hashes.push_back(tx_hash); oxen::log::warning(globallogcat, "Test tx: {}", obj_to_json_str(rct_txes.back())); diff --git a/tests/core_tests/chaingen.cpp b/tests/core_tests/chaingen.cpp index 2c57af838..8a25f9473 100644 --- a/tests/core_tests/chaingen.cpp +++ b/tests/core_tests/chaingen.cpp @@ -706,7 +706,7 @@ cryptonote::transaction oxen_chain_generator::create_oxen_name_system_tx(crypton auto lcname = tools::lowercase_ascii_string(name); crypto::hash name_hash = ons::name_to_hash(lcname); std::string name_base64_hash = ons::name_to_base64_hash(lcname); - crypto::hash prev_txid = crypto::null_hash; + crypto::hash prev_txid{}; if (ons::mapping_record mapping = ons_db_->get_mapping(type, name_base64_hash, new_height)) prev_txid = mapping.txid; @@ -767,7 +767,7 @@ cryptonote::transaction oxen_chain_generator::create_oxen_name_system_tx_update( auto data = ons::tx_extra_signature(encrypted_value.to_view(), owner, backup_owner, prev_txid); crypto::hash hash{}; if (!data.empty()) - crypto_generichash(reinterpret_cast(hash.data), sizeof(hash), reinterpret_cast(data.data()), data.size(), nullptr, 0); + crypto_generichash(hash.data(), hash.size(), reinterpret_cast(data.data()), data.size(), nullptr, 0); generate_signature(hash, src.get_keys().m_account_address.m_spend_public_key, src.get_keys().m_spend_secret_key, signature->monero); signature->type = ons::generic_owner_sig_type::monero; } @@ -849,7 +849,7 @@ static void fill_nonce_with_test_generator(test_generator *generator, cryptonote cryptonote::randomx_longhash_context randomx_context = {}; if (generator->m_hf_version >= hf::hf12_checkpointing) { - randomx_context.seed_height = crypto::rx_seedheight(height); + randomx_context.seed_height = rx_seedheight(height); cryptonote::block prev = blk; do { @@ -876,7 +876,7 @@ void fill_nonce_with_oxen_generator(oxen_chain_generator const *generator, crypt cryptonote::randomx_longhash_context randomx_context = {}; if (generator->blocks().size() && generator->hardfork() >= hf::hf12_checkpointing) { - randomx_context.seed_height = crypto::rx_seedheight(height); + randomx_context.seed_height = rx_seedheight(height); randomx_context.seed_block_hash = cryptonote::get_block_hash(generator->blocks()[randomx_context.seed_height].block); randomx_context.current_blockchain_height = height; } @@ -899,14 +899,15 @@ oxen_blockchain_entry oxen_chain_generator::create_genesis_block(const cryptonot blk.major_version = hf_version_; blk.minor_version = static_cast(hf_version_); blk.timestamp = timestamp; - blk.prev_id = crypto::null_hash; + blk.prev_id.zero(); // TODO(doyle): Does this evaluate to 0? If so we can simplify this a lot more size_t target_block_weight = get_transaction_weight(blk.miner_tx); while (true) { - auto [constructed, block_rewards] = construct_miner_tx(height, + [[maybe_unused]] auto [constructed, block_rewards] = construct_miner_tx( + height, 0 /*median_weight*/, 0 /*already_generated_coins*/, target_block_weight, @@ -1237,7 +1238,7 @@ std::vector oxen_chain_generator::last_n_block_weights(uint64_t height void test_generator::get_block_chain(std::vector& blockchain, const crypto::hash& head, size_t n) const { crypto::hash curr = head; - while (crypto::null_hash != curr && blockchain.size() < n) + while (curr && blockchain.size() < n) { auto it = m_blocks_info.find(curr); if (m_blocks_info.end() == it) @@ -1258,7 +1259,7 @@ void test_generator::get_block_chain(std::vector &blockchain, size_t n) const { crypto::hash curr = head; - while (crypto::null_hash != curr && blockchain.size() < n) + while (curr && blockchain.size() < n) { auto it = m_blocks_info.find(curr); if (m_blocks_info.end() == it) @@ -1455,7 +1456,7 @@ bool test_generator::construct_block(cryptonote::block &blk, { std::vector block_weights; std::list tx_list; - return construct_block(blk, 0, crypto::null_hash, miner_acc, timestamp, 0, block_weights, tx_list); + return construct_block(blk, 0, crypto::null, miner_acc, timestamp, 0, block_weights, tx_list); } bool test_generator::construct_block(cryptonote::block &blk, @@ -2048,9 +2049,9 @@ std::string block_tracker::dump_data() ss << " idx: " << oi.idx << ", rct: " << oi.rct << ", xmr: " << oi.amount - << ", key: " << dump_keys(out.key.data) + << ", key: " << dump_keys(out.key.data()) << ", msk: " << dump_keys(oi.comm.bytes) - << ", txid: " << dump_keys(oi.p_tx->hash.data) + << ", txid: " << dump_keys(oi.p_tx->hash.data()) << '\n'; } } @@ -2510,7 +2511,7 @@ bool find_block_chain(const std::vector &events, std::vectorsecond); id = it->second->prev_id; - if (crypto::null_hash == id) + if (!id) { b_success = true; break; @@ -2568,7 +2569,7 @@ bool find_block_chain(const std::vector &events, std::vectorsecond); id = it->second->prev_id; - if (crypto::null_hash == id) + if (!id) { b_success = true; break; diff --git a/tests/core_tests/chaingen.h b/tests/core_tests/chaingen.h index cadbebe28..ebb3b0368 100644 --- a/tests/core_tests/chaingen.h +++ b/tests/core_tests/chaingen.h @@ -359,22 +359,12 @@ public: } }; -template -std::string dump_keys(T * buff32) +// Dumps the 32-byte contents of some pointer as: [0x01,0xf1,0xbb,....,0xff]. +// (I have no idea why this makes any sense, look, squirrel!) +inline std::string dump_keys(const void* buff32) { - std::ostringstream ss; - char buff[10]; - - ss << "["; - for(int i = 0; i < 32; i++) - { - snprintf(buff, 10, "0x%02x", ((uint8_t)buff32[i] & 0xff)); - ss << buff; - if (i < 31) - ss << ","; - } - ss << "]"; - return ss.str(); + auto* begin = reinterpret_cast(buff32); + return "[{:#04x}]"_format(fmt::join(begin, begin+32, ",")); } struct output_index { @@ -454,7 +444,7 @@ struct output_index { typedef std::tuple get_outs_entry; typedef std::pair output_hasher; -struct output_hasher_hasher { size_t operator()(const output_hasher &h) const { return *reinterpret_cast(h.first.data) + h.second; } }; +struct output_hasher_hasher { size_t operator()(const output_hasher &h) const { return *reinterpret_cast(h.first.data()) + h.second; } }; typedef std::map > map_output_t; typedef std::map > map_output_idx_t; typedef std::unordered_map map_block_t; diff --git a/tests/core_tests/multisig.cpp b/tests/core_tests/multisig.cpp index 0d9084fd9..36acf5a44 100644 --- a/tests/core_tests/multisig.cpp +++ b/tests/core_tests/multisig.cpp @@ -40,6 +40,12 @@ using namespace cryptonote; //#define NO_MULTISIG +struct secret_key_hasher { + size_t operator()(const crypto::secret_key& k) const { + return *reinterpret_cast(k.data()); + } +}; + void make_multisig_accounts(std::vector& account, uint32_t threshold) { std::vector all_view_keys; @@ -96,7 +102,7 @@ void make_multisig_accounts(std::vector& account, uint std::unordered_set all_multisig_keys; for (size_t msidx = 0; msidx < account.size(); ++msidx) { - std::unordered_set view_keys(all_view_keys.begin(), all_view_keys.end()); + std::unordered_set view_keys(all_view_keys.begin(), all_view_keys.end()); view_keys.erase(all_view_keys[msidx]); crypto::secret_key view_skey = cryptonote::generate_multisig_view_secret_key(account[msidx].get_keys().m_view_secret_key, std::vector(view_keys.begin(), view_keys.end())); @@ -388,7 +394,7 @@ bool gen_multisig_tx_validation_base::generate_with(std::vector used_keys; + std::unordered_set used_keys; const std::vector &msk0 = miner_account[creator].get_multisig_keys(); for (const auto &sk: msk0) used_keys.insert(sk); diff --git a/tests/core_tests/oxen_tests.cpp b/tests/core_tests/oxen_tests.cpp index 9a7f40255..7aa97d09f 100644 --- a/tests/core_tests/oxen_tests.cpp +++ b/tests/core_tests/oxen_tests.cpp @@ -1070,8 +1070,10 @@ static ons_keys_t make_ons_keys(cryptonote::account_base const &src) auto iter = result.wallet_value.buffer.begin(); uint8_t identifier = 0; iter = std::copy_n(&identifier, 1, iter); - iter = std::copy_n(src.get_keys().m_account_address.m_spend_public_key.data, sizeof(src.get_keys().m_account_address.m_spend_public_key.data), iter); - iter = std::copy_n(src.get_keys().m_account_address.m_view_public_key.data, sizeof(src.get_keys().m_account_address.m_view_public_key.data), iter); + auto& spubkey = src.get_keys().m_account_address.m_spend_public_key; + iter = std::copy(spubkey.begin(), spubkey.end(), iter); + auto& vpubkey = src.get_keys().m_account_address.m_view_public_key; + iter = std::copy(vpubkey.begin(), vpubkey.end(), iter); // NOTE: Just needs a 32 byte key. Reuse spend key memcpy(&result.lokinet_value.buffer[0], (char *)&result.owner.wallet.address.m_spend_public_key, result.lokinet_value.len); @@ -1551,7 +1553,7 @@ bool oxen_name_system_invalid_tx_extra_params::generate(std::vector(args)...); if (!data.empty()) - crypto_generichash(reinterpret_cast(hash.data), sizeof(hash), reinterpret_cast(data.data()), data.size(), nullptr, 0); + crypto_generichash(hash.data(), hash.size(), reinterpret_cast(data.data()), data.size(), nullptr, 0); return hash; } @@ -2148,8 +2150,8 @@ bool oxen_name_system_update_mapping_multiple_owners::generate(std::vector& e const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; bool failed = false; - return generate_with(events, out_idx, mixin, amount_paid, false, - NULL, [&failed](transaction &tx) {std::string extra_nonce; crypto::hash pid = crypto::null_hash; set_payment_id_to_tx_extra_nonce(extra_nonce, pid); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; }) && !failed; + return generate_with(events, out_idx, mixin, amount_paid, false, nullptr, + [&failed](transaction &tx) { + std::string extra_nonce; + crypto::hash pid{}; + set_payment_id_to_tx_extra_nonce(extra_nonce, pid); + if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; + }) && !failed; } bool gen_rct_tx_rct_altered_extra::generate(std::vector& events) const @@ -518,8 +523,13 @@ bool gen_rct_tx_rct_altered_extra::generate(std::vector& event const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; bool failed = false; - return generate_with(events, out_idx, mixin, amount_paid, false, - NULL, [&failed](transaction &tx) {std::string extra_nonce; crypto::hash pid = crypto::null_hash; set_payment_id_to_tx_extra_nonce(extra_nonce, pid); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; }) && !failed; + return generate_with(events, out_idx, mixin, amount_paid, false, nullptr, + [&failed](transaction &tx) { + std::string extra_nonce; + crypto::hash pid{}; + set_payment_id_to_tx_extra_nonce(extra_nonce, pid); + if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; + }) && !failed; } bool gen_rct_tx_uses_output_too_early::generate(std::vector& events) const diff --git a/tests/core_tests/wallet_tools.cpp b/tests/core_tests/wallet_tools.cpp index 66d446eee..9663da760 100644 --- a/tests/core_tests/wallet_tools.cpp +++ b/tests/core_tests/wallet_tools.cpp @@ -112,7 +112,7 @@ bool wallet_tools::fill_tx_sources(tools::wallet2 * wallet, std::vectortx_hashes) { const map_hash2tx_t::const_iterator cit = mtx.find(h); - CHECK_AND_ASSERT_THROW_MES(mtx.end() != cit, "block contains an unknown tx hash @ " << height << ", " << h); + CHECK_AND_ASSERT_THROW_MES(mtx.end() != cit, "block contains an unknown tx hash @ {}, {}"_format(height, h)); vtx.push_back(cit->second); } diff --git a/tests/crypto/crypto.cpp b/tests/crypto/crypto.cpp index d68265806..a25f44545 100644 --- a/tests/crypto/crypto.cpp +++ b/tests/crypto/crypto.cpp @@ -33,17 +33,17 @@ #include "crypto-tests.h" bool check_scalar(const crypto::ec_scalar &scalar) { - return crypto::sc_check(crypto::operator &(scalar)) == 0; + return sc_check(scalar.data()) == 0; } void hash_to_point(const crypto::hash &h, crypto::ec_point &res) { - crypto::ge_p2 point; - crypto::ge_fromfe_frombytes_vartime(&point, reinterpret_cast(&h)); - crypto::ge_tobytes(crypto::operator &(res), &point); + ge_p2 point; + ge_fromfe_frombytes_vartime(&point, reinterpret_cast(&h)); + ge_tobytes(res.data(), &point); } void hash_to_ec(const crypto::public_key &key, crypto::ec_point &res) { - crypto::ge_p3 tmp; + ge_p3 tmp; crypto::hash_to_ec(key, tmp); - crypto::ge_p3_tobytes(crypto::operator &(res), &tmp); + ge_p3_tobytes(res.data(), &tmp); } diff --git a/tests/crypto/main.cpp b/tests/crypto/main.cpp index b9ef0f6a0..601696b2b 100644 --- a/tests/crypto/main.cpp +++ b/tests/crypto/main.cpp @@ -49,18 +49,6 @@ using namespace std::literals; using namespace crypto; typedef crypto::hash chash; -bool operator !=(const ec_scalar &a, const ec_scalar &b) { - return 0 != memcmp(&a, &b, sizeof(ec_scalar)); -} - -bool operator !=(const ec_point &a, const ec_point &b) { - return 0 != memcmp(&a, &b, sizeof(ec_point)); -} - -bool operator !=(const key_derivation &a, const key_derivation &b) { - return 0 != memcmp(&a, &b, sizeof(key_derivation)); -} - DISABLE_GCC_WARNING(maybe-uninitialized) size_t lineno; diff --git a/tests/hash/main.cpp b/tests/hash/main.cpp index dad75cf5d..059c3b728 100644 --- a/tests/hash/main.cpp +++ b/tests/hash/main.cpp @@ -45,9 +45,6 @@ using namespace crypto; typedef crypto::hash chash; -using std::cerr; -using std::endl; - #define X_MACRO \ HASH_X_MACRO(invalid, "INVALID") \ HASH_X_MACRO(fast, "fast") \ @@ -74,10 +71,8 @@ int test_variant2_int_sqrt(); int test_variant2_int_sqrt_ref(); int main(int argc, char *argv[]) { - TRY_ENTRY(); - std::fstream input; - std::vector data; + std::vector data; chash expected, actual; size_t test = 0; bool error = false; @@ -91,28 +86,17 @@ int main(int argc, char *argv[]) { std::fesetround(round_modes[i]); const int result = test_variant2_int_sqrt(); if (result != 0) { - cerr << "FPU round mode was set to "; - switch (round_modes[i]) { - case FE_DOWNWARD: - cerr << "FE_DOWNWARD"; - break; - case FE_TONEAREST: - cerr << "FE_TONEAREST"; - break; - case FE_UPWARD: - cerr << "FE_UPWARD"; - break; - default: - cerr << "unknown"; - break; - } - cerr << endl; + fmt::print(stderr, "FPU round mode was set to {}\n", + round_modes[i] == FE_DOWNWARD ? "FE_DOWNWARD" : + round_modes[i] == FE_TONEAREST ? "FE_TONEAREST" : + round_modes[i] == FE_UPWARD ? "FE_UPWARD" : + "unknown"); return result; } } return 0; } - cerr << "Wrong number of arguments" << endl; + fmt::print(stderr, "Wrong arguments. Usage: {} TESTTYPE test-file.txt\n"); return 1; } @@ -128,7 +112,7 @@ int main(int argc, char *argv[]) { if (type == hash_type::invalid) { - cerr << "Unknown hashing function" << endl; + std::cerr << "Unknown hashing function\n"; return 1; } @@ -146,7 +130,7 @@ int main(int argc, char *argv[]) { void const *buf = data.data(); size_t len = data.size(); - auto *actual_byte_ptr = reinterpret_cast(&actual); + auto *actual_byte_ptr = actual.data(); switch(type) { case hash_type::fast: cn_fast_hash(buf, len, actual_byte_ptr); break; @@ -154,7 +138,7 @@ int main(int argc, char *argv[]) { { if ((len & 31) != 0) throw std::ios_base::failure("Invalid input length for tree_hash"); - tree_hash((const char (*)[crypto::HASH_SIZE]) buf, len >> 5, actual_byte_ptr); + tree_hash((const unsigned char (*)[HASH_SIZE]) buf, len >> 5, actual_byte_ptr); } break; @@ -165,38 +149,17 @@ int main(int argc, char *argv[]) { case hash_type::heavy_v1: cn_slow_hash (buf, len, actual, cn_slow_hash_type::heavy_v1); break; case hash_type::heavy_v2: cn_slow_hash (buf, len, actual, cn_slow_hash_type::heavy_v2); break; case hash_type::turtle_light_v2: cn_slow_hash (buf, len, actual, cn_slow_hash_type::turtle_lite_v2); break; - - default: - { - cerr << "Unknown hashing function" << endl; - return 1; - } - }; + default: throw std::runtime_error{"Unknown hashing function"}; + } if (expected != actual) { size_t i; - cerr << "Hash mismatch on test " << test << endl << "Input: "; - if (data.size() == 0) { - cerr << "empty"; - } else { - for (i = 0; i < data.size(); i++) { - cerr << std::setbase(16) << std::setw(2) << std::setfill('0') << int(static_cast(data[i])); - } - } - cerr << endl << "Expected hash: "; - for (i = 0; i < 32; i++) { - cerr << std::setbase(16) << std::setw(2) << std::setfill('0') << int(reinterpret_cast(&expected)[i]); - } - cerr << endl << "Actual hash: "; - for (i = 0; i < 32; i++) { - cerr << std::setbase(16) << std::setw(2) << std::setfill('0') << int(reinterpret_cast(&actual)[i]); - } - cerr << endl; + fmt::print(stderr, "Hash mismatch on test {}\nInput: {}\nExpected hash: {}\nActual hash: {}\n", + test, (data.empty() ? "Empty" : oxenc::to_hex(data.begin(), data.end())), expected, actual); error = true; } } return error ? 1 : 0; - CATCH_ENTRY_L0("main", 1); } #if defined(__x86_64__) || (defined(_MSC_VER) && defined(_WIN64)) @@ -218,9 +181,9 @@ static inline bool test_variant2_int_sqrt_sse(const uint64_t sqrt_input, const u VARIANT2_INTEGER_MATH_SQRT_STEP_SSE2(); VARIANT2_INTEGER_MATH_SQRT_FIXUP(sqrt_result); if (sqrt_result != correct_result) { - cerr << "Integer sqrt (SSE2 version) returned incorrect result for N = " << sqrt_input << endl; - cerr << "Expected result: " << correct_result << endl; - cerr << "Returned result: " << sqrt_result << endl; + std::cerr << "Integer sqrt (SSE2 version) returned incorrect result for N = " << sqrt_input << "\n"; + std::cerr << "Expected result: " << correct_result << "\n"; + std::cerr << "Returned result: " << sqrt_result << "\n"; return false; } #endif @@ -235,9 +198,9 @@ static inline bool test_variant2_int_sqrt_fp64(const uint64_t sqrt_input, const VARIANT2_INTEGER_MATH_SQRT_STEP_FP64(); VARIANT2_INTEGER_MATH_SQRT_FIXUP(sqrt_result); if (sqrt_result != correct_result) { - cerr << "Integer sqrt (FP64 version) returned incorrect result for N = " << sqrt_input << endl; - cerr << "Expected result: " << correct_result << endl; - cerr << "Returned result: " << sqrt_result << endl; + std::cerr << "Integer sqrt (FP64 version) returned incorrect result for N = " << sqrt_input << "\n"; + std::cerr << "Expected result: " << correct_result << "\n"; + std::cerr << "Returned result: " << sqrt_result << "\n"; return false; } #endif @@ -250,9 +213,9 @@ static inline bool test_variant2_int_sqrt_ref(const uint64_t sqrt_input, const u uint64_t sqrt_result; VARIANT2_INTEGER_MATH_SQRT_STEP_REF(); if (sqrt_result != correct_result) { - cerr << "Integer sqrt (reference version) returned incorrect result for N = " << sqrt_input << endl; - cerr << "Expected result: " << correct_result << endl; - cerr << "Returned result: " << sqrt_result << endl; + std::cerr << "Integer sqrt (reference version) returned incorrect result for N = " << sqrt_input << "\n"; + std::cerr << "Expected result: " << correct_result << "\n"; + std::cerr << "Returned result: " << sqrt_result << "\n"; return false; } diff --git a/tests/io.h b/tests/io.h index 8020c2432..cf309293f 100644 --- a/tests/io.h +++ b/tests/io.h @@ -35,11 +35,12 @@ #include #include -inline bool hexdecode(const char *from, std::size_t length, void *to) { - const char* end = from + 2*length; +template +inline bool hexdecode(const Char *from, std::size_t length, void *to) { + const Char* end = from + 2*length; if (!oxenc::is_hex(from, end)) return false; - oxenc::from_hex(from, end, reinterpret_cast(to)); + oxenc::from_hex(from, end, reinterpret_cast(to)); return true; } @@ -73,7 +74,8 @@ void get(std::istream &input, T &res) { getvar(input, sizeof(T), &res); } -inline void get(std::istream &input, std::vector &res) { +template , int> = 0> +inline void get(std::istream &input, std::vector &res) { std::string sres; input >> sres; if (sres == "x") { diff --git a/tests/trezor/trezor_tests.cpp b/tests/trezor/trezor_tests.cpp index dc86a050e..f676cb07d 100644 --- a/tests/trezor/trezor_tests.cpp +++ b/tests/trezor/trezor_tests.cpp @@ -445,7 +445,7 @@ bool get_short_payment_id(crypto::hash8 &payment_id8, const tools::wallet2::pend static tools::wallet2::tx_construction_data get_construction_data_with_decrypted_short_payment_id(const tools::wallet2::pending_tx &ptx, hw::device &hwdev) { tools::wallet2::tx_construction_data construction_data = ptx.construction_data; - crypto::hash8 payment_id = crypto::null_hash8; + crypto::hash8 payment_id{}; if (get_short_payment_id(payment_id, ptx, hwdev)) { // Remove encrypted diff --git a/tests/unit_tests/crypto.cpp b/tests/unit_tests/crypto.cpp index 444ed2789..3e9820185 100644 --- a/tests/unit_tests/crypto.cpp +++ b/tests/unit_tests/crypto.cpp @@ -32,6 +32,7 @@ #include #include +#include "common/string_util.h" #include "cryptonote_basic/cryptonote_basic_impl.h" namespace @@ -76,8 +77,36 @@ TEST(Crypto, null_keys) { char zero[32]; memset(zero, 0, 32); - ASSERT_EQ(memcmp(crypto::null_skey.data, zero, 32), 0); - ASSERT_EQ(memcmp(crypto::null_pkey.data, zero, 32), 0); + ASSERT_EQ(memcmp(crypto::null.data(), zero, 32), 0); + ASSERT_EQ(memcmp(crypto::null.data(), zero, 32), 0); + ASSERT_EQ(memcmp(crypto::public_key{}.data(), zero, 32), 0); + ASSERT_EQ(memcmp(crypto::secret_key{}.data(), zero, 32), 0); +} + +TEST(Crypto, equality) +{ + crypto::public_key pk1{}; + std::copy(source.data(), source.data() + 32, pk1.begin()); + ASSERT_EQ("{}"_format(pk1), "<{}>"_format(hex_full.substr(0, 64))); + crypto::public_key pk2 = pk1; + ASSERT_EQ(tools::view_guts(pk1), tools::view_guts(pk2)); + EXPECT_EQ(pk1, pk2); + crypto::public_key pk3; + std::copy(source.data(), source.data() + 32, pk3.begin()); + ASSERT_EQ(tools::view_guts(pk1), tools::view_guts(pk3)); + EXPECT_EQ(pk1, pk3); + pk3.zero(); + ASSERT_EQ("{}"_format(pk3), "<{:064x}>"_format(0)); + ASSERT_NE(tools::view_guts(pk1), tools::view_guts(pk3)); + EXPECT_NE(pk1, pk3); + EXPECT_LT(pk3, pk1); + + std::copy(source.data() + 32, source.data() + 64, pk2.begin()); + ASSERT_EQ("{}"_format(pk2), "<{}>"_format(hex_full.substr(64))); + EXPECT_NE(pk1, pk2); + EXPECT_LT(pk2, pk1); + EXPECT_FALSE(pk1 == pk2); + EXPECT_FALSE(pk1 < pk2); } TEST(Crypto, verify_32) diff --git a/tests/unit_tests/hashchain.cpp b/tests/unit_tests/hashchain.cpp index df87f5df2..51a4b72de 100644 --- a/tests/unit_tests/hashchain.cpp +++ b/tests/unit_tests/hashchain.cpp @@ -34,14 +34,9 @@ static crypto::hash make_hash(uint64_t n) { - union - { - crypto::hash hash; - uint64_t n; - } hash; - hash.hash = crypto::null_hash; - hash.n = n; - return hash.hash; + crypto::hash hash{}; + *reinterpret_cast(hash.data()) = n; + return hash; } TEST(hashchain, empty) diff --git a/tests/unit_tests/long_term_block_weight.cpp b/tests/unit_tests/long_term_block_weight.cpp index 5cd6b3967..77603c1f5 100644 --- a/tests/unit_tests/long_term_block_weight.cpp +++ b/tests/unit_tests/long_term_block_weight.cpp @@ -80,15 +80,15 @@ public: return ret; } virtual crypto::hash get_block_hash_from_height(const uint64_t &height) const override { - crypto::hash hash = crypto::null_hash; - *(uint64_t*)&hash = height; + crypto::hash hash{}; + *(uint64_t*)hash.data() = height; return hash; } virtual crypto::hash top_block_hash(uint64_t *block_height = NULL) const override { uint64_t h = height(); - crypto::hash top = crypto::null_hash; + crypto::hash top{}; if (h) - *(uint64_t*)&top = h - 1; + *(uint64_t*)top.data() = h - 1; if (block_height) *block_height = h - 1; return top; diff --git a/tests/unit_tests/mnemonics.cpp b/tests/unit_tests/mnemonics.cpp index 45433a741..49d2c9985 100644 --- a/tests/unit_tests/mnemonics.cpp +++ b/tests/unit_tests/mnemonics.cpp @@ -82,7 +82,7 @@ namespace crypto::secret_key randkey; for (size_t ii = 0; ii < sizeof(randkey); ++ii) { - randkey.data[ii] = crypto::rand(); + randkey[ii] = crypto::rand(); } crypto::ElectrumWords::bytes_to_words(randkey, w_seed, language.get_language_name()); seed = std::string(w_seed.data(), w_seed.size()); diff --git a/tests/unit_tests/node_server.cpp b/tests/unit_tests/node_server.cpp index f4d6bcf92..884ed82ba 100644 --- a/tests/unit_tests/node_server.cpp +++ b/tests/unit_tests/node_server.cpp @@ -56,7 +56,7 @@ public: bool deinit(){return true;} bool get_short_chain_history(std::list& ids) const { return true; } bool have_block(const crypto::hash& id) const {return true;} - std::pair get_blockchain_top() const { return {0, crypto::null_hash};} + std::pair get_blockchain_top() const { return {0, crypto::null};} std::vector parse_incoming_txs(const std::vector& tx_blobs, const cryptonote::tx_pool_options &opts) { return {}; } bool handle_parsed_txs(std::vector &parsed_txs, const cryptonote::tx_pool_options &opts, uint64_t *blink_rollback_height = nullptr) { if (blink_rollback_height) *blink_rollback_height = 0; return true; } std::vector handle_incoming_txs(const std::vector& tx_blobs, const cryptonote::tx_pool_options &opts) { return {}; } @@ -78,7 +78,7 @@ public: bool cleanup_handle_incoming_blocks(bool force_sync = false) { return true; } uint64_t get_target_blockchain_height() const { return 1; } size_t get_block_sync_size(uint64_t height) const { return cryptonote::BLOCKS_SYNCHRONIZING_DEFAULT_COUNT; } - virtual crypto::hash on_transaction_relayed(const std::string& tx) { return crypto::null_hash; } + virtual crypto::hash on_transaction_relayed(const std::string& tx) { return crypto::null; } cryptonote::network_type get_nettype() const { return cryptonote::network_type::MAINNET; } bool get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks, std::vector& txs) const { return false; } bool get_transactions(const std::vector& txs_ids, std::vector& txs, std::unordered_set* missed_txs) const { return false; } diff --git a/tests/unit_tests/output_distribution.cpp b/tests/unit_tests/output_distribution.cpp index c126811e1..c1187d6e5 100644 --- a/tests/unit_tests/output_distribution.cpp +++ b/tests/unit_tests/output_distribution.cpp @@ -95,8 +95,8 @@ bool get_output_distribution(uint64_t amount, uint64_t from, uint64_t to, uint64 crypto::hash get_block_hash(uint64_t height) { - crypto::hash hash = crypto::null_hash; - *((uint64_t*)&hash) = height; + crypto::hash hash{}; + *reinterpret_cast(hash.data()) = height; return hash; } diff --git a/tests/unit_tests/output_selection.cpp b/tests/unit_tests/output_selection.cpp index 2e8864c6a..ad4a12f39 100644 --- a/tests/unit_tests/output_selection.cpp +++ b/tests/unit_tests/output_selection.cpp @@ -43,11 +43,11 @@ static tools::wallet2::transfer_container make_transfers_container(size_t N) tools::wallet2::transfer_details &td = transfers.back(); td.m_block_height = 1000; td.m_spent = false; - td.m_txid = crypto::null_hash; - td.m_txid.data[0] = n & 0xff; - td.m_txid.data[1] = (n >> 8) & 0xff; - td.m_txid.data[2] = (n >> 16) & 0xff; - td.m_txid.data[3] = (n >> 24) & 0xff; + td.m_txid.zero(); + td.m_txid[0] = n & 0xff; + td.m_txid[1] = (n >> 8) & 0xff; + td.m_txid[2] = (n >> 16) & 0xff; + td.m_txid[3] = (n >> 24) & 0xff; } return transfers; } diff --git a/tests/unit_tests/serialization.cpp b/tests/unit_tests/serialization.cpp index 8451c9b0b..ea6920828 100644 --- a/tests/unit_tests/serialization.cpp +++ b/tests/unit_tests/serialization.cpp @@ -442,7 +442,7 @@ TEST(serialization, serializes_transaction_signatures_correctly) tx.signatures[1].resize(2); for (char i : {0, 1}) for (char j : {0, 1}) - tx.signatures[i][j].c.data[2*i + j] = ((i+1) << 4) + 2*i + j + 1; + tx.signatures[i][j].c()[2*i + j] = ((i+1) << 4) + 2*i + j + 1; tx.invalidate_hashes(); ASSERT_NO_THROW(blob = serialization::dump_binary(tx)); ASSERT_EQ(oxenc::to_hex(blob), diff --git a/tests/unit_tests/test_tx_utils.cpp b/tests/unit_tests/test_tx_utils.cpp index cde1813f6..d3eb95129 100644 --- a/tests/unit_tests/test_tx_utils.cpp +++ b/tests/unit_tests/test_tx_utils.cpp @@ -146,7 +146,7 @@ TEST(parse_and_validate_tx_extra, is_valid_tx_extra_parsed) std::tie(r, block_rewards) = cryptonote::construct_miner_tx(0, 0, 10000000000000, 1000, TEST_FEE, tx, cryptonote::oxen_miner_tx_context::miner_block(cryptonote::network_type::FAKECHAIN, acc.get_keys().m_account_address), {}, b, cryptonote::hf::none); ASSERT_TRUE(r); crypto::public_key tx_pub_key = cryptonote::get_tx_pub_key_from_extra(tx); - ASSERT_NE(tx_pub_key, crypto::null_pkey); + ASSERT_NE(tx_pub_key, crypto::null); } TEST(parse_and_validate_tx_extra, fails_on_big_extra_nonce) { diff --git a/tests/wallet3_tests/db_schema.cpp b/tests/wallet3_tests/db_schema.cpp index 91897c594..4b3bbabb9 100644 --- a/tests/wallet3_tests/db_schema.cpp +++ b/tests/wallet3_tests/db_schema.cpp @@ -5,7 +5,7 @@ TEST_CASE("DB Schema", "[wallet,db]") { - wallet::WalletDB db{std::filesystem::path(":memory:"), ""}; + wallet::WalletDB db{fs::path(":memory:"), ""}; SECTION("db schema creation succeeds") { @@ -61,7 +61,7 @@ TEST_CASE("DB Schema", "[wallet,db]") TEST_CASE("DB Triggers", "[wallet,db]") { - wallet::WalletDB db{std::filesystem::path(":memory:"), ""}; + wallet::WalletDB db{fs::path(":memory:"), ""}; REQUIRE_NOTHROW(db.create_schema()); REQUIRE(db.db.tableExists("blocks")); diff --git a/tests/wallet3_tests/tx_creation.cpp b/tests/wallet3_tests/tx_creation.cpp index ecdb4f8a0..407502039 100644 --- a/tests/wallet3_tests/tx_creation.cpp +++ b/tests/wallet3_tests/tx_creation.cpp @@ -11,8 +11,6 @@ #include "mock_daemon_comms.hpp" #include "mock_decoy_selector.hpp" -#include - namespace wallet { class MockSigningKeyring : public Keyring From 9792b637fb2535829c40a97e1c6bbc5ff7579e48 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 18 Oct 2022 00:57:10 -0300 Subject: [PATCH 32/32] Remove broken formattable::to_string(T) support - This was infinitely recursing because it was picking up fmt::to_string (on macos) rather than formattable::to_string, which led to infinite recursion and then a crash. - Add a custom ghc::filesystem::path formatter (because it just seems wrong to add a function into ghc::filesystem) instead of using the to_string formatting. Same for boost formatting crap in simplewallet. - Move the formatter structs into the `formattable` namespace so that this sort of recursive error can't happen again. --- src/common/formattable.h | 58 ++++++++++++++----------------- src/common/fs-format.h | 17 +++++---- src/simplewallet/simplewallet.cpp | 12 +++++-- 3 files changed, 46 insertions(+), 41 deletions(-) diff --git a/src/common/formattable.h b/src/common/formattable.h index cb0eb3f4c..609e8ccf7 100644 --- a/src/common/formattable.h +++ b/src/common/formattable.h @@ -14,9 +14,6 @@ namespace formattable { // it as a string. // - a `to_string(val)` function in the same namespace as the type; we will call it to format it // as a string. - // - a `to_string(val)` function defined in the `formattable` namespace. (Prefer its own - // namespace, but sometimes that may be ugly/infeasible, e.g. if making some external library - // type printable). // // The function should return something string-like (string, string_view, const char*). // @@ -62,49 +59,30 @@ namespace formattable { } // namespace detail -} // namespace formattable - - - -namespace fmt { - - template - struct formatter>> - : formatter - { + template + struct to_string_formatter : fmt::formatter { template auto format(const T& val, FormatContext& ctx) const { if constexpr (::formattable::detail::has_to_string_method) return formatter::format(val.to_string(), ctx); - else { - // This `using namespace` is so that you can also put the to_string function in the - // formattable namespace if it can't go in its own namespace for some reason: - using namespace formattable; + else return formatter::format(to_string(val), ctx); - } } }; - template - struct formatter>> - : formatter - { + template + struct to_hex_string_formatter : fmt::formatter { template auto format(const T& val, FormatContext& ctx) const { if constexpr (::formattable::detail::has_to_hex_string_method) return formatter::format(val.to_hex_string(), ctx); - else { - using namespace formattable; + else return formatter::format(to_hex_string(val), ctx); - } } }; - - template - struct formatter>> - : formatter> - { + template + struct underlying_t_formatter : fmt::formatter> { #ifdef __cpp_lib_is_scoped_enum // C++23 static_assert(std::is_scoped_enum_v); #else @@ -114,8 +92,26 @@ namespace fmt { template auto format(const T& val, FormatContext& ctx) const { using Underlying = std::underlying_type_t; - return formatter::format(static_cast(val), ctx); + return fmt::formatter::format(static_cast(val), ctx); } }; +} // namespace formattable + + + +namespace fmt { + + template + struct formatter>> + : ::formattable::to_string_formatter {}; + + template + struct formatter>> + : ::formattable::to_hex_string_formatter {}; + + template + struct formatter>> + : ::formattable::underlying_t_formatter {}; + } // namespace fmt diff --git a/src/common/fs-format.h b/src/common/fs-format.h index f5c1e6b80..0ba82391a 100644 --- a/src/common/fs-format.h +++ b/src/common/fs-format.h @@ -5,13 +5,16 @@ #ifndef USE_GHC_FILESYSTEM #include #else -#include "formattable.h" +#include -namespace formattable { - template <> inline constexpr bool via_to_string = true; - - inline std::string to_string(const ghc::filesystem::path& path) { - return path.string(); - } +namespace fmt { + template <> + struct formatter : formatter + { + template + auto format(const ghc::filesystem::path& val, FormatContext& ctx) const { + return formatter::format(val.u8string(), ctx); + } + }; } #endif diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index a7b48a866..844a748ab 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -94,9 +94,15 @@ extern "C" } // grumble, grumble -namespace formattable { - std::string to_string(const boost::basic_format& f) { return f.str(); } - template <> constexpr bool via_to_string> = true; +namespace fmt { + template <> + struct formatter> : formatter + { + template + auto format(const boost::basic_format& val, FormatContext& ctx) const { + return formatter::format(val.str(), ctx); + } + }; } namespace cryptonote