diff options
Diffstat (limited to 'src/wallet')
-rw-r--r-- | src/wallet/CMakeLists.txt | 2 | ||||
-rw-r--r-- | src/wallet/api/address_book.cpp | 54 | ||||
-rw-r--r-- | src/wallet/api/address_book.h | 3 | ||||
-rw-r--r-- | src/wallet/api/transaction_history.h | 1 | ||||
-rw-r--r-- | src/wallet/api/wallet.cpp | 79 | ||||
-rw-r--r-- | src/wallet/api/wallet.h | 7 | ||||
-rw-r--r-- | src/wallet/api/wallet_manager.cpp | 4 | ||||
-rw-r--r-- | src/wallet/node_rpc_proxy.cpp | 134 | ||||
-rw-r--r-- | src/wallet/node_rpc_proxy.h | 65 | ||||
-rw-r--r-- | src/wallet/wallet2.cpp | 436 | ||||
-rw-r--r-- | src/wallet/wallet2.h | 27 | ||||
-rw-r--r-- | src/wallet/wallet2_api.h | 20 | ||||
-rw-r--r-- | src/wallet/wallet_args.cpp | 73 | ||||
-rw-r--r-- | src/wallet/wallet_errors.h | 12 | ||||
-rw-r--r-- | src/wallet/wallet_rpc_server.cpp | 19 | ||||
-rw-r--r-- | src/wallet/wallet_rpc_server.h | 4 | ||||
-rw-r--r-- | src/wallet/wallet_rpc_server_commands_defs.h | 4 |
17 files changed, 736 insertions, 208 deletions
diff --git a/src/wallet/CMakeLists.txt b/src/wallet/CMakeLists.txt index 53b0a794f..922464a3c 100644 --- a/src/wallet/CMakeLists.txt +++ b/src/wallet/CMakeLists.txt @@ -34,6 +34,7 @@ set(wallet_sources password_container.cpp wallet2.cpp wallet_args.cpp + node_rpc_proxy.cpp api/wallet.cpp api/wallet_manager.cpp api/transaction_info.cpp @@ -55,6 +56,7 @@ set(wallet_private_headers wallet_rpc_server.h wallet_rpc_server_commands_defs.h wallet_rpc_server_error_codes.h + node_rpc_proxy.h api/wallet.h api/wallet_manager.h api/transaction_info.h diff --git a/src/wallet/api/address_book.cpp b/src/wallet/api/address_book.cpp index b878491ce..e397dac04 100644 --- a/src/wallet/api/address_book.cpp +++ b/src/wallet/api/address_book.cpp @@ -33,6 +33,7 @@ #include "wallet.h" #include "crypto/hash.h" #include "wallet/wallet2.h" +#include "common_defines.h" #include <vector> @@ -43,30 +44,50 @@ AddressBook::~AddressBook() {} AddressBookImpl::AddressBookImpl(WalletImpl *wallet) : m_wallet(wallet) {} -bool AddressBookImpl::addRow(const std::string &dst_addr , const std::string &payment_id, const std::string &description) +bool AddressBookImpl::addRow(const std::string &dst_addr , const std::string &payment_id_str, const std::string &description) { - LOG_PRINT_L2("Adding row"); - clearStatus(); cryptonote::account_public_address addr; - bool has_payment_id; + bool has_short_pid; crypto::hash8 payment_id_short; - if(!cryptonote::get_account_integrated_address_from_str(addr, has_payment_id, payment_id_short, m_wallet->m_wallet->testnet(), dst_addr)) { - m_errorString = "Invalid destination address"; + if(!cryptonote::get_account_integrated_address_from_str(addr, has_short_pid, payment_id_short, m_wallet->m_wallet->testnet(), dst_addr)) { + m_errorString = tr("Invalid destination address"); m_errorCode = Invalid_Address; return false; } - crypto::hash pid32 = cryptonote::null_hash; - bool long_pid = (payment_id.empty())? false : tools::wallet2::parse_long_payment_id(payment_id, pid32); - if(!payment_id.empty() && !long_pid) { - m_errorString = "Invalid payment ID"; + crypto::hash payment_id = cryptonote::null_hash; + bool has_long_pid = (payment_id_str.empty())? false : tools::wallet2::parse_long_payment_id(payment_id_str, payment_id); + + // Short payment id provided + if(payment_id_str.length() == 16) { + m_errorString = tr("Invalid payment ID. Short payment ID should only be used in an integrated address"); + m_errorCode = Invalid_Payment_Id; + return false; + } + + // long payment id provided but not valid + if(!payment_id_str.empty() && !has_long_pid) { + m_errorString = tr("Invalid payment ID"); + m_errorCode = Invalid_Payment_Id; + return false; + } + + // integrated + long payment id provided + if(has_long_pid && has_short_pid) { + m_errorString = tr("Integrated address and long payment id can't be used at the same time"); m_errorCode = Invalid_Payment_Id; return false; } - bool r = m_wallet->m_wallet->add_address_book_row(addr,pid32,description); + // Pad short pid with zeros + if (has_short_pid) + { + memcpy(payment_id.data, payment_id_short.data, 8); + } + + bool r = m_wallet->m_wallet->add_address_book_row(addr,payment_id,description); if (r) refresh(); else @@ -87,7 +108,16 @@ void AddressBookImpl::refresh() std::string payment_id = (row->m_payment_id == cryptonote::null_hash)? "" : epee::string_tools::pod_to_hex(row->m_payment_id); std::string address = cryptonote::get_account_address_as_str(m_wallet->m_wallet->testnet(),row->m_address); - + // convert the zero padded short payment id to integrated address + if (payment_id.length() > 16 && payment_id.substr(16).find_first_not_of('0') == std::string::npos) { + payment_id = payment_id.substr(0,16); + crypto::hash8 payment_id_short; + if(tools::wallet2::parse_short_payment_id(payment_id, payment_id_short)) { + address = cryptonote::get_account_integrated_address_as_str(m_wallet->m_wallet->testnet(), row->m_address, payment_id_short); + // Don't show payment id when integrated address is used + payment_id = ""; + } + } AddressBookRow * abr = new AddressBookRow(i, address, payment_id, row->m_description); m_rows.push_back(abr); } diff --git a/src/wallet/api/address_book.h b/src/wallet/api/address_book.h index 33d06a078..5f72c5860 100644 --- a/src/wallet/api/address_book.h +++ b/src/wallet/api/address_book.h @@ -32,8 +32,7 @@ #include "wallet/wallet2.h" namespace Monero { - -class AddressBookRow; + class WalletImpl; class AddressBookImpl : public AddressBook diff --git a/src/wallet/api/transaction_history.h b/src/wallet/api/transaction_history.h index bd18e9440..37c9ea0e4 100644 --- a/src/wallet/api/transaction_history.h +++ b/src/wallet/api/transaction_history.h @@ -33,7 +33,6 @@ namespace Monero { -class TransactionInfo; class WalletImpl; class TransactionHistoryImpl : public TransactionHistory diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index e8ae7c642..5f7d8e522 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -54,6 +54,8 @@ namespace { static const int MAX_REFRESH_INTERVAL_MILLIS = 1000 * 60 * 1; // Default refresh interval when connected to remote node static const int DEFAULT_REMOTE_NODE_REFRESH_INTERVAL_MILLIS = 1000 * 10; + // Connection timeout 30 sec + static const int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 1000 * 30; } struct Wallet2CallbackImpl : public tools::i_wallet2_callback @@ -83,7 +85,7 @@ struct Wallet2CallbackImpl : public tools::i_wallet2_callback virtual void on_new_block(uint64_t height, const cryptonote::block& block) { - LOG_PRINT_L3(__FUNCTION__ << ": new block. height: " << height); + //LOG_PRINT_L3(__FUNCTION__ << ": new block. height: " << height); if (m_listener) { m_listener->newBlock(height); @@ -662,25 +664,68 @@ UnsignedTransaction *WalletImpl::loadUnsignedTx(const std::string &unsigned_file bool WalletImpl::submitTransaction(const string &fileName) { clearStatus(); - PendingTransactionImpl * transaction = new PendingTransactionImpl(*this); + std::unique_ptr<PendingTransactionImpl> transaction(new PendingTransactionImpl(*this)); -// bool r = m_wallet->load_tx(fileName, transaction->m_pending_tx, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); }); bool r = m_wallet->load_tx(fileName, transaction->m_pending_tx); if (!r) { m_errorString = tr("Failed to load transaction from file"); m_status = Status_Ok; - delete transaction; return false; } if(!transaction->commit()) { m_errorString = transaction->m_errorString; m_status = Status_Error; - delete transaction; return false; } - delete transaction; + return true; +} + +bool WalletImpl::exportKeyImages(const string &filename) +{ + if (m_wallet->watch_only()) + { + m_errorString = tr("Wallet is view only"); + m_status = Status_Error; + return false; + } + + try + { + if (!m_wallet->export_key_images(filename)) + { + m_errorString = tr("failed to save file ") + filename; + m_status = Status_Error; + return false; + } + } + catch (std::exception &e) + { + LOG_ERROR("Error exporting key images: " << e.what()); + m_errorString = e.what(); + m_status = Status_Error; + return false; + } + return true; +} + +bool WalletImpl::importKeyImages(const string &filename) +{ + try + { + uint64_t spent = 0, unspent = 0; + uint64_t height = m_wallet->import_key_images(filename, spent, unspent); + LOG_PRINT_L2("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()); + m_errorString = string(tr("Failed to import key images: ")) + e.what(); + m_status = Status_Error; + return false; + } return true; } @@ -1043,7 +1088,7 @@ bool WalletImpl::verifySignedMessage(const std::string &message, const std::stri bool WalletImpl::connectToDaemon() { - bool result = m_wallet->check_connection(); + bool result = m_wallet->check_connection(NULL, DEFAULT_CONNECTION_TIMEOUT_MILLIS); m_status = result ? Status_Ok : Status_Error; if (!result) { m_errorString = "Error connecting to daemon at " + m_wallet->get_daemon_address(); @@ -1056,7 +1101,7 @@ bool WalletImpl::connectToDaemon() Wallet::ConnectionStatus WalletImpl::connected() const { uint32_t version = 0; - m_is_connected = m_wallet->check_connection(&version); + m_is_connected = m_wallet->check_connection(&version, DEFAULT_CONNECTION_TIMEOUT_MILLIS); if (!m_is_connected) return Wallet::ConnectionStatus_Disconnected; if ((version >> 16) != CORE_RPC_VERSION_MAJOR) @@ -1217,6 +1262,24 @@ bool WalletImpl::parse_uri(const std::string &uri, std::string &address, std::st return m_wallet->parse_uri(uri, address, payment_id, amount, tx_description, recipient_name, unknown_parameters, error); } +bool WalletImpl::rescanSpent() +{ + clearStatus(); + if (!trustedDaemon()) { + m_status = Status_Error; + m_errorString = tr("Rescan spent can only be used with a trusted daemon"); + return false; + } + try { + m_wallet->rescan_spent(); + } catch (const std::exception &e) { + LOG_ERROR(__FUNCTION__ << " error: " << e.what()); + m_status = Status_Error; + m_errorString = e.what(); + return false; + } + return true; +} } // namespace namespace Bitmonero = Monero; diff --git a/src/wallet/api/wallet.h b/src/wallet/api/wallet.h index 5b4064e8e..e3df7fd01 100644 --- a/src/wallet/api/wallet.h +++ b/src/wallet/api/wallet.h @@ -93,7 +93,7 @@ public: void setRefreshFromBlockHeight(uint64_t refresh_from_block_height); void setRecoveringFromSeed(bool recoveringFromSeed); bool watchOnly() const; - + bool rescanSpent(); PendingTransaction * createTransaction(const std::string &dst_addr, const std::string &payment_id, @@ -102,6 +102,8 @@ public: virtual PendingTransaction * createSweepUnmixableTransaction(); bool submitTransaction(const std::string &fileName); virtual UnsignedTransaction * loadUnsignedTx(const std::string &unsigned_filename); + bool exportKeyImages(const std::string &filename); + bool importKeyImages(const std::string &filename); virtual void disposeTransaction(PendingTransaction * t); virtual TransactionHistory * history() const; @@ -127,11 +129,12 @@ private: bool isNewWallet() const; void doInit(const std::string &daemon_address, uint64_t upper_transaction_size_limit); + private: friend class PendingTransactionImpl; friend class UnsignedTransactionImpl; friend class TransactionHistoryImpl; - friend class Wallet2CallbackImpl; + friend struct Wallet2CallbackImpl; friend class AddressBookImpl; tools::wallet2 * m_wallet; diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 48faa3183..12bce0285 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -436,7 +436,7 @@ WalletManager *WalletManagerFactory::getWalletManager() static WalletManagerImpl * g_walletManager = nullptr; if (!g_walletManager) { - epee::log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL, LOG_LEVEL_MAX); + mlog_configure("monero-wallet-gui.log", false); g_walletManager = new WalletManagerImpl(); } @@ -445,7 +445,7 @@ WalletManager *WalletManagerFactory::getWalletManager() void WalletManagerFactory::setLogLevel(int level) { - epee::log_space::log_singletone::get_set_log_detalisation_level(true, level); + mlog_set_log_level(level); } diff --git a/src/wallet/node_rpc_proxy.cpp b/src/wallet/node_rpc_proxy.cpp new file mode 100644 index 000000000..d7f755e36 --- /dev/null +++ b/src/wallet/node_rpc_proxy.cpp @@ -0,0 +1,134 @@ +// Copyright (c) 2017, 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. + +#include "node_rpc_proxy.h" +#include "rpc/core_rpc_server_commands_defs.h" +#include "common/json_util.h" +#include "storages/http_abstract_invoke.h" + +using namespace epee; + +namespace tools +{ + +void NodeRPCProxy::init(const std::string &daemon_address) +{ + m_daemon_address = daemon_address; + + m_height = 0; + m_height_time = 0; + for (auto &slot: m_earliest_height) + slot = 0; + m_dynamic_per_kb_fee_estimate = 0; + m_dynamic_per_kb_fee_estimate_cached_height = 0; + m_dynamic_per_kb_fee_estimate_grace_blocks = 0; +} + +boost::optional<std::string> NodeRPCProxy::get_height(uint64_t &height) +{ + const time_t now = time(NULL); + if (m_height == 0 || now >= m_height_time + 30) // re-cache every 30 seconds + { + cryptonote::COMMAND_RPC_GET_HEIGHT::request req = AUTO_VAL_INIT(req); + cryptonote::COMMAND_RPC_GET_HEIGHT::response res = AUTO_VAL_INIT(res); + + m_daemon_rpc_mutex.lock(); + bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/getheight", req, res, m_http_client); + m_daemon_rpc_mutex.unlock(); + CHECK_AND_ASSERT_MES(r, std::string(), "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(res.status != CORE_RPC_STATUS_BUSY, res.status, "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(res.status == CORE_RPC_STATUS_OK, res.status, "Failed to get current blockchain height"); + m_height = res.height; + m_height_time = now; + } + height = m_height; + return boost::optional<std::string>(); +} + +void NodeRPCProxy::set_height(uint64_t h) +{ + m_height = h; +} + +boost::optional<std::string> NodeRPCProxy::get_earliest_height(uint8_t version, uint64_t &earliest_height) +{ + if (m_earliest_height[version] == 0) + { + epee::json_rpc::request<cryptonote::COMMAND_RPC_HARD_FORK_INFO::request> req_t = AUTO_VAL_INIT(req_t); + epee::json_rpc::response<cryptonote::COMMAND_RPC_HARD_FORK_INFO::response, std::string> resp_t = AUTO_VAL_INIT(resp_t); + + m_daemon_rpc_mutex.lock(); + req_t.jsonrpc = "2.0"; + req_t.id = epee::serialization::storage_entry(0); + req_t.method = "hard_fork_info"; + req_t.params.version = version; + bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/json_rpc", req_t, resp_t, m_http_client); + m_daemon_rpc_mutex.unlock(); + CHECK_AND_ASSERT_MES(r, std::string(), "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(resp_t.result.status != CORE_RPC_STATUS_BUSY, resp_t.result.status, "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(resp_t.result.status == CORE_RPC_STATUS_OK, resp_t.result.status, "Failed to get hard fork status"); + m_earliest_height[version] = resp_t.result.earliest_height; + } + + earliest_height = m_earliest_height[version]; + return boost::optional<std::string>(); +} + +boost::optional<std::string> NodeRPCProxy::get_dynamic_per_kb_fee_estimate(uint64_t grace_blocks, uint64_t &fee) +{ + uint64_t height; + + boost::optional<std::string> result = get_height(height); + if (result) + return result; + + if (m_dynamic_per_kb_fee_estimate_cached_height != height || m_dynamic_per_kb_fee_estimate_grace_blocks != grace_blocks) + { + epee::json_rpc::request<cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request> req_t = AUTO_VAL_INIT(req_t); + epee::json_rpc::response<cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response, std::string> resp_t = AUTO_VAL_INIT(resp_t); + + m_daemon_rpc_mutex.lock(); + req_t.jsonrpc = "2.0"; + req_t.id = epee::serialization::storage_entry(0); + req_t.method = "get_fee_estimate"; + req_t.params.grace_blocks = grace_blocks; + bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/json_rpc", req_t, resp_t, m_http_client); + m_daemon_rpc_mutex.unlock(); + CHECK_AND_ASSERT_MES(r, std::string(), "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(resp_t.result.status != CORE_RPC_STATUS_BUSY, resp_t.result.status, "Failed to connect to daemon"); + CHECK_AND_ASSERT_MES(resp_t.result.status == CORE_RPC_STATUS_OK, resp_t.result.status, "Failed to get fee estimate"); + m_dynamic_per_kb_fee_estimate = resp_t.result.fee; + m_dynamic_per_kb_fee_estimate_cached_height = height; + m_dynamic_per_kb_fee_estimate_grace_blocks = grace_blocks; + } + + fee = m_dynamic_per_kb_fee_estimate; + return boost::optional<std::string>(); +} + +} diff --git a/src/wallet/node_rpc_proxy.h b/src/wallet/node_rpc_proxy.h new file mode 100644 index 000000000..1ae716dab --- /dev/null +++ b/src/wallet/node_rpc_proxy.h @@ -0,0 +1,65 @@ +// Copyright (c) 2017, 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. + +#pragma once + +#include <string> +#include <boost/thread/mutex.hpp> +#include "include_base_utils.h" +#include "net/http_client.h" + +namespace tools +{ + +class NodeRPCProxy +{ +public: + NodeRPCProxy(epee::net_utils::http::http_simple_client &http_client, boost::mutex &mutex): + m_http_client(http_client), m_daemon_rpc_mutex(mutex) { init(""); } + + void init(const std::string &daemon_address); + + boost::optional<std::string> get_height(uint64_t &height); + void set_height(uint64_t h); + boost::optional<std::string> get_earliest_height(uint8_t version, uint64_t &earliest_height); + boost::optional<std::string> get_dynamic_per_kb_fee_estimate(uint64_t grace_blocks, uint64_t &fee); + +private: + std::string m_daemon_address; + epee::net_utils::http::http_simple_client &m_http_client; + boost::mutex &m_daemon_rpc_mutex; + + uint64_t m_height; + time_t m_height_time; + uint64_t m_earliest_height[256]; + uint64_t m_dynamic_per_kb_fee_estimate; + uint64_t m_dynamic_per_kb_fee_estimate_cached_height; + uint64_t m_dynamic_per_kb_fee_estimate_grace_blocks; +}; + +} diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 29cf47ddd..c08b16a5f 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -67,6 +67,9 @@ extern "C" } using namespace cryptonote; +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.wallet2" + // used to choose when to stop adding outputs to a tx #define APPROXIMATE_INPUT_BYTES 80 @@ -92,6 +95,8 @@ using namespace cryptonote; ioservice.stop(); \ } while(0) +#define KEY_IMAGE_EXPORT_FILE_MAGIC "Monero key image export\002" + namespace { // Create on-demand to prevent static initialization order fiasco issues. @@ -391,6 +396,19 @@ std::unique_ptr<tools::wallet2> generate_from_json(const std::string& json_file, return nullptr; } +static void throw_on_rpc_response_error(const boost::optional<std::string> &status, const char *method) +{ + // no error + if (!status) + return; + + // empty string -> not connection + THROW_WALLET_EXCEPTION_IF(status->empty(), tools::error::no_connection_to_daemon, method); + + THROW_WALLET_EXCEPTION_IF(*status == CORE_RPC_STATUS_BUSY, tools::error::daemon_busy, method); + THROW_WALLET_EXCEPTION_IF(*status != CORE_RPC_STATUS_OK, tools::error::wallet_generic_rpc_error, method, *status); +} + } //namespace namespace tools @@ -468,6 +486,7 @@ void wallet2::init(const std::string& daemon_address, uint64_t upper_transaction { m_upper_transaction_size_limit = upper_transaction_size_limit; m_daemon_address = daemon_address; + m_node_rpc_proxy.init(m_daemon_address); } //---------------------------------------------------------------------------------------------------- bool wallet2::is_deterministic() const @@ -1638,7 +1657,10 @@ void wallet2::refresh(uint64_t start_height, uint64_t & blocks_fetched, bool& re blocks_fetched += added_blocks; pull_thread.join(); if(blocks_start_height == next_blocks_start_height) + { + m_node_rpc_proxy.set_height(m_blockchain.size()); break; + } // switch to the new blocks from the daemon blocks_start_height = next_blocks_start_height; @@ -2063,7 +2085,7 @@ crypto::secret_key wallet2::generate(const std::string& wallet_, const std::stri THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); r = file_io_utils::save_string_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str(m_testnet)); - if(!r) LOG_PRINT_RED_L0("String with address text not saved"); + if(!r) MERROR("String with address text not saved"); cryptonote::block b; generate_genesis(b); @@ -2098,7 +2120,7 @@ void wallet2::generate(const std::string& wallet_, const std::string& password, THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); r = file_io_utils::save_string_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str(m_testnet)); - if(!r) LOG_PRINT_RED_L0("String with address text not saved"); + if(!r) MERROR("String with address text not saved"); cryptonote::block b; generate_genesis(b); @@ -2133,7 +2155,7 @@ void wallet2::generate(const std::string& wallet_, const std::string& password, THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); r = file_io_utils::save_string_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str(m_testnet)); - if(!r) LOG_PRINT_RED_L0("String with address text not saved"); + if(!r) MERROR("String with address text not saved"); cryptonote::block b; generate_genesis(b); @@ -2232,7 +2254,7 @@ bool wallet2::prepare_file_names(const std::string& file_path) return true; } //---------------------------------------------------------------------------------------------------- -bool wallet2::check_connection(uint32_t *version) +bool wallet2::check_connection(uint32_t *version, uint32_t timeout) { boost::lock_guard<boost::mutex> lock(m_daemon_rpc_mutex); @@ -2246,7 +2268,7 @@ bool wallet2::check_connection(uint32_t *version) u.port = m_testnet ? config::testnet::RPC_DEFAULT_PORT : config::RPC_DEFAULT_PORT; } - if (!m_http_client.connect(u.host, std::to_string(u.port), 10000)) + if (!m_http_client.connect(u.host, std::to_string(u.port), timeout)) return false; } @@ -2731,7 +2753,7 @@ float wallet2::get_output_relatedness(const transfer_details &td0, const transfe return 0.0f; } //---------------------------------------------------------------------------------------------------- -size_t wallet2::pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_indices, const std::list<size_t>& selected_transfers) const +size_t wallet2::pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_indices, const std::list<size_t>& selected_transfers, bool smallest) const { std::vector<size_t> candidates; float best_relatedness = 1.0f; @@ -2759,13 +2781,30 @@ size_t wallet2::pop_best_value_from(const transfer_container &transfers, std::ve if (relatedness == best_relatedness) candidates.push_back(n); } - size_t idx = crypto::rand<size_t>() % candidates.size(); + + // we have all the least related outputs in candidates, so we can pick either + // the smallest, or a random one, depending on request + size_t idx; + if (smallest) + { + idx = 0; + for (size_t n = 0; n < candidates.size(); ++n) + { + const transfer_details &td = transfers[unused_indices[candidates[n]]]; + if (td.amount() < transfers[unused_indices[candidates[idx]]].amount()) + idx = n; + } + } + else + { + idx = crypto::rand<size_t>() % candidates.size(); + } return pop_index (unused_indices, candidates[idx]); } //---------------------------------------------------------------------------------------------------- -size_t wallet2::pop_best_value(std::vector<size_t> &unused_indices, const std::list<size_t>& selected_transfers) const +size_t wallet2::pop_best_value(std::vector<size_t> &unused_indices, const std::list<size_t>& selected_transfers, bool smallest) const { - return pop_best_value_from(m_transfers, unused_indices, selected_transfers); + return pop_best_value_from(m_transfers, unused_indices, selected_transfers, smallest); } //---------------------------------------------------------------------------------------------------- // Select random input sources for transaction. @@ -3146,7 +3185,7 @@ bool wallet2::sign_tx(unsigned_tx_set &exported_txs, const std::string &signed_f { return false; } - LOG_PRINT_L2("Saving signed tx data: " << oss.str()); + LOG_PRINT_L3("Saving signed tx data: " << oss.str()); return epee::file_io_utils::save_string_to_file(signed_filename, std::string(SIGNED_TX_PREFIX) + oss.str()); } //---------------------------------------------------------------------------------------------------- @@ -3237,20 +3276,12 @@ uint64_t wallet2::get_fee_multiplier(uint32_t priority, bool use_new_fee) const //---------------------------------------------------------------------------------------------------- uint64_t wallet2::get_dynamic_per_kb_fee_estimate() { - epee::json_rpc::request<cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request> req_t = AUTO_VAL_INIT(req_t); - epee::json_rpc::response<cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response, std::string> resp_t = AUTO_VAL_INIT(resp_t); - - m_daemon_rpc_mutex.lock(); - req_t.jsonrpc = "2.0"; - req_t.id = epee::serialization::storage_entry(0); - req_t.method = "get_fee_estimate"; - req_t.params.grace_blocks = FEE_ESTIMATE_GRACE_BLOCKS; - bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/json_rpc", req_t, resp_t, m_http_client); - m_daemon_rpc_mutex.unlock(); - CHECK_AND_ASSERT_THROW_MES(r, "Failed to connect to daemon"); - CHECK_AND_ASSERT_THROW_MES(resp_t.result.status != CORE_RPC_STATUS_BUSY, "Failed to connect to daemon"); - CHECK_AND_ASSERT_THROW_MES(resp_t.result.status == CORE_RPC_STATUS_OK, "Failed to get fee estimate"); - return resp_t.result.fee; + uint64_t fee; + boost::optional<std::string> result = m_node_rpc_proxy.get_dynamic_per_kb_fee_estimate(FEE_ESTIMATE_GRACE_BLOCKS, fee); + if (!result) + return fee; + LOG_PRINT_L1("Failed to query per kB fee, using " << print_money(FEE_PER_KB)); + return FEE_PER_KB; } //---------------------------------------------------------------------------------------------------- uint64_t wallet2::get_per_kb_fee() @@ -3258,15 +3289,8 @@ uint64_t wallet2::get_per_kb_fee() bool use_dyn_fee = use_fork_rules(HF_VERSION_DYNAMIC_FEE, -720 * 1); if (!use_dyn_fee) return FEE_PER_KB; - try - { - return get_dynamic_per_kb_fee_estimate(); - } - catch (...) - { - LOG_PRINT_L1("Failed to query per kB fee, using " << print_money(FEE_PER_KB)); - return FEE_PER_KB; - } + + return get_dynamic_per_kb_fee_estimate(); } //---------------------------------------------------------------------------------------------------- // separated the call(s) to wallet2::transfer into their own function @@ -3378,8 +3402,7 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions(std::vector<crypto } } -template<typename entry> -void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<size_t> &selected_transfers, size_t fake_outputs_count) +void wallet2::get_outs(std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, const std::list<size_t> &selected_transfers, size_t fake_outputs_count) { LOG_PRINT_L2("fake_outputs_count: " << fake_outputs_count); outs.clear(); @@ -3470,6 +3493,7 @@ void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<si uint64_t num_found = 1; seen_indices.emplace(td.m_global_output_index); req.outputs.push_back({amount, td.m_global_output_index}); + LOG_PRINT_L1("Selecting real output: " << td.m_global_output_index << " for " << print_money(amount)); // while we still need more mixins while (num_found < requested_outputs_count) @@ -3541,7 +3565,7 @@ void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<si { const transfer_details &td = m_transfers[idx]; size_t requested_outputs_count = base_requested_outputs_count + (td.is_rct() ? CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW - CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE : 0); - outs.push_back(std::vector<entry>()); + outs.push_back(std::vector<get_outs_entry>()); outs.back().reserve(fake_outputs_count + 1); const rct::key mask = td.is_rct() ? rct::commit(td.amount(), td.m_mask) : rct::zeroCommit(td.amount()); @@ -3594,7 +3618,7 @@ void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<si else { // sort the subsection, so any spares are reset in order - std::sort(outs.back().begin(), outs.back().end(), [](const entry &a, const entry &b) { return std::get<0>(a) < std::get<0>(b); }); + std::sort(outs.back().begin(), outs.back().end(), [](const get_outs_entry &a, const get_outs_entry &b) { return std::get<0>(a) < std::get<0>(b); }); } base += requested_outputs_count; } @@ -3605,7 +3629,7 @@ void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<si for (size_t idx: selected_transfers) { const transfer_details &td = m_transfers[idx]; - std::vector<entry> v; + std::vector<get_outs_entry> v; const rct::key mask = td.is_rct() ? rct::commit(td.amount(), td.m_mask) : rct::zeroCommit(td.amount()); v.push_back(std::make_tuple(td.m_global_output_index, boost::get<txout_to_key>(td.m_tx.vout[td.m_internal_output_index].target).key, mask)); outs.push_back(v); @@ -3614,7 +3638,8 @@ void wallet2::get_outs(std::vector<std::vector<entry>> &outs, const std::list<si } template<typename T> -void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_entry>& dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count, +void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_entry>& dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count, + std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, cryptonote::transaction& tx, pending_tx &ptx) { using namespace cryptonote; @@ -3644,11 +3669,11 @@ void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_ent LOG_PRINT_L2("wanted " << print_money(needed_money) << ", found " << print_money(found_money) << ", fee " << print_money(fee)); THROW_WALLET_EXCEPTION_IF(found_money < needed_money, error::not_enough_money, found_money, needed_money - fee, fee); - typedef std::tuple<uint64_t, crypto::public_key, rct::key> entry; - std::vector<std::vector<entry>> outs; - get_outs(outs, selected_transfers, fake_outputs_count); // may throw + if (outs.empty()) + get_outs(outs, selected_transfers, fake_outputs_count); // may throw //prepare inputs + LOG_PRINT_L2("preparing outputs"); typedef cryptonote::tx_source_entry::output_entry tx_output_entry; size_t i = 0, out_index = 0; std::vector<cryptonote::tx_source_entry> sources; @@ -3691,6 +3716,7 @@ void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_ent detail::print_source_entry(src); ++out_index; } + LOG_PRINT_L2("outputs prepared"); cryptonote::tx_destination_entry change_dts = AUTO_VAL_INIT(change_dts); if (needed_money < found_money) @@ -3713,7 +3739,9 @@ void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_ent } crypto::secret_key tx_key; + LOG_PRINT_L2("constructing tx"); bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), sources, splitted_dsts, extra, tx, unlock_time, tx_key); + LOG_PRINT_L2("constructed tx, r="<<r); THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sources, splitted_dsts, unlock_time, m_testnet); THROW_WALLET_EXCEPTION_IF(upper_transaction_size_limit <= get_object_blobsize(tx), error::tx_too_big, tx, upper_transaction_size_limit); @@ -3749,9 +3777,11 @@ void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_ent ptx.construction_data.unlock_time = unlock_time; ptx.construction_data.use_rct = false; ptx.construction_data.dests = dsts; + LOG_PRINT_L2("transfer_selected done"); } void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry> dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count, + std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx &ptx) { using namespace cryptonote; @@ -3760,7 +3790,7 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry uint64_t upper_transaction_size_limit = get_upper_tranaction_size_limit(); uint64_t needed_money = fee; - LOG_PRINT_L2("transfer: starting with fee " << print_money (needed_money)); + LOG_PRINT_L2("transfer_selected_rct: starting with fee " << print_money (needed_money)); LOG_PRINT_L0("selected transfers: "); for (auto t: selected_transfers) LOG_PRINT_L2(" " << t); @@ -3784,11 +3814,11 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry LOG_PRINT_L2("wanted " << print_money(needed_money) << ", found " << print_money(found_money) << ", fee " << print_money(fee)); THROW_WALLET_EXCEPTION_IF(found_money < needed_money, error::not_enough_money, found_money, needed_money - fee, fee); - typedef std::tuple<uint64_t, crypto::public_key, rct::key> entry; - std::vector<std::vector<entry>> outs; - get_outs(outs, selected_transfers, fake_outputs_count); // may throw + if (outs.empty()) + get_outs(outs, selected_transfers, fake_outputs_count); // may throw //prepare inputs + LOG_PRINT_L2("preparing outputs"); size_t i = 0, out_index = 0; std::vector<cryptonote::tx_source_entry> sources; BOOST_FOREACH(size_t idx, selected_transfers) @@ -3831,6 +3861,7 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry detail::print_source_entry(src); ++out_index; } + LOG_PRINT_L2("outputs prepared"); // we still keep a copy, since we want to keep dsts free of change for user feedback purposes std::vector<cryptonote::tx_destination_entry> splitted_dsts = dsts; @@ -3842,9 +3873,11 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry // the sender with a 0 amount output. We send a 0 amount in order to avoid // letting the destination be able to work out which of the inputs is the // real one in our rings + LOG_PRINT_L2("generating dummy address for 0 change"); cryptonote::account_base dummy; dummy.generate(); change_dts.addr = dummy.get_keys().m_account_address; + LOG_PRINT_L2("generated dummy address for 0 change"); } else { @@ -3853,10 +3886,13 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry splitted_dsts.push_back(change_dts); crypto::secret_key tx_key; + LOG_PRINT_L2("constructing tx"); bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), sources, splitted_dsts, extra, tx, unlock_time, tx_key, true); + LOG_PRINT_L2("constructed tx, r="<<r); THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sources, dsts, unlock_time, m_testnet); THROW_WALLET_EXCEPTION_IF(upper_transaction_size_limit <= get_object_blobsize(tx), error::tx_too_big, tx, upper_transaction_size_limit); + LOG_PRINT_L2("gathering key images"); std::string key_images; bool all_are_txin_to_key = std::all_of(tx.vin.begin(), tx.vin.end(), [&](const txin_v& s_e) -> bool { @@ -3865,6 +3901,7 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry return true; }); THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, tx); + LOG_PRINT_L2("gathered key images"); ptx.key_images = key_images; ptx.fee = fee; @@ -3883,6 +3920,7 @@ void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry ptx.construction_data.unlock_time = unlock_time; ptx.construction_data.use_rct = true; ptx.construction_data.dests = dsts; + LOG_PRINT_L2("transfer_selected_rct done"); } static size_t estimate_rct_tx_size(int n_inputs, int mixin, int n_outputs) @@ -4084,12 +4122,14 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp accumulated_change = 0; adding_fee = false; needed_fee = 0; + std::vector<std::vector<tools::wallet2::get_outs_entry>> outs; // for rct, since we don't see the amounts, we will try to make all transactions // look the same, with 1 or 2 inputs, and 2 outputs. One input is preferable, as // this prevents linking to another by provenance analysis, but two is ok if we // try to pick outputs not from the same block. We will get two outputs, one for // the destination, and one for change. + LOG_PRINT_L2("checking preferred"); std::vector<size_t> prefered_inputs; uint64_t rct_outs_needed = 2 * (fake_outs_count + 1); rct_outs_needed += 100; // some fudge factor since we don't know how many are locked @@ -4106,9 +4146,13 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp LOG_PRINT_L1("Found prefered rct inputs for rct tx: " << s); } } + LOG_PRINT_L2("done checking preferred"); - // while we have something to send - while ((!dsts.empty() && dsts[0].amount > 0) || adding_fee) { + // while: + // - we have something to send + // - or we need to gather more fee + // - or we have just one input in that tx, which is rct (to try and make all/most rct txes 2/2) + while ((!dsts.empty() && dsts[0].amount > 0) || adding_fee || (use_rct && txes.back().selected_transfers.size() == 1)) { TX &tx = txes.back(); // if we need to spend money and don't have any left, we fail @@ -4119,7 +4163,14 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp // get a random unspent output and use it to pay part (or all) of the current destination (and maybe next one, etc) // This could be more clever, but maybe at the cost of making probabilistic inferences easier - size_t idx = !prefered_inputs.empty() ? pop_back(prefered_inputs) : !unused_transfers_indices.empty() ? pop_best_value(unused_transfers_indices, tx.selected_transfers) : pop_best_value(unused_dust_indices, tx.selected_transfers); + size_t idx; + if ((dsts.empty() || dsts[0].amount == 0) && !adding_fee) + // the "make rct txes 2/2" case - we pick a small value output to "clean up" the wallet too + idx = pop_best_value(unused_dust_indices.empty() ? unused_transfers_indices : unused_dust_indices, tx.selected_transfers, true); + else if (!prefered_inputs.empty()) + idx = pop_back(prefered_inputs); + else + idx = pop_best_value(unused_transfers_indices.empty() ? 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); @@ -4129,6 +4180,9 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp uint64_t available_amount = td.amount(); accumulated_outputs += available_amount; + // clear any fake outs we'd already gathered, since we'll need a new set + outs.clear(); + if (adding_fee) { LOG_PRINT_L2("We need more fee, adding it to fee"); @@ -4185,10 +4239,10 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp LOG_PRINT_L2("Trying to create a tx now, with " << tx.dsts.size() << " destinations and " << tx.selected_transfers.size() << " outputs"); if (use_rct) - transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx); else - transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx); auto txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(fee_per_kb, txBlob, fee_multiplier); @@ -4226,13 +4280,19 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryp else { LOG_PRINT_L2("We made a tx, adjusting fee and saving it"); - if (use_rct) - transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, - test_tx, test_ptx); - else - transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, - detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx); - txBlob = t_serializable_object_to_blob(test_ptx.tx); + do { + if (use_rct) + transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, + test_tx, test_ptx); + else + transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, + detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx); + txBlob = t_serializable_object_to_blob(test_ptx.tx); + needed_fee = calculate_fee(fee_per_kb, txBlob, fee_multiplier); + LOG_PRINT_L2("Made an attempt at a final " << ((txBlob.size() + 1023)/1024) << " kB tx, with " << print_money(test_ptx.fee) << + " fee and " << print_money(test_ptx.change_dts.amount) << " change"); + } while (needed_fee > test_ptx.fee); + LOG_PRINT_L2("Made a final " << ((txBlob.size() + 1023)/1024) << " kB tx, with " << print_money(test_ptx.fee) << " fee and " << print_money(test_ptx.change_dts.amount) << " change"); @@ -4313,6 +4373,7 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_from(const crypton std::vector<TX> txes; uint64_t needed_fee, available_for_fee = 0; uint64_t upper_transaction_size_limit = get_upper_tranaction_size_limit(); + std::vector<std::vector<get_outs_entry>> outs; const bool use_rct = fake_outs_count > 0 && use_fork_rules(4, 0); const bool use_new_fee = use_fork_rules(3, -720 * 14); @@ -4348,6 +4409,9 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_from(const crypton uint64_t available_amount = td.amount(); accumulated_outputs += available_amount; + // clear any fake outs we'd already gathered, since we'll need a new set + 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_size_limit); @@ -4369,10 +4433,10 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_from(const crypton LOG_PRINT_L2("Trying to create a tx now, with " << tx.dsts.size() << " destinations and " << tx.selected_transfers.size() << " outputs"); if (use_rct) - transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx); else - transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx); auto txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(fee_per_kb, txBlob, fee_multiplier); @@ -4386,10 +4450,10 @@ std::vector<wallet2::pending_tx> wallet2::create_transactions_from(const crypton LOG_PRINT_L2("We made a tx, adjusting fee and saving it"); tx.dsts[0].amount = available_for_fee - needed_fee; if (use_rct) - transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, test_tx, test_ptx); else - transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, unlock_time, needed_fee, extra, + transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, unlock_time, needed_fee, extra, detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx); txBlob = t_serializable_object_to_blob(test_ptx.tx); needed_fee = calculate_fee(fee_per_kb, txBlob, fee_multiplier); @@ -4451,39 +4515,19 @@ uint64_t wallet2::unlocked_dust_balance(const tx_dust_policy &dust_policy) const //---------------------------------------------------------------------------------------------------- void wallet2::get_hard_fork_info(uint8_t version, uint64_t &earliest_height) { - epee::json_rpc::request<cryptonote::COMMAND_RPC_HARD_FORK_INFO::request> req_t = AUTO_VAL_INIT(req_t); - epee::json_rpc::response<cryptonote::COMMAND_RPC_HARD_FORK_INFO::response, std::string> resp_t = AUTO_VAL_INIT(resp_t); - - m_daemon_rpc_mutex.lock(); - req_t.jsonrpc = "2.0"; - req_t.id = epee::serialization::storage_entry(0); - req_t.method = "hard_fork_info"; - req_t.params.version = version; - bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/json_rpc", req_t, resp_t, m_http_client); - m_daemon_rpc_mutex.unlock(); - CHECK_AND_ASSERT_THROW_MES(r, "Failed to connect to daemon"); - CHECK_AND_ASSERT_THROW_MES(resp_t.result.status != CORE_RPC_STATUS_BUSY, "Failed to connect to daemon"); - CHECK_AND_ASSERT_THROW_MES(resp_t.result.status == CORE_RPC_STATUS_OK, "Failed to get hard fork status"); - - earliest_height = resp_t.result.earliest_height; + boost::optional<std::string> result = m_node_rpc_proxy.get_earliest_height(version, earliest_height); + throw_on_rpc_response_error(result, "get_hard_fork_info"); } //---------------------------------------------------------------------------------------------------- bool wallet2::use_fork_rules(uint8_t version, int64_t early_blocks) { - cryptonote::COMMAND_RPC_GET_HEIGHT::request req = AUTO_VAL_INIT(req); - cryptonote::COMMAND_RPC_GET_HEIGHT::response res = AUTO_VAL_INIT(res); - - m_daemon_rpc_mutex.lock(); - bool r = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/getheight", req, res, m_http_client); - m_daemon_rpc_mutex.unlock(); - CHECK_AND_ASSERT_MES(r, false, "Failed to connect to daemon"); - CHECK_AND_ASSERT_MES(res.status != CORE_RPC_STATUS_BUSY, false, "Failed to connect to daemon"); - CHECK_AND_ASSERT_MES(res.status == CORE_RPC_STATUS_OK, false, "Failed to get current blockchain height"); + uint64_t height, earliest_height; + boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); + throw_on_rpc_response_error(result, "get_info"); + result = m_node_rpc_proxy.get_earliest_height(version, earliest_height); + throw_on_rpc_response_error(result, "get_hard_fork_info"); - uint64_t earliest_height; - get_hard_fork_info(version, earliest_height); // can throw - - bool close_enough = res.height >= earliest_height - early_blocks; // start using the rules that many blocks beforehand + bool close_enough = height >= earliest_height - early_blocks; // start using the rules that many blocks beforehand if (close_enough) LOG_PRINT_L2("Using v" << (unsigned)version << " rules"); else @@ -4672,34 +4716,17 @@ std::string wallet2::get_daemon_address() const uint64_t wallet2::get_daemon_blockchain_height(string &err) { - // XXX: DRY violation. copy-pasted from simplewallet.cpp:get_daemon_blockchain_height() - // consider to move it from simplewallet to wallet2 ? - COMMAND_RPC_GET_HEIGHT::request req; - COMMAND_RPC_GET_HEIGHT::response res = boost::value_initialized<COMMAND_RPC_GET_HEIGHT::response>(); - m_daemon_rpc_mutex.lock(); - bool ok = net_utils::invoke_http_json_remote_command2(m_daemon_address + "/getheight", req, res, m_http_client); - m_daemon_rpc_mutex.unlock(); - // XXX: DRY violation. copy-pasted from simplewallet.cpp:interpret_rpc_response() - if (ok) - { - if (res.status == CORE_RPC_STATUS_BUSY) - { - err = "daemon is busy. Please try again later."; - } - else if (res.status != CORE_RPC_STATUS_OK) - { - err = res.status; - } - else // success, cleaning up error message - { - err = ""; - } - } - else + uint64_t height; + + boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); + if (result) { - err = "possibly lost connection to daemon"; + err = *result; + return 0; } - return res.height; + + err = ""; + return height; } uint64_t wallet2::get_daemon_blockchain_target_height(string &err) @@ -4841,6 +4868,27 @@ crypto::public_key wallet2::get_tx_pub_key_from_received_outs(const tools::walle "Public key yielding at least one output wasn't found in the transaction extra"); return cryptonote::null_pkey; } + +bool wallet2::export_key_images(const std::string filename) +{ + std::vector<std::pair<crypto::key_image, crypto::signature>> ski = export_key_images(); + std::string magic(KEY_IMAGE_EXPORT_FILE_MAGIC, strlen(KEY_IMAGE_EXPORT_FILE_MAGIC)); + const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; + + std::string data; + data += std::string((const char *)&keys.m_spend_public_key, sizeof(crypto::public_key)); + data += std::string((const char *)&keys.m_view_public_key, sizeof(crypto::public_key)); + for (const auto &i: ski) + { + data += std::string((const char *)&i.first, sizeof(crypto::key_image)); + data += std::string((const char *)&i.second, sizeof(crypto::signature)); + } + + // encrypt data, keep magic plaintext + std::string ciphertext = encrypt_with_view_secret_key(data); + return epee::file_io_utils::save_string_to_file(filename, magic + ciphertext); +} + //---------------------------------------------------------------------------------------------------- std::vector<std::pair<crypto::key_image, crypto::signature>> wallet2::export_key_images() const { @@ -4891,6 +4939,70 @@ std::vector<std::pair<crypto::key_image, crypto::signature>> wallet2::export_key } return ski; } + +uint64_t wallet2::import_key_images(const std::string &filename, uint64_t &spent, uint64_t &unspent) +{ + std::string data; + bool r = epee::file_io_utils::load_file_to_string(filename, data); + + if (!r) + { + fail_msg_writer() << tr("failed to read file ") << filename; + return 0; + } + const size_t magiclen = strlen(KEY_IMAGE_EXPORT_FILE_MAGIC); + if (data.size() < magiclen || memcmp(data.data(), KEY_IMAGE_EXPORT_FILE_MAGIC, magiclen)) + { + fail_msg_writer() << "Bad key image export file magic in " << filename; + return 0; + } + + try + { + data = decrypt_with_view_secret_key(std::string(data, magiclen)); + } + catch (const std::exception &e) + { + fail_msg_writer() << "Failed to decrypt " << filename << ": " << e.what(); + return 0; + } + + const size_t headerlen = 2 * sizeof(crypto::public_key); + if (data.size() < headerlen) + { + fail_msg_writer() << "Bad data size from file " << filename; + return 0; + } + const crypto::public_key &public_spend_key = *(const crypto::public_key*)&data[0]; + const crypto::public_key &public_view_key = *(const crypto::public_key*)&data[sizeof(crypto::public_key)]; + const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; + if (public_spend_key != keys.m_spend_public_key || public_view_key != keys.m_view_public_key) + { + fail_msg_writer() << "Key images from " << filename << " are for a different account"; + return 0; + } + + const size_t record_size = sizeof(crypto::key_image) + sizeof(crypto::signature); + if ((data.size() - headerlen) % record_size) + { + fail_msg_writer() << "Bad data size from file " << filename; + return 0; + } + size_t nki = (data.size() - headerlen) / record_size; + + std::vector<std::pair<crypto::key_image, crypto::signature>> ski; + ski.reserve(nki); + for (size_t n = 0; n < nki; ++n) + { + crypto::key_image key_image = *reinterpret_cast<const crypto::key_image*>(&data[headerlen + n * record_size]); + crypto::signature signature = *reinterpret_cast<const crypto::signature*>(&data[headerlen + n * record_size + sizeof(crypto::key_image)]); + + ski.push_back(std::make_pair(key_image, signature)); + } + + return import_key_images(ski, spent, unspent); +} + //---------------------------------------------------------------------------------------------------- uint64_t wallet2::import_key_images(const std::vector<std::pair<crypto::key_image, crypto::signature>> &signed_key_images, uint64_t &spent, uint64_t &unspent) { @@ -5030,7 +5142,7 @@ std::string wallet2::encrypt(const std::string &plaintext, const crypto::secret_ crypto::signature &signature = *(crypto::signature*)&ciphertext[ciphertext.size() - sizeof(crypto::signature)]; crypto::generate_signature(hash, pkey, skey, signature); } - return std::move(ciphertext); + return ciphertext; } //---------------------------------------------------------------------------------------------------- std::string wallet2::encrypt_with_view_secret_key(const std::string &plaintext, bool authenticated) const @@ -5060,7 +5172,7 @@ std::string wallet2::decrypt(const std::string &ciphertext, const crypto::secret error::wallet_internal_error, "Failed to authenticate criphertext"); } crypto::chacha8(ciphertext.data() + sizeof(iv), ciphertext.size() - prefix_size, key, iv, &plaintext[0]); - return std::move(plaintext); + return plaintext; } //---------------------------------------------------------------------------------------------------- std::string wallet2::decrypt_with_view_secret_key(const std::string &ciphertext, bool authenticated) const @@ -5098,7 +5210,7 @@ std::string wallet2::make_uri(const std::string &address, const std::string &pay } std::string uri = "monero:" + address; - bool n_fields = 0; + unsigned int n_fields = 0; if (!payment_id.empty()) { @@ -5210,6 +5322,92 @@ bool wallet2::parse_uri(const std::string &uri, std::string &address, std::strin return true; } //---------------------------------------------------------------------------------------------------- +uint64_t wallet2::get_blockchain_height_by_date(uint16_t year, uint8_t month, uint8_t day) +{ + uint32_t version; + if (!check_connection(&version)) + { + throw std::runtime_error("failed to connect to daemon: " + get_daemon_address()); + } + if (version < MAKE_CORE_RPC_VERSION(1, 6)) + { + throw std::runtime_error("this function requires RPC version 1.6 or higher"); + } + std::tm date = { 0, 0, 0, 0, 0, 0, 0, 0 }; + date.tm_year = year - 1900; + date.tm_mon = month - 1; + date.tm_mday = day; + if (date.tm_mon < 0 || 11 < date.tm_mon || date.tm_mday < 1 || 31 < date.tm_mday) + { + throw std::runtime_error("month or day out of range"); + } + uint64_t timestamp_target = std::mktime(&date); + std::string err; + uint64_t height_min = 0; + uint64_t height_max = get_daemon_blockchain_height(err) - 1; + if (!err.empty()) + { + throw std::runtime_error("failed to get blockchain height"); + } + while (true) + { + COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::request req; + COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::response res; + uint64_t height_mid = (height_min + height_max) / 2; + req.heights = + { + height_min, + height_mid, + height_max + }; + bool r = net_utils::invoke_http_bin_remote_command2(get_daemon_address() + "/getblocks_by_height.bin", req, res, m_http_client); + if (!r || res.status != CORE_RPC_STATUS_OK) + { + std::ostringstream oss; + oss << "failed to get blocks by heights: "; + for (auto height : req.heights) + oss << height << ' '; + oss << endl << "reason: "; + if (!r) + oss << "possibly lost connection to daemon"; + else if (res.status == CORE_RPC_STATUS_BUSY) + oss << "daemon is busy"; + else + oss << res.status; + throw std::runtime_error(oss.str()); + } + cryptonote::block blk_min, blk_mid, blk_max; + if (!parse_and_validate_block_from_blob(res.blocks[0].block, blk_min)) throw std::runtime_error("failed to parse blob at height " + height_min); + if (!parse_and_validate_block_from_blob(res.blocks[1].block, blk_mid)) throw std::runtime_error("failed to parse blob at height " + height_mid); + if (!parse_and_validate_block_from_blob(res.blocks[2].block, blk_max)) throw std::runtime_error("failed to parse blob at height " + height_max); + uint64_t timestamp_min = blk_min.timestamp; + uint64_t timestamp_mid = blk_mid.timestamp; + uint64_t timestamp_max = blk_max.timestamp; + if (!(timestamp_min <= timestamp_mid && timestamp_mid <= timestamp_max)) + { + // the timestamps are not in the chronological order. + // assuming they're sufficiently close to each other, simply return the smallest height + return std::min({height_min, height_mid, height_max}); + } + if (timestamp_target > timestamp_max) + { + throw std::runtime_error("specified date is in the future"); + } + if (timestamp_target <= timestamp_min + 2 * 24 * 60 * 60) // two days of "buffer" period + { + return height_min; + } + if (timestamp_target <= timestamp_mid) + height_max = height_mid; + else + height_min = height_mid; + if (height_max - height_min <= 2 * 24 * 30) // don't divide the height range finer than two days + { + return height_min; + } + } +} +//---------------------------------------------------------------------------------------------------- void wallet2::generate_genesis(cryptonote::block& b) { if (m_testnet) { diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 5883102bc..629011800 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -54,8 +54,13 @@ #include "wallet_errors.h" #include "password_container.h" +#include "node_rpc_proxy.h" #include <iostream> + +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.wallet2" + #define WALLET_RCP_CONNECTION_TIMEOUT 200000 class Serialization_portability_wallet_Test; @@ -99,7 +104,7 @@ namespace tools }; private: - wallet2(const wallet2&) : m_run(true), m_callback(0), m_testnet(false), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true) {} + wallet2(const wallet2&) : m_run(true), m_callback(0), m_testnet(false), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_node_rpc_proxy(m_http_client, m_daemon_rpc_mutex) {} public: static const char* tr(const char* str);// { return i18n_translate(str, "cryptonote::simple_wallet"); } @@ -120,7 +125,7 @@ namespace tools //! Uses stdin and stdout. Returns a wallet2 and password for wallet with no file if no errors. static std::pair<std::unique_ptr<wallet2>, password_container> make_new(const boost::program_options::variables_map& vm); - wallet2(bool testnet = false, bool restricted = false) : m_run(true), m_callback(0), m_testnet(testnet), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_restricted(restricted), is_old_file_format(false) {} + wallet2(bool testnet = false, bool restricted = false) : m_run(true), m_callback(0), m_testnet(testnet), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_restricted(restricted), is_old_file_format(false), m_node_rpc_proxy(m_http_client, m_daemon_rpc_mutex) {} struct transfer_details { uint64_t m_block_height; @@ -271,6 +276,8 @@ namespace tools std::string m_description; }; + typedef std::tuple<uint64_t, crypto::public_key, rct::key> get_outs_entry; + /*! * \brief Generates a wallet or restores one. * \param wallet_ Name of wallet file @@ -383,8 +390,10 @@ namespace tools void transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx& ptx, bool trusted_daemon); template<typename T> void transfer_selected(const std::vector<cryptonote::tx_destination_entry>& dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count, + std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, cryptonote::transaction& tx, pending_tx &ptx); void transfer_selected_rct(std::vector<cryptonote::tx_destination_entry> dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count, + std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx &ptx); void commit_tx(pending_tx& ptx_vector); @@ -402,7 +411,7 @@ namespace tools std::vector<wallet2::pending_tx> create_transactions_all(const cryptonote::account_public_address &address, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon); std::vector<wallet2::pending_tx> create_transactions_from(const cryptonote::account_public_address &address, std::vector<size_t> unused_transfers_indices, std::vector<size_t> unused_dust_indices, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon); std::vector<pending_tx> create_unmixable_sweep_transactions(bool trusted_daemon); - bool check_connection(uint32_t *version = NULL); + bool check_connection(uint32_t *version = NULL, uint32_t timeout = 200000); void get_transfers(wallet2::transfer_container& incoming_transfers) const; void get_payments(const crypto::hash& payment_id, std::list<wallet2::payment_details>& payments, uint64_t min_height = 0) const; void get_payments(std::list<std::pair<crypto::hash,wallet2::payment_details>>& payments, uint64_t min_height, uint64_t max_height = (uint64_t)-1) const; @@ -527,8 +536,8 @@ namespace tools std::vector<size_t> select_available_unmixable_outputs(bool trusted_daemon); std::vector<size_t> select_available_mixable_outputs(bool trusted_daemon); - size_t pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers) const; - size_t pop_best_value(std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers) const; + size_t pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers, bool smallest = false) const; + size_t pop_best_value(std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers, bool smallest = false) const; void set_tx_note(const crypto::hash &txid, const std::string ¬e); std::string get_tx_note(const crypto::hash &txid) const; @@ -539,8 +548,10 @@ namespace tools std::vector<tools::wallet2::transfer_details> export_outputs() const; size_t import_outputs(const std::vector<tools::wallet2::transfer_details> &outputs); + bool export_key_images(const std::string filename); std::vector<std::pair<crypto::key_image, crypto::signature>> export_key_images() const; uint64_t import_key_images(const std::vector<std::pair<crypto::key_image, crypto::signature>> &signed_key_images, uint64_t &spent, uint64_t &unspent); + uint64_t import_key_images(const std::string &filename, uint64_t &spent, uint64_t &unspent); void update_pool_state(); @@ -552,6 +563,8 @@ namespace tools std::string make_uri(const std::string &address, const std::string &payment_id, uint64_t amount, const std::string &tx_description, const std::string &recipient_name, std::string &error); bool parse_uri(const std::string &uri, std::string &address, std::string &payment_id, uint64_t &amount, std::string &tx_description, std::string &recipient_name, std::vector<std::string> &unknown_parameters, std::string &error); + uint64_t get_blockchain_height_by_date(uint16_t year, uint8_t month, uint8_t day); // 1<=month<=12, 1<=day<=31 + private: /*! * \brief Stores wallet information to wallet file. @@ -599,8 +612,7 @@ namespace tools std::vector<size_t> pick_preferred_rct_inputs(uint64_t needed_money) const; void set_spent(size_t idx, uint64_t height); void set_unspent(size_t idx); - template<typename entry> - void get_outs(std::vector<std::vector<entry>> &outs, const std::list<size_t> &selected_transfers, size_t fake_outputs_count); + void get_outs(std::vector<std::vector<get_outs_entry>> &outs, const std::list<size_t> &selected_transfers, size_t fake_outputs_count); bool wallet_generate_key_image_helper(const cryptonote::account_keys& ack, const crypto::public_key& tx_public_key, size_t real_output_index, cryptonote::keypair& in_ephemeral, crypto::key_image& ki); crypto::public_key get_tx_pub_key_from_received_outs(const tools::wallet2::transfer_details &td) const; @@ -644,6 +656,7 @@ namespace tools bool m_auto_refresh; uint64_t m_refresh_from_block_height; bool m_confirm_missing_payment_id; + NodeRPCProxy m_node_rpc_proxy; }; } BOOST_CLASS_VERSION(tools::wallet2, 16) diff --git a/src/wallet/wallet2_api.h b/src/wallet/wallet2_api.h index daffb48bf..5a13205c5 100644 --- a/src/wallet/wallet2_api.h +++ b/src/wallet/wallet2_api.h @@ -513,6 +513,21 @@ struct Wallet */ virtual void disposeTransaction(PendingTransaction * t) = 0; + /*! + * \brief exportKeyImages - exports key images to file + * \param filename + * \return - true on success + */ + virtual bool exportKeyImages(const std::string &filename) = 0; + + /*! + * \brief importKeyImages - imports key images from file + * \param filename + * \return - true on success + */ + virtual bool importKeyImages(const std::string &filename) = 0; + + virtual TransactionHistory * history() const = 0; virtual AddressBook * addressBook() const = 0; virtual void setListener(WalletListener *) = 0; @@ -558,6 +573,11 @@ struct Wallet virtual bool verifySignedMessage(const std::string &message, const std::string &addres, const std::string &signature) const = 0; virtual bool parse_uri(const std::string &uri, std::string &address, std::string &payment_id, uint64_t &amount, std::string &tx_description, std::string &recipient_name, std::vector<std::string> &unknown_parameters, std::string &error) = 0; + /* + * \brief rescanSpent - Rescan spent outputs - Can only be used with trusted daemon + * \return true on success + */ + virtual bool rescanSpent() = 0; }; /** diff --git a/src/wallet/wallet_args.cpp b/src/wallet/wallet_args.cpp index f7eec8cfc..7ec4ad6e4 100644 --- a/src/wallet/wallet_args.cpp +++ b/src/wallet/wallet_args.cpp @@ -40,6 +40,9 @@ #include <crtdbg.h> #endif +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.wallet2" + // workaround for a suspected bug in pthread/kernel on MacOS X #ifdef __APPLE__ #define DEFAULT_MAX_CONCURRENCY 1 @@ -78,7 +81,7 @@ namespace wallet_args _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif - const command_line::arg_descriptor<uint32_t> arg_log_level = {"log-level", "", LOG_LEVEL_0}; + const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""}; const command_line::arg_descriptor<uint32_t> 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<std::string> arg_log_file = {"log-file", wallet_args::tr("Specify log file"), ""}; @@ -93,26 +96,7 @@ namespace wallet_args command_line::add_arg(desc_general, command_line::arg_help); command_line::add_arg(desc_general, command_line::arg_version); - - bf::path default_log {epee::log_space::log_singletone::get_default_log_folder()}; - std::string log_file_name = epee::log_space::log_singletone::get_default_log_file(); - if (log_file_name.empty()) - { - // Sanity check: File path should also be empty if file name is. If not, - // this would be a problem in epee's discovery of current process's file - // path. - if (! default_log.empty()) - { - tools::fail_msg_writer() << wallet_args::tr("unexpected empty log file name in presence of non-empty file path"); - return boost::none; - } - // epee didn't find path to executable from argv[0], so use this default file name. - log_file_name = "monero-wallet-cli.log"; - // The full path will use cwd because epee also returned an empty default log folder. - } - default_log /= log_file_name; - - command_line::add_arg(desc_params, arg_log_file, default_log.string()); + command_line::add_arg(desc_params, arg_log_file, ""); command_line::add_arg(desc_params, arg_log_level); command_line::add_arg(desc_params, arg_max_concurrency); @@ -146,39 +130,28 @@ namespace wallet_args if (!r) return boost::none; - // log_file_path - // default: < argv[0] directory >/monero-wallet-cli.log - // so if ran as "monero-wallet-cli" (no path), log file will be in cwd - // - // if log-file argument given: - // absolute path - // relative path: relative to cwd - - // Set log file - bf::path log_file_path {bf::absolute(command_line::get_arg(vm, arg_log_file))}; - - // Set up logging options - int log_level = LOG_LEVEL_2; - epee::log_space::get_set_log_detalisation_level(true, log_level); - //epee::log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL, LOG_LEVEL_0); - epee::log_space::log_singletone::add_logger(LOGGER_FILE, - log_file_path.filename().string().c_str(), - log_file_path.parent_path().string().c_str(), - LOG_LEVEL_4 - ); - if(command_line::has_arg(vm, arg_max_concurrency)) tools::set_max_concurrency(command_line::get_arg(vm, arg_max_concurrency)); - tools::scoped_message_writer(epee::log_space::console_color_white, true) << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")"; + std::string log_path; + if (!vm["log-file"].defaulted()) + log_path = command_line::get_arg(vm, arg_log_file); + else + log_path = mlog_get_default_log_path("monero-wallet-cli,log"); + mlog_configure(log_path, false); + if (!vm["log-level"].defaulted()) + { + mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); + } + + tools::scoped_message_writer(epee::console_color_white, true) << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")"; - if(command_line::has_arg(vm, arg_log_level)) - log_level = command_line::get_arg(vm, arg_log_level); - LOG_PRINT_L0("Setting log level = " << log_level); - LOG_PRINT_L0(wallet_args::tr("default_log: ") << default_log.string()); - tools::scoped_message_writer(epee::log_space::console_color_white, true) << boost::format(wallet_args::tr("Logging at log level %d to %s")) % - log_level % log_file_path.string(); - epee::log_space::get_set_log_detalisation_level(true, log_level); + if (!vm["log-level"].defaulted()) + MINFO("Setting log level = " << command_line::get_arg(vm, arg_log_level)); + else + MINFO("Setting log levels = " << getenv("MONERO_LOGS")); + MINFO(wallet_args::tr("Logging to: ") << log_path); + tools::scoped_message_writer(epee::console_color_white, true) << boost::format(wallet_args::tr("Logging to %s")) % log_path; return {std::move(vm)}; } diff --git a/src/wallet/wallet_errors.h b/src/wallet/wallet_errors.h index 93e7c2ec3..785a72e4b 100644 --- a/src/wallet/wallet_errors.h +++ b/src/wallet/wallet_errors.h @@ -626,6 +626,18 @@ namespace tools std::string m_request; }; //---------------------------------------------------------------------------------------------------- + struct wallet_generic_rpc_error : public wallet_rpc_error + { + explicit wallet_generic_rpc_error(std::string&& loc, const std::string& request, const std::string& status) + : wallet_rpc_error(std::move(loc), std::string("error in ") + request + " RPC: " + status, request), + m_status(status) + { + } + const std::string& status() const { return m_status; } + private: + const std::string m_status; + }; + //---------------------------------------------------------------------------------------------------- struct daemon_busy : public wallet_rpc_error { explicit daemon_busy(std::string&& loc, const std::string& request) diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index d61b11f8a..33e099ceb 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -46,6 +46,9 @@ using namespace epee; #include "string_tools.h" #include "crypto/hash.h" +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.rpc" + namespace { const command_line::arg_descriptor<std::string, true> arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"}; @@ -393,6 +396,7 @@ namespace tools std::vector<cryptonote::tx_destination_entry> dsts; std::vector<uint8_t> extra; + LOG_PRINT_L3("on_transfer_split starts"); if (m_wallet.restricted()) { er.code = WALLET_RPC_ERROR_CODE_DENIED; @@ -482,9 +486,13 @@ namespace tools mixin = 2; } std::vector<wallet2::pending_tx> ptx_vector; + LOG_PRINT_L2("on_transfer_split calling create_transactions_2"); ptx_vector = m_wallet.create_transactions_2(dsts, mixin, req.unlock_time, req.priority, extra, req.trusted_daemon); + LOG_PRINT_L2("on_transfer_split called create_transactions_2"); + LOG_PRINT_L2("on_transfer_split calling commit_txyy"); m_wallet.commit_tx(ptx_vector); + LOG_PRINT_L2("on_transfer_split called commit_txyy"); // populate response with tx hashes for (auto & ptx : ptx_vector) @@ -1323,7 +1331,8 @@ int main(int argc, char** argv) { return 1; } - epee::log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL, LOG_LEVEL_2); + mlog_configure("monero-wallet-rpc.log", true); + mlog_set_log_level(2); std::unique_ptr<tools::wallet2> wal; try @@ -1368,12 +1377,12 @@ int main(int argc, char** argv) { // if we ^C during potentially length load/refresh, there's no server loop yet if (quit) { - LOG_PRINT_L0(tools::wallet_rpc_server::tr("Storing wallet...")); + MINFO(tools::wallet_rpc_server::tr("Storing wallet...")); wal->store(); - LOG_PRINT_GREEN(tools::wallet_rpc_server::tr("Stored ok"), LOG_LEVEL_0); + MINFO(tools::wallet_rpc_server::tr("Stored ok")); return 1; } - LOG_PRINT_GREEN(tools::wallet_rpc_server::tr("Loaded ok"), LOG_LEVEL_0); + MINFO(tools::wallet_rpc_server::tr("Loaded ok")); } catch (const std::exception& e) { @@ -1393,7 +1402,7 @@ int main(int argc, char** argv) { { LOG_PRINT_L0(tools::wallet_rpc_server::tr("Storing wallet...")); wal->store(); - LOG_PRINT_GREEN(tools::wallet_rpc_server::tr("Stored ok"), LOG_LEVEL_0); + LOG_PRINT_L0(tools::wallet_rpc_server::tr("Stored ok")); } catch (const std::exception& e) { diff --git a/src/wallet/wallet_rpc_server.h b/src/wallet/wallet_rpc_server.h index 4ff1b267f..7d5db1bcb 100644 --- a/src/wallet/wallet_rpc_server.h +++ b/src/wallet/wallet_rpc_server.h @@ -36,6 +36,10 @@ #include "net/http_server_impl_base.h" #include "wallet_rpc_server_commands_defs.h" #include "wallet2.h" + +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.rpc" + namespace tools { /************************************************************************/ diff --git a/src/wallet/wallet_rpc_server_commands_defs.h b/src/wallet/wallet_rpc_server_commands_defs.h index ea0fc685f..4d643637f 100644 --- a/src/wallet/wallet_rpc_server_commands_defs.h +++ b/src/wallet/wallet_rpc_server_commands_defs.h @@ -33,6 +33,10 @@ #include "cryptonote_core/cryptonote_basic.h" #include "crypto/hash.h" #include "wallet_rpc_server_error_codes.h" + +#undef MONERO_DEFAULT_LOG_CATEGORY +#define MONERO_DEFAULT_LOG_CATEGORY "wallet.rpc" + namespace tools { namespace wallet_rpc |