diff --git a/src/utils/gen_utils.h b/src/utils/gen_utils.h index 3278fba3..15def2ae 100644 --- a/src/utils/gen_utils.h +++ b/src/utils/gen_utils.h @@ -62,6 +62,8 @@ #include #include "rapidjson/document.h" #include +#include +#include #include #include #include @@ -91,27 +93,19 @@ namespace gen_utils } static bool is_uint64_t(const std::string& str) { + if (str.empty() || !std::all_of(str.begin(), str.end(), [](char c) { return std::isdigit(static_cast(c)); })) return false; try { size_t sz; - std::stol(str, &sz); + std::stoull(str, &sz); return sz == str.size(); } - catch (const std::invalid_argument&) { - // if no conversion could be performed. - return false; - } - catch (const std::out_of_range&) { - // if the converted value would fall out of the range of the result type. - return false; - } + catch (const std::invalid_argument&) { return false; } + catch (const std::out_of_range&) { return false; } } static uint64_t uint64_t_cast(const std::string& str) { if (!is_uint64_t(str)) throw std::out_of_range("String provided is not a valid uint64_t"); - uint64_t value; - std::istringstream itr(str); - itr >> value; - return value; + return std::stoull(str); } static uint64_t timestamp_to_epoch(const std::string& iso_timestamp) { diff --git a/src/utils/monero_utils.cpp b/src/utils/monero_utils.cpp index e35bf2b1..5b0709dd 100644 --- a/src/utils/monero_utils.cpp +++ b/src/utils/monero_utils.cpp @@ -792,7 +792,7 @@ bool monero_utils::parse_payment_id_short(const std::string& payment_id_str, cry return true; } -std::shared_ptr monero_utils::generate_key_image(const crypto::public_key &ephem_pubkey, const size_t tx_output_index, const cryptonote::subaddress_index &received_subaddr, const cryptonote::account_base& account) { +std::shared_ptr monero_utils::generate_key_image(const crypto::public_key &ephem_pubkey, const size_t tx_output_index, const cryptonote::subaddress_index &received_subaddr, const cryptonote::account_base& account, const boost::optional& expected_output_pubkey) { // - R: ephem_pubkey // - a: ack.m_view_secret_key [private viewkey] // - b: ack.m_spend_secret_key [private spendkey] @@ -824,14 +824,19 @@ std::shared_ptr monero_utils::generate_key_image(const crypto: crypto::public_key onetime_pubkey; CHECK_AND_ASSERT_THROW_MES(hwdev.secret_key_to_public_key(onetime_privkey, onetime_pubkey), "Failed to make public key"); + // the wallet derived the one-time key from the transaction key and its own, so a server that names + // another one-time key for the output says the wallet owns money that it does not + if (expected_output_pubkey != boost::none && onetime_pubkey != *expected_output_pubkey) throw std::runtime_error("The one-time key of the output does not match the one the wallet derived"); + // 6. Key image I = x Hp(K) crypto::key_image ki; hwdev.generate_key_image(onetime_pubkey, onetime_privkey, ki); - // sign the key image with the output secret key + // sign the key image with the output secret key over the one-time key it spends: the verifier checks + // the signature against that key, and one over the transaction key would never verify crypto::signature signature; std::vector key_ptrs; - key_ptrs.push_back(&ephem_pubkey); + key_ptrs.push_back(&onetime_pubkey); crypto::generate_ring_signature((const crypto::hash&)ki, ki, key_ptrs, onetime_privkey, 0, &signature); diff --git a/src/utils/monero_utils.h b/src/utils/monero_utils.h index 8c813fff..9992aee0 100644 --- a/src/utils/monero_utils.h +++ b/src/utils/monero_utils.h @@ -240,7 +240,7 @@ namespace monero_utils * @param account recipient's account * @return the generated key image */ - std::shared_ptr generate_key_image(const crypto::public_key &ephem_pubkey, const size_t tx_output_index, const cryptonote::subaddress_index &received_subaddr, const cryptonote::account_base& account); + std::shared_ptr generate_key_image(const crypto::public_key &ephem_pubkey, const size_t tx_output_index, const cryptonote::subaddress_index &received_subaddr, const cryptonote::account_base& account, const boost::optional& expected_output_pubkey = boost::none); // ----------------------------- GATHER BLOCKS ------------------------------ diff --git a/src/utils/monero_wallet_utils.cpp b/src/utils/monero_wallet_utils.cpp index 80882d7e..ad22e5e7 100644 --- a/src/utils/monero_wallet_utils.cpp +++ b/src/utils/monero_wallet_utils.cpp @@ -156,7 +156,9 @@ std::shared_ptr monero_wallet_utils::ptx_to_tx(const tools::wa output->m_subaddress_index = subaddress_idx; output->m_is_spent = false; output->m_is_frozen = false; - bool is_change = cd.change_dts.amount > 0 && dest.amount == cd.change_dts.amount && change_output == nullptr; + // the change is the output that pays the address of the change, and not the first one of its + // amount, which a destination can share: wallet2 tells them apart the same way + bool is_change = cd.change_dts.amount > 0 && dest.addr == cd.change_dts.addr && change_output == nullptr; if (is_change) { change_output = output; } diff --git a/src/wallet/monero_wallet_full.cpp b/src/wallet/monero_wallet_full.cpp index acbe9d69..419a3153 100644 --- a/src/wallet/monero_wallet_full.cpp +++ b/src/wallet/monero_wallet_full.cpp @@ -3034,7 +3034,9 @@ namespace monero { uint64_t num_confirmations; m_w2->check_tx_key(_tx_hash, _tx_key, additional_tx_keys, info.address, received_amount, in_tx_pool, num_confirmations); std::shared_ptr check_tx = std::make_shared(); - check_tx->m_is_good = true; // check is good if we get this far + // a key that is not the one of the tx, or a tx that did not pay the address, receives nothing: the + // check says it is not good and not that it erred + check_tx->m_is_good = received_amount > 0; check_tx->m_received_amount = received_amount; check_tx->m_in_tx_pool = in_tx_pool; check_tx->m_num_confirmations = num_confirmations; diff --git a/src/wallet/monero_wallet_light.cpp b/src/wallet/monero_wallet_light.cpp index ea094c56..ef787a39 100644 --- a/src/wallet/monero_wallet_light.cpp +++ b/src/wallet/monero_wallet_light.cpp @@ -186,16 +186,12 @@ namespace monero { // ----------------------- INTERNAL PRIVATE HELPERS ----------------------- bool output_before(const std::shared_ptr& ow1, const std::shared_ptr& ow2) { - // compare by account index, subaddress index, output index, then global index - if (ow1->m_recipient->m_maj_i < ow2->m_recipient->m_maj_i) return true; - if (ow1->m_recipient->m_maj_i == ow2->m_recipient->m_maj_i) { - if (ow1->m_recipient->m_min_i < ow2->m_recipient->m_min_i) return true; - if (ow1->m_recipient->m_min_i == ow2->m_recipient->m_min_i) { - if (ow1->m_global_index.get() < ow2->m_global_index.get()) return true; - if (ow1->m_global_index.get() == ow2->m_global_index.get()) throw std::runtime_error("Should never sort outputs with duplicate indices"); - } - } - return false; + // compare by account index, subaddress index, amount, then global index: the global index of a + // pre-rct output counts within its amount, so two outputs of different amounts can share it + if (ow1->m_recipient->m_maj_i != ow2->m_recipient->m_maj_i) return ow1->m_recipient->m_maj_i < ow2->m_recipient->m_maj_i; + if (ow1->m_recipient->m_min_i != ow2->m_recipient->m_min_i) return ow1->m_recipient->m_min_i < ow2->m_recipient->m_min_i; + if (ow1->m_amount.get() != ow2->m_amount.get()) return ow1->m_amount.get() < ow2->m_amount.get(); + return ow1->m_global_index.get() < ow2->m_global_index.get(); } void normalize_subaddress_indices(const std::shared_ptr& tx, const tools::wallet2::pending_tx& ptx, const std::vector>& outs) { @@ -596,8 +592,8 @@ namespace monero { std::vector sources; LOG_PRINT_L2("preparing outputs"); for (size_t out_index = 0; out_index < outputs.size(); out_index++) { + if (outputs[out_index]->m_amount.get() > UINT64_MAX - found_money) throw std::runtime_error("input amount overflow"); found_money += outputs[out_index]->m_amount.get(); - if (found_money > UINT64_MAX) throw std::runtime_error("input amount overflow"); auto src = cryptonote::tx_source_entry{}; src.amount = outputs[out_index]->m_amount.get(); @@ -852,7 +848,7 @@ namespace monero { } } - if (!found && !additional_derivations.empty()) { + if (!found && output_index < additional_derivations.size()) { const crypto::key_derivation& additional_derivation = additional_derivations[output_index]; if (cryptonote::out_can_be_to_acc(view_tag_opt, additional_derivation, output_index)) { if (!crypto::derive_public_key(additional_derivation, output_index, address.m_spend_public_key, derived_out_key)) throw std::runtime_error("Failed to derive public key"); @@ -1047,7 +1043,7 @@ namespace monero { // build dummy input for notification // TODO: this provides one input with outgoing amount like monero-wallet-rpc client, use real inputs instead std::shared_ptr input = std::make_shared(); - input->m_amount = tx->m_outgoing_transfer->m_amount.get() + tx->m_fee.get(); + input->m_amount = tx->m_outgoing_transfer->m_amount.get() + tx->m_fee.value_or(0); input->m_account_index = tx->m_outgoing_transfer->m_account_index; if (tx->m_outgoing_transfer->m_subaddress_indices.size() == 1) input->m_subaddress_index = tx->m_outgoing_transfer->m_subaddress_indices[0]; // initialize if transfer sourced from single subaddress std::shared_ptr tx_notify = std::make_shared(); @@ -1087,7 +1083,13 @@ namespace monero { return true; } catch (const monero_rpc_error& ex) { - return ex.code == 401; + // a light wallet server answers that the account of the keys does not exist with a forbidden, and + // never with the unauthorized of an http server + if (ex.code == 403) return false; + throw; + } + catch (const monero_error&) { + return false; // a server that does not answer has no wallet on it to find } } @@ -1175,7 +1177,7 @@ namespace monero { if (offset_set) spend_key_sk = cryptonote::decrypt_key(spend_key_sk, config.m_seed_offset.get()); // initialize wallet account - monero_wallet_light* wallet = new monero_wallet_light(rpc); + std::unique_ptr wallet(new monero_wallet_light(rpc)); // freed when the setup throws wallet->m_account = cryptonote::account_base{}; crypto::secret_key spend_key_val = wallet->m_account.generate(spend_key_sk, true, false); @@ -1200,7 +1202,7 @@ namespace monero { } else if (config.m_restore_height != boost::none) throw std::runtime_error("Cannote restore wallet from height: wallet is not connected to lws"); - return wallet; + return wallet.release(); } monero_wallet_light* monero_wallet_light::create_wallet_from_keys(monero_wallet_config& config, const std::shared_ptr& rpc) { @@ -1261,7 +1263,7 @@ namespace monero { } // initialize wallet account - monero_wallet_light* wallet = new monero_wallet_light(rpc); + std::unique_ptr wallet(new monero_wallet_light(rpc)); // freed when the setup throws if (has_spend_key && has_view_key) wallet->m_account.create_from_keys(address_info.address, spend_key_sk, view_key_sk); else if (has_spend_key) wallet->m_account.generate(spend_key_sk, true, false); else wallet->m_account.create_from_viewkey(address_info.address, view_key_sk); @@ -1286,7 +1288,7 @@ namespace monero { } else if (config.m_restore_height != boost::none) throw std::runtime_error("Cannot restore wallet from height: wallet is not connected to lws"); - return wallet; + return wallet.release(); } monero_wallet_light* monero_wallet_light::create_wallet_random(monero_wallet_config& config, const std::shared_ptr& rpc) { @@ -1299,7 +1301,7 @@ namespace monero { if (!monero_utils::is_valid_language(config_normalized.m_language.get())) throw std::runtime_error("Unknown language: " + config_normalized.m_language.get()); // initialize random wallet account - monero_wallet_light* wallet = new monero_wallet_light(rpc); + std::unique_ptr wallet(new monero_wallet_light(rpc)); // freed when the setup throws crypto::secret_key spend_key_sk = wallet->m_account.generate(); // initialize remaining wallet @@ -1322,7 +1324,7 @@ namespace monero { } } - return wallet; + return wallet.release(); } // ----------------------------- WALLET METHODS ----------------------------- @@ -1346,6 +1348,14 @@ namespace monero { return m_rpc; } + void monero_wallet_light::set_daemon_connection(const std::string& uri, const std::string& username, const std::string& password, const std::string& proxy_uri, const boost::optional& is_trusted) { + throw std::runtime_error("Cannot set daemon connection for light wallet: light wallets use a light wallet server (monero-lws), not a daemon"); + } + + void monero_wallet_light::set_daemon_connection(const std::shared_ptr& connection, const boost::optional& is_trusted) { + throw std::runtime_error("Cannot set daemon connection for light wallet: light wallets use a light wallet server (monero-lws), not a daemon"); + } + bool monero_wallet_light::is_connected_to_daemon() const { assert_not_closed(); m_is_connected = m_client->is_connected(); @@ -1376,16 +1386,19 @@ namespace monero { void monero_wallet_light::add_listener(monero_wallet_listener& listener) { assert_not_closed(); + boost::lock_guard guard(m_listeners_mutex); m_listeners.insert(&listener); } void monero_wallet_light::remove_listener(monero_wallet_listener& listener) { assert_not_closed(); + boost::lock_guard guard(m_listeners_mutex); m_listeners.erase(&listener); } std::set monero_wallet_light::get_listeners() { assert_not_closed(); + boost::lock_guard guard(m_listeners_mutex); return m_listeners; } @@ -1456,6 +1469,9 @@ namespace monero { void monero_wallet_light::scan_txs(const std::vector& tx_ids) { assert_not_closed(); + // a light wallet server has no call for the transactions of ids, so the wallet cannot scan them: it + // syncs, which picks up every transaction the server has for the account + if (!tx_ids.empty()) throw std::runtime_error("command not supported by light wallet: scanning transactions of ids"); sync(); } @@ -1501,6 +1517,7 @@ namespace monero { uint64_t monero_wallet_light::get_height() const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the scanned height while the sync thread refreshes the cache return m_cache->get_scanned_block_height() + 1; } @@ -1509,7 +1526,7 @@ namespace monero { const uint64_t from_height = restore_height > 0 ? restore_height - 1 : 0; auto response = m_client->import_request(from_height); if (response->m_import_fee != boost::none && response->m_import_fee.get() > 0) { - throw std::runtime_error("Payment is required to rescan blockchain: address " + response->m_payment_address.get() + ", amount " + std::to_string(response->m_import_fee.get())); + throw std::runtime_error("Payment is required to rescan blockchain: address " + response->m_payment_address.value_or("") + ", amount " + std::to_string(response->m_import_fee.get())); } // only update the cache once the server confirms the import took effect; otherwise wait for refresh() if (response->m_request_fullfilled != boost::none && response->m_request_fullfilled.get()) { @@ -1539,31 +1556,37 @@ namespace monero { uint64_t monero_wallet_light::get_balance() const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_balance(); } uint64_t monero_wallet_light::get_balance(uint32_t account_index) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_balance(account_index); } uint64_t monero_wallet_light::get_balance(uint32_t account_idx, uint32_t subaddress_idx) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_balance(account_idx, subaddress_idx); } uint64_t monero_wallet_light::get_unlocked_balance() const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_unlocked_balance(); } uint64_t monero_wallet_light::get_unlocked_balance(uint32_t account_index) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_unlocked_balance(account_index); } uint64_t monero_wallet_light::get_unlocked_balance(uint32_t account_idx, uint32_t subaddress_idx) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balance while the sync thread recalculates it return m_cache->get_unlocked_balance(account_idx, subaddress_idx); } @@ -1622,6 +1645,7 @@ namespace monero { std::vector monero_wallet_light::get_subaddresses(const uint32_t account_idx, const std::vector& subaddress_indices) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balances while the sync thread recalculates them std::vector subaddresses = get_subaddresses_aux(account_idx, subaddress_indices); for(monero_subaddress& subaddress : subaddresses) m_cache->init_subaddress(subaddress); return subaddresses; @@ -1662,6 +1686,7 @@ namespace monero { monero_subaddress monero_wallet_light::get_subaddress(const uint32_t account_idx, const uint32_t subaddress_idx) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the balances while the sync thread recalculates them std::vector indices; indices.push_back(subaddress_idx); std::vector subaddresses = monero_wallet_keys::get_subaddresses(account_idx, indices); @@ -1675,8 +1700,12 @@ namespace monero { assert_not_closed(); sync_op_lock op_lock(*this); // do not refresh while relaying txs - // relay each metadata as a tx + // relay each metadata as a tx; the transactions relay one by one, so a failure after the first leaves them + // on the network that no returned list names: a submit that fails is collected per transaction and the set + // is tried to its end, and the report names the hashes that went out, so a caller that rebuilds knows what + // already pays std::vector tx_hashes; + std::vector failed; for (const auto& tx_metadata : tx_metadatas) { // parse tx metadata hex cryptonote::blobdata blob; @@ -1703,21 +1732,43 @@ namespace monero { // commit tx std::string full_hex = epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(ptx.tx)); - try { m_client->submit_raw_tx(full_hex); } - catch (const std::exception& e) { throw std::runtime_error("Failed to commit tx"); } - std::string change_pubkey; - std::shared_ptr tx = monero_wallet_utils::ptx_to_tx(ptx, static_cast(m_network_type), this, &change_pubkey); - tx->m_full_hex = full_hex; - m_cache->add_unconfirmed_tx(tx, change_pubkey); - // collect resulting hash + std::string failure; + std::shared_ptr submit_res; + try { submit_res = m_client->submit_raw_tx(full_hex); } + catch (const std::exception& e) { failure = std::string("Failed to commit tx: ") + e.what(); } + if (failure.empty() && (submit_res == nullptr || submit_res->m_status == boost::none || submit_res->m_status.get() != std::string("OK") || submit_res->m_not_relayed.value_or(false))) { + failure = "Failed to commit tx" + (submit_res != nullptr && submit_res->m_status != boost::none ? (": " + submit_res->m_status.get()) : std::string()); + } + if (!failure.empty()) { + failed.push_back(failure); + continue; + } + // the tx is on the network now, so a failure of the bookkeeping that follows is reported with its + // hash and the set is tried to its end like a submit that fails std::string pending_tx_hash = epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)); + try { + std::string change_pubkey; + std::shared_ptr tx = monero_wallet_utils::ptx_to_tx(ptx, static_cast(m_network_type), this, &change_pubkey); + tx->m_full_hex = full_hex; + m_cache->add_unconfirmed_tx(tx, change_pubkey); + } catch (const std::exception& e) { + failed.push_back(pending_tx_hash + " relayed but not tracked: " + e.what()); + continue; + } + // collect resulting hash tx_hashes.push_back(pending_tx_hash); } - if (!tx_metadatas.empty()) m_cache->calculate_balance(); - - // notify listeners of spent funds - m_wallet_listener->on_spend_tx_hashes(tx_hashes); + if (!tx_hashes.empty()) m_cache->calculate_balance(); // the transactions that relayed are in the cache + op_lock.unlock(); // the listener reads the balances of the wallet through the lock itself, and the pool that runs it must not wait on this one + m_wallet_listener->on_spend_tx_hashes(tx_hashes); // notify listeners of the funds that left, also when a later one failed + if (!failed.empty()) { + std::string relayed_list; + for (const auto& h : tx_hashes) relayed_list += (relayed_list.empty() ? "" : ", ") + h; + std::string failed_list; + for (const auto& f : failed) failed_list += (failed_list.empty() ? "" : "; ") + f; + throw std::runtime_error("failed to relay " + std::to_string(failed.size()) + " of " + std::to_string(tx_metadatas.size()) + " transactions" + (tx_hashes.empty() ? std::string() : "; already relayed: " + relayed_list) + "; " + failed_list); + } // return relayed tx hashes return tx_hashes; @@ -1908,25 +1959,47 @@ namespace monero { try { ptx_vector = monero_wallet_utils::parse_signed_tx(blob, m_account.get_keys().m_view_secret_key); } catch (const std::exception &e) { throw std::runtime_error(std::string("Failed to parse signed tx: ") + e.what()); } - try { - std::vector tx_hashes; - for (auto &ptx: ptx_vector) { + // the transactions relay one by one, so a failure after the first leaves them on the network that no + // returned list names: a submit that fails is collected per transaction and the set is tried to its end, + // and the report names the hashes that went out, so a caller that rebuilds knows what already pays + std::vector refused; + std::vector tx_hashes; + for (auto &ptx: ptx_vector) { + std::string pending_tx_hash = epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)); + std::string failure; + try { const auto res = m_client->submit_raw_tx(epee::string_tools::buff_to_hex_nodelimer(cryptonote::tx_to_blob(ptx.tx))); - if (res->m_status == boost::none || res->m_status.get() != std::string("OK")) throw std::runtime_error("Could not relay tx" + signed_tx_hex); - crypto::hash txid; - txid = cryptonote::get_transaction_hash(ptx.tx); - std::string pending_tx_hash = epee::string_tools::pod_to_hex(txid); - tx_hashes.push_back(pending_tx_hash); + if (res->m_status == boost::none || res->m_status.get() != std::string("OK")) failure = res->m_status ? *res->m_status : std::string("no status"); + else if (res->m_not_relayed.value_or(false)) failure = "not relayed"; + } catch (const std::exception &e) { failure = e.what(); } + if (!failure.empty()) { + refused.push_back(pending_tx_hash + ": " + failure); + continue; + } + tx_hashes.push_back(pending_tx_hash); + // the tx is on the network now, so a failure of the bookkeeping that follows is reported with its + // hash and the set is tried to its end like a submit that fails + try { std::string change_pubkey; std::shared_ptr tx = monero_wallet_utils::ptx_to_tx(ptx, static_cast(m_network_type), this, &change_pubkey); m_cache->add_unconfirmed_tx(tx, change_pubkey); + } catch (const std::exception &e) { + refused.push_back(pending_tx_hash + " relayed but not tracked: " + e.what()); + continue; } + } - m_wallet_listener->on_spend_tx_hashes(tx_hashes); // notify listeners of spent funds - return tx_hashes; - } catch (const std::exception &e) { - throw std::runtime_error(std::string("Failed to submit signed tx: ") + e.what()); + m_cache->calculate_balance(); // the pending spends change the balances, which a wallet that does not sync in the background keeps otherwise stale + op_lock.unlock(); // the listener reads the balances of the wallet through the lock itself, and the pool that runs it must not wait on this one + m_wallet_listener->on_spend_tx_hashes(tx_hashes); // notify listeners of spent funds + if (!refused.empty()) { + std::string relayed_list; + for (const auto& h : tx_hashes) relayed_list += (relayed_list.empty() ? "" : ", ") + h; + std::string refused_list; + for (const auto& r : refused) refused_list += (refused_list.empty() ? "" : "; ") + r; + throw std::runtime_error("the server did not relay " + std::to_string(refused.size()) + " of " + std::to_string(ptx_vector.size()) + " transactions" + (tx_hashes.empty() ? std::string() : "; already relayed: " + relayed_list) + "; not relayed: " + refused_list); } + return tx_hashes; } // implementation based on monero-project's wallet2::get_tx_key() @@ -1938,6 +2011,8 @@ namespace monero { crypto::hash txid; if (!epee::string_tools::hex_to_pod(tx_hash, txid)) throw std::runtime_error("TX hash has invalid format"); + sync_op_lock op_lock(*this); // do not read the tx keys while another thread adds one + crypto::secret_key tx_key; std::vector additional_tx_keys; @@ -2009,7 +2084,7 @@ namespace monero { // this wallet only has raw tx bytes cached for txs it itself built and relayed std::shared_ptr cached_tx = m_cache->get_self_constructed_tx(tx_hash); if (cached_tx == nullptr || cached_tx->m_full_hex == boost::none || cached_tx->m_full_hex->empty()) { - throw std::runtime_error("No tx secret key is stored for this tx"); + throw std::runtime_error("No tx is stored for this tx hash: a light wallet checks a tx key against the raw tx of one it built itself"); } cryptonote::blobdata tx_blob; @@ -2024,16 +2099,32 @@ namespace monero { received_amount = tx_builder.compute_amount_received(tx, _tx_key, additional_tx_keys, info.address); } - bool in_tx_pool = cached_tx->m_in_tx_pool != boost::none && cached_tx->m_in_tx_pool.get(); + // a tx that the wallet relayed is in the pool until the next sync sees it in the chain: the state of + // the chain names it, and not the copy that the relay left, which stays in the pool forever + bool in_tx_pool; uint64_t num_confirmations = 0; - if (!in_tx_pool) { - uint64_t tx_height = cached_tx->get_height().value_or(0); - uint64_t chain_height = get_daemon_height(); - if (chain_height > tx_height) num_confirmations = chain_height - tx_height; + try { + const auto tx = m_cache->get_tx(tx_hash); + in_tx_pool = tx->m_mempool.get(); + if (!in_tx_pool) { + uint64_t tx_height = tx->m_height.get(); + uint64_t chain_height = get_daemon_height(); + if (chain_height > tx_height) num_confirmations = chain_height - tx_height; + } + } catch (const std::runtime_error&) { + // the tx is not in the store of the account yet, so only the copy of the relay tells its state + in_tx_pool = cached_tx->m_in_tx_pool != boost::none && cached_tx->m_in_tx_pool.get(); + if (!in_tx_pool) { + uint64_t tx_height = cached_tx->get_height().value_or(0); + uint64_t chain_height = get_daemon_height(); + if (chain_height > tx_height) num_confirmations = chain_height - tx_height; + } } std::shared_ptr check_tx = std::make_shared(); - check_tx->m_is_good = true; // check is good if we get this far + // a key that is not the one of the tx, or a tx that did not pay the address, receives nothing: the + // check says it is not good and not that it erred + check_tx->m_is_good = received_amount > 0; check_tx->m_received_amount = received_amount; check_tx->m_in_tx_pool = in_tx_pool; check_tx->m_num_confirmations = num_confirmations; @@ -2067,6 +2158,9 @@ namespace monero { MINFO("monero_wallet_light::create_txs()"); assert_not_closed(); if (is_multisig()) throw std::runtime_error("Multisig wallet not supported"); + // a view-only wallet cannot sign what it builds, so a tx that it submits is garbage that the daemon + // refuses: it builds the unsigned set instead, which a full wallet signs and submits + if (config.m_relay != boost::none && config.m_relay.get() && is_view_only()) throw std::runtime_error("Cannot relay from a view-only wallet"); if (!m_is_connected) throw std::runtime_error("Wallet is not connected to daemon"); // validate config @@ -2158,7 +2252,7 @@ namespace monero { if (relay) { try { auto submit_res = m_client->submit_raw_tx(full_hex); - if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK")) { + if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK") && !submit_res->m_not_relayed.value_or(false)) { MINFO("monero_wallet_light::create_txs(): relayed tx"); relayed = true; } @@ -2208,6 +2302,7 @@ namespace monero { m_cache->calculate_balance(); + op_lock.unlock(); // the listener reads the balances of the wallet through the lock itself, and the pool that runs it must not wait on this one if (any_relayed) m_wallet_listener->on_spend_txs(result); return result; @@ -2215,6 +2310,9 @@ namespace monero { std::vector> monero_wallet_light::sweep_account(const monero_tx_config& config) { MINFO("monero_wallet_light::sweep_account()"); + // a view-only wallet cannot sign what it sweeps, so a tx that it submits is garbage that the daemon + // refuses: it builds the unsigned set instead, which a full wallet signs and submits + if (config.m_relay != boost::none && config.m_relay.get() && is_view_only()) throw std::runtime_error("Cannot relay from a view-only wallet"); assert_not_closed(); if (is_multisig()) throw std::runtime_error("Multisig wallet not supported"); if (!m_is_connected) throw std::runtime_error("Wallet is not connected to daemon"); @@ -2245,10 +2343,20 @@ namespace monero { tx_builder tx_builder(static_cast(m_network_type), m_account.get_keys(), is_view_only(), *m_client, m_cache); std::vector unsigned_construction_data; + // a sweep of many outputs relays one tx per iteration, so a build that fails after the first leaves + // them on the network that no returned list names: the build that fails stops the loop, and the + // report names the hashes that went out, so a caller that rebuilds knows what already pays + std::vector failed; while (!unspent_outs.empty()) { cryptonote::blobdata tx_blob; - tools::wallet2::pending_tx ptx = tx_builder.build(subaddr_account_idx, {dest_address}, config.m_payment_id, {}, true, simple_priority, unspent_outs, fee_per_b, fee_mask, tx_blob); + tools::wallet2::pending_tx ptx; + try { + ptx = tx_builder.build(subaddr_account_idx, {dest_address}, config.m_payment_id, {}, true, simple_priority, unspent_outs, fee_per_b, fee_mask, tx_blob); + } catch (const std::exception& e) { + failed.push_back(e.what()); + break; + } std::string full_hex = epee::string_tools::buff_to_hex_nodelimer(tx_blob); if (ptx.tx_key != crypto::null_skey) { @@ -2277,7 +2385,7 @@ namespace monero { if (relay) { try { auto submit_res = m_client->submit_raw_tx(full_hex); - if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK")) { + if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK") && !submit_res->m_not_relayed.value_or(false)) { MINFO("monero_wallet_light::sweep_account(): relayed tx"); relayed = true; } @@ -2310,6 +2418,14 @@ namespace monero { if (!is_view_only() && relayed) m_cache->add_unconfirmed_tx(tx, change_pubkey); } + if (!failed.empty()) { + std::string relayed_list; + for (const auto& tx : result) if (tx->m_is_relayed == true) relayed_list += (relayed_list.empty() ? "" : ", ") + tx->m_hash.get(); + std::string failed_list; + for (const auto& f : failed) failed_list += (failed_list.empty() ? "" : "; ") + f; + throw std::runtime_error("failed to sweep " + std::to_string(failed.size()) + " of the remaining transactions" + (result.empty() ? std::string() : "; already relayed: " + relayed_list) + "; " + failed_list); + } + std::string unsigned_tx_hex; if (is_view_only()) { unsigned_tx_hex = monero_wallet_utils::dump_unsigned_tx(unsigned_construction_data, config.m_payment_id, m_cache->export_outputs(true, 0), m_account.get_keys().m_view_secret_key); @@ -2375,12 +2491,16 @@ namespace monero { } // notify listeners of spent funds + op_lock.unlock(); // the listener reads the balances of the wallet through the lock itself, and the pool that runs it must not wait on this one if (config.m_relay != boost::none && config.m_relay.get()) m_wallet_listener->on_spend_txs(txs); return txs; } std::shared_ptr monero_wallet_light::sweep_output(const monero_tx_config& config) { MINFO("monero_wallet_light::sweep_output()"); + // a view-only wallet cannot sign what it sweeps, so a tx that it submits is garbage that the daemon + // refuses: it builds the unsigned set instead, which a full wallet signs and submits + if (config.m_relay != boost::none && config.m_relay.get() && is_view_only()) throw std::runtime_error("Cannot relay from a view-only wallet"); assert_not_closed(); if (is_multisig()) throw std::runtime_error("Multisig wallet not supported"); if (!m_is_connected) throw std::runtime_error("Wallet is not connected to daemon"); @@ -2430,7 +2550,7 @@ namespace monero { if (relay) { try { auto submit_res = m_client->submit_raw_tx(full_hex); - if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK")) { + if (submit_res->m_status != boost::none && submit_res->m_status == std::string("OK") && !submit_res->m_not_relayed.value_or(false)) { MINFO("monero_wallet_light::sweep_output(): relayed tx"); relayed = true; } @@ -2473,6 +2593,7 @@ namespace monero { m_cache->calculate_balance(); + op_lock.unlock(); // the listener reads the balances of the wallet through the lock itself, and the pool that runs it must not wait on this one if (relayed) m_wallet_listener->on_spend_txs(result); return unconfirmed_tx; @@ -2486,6 +2607,7 @@ namespace monero { std::vector> monero_wallet_light::get_txs(const monero_tx_query& query) const { MTRACE("monero_wallet_light::get_txs(query)"); assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the txs while the sync thread reassigns them // copy query std::shared_ptr query_sp = std::make_shared(query); // convert to shared pointer @@ -2591,6 +2713,7 @@ namespace monero { std::vector> monero_wallet_light::get_transfers(const monero_transfer_query& query) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the transfers while the sync thread reassigns the txs // get transfers directly if query does not require tx context (e.g. other transfers, outputs) if (!monero_transfer_query::is_contextual(query)) return get_transfers_aux(query); @@ -2606,6 +2729,7 @@ namespace monero { std::vector> monero_wallet_light::get_outputs(const monero_output_query& query) const { assert_not_closed(); + sync_op_lock op_lock(*this); // do not read the outputs while the sync thread reassigns them // get outputs directly if query does not require tx context (e.g. other outputs, transfers) if (!monero_output_query::is_contextual(query)) return get_outputs_aux(query); @@ -2664,7 +2788,13 @@ namespace monero { auto cached_key_image = m_key_image_cache->get(output->m_tx_pub_key.get(), output->m_index.get(), account_idx, subaddress_idx); if (cached_key_image != nullptr) key_image = cached_key_image; - else if (!is_view_only()) key_image = generate_key_image(output->m_tx_pub_key.get(), output->m_index.get(), account_idx, subaddress_idx); + else if (!is_view_only()) { + crypto::public_key expected_pub_key; + if (!epee::string_tools::hex_to_pod(output->m_public_key.get(), expected_pub_key)) throw std::runtime_error("Failed to parse output public key at index " + std::to_string(n)); + crypto::public_key tx_pub_key; + if (!epee::string_tools::hex_to_pod(output->m_tx_pub_key.get(), tx_pub_key)) throw std::runtime_error("Failed to parse output tx public key at index " + std::to_string(n)); + key_image = monero_utils::generate_key_image(tx_pub_key, output->m_index.get(), cryptonote::subaddress_index{account_idx, subaddress_idx}, m_account, boost::optional(expected_pub_key)); + } result->m_key_images.push_back(key_image); } @@ -2758,10 +2888,13 @@ namespace monero { struct block_notifier : monero_wallet_listener { boost::mutex* temp; boost::condition_variable* cv; - uint64_t last_height; + uint64_t last_height = 0; + bool notified = false; block_notifier(boost::mutex* temp, boost::condition_variable* cv) { this->temp = temp; this->cv = cv; } void on_new_block(uint64_t height) { + boost::mutex::scoped_lock lock(*temp); last_height = height; + notified = true; cv->notify_one(); } } block_listener(&temp, &cv); @@ -2769,15 +2902,20 @@ namespace monero { // register the listener add_listener(block_listener); - // wait until condition variable is notified - boost::mutex::scoped_lock lock(temp); - cv.wait(lock); + // wait until the listener reports a block, which a wallet that does not sync in the background + // never gets: the wait gives up after a minute instead of staying for one + uint64_t height; + { + boost::mutex::scoped_lock lock(temp); + cv.wait_for(lock, boost::chrono::minutes(1), [&block_listener]() { return block_listener.notified; }); + height = block_listener.last_height; + } // unregister the listener remove_listener(block_listener); // return last height - return block_listener.last_height; + return height; } bool monero_wallet_light::is_multisig_import_needed() const { @@ -2819,11 +2957,17 @@ namespace monero { wallet.m_sync_data_mutex.lock(); } - monero_wallet_light::sync_op_lock::~sync_op_lock() { + void monero_wallet_light::sync_op_lock::unlock() { + if (!m_locked) return; + m_locked = false; m_wallet.m_num_sync_pauses--; // resume background sync before unlocking so the sync does not yield to a finished operation m_wallet.m_sync_data_mutex.unlock(); } + monero_wallet_light::sync_op_lock::~sync_op_lock() { + unlock(); + } + void monero_wallet_light::init_common() { monero_wallet_keys::init_common(); m_cache = std::make_shared(m_key_image_cache); @@ -2840,8 +2984,10 @@ namespace monero { cryptonote::subaddress_index get_transaction_sender(const std::shared_ptr& tx) { cryptonote::subaddress_index si = {0,0}; for (const auto &output : tx->m_spent_outputs) { - si.major = output->m_sender->m_maj_i; - si.minor = output->m_sender->m_min_i; + if (output->m_sender != nullptr) { // sender is a monero-lws-specific field which spec-conformant servers omit + si.major = output->m_sender->m_maj_i; + si.minor = output->m_sender->m_min_i; + } break; } return si; @@ -2872,7 +3018,7 @@ namespace monero { for (const auto &tx : m_cache->get_txs()) { uint64_t total_sent = tx->m_total_sent.get(); uint64_t total_received = tx->m_total_received.get(); - uint64_t fee = tx->m_fee.get(); + uint64_t fee = tx->m_fee.value_or(0); // fee is a monero-lws-specific field which spec-conformant servers omit bool is_incoming = total_received > 0; bool is_outgoing = total_sent > 0; bool is_change = is_incoming && is_outgoing; @@ -3025,8 +3171,9 @@ namespace monero { } for (const auto& spent_output : tx->m_spent_outputs) { - uint32_t account_idx = spent_output->m_sender->m_maj_i; - uint32_t subaddress_idx = spent_output->m_sender->m_min_i; + // sender is a monero-lws-specific field which spec-conformant servers omit; default to the primary address + uint32_t account_idx = spent_output->m_sender == nullptr ? 0 : spent_output->m_sender->m_maj_i; + uint32_t subaddress_idx = spent_output->m_sender == nullptr ? 0 : spent_output->m_sender->m_min_i; uint64_t out_amount = spent_output->m_amount.get(); if (account_idx == sender.major && std::find_if(outgoing_transfer->m_subaddress_indices.begin(), outgoing_transfer->m_subaddress_indices.end(), [subaddress_idx](const uint32_t &idx) { return subaddress_idx == idx; }) == outgoing_transfer->m_subaddress_indices.end()) { @@ -3195,7 +3342,13 @@ namespace monero { if (!spent && !output->is_key_image_known()) { try { - output->m_key_image = generate_key_image(tx_pub_key, output_idx, account_idx, subaddress_idx)->m_hex; + // the expected one-time key is the one the server names for the output, which the derivation + // checks itself against before it signs + crypto::public_key expected_pub_key; + if (!epee::string_tools::hex_to_pod(output->m_public_key.get(), expected_pub_key)) throw std::runtime_error("Failed to parse output public key"); + crypto::public_key tx_pub_key_pod; + if (!epee::string_tools::hex_to_pod(tx_pub_key, tx_pub_key_pod)) throw std::runtime_error("Failed to parse output tx public key"); + output->m_key_image = monero_utils::generate_key_image(tx_pub_key_pod, output_idx, cryptonote::subaddress_index{account_idx, subaddress_idx}, m_account, boost::optional(expected_pub_key))->m_hex; // check key image is spent in unconfirmed transactions spent = m_cache->is_key_image_spent(output->m_key_image.get(), pool_key_images); checked_unconfirmed = true; @@ -3217,7 +3370,37 @@ namespace monero { bool monero_wallet_light::is_spend_real(const std::shared_ptr& spend) const { if (spend->m_key_image == boost::none) return false; std::string key_image = spend->m_key_image.get(); - return is_key_image_ours(key_image, spend->m_tx_pub_key.get(), spend->m_out_index.get(), spend->m_sender->m_maj_i, spend->m_sender->m_min_i); + if (spend->m_sender != nullptr) { + return is_key_image_ours(key_image, spend->m_tx_pub_key.get(), spend->m_out_index.get(), spend->m_sender->m_maj_i, spend->m_sender->m_min_i); + } + // sender is a monero-lws-specific field which spec-conformant servers omit: the spend does not say + // which subaddress it came from, so the key image is tested against every one the wallet knows, and + // not just the primary address, which would call the spends of the other subaddresses fake + for (const auto& kv : m_cache->m_subaddresses) { + if (is_key_image_ours(key_image, spend->m_tx_pub_key.get(), spend->m_out_index.get(), kv.second.major, kv.second.minor)) return true; + } + return false; + } + + bool monero_wallet_light::is_spend_verifiable(const std::shared_ptr& spend) const { + // a full wallet can always derive key images to verify candidate spends; a view-only wallet + // cannot (is_key_image_ours returns false on the uncached path) so a candidate spend is only + // verifiable when its key image was previously cached, e.g. by import_key_images + if (!is_view_only()) return true; + if (spend->m_sender != nullptr) { + return m_key_image_cache->get(spend->m_tx_pub_key.get(), spend->m_out_index.get(), spend->m_sender->m_maj_i, spend->m_sender->m_min_i) != nullptr; + } + // the spend does not say which subaddress it came from, so the cache of imported key images is + // looked in at every subaddress the wallet knows, or the spends of the other ones stay unrefined + for (const auto& kv : m_cache->m_subaddresses) { + if (m_key_image_cache->get(spend->m_tx_pub_key.get(), spend->m_out_index.get(), kv.second.major, kv.second.minor) != nullptr) return true; + } + return false; + } + + uint64_t monero_wallet_light::get_unrefined_spend_count() const { + assert_not_closed(); + return m_unrefined_spend_count; } void monero_wallet_light::run_sync_loop() { @@ -3297,6 +3480,7 @@ namespace monero { if (new_height == last_height) { m_cache->set_sync_status(*addr_info); + m_wallet_listener->on_sync_end(); // end the sync the listeners started, or their bounds stay for the next one return result; } @@ -3306,6 +3490,7 @@ namespace monero { monero_get_unspent_outs_response unspent_outs = *m_client->get_unspent_outs(0, 0); m_cache->m_subaddrs = m_client->get_subaddrs(); process_subaddresses(); + m_unrefined_spend_count = 0; process_txs(address_txs); unspent_outs.m_amount = process_outputs(unspent_outs.m_outputs, unspent_outs.m_amount.value_or(0)); const uint64_t new_outs_amount = unspent_outs.m_amount.get(); @@ -3320,7 +3505,9 @@ namespace monero { if (restore_height < current_height) { if (last_height < restore_height) last_height = restore_height; - uint64_t blocks_fetched = current_height - last_height; + // the server can name a start height above the height that the wallet scanned, which the subtraction + // below would wrap around on: the wallet fetched nothing then + uint64_t blocks_fetched = current_height > last_height ? current_height - last_height : 0; result.m_num_blocks_fetched = blocks_fetched; if (current_height > last_height) { @@ -3352,7 +3539,11 @@ namespace monero { size_t out_idx = 0; for (auto& spend : tx->m_spent_outputs) { - if (!is_spend_real(spend)) { + if (!is_spend_verifiable(spend)) { + // view-only wallet without a cached key image cannot disprove the candidate spend: + // keep the server's conservative amount so spent funds are not shown as available + m_unrefined_spend_count++; + } else if (!is_spend_real(spend)) { uint64_t spend_amount = spend->m_amount.get(); if (spend_amount > tx_total_sent) throw std::runtime_error("tx total sent is negative: " + tx->m_hash.get()); tx_total_sent -= spend_amount; @@ -3378,6 +3569,7 @@ namespace monero { const auto pool_key_images = m_cache->get_pool_key_images(); for (auto& output : outputs) { if (!is_output_spent(output, pool_key_images)) continue; + if (total_amount < output->m_amount.get()) throw std::runtime_error("output amount exceeds the total amount of the server"); total_amount -= output->m_amount.get(); } @@ -3402,11 +3594,16 @@ namespace monero { for (const auto& index_range : kv.second) { const uint32_t range_start = index_range->at(0); const uint32_t range_end = index_range->at(1); - for (uint32_t i = range_start; i <= range_end; i++) { - if (account_idx == 0 && i == 0) continue; - if (has_watermark && i <= watermark) continue; - const auto& subaddress_spend_pub_key = hwdev.get_subaddress_spend_public_key(account_keys, {account_idx, i}); - m_cache->m_subaddresses[subaddress_spend_pub_key] = {account_idx, i}; + // a server that answers a range of the whole space of an index would loop a derivation per index + // of it, and the last index of the space wraps when it counts up: no account holds more + // subaddresses than the server itself keeps, and the count runs where it cannot wrap + if (range_start > range_end || range_end - range_start > 16384) throw std::runtime_error("subaddress range is out of the range of an account: [" + std::to_string(range_start) + ", " + std::to_string(range_end) + "]"); + for (uint64_t i = range_start; i <= (uint64_t) range_end; i++) { + const uint32_t subaddress_idx = (uint32_t) i; + if (account_idx == 0 && subaddress_idx == 0) continue; + if (has_watermark && subaddress_idx <= watermark) continue; + const auto& subaddress_spend_pub_key = hwdev.get_subaddress_spend_public_key(account_keys, {account_idx, subaddress_idx}); + m_cache->m_subaddresses[subaddress_spend_pub_key] = {account_idx, subaddress_idx}; } if (range_end > highest) highest = range_end; } diff --git a/src/wallet/monero_wallet_light.h b/src/wallet/monero_wallet_light.h index 8fa13b9b..3f990e1c 100644 --- a/src/wallet/monero_wallet_light.h +++ b/src/wallet/monero_wallet_light.h @@ -160,6 +160,14 @@ namespace monero { void start_syncing(uint64_t sync_period_in_ms) override; void stop_syncing() override; void scan_txs(const std::vector& tx_ids) override; + /** + * Get the number of candidate spends the last sync could not verify, which is greater than + * zero only for view-only wallets without imported key images; when non-zero, total sent + * and balances are the server's unrefined conservative values. + * + * @return the number of unrefined spends from the last sync + */ + uint64_t get_unrefined_spend_count() const; uint64_t get_balance() const override; uint64_t get_balance(uint32_t account_idx) const override; uint64_t get_balance(uint32_t account_idx, uint32_t subaddress_idx) const override; @@ -207,6 +215,7 @@ namespace monero { friend struct wallet_light_listener; std::unique_ptr m_wallet_listener; // internal wallet implementation listener std::set m_listeners; // external wallet listeners + mutable boost::recursive_mutex m_listeners_mutex; // guards m_listeners, which the sync and pool threads notify while the app thread changes it static monero_wallet_light* create_wallet_from_seed(monero_wallet_config& config, const std::shared_ptr& rpc); static monero_wallet_light* create_wallet_from_keys(monero_wallet_config& config, const std::shared_ptr& rpc); @@ -221,7 +230,9 @@ namespace monero { sync_op_lock(const monero_wallet_light& wallet); sync_op_lock(const sync_op_lock&) = delete; ~sync_op_lock(); + void unlock(); // end the pause before the scope ends, for a listener that reads the wallet through its own lock const monero_wallet_light& m_wallet; + bool m_locked = true; }; // blockchain sync management @@ -237,7 +248,15 @@ namespace monero { boost::mutex m_syncing_mutex; // synchronize auto sync loop void run_sync_loop(); // run the sync loop in a thread monero_sync_result lock_and_sync(boost::optional start_height = boost::none); // internal function to synchronize request to sync and rescan + /** + * Light wallets sync from a light wallet server (monero-lws), never from a daemon, so + * setting a daemon connection is unsupported. + */ + void set_daemon_connection(const std::string& uri, const std::string& username = "", const std::string& password = "", const std::string& proxy_uri = "", const boost::optional& is_trusted = boost::none) override; + void set_daemon_connection(const std::shared_ptr& connection, const boost::optional& is_trusted = boost::none) override; + monero_sync_result sync_aux(boost::optional start_height = boost::none); // internal function to immediately block, sync, and report progress + std::atomic m_unrefined_spend_count{0}; // candidate spends the last sync could not verify (view-only without cached key images) // wallet data mutable boost::recursive_mutex m_sync_data_mutex; @@ -245,6 +264,7 @@ namespace monero { bool is_output_spent(const std::shared_ptr &output, const std::unordered_set& pool_key_images) const; bool is_spend_real(const std::shared_ptr& spend) const; + bool is_spend_verifiable(const std::shared_ptr& spend) const; // whether the wallet can verify a candidate spend is real (spend key present or key image cached) void process_txs(monero_get_address_txs_response& address_txs); uint64_t process_outputs(std::vector>& outputs, uint64_t total_amount); void process_subaddresses(); diff --git a/src/wallet/monero_wallet_light_model.cpp b/src/wallet/monero_wallet_light_model.cpp index 22f264cc..eeaf3b3f 100644 --- a/src/wallet/monero_wallet_light_model.cpp +++ b/src/wallet/monero_wallet_light_model.cpp @@ -113,6 +113,8 @@ namespace monero { } void monero_output_light::from_property_tree(const boost::property_tree::ptree& node, const std::shared_ptr& output) { + // recipient is a monero-lws-specific field which spec-conformant servers omit; default to the primary address + output->m_recipient = std::make_shared(); for (boost::property_tree::ptree::const_iterator it = node.begin(); it != node.end(); ++it) { std::string key = it->first; if (key == std::string("tx_id")) output->m_tx_id = it->second.get_value(); @@ -213,7 +215,10 @@ namespace monero { if (size() != 2) return indices; uint32_t min_i = at(0); uint32_t maj_i = at(1); - for(uint32_t i = min_i; i <= maj_i; i++) indices.push_back(i); + // a range of the whole space of an index would fill the memory with indices, and the last index of + // the space wraps when it counts up: the count runs where it cannot wrap + if (min_i > maj_i || maj_i - min_i > 16384) throw std::runtime_error("subaddress range is out of the range of an account: [" + std::to_string(min_i) + ", " + std::to_string(maj_i) + "]"); + for(uint64_t i = min_i; i <= (uint64_t) maj_i; i++) indices.push_back((uint32_t) i); return indices; } @@ -596,6 +601,7 @@ namespace monero { for (boost::property_tree::ptree::const_iterator it = node.begin(); it != node.end(); ++it) { std::string key = it->first; if (key == std::string("status")) response->m_status = it->second.data(); + else if (key == std::string("not_relayed")) response->m_not_relayed = it->second.get_value(); } } @@ -706,7 +712,7 @@ namespace monero { } for (const auto& output : kv.second) { - if (output->m_frozen.value_or(false) || get_num_blocks_to_unlock(output->m_tx_hash.get()) > 0) continue; + if (output->m_frozen.value_or(false) || (output->m_key_image != boost::none && m_frozen_key_images.count(output->m_key_image.get()) > 0) || get_num_blocks_to_unlock(output->m_tx_hash.get()) > 0) continue; if (output->is_key_image_known() && pool_key_images.count(output->m_key_image.get())) continue; spendable.push_back(output); } @@ -735,9 +741,13 @@ namespace monero { void monero_wallet_light_cache::set_outputs(monero_get_unspent_outs_response& response) { boost::lock_guard lock(m_mutex); + // a server that omits the mask or answers zero would make the fee computation divide by it: the + // value is clamped to a sane bound and read as one at the least, which the fees of a real chain + // never notice but a hostile or broken answer cannot turn into a crash + static const uint64_t MAX_SANE_FEE_MASK = 1000000; // 100x today's real value m_per_byte_fee = response.m_per_byte_fee.value_or(0); m_fees = std::move(response.m_fees); - m_fee_mask = response.m_fee_mask.value_or(0); + m_fee_mask = std::min(response.m_fee_mask.value_or(0), MAX_SANE_FEE_MASK); m_amount = response.m_amount.value_or(0); m_outputs = std::move(response.m_outputs); std::sort(m_outputs.begin(), m_outputs.end(), [](const std::shared_ptr& a, const std::shared_ptr& b) { @@ -875,9 +885,11 @@ namespace monero { uint64_t change_amount = 0; if (tx->m_change_amount != boost::none) change_amount = tx->m_change_amount.get(); + // the change of a pending tx goes to the account that sent it, and not always to the primary one + uint32_t change_account_idx = tx->m_outgoing_transfer != nullptr && tx->m_outgoing_transfer->m_account_index != boost::none ? tx->m_outgoing_transfer->m_account_index.get() : 0; m_balance += change_amount; - m_account_balance[0] += change_amount; - m_subaddress_balance[0][0] += change_amount; + m_account_balance[change_account_idx] += change_amount; + m_subaddress_balance[change_account_idx][0] += change_amount; for (const std::shared_ptr &out : tx->m_outputs) { std::shared_ptr output = std::dynamic_pointer_cast(out); @@ -932,13 +944,16 @@ namespace monero { auto it = m_key_image_index.find(key_image); if (it == m_key_image_index.end()) throw std::runtime_error("Key image not found"); m_outputs[it->second]->m_frozen = frozen; + // the sync replaces the outputs, so the setting lives in the set of key images and not only on the object + if (frozen) m_frozen_key_images.insert(key_image); + else m_frozen_key_images.erase(key_image); } bool monero_wallet_light_cache::is_key_image_frozen(const std::string& key_image) const { validate_key_image(key_image); auto it = m_key_image_index.find(key_image); if (it == m_key_image_index.end()) throw std::runtime_error("Key image not found"); - return m_outputs[it->second]->m_frozen.value_or(false); + return m_outputs[it->second]->m_frozen.value_or(false) || m_frozen_key_images.count(key_image) > 0; } std::shared_ptr monero_wallet_light_cache::get_output(const std::string& key_image) const { @@ -979,8 +994,17 @@ namespace monero { const auto &out = unspent_outs[n]; uint64_t out_amount = out->m_amount.get(); auto internal_output_index = out->m_index.get(); + // the index comes from the server: a garbage one would resize the prefix by billions of outputs + if (internal_output_index > 100000) throw std::runtime_error("output index is out of the range of a transaction: " + std::to_string(internal_output_index)); std::string tx_hash = out->m_tx_hash.get(); - uint64_t unlock_time = get_tx(tx_hash)->m_unlock_time.get(); + // the tx can be missing in the window of the two requests of a sync, like the unlock path: the + // prefix of the export carries no lock then, which the next export after the next sync corrects + uint64_t unlock_time; + { + boost::lock_guard lock(m_mutex); + auto tx_it = m_txs.find(tx_hash); + unlock_time = tx_it == m_txs.end() ? 0 : tx_it->second->m_unlock_time.get(); + } crypto::public_key public_key; crypto::public_key tx_pub_key; @@ -1128,7 +1152,13 @@ namespace monero { } uint64_t monero_wallet_light_cache::get_num_blocks_to_unlock(const std::string& tx_hash) const { - const auto& tx = get_tx(tx_hash); + // the address txs and the unspent outs arrive in two requests, so an output can name a tx that the + // txs response does not have: the output is treated as unlocked, which the next sync corrects, and + // not as an error that leaves the balance of a partial sync + boost::lock_guard lock(m_mutex); + auto it = m_txs.find(tx_hash); + if (it == m_txs.end()) return 0; + const auto& tx = it->second; uint64_t current_height = get_scanned_block_height() + 1; uint64_t tx_height = tx->m_mempool.get() ? current_height : tx->m_height.get(); uint64_t unlock_time = tx->m_unlock_time.get(); @@ -1273,7 +1303,7 @@ namespace monero { if (out->is_key_image_known()) { output->m_key_image = std::make_shared(); output->m_key_image.get()->m_hex = out->m_key_image; - output->m_is_frozen = out->m_frozen.value_or(false); + output->m_is_frozen = out->m_frozen.value_or(false) || (out->m_key_image != boost::none && m_frozen_key_images.count(out->m_key_image.get()) > 0); if (!*output->m_is_spent) output->m_is_spent = is_key_image_spent(out->m_key_image.get(), pool_key_images); } diff --git a/src/wallet/monero_wallet_light_model.h b/src/wallet/monero_wallet_light_model.h index cc701ef7..84f2c2b3 100644 --- a/src/wallet/monero_wallet_light_model.h +++ b/src/wallet/monero_wallet_light_model.h @@ -317,6 +317,7 @@ namespace monero { struct monero_submit_raw_tx_response { boost::optional m_status; + boost::optional m_not_relayed; static void from_property_tree(const boost::property_tree::ptree& node, const std::shared_ptr& response); }; @@ -399,7 +400,8 @@ namespace monero { void reindex_outputs(uint64_t amount); uint64_t get_per_byte_fee() const { return m_per_byte_fee; } uint64_t get_base_fee(uint32_t priority) const; - uint64_t get_fee_mask() const { return m_fee_mask; } + // a zero mask would divide by nothing in the fee computation, so it reads as one at the least + uint64_t get_fee_mask() const { return m_fee_mask == 0 ? 1 : m_fee_mask; } uint64_t get_amount() const { return m_amount; } // subaddresses @@ -408,17 +410,26 @@ namespace monero { uint64_t get_num_blocks_to_unlock(uint32_t account_idx, uint32_t subaddress_idx) const; void init_subaddress(monero_subaddress& subaddress) const; + /** + * Get the tx of a hash that the account received or sent, which throws when the store does not have it. + * + * @param hash is the hash of the tx + * @return the tx of the hash + */ + std::shared_ptr get_tx(const std::string& hash) const; + private: mutable boost::recursive_mutex m_mutex; std::shared_ptr m_key_image_cache; + // the frozen key images, which a sync replaces the outputs they mark, so the setting outlives them + std::set m_frozen_key_images; + // transactions serializable_unordered_map> m_txs; std::vector> m_tx_list; serializable_unordered_map> m_self_constructed_txs; serializable_unordered_map m_spent_key_images; - - std::shared_ptr get_tx(const std::string& hash) const; void set_txs(monero_get_address_txs_response& response, const monero_get_address_info_response& addr_info_response); // blockchain diff --git a/src/wallet/monero_wallet_rpc.cpp b/src/wallet/monero_wallet_rpc.cpp index c83f3053..2881e57d 100644 --- a/src/wallet/monero_wallet_rpc.cpp +++ b/src/wallet/monero_wallet_rpc.cpp @@ -1321,6 +1321,10 @@ namespace monero { auto result = m_rpc->send_json_request("check_tx_key", params); check->m_is_good = true; deserialize_check_tx(result, check); + // the wallet behind the rpc answers the fields of the check and not whether the key checked out: + // the address received nothing when the key is not the one of the tx, which the other wallets + // derive the same way + check->m_is_good = check->m_received_amount != boost::none && check->m_received_amount.get() > 0; } catch (const monero_rpc_error& ex) { normalize_wallet_error(ex); }