| 1 | // Copyright (c) 2014-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | // |
| 29 | // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers |
| 30 | |
| 31 | #include <algorithm> |
| 32 | #include <numeric> |
| 33 | #include <tuple> |
| 34 | #include <queue> |
| 35 | #include <boost/format.hpp> |
| 36 | #include <boost/optional/optional.hpp> |
| 37 | #include <boost/algorithm/string/classification.hpp> |
| 38 | #include <boost/algorithm/string/trim.hpp> |
| 39 | #include <boost/algorithm/string/split.hpp> |
| 40 | #include <boost/algorithm/string/join.hpp> |
| 41 | #include <boost/algorithm/string/predicate.hpp> |
| 42 | #include <boost/asio/ip/address.hpp> |
| 43 | #include <boost/range/adaptor/transformed.hpp> |
| 44 | #include <boost/preprocessor/stringize.hpp> |
| 45 | #include <openssl/evp.h> |
| 46 | #include "include_base_utils.h" |
| 47 | using namespace epee; |
| 48 | |
| 49 | #include "cryptonote_config.h" |
| 50 | #include "hardforks/hardforks.h" |
| 51 | #include "cryptonote_core/tx_sanity_check.h" |
| 52 | #include "wallet_rpc_helpers.h" |
| 53 | #include "wallet2.h" |
| 54 | #include "wallet_args.h" |
| 55 | #include "cryptonote_basic/cryptonote_format_utils.h" |
| 56 | #include "net/parse.h" |
| 57 | #include "rpc/core_rpc_server_commands_defs.h" |
| 58 | #include "rpc/core_rpc_server_error_codes.h" |
| 59 | #include "rpc/rpc_payment_signature.h" |
| 60 | #include "rpc/rpc_payment_costs.h" |
| 61 | #include "misc_language.h" |
| 62 | #include "cryptonote_basic/cryptonote_basic_impl.h" |
| 63 | #include "multisig/multisig.h" |
| 64 | #include "multisig/multisig_account.h" |
| 65 | #include "multisig/multisig_kex_msg.h" |
| 66 | #include "multisig/multisig_tx_builder_ringct.h" |
| 67 | #include "common/boost_serialization_helper.h" |
| 68 | #include "common/command_line.h" |
| 69 | #include "common/threadpool.h" |
| 70 | #include "int-util.h" |
| 71 | #include "profile_tools.h" |
| 72 | #include "crypto/crypto.h" |
| 73 | #include "serialization/binary_utils.h" |
| 74 | #include "serialization/string.h" |
| 75 | #include "cryptonote_basic/blobdatatype.h" |
| 76 | #include "mnemonics/electrum-words.h" |
| 77 | #include "common/i18n.h" |
| 78 | #include "common/util.h" |
| 79 | #include "common/apply_permutation.h" |
| 80 | #include "rapidjson/document.h" |
| 81 | #include "rapidjson/writer.h" |
| 82 | #include "rapidjson/stringbuffer.h" |
| 83 | #include "common/json_util.h" |
| 84 | #include "memwipe.h" |
| 85 | #include "common/base58.h" |
| 86 | #include "common/combinator.h" |
| 87 | #include "common/dns_utils.h" |
| 88 | #include "common/notify.h" |
| 89 | #include "common/perf_timer.h" |
| 90 | #include "ringct/rctSigs.h" |
| 91 | #include "ringdb.h" |
| 92 | #include "device/device_cold.hpp" |
| 93 | #include "device_trezor/device_trezor.hpp" |
| 94 | #include "net/socks_connect.h" |
| 95 | |
| 96 | extern "C" |
| 97 | { |
| 98 | #include "crypto/keccak.h" |
| 99 | #include "crypto/crypto-ops.h" |
| 100 | } |
| 101 | using namespace std; |
| 102 | using namespace crypto; |
| 103 | using namespace cryptonote; |
| 104 | |
| 105 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 106 | #define MONERO_DEFAULT_LOG_CATEGORY "wallet.wallet2" |
| 107 | |
| 108 | // used to choose when to stop adding outputs to a tx |
| 109 | #define APPROXIMATE_INPUT_BYTES 80 |
| 110 | |
| 111 | // used to target a given block weight (additional outputs may be added on top to build fee) |
| 112 | #define TX_WEIGHT_TARGET(bytes) (bytes*2/3) |
| 113 | |
| 114 | #define UNSIGNED_TX_PREFIX "Monero unsigned tx set\005" |
| 115 | #define SIGNED_TX_PREFIX "Monero signed tx set\005" |
| 116 | #define MULTISIG_UNSIGNED_TX_PREFIX "Monero multisig unsigned tx set\001" |
| 117 | |
| 118 | #define RECENT_OUTPUT_RATIO (0.5) // 50% of outputs are from the recent zone |
| 119 | #define RECENT_OUTPUT_DAYS (1.8) // last 1.8 day makes up the recent zone (taken from monerolink.pdf, Miller et al) |
| 120 | #define RECENT_OUTPUT_ZONE ((time_t)(RECENT_OUTPUT_DAYS * 86400)) |
| 121 | #define RECENT_OUTPUT_BLOCKS (RECENT_OUTPUT_DAYS * 720) |
| 122 | |
| 123 | #define FEE_ESTIMATE_GRACE_BLOCKS 10 // estimate fee valid for that many blocks |
| 124 | |
| 125 | #define SECOND_OUTPUT_RELATEDNESS_THRESHOLD 0.0f |
| 126 | |
| 127 | #define SUBADDRESS_LOOKAHEAD_MAJOR 50 |
| 128 | #define SUBADDRESS_LOOKAHEAD_MINOR 200 |
| 129 | |
| 130 | #define KEY_IMAGE_EXPORT_FILE_MAGIC "Monero key image export\003" |
| 131 | |
| 132 | #define MULTISIG_EXPORT_FILE_MAGIC "Monero multisig export\001" |
| 133 | |
| 134 | #define OUTPUT_EXPORT_FILE_MAGIC "Monero output export\004" |
| 135 | |
| 136 | #define SEGREGATION_FORK_HEIGHT 99999999 |
| 137 | #define TESTNET_SEGREGATION_FORK_HEIGHT 99999999 |
| 138 | #define STAGENET_SEGREGATION_FORK_HEIGHT 99999999 |
| 139 | #define SEGREGATION_FORK_VICINITY 1500 /* blocks */ |
| 140 | |
| 141 | #define FIRST_REFRESH_GRANULARITY 1024 |
| 142 | |
| 143 | #define GAMMA_SHAPE 19.28 |
| 144 | #define GAMMA_SCALE (1/1.61) |
| 145 | |
| 146 | #define DEFAULT_MIN_OUTPUT_COUNT 5 |
| 147 | #define DEFAULT_MIN_OUTPUT_VALUE (2*COIN) |
| 148 | |
| 149 | #define DEFAULT_INACTIVITY_LOCK_TIMEOUT 90 // a minute and a half |
| 150 | |
| 151 | #define IGNORE_LONG_PAYMENT_ID_FROM_BLOCK_VERSION 12 |
| 152 | |
| 153 | #define DEFAULT_UNLOCK_TIME (CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE * DIFFICULTY_TARGET_V2) |
| 154 | #define RECENT_SPEND_WINDOW (15 * DIFFICULTY_TARGET_V2) |
| 155 | |
| 156 | static const std::string MULTISIG_SIGNATURE_MAGIC = "SigMultisigPkV1"; |
| 157 | |
| 158 | static const std::string ASCII_OUTPUT_MAGIC = "MoneroAsciiDataV1"; |
| 159 | |
| 160 | static const std::string BACKGROUND_WALLET_SUFFIX = ".background"; |
| 161 | |
| 162 | boost::mutex tools::wallet2::default_daemon_address_lock; |
| 163 | std::string tools::wallet2::default_daemon_address = ""; |
| 164 | |
| 165 | namespace |
| 166 | { |
| 167 | std::string get_default_ringdb_path() |
| 168 | { |
| 169 | boost::filesystem::path dir = tools::get_default_data_dir(); |
| 170 | // remove .bitmonero, replace with .shared-ringdb |
| 171 | dir = dir.remove_filename(); |
| 172 | dir /= ".shared-ringdb"; |
| 173 | return dir.string(); |
| 174 | } |
| 175 | |
| 176 | bool keys_intersect(const std::unordered_set<crypto::public_key>& s1, const std::unordered_set<crypto::public_key>& s2) |
| 177 | { |
| 178 | if (s1.empty() || s2.empty()) |
| 179 | return false; |
| 180 | |
| 181 | for (const auto& e: s1) |
| 182 | { |
| 183 | if (s2.find(e) != s2.end()) |
| 184 | return true; |
| 185 | } |
| 186 | |
| 187 | return false; |
| 188 | } |
| 189 | |
| 190 | void add_reason(std::string &reasons, const char *reason) |
| 191 | { |
| 192 | if (!reasons.empty()) |
| 193 | reasons += ", "; |
| 194 | reasons += reason; |
| 195 | } |
| 196 | |
| 197 | std::string get_text_reason(const cryptonote::COMMAND_RPC_SEND_RAW_TX::response &res) |
| 198 | { |
| 199 | std::string reason; |
| 200 | if (res.low_mixin) |
| 201 | add_reason(reason, "bad ring size"); |
| 202 | if (res.double_spend) |
| 203 | add_reason(reason, "double spend"); |
| 204 | if (res.invalid_input) |
| 205 | add_reason(reason, "invalid input"); |
| 206 | if (res.invalid_output) |
| 207 | add_reason(reason, "invalid output"); |
| 208 | if (res.too_few_outputs) |
| 209 | add_reason(reason, "too few outputs"); |
| 210 | if (res.too_big) |
| 211 | add_reason(reason, "too big"); |
| 212 | if (res.overspend) |
| 213 | add_reason(reason, "overspend"); |
| 214 | if (res.fee_too_low) |
| 215 | add_reason(reason, "fee too low"); |
| 216 | if (res.sanity_check_failed) |
| 217 | add_reason(reason, "tx sanity check failed"); |
| 218 | if (res.not_relayed) |
| 219 | add_reason(reason, "tx was not relayed"); |
| 220 | return reason; |
| 221 | } |
| 222 | |
| 223 | size_t get_num_outputs(const std::vector<cryptonote::tx_destination_entry> &dsts, const std::vector<tools::wallet2::transfer_details> &transfers, const std::vector<size_t> &selected_transfers) |
| 224 | { |
| 225 | size_t outputs = dsts.size(); |
| 226 | uint64_t needed_money = 0; |
| 227 | for (const auto& dt: dsts) |
| 228 | needed_money += dt.amount; |
| 229 | uint64_t found_money = 0; |
| 230 | for(size_t idx: selected_transfers) |
| 231 | found_money += transfers[idx].amount(); |
| 232 | if (found_money != needed_money) |
| 233 | ++outputs; // change |
| 234 | if (outputs < 2) |
| 235 | ++outputs; // extra 0 dummy output |
| 236 | return outputs; |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | namespace |
| 241 | { |
| 242 | // Create on-demand to prevent static initialization order fiasco issues. |
| 243 | struct options { |
| 244 | const command_line::arg_descriptor<std::string> daemon_address = {"daemon-address", tools::wallet2::tr("Use daemon instance at <host>:<port>"), ""}; |
| 245 | const command_line::arg_descriptor<std::string> daemon_host = {"daemon-host", tools::wallet2::tr("Use daemon instance at host <arg> instead of localhost"), ""}; |
| 246 | const command_line::arg_descriptor<std::string> proxy = {"proxy", tools::wallet2::tr("[<ip>:]<port> socks proxy to use for daemon connections"), {}, true}; |
| 247 | const command_line::arg_descriptor<bool> trusted_daemon = {"trusted-daemon", tools::wallet2::tr("Enable commands which rely on a trusted daemon"), false}; |
| 248 | const command_line::arg_descriptor<bool> untrusted_daemon = {"untrusted-daemon", tools::wallet2::tr("Disable commands which rely on a trusted daemon"), false}; |
| 249 | const command_line::arg_descriptor<std::string> password = {"password", tools::wallet2::tr("Wallet password (escape/quote as needed)"), "", true}; |
| 250 | const command_line::arg_descriptor<std::string> password_file = wallet_args::arg_password_file(); |
| 251 | const command_line::arg_descriptor<int> daemon_port = {"daemon-port", tools::wallet2::tr("Use daemon instance at port <arg> instead of 18081"), 0}; |
| 252 | const command_line::arg_descriptor<std::string> daemon_login = {"daemon-login", tools::wallet2::tr("Specify username[:password] for daemon RPC client"), "", true}; |
| 253 | const command_line::arg_descriptor<std::string> daemon_ssl = {"daemon-ssl", tools::wallet2::tr("Enable SSL on daemon RPC connections: enabled|disabled|autodetect"), "autodetect"}; |
| 254 | const command_line::arg_descriptor<std::string> daemon_ssl_private_key = {"daemon-ssl-private-key", tools::wallet2::tr("Path to a PEM format private key"), ""}; |
| 255 | const command_line::arg_descriptor<std::string> daemon_ssl_certificate = {"daemon-ssl-certificate", tools::wallet2::tr("Path to a PEM format certificate"), ""}; |
| 256 | const command_line::arg_descriptor<std::string> daemon_ssl_ca_certificates = {"daemon-ssl-ca-certificates", tools::wallet2::tr("Path to file containing concatenated PEM format certificate(s) to replace system CA(s).")}; |
| 257 | const command_line::arg_descriptor<std::vector<std::string>> daemon_ssl_allowed_fingerprints = {"daemon-ssl-allowed-fingerprints", tools::wallet2::tr("List of valid fingerprints of allowed RPC servers")}; |
| 258 | const command_line::arg_descriptor<bool> daemon_ssl_allow_any_cert = {"daemon-ssl-allow-any-cert", tools::wallet2::tr("Allow any SSL certificate from the daemon"), false}; |
| 259 | const command_line::arg_descriptor<bool> daemon_ssl_allow_chained = {"daemon-ssl-allow-chained", tools::wallet2::tr("Allow user (via --daemon-ssl-ca-certificates) chain certificates"), false}; |
| 260 | const command_line::arg_descriptor<bool> testnet = {"testnet", tools::wallet2::tr("For testnet. Daemon must also be launched with --testnet flag"), false}; |
| 261 | const command_line::arg_descriptor<bool> stagenet = {"stagenet", tools::wallet2::tr("For stagenet. Daemon must also be launched with --stagenet flag"), false}; |
| 262 | const command_line::arg_descriptor<std::string, false, true, 2> shared_ringdb_dir = { |
| 263 | "shared-ringdb-dir", tools::wallet2::tr("Set shared ring database path"), |
| 264 | get_default_ringdb_path(), |
| 265 | {{ &testnet, &stagenet }}, |
| 266 | [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string { |
| 267 | if (testnet_stagenet[0]) |
| 268 | return (boost::filesystem::path(val) / "testnet").string(); |
| 269 | else if (testnet_stagenet[1]) |
| 270 | return (boost::filesystem::path(val) / "stagenet").string(); |
| 271 | return val; |
| 272 | } |
| 273 | }; |
| 274 | const command_line::arg_descriptor<uint64_t> kdf_rounds = {"kdf-rounds", tools::wallet2::tr("Number of rounds for the key derivation function"), 1}; |
| 275 | const command_line::arg_descriptor<std::string> hw_device = {"hw-device", tools::wallet2::tr("HW device to use"), ""}; |
| 276 | const command_line::arg_descriptor<std::string> hw_device_derivation_path = {"hw-device-deriv-path", tools::wallet2::tr("HW device wallet derivation path (e.g., SLIP-10)"), ""}; |
| 277 | const command_line::arg_descriptor<std::string> tx_notify = { "tx-notify" , "Run a program for each new incoming transaction, '%s' will be replaced by the transaction hash" , "" }; |
| 278 | const command_line::arg_descriptor<bool> no_dns = {"no-dns", tools::wallet2::tr("Do not use DNS"), false}; |
| 279 | const command_line::arg_descriptor<bool> offline = {"offline", tools::wallet2::tr("Do not connect to a daemon, nor use DNS"), false}; |
| 280 | const command_line::arg_descriptor<std::string> extra_entropy = {"extra-entropy", tools::wallet2::tr("File containing extra entropy to initialize the PRNG (any data, aim for 256 bits of entropy to be useful, which typically means more than 256 bits of data)")}; |
| 281 | const command_line::arg_descriptor<bool> allow_mismatched_daemon_version = {"allow-mismatched-daemon-version", tools::wallet2::tr("Allow communicating with a daemon that uses a different version"), false}; |
| 282 | }; |
| 283 | |
| 284 | void do_prepare_file_names(const std::string& file_path, std::string& keys_file, std::string& wallet_file, std::string &mms_file) |
| 285 | { |
| 286 | keys_file = file_path; |
| 287 | wallet_file = file_path; |
| 288 | if(string_tools::get_extension(keys_file) == "keys") |
| 289 | {//provided keys file name |
| 290 | wallet_file = string_tools::cut_off_extension(wallet_file); |
| 291 | }else |
| 292 | {//provided wallet file name |
| 293 | keys_file += ".keys"; |
| 294 | } |
| 295 | mms_file = file_path + ".mms"; |
| 296 | } |
| 297 | |
| 298 | uint64_t calculate_fee(uint64_t fee_per_kb, size_t bytes) |
| 299 | { |
| 300 | uint64_t kB = (bytes + 1023) / 1024; |
| 301 | return kB * fee_per_kb; |
| 302 | } |
| 303 | |
| 304 | uint64_t calculate_fee_from_weight(uint64_t base_fee, uint64_t weight, uint64_t fee_quantization_mask) |
| 305 | { |
| 306 | uint64_t fee = weight * base_fee; |
| 307 | fee = (fee + fee_quantization_mask - 1) / fee_quantization_mask * fee_quantization_mask; |
| 308 | return fee; |
| 309 | } |
| 310 | |
| 311 | std::string get_weight_string(size_t weight) |
| 312 | { |
| 313 | return std::to_string(weight) + " weight"; |
| 314 | } |
| 315 | |
| 316 | std::string get_weight_string(const cryptonote::transaction &tx, size_t blob_size) |
| 317 | { |
| 318 | return get_weight_string(get_transaction_weight(tx, blob_size)); |
| 319 | } |
| 320 | |
| 321 | std::unique_ptr<tools::wallet2> make_basic(const boost::program_options::variables_map& vm, bool unattended, const options& opts, const std::function<boost::optional<tools::password_container>(const char *, bool)> &password_prompter) |
| 322 | { |
| 323 | const bool testnet = command_line::get_arg(vm, opts.testnet); |
| 324 | const bool stagenet = command_line::get_arg(vm, opts.stagenet); |
| 325 | const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET; |
| 326 | const uint64_t kdf_rounds = command_line::get_arg(vm, opts.kdf_rounds); |
| 327 | THROW_WALLET_EXCEPTION_IF(kdf_rounds == 0, tools::error::wallet_internal_error, "KDF rounds must not be 0"); |
| 328 | |
| 329 | const bool use_proxy = command_line::has_arg(vm, opts.proxy); |
| 330 | auto daemon_address = command_line::get_arg(vm, opts.daemon_address); |
| 331 | auto daemon_host = command_line::get_arg(vm, opts.daemon_host); |
| 332 | auto daemon_port = command_line::get_arg(vm, opts.daemon_port); |
| 333 | auto device_name = command_line::get_arg(vm, opts.hw_device); |
| 334 | auto device_derivation_path = command_line::get_arg(vm, opts.hw_device_derivation_path); |
| 335 | auto daemon_ssl_private_key = command_line::get_arg(vm, opts.daemon_ssl_private_key); |
| 336 | auto daemon_ssl_certificate = command_line::get_arg(vm, opts.daemon_ssl_certificate); |
| 337 | auto daemon_ssl_ca_file = command_line::get_arg(vm, opts.daemon_ssl_ca_certificates); |
| 338 | auto daemon_ssl_allowed_fingerprints = command_line::get_arg(vm, opts.daemon_ssl_allowed_fingerprints); |
| 339 | auto daemon_ssl_allow_any_cert = command_line::get_arg(vm, opts.daemon_ssl_allow_any_cert); |
| 340 | auto daemon_ssl = command_line::get_arg(vm, opts.daemon_ssl); |
| 341 | |
| 342 | // user specified CA file or fingeprints implies enabled SSL by default |
| 343 | epee::net_utils::ssl_options_t ssl_options = epee::net_utils::ssl_support_t::e_ssl_support_enabled; |
| 344 | if (daemon_ssl_allow_any_cert) |
| 345 | ssl_options.verification = epee::net_utils::ssl_verification_t::none; |
| 346 | else if (!daemon_ssl_ca_file.empty() || !daemon_ssl_allowed_fingerprints.empty()) |
| 347 | { |
| 348 | std::vector<std::vector<uint8_t>> ssl_allowed_fingerprints{ daemon_ssl_allowed_fingerprints.size() }; |
| 349 | std::transform(daemon_ssl_allowed_fingerprints.begin(), daemon_ssl_allowed_fingerprints.end(), ssl_allowed_fingerprints.begin(), epee::from_hex_locale::to_vector); |
| 350 | for (const auto &fpr: ssl_allowed_fingerprints) |
| 351 | { |
| 352 | THROW_WALLET_EXCEPTION_IF(fpr.size() != SSL_FINGERPRINT_SIZE, tools::error::wallet_internal_error, |
| 353 | "SHA-256 fingerprint should be " BOOST_PP_STRINGIZE(SSL_FINGERPRINT_SIZE) " bytes long."); |
| 354 | } |
| 355 | |
| 356 | ssl_options = epee::net_utils::ssl_options_t{ |
| 357 | std::move(ssl_allowed_fingerprints), std::move(daemon_ssl_ca_file) |
| 358 | }; |
| 359 | |
| 360 | if (command_line::get_arg(vm, opts.daemon_ssl_allow_chained)) |
| 361 | ssl_options.verification = epee::net_utils::ssl_verification_t::user_ca; |
| 362 | } |
| 363 | |
| 364 | if (ssl_options.verification != epee::net_utils::ssl_verification_t::user_certificates || !command_line::is_arg_defaulted(vm, opts.daemon_ssl)) |
| 365 | { |
| 366 | THROW_WALLET_EXCEPTION_IF(!epee::net_utils::ssl_support_from_string(ssl_options.support, daemon_ssl), tools::error::wallet_internal_error, |
| 367 | tools::wallet2::tr("Invalid argument for ") + std::string(opts.daemon_ssl.name)); |
| 368 | } |
| 369 | |
| 370 | ssl_options.auth = epee::net_utils::ssl_authentication_t{ |
| 371 | std::move(daemon_ssl_private_key), std::move(daemon_ssl_certificate) |
| 372 | }; |
| 373 | |
| 374 | THROW_WALLET_EXCEPTION_IF(!daemon_address.empty() && !daemon_host.empty() && 0 != daemon_port, |
| 375 | tools::error::wallet_internal_error, tools::wallet2::tr("can't specify daemon host or port more than once")); |
| 376 | |
| 377 | boost::optional<epee::net_utils::http::login> login{}; |
| 378 | if (command_line::has_arg(vm, opts.daemon_login)) |
| 379 | { |
| 380 | auto parsed = tools::login::parse( |
| 381 | command_line::get_arg(vm, opts.daemon_login), false, [password_prompter](bool verify) { |
| 382 | if (!password_prompter) |
| 383 | { |
| 384 | MERROR("Password needed without prompt function"); |
| 385 | return boost::optional<tools::password_container>(); |
| 386 | } |
| 387 | return password_prompter("Daemon client password", verify); |
| 388 | } |
| 389 | ); |
| 390 | if (!parsed) |
| 391 | return nullptr; |
| 392 | |
| 393 | login.emplace(std::move(parsed->username), std::move(parsed->password).password()); |
| 394 | } |
| 395 | |
| 396 | if (daemon_host.empty()) |
| 397 | daemon_host = "localhost"; |
| 398 | |
| 399 | if (!daemon_port) |
| 400 | { |
| 401 | daemon_port = get_config(nettype).RPC_DEFAULT_PORT; |
| 402 | } |
| 403 | |
| 404 | // if no daemon settings are given and we have a previous one, reuse that one |
| 405 | if (command_line::is_arg_defaulted(vm, opts.daemon_host) && command_line::is_arg_defaulted(vm, opts.daemon_port) && command_line::is_arg_defaulted(vm, opts.daemon_address)) |
| 406 | { |
| 407 | // not a bug: taking a const ref to a temporary in this way is actually ok in a recent C++ standard |
| 408 | const std::string &def = tools::wallet2::get_default_daemon_address(); |
| 409 | if (!def.empty()) |
| 410 | daemon_address = def; |
| 411 | } |
| 412 | |
| 413 | if (daemon_address.empty()) |
| 414 | daemon_address = std::string("http://") + daemon_host + ":" + std::to_string(daemon_port); |
| 415 | |
| 416 | { |
| 417 | const boost::string_ref real_daemon = boost::string_ref{daemon_address}.substr(0, daemon_address.rfind(':')); |
| 418 | |
| 419 | /* If SSL or proxy is enabled, then a specific cert, CA or fingerprint must |
| 420 | be specified. This is specific to the wallet. */ |
| 421 | const bool verification_required = |
| 422 | ssl_options.verification != epee::net_utils::ssl_verification_t::none && |
| 423 | (ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_enabled || use_proxy); |
| 424 | |
| 425 | THROW_WALLET_EXCEPTION_IF( |
| 426 | verification_required && !ssl_options.has_strong_verification(real_daemon), |
| 427 | tools::error::wallet_internal_error, |
| 428 | tools::wallet2::tr("Enabling --") + std::string{use_proxy ? opts.proxy.name : opts.daemon_ssl.name} + tools::wallet2::tr(" requires --") + |
| 429 | opts.daemon_ssl_allow_any_cert.name + tools::wallet2::tr(" or --") + |
| 430 | opts.daemon_ssl_ca_certificates.name + tools::wallet2::tr(" or --") + opts.daemon_ssl_allowed_fingerprints.name + tools::wallet2::tr(" or use of a .onion/.i2p domain") |
| 431 | ); |
| 432 | } |
| 433 | |
| 434 | std::string proxy; |
| 435 | if (use_proxy) |
| 436 | { |
| 437 | proxy = command_line::get_arg(vm, opts.proxy); |
| 438 | THROW_WALLET_EXCEPTION_IF( |
| 439 | !net::socks::endpoint::get(proxy), |
| 440 | tools::error::wallet_internal_error, |
| 441 | std::string{"Invalid address specified for --"} + opts.proxy.name); |
| 442 | } |
| 443 | |
| 444 | boost::optional<bool> trusted_daemon; |
| 445 | if (!command_line::is_arg_defaulted(vm, opts.trusted_daemon) || !command_line::is_arg_defaulted(vm, opts.untrusted_daemon)) |
| 446 | trusted_daemon = command_line::get_arg(vm, opts.trusted_daemon) && !command_line::get_arg(vm, opts.untrusted_daemon); |
| 447 | THROW_WALLET_EXCEPTION_IF(!command_line::is_arg_defaulted(vm, opts.trusted_daemon) && !command_line::is_arg_defaulted(vm, opts.untrusted_daemon), |
| 448 | tools::error::wallet_internal_error, tools::wallet2::tr("--trusted-daemon and --untrusted-daemon are both seen, assuming untrusted")); |
| 449 | |
| 450 | // set --trusted-daemon if local and not overridden |
| 451 | if (!trusted_daemon) |
| 452 | { |
| 453 | try |
| 454 | { |
| 455 | trusted_daemon = false; |
| 456 | if (tools::is_local_address(daemon_address)) |
| 457 | { |
| 458 | MINFO(tools::wallet2::tr("Daemon is local, assuming trusted")); |
| 459 | trusted_daemon = true; |
| 460 | } |
| 461 | } |
| 462 | catch (const std::exception &e) { } |
| 463 | } |
| 464 | |
| 465 | std::unique_ptr<tools::wallet2> wallet(new tools::wallet2(nettype, kdf_rounds, unattended)); |
| 466 | if (!wallet->init(std::move(daemon_address), std::move(login), std::move(proxy), 0, *trusted_daemon, std::move(ssl_options))) |
| 467 | { |
| 468 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to initialize the wallet")); |
| 469 | } |
| 470 | boost::filesystem::path ringdb_path = command_line::get_arg(vm, opts.shared_ringdb_dir); |
| 471 | wallet->set_ring_database(ringdb_path.string()); |
| 472 | wallet->get_message_store().set_options(vm); |
| 473 | wallet->device_name(device_name); |
| 474 | wallet->device_derivation_path(device_derivation_path); |
| 475 | |
| 476 | if (command_line::get_arg(vm, opts.no_dns)) |
| 477 | wallet->enable_dns(false); |
| 478 | |
| 479 | if (command_line::get_arg(vm, opts.offline)) |
| 480 | wallet->set_offline(); |
| 481 | |
| 482 | const std::string extra_entropy = command_line::get_arg(vm, opts.extra_entropy); |
| 483 | if (!extra_entropy.empty()) |
| 484 | { |
| 485 | std::string data; |
| 486 | THROW_WALLET_EXCEPTION_IF(!epee::file_io_utils::load_file_to_string(extra_entropy, data), |
| 487 | tools::error::wallet_internal_error, "Failed to load extra entropy from " + extra_entropy); |
| 488 | add_extra_entropy_thread_safe(data.data(), data.size()); |
| 489 | } |
| 490 | |
| 491 | if (command_line::has_arg(vm, opts.allow_mismatched_daemon_version)) |
| 492 | wallet->allow_mismatched_daemon_version(true); |
| 493 | |
| 494 | try |
| 495 | { |
| 496 | if (!command_line::is_arg_defaulted(vm, opts.tx_notify)) |
| 497 | wallet->set_tx_notify(std::shared_ptr<tools::Notify>(new tools::Notify(command_line::get_arg(vm, opts.tx_notify).c_str()))); |
| 498 | } |
| 499 | catch (const std::exception &e) |
| 500 | { |
| 501 | MERROR("Failed to parse tx notify spec: " << e.what()); |
| 502 | } |
| 503 | |
| 504 | return wallet; |
| 505 | } |
| 506 | |
| 507 | boost::optional<tools::password_container> get_password(const boost::program_options::variables_map& vm, const options& opts, const std::function<boost::optional<tools::password_container>(const char*, bool)> &password_prompter, const bool verify) |
| 508 | { |
| 509 | if (command_line::has_arg(vm, opts.password) && !command_line::is_arg_defaulted(vm, opts.password_file)) |
| 510 | { |
| 511 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("can't specify more than one of --password and --password-file")); |
| 512 | } |
| 513 | |
| 514 | if (command_line::has_arg(vm, opts.password)) |
| 515 | { |
| 516 | return tools::password_container{command_line::get_arg(vm, opts.password)}; |
| 517 | } |
| 518 | |
| 519 | if (!command_line::is_arg_defaulted(vm, opts.password_file)) |
| 520 | { |
| 521 | std::string password; |
| 522 | const auto password_file = command_line::get_arg(vm, opts.password_file); |
| 523 | bool r = epee::file_io_utils::load_file_to_string(password_file, |
| 524 | password); |
| 525 | THROW_WALLET_EXCEPTION_IF(!r, tools::error::wallet_internal_error, tools::wallet2::tr("the password file specified could not be read")); |
| 526 | |
| 527 | // Remove line breaks the user might have inserted |
| 528 | boost::trim_right_if(password, boost::is_any_of("\r\n")); |
| 529 | return {tools::password_container{std::move(password)}}; |
| 530 | } |
| 531 | |
| 532 | THROW_WALLET_EXCEPTION_IF(!password_prompter, tools::error::wallet_internal_error, tools::wallet2::tr("no password specified; use --prompt-for-password to prompt for a password")); |
| 533 | |
| 534 | return password_prompter(verify ? tools::wallet2::tr("Enter a new password for the wallet") : tools::wallet2::tr("Wallet password"), verify); |
| 535 | } |
| 536 | |
| 537 | std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> generate_from_json(const std::string& json_file, const boost::program_options::variables_map& vm, bool unattended, const options& opts, const std::function<boost::optional<tools::password_container>(const char *, bool)> &password_prompter) |
| 538 | { |
| 539 | const bool testnet = command_line::get_arg(vm, opts.testnet); |
| 540 | const bool stagenet = command_line::get_arg(vm, opts.stagenet); |
| 541 | const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET; |
| 542 | |
| 543 | /* GET_FIELD_FROM_JSON_RETURN_ON_ERROR Is a generic macro that can return |
| 544 | false. Gcc will coerce this into unique_ptr(nullptr), but clang correctly |
| 545 | fails. This large wrapper is for the use of that macro */ |
| 546 | std::unique_ptr<tools::wallet2> wallet; |
| 547 | epee::wipeable_string password; |
| 548 | const auto do_generate = [&]() -> bool { |
| 549 | std::string buf; |
| 550 | if (!epee::file_io_utils::load_file_to_string(json_file, buf)) { |
| 551 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, std::string(tools::wallet2::tr("Failed to load file ")) + json_file); |
| 552 | return false; |
| 553 | } |
| 554 | |
| 555 | rapidjson::Document json; |
| 556 | if (json.Parse(buf.c_str()).HasParseError()) { |
| 557 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("Failed to parse JSON")); |
| 558 | return false; |
| 559 | } |
| 560 | |
| 561 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, version, unsigned, Uint, true, 0); |
| 562 | const int current_version = 1; |
| 563 | THROW_WALLET_EXCEPTION_IF(field_version > current_version, tools::error::wallet_internal_error, |
| 564 | ((boost::format(tools::wallet2::tr("Version %u too new, we can only grok up to %u")) % field_version % current_version)).str()); |
| 565 | |
| 566 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, filename, std::string, String, true, std::string()); |
| 567 | |
| 568 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, scan_from_height, uint64_t, Uint64, false, 0); |
| 569 | const bool recover = true; |
| 570 | |
| 571 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, password, std::string, String, false, std::string()); |
| 572 | |
| 573 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, viewkey, std::string, String, false, std::string()); |
| 574 | crypto::secret_key viewkey; |
| 575 | if (field_viewkey_found) |
| 576 | { |
| 577 | cryptonote::blobdata viewkey_data; |
| 578 | if(!epee::string_tools::parse_hexstr_to_binbuff(field_viewkey, viewkey_data) || viewkey_data.size() != sizeof(crypto::secret_key)) |
| 579 | { |
| 580 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to parse view key secret key")); |
| 581 | } |
| 582 | viewkey = *reinterpret_cast<const crypto::secret_key*>(viewkey_data.data()); |
| 583 | crypto::public_key pkey; |
| 584 | if (viewkey == crypto::null_skey) |
| 585 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("view secret key may not be all zeroes")); |
| 586 | if (!crypto::secret_key_to_public_key(viewkey, pkey)) { |
| 587 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify view key secret key")); |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, spendkey, std::string, String, false, std::string()); |
| 592 | crypto::secret_key spendkey; |
| 593 | if (field_spendkey_found) |
| 594 | { |
| 595 | cryptonote::blobdata spendkey_data; |
| 596 | if(!epee::string_tools::parse_hexstr_to_binbuff(field_spendkey, spendkey_data) || spendkey_data.size() != sizeof(crypto::secret_key)) |
| 597 | { |
| 598 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to parse spend key secret key")); |
| 599 | } |
| 600 | spendkey = *reinterpret_cast<const crypto::secret_key*>(spendkey_data.data()); |
| 601 | crypto::public_key pkey; |
| 602 | if (spendkey == crypto::null_skey) |
| 603 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("spend secret key may not be all zeroes")); |
| 604 | if (!crypto::secret_key_to_public_key(spendkey, pkey)) { |
| 605 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify spend key secret key")); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, seed, std::string, String, false, std::string()); |
| 610 | std::string old_language; |
| 611 | crypto::secret_key recovery_key; |
| 612 | bool restore_deterministic_wallet = false; |
| 613 | if (field_seed_found) |
| 614 | { |
| 615 | if (!crypto::ElectrumWords::words_to_bytes(field_seed, recovery_key, old_language)) |
| 616 | { |
| 617 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("Electrum-style word list failed verification")); |
| 618 | } |
| 619 | restore_deterministic_wallet = true; |
| 620 | |
| 621 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, seed_passphrase, std::string, String, false, std::string()); |
| 622 | if (field_seed_passphrase_found) |
| 623 | { |
| 624 | if (!field_seed_passphrase.empty()) |
| 625 | recovery_key = cryptonote::decrypt_key(recovery_key, field_seed_passphrase); |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, address, std::string, String, false, std::string()); |
| 630 | |
| 631 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, create_address_file, int, Int, false, false); |
| 632 | bool create_address_file = field_create_address_file; |
| 633 | |
| 634 | // compatibility checks |
| 635 | if (!field_seed_found && !field_viewkey_found && !field_spendkey_found) |
| 636 | { |
| 637 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("At least one of either an Electrum-style word list, private view key, or private spend key must be specified")); |
| 638 | } |
| 639 | if (field_seed_found && (field_viewkey_found || field_spendkey_found)) |
| 640 | { |
| 641 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("Both Electrum-style word list and private key(s) specified")); |
| 642 | } |
| 643 | |
| 644 | // if an address was given, we check keys against it, and deduce the spend |
| 645 | // public key if it was not given |
| 646 | if (field_address_found) |
| 647 | { |
| 648 | cryptonote::address_parse_info info; |
| 649 | if(!get_account_address_from_str(info, nettype, field_address)) |
| 650 | { |
| 651 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("invalid address")); |
| 652 | } |
| 653 | if (field_viewkey_found) |
| 654 | { |
| 655 | crypto::public_key pkey; |
| 656 | if (!crypto::secret_key_to_public_key(viewkey, pkey)) { |
| 657 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify view key secret key")); |
| 658 | } |
| 659 | if (info.address.m_view_public_key != pkey) { |
| 660 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("view key does not match standard address")); |
| 661 | } |
| 662 | } |
| 663 | if (field_spendkey_found) |
| 664 | { |
| 665 | crypto::public_key pkey; |
| 666 | if (!crypto::secret_key_to_public_key(spendkey, pkey)) { |
| 667 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify spend key secret key")); |
| 668 | } |
| 669 | if (info.address.m_spend_public_key != pkey) { |
| 670 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("spend key does not match standard address")); |
| 671 | } |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | const bool deprecated_wallet = restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) || |
| 676 | crypto::ElectrumWords::get_is_old_style_seed(field_seed)); |
| 677 | THROW_WALLET_EXCEPTION_IF(deprecated_wallet, tools::error::wallet_internal_error, |
| 678 | tools::wallet2::tr("Cannot generate deprecated wallets from JSON")); |
| 679 | |
| 680 | wallet.reset(make_basic(vm, unattended, opts, password_prompter).release()); |
| 681 | wallet->set_refresh_from_block_height(field_scan_from_height); |
| 682 | wallet->explicit_refresh_from_block_height(field_scan_from_height_found); |
| 683 | if (!old_language.empty()) |
| 684 | wallet->set_seed_language(old_language); |
| 685 | |
| 686 | try |
| 687 | { |
| 688 | if (!field_seed.empty()) |
| 689 | { |
| 690 | wallet->generate(field_filename, field_password, recovery_key, recover, false, create_address_file); |
| 691 | password = field_password; |
| 692 | } |
| 693 | else if (field_viewkey.empty() && !field_spendkey.empty()) |
| 694 | { |
| 695 | wallet->generate(field_filename, field_password, spendkey, recover, false, create_address_file); |
| 696 | password = field_password; |
| 697 | } |
| 698 | else |
| 699 | { |
| 700 | cryptonote::account_public_address address; |
| 701 | if (!crypto::secret_key_to_public_key(viewkey, address.m_view_public_key)) { |
| 702 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify view key secret key")); |
| 703 | } |
| 704 | |
| 705 | if (field_spendkey.empty()) |
| 706 | { |
| 707 | // if we have an address but no spend key, we can deduce the spend public key |
| 708 | // from the address |
| 709 | if (field_address_found) |
| 710 | { |
| 711 | cryptonote::address_parse_info info; |
| 712 | if(!get_account_address_from_str(info, nettype, field_address)) |
| 713 | { |
| 714 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, std::string(tools::wallet2::tr("failed to parse address: ")) + field_address); |
| 715 | } |
| 716 | address.m_spend_public_key = info.address.m_spend_public_key; |
| 717 | } |
| 718 | else |
| 719 | { |
| 720 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("Address must be specified in order to create watch-only wallet")); |
| 721 | } |
| 722 | wallet->generate(field_filename, field_password, address, viewkey, create_address_file); |
| 723 | password = field_password; |
| 724 | } |
| 725 | else |
| 726 | { |
| 727 | if (!crypto::secret_key_to_public_key(spendkey, address.m_spend_public_key)) { |
| 728 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, tools::wallet2::tr("failed to verify spend key secret key")); |
| 729 | } |
| 730 | wallet->generate(field_filename, field_password, address, spendkey, viewkey, create_address_file); |
| 731 | password = field_password; |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | catch (const std::exception& e) |
| 736 | { |
| 737 | THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, std::string(tools::wallet2::tr("failed to generate new wallet: ")) + e.what()); |
| 738 | } |
| 739 | return true; |
| 740 | }; |
| 741 | |
| 742 | if (do_generate()) |
| 743 | { |
| 744 | return {std::move(wallet), tools::password_container(password)}; |
| 745 | } |
| 746 | return {nullptr, tools::password_container{}}; |
| 747 | } |
| 748 | |
| 749 | std::string strjoin(const std::vector<size_t> &V, const char *sep) |
| 750 | { |
| 751 | std::stringstream ss; |
| 752 | bool first = true; |
| 753 | for (const auto &v: V) |
| 754 | { |
| 755 | if (!first) |
| 756 | ss << sep; |
| 757 | ss << std::to_string(v); |
| 758 | first = false; |
| 759 | } |
| 760 | return ss.str(); |
| 761 | } |
| 762 | |
| 763 | static bool emplace_or_replace(std::unordered_multimap<crypto::hash, tools::wallet2::pool_payment_details> &container, |
| 764 | const crypto::hash &key, const tools::wallet2::pool_payment_details &pd) |
| 765 | { |
| 766 | auto range = container.equal_range(key); |
| 767 | for (auto i = range.first; i != range.second; ++i) |
| 768 | { |
| 769 | if (i->second.m_pd.m_tx_hash == pd.m_pd.m_tx_hash && i->second.m_pd.m_subaddr_index == pd.m_pd.m_subaddr_index) |
| 770 | { |
| 771 | i->second = pd; |
| 772 | return false; |
| 773 | } |
| 774 | } |
| 775 | container.emplace(key, pd); |
| 776 | return true; |
| 777 | } |
| 778 | |
| 779 | void drop_from_short_history(std::list<crypto::hash> &short_chain_history, size_t N) |
| 780 | { |
| 781 | std::list<crypto::hash>::iterator right; |
| 782 | // drop early N off, skipping the genesis block |
| 783 | if (short_chain_history.size() > N) { |
| 784 | right = short_chain_history.end(); |
| 785 | std::advance(right,-1); |
| 786 | std::list<crypto::hash>::iterator left = right; |
| 787 | std::advance(left, -N); |
| 788 | short_chain_history.erase(left, right); |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | size_t estimate_rct_tx_size(int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag, bool bulletproof_plus, bool use_view_tags) |
| 793 | { |
| 794 | size_t size = 0; |
| 795 | |
| 796 | // tx prefix |
| 797 | |
| 798 | // first few bytes |
| 799 | size += 1 + 6; |
| 800 | |
| 801 | // vin |
| 802 | size += n_inputs * (1+6+(mixin+1)*2+32); |
| 803 | |
| 804 | // vout |
| 805 | size += n_outputs * (6+32); |
| 806 | |
| 807 | // extra |
| 808 | size += extra_size; |
| 809 | |
| 810 | // rct signatures |
| 811 | |
| 812 | // type |
| 813 | size += 1; |
| 814 | |
| 815 | // rangeSigs |
| 816 | if (bulletproof || bulletproof_plus) |
| 817 | { |
| 818 | size_t log_padded_outputs = 0; |
| 819 | while ((1<<log_padded_outputs) < n_outputs) |
| 820 | ++log_padded_outputs; |
| 821 | size += (2 * (6 + log_padded_outputs) + (bulletproof_plus ? 6 : (4 + 5))) * 32 + 3; |
| 822 | } |
| 823 | else |
| 824 | size += (2*64*32+32+64*32) * n_outputs; |
| 825 | |
| 826 | // MGs/CLSAGs |
| 827 | if (clsag) |
| 828 | size += n_inputs * (32 * (mixin+1) + 64); |
| 829 | else |
| 830 | size += n_inputs * (64 * (mixin+1) + 32); |
| 831 | |
| 832 | if (use_view_tags) |
| 833 | size += n_outputs * sizeof(crypto::view_tag); |
| 834 | |
| 835 | // mixRing - not serialized, can be reconstructed |
| 836 | /* size += 2 * 32 * (mixin+1) * n_inputs; */ |
| 837 | |
| 838 | // pseudoOuts |
| 839 | size += 32 * n_inputs; |
| 840 | // ecdhInfo |
| 841 | size += 8 * n_outputs; |
| 842 | // outPk - only commitment is saved |
| 843 | size += 32 * n_outputs; |
| 844 | // txnFee |
| 845 | size += 4; |
| 846 | |
| 847 | LOG_PRINT_L2("estimated " << (bulletproof_plus ? "bulletproof plus" : bulletproof ? "bulletproof" : "borromean") << " rct tx size for " << n_inputs << " inputs with ring size " << (mixin+1) << " and " << n_outputs << " outputs: " << size << " (" << ((32 * n_inputs/*+1*/) + 2 * 32 * (mixin+1) * n_inputs + 32 * n_outputs) << " saved)"); |
| 848 | return size; |
| 849 | } |
| 850 | |
| 851 | size_t estimate_tx_size(bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag, bool bulletproof_plus, bool use_view_tags) |
| 852 | { |
| 853 | if (use_rct) |
| 854 | return estimate_rct_tx_size(n_inputs, mixin, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 855 | else |
| 856 | return n_inputs * (mixin+1) * APPROXIMATE_INPUT_BYTES + extra_size + (use_view_tags ? (n_outputs * sizeof(crypto::view_tag)) : 0); |
| 857 | } |
| 858 | |
| 859 | uint64_t estimate_tx_weight(bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag, bool bulletproof_plus, bool use_view_tags) |
| 860 | { |
| 861 | size_t size = estimate_tx_size(use_rct, n_inputs, mixin, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 862 | if (use_rct && (bulletproof || bulletproof_plus) && n_outputs > 2) |
| 863 | { |
| 864 | const uint64_t bp_base = (32 * ((bulletproof_plus ? 6 : 9) + 7 * 2)) / 2; // notional size of a 2 output proof, normalized to 1 proof (ie, divided by 2) |
| 865 | size_t log_padded_outputs = 2; |
| 866 | while ((1<<log_padded_outputs) < n_outputs) |
| 867 | ++log_padded_outputs; |
| 868 | uint64_t nlr = 2 * (6 + log_padded_outputs); |
| 869 | const uint64_t bp_size = 32 * ((bulletproof_plus ? 6 : 9) + nlr); |
| 870 | const uint64_t bp_clawback = (bp_base * (1<<log_padded_outputs) - bp_size) * 4 / 5; |
| 871 | MDEBUG("clawback on size " << size << ": " << bp_clawback); |
| 872 | size += bp_clawback; |
| 873 | } |
| 874 | return size; |
| 875 | } |
| 876 | |
| 877 | uint8_t get_bulletproof_fork() |
| 878 | { |
| 879 | return 8; |
| 880 | } |
| 881 | |
| 882 | uint8_t get_bulletproof_plus_fork() |
| 883 | { |
| 884 | return HF_VERSION_BULLETPROOF_PLUS; |
| 885 | } |
| 886 | |
| 887 | uint8_t get_clsag_fork() |
| 888 | { |
| 889 | return HF_VERSION_CLSAG; |
| 890 | } |
| 891 | |
| 892 | uint8_t get_view_tag_fork() |
| 893 | { |
| 894 | return HF_VERSION_VIEW_TAGS; |
| 895 | } |
| 896 | |
| 897 | uint64_t calculate_fee(bool use_per_byte_fee, const cryptonote::transaction &tx, size_t blob_size, uint64_t base_fee, uint64_t fee_quantization_mask) |
| 898 | { |
| 899 | if (use_per_byte_fee) |
| 900 | return calculate_fee_from_weight(base_fee, cryptonote::get_transaction_weight(tx, blob_size), fee_quantization_mask); |
| 901 | else |
| 902 | return calculate_fee(base_fee, blob_size); |
| 903 | } |
| 904 | |
| 905 | bool get_short_payment_id(crypto::hash8 &payment_id8, const tools::wallet2::pending_tx &ptx, hw::device &hwdev) |
| 906 | { |
| 907 | std::vector<tx_extra_field> tx_extra_fields; |
| 908 | parse_tx_extra(ptx.tx.extra, tx_extra_fields); // ok if partially parsed |
| 909 | cryptonote::tx_extra_nonce extra_nonce; |
| 910 | if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) |
| 911 | { |
| 912 | if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) |
| 913 | { |
| 914 | if (ptx.dests.empty()) |
| 915 | { |
| 916 | MWARNING("Encrypted payment id found, but no destinations public key, cannot decrypt"); |
| 917 | return false; |
| 918 | } |
| 919 | return hwdev.decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key); |
| 920 | } |
| 921 | } |
| 922 | return false; |
| 923 | } |
| 924 | |
| 925 | uint64_t get_outgoing_amount(const cryptonote::transaction &tx, const uint64_t amount_spent) |
| 926 | { |
| 927 | return tx.version == 1 ? get_outs_money_amount(tx) : (amount_spent - tx.rct_signatures.txnFee); |
| 928 | } |
| 929 | |
| 930 | tools::wallet2::tx_construction_data get_construction_data_with_decrypted_short_payment_id(const tools::wallet2::pending_tx &ptx, hw::device &hwdev) |
| 931 | { |
| 932 | tools::wallet2::tx_construction_data construction_data = ptx.construction_data; |
| 933 | crypto::hash8 payment_id = null_hash8; |
| 934 | if (get_short_payment_id(payment_id, ptx, hwdev)) |
| 935 | { |
| 936 | // Remove encrypted |
| 937 | remove_field_from_tx_extra(construction_data.extra, typeid(cryptonote::tx_extra_nonce)); |
| 938 | // Add decrypted |
| 939 | std::string extra_nonce; |
| 940 | set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id); |
| 941 | THROW_WALLET_EXCEPTION_IF(!add_extra_nonce_to_tx_extra(construction_data.extra, extra_nonce), |
| 942 | tools::error::wallet_internal_error, "Failed to add decrypted payment id to tx extra"); |
| 943 | LOG_PRINT_L1("Decrypted payment ID: " << payment_id); |
| 944 | } |
| 945 | return construction_data; |
| 946 | } |
| 947 | |
| 948 | uint32_t get_subaddress_clamped_sum(uint32_t idx, uint32_t extra) |
| 949 | { |
| 950 | static constexpr uint32_t uint32_max = std::numeric_limits<uint32_t>::max(); |
| 951 | if (idx > uint32_max - extra) |
| 952 | return uint32_max; |
| 953 | return idx + extra; |
| 954 | } |
| 955 | |
| 956 | static void setup_shim(hw::wallet_shim * shim, tools::wallet2 * wallet) |
| 957 | { |
| 958 | shim->get_tx_pub_key_from_received_outs = std::bind(&tools::wallet2::get_tx_pub_key_from_received_outs, wallet, std::placeholders::_1); |
| 959 | } |
| 960 | |
| 961 | bool get_pruned_tx(const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::entry &entry, cryptonote::transaction &tx, crypto::hash &tx_hash) |
| 962 | { |
| 963 | cryptonote::blobdata bd; |
| 964 | |
| 965 | // easy case if we have the whole tx |
| 966 | if (!entry.as_hex.empty() || (!entry.prunable_as_hex.empty() && !entry.pruned_as_hex.empty())) |
| 967 | { |
| 968 | CHECK_AND_ASSERT_MES(epee::string_tools::parse_hexstr_to_binbuff(entry.as_hex.empty() ? entry.pruned_as_hex + entry.prunable_as_hex : entry.as_hex, bd), false, "Failed to parse tx data"); |
| 969 | CHECK_AND_ASSERT_MES(cryptonote::parse_and_validate_tx_from_blob(bd, tx), false, "Invalid tx data"); |
| 970 | tx_hash = cryptonote::get_transaction_hash(tx); |
| 971 | // if the hash was given, check it matches |
| 972 | CHECK_AND_ASSERT_MES(entry.tx_hash.empty() || epee::string_tools::pod_to_hex(tx_hash) == entry.tx_hash, false, |
| 973 | "Response claims a different hash than the data yields"); |
| 974 | return true; |
| 975 | } |
| 976 | // case of a pruned tx with its prunable data hash |
| 977 | if (!entry.pruned_as_hex.empty() && !entry.prunable_hash.empty()) |
| 978 | { |
| 979 | crypto::hash ph; |
| 980 | CHECK_AND_ASSERT_MES(epee::string_tools::hex_to_pod(entry.prunable_hash, ph), false, "Failed to parse prunable hash"); |
| 981 | CHECK_AND_ASSERT_MES(epee::string_tools::parse_hexstr_to_binbuff(entry.pruned_as_hex, bd), false, "Failed to parse pruned data"); |
| 982 | CHECK_AND_ASSERT_MES(parse_and_validate_tx_base_from_blob(bd, tx), false, "Invalid base tx data"); |
| 983 | // only v2 txes can calculate their txid after pruned |
| 984 | if (bd[0] > 1) |
| 985 | { |
| 986 | CHECK_AND_ASSERT_MES(cryptonote::get_pruned_transaction_hash(tx, ph, tx_hash), false, "Failed to get pruned tx hash"); |
| 987 | } |
| 988 | else |
| 989 | { |
| 990 | // for v1, we trust the dameon |
| 991 | CHECK_AND_ASSERT_MES(epee::string_tools::hex_to_pod(entry.tx_hash, tx_hash), false, "Failed to parse tx hash"); |
| 992 | } |
| 993 | return true; |
| 994 | } |
| 995 | return false; |
| 996 | } |
| 997 | |
| 998 | // Given M (threshold) and N (total), calculate the number of private multisig keys each |
| 999 | // signer should have. This value is equal to (N - 1) choose (N - M) |
| 1000 | // Prereq: M >= 1 && N >= M && N <= 16 |
| 1001 | uint64_t num_priv_multisig_keys_post_setup(uint64_t threshold, uint64_t total) |
| 1002 | { |
| 1003 | THROW_WALLET_EXCEPTION_IF(threshold < 1 || total < threshold || threshold > 16, |
| 1004 | tools::error::wallet_internal_error, "Invalid arguments to num_priv_multisig_keys_post_setup"); |
| 1005 | |
| 1006 | uint64_t n_multisig_keys = 1; |
| 1007 | for (uint64_t i = 2; i <= total - 1; ++i) n_multisig_keys *= i; // multiply by (N - 1)! |
| 1008 | for (uint64_t i = 2; i <= total - threshold; ++i) n_multisig_keys /= i; // divide by (N - M)! |
| 1009 | for (uint64_t i = 2; i <= threshold - 1; ++i) n_multisig_keys /= i; // divide by ((N - 1) - (N - M))! |
| 1010 | return n_multisig_keys; |
| 1011 | } |
| 1012 | |
| 1013 | /** |
| 1014 | * @brief Derives the chacha key to encrypt wallet cache files given the chacha key to encrypt the wallet keys files |
| 1015 | * |
| 1016 | * @param keys_data_key the chacha key that encrypts wallet keys files |
| 1017 | * @return crypto::chacha_key the chacha key that encrypts the wallet cache files |
| 1018 | */ |
| 1019 | crypto::chacha_key derive_cache_key(const crypto::chacha_key& keys_data_key, const unsigned char domain_separator) |
| 1020 | { |
| 1021 | static_assert(HASH_SIZE == sizeof(crypto::chacha_key), "Mismatched sizes of hash and chacha key"); |
| 1022 | |
| 1023 | crypto::chacha_key cache_key; |
| 1024 | epee::mlocked<tools::scrubbed_arr<char, HASH_SIZE+1>> cache_key_data; |
| 1025 | memcpy(cache_key_data.data(), &keys_data_key, HASH_SIZE); |
| 1026 | cache_key_data[HASH_SIZE] = domain_separator; |
| 1027 | cn_fast_hash(cache_key_data.data(), HASH_SIZE+1, (crypto::hash&) cache_key); |
| 1028 | |
| 1029 | return cache_key; |
| 1030 | } |
| 1031 | //----------------------------------------------------------------- |
| 1032 | } //namespace |
| 1033 | |
| 1034 | namespace tools |
| 1035 | { |
| 1036 | constexpr const std::chrono::seconds wallet2::rpc_timeout; |
| 1037 | const char* wallet2::tr(const char* str) { return i18n_translate(str, "tools::wallet2"); } |
| 1038 | |
| 1039 | gamma_picker::gamma_picker(const std::vector<uint64_t> &rct_offsets, double shape, double scale): |
| 1040 | rct_offsets(rct_offsets) |
| 1041 | { |
| 1042 | gamma = std::gamma_distribution<double>(shape, scale); |
| 1043 | THROW_WALLET_EXCEPTION_IF(rct_offsets.size() <= CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE, error::wallet_internal_error, "Bad offset calculation"); |
| 1044 | const size_t blocks_in_a_year = 86400 * 365 / DIFFICULTY_TARGET_V2; |
| 1045 | const size_t blocks_to_consider = std::min<size_t>(rct_offsets.size(), blocks_in_a_year); |
| 1046 | const size_t outputs_to_consider = rct_offsets.back() - (blocks_to_consider < rct_offsets.size() ? rct_offsets[rct_offsets.size() - blocks_to_consider - 1] : 0); |
| 1047 | begin = rct_offsets.data(); |
| 1048 | end = rct_offsets.data() + rct_offsets.size() - (std::max(1, CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE) - 1); |
| 1049 | num_rct_outputs = *(end - 1); |
| 1050 | THROW_WALLET_EXCEPTION_IF(num_rct_outputs == 0, error::wallet_internal_error, "No rct outputs"); |
| 1051 | average_output_time = DIFFICULTY_TARGET_V2 * blocks_to_consider / static_cast<double>(outputs_to_consider); // this assumes constant target over the whole rct range |
| 1052 | }; |
| 1053 | |
| 1054 | gamma_picker::gamma_picker(const std::vector<uint64_t> &rct_offsets): gamma_picker(rct_offsets, GAMMA_SHAPE, GAMMA_SCALE) {} |
| 1055 | |
| 1056 | uint64_t gamma_picker::pick() |
| 1057 | { |
| 1058 | double x = gamma(engine); |
| 1059 | x = exp(x); |
| 1060 | |
| 1061 | if (x > DEFAULT_UNLOCK_TIME) |
| 1062 | { |
| 1063 | // We are trying to select an output from the chain that appeared 'x' seconds before the |
| 1064 | // current chain tip, where 'x' is selected from the gamma distribution recommended in Miller et al. |
| 1065 | // (https://arxiv.org/pdf/1704.04299/). |
| 1066 | // Our method is to get the average time delta between outputs in the recent past, estimate the number of |
| 1067 | // outputs 'n' that would have appeared between 'chain_tip - x' and 'chain_tip', select the real output at |
| 1068 | // 'current_num_outputs - n', then randomly select an output from the block where that output appears. |
| 1069 | // Source code to paper: https://github.com/maltemoeser/moneropaper |
| 1070 | // |
| 1071 | // Due to the 'default spendable age' mechanic in Monero, 'current_num_outputs' only contains |
| 1072 | // currently *unlocked* outputs, which means the earliest output that can be selected is not at the chain tip! |
| 1073 | // Therefore, we must offset 'x' so it matches up with the timing of the outputs being considered. We do |
| 1074 | // this by saying if 'x` equals the expected age of the first unlocked output (compared to the current |
| 1075 | // chain tip - i.e. DEFAULT_UNLOCK_TIME), then select the first unlocked output. |
| 1076 | x -= DEFAULT_UNLOCK_TIME; |
| 1077 | } |
| 1078 | else |
| 1079 | { |
| 1080 | // If the spent time suggested by the gamma is less than the unlock time, that means the gamma is suggesting an output |
| 1081 | // that is no longer feasible to be spent (possible since the gamma was constructed when consensus rules did not enforce the |
| 1082 | // lock time). The assumption made in this code is that an output expected spent quicker than the unlock time would likely |
| 1083 | // be spent within RECENT_SPEND_WINDOW after allowed. So it returns an output that falls between 0 and the RECENT_SPEND_WINDOW. |
| 1084 | // The RECENT_SPEND_WINDOW was determined with empirical analysis of observed data. |
| 1085 | x = crypto::rand_idx(static_cast<uint64_t>(RECENT_SPEND_WINDOW)); |
| 1086 | } |
| 1087 | |
| 1088 | uint64_t output_index = x / average_output_time; |
| 1089 | if (output_index >= num_rct_outputs) |
| 1090 | return std::numeric_limits<uint64_t>::max(); // bad pick |
| 1091 | output_index = num_rct_outputs - 1 - output_index; |
| 1092 | |
| 1093 | const uint64_t *it = std::lower_bound(begin, end, output_index); |
| 1094 | THROW_WALLET_EXCEPTION_IF(it == end, error::wallet_internal_error, "output_index not found"); |
| 1095 | uint64_t index = std::distance(begin, it); |
| 1096 | |
| 1097 | const uint64_t first_rct = index == 0 ? 0 : rct_offsets[index - 1]; |
| 1098 | const uint64_t n_rct = rct_offsets[index] - first_rct; |
| 1099 | if (n_rct == 0) |
| 1100 | return std::numeric_limits<uint64_t>::max(); // bad pick |
| 1101 | MTRACE("Picking 1/" << n_rct << " in block " << index); |
| 1102 | return first_rct + crypto::rand_idx(n_rct); |
| 1103 | }; |
| 1104 | |
| 1105 | boost::mutex wallet_keys_unlocker::lockers_lock; |
| 1106 | unsigned int wallet_keys_unlocker::lockers = 0; |
| 1107 | wallet_keys_unlocker::wallet_keys_unlocker(wallet2 &w, const boost::optional<tools::password_container> &password): |
| 1108 | w(w), |
| 1109 | locked(password != boost::none) |
| 1110 | { |
| 1111 | boost::lock_guard<boost::mutex> lock(lockers_lock); |
| 1112 | if (lockers++ > 0) |
| 1113 | locked = false; |
| 1114 | if (!locked || w.is_unattended() || w.ask_password() != tools::wallet2::AskPasswordToDecrypt || w.watch_only() || w.is_background_syncing()) |
| 1115 | { |
| 1116 | locked = false; |
| 1117 | return; |
| 1118 | } |
| 1119 | const epee::wipeable_string pass = password->password(); |
| 1120 | w.generate_chacha_key_from_password(pass, key); |
| 1121 | w.decrypt_keys(key); |
| 1122 | } |
| 1123 | |
| 1124 | wallet_keys_unlocker::wallet_keys_unlocker(wallet2 &w, bool locked, const epee::wipeable_string &password): |
| 1125 | w(w), |
| 1126 | locked(locked) |
| 1127 | { |
| 1128 | boost::lock_guard<boost::mutex> lock(lockers_lock); |
| 1129 | if (lockers++ > 0) |
| 1130 | locked = false; |
| 1131 | if (!locked) |
| 1132 | return; |
| 1133 | w.generate_chacha_key_from_password(password, key); |
| 1134 | w.decrypt_keys(key); |
| 1135 | } |
| 1136 | |
| 1137 | wallet_keys_unlocker::~wallet_keys_unlocker() |
| 1138 | { |
| 1139 | try |
| 1140 | { |
| 1141 | boost::lock_guard<boost::mutex> lock(lockers_lock); |
| 1142 | if (lockers == 0) |
| 1143 | { |
| 1144 | MERROR("There are no lockers in wallet_keys_unlocker dtor"); |
| 1145 | return; |
| 1146 | } |
| 1147 | --lockers; |
| 1148 | if (!locked) |
| 1149 | return; |
| 1150 | w.encrypt_keys(key); |
| 1151 | } |
| 1152 | catch (...) |
| 1153 | { |
| 1154 | MERROR("Failed to re-encrypt wallet keys"); |
| 1155 | // do not propagate through dtor, we'd crash |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | void wallet_device_callback::on_button_request(uint64_t code) |
| 1160 | { |
| 1161 | if (wallet) |
| 1162 | wallet->on_device_button_request(code); |
| 1163 | } |
| 1164 | |
| 1165 | void wallet_device_callback::on_button_pressed() |
| 1166 | { |
| 1167 | if (wallet) |
| 1168 | wallet->on_device_button_pressed(); |
| 1169 | } |
| 1170 | |
| 1171 | boost::optional<epee::wipeable_string> wallet_device_callback::on_pin_request() |
| 1172 | { |
| 1173 | if (wallet) |
| 1174 | return wallet->on_device_pin_request(); |
| 1175 | return boost::none; |
| 1176 | } |
| 1177 | |
| 1178 | boost::optional<epee::wipeable_string> wallet_device_callback::on_passphrase_request(bool & on_device) |
| 1179 | { |
| 1180 | if (wallet) |
| 1181 | return wallet->on_device_passphrase_request(on_device); |
| 1182 | else |
| 1183 | on_device = true; |
| 1184 | return boost::none; |
| 1185 | } |
| 1186 | |
| 1187 | void wallet_device_callback::on_progress(const hw::device_progress& event) |
| 1188 | { |
| 1189 | if (wallet) |
| 1190 | wallet->on_device_progress(event); |
| 1191 | } |
| 1192 | |
| 1193 | wallet2::wallet2(network_type nettype, uint64_t kdf_rounds, bool unattended, std::unique_ptr<epee::net_utils::http::http_client_factory> http_client_factory): |
| 1194 | m_http_client(http_client_factory->create()), |
| 1195 | m_upper_transaction_weight_limit(0), |
| 1196 | m_run(true), |
| 1197 | m_callback(0), |
| 1198 | m_trusted_daemon(false), |
| 1199 | m_nettype(nettype), |
| 1200 | m_multisig_rounds_passed(0), |
| 1201 | m_always_confirm_transfers(true), |
| 1202 | m_print_ring_members(false), |
| 1203 | m_store_tx_info(true), |
| 1204 | m_default_mixin(0), |
| 1205 | m_default_priority(0), |
| 1206 | m_refresh_type(RefreshOptimizeCoinbase), |
| 1207 | m_auto_refresh(true), |
| 1208 | m_first_refresh_done(false), |
| 1209 | m_refresh_from_block_height(0), |
| 1210 | m_explicit_refresh_from_block_height(true), |
| 1211 | m_skip_to_height(0), |
| 1212 | m_confirm_non_default_ring_size(true), |
| 1213 | m_ask_password(AskPasswordToDecrypt), |
| 1214 | m_max_reorg_depth(ORPHANED_BLOCKS_MAX_COUNT), |
| 1215 | m_min_output_count(0), |
| 1216 | m_min_output_value(0), |
| 1217 | m_merge_destinations(false), |
| 1218 | m_confirm_backlog(true), |
| 1219 | m_confirm_backlog_threshold(0), |
| 1220 | m_confirm_export_overwrite(true), |
| 1221 | m_auto_low_priority(true), |
| 1222 | m_segregate_pre_fork_outputs(true), |
| 1223 | m_key_reuse_mitigation2(true), |
| 1224 | m_segregation_height(0), |
| 1225 | m_ignore_fractional_outputs(true), |
| 1226 | m_ignore_outputs_above(MONEY_SUPPLY), |
| 1227 | m_ignore_outputs_below(0), |
| 1228 | m_track_uses(false), |
| 1229 | m_is_background_wallet(false), |
| 1230 | m_background_sync_type(BackgroundSyncOff), |
| 1231 | m_background_syncing(false), |
| 1232 | m_processing_background_cache(false), |
| 1233 | m_custom_background_key(boost::none), |
| 1234 | m_show_wallet_name_when_locked(false), |
| 1235 | m_inactivity_lock_timeout(DEFAULT_INACTIVITY_LOCK_TIMEOUT), |
| 1236 | m_setup_background_mining(BackgroundMiningMaybe), |
| 1237 | m_persistent_rpc_client_id(false), |
| 1238 | m_auto_mine_for_rpc_payment_threshold(-1.0f), |
| 1239 | m_is_initialized(false), |
| 1240 | m_kdf_rounds(kdf_rounds), |
| 1241 | is_old_file_format(false), |
| 1242 | m_watch_only(false), |
| 1243 | m_multisig(false), |
| 1244 | m_multisig_threshold(0), |
| 1245 | m_node_rpc_proxy(*m_http_client, m_rpc_payment_state, m_daemon_rpc_mutex), |
| 1246 | m_account_public_address{crypto::null_pkey, crypto::null_pkey}, |
| 1247 | m_subaddress_lookahead_major(SUBADDRESS_LOOKAHEAD_MAJOR), |
| 1248 | m_subaddress_lookahead_minor(SUBADDRESS_LOOKAHEAD_MINOR), |
| 1249 | m_light_wallet(false), |
| 1250 | m_light_wallet_scanned_block_height(0), |
| 1251 | m_light_wallet_blockchain_height(0), |
| 1252 | m_light_wallet_connected(false), |
| 1253 | m_light_wallet_balance(0), |
| 1254 | m_light_wallet_unlocked_balance(0), |
| 1255 | m_original_keys_available(false), |
| 1256 | m_message_store(http_client_factory->create()), |
| 1257 | m_key_device_type(hw::device::device_type::SOFTWARE), |
| 1258 | m_ring_history_saved(true), |
| 1259 | m_ringdb(), |
| 1260 | m_last_block_reward(0), |
| 1261 | m_unattended(unattended), |
| 1262 | m_devices_registered(false), |
| 1263 | m_device_last_key_image_sync(0), |
| 1264 | m_use_dns(true), |
| 1265 | m_offline(false), |
| 1266 | m_rpc_version(0), |
| 1267 | m_export_format(ExportFormat::Binary), |
| 1268 | m_load_deprecated_formats(false), |
| 1269 | m_credits_target(0), |
| 1270 | m_enable_multisig(false), |
| 1271 | m_pool_info_query_time(0), |
| 1272 | m_has_ever_refreshed_from_node(false), |
| 1273 | m_allow_mismatched_daemon_version(false) |
| 1274 | { |
| 1275 | set_rpc_client_secret_key(rct::rct2sk(rct::skGen())); |
| 1276 | } |
| 1277 | |
| 1278 | wallet2::~wallet2() |
| 1279 | { |
| 1280 | deinit(); |
| 1281 | } |
| 1282 | |
| 1283 | bool wallet2::has_testnet_option(const boost::program_options::variables_map& vm) |
| 1284 | { |
| 1285 | return command_line::get_arg(vm, options().testnet); |
| 1286 | } |
| 1287 | |
| 1288 | bool wallet2::has_stagenet_option(const boost::program_options::variables_map& vm) |
| 1289 | { |
| 1290 | return command_line::get_arg(vm, options().stagenet); |
| 1291 | } |
| 1292 | |
| 1293 | bool wallet2::has_proxy_option() const |
| 1294 | { |
| 1295 | return !m_proxy.empty(); |
| 1296 | } |
| 1297 | |
| 1298 | std::string wallet2::device_name_option(const boost::program_options::variables_map& vm) |
| 1299 | { |
| 1300 | return command_line::get_arg(vm, options().hw_device); |
| 1301 | } |
| 1302 | |
| 1303 | std::string wallet2::device_derivation_path_option(const boost::program_options::variables_map &vm) |
| 1304 | { |
| 1305 | return command_line::get_arg(vm, options().hw_device_derivation_path); |
| 1306 | } |
| 1307 | |
| 1308 | void wallet2::init_options(boost::program_options::options_description& desc_params) |
| 1309 | { |
| 1310 | const options opts{}; |
| 1311 | command_line::add_arg(desc_params, opts.daemon_address); |
| 1312 | command_line::add_arg(desc_params, opts.daemon_host); |
| 1313 | command_line::add_arg(desc_params, opts.proxy); |
| 1314 | command_line::add_arg(desc_params, opts.trusted_daemon); |
| 1315 | command_line::add_arg(desc_params, opts.untrusted_daemon); |
| 1316 | command_line::add_arg(desc_params, opts.password); |
| 1317 | command_line::add_arg(desc_params, opts.password_file); |
| 1318 | command_line::add_arg(desc_params, opts.daemon_port); |
| 1319 | command_line::add_arg(desc_params, opts.daemon_login); |
| 1320 | command_line::add_arg(desc_params, opts.daemon_ssl); |
| 1321 | command_line::add_arg(desc_params, opts.daemon_ssl_private_key); |
| 1322 | command_line::add_arg(desc_params, opts.daemon_ssl_certificate); |
| 1323 | command_line::add_arg(desc_params, opts.daemon_ssl_ca_certificates); |
| 1324 | command_line::add_arg(desc_params, opts.daemon_ssl_allowed_fingerprints); |
| 1325 | command_line::add_arg(desc_params, opts.daemon_ssl_allow_any_cert); |
| 1326 | command_line::add_arg(desc_params, opts.daemon_ssl_allow_chained); |
| 1327 | command_line::add_arg(desc_params, opts.testnet); |
| 1328 | command_line::add_arg(desc_params, opts.stagenet); |
| 1329 | command_line::add_arg(desc_params, opts.shared_ringdb_dir); |
| 1330 | command_line::add_arg(desc_params, opts.kdf_rounds); |
| 1331 | mms::message_store::init_options(desc_params); |
| 1332 | command_line::add_arg(desc_params, opts.hw_device); |
| 1333 | command_line::add_arg(desc_params, opts.hw_device_derivation_path); |
| 1334 | command_line::add_arg(desc_params, opts.tx_notify); |
| 1335 | command_line::add_arg(desc_params, opts.no_dns); |
| 1336 | command_line::add_arg(desc_params, opts.offline); |
| 1337 | command_line::add_arg(desc_params, opts.extra_entropy); |
| 1338 | command_line::add_arg(desc_params, opts.allow_mismatched_daemon_version); |
| 1339 | } |
| 1340 | |
| 1341 | std::pair<std::unique_ptr<wallet2>, tools::password_container> wallet2::make_from_json(const boost::program_options::variables_map& vm, bool unattended, const std::string& json_file, const std::function<boost::optional<tools::password_container>(const char *, bool)> &password_prompter) |
| 1342 | { |
| 1343 | const options opts{}; |
| 1344 | return generate_from_json(json_file, vm, unattended, opts, password_prompter); |
| 1345 | } |
| 1346 | |
| 1347 | std::pair<std::unique_ptr<wallet2>, password_container> wallet2::make_from_file( |
| 1348 | const boost::program_options::variables_map& vm, bool unattended, const std::string& wallet_file, const std::function<boost::optional<tools::password_container>(const char *, bool)> &password_prompter) |
| 1349 | { |
| 1350 | const options opts{}; |
| 1351 | auto pwd = get_password(vm, opts, password_prompter, false); |
| 1352 | if (!pwd) |
| 1353 | { |
| 1354 | return {nullptr, password_container{}}; |
| 1355 | } |
| 1356 | auto wallet = make_basic(vm, unattended, opts, password_prompter); |
| 1357 | if (wallet && !wallet_file.empty()) |
| 1358 | { |
| 1359 | wallet->load(wallet_file, pwd->password()); |
| 1360 | } |
| 1361 | return {std::move(wallet), std::move(*pwd)}; |
| 1362 | } |
| 1363 | |
| 1364 | std::pair<std::unique_ptr<wallet2>, password_container> wallet2::make_new(const boost::program_options::variables_map& vm, bool unattended, const std::function<boost::optional<password_container>(const char *, bool)> &password_prompter) |
| 1365 | { |
| 1366 | const options opts{}; |
| 1367 | auto pwd = get_password(vm, opts, password_prompter, true); |
| 1368 | if (!pwd) |
| 1369 | { |
| 1370 | return {nullptr, password_container{}}; |
| 1371 | } |
| 1372 | return {make_basic(vm, unattended, opts, password_prompter), std::move(*pwd)}; |
| 1373 | } |
| 1374 | |
| 1375 | std::unique_ptr<wallet2> wallet2::make_dummy(const boost::program_options::variables_map& vm, bool unattended, const std::function<boost::optional<tools::password_container>(const char *, bool)> &password_prompter) |
| 1376 | { |
| 1377 | const options opts{}; |
| 1378 | return make_basic(vm, unattended, opts, password_prompter); |
| 1379 | } |
| 1380 | |
| 1381 | //---------------------------------------------------------------------------------------------------- |
| 1382 | bool wallet2::set_daemon(std::string daemon_address, boost::optional<epee::net_utils::http::login> daemon_login, bool trusted_daemon, epee::net_utils::ssl_options_t ssl_options, const std::string& proxy) |
| 1383 | { |
| 1384 | boost::lock_guard<boost::recursive_mutex> lock(m_daemon_rpc_mutex); |
| 1385 | |
| 1386 | if(m_http_client->is_connected()) |
| 1387 | m_http_client->disconnect(); |
| 1388 | CHECK_AND_ASSERT_MES2(m_proxy.empty() || proxy.empty() , "It is not possible to set global proxy (--proxy) and daemon specific proxy together."); |
| 1389 | if(m_proxy.empty()) |
| 1390 | CHECK_AND_ASSERT_MES(set_proxy(proxy), false, "failed to set proxy address"); |
| 1391 | const bool changed = m_daemon_address != daemon_address; |
| 1392 | m_daemon_address = std::move(daemon_address); |
| 1393 | m_daemon_login = std::move(daemon_login); |
| 1394 | m_trusted_daemon = trusted_daemon; |
| 1395 | if (changed) |
| 1396 | { |
| 1397 | if (!m_persistent_rpc_client_id) { |
| 1398 | set_rpc_client_secret_key(rct::rct2sk(rct::skGen())); |
| 1399 | } |
| 1400 | m_rpc_payment_state.expected_spent = 0; |
| 1401 | m_rpc_payment_state.discrepancy = 0; |
| 1402 | m_rpc_version = 0; |
| 1403 | m_node_rpc_proxy.invalidate(); |
| 1404 | m_pool_info_query_time = 0; |
| 1405 | } |
| 1406 | |
| 1407 | const std::string address = get_daemon_address(); |
| 1408 | MINFO("setting daemon to " << address); |
| 1409 | bool ret = m_http_client->set_server(address, get_daemon_login(), std::move(ssl_options)); |
| 1410 | if (ret) |
| 1411 | { |
| 1412 | CRITICAL_REGION_LOCAL(default_daemon_address_lock); |
| 1413 | default_daemon_address = address; |
| 1414 | } |
| 1415 | return ret; |
| 1416 | } |
| 1417 | //---------------------------------------------------------------------------------------------------- |
| 1418 | bool wallet2::set_proxy(const std::string &address) |
| 1419 | { |
| 1420 | return m_http_client->set_proxy(address); |
| 1421 | } |
| 1422 | //---------------------------------------------------------------------------------------------------- |
| 1423 | bool wallet2::init(std::string daemon_address, boost::optional<epee::net_utils::http::login> daemon_login, const std::string &proxy_address, uint64_t upper_transaction_weight_limit, bool trusted_daemon, epee::net_utils::ssl_options_t ssl_options) |
| 1424 | { |
| 1425 | m_proxy = proxy_address; |
| 1426 | CHECK_AND_ASSERT_MES(set_proxy(m_proxy), false, "failed to set proxy address"); |
| 1427 | m_checkpoints.init_default_checkpoints(m_nettype); |
| 1428 | m_is_initialized = true; |
| 1429 | m_upper_transaction_weight_limit = upper_transaction_weight_limit; |
| 1430 | return set_daemon(daemon_address, daemon_login, trusted_daemon, std::move(ssl_options)); |
| 1431 | } |
| 1432 | //---------------------------------------------------------------------------------------------------- |
| 1433 | bool wallet2::is_deterministic() const |
| 1434 | { |
| 1435 | crypto::secret_key second; |
| 1436 | keccak((uint8_t *)&get_account().get_keys().m_spend_secret_key, sizeof(crypto::secret_key), (uint8_t *)&second, sizeof(crypto::secret_key)); |
| 1437 | sc_reduce32((uint8_t *)&second); |
| 1438 | return memcmp(second.data,get_account().get_keys().m_view_secret_key.data, sizeof(crypto::secret_key)) == 0; |
| 1439 | } |
| 1440 | //---------------------------------------------------------------------------------------------------- |
| 1441 | bool wallet2::get_seed(epee::wipeable_string& electrum_words, const epee::wipeable_string &passphrase) const |
| 1442 | { |
| 1443 | bool keys_deterministic = is_deterministic(); |
| 1444 | if (!keys_deterministic) |
| 1445 | { |
| 1446 | std::cout << "This is not a deterministic wallet" << std::endl; |
| 1447 | return false; |
| 1448 | } |
| 1449 | if (seed_language.empty()) |
| 1450 | { |
| 1451 | std::cout << "seed_language not set" << std::endl; |
| 1452 | return false; |
| 1453 | } |
| 1454 | |
| 1455 | crypto::secret_key key = get_account().get_keys().m_spend_secret_key; |
| 1456 | if (!passphrase.empty()) |
| 1457 | key = cryptonote::encrypt_key(key, passphrase); |
| 1458 | if (!crypto::ElectrumWords::bytes_to_words(key, electrum_words, seed_language)) |
| 1459 | { |
| 1460 | std::cout << "Failed to create seed from key for language: " << seed_language << std::endl; |
| 1461 | return false; |
| 1462 | } |
| 1463 | |
| 1464 | return true; |
| 1465 | } |
| 1466 | //---------------------------------------------------------------------------------------------------- |
| 1467 | bool wallet2::get_multisig_seed(epee::wipeable_string& seed, const epee::wipeable_string &passphrase) const |
| 1468 | { |
| 1469 | bool ready; |
| 1470 | uint32_t threshold, total; |
| 1471 | if (!multisig(&ready, &threshold, &total)) |
| 1472 | { |
| 1473 | std::cout << "This is not a multisig wallet" << std::endl; |
| 1474 | return false; |
| 1475 | } |
| 1476 | if (!ready) |
| 1477 | { |
| 1478 | std::cout << "This multisig wallet is not yet finalized" << std::endl; |
| 1479 | return false; |
| 1480 | } |
| 1481 | |
| 1482 | const uint64_t num_expected_ms_keys = num_priv_multisig_keys_post_setup(threshold, total); |
| 1483 | |
| 1484 | crypto::secret_key skey; |
| 1485 | crypto::public_key pkey; |
| 1486 | const account_keys &keys = get_account().get_keys(); |
| 1487 | THROW_WALLET_EXCEPTION_IF(num_expected_ms_keys != keys.m_multisig_keys.size(), |
| 1488 | error::wallet_internal_error, "Unexpected number of private multisig keys") |
| 1489 | epee::wipeable_string data; |
| 1490 | data.append((const char*)&threshold, sizeof(uint32_t)); |
| 1491 | data.append((const char*)&total, sizeof(uint32_t)); |
| 1492 | skey = keys.m_spend_secret_key; |
| 1493 | data.append((const char*)&skey, sizeof(skey)); |
| 1494 | pkey = keys.m_account_address.m_spend_public_key; |
| 1495 | data.append((const char*)&pkey, sizeof(pkey)); |
| 1496 | skey = keys.m_view_secret_key; |
| 1497 | data.append((const char*)&skey, sizeof(skey)); |
| 1498 | pkey = keys.m_account_address.m_view_public_key; |
| 1499 | data.append((const char*)&pkey, sizeof(pkey)); |
| 1500 | for (const auto &skey: keys.m_multisig_keys) |
| 1501 | data.append((const char*)&skey, sizeof(skey)); |
| 1502 | for (const auto &signer: m_multisig_signers) |
| 1503 | data.append((const char*)&signer, sizeof(signer)); |
| 1504 | |
| 1505 | if (!passphrase.empty()) |
| 1506 | { |
| 1507 | crypto::secret_key key; |
| 1508 | crypto::cn_slow_hash(passphrase.data(), passphrase.size(), (crypto::hash&)key); |
| 1509 | sc_reduce32((unsigned char*)key.data); |
| 1510 | data = encrypt(data, key, true); |
| 1511 | } |
| 1512 | |
| 1513 | seed = epee::to_hex::wipeable_string({(const unsigned char*)data.data(), data.size()}); |
| 1514 | |
| 1515 | return true; |
| 1516 | } |
| 1517 | //---------------------------------------------------------------------------------------------------- |
| 1518 | bool wallet2::reconnect_device() |
| 1519 | { |
| 1520 | bool r = true; |
| 1521 | hw::device &hwdev = lookup_device(m_device_name); |
| 1522 | hwdev.set_name(m_device_name); |
| 1523 | hwdev.set_network_type(m_nettype); |
| 1524 | hwdev.set_derivation_path(m_device_derivation_path); |
| 1525 | hwdev.set_callback(get_device_callback()); |
| 1526 | r = hwdev.init(); |
| 1527 | if (!r){ |
| 1528 | MERROR("Could not init device"); |
| 1529 | return false; |
| 1530 | } |
| 1531 | |
| 1532 | r = hwdev.connect(); |
| 1533 | if (!r){ |
| 1534 | MERROR("Could not connect to the device"); |
| 1535 | return false; |
| 1536 | } |
| 1537 | |
| 1538 | m_account.set_device(hwdev); |
| 1539 | return true; |
| 1540 | } |
| 1541 | //---------------------------------------------------------------------------------------------------- |
| 1542 | /*! |
| 1543 | * \brief Gets the seed language |
| 1544 | */ |
| 1545 | const std::string &wallet2::get_seed_language() const |
| 1546 | { |
| 1547 | return seed_language; |
| 1548 | } |
| 1549 | /*! |
| 1550 | * \brief Sets the seed language |
| 1551 | * \param language Seed language to set to |
| 1552 | */ |
| 1553 | void wallet2::set_seed_language(const std::string &language) |
| 1554 | { |
| 1555 | seed_language = language; |
| 1556 | } |
| 1557 | //---------------------------------------------------------------------------------------------------- |
| 1558 | cryptonote::account_public_address wallet2::get_subaddress(const cryptonote::subaddress_index& index) const |
| 1559 | { |
| 1560 | hw::device &hwdev = m_account.get_device(); |
| 1561 | return hwdev.get_subaddress(m_account.get_keys(), index); |
| 1562 | } |
| 1563 | //---------------------------------------------------------------------------------------------------- |
| 1564 | boost::optional<cryptonote::subaddress_index> wallet2::get_subaddress_index(const cryptonote::account_public_address& address) const |
| 1565 | { |
| 1566 | auto index = m_subaddresses.find(address.m_spend_public_key); |
| 1567 | if (index == m_subaddresses.end()) |
| 1568 | return boost::none; |
| 1569 | return index->second; |
| 1570 | } |
| 1571 | //---------------------------------------------------------------------------------------------------- |
| 1572 | crypto::public_key wallet2::get_subaddress_spend_public_key(const cryptonote::subaddress_index& index) const |
| 1573 | { |
| 1574 | hw::device &hwdev = m_account.get_device(); |
| 1575 | return hwdev.get_subaddress_spend_public_key(m_account.get_keys(), index); |
| 1576 | } |
| 1577 | //---------------------------------------------------------------------------------------------------- |
| 1578 | std::string wallet2::get_subaddress_as_str(const cryptonote::subaddress_index& index) const |
| 1579 | { |
| 1580 | cryptonote::account_public_address address = get_subaddress(index); |
| 1581 | return cryptonote::get_account_address_as_str(m_nettype, !index.is_zero(), address); |
| 1582 | } |
| 1583 | //---------------------------------------------------------------------------------------------------- |
| 1584 | std::string wallet2::get_integrated_address_as_str(const crypto::hash8& payment_id) const |
| 1585 | { |
| 1586 | return cryptonote::get_account_integrated_address_as_str(m_nettype, get_address(), payment_id); |
| 1587 | } |
| 1588 | //---------------------------------------------------------------------------------------------------- |
| 1589 | void wallet2::add_subaddress_account(const std::string& label) |
| 1590 | { |
| 1591 | uint32_t index_major = (uint32_t)get_num_subaddress_accounts(); |
| 1592 | expand_subaddresses({index_major, 0}); |
| 1593 | m_subaddress_labels[index_major][0] = label; |
| 1594 | } |
| 1595 | //---------------------------------------------------------------------------------------------------- |
| 1596 | void wallet2::add_subaddress(uint32_t index_major, const std::string& label) |
| 1597 | { |
| 1598 | THROW_WALLET_EXCEPTION_IF(index_major >= m_subaddress_labels.size(), error::account_index_outofbound); |
| 1599 | uint32_t index_minor = (uint32_t)get_num_subaddresses(index_major); |
| 1600 | expand_subaddresses({index_major, index_minor}); |
| 1601 | m_subaddress_labels[index_major][index_minor] = label; |
| 1602 | } |
| 1603 | //---------------------------------------------------------------------------------------------------- |
| 1604 | bool wallet2::should_expand(const cryptonote::subaddress_index &index) const |
| 1605 | { |
| 1606 | const uint32_t last_major = m_subaddress_labels.size() - 1 > (std::numeric_limits<uint32_t>::max() - m_subaddress_lookahead_major) ? std::numeric_limits<uint32_t>::max() : (m_subaddress_labels.size() + m_subaddress_lookahead_major - 1); |
| 1607 | if (index.major > last_major) |
| 1608 | return false; |
| 1609 | const size_t nsub = index.major < m_subaddress_labels.size() ? m_subaddress_labels[index.major].size() : 0; |
| 1610 | const uint32_t last_minor = nsub - 1 > (std::numeric_limits<uint32_t>::max() - m_subaddress_lookahead_minor) ? std::numeric_limits<uint32_t>::max() : (nsub + m_subaddress_lookahead_minor - 1); |
| 1611 | if (index.minor > last_minor) |
| 1612 | return false; |
| 1613 | return true; |
| 1614 | } |
| 1615 | //---------------------------------------------------------------------------------------------------- |
| 1616 | void wallet2::expand_subaddresses(const cryptonote::subaddress_index& index) |
| 1617 | { |
| 1618 | // check if index will overflow container (usually only applicable on 32-bit systems) |
| 1619 | if constexpr (sizeof(std::size_t) <= sizeof(std::uint32_t)) |
| 1620 | { |
| 1621 | static constexpr std::uint32_t max_idx = static_cast<std::uint32_t>(std::numeric_limits<std::size_t>::max()); |
| 1622 | const bool cannot_label_index = index.major == max_idx || index.minor == max_idx; |
| 1623 | THROW_WALLET_EXCEPTION_IF(cannot_label_index, error::wallet_internal_error, "subaddress index out of range"); |
| 1624 | } |
| 1625 | |
| 1626 | // resize subaddress labels just big enough that `m_subaddress_labels[index.major][index.minor]` is present |
| 1627 | if (m_subaddress_labels.size() <= index.major) |
| 1628 | m_subaddress_labels.resize(index.major + 1, {"Untitled account"}); |
| 1629 | auto &subaddr_labels_in_account = m_subaddress_labels[index.major]; |
| 1630 | if (subaddr_labels_in_account.size() <= index.minor) |
| 1631 | subaddr_labels_in_account.resize(index.minor + 1); |
| 1632 | get_account_tags(); //trigger m_account_tags integrity checks |
| 1633 | |
| 1634 | // compile all indices present in subaddress scanning map, as well as every major index |
| 1635 | std::unordered_set<cryptonote::subaddress_index> all_indices; |
| 1636 | std::unordered_map<std::uint32_t, std::uint32_t> lowest_missing_minor; |
| 1637 | for (const auto &p : m_subaddresses) |
| 1638 | { |
| 1639 | all_indices.insert(p.second); |
| 1640 | lowest_missing_minor[p.second.major]; |
| 1641 | } |
| 1642 | |
| 1643 | // find lowest "missing" minor index in map, for all major indices |
| 1644 | // this is an optimization which allows us to skip re-generating pubkeys that we already have |
| 1645 | for (auto &p : lowest_missing_minor) |
| 1646 | { |
| 1647 | const std::uint32_t major = p.first; |
| 1648 | std::uint32_t &minor = p.second; |
| 1649 | while (all_indices.count({major, minor}) && minor < std::numeric_limits<std::uint32_t>::max()) |
| 1650 | ++minor; |
| 1651 | } |
| 1652 | |
| 1653 | // resize subaddress scanning map to highest historical received subaddress index plus lookahead |
| 1654 | hw::device &hwdev = m_account.get_device(); |
| 1655 | const std::uint32_t major_base = std::max<std::uint32_t>(m_subaddress_labels.size(), 1) - 1; |
| 1656 | const std::uint32_t major_end = get_subaddress_clamped_sum(major_base, m_subaddress_lookahead_major); |
| 1657 | for (std::uint32_t major = 0; major < major_end; ++major) |
| 1658 | { |
| 1659 | const std::size_t n_minor_labels = (major < m_subaddress_labels.size()) ? m_subaddress_labels.at(major).size() : 0; |
| 1660 | const std::uint32_t minor_base = std::max<std::uint32_t>(n_minor_labels, 1) - 1; |
| 1661 | const std::uint32_t minor_end = get_subaddress_clamped_sum(minor_base, m_subaddress_lookahead_minor); |
| 1662 | const std::uint32_t minor_begin = lowest_missing_minor.count(major) ? lowest_missing_minor.at(major) : 0; |
| 1663 | if (minor_begin >= minor_end) |
| 1664 | continue; |
| 1665 | const std::vector<crypto::public_key> pkeys |
| 1666 | = hwdev.get_subaddress_spend_public_keys(m_account.get_keys(), major, minor_begin, minor_end); |
| 1667 | for (std::uint32_t minor = minor_begin; minor < minor_end; ++minor) |
| 1668 | { |
| 1669 | const crypto::public_key &D = pkeys.at(minor - minor_begin); |
| 1670 | m_subaddresses[D] = {major, minor}; |
| 1671 | } |
| 1672 | } |
| 1673 | } |
| 1674 | //---------------------------------------------------------------------------------------------------- |
| 1675 | void wallet2::create_one_off_subaddress(const cryptonote::subaddress_index& index) |
| 1676 | { |
| 1677 | const crypto::public_key pkey = get_subaddress_spend_public_key(index); |
| 1678 | m_subaddresses[pkey] = index; |
| 1679 | } |
| 1680 | //---------------------------------------------------------------------------------------------------- |
| 1681 | std::string wallet2::get_subaddress_label(const cryptonote::subaddress_index& index) const |
| 1682 | { |
| 1683 | if (index.major >= m_subaddress_labels.size() || index.minor >= m_subaddress_labels[index.major].size()) |
| 1684 | { |
| 1685 | MERROR("Subaddress label doesn't exist"); |
| 1686 | return ""; |
| 1687 | } |
| 1688 | return m_subaddress_labels[index.major][index.minor]; |
| 1689 | } |
| 1690 | //---------------------------------------------------------------------------------------------------- |
| 1691 | wallet2::tx_entry_data wallet2::get_tx_entries(const std::unordered_set<crypto::hash> &txids) |
| 1692 | { |
| 1693 | tx_entry_data tx_entries; |
| 1694 | tx_entries.tx_entries.reserve(txids.size()); |
| 1695 | |
| 1696 | const size_t SLICE_SIZE = 100; // RESTRICTED_TRANSACTIONS_COUNT as defined in rpc/core_rpc_server.cpp, hardcoded in daemon code |
| 1697 | std::unordered_set<crypto::hash>::const_iterator it = txids.begin(); |
| 1698 | for(size_t slice = 0; slice < txids.size(); slice += SLICE_SIZE) { |
| 1699 | cryptonote::COMMAND_RPC_GET_TRANSACTIONS::request req = AUTO_VAL_INIT(req); |
| 1700 | cryptonote::COMMAND_RPC_GET_TRANSACTIONS::response res = AUTO_VAL_INIT(res); |
| 1701 | req.decode_as_json = false; |
| 1702 | req.prune = true; |
| 1703 | |
| 1704 | size_t ntxes = slice + SLICE_SIZE > txids.size() ? txids.size() - slice : SLICE_SIZE; |
| 1705 | for (size_t i = slice; i < slice + ntxes; ++i) |
| 1706 | { |
| 1707 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(*it)); |
| 1708 | ++it; |
| 1709 | } |
| 1710 | |
| 1711 | { |
| 1712 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 1713 | req.client = get_client_signature(); |
| 1714 | bool r = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client, rpc_timeout); |
| 1715 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 1716 | THROW_WALLET_EXCEPTION_IF(res.txs.size() != req.txs_hashes.size(), error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 1717 | } |
| 1718 | |
| 1719 | for (auto& tx_info : res.txs) |
| 1720 | { |
| 1721 | if (!tx_info.in_pool) |
| 1722 | { |
| 1723 | tx_entries.lowest_height = std::min(tx_info.block_height, tx_entries.lowest_height); |
| 1724 | tx_entries.highest_height = std::max(tx_info.block_height, tx_entries.highest_height); |
| 1725 | } |
| 1726 | |
| 1727 | cryptonote::transaction tx; |
| 1728 | crypto::hash tx_hash; |
| 1729 | THROW_WALLET_EXCEPTION_IF(!get_pruned_tx(tx_info, tx, tx_hash), error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 1730 | tx_entries.tx_entries.emplace_back(process_tx_entry_t{ std::move(tx_info), std::move(tx), std::move(tx_hash) }); |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | return tx_entries; |
| 1735 | } |
| 1736 | //---------------------------------------------------------------------------------------------------- |
| 1737 | void wallet2::sort_scan_tx_entries(std::vector<process_tx_entry_t> &unsorted_tx_entries) |
| 1738 | { |
| 1739 | // If any txs we're scanning have the same height, then we need to request the |
| 1740 | // blocks those txs are in to see what order they appear in the chain. We |
| 1741 | // need to scan txs in the same order they appear in the chain so that the |
| 1742 | // `m_transfers` container holds entries in a consistently sorted order. |
| 1743 | // This ensures that hot wallets <> cold wallets both maintain the same order |
| 1744 | // of m_transfers, which they rely on when importing/exporting. Same goes |
| 1745 | // for multisig wallets when they synchronize. |
| 1746 | std::set<uint64_t> entry_heights; |
| 1747 | std::set<uint64_t> entry_heights_requested; |
| 1748 | COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::request req; |
| 1749 | COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::response res; |
| 1750 | for (const auto & tx_info : unsorted_tx_entries) |
| 1751 | { |
| 1752 | if (!tx_info.tx_entry.in_pool && !cryptonote::is_coinbase(tx_info.tx)) |
| 1753 | { |
| 1754 | const uint64_t height = tx_info.tx_entry.block_height; |
| 1755 | if (entry_heights.find(height) == entry_heights.end()) |
| 1756 | { |
| 1757 | entry_heights.insert(height); |
| 1758 | } |
| 1759 | else if (entry_heights_requested.find(height) == entry_heights_requested.end()) |
| 1760 | { |
| 1761 | req.heights.push_back(height); |
| 1762 | entry_heights_requested.insert(height); |
| 1763 | } |
| 1764 | } |
| 1765 | } |
| 1766 | |
| 1767 | { |
| 1768 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 1769 | req.client = get_client_signature(); |
| 1770 | bool r = net_utils::invoke_http_bin("/getblocks_by_height.bin", req, res, *m_http_client, rpc_timeout); |
| 1771 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to get blocks by height from daemon"); |
| 1772 | THROW_WALLET_EXCEPTION_IF(res.blocks.size() != req.heights.size(), error::wallet_internal_error, "Failed to get blocks by height from daemon"); |
| 1773 | } |
| 1774 | |
| 1775 | std::unordered_map<uint64_t, cryptonote::block> parsed_blocks; |
| 1776 | for (size_t i = 0; i < res.blocks.size(); ++i) |
| 1777 | { |
| 1778 | const auto &blk = res.blocks[i]; |
| 1779 | cryptonote::block parsed_block; |
| 1780 | THROW_WALLET_EXCEPTION_IF(!cryptonote::parse_and_validate_block_from_blob(blk.block, parsed_block), |
| 1781 | error::wallet_internal_error, "Failed to parse block"); |
| 1782 | parsed_blocks[req.heights[i]] = std::move(parsed_block); |
| 1783 | } |
| 1784 | |
| 1785 | // sort tx_entries in chronologically ascending order; pool txs to the back |
| 1786 | auto cmp_tx_entry = [&](const process_tx_entry_t& l, const process_tx_entry_t& r) |
| 1787 | { |
| 1788 | if (l.tx_entry.in_pool) |
| 1789 | return false; |
| 1790 | else if (r.tx_entry.in_pool) |
| 1791 | return true; |
| 1792 | else if (l.tx_entry.block_height > r.tx_entry.block_height) |
| 1793 | return false; |
| 1794 | else if (l.tx_entry.block_height < r.tx_entry.block_height) |
| 1795 | return true; |
| 1796 | else // l.tx_entry.block_height == r.tx_entry.block_height |
| 1797 | { |
| 1798 | // coinbase tx is the first tx in a block |
| 1799 | if (cryptonote::is_coinbase(r.tx)) |
| 1800 | return false; |
| 1801 | if (cryptonote::is_coinbase(l.tx)) |
| 1802 | return true; |
| 1803 | |
| 1804 | // in case std::sort is comparing elem to itself |
| 1805 | if (l.tx_hash == r.tx_hash) |
| 1806 | return false; |
| 1807 | |
| 1808 | // see which tx hash comes first in the block |
| 1809 | THROW_WALLET_EXCEPTION_IF(parsed_blocks.find(l.tx_entry.block_height) == parsed_blocks.end(), |
| 1810 | error::wallet_internal_error, std::string("Expected block not returned by daemon, ") + |
| 1811 | "left tx: " + string_tools::pod_to_hex(l.tx_hash) + ", right tx: " + string_tools::pod_to_hex(r.tx_hash)); |
| 1812 | const auto &blk = parsed_blocks[l.tx_entry.block_height]; |
| 1813 | for (const auto &tx_hash : blk.tx_hashes) |
| 1814 | { |
| 1815 | if (tx_hash == r.tx_hash) |
| 1816 | return false; |
| 1817 | if (tx_hash == l.tx_hash) |
| 1818 | return true; |
| 1819 | } |
| 1820 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, "Tx hashes not found in block"); |
| 1821 | return false; |
| 1822 | } |
| 1823 | }; |
| 1824 | std::sort(unsorted_tx_entries.begin(), unsorted_tx_entries.end(), cmp_tx_entry); |
| 1825 | } |
| 1826 | //---------------------------------------------------------------------------------------------------- |
| 1827 | void wallet2::process_scan_txs(const tx_entry_data &txs_to_scan, const tx_entry_data &txs_to_reprocess, const std::unordered_set<crypto::hash> &tx_hashes_to_reprocess, detached_blockchain_data &dbd) |
| 1828 | { |
| 1829 | LOG_PRINT_L0("Processing " << txs_to_scan.tx_entries.size() << " txs, re-processing " |
| 1830 | << txs_to_reprocess.tx_entries.size() << " txs"); |
| 1831 | |
| 1832 | // Sort the txs in chronologically ascending order they appear in the chain |
| 1833 | std::vector<process_tx_entry_t> process_txs; |
| 1834 | process_txs.reserve(txs_to_scan.tx_entries.size() + txs_to_reprocess.tx_entries.size()); |
| 1835 | process_txs.insert(process_txs.end(), txs_to_scan.tx_entries.begin(), txs_to_scan.tx_entries.end()); |
| 1836 | process_txs.insert(process_txs.end(), txs_to_reprocess.tx_entries.begin(), txs_to_reprocess.tx_entries.end()); |
| 1837 | sort_scan_tx_entries(process_txs); |
| 1838 | |
| 1839 | for (const auto &tx_info : process_txs) |
| 1840 | { |
| 1841 | const auto &tx_entry = tx_info.tx_entry; |
| 1842 | |
| 1843 | // Ignore callbacks when re-processing a tx to avoid confusing feedback to user |
| 1844 | bool ignore_callbacks = tx_hashes_to_reprocess.find(tx_info.tx_hash) != tx_hashes_to_reprocess.end(); |
| 1845 | process_new_transaction( |
| 1846 | tx_info.tx_hash, |
| 1847 | tx_info.tx, |
| 1848 | tx_entry.output_indices, |
| 1849 | tx_entry.block_height, |
| 1850 | 0, |
| 1851 | tx_entry.block_timestamp, |
| 1852 | cryptonote::is_coinbase(tx_info.tx), |
| 1853 | tx_entry.in_pool, |
| 1854 | tx_entry.double_spend_seen, |
| 1855 | {}, {}, // unused caches |
| 1856 | ignore_callbacks); |
| 1857 | |
| 1858 | // Re-set destination addresses if they were previously set |
| 1859 | if (m_confirmed_txs.find(tx_info.tx_hash) != m_confirmed_txs.end() && |
| 1860 | dbd.detached_confirmed_txs_dests.find(tx_info.tx_hash) != dbd.detached_confirmed_txs_dests.end()) |
| 1861 | { |
| 1862 | m_confirmed_txs[tx_info.tx_hash].m_dests = std::move(dbd.detached_confirmed_txs_dests[tx_info.tx_hash]); |
| 1863 | } |
| 1864 | } |
| 1865 | |
| 1866 | LOG_PRINT_L0("Done processing " << txs_to_scan.tx_entries.size() << " txs and re-processing " |
| 1867 | << txs_to_reprocess.tx_entries.size() << " txs"); |
| 1868 | } |
| 1869 | //---------------------------------------------------------------------------------------------------- |
| 1870 | void reattach_blockchain(hashchain &blockchain, wallet2::detached_blockchain_data &dbd) |
| 1871 | { |
| 1872 | if (!dbd.detached_blockchain.empty()) |
| 1873 | { |
| 1874 | LOG_PRINT_L0("Re-attaching " << dbd.detached_blockchain.size() << " blocks"); |
| 1875 | for (size_t i = 0; i < dbd.detached_blockchain.size(); ++i) |
| 1876 | blockchain.push_back(dbd.detached_blockchain[i]); |
| 1877 | } |
| 1878 | |
| 1879 | THROW_WALLET_EXCEPTION_IF(blockchain.size() != dbd.original_chain_size, |
| 1880 | error::wallet_internal_error, "Unexpected blockchain size after re-attaching"); |
| 1881 | } |
| 1882 | //---------------------------------------------------------------------------------------------------- |
| 1883 | bool has_nonrequested_tx_at_height_or_above_requested(uint64_t height, const std::unordered_set<crypto::hash> &requested_txids, const wallet2::transfer_container &transfers, |
| 1884 | const wallet2::payment_container &payments, const serializable_unordered_map<crypto::hash, wallet2::confirmed_transfer_details> &confirmed_txs) |
| 1885 | { |
| 1886 | for (const auto &td : transfers) |
| 1887 | if (td.m_block_height >= height && requested_txids.find(td.m_txid) == requested_txids.end()) |
| 1888 | return true; |
| 1889 | |
| 1890 | for (const auto &pmt : payments) |
| 1891 | if (pmt.second.m_block_height >= height && requested_txids.find(pmt.second.m_tx_hash) == requested_txids.end()) |
| 1892 | return true; |
| 1893 | |
| 1894 | for (const auto &ct : confirmed_txs) |
| 1895 | if (ct.second.m_block_height >= height && requested_txids.find(ct.first) == requested_txids.end()) |
| 1896 | return true; |
| 1897 | |
| 1898 | return false; |
| 1899 | } |
| 1900 | //---------------------------------------------------------------------------------------------------- |
| 1901 | void wallet2::scan_tx(const std::unordered_set<crypto::hash> &txids) |
| 1902 | { |
| 1903 | THROW_WALLET_EXCEPTION_IF(m_background_syncing || m_is_background_wallet, error::wallet_internal_error, |
| 1904 | "cannot scan tx from background wallet"); |
| 1905 | |
| 1906 | // Get the transactions from daemon in batches sorted lowest height to highest |
| 1907 | tx_entry_data txs_to_scan = get_tx_entries(txids); |
| 1908 | if (txs_to_scan.tx_entries.empty()) |
| 1909 | return; |
| 1910 | |
| 1911 | // Re-process wallet's txs >= lowest scan_tx height. Re-processing ensures |
| 1912 | // process_new_transaction is called with txs in chronological order. Say that |
| 1913 | // tx2 spends an output from tx1, and the user calls scan_tx(tx1) *after* tx2 |
| 1914 | // has already been scanned. In this case, we will "re-process" tx2 *after* |
| 1915 | // processing tx1 to ensure the wallet picks up that tx2 spends the output |
| 1916 | // from tx1, and to ensure transfers are placed in the sorted transfers |
| 1917 | // container in chronological order. Note: in the above example, if tx2 is |
| 1918 | // a sweep to a different wallet's address, the wallet will not be able to |
| 1919 | // detect tx2. The wallet would need to scan tx1 first in that case. |
| 1920 | // TODO: handle this sweep case |
| 1921 | detached_blockchain_data dbd; |
| 1922 | dbd.original_chain_size = m_blockchain.size(); |
| 1923 | if (m_blockchain.size() > txs_to_scan.lowest_height) |
| 1924 | { |
| 1925 | // When connected to an untrusted daemon, if we will need to re-process 1+ |
| 1926 | // tx that the user did not request to scan, then we fail out because |
| 1927 | // re-requesting those unexpected txs from the daemon poses a more severe |
| 1928 | // and unintuitive privacy risk to the user |
| 1929 | THROW_WALLET_EXCEPTION_IF(!is_trusted_daemon() && |
| 1930 | has_nonrequested_tx_at_height_or_above_requested(txs_to_scan.lowest_height, txids, m_transfers, m_payments, m_confirmed_txs), |
| 1931 | error::wont_reprocess_recent_txs_via_untrusted_daemon |
| 1932 | ); |
| 1933 | |
| 1934 | LOG_PRINT_L0("Re-processing wallet's existing txs (if any) starting from height " << txs_to_scan.lowest_height); |
| 1935 | dbd = detach_blockchain(txs_to_scan.lowest_height); |
| 1936 | } |
| 1937 | std::unordered_set<crypto::hash> tx_hashes_to_reprocess; |
| 1938 | tx_hashes_to_reprocess.reserve(dbd.detached_tx_hashes.size()); |
| 1939 | for (const auto &tx_hash : dbd.detached_tx_hashes) |
| 1940 | { |
| 1941 | if (txids.find(tx_hash) == txids.end()) |
| 1942 | tx_hashes_to_reprocess.insert(tx_hash); |
| 1943 | } |
| 1944 | // re-request txs from daemon to re-process with all tx data needed |
| 1945 | tx_entry_data txs_to_reprocess = get_tx_entries(tx_hashes_to_reprocess); |
| 1946 | |
| 1947 | process_scan_txs(txs_to_scan, txs_to_reprocess, tx_hashes_to_reprocess, dbd); |
| 1948 | reattach_blockchain(m_blockchain, dbd); |
| 1949 | |
| 1950 | // If the highest scan_tx height exceeds the wallet's known scan height, then |
| 1951 | // the wallet should skip ahead to the scan_tx's height in order to service |
| 1952 | // the request in a timely manner. Skipping unrequested transactions avoids |
| 1953 | // generating sequences of calls to process_new_transaction which process |
| 1954 | // transactions out-of-order, relative to their order in the blockchain, as |
| 1955 | // the process_new_transaction implementation requires transactions to be |
| 1956 | // processed in blockchain order. If a user misses a tx, they should either |
| 1957 | // use rescan_bc, or manually scan missed txs with scan_tx. |
| 1958 | uint64_t skip_to_height = txs_to_scan.highest_height + 1; |
| 1959 | if (skip_to_height > m_blockchain.size()) |
| 1960 | { |
| 1961 | m_skip_to_height = skip_to_height; |
| 1962 | LOG_PRINT_L0("Skipping refresh to height " << skip_to_height); |
| 1963 | |
| 1964 | // update last block reward here because the refresh loop won't necessarily set it |
| 1965 | try |
| 1966 | { |
| 1967 | cryptonote::block_header_response block_header; |
| 1968 | if (m_node_rpc_proxy.get_block_header_by_height(txs_to_scan.highest_height, block_header)) |
| 1969 | throw std::runtime_error("Failed to request block header by height"); |
| 1970 | m_last_block_reward = block_header.reward; |
| 1971 | } |
| 1972 | catch (...) { MERROR("Failed getting block header at height " << txs_to_scan.highest_height); } |
| 1973 | |
| 1974 | // TODO: use fast_refresh instead of refresh to update m_blockchain. It needs refactoring to work correctly here. |
| 1975 | // Or don't refresh at all, and let it update on the next refresh loop. |
| 1976 | refresh(is_trusted_daemon()); |
| 1977 | } |
| 1978 | } |
| 1979 | //---------------------------------------------------------------------------------------------------- |
| 1980 | void wallet2::set_subaddress_label(const cryptonote::subaddress_index& index, const std::string &label) |
| 1981 | { |
| 1982 | THROW_WALLET_EXCEPTION_IF(index.major >= m_subaddress_labels.size(), error::account_index_outofbound); |
| 1983 | THROW_WALLET_EXCEPTION_IF(index.minor >= m_subaddress_labels[index.major].size(), error::address_index_outofbound); |
| 1984 | m_subaddress_labels[index.major][index.minor] = label; |
| 1985 | } |
| 1986 | //---------------------------------------------------------------------------------------------------- |
| 1987 | void wallet2::set_subaddress_lookahead(size_t major, size_t minor) |
| 1988 | { |
| 1989 | THROW_WALLET_EXCEPTION_IF(major == 0, error::wallet_internal_error, "Subaddress major lookahead may not be zero"); |
| 1990 | THROW_WALLET_EXCEPTION_IF(major > 0xffffffff, error::wallet_internal_error, "Subaddress major lookahead is too large"); |
| 1991 | THROW_WALLET_EXCEPTION_IF(minor == 0, error::wallet_internal_error, "Subaddress minor lookahead may not be zero"); |
| 1992 | THROW_WALLET_EXCEPTION_IF(minor > 0xffffffff, error::wallet_internal_error, "Subaddress minor lookahead is too large"); |
| 1993 | |
| 1994 | const uint32_t old_major_lookahead = m_subaddress_lookahead_major; |
| 1995 | const uint32_t old_minor_lookahead = m_subaddress_lookahead_minor; |
| 1996 | |
| 1997 | m_subaddress_lookahead_major = major; |
| 1998 | m_subaddress_lookahead_minor = minor; |
| 1999 | |
| 2000 | if (old_major_lookahead >= major && old_minor_lookahead >= minor) |
| 2001 | return; |
| 2002 | |
| 2003 | expand_subaddresses({0, 0}); |
| 2004 | } |
| 2005 | //---------------------------------------------------------------------------------------------------- |
| 2006 | /*! |
| 2007 | * \brief Tells if the wallet file is deprecated. |
| 2008 | */ |
| 2009 | bool wallet2::is_deprecated() const |
| 2010 | { |
| 2011 | return is_old_file_format; |
| 2012 | } |
| 2013 | //---------------------------------------------------------------------------------------------------- |
| 2014 | void wallet2::set_spent(size_t idx, uint64_t height) |
| 2015 | { |
| 2016 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); |
| 2017 | transfer_details &td = m_transfers[idx]; |
| 2018 | LOG_PRINT_L2("Setting SPENT at " << height << ": ki " << td.m_key_image << ", amount " << print_money(td.m_amount)); |
| 2019 | td.m_spent = true; |
| 2020 | td.m_spent_height = height; |
| 2021 | } |
| 2022 | //---------------------------------------------------------------------------------------------------- |
| 2023 | void wallet2::set_unspent(size_t idx) |
| 2024 | { |
| 2025 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); |
| 2026 | transfer_details &td = m_transfers[idx]; |
| 2027 | LOG_PRINT_L2("Setting UNSPENT: ki " << td.m_key_image << ", amount " << print_money(td.m_amount)); |
| 2028 | td.m_spent = false; |
| 2029 | td.m_spent_height = 0; |
| 2030 | } |
| 2031 | //---------------------------------------------------------------------------------------------------- |
| 2032 | bool wallet2::is_spent(const transfer_details &td, bool strict) const |
| 2033 | { |
| 2034 | if (strict) |
| 2035 | { |
| 2036 | return td.m_spent && td.m_spent_height > 0; |
| 2037 | } |
| 2038 | else |
| 2039 | { |
| 2040 | return td.m_spent; |
| 2041 | } |
| 2042 | } |
| 2043 | //---------------------------------------------------------------------------------------------------- |
| 2044 | bool wallet2::is_spent(size_t idx, bool strict) const |
| 2045 | { |
| 2046 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid index"); |
| 2047 | const transfer_details &td = m_transfers[idx]; |
| 2048 | return is_spent(td, strict); |
| 2049 | } |
| 2050 | //---------------------------------------------------------------------------------------------------- |
| 2051 | void wallet2::freeze(size_t idx) |
| 2052 | { |
| 2053 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid transfer_details index"); |
| 2054 | transfer_details &td = m_transfers[idx]; |
| 2055 | td.m_frozen = true; |
| 2056 | } |
| 2057 | //---------------------------------------------------------------------------------------------------- |
| 2058 | void wallet2::thaw(size_t idx) |
| 2059 | { |
| 2060 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid transfer_details index"); |
| 2061 | transfer_details &td = m_transfers[idx]; |
| 2062 | td.m_frozen = false; |
| 2063 | } |
| 2064 | //---------------------------------------------------------------------------------------------------- |
| 2065 | bool wallet2::frozen(size_t idx) const |
| 2066 | { |
| 2067 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "Invalid transfer_details index"); |
| 2068 | const transfer_details &td = m_transfers[idx]; |
| 2069 | return td.m_frozen; |
| 2070 | } |
| 2071 | //---------------------------------------------------------------------------------------------------- |
| 2072 | bool wallet2::frozen(const multisig_tx_set& txs) const |
| 2073 | { |
| 2074 | // Each call to frozen(const key_image&) is O(N), so if we didn't use batching like we did here, |
| 2075 | // this op would be O(M * N) instead of O(M + N). N = # wallet transfers, M = # key images in set. |
| 2076 | // Step 1. Collect all key images from all pending txs into set |
| 2077 | std::unordered_set<crypto::key_image> kis_to_sign; |
| 2078 | for (const auto& ptx : txs.m_ptx) |
| 2079 | { |
| 2080 | const tools::wallet2::tx_construction_data& cd = ptx.construction_data; |
| 2081 | CHECK_AND_ASSERT_THROW_MES(cd.sources.size() == ptx.tx.vin.size(), "mismatched multisg tx set source sizes"); |
| 2082 | for (size_t src_idx = 0; src_idx < cd.sources.size(); ++src_idx) |
| 2083 | { |
| 2084 | // Extract keys images from tx vin and construction data |
| 2085 | const crypto::key_image multisig_ki = rct::rct2ki(cd.sources[src_idx].multisig_kLRki.ki); |
| 2086 | CHECK_AND_ASSERT_THROW_MES(ptx.tx.vin[src_idx].type() == typeid(cryptonote::txin_to_key), "multisig tx cannot be miner"); |
| 2087 | const crypto::key_image& vin_ki = boost::get<cryptonote::txin_to_key>(ptx.tx.vin[src_idx]).k_image; |
| 2088 | |
| 2089 | // Add key images to set (there will be some overlap) |
| 2090 | kis_to_sign.insert(multisig_ki); |
| 2091 | kis_to_sign.insert(vin_ki); |
| 2092 | } |
| 2093 | } |
| 2094 | // Step 2. Scan all transfers for frozen key images |
| 2095 | for (const auto& td : m_transfers) |
| 2096 | if (td.m_frozen && kis_to_sign.count(td.m_key_image)) |
| 2097 | return true; |
| 2098 | |
| 2099 | return false; |
| 2100 | } |
| 2101 | //---------------------------------------------------------------------------------------------------- |
| 2102 | void wallet2::freeze(const crypto::key_image &ki) |
| 2103 | { |
| 2104 | freeze(get_transfer_details(ki)); |
| 2105 | } |
| 2106 | //---------------------------------------------------------------------------------------------------- |
| 2107 | void wallet2::thaw(const crypto::key_image &ki) |
| 2108 | { |
| 2109 | thaw(get_transfer_details(ki)); |
| 2110 | } |
| 2111 | //---------------------------------------------------------------------------------------------------- |
| 2112 | bool wallet2::frozen(const crypto::key_image &ki) const |
| 2113 | { |
| 2114 | return frozen(get_transfer_details(ki)); |
| 2115 | } |
| 2116 | //---------------------------------------------------------------------------------------------------- |
| 2117 | size_t wallet2::get_transfer_details(const crypto::key_image &ki) const |
| 2118 | { |
| 2119 | for (size_t idx = 0; idx < m_transfers.size(); ++idx) |
| 2120 | { |
| 2121 | const transfer_details &td = m_transfers[idx]; |
| 2122 | if (td.m_key_image == ki) |
| 2123 | { |
| 2124 | if (td.m_key_image_known) |
| 2125 | return idx; |
| 2126 | else if (td.m_key_image_partial) |
| 2127 | CHECK_AND_ASSERT_THROW_MES(false, "Transfer detail lookups are not allowed for multisig partial key images"); |
| 2128 | } |
| 2129 | } |
| 2130 | CHECK_AND_ASSERT_THROW_MES(false, "Key image not found"); |
| 2131 | } |
| 2132 | //---------------------------------------------------------------------------------------------------- |
| 2133 | bool wallet2::frozen(const transfer_details &td) const |
| 2134 | { |
| 2135 | return td.m_frozen; |
| 2136 | } |
| 2137 | //---------------------------------------------------------------------------------------------------- |
| 2138 | void wallet2::check_acc_out_precomp(const tx_out &o, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, size_t i, tx_scan_info_t &tx_scan_info) const |
| 2139 | { |
| 2140 | hw::device &hwdev = m_account.get_device(); |
| 2141 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 2142 | hwdev.set_mode(hw::device::TRANSACTION_PARSE); |
| 2143 | crypto::public_key output_public_key; |
| 2144 | if (!get_output_public_key(o, output_public_key)) |
| 2145 | { |
| 2146 | tx_scan_info.error = true; |
| 2147 | LOG_ERROR("wrong type id in transaction out"); |
| 2148 | return; |
| 2149 | } |
| 2150 | tx_scan_info.received = is_out_to_acc_precomp(m_subaddresses, output_public_key, derivation, additional_derivations, i, hwdev, get_output_view_tag(o)); |
| 2151 | if(tx_scan_info.received) |
| 2152 | { |
| 2153 | tx_scan_info.money_transfered = o.amount; // may be 0 for ringct outputs |
| 2154 | } |
| 2155 | else |
| 2156 | { |
| 2157 | tx_scan_info.money_transfered = 0; |
| 2158 | } |
| 2159 | tx_scan_info.error = false; |
| 2160 | } |
| 2161 | //---------------------------------------------------------------------------------------------------- |
| 2162 | void wallet2::check_acc_out_precomp(const tx_out &o, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, size_t i, const is_out_data *is_out_data, tx_scan_info_t &tx_scan_info) const |
| 2163 | { |
| 2164 | if (!is_out_data || i >= is_out_data->received.size()) |
| 2165 | return check_acc_out_precomp(o, derivation, additional_derivations, i, tx_scan_info); |
| 2166 | |
| 2167 | tx_scan_info.received = is_out_data->received[i]; |
| 2168 | if(tx_scan_info.received) |
| 2169 | { |
| 2170 | tx_scan_info.money_transfered = o.amount; // may be 0 for ringct outputs |
| 2171 | } |
| 2172 | else |
| 2173 | { |
| 2174 | tx_scan_info.money_transfered = 0; |
| 2175 | } |
| 2176 | tx_scan_info.error = false; |
| 2177 | } |
| 2178 | //---------------------------------------------------------------------------------------------------- |
| 2179 | void wallet2::check_acc_out_precomp_once(const tx_out &o, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, size_t i, const is_out_data *is_out_data, tx_scan_info_t &tx_scan_info, bool &already_seen) const |
| 2180 | { |
| 2181 | tx_scan_info.received = boost::none; |
| 2182 | if (already_seen) |
| 2183 | return; |
| 2184 | check_acc_out_precomp(o, derivation, additional_derivations, i, is_out_data, tx_scan_info); |
| 2185 | if (tx_scan_info.received) |
| 2186 | already_seen = true; |
| 2187 | } |
| 2188 | //---------------------------------------------------------------------------------------------------- |
| 2189 | static uint64_t decodeRct(const rct::rctSig & rv, const crypto::key_derivation &derivation, unsigned int i, rct::key & mask, hw::device &hwdev) |
| 2190 | { |
| 2191 | crypto::secret_key scalar1; |
| 2192 | hwdev.derivation_to_scalar(derivation, i, scalar1); |
| 2193 | try |
| 2194 | { |
| 2195 | switch (rv.type) |
| 2196 | { |
| 2197 | case rct::RCTTypeSimple: |
| 2198 | case rct::RCTTypeBulletproof: |
| 2199 | case rct::RCTTypeBulletproof2: |
| 2200 | case rct::RCTTypeCLSAG: |
| 2201 | case rct::RCTTypeBulletproofPlus: |
| 2202 | return rct::decodeRctSimple(rv, rct::sk2rct(scalar1), i, mask, hwdev); |
| 2203 | case rct::RCTTypeFull: |
| 2204 | return rct::decodeRct(rv, rct::sk2rct(scalar1), i, mask, hwdev); |
| 2205 | default: |
| 2206 | LOG_ERROR("Unsupported rct type: " << rv.type); |
| 2207 | return 0; |
| 2208 | } |
| 2209 | } |
| 2210 | catch (const std::exception &e) |
| 2211 | { |
| 2212 | LOG_ERROR("Failed to decode input " << i); |
| 2213 | return 0; |
| 2214 | } |
| 2215 | } |
| 2216 | //---------------------------------------------------------------------------------------------------- |
| 2217 | void wallet2::scan_output(const cryptonote::transaction &tx, bool miner_tx, const crypto::public_key &tx_pub_key, size_t i, tx_scan_info_t &tx_scan_info, int &num_vouts_received, std::unordered_map<cryptonote::subaddress_index, uint64_t> &tx_money_got_in_outs, std::vector<size_t> &outs, bool pool) |
| 2218 | { |
| 2219 | THROW_WALLET_EXCEPTION_IF(i >= tx.vout.size(), error::wallet_internal_error, "Invalid vout index"); |
| 2220 | |
| 2221 | // if keys are encrypted, ask for password |
| 2222 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only && m_multisig_rescan_k.empty() && !m_background_syncing) |
| 2223 | { |
| 2224 | static critical_section password_lock; |
| 2225 | CRITICAL_REGION_LOCAL(password_lock); |
| 2226 | if (!m_encrypt_keys_after_refresh && !m_processing_background_cache) |
| 2227 | { |
| 2228 | boost::optional<epee::wipeable_string> pwd = m_callback->on_get_password(pool ? "output found in pool" : "output received"); |
| 2229 | THROW_WALLET_EXCEPTION_IF(!pwd, error::password_needed, tr("Password is needed to compute key image for incoming monero")); |
| 2230 | THROW_WALLET_EXCEPTION_IF(!verify_password(*pwd), error::password_needed, tr("Invalid password: password is needed to compute key image for incoming monero")); |
| 2231 | m_encrypt_keys_after_refresh.reset(new wallet_keys_unlocker(*this, m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only, *pwd)); |
| 2232 | } |
| 2233 | } |
| 2234 | |
| 2235 | crypto::public_key output_public_key; |
| 2236 | THROW_WALLET_EXCEPTION_IF(!get_output_public_key(tx.vout[i], output_public_key), error::wallet_internal_error, "Failed to get output public key"); |
| 2237 | |
| 2238 | if (m_multisig || m_background_syncing/*no spend key*/) |
| 2239 | { |
| 2240 | tx_scan_info.in_ephemeral.pub = output_public_key; |
| 2241 | tx_scan_info.in_ephemeral.sec = crypto::null_skey; |
| 2242 | tx_scan_info.ki = rct::rct2ki(rct::zero()); |
| 2243 | } |
| 2244 | else |
| 2245 | { |
| 2246 | bool r = cryptonote::generate_key_image_helper_precomp(m_account.get_keys(), output_public_key, tx_scan_info.received->derivation, i, tx_scan_info.received->index, tx_scan_info.in_ephemeral, tx_scan_info.ki, m_account.get_device()); |
| 2247 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 2248 | THROW_WALLET_EXCEPTION_IF(tx_scan_info.in_ephemeral.pub != output_public_key, |
| 2249 | error::wallet_internal_error, "key_image generated ephemeral public key not matched with output_key"); |
| 2250 | } |
| 2251 | |
| 2252 | THROW_WALLET_EXCEPTION_IF(std::find(outs.begin(), outs.end(), i) != outs.end(), error::wallet_internal_error, "Same output cannot be added twice"); |
| 2253 | if (tx_scan_info.money_transfered == 0 && !miner_tx) |
| 2254 | { |
| 2255 | tx_scan_info.money_transfered = tools::decodeRct(tx.rct_signatures, tx_scan_info.received->derivation, i, tx_scan_info.mask, m_account.get_device()); |
| 2256 | } |
| 2257 | if (tx_scan_info.money_transfered == 0) |
| 2258 | { |
| 2259 | MERROR("Invalid output amount, skipping"); |
| 2260 | tx_scan_info.error = true; |
| 2261 | return; |
| 2262 | } |
| 2263 | outs.push_back(i); |
| 2264 | THROW_WALLET_EXCEPTION_IF(tx_money_got_in_outs[tx_scan_info.received->index] >= std::numeric_limits<uint64_t>::max() - tx_scan_info.money_transfered, |
| 2265 | error::wallet_internal_error, "Overflow in received amounts"); |
| 2266 | tx_money_got_in_outs[tx_scan_info.received->index] += tx_scan_info.money_transfered; |
| 2267 | tx_scan_info.amount = tx_scan_info.money_transfered; |
| 2268 | ++num_vouts_received; |
| 2269 | } |
| 2270 | //---------------------------------------------------------------------------------------------------- |
| 2271 | void wallet2::cache_tx_data(const cryptonote::transaction& tx, const crypto::hash &txid, tx_cache_data &tx_cache_data) const |
| 2272 | { |
| 2273 | if(!parse_tx_extra(tx.extra, tx_cache_data.tx_extra_fields)) |
| 2274 | { |
| 2275 | // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key |
| 2276 | LOG_PRINT_L0("Transaction extra has unsupported format: " << txid); |
| 2277 | if (tx_cache_data.tx_extra_fields.empty()) |
| 2278 | return; |
| 2279 | } |
| 2280 | |
| 2281 | // Don't try to extract tx public key if tx has no ouputs |
| 2282 | const bool is_miner = tx.vin.size() == 1 && tx.vin[0].type() == typeid(cryptonote::txin_gen); |
| 2283 | if (!is_miner || m_refresh_type != RefreshType::RefreshNoCoinbase) |
| 2284 | { |
| 2285 | const size_t rec_size = (is_miner && m_refresh_type == RefreshType::RefreshOptimizeCoinbase && tx.version < 2) ? 1 : tx.vout.size(); |
| 2286 | if (!tx.vout.empty()) |
| 2287 | { |
| 2288 | // if tx.vout is not empty, we loop through all tx pubkeys |
| 2289 | const std::vector<boost::optional<cryptonote::subaddress_receive_info>> rec(rec_size, boost::none); |
| 2290 | |
| 2291 | tx_extra_pub_key pub_key_field; |
| 2292 | size_t pk_index = 0; |
| 2293 | while (find_tx_extra_field_by_type(tx_cache_data.tx_extra_fields, pub_key_field, pk_index++)) |
| 2294 | tx_cache_data.primary.push_back({pub_key_field.pub_key, {}, rec}); |
| 2295 | |
| 2296 | // additional tx pubkeys and derivations for multi-destination transfers involving one or more subaddresses |
| 2297 | tx_extra_additional_pub_keys additional_tx_pub_keys; |
| 2298 | if (find_tx_extra_field_by_type(tx_cache_data.tx_extra_fields, additional_tx_pub_keys)) |
| 2299 | { |
| 2300 | for (size_t i = 0; i < additional_tx_pub_keys.data.size(); ++i) |
| 2301 | tx_cache_data.additional.push_back({additional_tx_pub_keys.data[i], {}, {}}); |
| 2302 | } |
| 2303 | } |
| 2304 | } |
| 2305 | } |
| 2306 | //---------------------------------------------------------------------------------------------------- |
| 2307 | bool wallet2::spends_one_of_ours(const cryptonote::transaction &tx) const |
| 2308 | { |
| 2309 | for (const auto &in: tx.vin) |
| 2310 | { |
| 2311 | if (in.type() != typeid(cryptonote::txin_to_key)) |
| 2312 | continue; |
| 2313 | const cryptonote::txin_to_key &in_to_key = boost::get<cryptonote::txin_to_key>(in); |
| 2314 | auto it = m_key_images.find(in_to_key.k_image); |
| 2315 | if (it != m_key_images.end()) |
| 2316 | return true; |
| 2317 | } |
| 2318 | return false; |
| 2319 | } |
| 2320 | //---------------------------------------------------------------------------------------------------- |
| 2321 | void wallet2::process_new_transaction(const crypto::hash &txid, const cryptonote::transaction& tx, const std::vector<uint64_t> &o_indices, uint64_t height, uint8_t block_version, uint64_t ts, bool miner_tx, bool pool, bool double_spend_seen, const tx_cache_data &tx_cache_data, std::map<std::pair<uint64_t, uint64_t>, size_t> *output_tracker_cache, bool ignore_callbacks) |
| 2322 | { |
| 2323 | PERF_TIMER(process_new_transaction); |
| 2324 | // In this function, tx (probably) only contains the base information |
| 2325 | // (that is, the prunable stuff may or may not be included) |
| 2326 | if (!miner_tx && !pool) |
| 2327 | process_unconfirmed(txid, tx, height); |
| 2328 | |
| 2329 | // per receiving subaddress index |
| 2330 | std::unordered_map<cryptonote::subaddress_index, uint64_t> tx_money_got_in_outs; |
| 2331 | std::unordered_map<cryptonote::subaddress_index, amounts_container> tx_amounts_individual_outs; |
| 2332 | |
| 2333 | crypto::public_key tx_pub_key = null_pkey; |
| 2334 | bool notify = false; |
| 2335 | |
| 2336 | std::vector<tx_extra_field> local_tx_extra_fields; |
| 2337 | if (tx_cache_data.tx_extra_fields.empty()) |
| 2338 | { |
| 2339 | if(!parse_tx_extra(tx.extra, local_tx_extra_fields)) |
| 2340 | { |
| 2341 | // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key |
| 2342 | LOG_PRINT_L0("Transaction extra has unsupported format: " << txid); |
| 2343 | } |
| 2344 | } |
| 2345 | const std::vector<tx_extra_field> &tx_extra_fields = tx_cache_data.tx_extra_fields.empty() ? local_tx_extra_fields : tx_cache_data.tx_extra_fields; |
| 2346 | |
| 2347 | // Don't try to extract tx public key if tx has no ouputs |
| 2348 | size_t pk_index = 0; |
| 2349 | std::vector<tx_scan_info_t> tx_scan_info(tx.vout.size()); |
| 2350 | std::deque<bool> output_found(tx.vout.size(), false); |
| 2351 | uint64_t total_received_1 = 0; |
| 2352 | while (!tx.vout.empty()) |
| 2353 | { |
| 2354 | std::vector<size_t> outs; |
| 2355 | // if tx.vout is not empty, we loop through all tx pubkeys |
| 2356 | |
| 2357 | tx_extra_pub_key pub_key_field; |
| 2358 | if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index++)) |
| 2359 | { |
| 2360 | if (pk_index > 1) |
| 2361 | break; |
| 2362 | LOG_PRINT_L0("Public key wasn't found in the transaction extra. Skipping transaction " << txid); |
| 2363 | if(!ignore_callbacks && 0 != m_callback) |
| 2364 | m_callback->on_skip_transaction(height, txid, tx); |
| 2365 | break; |
| 2366 | } |
| 2367 | if (!tx_cache_data.primary.empty()) |
| 2368 | { |
| 2369 | THROW_WALLET_EXCEPTION_IF(tx_cache_data.primary.size() < pk_index || pub_key_field.pub_key != tx_cache_data.primary[pk_index - 1].pkey, |
| 2370 | error::wallet_internal_error, "tx_cache_data is out of sync"); |
| 2371 | } |
| 2372 | |
| 2373 | int num_vouts_received = 0; |
| 2374 | tx_pub_key = pub_key_field.pub_key; |
| 2375 | const cryptonote::account_keys& keys = m_account.get_keys(); |
| 2376 | crypto::key_derivation derivation; |
| 2377 | |
| 2378 | std::vector<crypto::key_derivation> additional_derivations; |
| 2379 | tx_extra_additional_pub_keys additional_tx_pub_keys; |
| 2380 | const wallet2::is_out_data *is_out_data_ptr = NULL; |
| 2381 | if (tx_cache_data.primary.empty()) |
| 2382 | { |
| 2383 | hw::device &hwdev = m_account.get_device(); |
| 2384 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 2385 | hw::reset_mode rst(hwdev); |
| 2386 | |
| 2387 | hwdev.set_mode(hw::device::TRANSACTION_PARSE); |
| 2388 | if (!hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation)) |
| 2389 | { |
| 2390 | MWARNING("Failed to generate key derivation from tx pubkey in " << txid << ", skipping"); |
| 2391 | static_assert(sizeof(derivation) == sizeof(rct::key), "Mismatched sizes of key_derivation and rct::key"); |
| 2392 | memcpy(&derivation, rct::identity().bytes, sizeof(derivation)); |
| 2393 | } |
| 2394 | |
| 2395 | if (pk_index == 1) |
| 2396 | { |
| 2397 | // additional tx pubkeys and derivations for multi-destination transfers involving one or more subaddresses |
| 2398 | if (find_tx_extra_field_by_type(tx_extra_fields, additional_tx_pub_keys)) |
| 2399 | { |
| 2400 | for (size_t i = 0; i < additional_tx_pub_keys.data.size(); ++i) |
| 2401 | { |
| 2402 | additional_derivations.push_back({}); |
| 2403 | if (!hwdev.generate_key_derivation(additional_tx_pub_keys.data[i], keys.m_view_secret_key, additional_derivations.back())) |
| 2404 | { |
| 2405 | MWARNING("Failed to generate key derivation from additional tx pubkey in " << txid << ", skipping"); |
| 2406 | memcpy(&additional_derivations.back(), rct::identity().bytes, sizeof(crypto::key_derivation)); |
| 2407 | } |
| 2408 | } |
| 2409 | } |
| 2410 | } |
| 2411 | } |
| 2412 | else |
| 2413 | { |
| 2414 | THROW_WALLET_EXCEPTION_IF(pk_index - 1 >= tx_cache_data.primary.size(), |
| 2415 | error::wallet_internal_error, "pk_index out of range of tx_cache_data"); |
| 2416 | is_out_data_ptr = &tx_cache_data.primary[pk_index - 1]; |
| 2417 | derivation = tx_cache_data.primary[pk_index - 1].derivation; |
| 2418 | if (pk_index == 1) |
| 2419 | { |
| 2420 | for (size_t n = 0; n < tx_cache_data.additional.size(); ++n) |
| 2421 | { |
| 2422 | additional_tx_pub_keys.data.push_back(tx_cache_data.additional[n].pkey); |
| 2423 | additional_derivations.push_back(tx_cache_data.additional[n].derivation); |
| 2424 | } |
| 2425 | } |
| 2426 | } |
| 2427 | |
| 2428 | if (miner_tx && m_refresh_type == RefreshNoCoinbase) |
| 2429 | { |
| 2430 | // assume coinbase isn't for us |
| 2431 | } |
| 2432 | else if (miner_tx && m_refresh_type == RefreshOptimizeCoinbase && tx.version < 2) |
| 2433 | { |
| 2434 | check_acc_out_precomp_once(tx.vout[0], derivation, additional_derivations, 0, is_out_data_ptr, tx_scan_info[0], output_found[0]); |
| 2435 | THROW_WALLET_EXCEPTION_IF(tx_scan_info[0].error, error::acc_outs_lookup_error, tx, tx_pub_key, m_account.get_keys()); |
| 2436 | |
| 2437 | // this assumes that the miner tx pays a single address |
| 2438 | if (tx_scan_info[0].received) |
| 2439 | { |
| 2440 | // process the other outs from that tx |
| 2441 | // the first one was already checked |
| 2442 | for (size_t i = 1; i < tx.vout.size(); ++i) |
| 2443 | { |
| 2444 | check_acc_out_precomp_once(tx.vout[i], derivation, additional_derivations, i, is_out_data_ptr, tx_scan_info[i], output_found[i]); |
| 2445 | } |
| 2446 | // then scan all outputs from 0 |
| 2447 | hw::device &hwdev = m_account.get_device(); |
| 2448 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 2449 | hwdev.set_mode(hw::device::NONE); |
| 2450 | for (size_t i = 0; i < tx.vout.size(); ++i) |
| 2451 | { |
| 2452 | THROW_WALLET_EXCEPTION_IF(tx_scan_info[i].error, error::acc_outs_lookup_error, tx, tx_pub_key, m_account.get_keys()); |
| 2453 | if (tx_scan_info[i].received) |
| 2454 | { |
| 2455 | hwdev.conceal_derivation(tx_scan_info[i].received->derivation, tx_pub_key, additional_tx_pub_keys.data, derivation, additional_derivations); |
| 2456 | scan_output(tx, miner_tx, tx_pub_key, i, tx_scan_info[i], num_vouts_received, tx_money_got_in_outs, outs, pool); |
| 2457 | if (!tx_scan_info[i].error) |
| 2458 | { |
| 2459 | tx_amounts_individual_outs[tx_scan_info[i].received->index].push_back(tx_scan_info[i].money_transfered); |
| 2460 | } |
| 2461 | } |
| 2462 | } |
| 2463 | } |
| 2464 | } |
| 2465 | else |
| 2466 | { |
| 2467 | for (size_t i = 0; i < tx.vout.size(); ++i) |
| 2468 | { |
| 2469 | check_acc_out_precomp_once(tx.vout[i], derivation, additional_derivations, i, is_out_data_ptr, tx_scan_info[i], output_found[i]); |
| 2470 | THROW_WALLET_EXCEPTION_IF(tx_scan_info[i].error, error::acc_outs_lookup_error, tx, tx_pub_key, m_account.get_keys()); |
| 2471 | if (tx_scan_info[i].received) |
| 2472 | { |
| 2473 | hw::device &hwdev = m_account.get_device(); |
| 2474 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 2475 | hwdev.set_mode(hw::device::NONE); |
| 2476 | hwdev.conceal_derivation(tx_scan_info[i].received->derivation, tx_pub_key, additional_tx_pub_keys.data, derivation, additional_derivations); |
| 2477 | scan_output(tx, miner_tx, tx_pub_key, i, tx_scan_info[i], num_vouts_received, tx_money_got_in_outs, outs, pool); |
| 2478 | if (!tx_scan_info[i].error) |
| 2479 | { |
| 2480 | tx_amounts_individual_outs[tx_scan_info[i].received->index].push_back(tx_scan_info[i].money_transfered); |
| 2481 | } |
| 2482 | } |
| 2483 | } |
| 2484 | } |
| 2485 | |
| 2486 | if(!outs.empty() && num_vouts_received > 0) |
| 2487 | { |
| 2488 | //good news - got money! take care about it |
| 2489 | //usually we have only one transfer for user in transaction |
| 2490 | if (!pool) |
| 2491 | { |
| 2492 | THROW_WALLET_EXCEPTION_IF(tx.vout.size() != o_indices.size(), error::wallet_internal_error, |
| 2493 | "transactions outputs size=" + std::to_string(tx.vout.size()) + |
| 2494 | " not match with daemon response size=" + std::to_string(o_indices.size())); |
| 2495 | |
| 2496 | // we're going to re-process this receive when background sync is disabled |
| 2497 | if (m_background_syncing && m_background_sync_data.txs.find(txid) == m_background_sync_data.txs.end()) |
| 2498 | { |
| 2499 | size_t bgs_idx = m_background_sync_data.txs.size(); |
| 2500 | background_synced_tx_t bgs_tx = { |
| 2501 | .index_in_background_sync_data = bgs_idx, |
| 2502 | .tx = tx, |
| 2503 | .output_indices = o_indices, |
| 2504 | .height = height, |
| 2505 | .block_timestamp = ts, |
| 2506 | .double_spend_seen = double_spend_seen |
| 2507 | }; |
| 2508 | LOG_PRINT_L2("Adding received tx " << txid << " to background sync data (idx=" << bgs_idx << ")"); |
| 2509 | m_background_sync_data.txs.insert({txid, std::move(bgs_tx)}); |
| 2510 | } |
| 2511 | } |
| 2512 | |
| 2513 | for(size_t o: outs) |
| 2514 | { |
| 2515 | THROW_WALLET_EXCEPTION_IF(tx.vout.size() <= o, error::wallet_internal_error, "wrong out in transaction: internal index=" + |
| 2516 | std::to_string(o) + ", total_outs=" + std::to_string(tx.vout.size())); |
| 2517 | |
| 2518 | auto kit = m_pub_keys.find(tx_scan_info[o].in_ephemeral.pub); |
| 2519 | THROW_WALLET_EXCEPTION_IF(kit != m_pub_keys.end() && kit->second >= m_transfers.size(), |
| 2520 | error::wallet_internal_error, std::string("Unexpected transfer index from public key: ") |
| 2521 | + "got " + (kit == m_pub_keys.end() ? "<none>" : boost::lexical_cast<std::string>(kit->second)) |
| 2522 | + ", m_transfers.size() is " + boost::lexical_cast<std::string>(m_transfers.size())); |
| 2523 | if (kit == m_pub_keys.end()) |
| 2524 | { |
| 2525 | uint64_t amount = tx.vout[o].amount ? tx.vout[o].amount : tx_scan_info[o].amount; |
| 2526 | if (!pool) |
| 2527 | { |
| 2528 | m_transfers.push_back(transfer_details{}); |
| 2529 | transfer_details& td = m_transfers.back(); |
| 2530 | td.m_block_height = height; |
| 2531 | td.m_internal_output_index = o; |
| 2532 | td.m_global_output_index = o_indices[o]; |
| 2533 | td.m_tx = (const cryptonote::transaction_prefix&)tx; |
| 2534 | td.m_txid = txid; |
| 2535 | td.m_key_image = tx_scan_info[o].ki; |
| 2536 | td.m_key_image_known = !m_watch_only && !m_multisig && !m_background_syncing; |
| 2537 | if (!td.m_key_image_known) |
| 2538 | { |
| 2539 | // we might have cold signed, and have a mapping to key images |
| 2540 | std::unordered_map<crypto::public_key, crypto::key_image>::const_iterator i = m_cold_key_images.find(tx_scan_info[o].in_ephemeral.pub); |
| 2541 | if (i != m_cold_key_images.end()) |
| 2542 | { |
| 2543 | td.m_key_image = i->second; |
| 2544 | td.m_key_image_known = true; |
| 2545 | } |
| 2546 | } |
| 2547 | if (m_watch_only) |
| 2548 | { |
| 2549 | // for view wallets, that flag means "we want to request it" |
| 2550 | td.m_key_image_request = true; |
| 2551 | } |
| 2552 | else |
| 2553 | { |
| 2554 | td.m_key_image_request = false; |
| 2555 | } |
| 2556 | td.m_key_image_partial = m_multisig; |
| 2557 | td.m_amount = amount; |
| 2558 | td.m_pk_index = pk_index - 1; |
| 2559 | td.m_subaddr_index = tx_scan_info[o].received->index; |
| 2560 | if (should_expand(tx_scan_info[o].received->index)) |
| 2561 | expand_subaddresses(tx_scan_info[o].received->index); |
| 2562 | if (tx.vout[o].amount == 0) |
| 2563 | { |
| 2564 | td.m_mask = tx_scan_info[o].mask; |
| 2565 | td.m_rct = true; |
| 2566 | } |
| 2567 | else if (miner_tx && tx.version == 2) |
| 2568 | { |
| 2569 | td.m_mask = rct::identity(); |
| 2570 | td.m_rct = true; |
| 2571 | } |
| 2572 | else |
| 2573 | { |
| 2574 | td.m_mask = rct::identity(); |
| 2575 | td.m_rct = false; |
| 2576 | } |
| 2577 | td.m_frozen = false; |
| 2578 | set_unspent(m_transfers.size()-1); |
| 2579 | if (td.m_key_image_known) |
| 2580 | m_key_images[td.m_key_image] = m_transfers.size()-1; |
| 2581 | m_pub_keys[tx_scan_info[o].in_ephemeral.pub] = m_transfers.size()-1; |
| 2582 | if (output_tracker_cache) |
| 2583 | (*output_tracker_cache)[std::make_pair(tx.vout[o].amount, td.m_global_output_index)] = m_transfers.size() - 1; |
| 2584 | if (m_multisig) |
| 2585 | { |
| 2586 | THROW_WALLET_EXCEPTION_IF(m_multisig_rescan_k.empty() && !m_multisig_rescan_info.empty(), |
| 2587 | error::wallet_internal_error, "NULL m_multisig_rescan_k"); |
| 2588 | if (!m_multisig_rescan_info.empty() && m_multisig_rescan_info.front().size() >= m_transfers.size()) |
| 2589 | update_multisig_rescan_info(m_multisig_rescan_k, m_multisig_rescan_info, m_transfers.size() - 1); |
| 2590 | } |
| 2591 | LOG_PRINT_L0("Received money: " << print_money(td.amount()) << ", with tx: " << txid); |
| 2592 | if (!ignore_callbacks && 0 != m_callback) |
| 2593 | m_callback->on_money_received(height, txid, tx, td.m_amount, 0, td.m_subaddr_index, spends_one_of_ours(tx), td.m_tx.unlock_time); |
| 2594 | } |
| 2595 | total_received_1 += amount; |
| 2596 | notify = true; |
| 2597 | } |
| 2598 | else if (m_transfers[kit->second].m_spent || m_transfers[kit->second].amount() >= tx_scan_info[o].amount) |
| 2599 | { |
| 2600 | LOG_ERROR("Public key " << epee::string_tools::pod_to_hex(kit->first) |
| 2601 | << " from received " << print_money(tx_scan_info[o].amount) << " output already exists with " |
| 2602 | << (m_transfers[kit->second].m_spent ? "spent" : "unspent") << " " |
| 2603 | << print_money(m_transfers[kit->second].amount()) << " in tx " << m_transfers[kit->second].m_txid << ", received output ignored"); |
| 2604 | THROW_WALLET_EXCEPTION_IF(tx_money_got_in_outs[tx_scan_info[o].received->index] < tx_scan_info[o].amount, |
| 2605 | error::wallet_internal_error, "Unexpected values of new and old outputs"); |
| 2606 | tx_money_got_in_outs[tx_scan_info[o].received->index] -= tx_scan_info[o].amount; |
| 2607 | |
| 2608 | amounts_container& tx_amounts_this_out = tx_amounts_individual_outs[tx_scan_info[o].received->index]; // Only for readability on the following lines |
| 2609 | auto amount_iterator = std::find(tx_amounts_this_out.begin(), tx_amounts_this_out.end(), tx_scan_info[o].amount); |
| 2610 | THROW_WALLET_EXCEPTION_IF(amount_iterator == tx_amounts_this_out.end(), |
| 2611 | error::wallet_internal_error, "Unexpected values of new and old outputs"); |
| 2612 | tx_amounts_this_out.erase(amount_iterator); |
| 2613 | } |
| 2614 | else |
| 2615 | { |
| 2616 | LOG_ERROR("Public key " << epee::string_tools::pod_to_hex(kit->first) |
| 2617 | << " from received " << print_money(tx_scan_info[o].amount) << " output already exists with " |
| 2618 | << print_money(m_transfers[kit->second].amount()) << ", replacing with new output"); |
| 2619 | // The new larger output replaced a previous smaller one |
| 2620 | THROW_WALLET_EXCEPTION_IF(tx_money_got_in_outs[tx_scan_info[o].received->index] < tx_scan_info[o].amount, |
| 2621 | error::wallet_internal_error, "Unexpected values of new and old outputs"); |
| 2622 | THROW_WALLET_EXCEPTION_IF(m_transfers[kit->second].amount() > tx_scan_info[o].amount, |
| 2623 | error::wallet_internal_error, "Unexpected values of new and old outputs"); |
| 2624 | tx_money_got_in_outs[tx_scan_info[o].received->index] -= m_transfers[kit->second].amount(); |
| 2625 | |
| 2626 | uint64_t amount = tx.vout[o].amount ? tx.vout[o].amount : tx_scan_info[o].amount; |
| 2627 | uint64_t burnt = m_transfers[kit->second].amount(); |
| 2628 | uint64_t extra_amount = amount - burnt; |
| 2629 | if (!pool) |
| 2630 | { |
| 2631 | transfer_details &td = m_transfers[kit->second]; |
| 2632 | td.m_block_height = height; |
| 2633 | td.m_internal_output_index = o; |
| 2634 | td.m_global_output_index = o_indices[o]; |
| 2635 | td.m_tx = (const cryptonote::transaction_prefix&)tx; |
| 2636 | td.m_txid = txid; |
| 2637 | td.m_amount = amount; |
| 2638 | td.m_pk_index = pk_index - 1; |
| 2639 | td.m_subaddr_index = tx_scan_info[o].received->index; |
| 2640 | if (should_expand(tx_scan_info[o].received->index)) |
| 2641 | expand_subaddresses(tx_scan_info[o].received->index); |
| 2642 | if (tx.vout[o].amount == 0) |
| 2643 | { |
| 2644 | td.m_mask = tx_scan_info[o].mask; |
| 2645 | td.m_rct = true; |
| 2646 | } |
| 2647 | else if (miner_tx && tx.version == 2) |
| 2648 | { |
| 2649 | td.m_mask = rct::identity(); |
| 2650 | td.m_rct = true; |
| 2651 | } |
| 2652 | else |
| 2653 | { |
| 2654 | td.m_mask = rct::identity(); |
| 2655 | td.m_rct = false; |
| 2656 | } |
| 2657 | if (output_tracker_cache) |
| 2658 | (*output_tracker_cache)[std::make_pair(tx.vout[o].amount, td.m_global_output_index)] = kit->second; |
| 2659 | if (m_multisig) |
| 2660 | { |
| 2661 | THROW_WALLET_EXCEPTION_IF(m_multisig_rescan_k.empty() && !m_multisig_rescan_info.empty(), |
| 2662 | error::wallet_internal_error, "NULL m_multisig_rescan_k"); |
| 2663 | if (!m_multisig_rescan_info.empty() && m_multisig_rescan_info.front().size() >= m_transfers.size()) |
| 2664 | update_multisig_rescan_info(m_multisig_rescan_k, m_multisig_rescan_info, m_transfers.size() - 1); |
| 2665 | } |
| 2666 | THROW_WALLET_EXCEPTION_IF(td.get_public_key() != tx_scan_info[o].in_ephemeral.pub, error::wallet_internal_error, "Inconsistent public keys"); |
| 2667 | THROW_WALLET_EXCEPTION_IF(td.m_spent, error::wallet_internal_error, "Inconsistent spent status"); |
| 2668 | |
| 2669 | LOG_PRINT_L0("Received money: " << print_money(td.amount()) << ", with tx: " << txid); |
| 2670 | if (!ignore_callbacks && 0 != m_callback) |
| 2671 | m_callback->on_money_received(height, txid, tx, td.m_amount, burnt, td.m_subaddr_index, spends_one_of_ours(tx), td.m_tx.unlock_time); |
| 2672 | } |
| 2673 | total_received_1 += extra_amount; |
| 2674 | notify = true; |
| 2675 | } |
| 2676 | } |
| 2677 | } |
| 2678 | } |
| 2679 | |
| 2680 | THROW_WALLET_EXCEPTION_IF(tx_money_got_in_outs.size() != tx_amounts_individual_outs.size(), error::wallet_internal_error, "Inconsistent size of output arrays"); |
| 2681 | |
| 2682 | uint64_t tx_money_spent_in_ins = 0; |
| 2683 | // The line below is equivalent to "boost::optional<uint32_t> subaddr_account;", but avoids the GCC warning: ‘*((void*)& subaddr_account +4)’ may be used uninitialized in this function |
| 2684 | // It's a GCC bug with boost::optional, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47679 |
| 2685 | auto subaddr_account ([]()->boost::optional<uint32_t> {return boost::none;}()); |
| 2686 | std::set<uint32_t> subaddr_indices; |
| 2687 | // check all outputs for spending (compare key images) |
| 2688 | for(auto& in: tx.vin) |
| 2689 | { |
| 2690 | if(in.type() != typeid(cryptonote::txin_to_key)) |
| 2691 | continue; |
| 2692 | const cryptonote::txin_to_key &in_to_key = boost::get<cryptonote::txin_to_key>(in); |
| 2693 | auto it = m_key_images.find(in_to_key.k_image); |
| 2694 | if(it != m_key_images.end()) |
| 2695 | { |
| 2696 | transfer_details& td = m_transfers[it->second]; |
| 2697 | uint64_t amount = in_to_key.amount; |
| 2698 | if (amount > 0) |
| 2699 | { |
| 2700 | if(amount != td.amount()) |
| 2701 | { |
| 2702 | MERROR("Inconsistent amount in tx input: got " << print_money(amount) << |
| 2703 | ", expected " << print_money(td.amount())); |
| 2704 | // this means: |
| 2705 | // 1) the same output pub key was used as destination multiple times, |
| 2706 | // 2) the wallet set the highest amount among them to transfer_details::m_amount, and |
| 2707 | // 3) the wallet somehow spent that output with an amount smaller than the above amount, causing inconsistency |
| 2708 | td.m_amount = amount; |
| 2709 | } |
| 2710 | } |
| 2711 | else |
| 2712 | { |
| 2713 | amount = td.amount(); |
| 2714 | } |
| 2715 | tx_money_spent_in_ins += amount; |
| 2716 | if (subaddr_account && *subaddr_account != td.m_subaddr_index.major) |
| 2717 | LOG_ERROR("spent funds are from different subaddress accounts; count of incoming/outgoing payments will be incorrect"); |
| 2718 | subaddr_account = td.m_subaddr_index.major; |
| 2719 | subaddr_indices.insert(td.m_subaddr_index.minor); |
| 2720 | LOG_PRINT_L0("Spent money: " << print_money(amount) << ", with tx: " << txid); |
| 2721 | set_spent(it->second, height); |
| 2722 | if (!pool) |
| 2723 | { |
| 2724 | if (!ignore_callbacks && 0 != m_callback) |
| 2725 | m_callback->on_money_spent(height, txid, tx, amount, tx, td.m_subaddr_index); |
| 2726 | |
| 2727 | if (m_background_syncing && m_background_sync_data.txs.find(txid) == m_background_sync_data.txs.end()) |
| 2728 | { |
| 2729 | size_t bgs_idx = m_background_sync_data.txs.size(); |
| 2730 | background_synced_tx_t bgs_tx = { |
| 2731 | .index_in_background_sync_data = bgs_idx, |
| 2732 | .tx = tx, |
| 2733 | .output_indices = o_indices, |
| 2734 | .height = height, |
| 2735 | .block_timestamp = ts, |
| 2736 | .double_spend_seen = double_spend_seen |
| 2737 | }; |
| 2738 | LOG_PRINT_L2("Adding spent tx " << txid << " to background sync data (idx=" << bgs_idx << ")"); |
| 2739 | m_background_sync_data.txs.insert({txid, std::move(bgs_tx)}); |
| 2740 | } |
| 2741 | } |
| 2742 | } |
| 2743 | |
| 2744 | if (!pool && (m_track_uses || (m_background_syncing && it == m_key_images.end()))) |
| 2745 | { |
| 2746 | PERF_TIMER(track_uses); |
| 2747 | const uint64_t amount = in_to_key.amount; |
| 2748 | std::vector<uint64_t> offsets = cryptonote::relative_output_offsets_to_absolute(in_to_key.key_offsets); |
| 2749 | if (output_tracker_cache) |
| 2750 | { |
| 2751 | for (uint64_t offset: offsets) |
| 2752 | { |
| 2753 | const std::map<std::pair<uint64_t, uint64_t>, size_t>::const_iterator i = output_tracker_cache->find(std::make_pair(amount, offset)); |
| 2754 | if (i != output_tracker_cache->end()) |
| 2755 | { |
| 2756 | size_t idx = i->second; |
| 2757 | THROW_WALLET_EXCEPTION_IF(idx >= m_transfers.size(), error::wallet_internal_error, "Output tracker cache index out of range"); |
| 2758 | |
| 2759 | if (m_track_uses) |
| 2760 | m_transfers[idx].m_uses.push_back(std::make_pair(height, txid)); |
| 2761 | |
| 2762 | // We'll re-process all txs which *might* be spends when we disable |
| 2763 | // background sync and retrieve the spend key. We don't know if an |
| 2764 | // output is a spend in this tx if we don't know its key image. |
| 2765 | if (m_background_syncing && !m_transfers[idx].m_key_image_known && m_background_sync_data.txs.find(txid) == m_background_sync_data.txs.end()) |
| 2766 | { |
| 2767 | size_t bgs_idx = m_background_sync_data.txs.size(); |
| 2768 | background_synced_tx_t bgs_tx = { |
| 2769 | .index_in_background_sync_data = bgs_idx, |
| 2770 | .tx = tx, |
| 2771 | .output_indices = o_indices, |
| 2772 | .height = height, |
| 2773 | .block_timestamp = ts, |
| 2774 | .double_spend_seen = double_spend_seen |
| 2775 | }; |
| 2776 | LOG_PRINT_L2("Adding plausible spent tx " << txid << " to background sync data (idx=" << bgs_idx << ")"); |
| 2777 | m_background_sync_data.txs.insert({txid, std::move(bgs_tx)}); |
| 2778 | } |
| 2779 | } |
| 2780 | } |
| 2781 | } |
| 2782 | else for (transfer_details &td: m_transfers) |
| 2783 | { |
| 2784 | if (amount != in_to_key.amount) |
| 2785 | continue; |
| 2786 | for (uint64_t offset: offsets) |
| 2787 | if (offset == td.m_global_output_index) |
| 2788 | { |
| 2789 | if (m_track_uses) |
| 2790 | td.m_uses.push_back(std::make_pair(height, txid)); |
| 2791 | if (m_background_syncing && !td.m_key_image_known && m_background_sync_data.txs.find(txid) == m_background_sync_data.txs.end()) |
| 2792 | { |
| 2793 | size_t bgs_idx = m_background_sync_data.txs.size(); |
| 2794 | background_synced_tx_t bgs_tx = { |
| 2795 | .index_in_background_sync_data = bgs_idx, |
| 2796 | .tx = tx, |
| 2797 | .output_indices = o_indices, |
| 2798 | .height = height, |
| 2799 | .block_timestamp = ts, |
| 2800 | .double_spend_seen = double_spend_seen |
| 2801 | }; |
| 2802 | LOG_PRINT_L2("Adding plausible spent tx " << txid << " to background sync data (idx=" << bgs_idx << ")"); |
| 2803 | m_background_sync_data.txs.insert({txid, std::move(bgs_tx)}); |
| 2804 | } |
| 2805 | } |
| 2806 | } |
| 2807 | } |
| 2808 | } |
| 2809 | |
| 2810 | uint64_t fee = miner_tx ? 0 : tx.version == 1 ? tx_money_spent_in_ins - get_outs_money_amount(tx) : tx.rct_signatures.txnFee; |
| 2811 | |
| 2812 | if (tx_money_spent_in_ins > 0) |
| 2813 | { |
| 2814 | uint64_t self_received = std::accumulate<decltype(tx_money_got_in_outs.begin()), uint64_t>(tx_money_got_in_outs.begin(), tx_money_got_in_outs.end(), 0, |
| 2815 | [&subaddr_account] (uint64_t acc, const std::pair<cryptonote::subaddress_index, uint64_t>& p) |
| 2816 | { |
| 2817 | return acc + (p.first.major == *subaddr_account ? p.second : 0); |
| 2818 | }); |
| 2819 | if (!pool) |
| 2820 | { |
| 2821 | process_outgoing(txid, tx, height, ts, tx_money_spent_in_ins, self_received, *subaddr_account, subaddr_indices); |
| 2822 | // if sending to yourself at the same subaddress account, set the outgoing payment amount to 0 so that it's less confusing |
| 2823 | if (tx_money_spent_in_ins == self_received + fee) |
| 2824 | { |
| 2825 | auto i = m_confirmed_txs.find(txid); |
| 2826 | THROW_WALLET_EXCEPTION_IF(i == m_confirmed_txs.end(), error::wallet_internal_error, |
| 2827 | "confirmed tx wasn't found: " + string_tools::pod_to_hex(txid)); |
| 2828 | i->second.m_change = self_received; |
| 2829 | } |
| 2830 | } |
| 2831 | else if (!m_unconfirmed_txs.count(txid)) |
| 2832 | { |
| 2833 | // Add to unconfirmed txs if not already there (e.g. restoring wallet, or running the wallet in parallel to the sending wallet w/same seed) |
| 2834 | add_unconfirmed_tx(txid, tx, tx_money_spent_in_ins, {}/*don't know dests*/, crypto::null_hash/*don't know payment_id*/, self_received, *subaddr_account, subaddr_indices); |
| 2835 | auto i = m_unconfirmed_txs.find(txid); |
| 2836 | THROW_WALLET_EXCEPTION_IF(i == m_unconfirmed_txs.end(), error::wallet_internal_error, |
| 2837 | "unconfirmed tx wasn't found: " + string_tools::pod_to_hex(txid)); |
| 2838 | i->second.m_amount_out = get_outgoing_amount(tx, tx_money_spent_in_ins); |
| 2839 | } |
| 2840 | } |
| 2841 | |
| 2842 | // remove change sent to the spending subaddress account from the list of received funds |
| 2843 | uint64_t sub_change = 0; |
| 2844 | for (auto i = tx_money_got_in_outs.begin(); i != tx_money_got_in_outs.end();) |
| 2845 | { |
| 2846 | if (subaddr_account && i->first.major == *subaddr_account) |
| 2847 | { |
| 2848 | sub_change += i->second; |
| 2849 | tx_amounts_individual_outs.erase(i->first); |
| 2850 | i = tx_money_got_in_outs.erase(i); |
| 2851 | } |
| 2852 | else |
| 2853 | ++i; |
| 2854 | } |
| 2855 | |
| 2856 | // create payment_details for each incoming transfer to a subaddress index |
| 2857 | if (tx_money_got_in_outs.size() > 0) |
| 2858 | { |
| 2859 | tx_extra_nonce extra_nonce; |
| 2860 | crypto::hash payment_id = null_hash; |
| 2861 | if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) |
| 2862 | { |
| 2863 | crypto::hash8 payment_id8 = null_hash8; |
| 2864 | if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) |
| 2865 | { |
| 2866 | // We got a payment ID to go with this tx |
| 2867 | LOG_PRINT_L2("Found encrypted payment ID: " << payment_id8); |
| 2868 | MINFO("Consider using subaddresses instead of encrypted payment IDs"); |
| 2869 | if (tx_pub_key != null_pkey) |
| 2870 | { |
| 2871 | if (!m_account.get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_account.get_keys().m_view_secret_key)) |
| 2872 | { |
| 2873 | LOG_PRINT_L0("Failed to decrypt payment ID: " << payment_id8); |
| 2874 | } |
| 2875 | else |
| 2876 | { |
| 2877 | LOG_PRINT_L2("Decrypted payment ID: " << payment_id8); |
| 2878 | // put the 64 bit decrypted payment id in the first 8 bytes |
| 2879 | memcpy(payment_id.data, payment_id8.data, 8); |
| 2880 | // rest is already 0, but guard against code changes above |
| 2881 | memset(payment_id.data + 8, 0, 24); |
| 2882 | } |
| 2883 | } |
| 2884 | else |
| 2885 | { |
| 2886 | LOG_PRINT_L1("No public key found in tx, unable to decrypt payment id"); |
| 2887 | } |
| 2888 | } |
| 2889 | else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) |
| 2890 | { |
| 2891 | bool ignore = block_version >= IGNORE_LONG_PAYMENT_ID_FROM_BLOCK_VERSION; |
| 2892 | if (ignore) |
| 2893 | { |
| 2894 | LOG_PRINT_L2("Found unencrypted payment ID in tx " << txid << " (ignored)"); |
| 2895 | MWARNING("Found OBSOLETE AND IGNORED unencrypted payment ID: these are bad for privacy, use subaddresses instead"); |
| 2896 | payment_id = crypto::null_hash; |
| 2897 | } |
| 2898 | else |
| 2899 | { |
| 2900 | LOG_PRINT_L2("Found unencrypted payment ID: " << payment_id); |
| 2901 | MWARNING("Found unencrypted payment ID: these are bad for privacy, consider using subaddresses instead"); |
| 2902 | } |
| 2903 | } |
| 2904 | } |
| 2905 | |
| 2906 | uint64_t total_received_2 = sub_change; |
| 2907 | for (const auto& i : tx_money_got_in_outs) |
| 2908 | total_received_2 += i.second; |
| 2909 | if (total_received_1 != total_received_2) |
| 2910 | { |
| 2911 | const el::Level level = el::Level::Warning; |
| 2912 | MCLOG_RED(level, "global", "**********************************************************************"); |
| 2913 | MCLOG_RED(level, "global", "Consistency failure in amounts received"); |
| 2914 | MCLOG_RED(level, "global", "Check transaction " << txid); |
| 2915 | MCLOG_RED(level, "global", "**********************************************************************"); |
| 2916 | exit(1); |
| 2917 | return; |
| 2918 | } |
| 2919 | |
| 2920 | bool all_same = true; |
| 2921 | for (const auto& i : tx_money_got_in_outs) |
| 2922 | { |
| 2923 | payment_details payment; |
| 2924 | payment.m_tx_hash = txid; |
| 2925 | payment.m_fee = fee; |
| 2926 | payment.m_amount = i.second; |
| 2927 | payment.m_amounts = tx_amounts_individual_outs[i.first]; |
| 2928 | payment.m_block_height = height; |
| 2929 | payment.m_unlock_time = tx.unlock_time; |
| 2930 | payment.m_timestamp = ts; |
| 2931 | payment.m_coinbase = miner_tx; |
| 2932 | payment.m_subaddr_index = i.first; |
| 2933 | if (pool) { |
| 2934 | if (emplace_or_replace(m_unconfirmed_payments, payment_id, pool_payment_details{payment, double_spend_seen})) |
| 2935 | all_same = false; |
| 2936 | if (0 != m_callback) |
| 2937 | m_callback->on_unconfirmed_money_received(height, txid, tx, payment.m_amount, payment.m_subaddr_index); |
| 2938 | } |
| 2939 | else |
| 2940 | m_payments.emplace(payment_id, payment); |
| 2941 | LOG_PRINT_L2("Payment found in " << (pool ? "pool" : "block") << ": " << payment_id << " / " << payment.m_tx_hash << " / " << payment.m_amount); |
| 2942 | } |
| 2943 | |
| 2944 | // if it's a pool tx and we already had it, don't notify again |
| 2945 | if (pool && all_same) |
| 2946 | notify = false; |
| 2947 | } |
| 2948 | |
| 2949 | if (notify) |
| 2950 | { |
| 2951 | std::shared_ptr<tools::Notify> tx_notify = m_tx_notify; |
| 2952 | if (tx_notify) |
| 2953 | tx_notify->notify("%s", epee::string_tools::pod_to_hex(txid).c_str(), NULL); |
| 2954 | } |
| 2955 | } |
| 2956 | //---------------------------------------------------------------------------------------------------- |
| 2957 | void wallet2::process_unconfirmed(const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t height) |
| 2958 | { |
| 2959 | if (m_unconfirmed_txs.empty()) |
| 2960 | return; |
| 2961 | |
| 2962 | auto unconf_it = m_unconfirmed_txs.find(txid); |
| 2963 | if(unconf_it != m_unconfirmed_txs.end()) { |
| 2964 | if (store_tx_info()) { |
| 2965 | try { |
| 2966 | m_confirmed_txs.insert(std::make_pair(txid, confirmed_transfer_details(unconf_it->second, height))); |
| 2967 | } |
| 2968 | catch (...) { |
| 2969 | // can fail if the tx has unexpected input types |
| 2970 | LOG_PRINT_L0("Failed to add outgoing transaction to confirmed transaction map"); |
| 2971 | } |
| 2972 | } |
| 2973 | m_unconfirmed_txs.erase(unconf_it); |
| 2974 | } |
| 2975 | } |
| 2976 | //---------------------------------------------------------------------------------------------------- |
| 2977 | void wallet2::process_outgoing(const crypto::hash &txid, const cryptonote::transaction &tx, uint64_t height, uint64_t ts, uint64_t spent, uint64_t received, uint32_t subaddr_account, const std::set<uint32_t>& subaddr_indices) |
| 2978 | { |
| 2979 | std::pair<std::unordered_map<crypto::hash, confirmed_transfer_details>::iterator, bool> entry = m_confirmed_txs.insert(std::make_pair(txid, confirmed_transfer_details())); |
| 2980 | // fill with the info we know, some info might already be there |
| 2981 | if (entry.second) |
| 2982 | { |
| 2983 | // this case will happen if the tx is from our outputs, but was sent by another |
| 2984 | // wallet (eg, we're a cold wallet and the hot wallet sent it). For RCT transactions, |
| 2985 | // we only see 0 input amounts, so have to deduce amount out from other parameters. |
| 2986 | entry.first->second.m_amount_in = spent; |
| 2987 | entry.first->second.m_amount_out = get_outgoing_amount(tx, spent); |
| 2988 | entry.first->second.m_change = received; |
| 2989 | |
| 2990 | std::vector<tx_extra_field> tx_extra_fields; |
| 2991 | parse_tx_extra(tx.extra, tx_extra_fields); // ok if partially parsed |
| 2992 | tx_extra_nonce extra_nonce; |
| 2993 | if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) |
| 2994 | { |
| 2995 | // we do not care about failure here |
| 2996 | get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, entry.first->second.m_payment_id); |
| 2997 | } |
| 2998 | entry.first->second.m_subaddr_account = subaddr_account; |
| 2999 | entry.first->second.m_subaddr_indices = subaddr_indices; |
| 3000 | } |
| 3001 | |
| 3002 | entry.first->second.m_rings.clear(); |
| 3003 | for (const auto &in: tx.vin) |
| 3004 | { |
| 3005 | if (in.type() != typeid(cryptonote::txin_to_key)) |
| 3006 | continue; |
| 3007 | const auto &txin = boost::get<cryptonote::txin_to_key>(in); |
| 3008 | entry.first->second.m_rings.push_back(std::make_pair(txin.k_image, txin.key_offsets)); |
| 3009 | } |
| 3010 | entry.first->second.m_block_height = height; |
| 3011 | entry.first->second.m_timestamp = ts; |
| 3012 | entry.first->second.m_unlock_time = tx.unlock_time; |
| 3013 | |
| 3014 | add_rings(tx); |
| 3015 | } |
| 3016 | //---------------------------------------------------------------------------------------------------- |
| 3017 | bool wallet2::should_skip_block(const cryptonote::block &b, uint64_t height) const |
| 3018 | { |
| 3019 | // seeking only for blocks that are not older then the wallet creation time plus 1 day. 1 day is for possible user incorrect time setup |
| 3020 | return !(b.timestamp + 60*60*24 > m_account.get_createtime() && height >= m_refresh_from_block_height && height >= m_skip_to_height); |
| 3021 | } |
| 3022 | //---------------------------------------------------------------------------------------------------- |
| 3023 | void wallet2::process_new_blockchain_entry(const cryptonote::block& b, const cryptonote::block_complete_entry& bche, const parsed_block &parsed_block, const crypto::hash& bl_id, uint64_t height, const std::vector<tx_cache_data> &tx_cache_data, size_t tx_cache_data_offset, std::map<std::pair<uint64_t, uint64_t>, size_t> *output_tracker_cache) |
| 3024 | { |
| 3025 | THROW_WALLET_EXCEPTION_IF(bche.txs.size() + 1 != parsed_block.o_indices.indices.size(), error::wallet_internal_error, |
| 3026 | "block transactions=" + std::to_string(bche.txs.size()) + |
| 3027 | " not match with daemon response size=" + std::to_string(parsed_block.o_indices.indices.size())); |
| 3028 | |
| 3029 | //handle transactions from new block |
| 3030 | |
| 3031 | //optimization: seeking only for blocks that are not older then the wallet creation time plus 1 day. 1 day is for possible user incorrect time setup |
| 3032 | if (!should_skip_block(b, height)) |
| 3033 | { |
| 3034 | TIME_MEASURE_START(miner_tx_handle_time); |
| 3035 | if (m_refresh_type != RefreshNoCoinbase) |
| 3036 | process_new_transaction(get_transaction_hash(b.miner_tx), b.miner_tx, parsed_block.o_indices.indices[0].indices, height, b.major_version, b.timestamp, true, false, false, tx_cache_data[tx_cache_data_offset], output_tracker_cache); |
| 3037 | ++tx_cache_data_offset; |
| 3038 | TIME_MEASURE_FINISH(miner_tx_handle_time); |
| 3039 | |
| 3040 | TIME_MEASURE_START(txs_handle_time); |
| 3041 | THROW_WALLET_EXCEPTION_IF(bche.txs.size() != b.tx_hashes.size(), error::wallet_internal_error, "Wrong amount of transactions for block"); |
| 3042 | THROW_WALLET_EXCEPTION_IF(bche.txs.size() != parsed_block.txes.size(), error::wallet_internal_error, "Wrong amount of transactions for block"); |
| 3043 | for (size_t idx = 0; idx < b.tx_hashes.size(); ++idx) |
| 3044 | { |
| 3045 | process_new_transaction(b.tx_hashes[idx], parsed_block.txes[idx], parsed_block.o_indices.indices[idx+1].indices, height, b.major_version, b.timestamp, false, false, false, tx_cache_data[tx_cache_data_offset++], output_tracker_cache); |
| 3046 | } |
| 3047 | TIME_MEASURE_FINISH(txs_handle_time); |
| 3048 | m_last_block_reward = cryptonote::get_outs_money_amount(b.miner_tx); |
| 3049 | LOG_PRINT_L2("Processed block: " << bl_id << ", height " << height << ", " << miner_tx_handle_time + txs_handle_time << "(" << miner_tx_handle_time << "/" << txs_handle_time <<")ms"); |
| 3050 | }else |
| 3051 | { |
| 3052 | if (!(height % 128)) |
| 3053 | LOG_PRINT_L2( "Skipped block by timestamp, height: " << height << ", block time " << b.timestamp << ", account time " << m_account.get_createtime()); |
| 3054 | } |
| 3055 | m_blockchain.push_back(bl_id); |
| 3056 | |
| 3057 | if (0 != m_callback) |
| 3058 | m_callback->on_new_block(height, b); |
| 3059 | } |
| 3060 | //---------------------------------------------------------------------------------------------------- |
| 3061 | void wallet2::get_short_chain_history(std::list<crypto::hash>& ids, uint64_t granularity) const |
| 3062 | { |
| 3063 | size_t i = 0; |
| 3064 | size_t current_multiplier = 1; |
| 3065 | size_t blockchain_size = std::max((size_t)(m_blockchain.size() / granularity * granularity), m_blockchain.offset()); |
| 3066 | size_t sz = blockchain_size - m_blockchain.offset(); |
| 3067 | if(!sz) |
| 3068 | { |
| 3069 | if(m_blockchain.size() > m_blockchain.offset()) |
| 3070 | ids.push_back(m_blockchain[m_blockchain.offset()]); |
| 3071 | ids.push_back(m_blockchain.genesis()); |
| 3072 | return; |
| 3073 | } |
| 3074 | size_t current_back_offset = 1; |
| 3075 | bool base_included = false; |
| 3076 | while(current_back_offset < sz) |
| 3077 | { |
| 3078 | ids.push_back(m_blockchain[m_blockchain.offset() + sz-current_back_offset]); |
| 3079 | if(sz-current_back_offset == 0) |
| 3080 | base_included = true; |
| 3081 | if(i < 10) |
| 3082 | { |
| 3083 | ++current_back_offset; |
| 3084 | }else |
| 3085 | { |
| 3086 | current_back_offset += current_multiplier *= 2; |
| 3087 | } |
| 3088 | ++i; |
| 3089 | } |
| 3090 | if(!base_included) |
| 3091 | ids.push_back(m_blockchain[m_blockchain.offset()]); |
| 3092 | if(m_blockchain.offset()) |
| 3093 | ids.push_back(m_blockchain.genesis()); |
| 3094 | } |
| 3095 | //---------------------------------------------------------------------------------------------------- |
| 3096 | void wallet2::parse_block_round(const cryptonote::blobdata &blob, cryptonote::block &bl, crypto::hash &bl_id, bool &error) const |
| 3097 | { |
| 3098 | error = !cryptonote::parse_and_validate_block_from_blob(blob, bl, bl_id); |
| 3099 | } |
| 3100 | //---------------------------------------------------------------------------------------------------- |
| 3101 | void read_pool_txs(const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::request &req, const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::response &res, bool r, const std::vector<crypto::hash> &txids, std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &txs) |
| 3102 | { |
| 3103 | if (r && res.status == CORE_RPC_STATUS_OK) |
| 3104 | { |
| 3105 | MDEBUG("Reading pool txs"); |
| 3106 | if (res.txs.size() == req.txs_hashes.size()) |
| 3107 | { |
| 3108 | for (const auto &tx_entry: res.txs) |
| 3109 | { |
| 3110 | if (tx_entry.in_pool) |
| 3111 | { |
| 3112 | cryptonote::transaction tx; |
| 3113 | cryptonote::blobdata bd; |
| 3114 | crypto::hash tx_hash; |
| 3115 | |
| 3116 | if (get_pruned_tx(tx_entry, tx, tx_hash)) |
| 3117 | { |
| 3118 | const std::vector<crypto::hash>::const_iterator i = std::find_if(txids.begin(), txids.end(), |
| 3119 | [tx_hash](const crypto::hash &e) { return e == tx_hash; }); |
| 3120 | if (i != txids.end()) |
| 3121 | { |
| 3122 | txs.push_back(std::make_tuple(tx, tx_hash, tx_entry.double_spend_seen)); |
| 3123 | } |
| 3124 | else |
| 3125 | { |
| 3126 | MERROR("Got txid " << tx_hash << " which we did not ask for"); |
| 3127 | } |
| 3128 | } |
| 3129 | else |
| 3130 | { |
| 3131 | LOG_PRINT_L0("Failed to parse transaction from daemon"); |
| 3132 | } |
| 3133 | } |
| 3134 | else |
| 3135 | { |
| 3136 | LOG_PRINT_L1("Transaction from daemon was in pool, but is no more"); |
| 3137 | } |
| 3138 | } |
| 3139 | } |
| 3140 | else |
| 3141 | { |
| 3142 | LOG_PRINT_L0("Expected " << req.txs_hashes.size() << " out of " << txids.size() << " tx(es), got " << res.txs.size()); |
| 3143 | } |
| 3144 | } |
| 3145 | } |
| 3146 | //---------------------------------------------------------------------------------------------------- |
| 3147 | void wallet2::process_pool_info_extent(const cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::response &res, std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &process_txs, bool refreshed) |
| 3148 | { |
| 3149 | std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> added_pool_txs; |
| 3150 | added_pool_txs.reserve(res.added_pool_txs.size() + res.remaining_added_pool_txids.size()); |
| 3151 | |
| 3152 | for (const auto &pool_tx: res.added_pool_txs) |
| 3153 | { |
| 3154 | cryptonote::transaction tx; |
| 3155 | THROW_WALLET_EXCEPTION_IF(!cryptonote::parse_and_validate_tx_base_from_blob(pool_tx.tx_blob, tx), |
| 3156 | error::wallet_internal_error, "Failed to validate transaction base from daemon"); |
| 3157 | added_pool_txs.push_back(std::make_tuple(tx, pool_tx.tx_hash, pool_tx.double_spend_seen)); |
| 3158 | } |
| 3159 | |
| 3160 | // getblocks.bin may return more added pool transactions than we're allowed to request in restricted mode |
| 3161 | if (!res.remaining_added_pool_txids.empty()) |
| 3162 | { |
| 3163 | // request the remaining txs |
| 3164 | m_node_rpc_proxy.get_transactions(res.remaining_added_pool_txids, |
| 3165 | [this, &res, &added_pool_txs](const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::request &req_t, const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::response &resp_t, bool r) |
| 3166 | { |
| 3167 | read_pool_txs(req_t, resp_t, r, res.remaining_added_pool_txids, added_pool_txs); |
| 3168 | if (!r || resp_t.status != CORE_RPC_STATUS_OK) |
| 3169 | LOG_PRINT_L0("Error calling gettransactions daemon RPC: r " << r << ", status " << get_rpc_status(resp_t.status)); |
| 3170 | } |
| 3171 | ); |
| 3172 | } |
| 3173 | |
| 3174 | update_pool_state_from_pool_data(res.pool_info_extent == COMMAND_RPC_GET_BLOCKS_FAST::INCREMENTAL, res.removed_pool_txids, added_pool_txs, process_txs, refreshed); |
| 3175 | } |
| 3176 | //---------------------------------------------------------------------------------------------------- |
| 3177 | void wallet2::pull_blocks(bool first, bool try_incremental, uint64_t start_height, uint64_t &blocks_start_height, const std::list<crypto::hash> &short_chain_history, std::vector<cryptonote::block_complete_entry> &blocks, std::vector<cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices> &o_indices, uint64_t ¤t_height) |
| 3178 | { |
| 3179 | cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::request req = AUTO_VAL_INIT(req); |
| 3180 | cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::response res = AUTO_VAL_INIT(res); |
| 3181 | req.block_ids = short_chain_history; |
| 3182 | |
| 3183 | MDEBUG("Pulling blocks: start_height " << start_height); |
| 3184 | |
| 3185 | req.prune = true; |
| 3186 | req.start_height = start_height; |
| 3187 | req.no_miner_tx = m_refresh_type == RefreshNoCoinbase; |
| 3188 | |
| 3189 | req.requested_info = (first && !m_background_syncing) ? COMMAND_RPC_GET_BLOCKS_FAST::BLOCKS_AND_POOL : COMMAND_RPC_GET_BLOCKS_FAST::BLOCKS_ONLY; |
| 3190 | if (try_incremental && !m_background_syncing) |
| 3191 | req.pool_info_since = m_pool_info_query_time; |
| 3192 | |
| 3193 | { |
| 3194 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 3195 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 3196 | req.client = get_client_signature(); |
| 3197 | bool r = net_utils::invoke_http_bin("/getblocks.bin", req, res, *m_http_client, rpc_timeout); |
| 3198 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "getblocks.bin", error::get_blocks_error, get_rpc_status(res.status)); |
| 3199 | THROW_WALLET_EXCEPTION_IF(res.blocks.size() != res.output_indices.size(), error::wallet_internal_error, |
| 3200 | "mismatched blocks (" + boost::lexical_cast<std::string>(res.blocks.size()) + ") and output_indices (" + |
| 3201 | boost::lexical_cast<std::string>(res.output_indices.size()) + ") sizes from daemon"); |
| 3202 | uint64_t pool_info_cost = res.added_pool_txs.size() * COST_PER_TX + (res.remaining_added_pool_txids.size() + res.removed_pool_txids.size()) * COST_PER_POOL_HASH; |
| 3203 | check_rpc_cost("/getblocks.bin", res.credits, pre_call_credits, 1 + res.blocks.size() * COST_PER_BLOCK + pool_info_cost); |
| 3204 | } |
| 3205 | |
| 3206 | blocks_start_height = res.start_height; |
| 3207 | blocks = std::move(res.blocks); |
| 3208 | o_indices = std::move(res.output_indices); |
| 3209 | current_height = res.current_height; |
| 3210 | if (res.pool_info_extent != COMMAND_RPC_GET_BLOCKS_FAST::NONE) |
| 3211 | m_pool_info_query_time = res.daemon_time; |
| 3212 | |
| 3213 | MDEBUG("Pulled blocks: blocks_start_height " << blocks_start_height << ", count " << blocks.size() |
| 3214 | << ", height " << blocks_start_height + blocks.size() << ", node height " << res.current_height |
| 3215 | << ", pool info " << static_cast<unsigned int>(res.pool_info_extent)); |
| 3216 | |
| 3217 | if (first && !m_background_syncing) |
| 3218 | { |
| 3219 | if (res.pool_info_extent != COMMAND_RPC_GET_BLOCKS_FAST::NONE) |
| 3220 | { |
| 3221 | process_pool_info_extent(res, m_process_pool_txs, true); |
| 3222 | } |
| 3223 | else |
| 3224 | { |
| 3225 | // If we did not get any pool info, neither incremental nor the whole pool, we probably talk |
| 3226 | // to a daemon that does not yet support giving back pool info with the 'getblocks' call, |
| 3227 | // and we have to update in the "old way" |
| 3228 | update_pool_state_by_pool_query(m_process_pool_txs, true); |
| 3229 | } |
| 3230 | } |
| 3231 | |
| 3232 | } |
| 3233 | //---------------------------------------------------------------------------------------------------- |
| 3234 | void wallet2::pull_hashes(uint64_t start_height, uint64_t &blocks_start_height, const std::list<crypto::hash> &short_chain_history, std::vector<crypto::hash> &hashes) |
| 3235 | { |
| 3236 | cryptonote::COMMAND_RPC_GET_HASHES_FAST::request req = AUTO_VAL_INIT(req); |
| 3237 | cryptonote::COMMAND_RPC_GET_HASHES_FAST::response res = AUTO_VAL_INIT(res); |
| 3238 | req.block_ids = short_chain_history; |
| 3239 | |
| 3240 | req.start_height = start_height; |
| 3241 | |
| 3242 | { |
| 3243 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 3244 | req.client = get_client_signature(); |
| 3245 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 3246 | bool r = net_utils::invoke_http_bin("/gethashes.bin", req, res, *m_http_client, rpc_timeout); |
| 3247 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "gethashes.bin", error::get_hashes_error, get_rpc_status(res.status)); |
| 3248 | check_rpc_cost("/gethashes.bin", res.credits, pre_call_credits, 1 + res.m_block_ids.size() * COST_PER_BLOCK_HASH); |
| 3249 | } |
| 3250 | |
| 3251 | blocks_start_height = res.start_height; |
| 3252 | hashes = std::move(res.m_block_ids); |
| 3253 | } |
| 3254 | //---------------------------------------------------------------------------------------------------- |
| 3255 | void wallet2::process_parsed_blocks(uint64_t start_height, const std::vector<cryptonote::block_complete_entry> &blocks, const std::vector<parsed_block> &parsed_blocks, uint64_t& blocks_added, std::map<std::pair<uint64_t, uint64_t>, size_t> *output_tracker_cache) |
| 3256 | { |
| 3257 | size_t current_index = start_height; |
| 3258 | blocks_added = 0; |
| 3259 | |
| 3260 | THROW_WALLET_EXCEPTION_IF(blocks.size() != parsed_blocks.size(), error::wallet_internal_error, "size mismatch"); |
| 3261 | THROW_WALLET_EXCEPTION_IF(!m_blockchain.is_in_bounds(current_index), error::out_of_hashchain_bounds_error); |
| 3262 | |
| 3263 | tools::threadpool& tpool = tools::threadpool::getInstanceForCompute(); |
| 3264 | tools::threadpool::waiter waiter(tpool); |
| 3265 | |
| 3266 | size_t num_txes = 0; |
| 3267 | std::vector<tx_cache_data> tx_cache_data; |
| 3268 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3269 | num_txes += 1 + parsed_blocks[i].txes.size(); |
| 3270 | tx_cache_data.resize(num_txes); |
| 3271 | size_t txidx = 0; |
| 3272 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3273 | { |
| 3274 | THROW_WALLET_EXCEPTION_IF(parsed_blocks[i].txes.size() != parsed_blocks[i].block.tx_hashes.size(), |
| 3275 | error::wallet_internal_error, "Mismatched parsed_blocks[i].txes.size() and parsed_blocks[i].block.tx_hashes.size()"); |
| 3276 | if (should_skip_block(parsed_blocks[i].block, start_height + i)) |
| 3277 | { |
| 3278 | txidx += 1 + parsed_blocks[i].block.tx_hashes.size(); |
| 3279 | continue; |
| 3280 | } |
| 3281 | if (m_refresh_type != RefreshNoCoinbase) |
| 3282 | tpool.submit(&waiter, [&, i, txidx](){ cache_tx_data(parsed_blocks[i].block.miner_tx, get_transaction_hash(parsed_blocks[i].block.miner_tx), tx_cache_data[txidx]); }); |
| 3283 | ++txidx; |
| 3284 | for (size_t idx = 0; idx < parsed_blocks[i].txes.size(); ++idx) |
| 3285 | { |
| 3286 | tpool.submit(&waiter, [&, i, idx, txidx](){ cache_tx_data(parsed_blocks[i].txes[idx], parsed_blocks[i].block.tx_hashes[idx], tx_cache_data[txidx]); }); |
| 3287 | ++txidx; |
| 3288 | } |
| 3289 | } |
| 3290 | THROW_WALLET_EXCEPTION_IF(txidx != num_txes, error::wallet_internal_error, "txidx does not match tx_cache_data size"); |
| 3291 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 3292 | |
| 3293 | hw::device &hwdev = m_account.get_device(); |
| 3294 | hw::reset_mode rst(hwdev); |
| 3295 | hwdev.set_mode(hw::device::TRANSACTION_PARSE); |
| 3296 | const cryptonote::account_keys &keys = m_account.get_keys(); |
| 3297 | |
| 3298 | auto gender = [&](wallet2::is_out_data &iod) { |
| 3299 | if (!hwdev.generate_key_derivation(iod.pkey, keys.m_view_secret_key, iod.derivation)) |
| 3300 | { |
| 3301 | MWARNING("Failed to generate key derivation from tx pubkey, skipping"); |
| 3302 | static_assert(sizeof(iod.derivation) == sizeof(rct::key), "Mismatched sizes of key_derivation and rct::key"); |
| 3303 | memcpy(&iod.derivation, rct::identity().bytes, sizeof(iod.derivation)); |
| 3304 | } |
| 3305 | }; |
| 3306 | |
| 3307 | for (size_t i = 0; i < tx_cache_data.size(); ++i) |
| 3308 | { |
| 3309 | if (tx_cache_data[i].empty()) |
| 3310 | continue; |
| 3311 | tpool.submit(&waiter, [&gender, &tx_cache_data, i]() { |
| 3312 | auto &slot = tx_cache_data[i]; |
| 3313 | for (auto &iod: slot.primary) |
| 3314 | gender(iod); |
| 3315 | for (auto &iod: slot.additional) |
| 3316 | gender(iod); |
| 3317 | }, true); |
| 3318 | } |
| 3319 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 3320 | |
| 3321 | auto geniod = [&](const cryptonote::transaction &tx, size_t n_vouts, size_t txidx) { |
| 3322 | for (size_t k = 0; k < n_vouts; ++k) |
| 3323 | { |
| 3324 | const auto &o = tx.vout[k]; |
| 3325 | crypto::public_key output_public_key; |
| 3326 | if (get_output_public_key(o, output_public_key)) |
| 3327 | { |
| 3328 | std::vector<crypto::key_derivation> additional_derivations; |
| 3329 | additional_derivations.reserve(tx_cache_data[txidx].additional.size()); |
| 3330 | for (const auto &iod: tx_cache_data[txidx].additional) |
| 3331 | additional_derivations.push_back(iod.derivation); |
| 3332 | for (size_t l = 0; l < tx_cache_data[txidx].primary.size(); ++l) |
| 3333 | { |
| 3334 | THROW_WALLET_EXCEPTION_IF(tx_cache_data[txidx].primary[l].received.size() != n_vouts, |
| 3335 | error::wallet_internal_error, "Unexpected received array size"); |
| 3336 | tx_cache_data[txidx].primary[l].received[k] = is_out_to_acc_precomp(m_subaddresses, output_public_key, tx_cache_data[txidx].primary[l].derivation, additional_derivations, k, hwdev, get_output_view_tag(o)); |
| 3337 | additional_derivations.clear(); |
| 3338 | } |
| 3339 | } |
| 3340 | } |
| 3341 | }; |
| 3342 | struct geniod_params |
| 3343 | { |
| 3344 | const cryptonote::transaction &tx; |
| 3345 | size_t n_outs; |
| 3346 | size_t txidx; |
| 3347 | }; |
| 3348 | std::vector<geniod_params> geniods; |
| 3349 | geniods.reserve(num_txes); |
| 3350 | |
| 3351 | txidx = 0; |
| 3352 | uint8_t hf_version_view_tags = get_view_tag_fork(); |
| 3353 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3354 | { |
| 3355 | if (should_skip_block(parsed_blocks[i].block, start_height + i)) |
| 3356 | { |
| 3357 | txidx += 1 + parsed_blocks[i].block.tx_hashes.size(); |
| 3358 | continue; |
| 3359 | } |
| 3360 | |
| 3361 | if (m_refresh_type != RefreshType::RefreshNoCoinbase) |
| 3362 | { |
| 3363 | THROW_WALLET_EXCEPTION_IF(txidx >= tx_cache_data.size(), error::wallet_internal_error, "txidx out of range"); |
| 3364 | const cryptonote::transaction& tx = parsed_blocks[i].block.miner_tx; |
| 3365 | const size_t n_vouts = (m_refresh_type == RefreshType::RefreshOptimizeCoinbase && tx.version < 2) ? 1 : tx.vout.size(); |
| 3366 | if (parsed_blocks[i].block.major_version >= hf_version_view_tags) |
| 3367 | geniods.push_back(geniod_params{ tx, n_vouts, txidx }); |
| 3368 | else |
| 3369 | tpool.submit(&waiter, [&, n_vouts, txidx](){ geniod(tx, n_vouts, txidx); }, true); |
| 3370 | } |
| 3371 | ++txidx; |
| 3372 | for (size_t j = 0; j < parsed_blocks[i].txes.size(); ++j) |
| 3373 | { |
| 3374 | THROW_WALLET_EXCEPTION_IF(txidx >= tx_cache_data.size(), error::wallet_internal_error, "txidx out of range"); |
| 3375 | if (parsed_blocks[i].block.major_version >= hf_version_view_tags) |
| 3376 | geniods.push_back(geniod_params{ parsed_blocks[i].txes[j], parsed_blocks[i].txes[j].vout.size(), txidx }); |
| 3377 | else |
| 3378 | tpool.submit(&waiter, [&, i, j, txidx](){ geniod(parsed_blocks[i].txes[j], parsed_blocks[i].txes[j].vout.size(), txidx); }, true); |
| 3379 | ++txidx; |
| 3380 | } |
| 3381 | } |
| 3382 | THROW_WALLET_EXCEPTION_IF(txidx != tx_cache_data.size(), error::wallet_internal_error, "txidx did not reach expected value"); |
| 3383 | |
| 3384 | // View tags significantly speed up the geniod function that determines if an output belongs to the account. |
| 3385 | // Because the speedup is so large, the overhead from submitting individual geniods to the thread pool eats into |
| 3386 | // the benefit of executing in parallel. So to maximize the benefit from threads when view tags are enabled, |
| 3387 | // the wallet starts submitting geniod function calls to the thread pool in batches of size GENIOD_BATCH_SIZE. |
| 3388 | if (geniods.size()) |
| 3389 | { |
| 3390 | size_t GENIOD_BATCH_SIZE = 100; |
| 3391 | size_t num_batch_txes = 0; |
| 3392 | size_t batch_start = 0; |
| 3393 | while (batch_start < geniods.size()) |
| 3394 | { |
| 3395 | size_t batch_end = std::min(batch_start + GENIOD_BATCH_SIZE, geniods.size()); |
| 3396 | THROW_WALLET_EXCEPTION_IF(batch_end < batch_start, error::wallet_internal_error, "Thread batch end overflow"); |
| 3397 | tpool.submit(&waiter, [&geniods, &geniod, batch_start, batch_end]() { |
| 3398 | for (size_t i = batch_start; i < batch_end; ++i) |
| 3399 | { |
| 3400 | const geniod_params &gp = geniods[i]; |
| 3401 | geniod(gp.tx, gp.n_outs, gp.txidx); |
| 3402 | } |
| 3403 | }, true); |
| 3404 | num_batch_txes += batch_end - batch_start; |
| 3405 | batch_start = batch_end; |
| 3406 | } |
| 3407 | THROW_WALLET_EXCEPTION_IF(num_batch_txes != geniods.size(), error::wallet_internal_error, "txes batched for thread pool did not reach expected value"); |
| 3408 | } |
| 3409 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 3410 | |
| 3411 | hwdev.set_mode(hw::device::NONE); |
| 3412 | |
| 3413 | size_t tx_cache_data_offset = 0; |
| 3414 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3415 | { |
| 3416 | const crypto::hash &bl_id = parsed_blocks[i].hash; |
| 3417 | const cryptonote::block &bl = parsed_blocks[i].block; |
| 3418 | |
| 3419 | if(current_index >= m_blockchain.size()) |
| 3420 | { |
| 3421 | process_new_blockchain_entry(bl, blocks[i], parsed_blocks[i], bl_id, current_index, tx_cache_data, tx_cache_data_offset, output_tracker_cache); |
| 3422 | ++blocks_added; |
| 3423 | } |
| 3424 | else if(bl_id != m_blockchain[current_index]) |
| 3425 | { |
| 3426 | //split detected here !!! |
| 3427 | THROW_WALLET_EXCEPTION_IF(current_index == start_height, error::wallet_internal_error, |
| 3428 | "wrong daemon response: split starts from the first block in response " + string_tools::pod_to_hex(bl_id) + |
| 3429 | " (height " + std::to_string(start_height) + "), local block id at this height: " + |
| 3430 | string_tools::pod_to_hex(m_blockchain[current_index])); |
| 3431 | |
| 3432 | const uint64_t reorg_depth = m_blockchain.size() - current_index; |
| 3433 | THROW_WALLET_EXCEPTION_IF(reorg_depth > m_max_reorg_depth, error::reorg_depth_error, |
| 3434 | tr("reorg exceeds maximum allowed depth, use 'set max-reorg-depth N' to allow it, reorg depth: ") + |
| 3435 | std::to_string(reorg_depth)); |
| 3436 | |
| 3437 | handle_reorg(current_index, output_tracker_cache); |
| 3438 | process_new_blockchain_entry(bl, blocks[i], parsed_blocks[i], bl_id, current_index, tx_cache_data, tx_cache_data_offset, output_tracker_cache); |
| 3439 | } |
| 3440 | else |
| 3441 | { |
| 3442 | LOG_PRINT_L2("Block is already in blockchain: " << string_tools::pod_to_hex(bl_id)); |
| 3443 | } |
| 3444 | ++current_index; |
| 3445 | tx_cache_data_offset += 1 + parsed_blocks[i].txes.size(); |
| 3446 | } |
| 3447 | } |
| 3448 | //---------------------------------------------------------------------------------------------------- |
| 3449 | void wallet2::refresh(bool trusted_daemon) |
| 3450 | { |
| 3451 | uint64_t blocks_fetched = 0; |
| 3452 | refresh(trusted_daemon, 0, blocks_fetched); |
| 3453 | } |
| 3454 | //---------------------------------------------------------------------------------------------------- |
| 3455 | void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blocks_fetched) |
| 3456 | { |
| 3457 | bool received_money = false; |
| 3458 | refresh(trusted_daemon, start_height, blocks_fetched, received_money); |
| 3459 | } |
| 3460 | //---------------------------------------------------------------------------------------------------- |
| 3461 | void check_block_hard_fork_version(cryptonote::network_type nettype, uint8_t hf_version, uint64_t height, bool &wallet_is_outdated, bool &daemon_is_outdated) |
| 3462 | { |
| 3463 | const size_t wallet_num_hard_forks = nettype == TESTNET ? num_testnet_hard_forks |
| 3464 | : nettype == STAGENET ? num_stagenet_hard_forks : num_mainnet_hard_forks; |
| 3465 | const hardfork_t *wallet_hard_forks = nettype == TESTNET ? testnet_hard_forks |
| 3466 | : nettype == STAGENET ? stagenet_hard_forks : mainnet_hard_forks; |
| 3467 | |
| 3468 | wallet_is_outdated = static_cast<size_t>(hf_version) > wallet_num_hard_forks; |
| 3469 | if (wallet_is_outdated) |
| 3470 | return; |
| 3471 | |
| 3472 | // check block's height falls within wallet's expected range for block's given version |
| 3473 | uint64_t start_height = hf_version == 1 ? 0 : wallet_hard_forks[hf_version - 1].height; |
| 3474 | uint64_t end_height = static_cast<size_t>(hf_version) + 1 > wallet_num_hard_forks |
| 3475 | ? std::numeric_limits<uint64_t>::max() |
| 3476 | : wallet_hard_forks[hf_version].height; |
| 3477 | |
| 3478 | daemon_is_outdated = height < start_height || height >= end_height; |
| 3479 | } |
| 3480 | //---------------------------------------------------------------------------------------------------- |
| 3481 | void wallet2::pull_and_parse_next_blocks(bool first, bool try_incremental, uint64_t start_height, uint64_t &blocks_start_height, std::list<crypto::hash> &short_chain_history, const std::vector<cryptonote::block_complete_entry> &prev_blocks, const std::vector<parsed_block> &prev_parsed_blocks, std::vector<cryptonote::block_complete_entry> &blocks, std::vector<parsed_block> &parsed_blocks, bool &last, bool &error, std::exception_ptr &exception) |
| 3482 | { |
| 3483 | error = false; |
| 3484 | last = false; |
| 3485 | exception = NULL; |
| 3486 | |
| 3487 | try |
| 3488 | { |
| 3489 | drop_from_short_history(short_chain_history, 3); |
| 3490 | |
| 3491 | THROW_WALLET_EXCEPTION_IF(prev_blocks.size() != prev_parsed_blocks.size(), error::wallet_internal_error, "size mismatch"); |
| 3492 | |
| 3493 | // prepend the last 3 blocks, should be enough to guard against a block or two's reorg |
| 3494 | auto s = std::next(prev_parsed_blocks.rbegin(), std::min((size_t)3, prev_parsed_blocks.size())).base(); |
| 3495 | for (; s != prev_parsed_blocks.end(); ++s) |
| 3496 | { |
| 3497 | short_chain_history.push_front(s->hash); |
| 3498 | } |
| 3499 | |
| 3500 | // pull the new blocks |
| 3501 | std::vector<cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices> o_indices; |
| 3502 | uint64_t current_height; |
| 3503 | pull_blocks(first, try_incremental, start_height, blocks_start_height, short_chain_history, blocks, o_indices, current_height); |
| 3504 | THROW_WALLET_EXCEPTION_IF(blocks.size() != o_indices.size(), error::wallet_internal_error, "Mismatched sizes of blocks and o_indices"); |
| 3505 | |
| 3506 | tools::threadpool& tpool = tools::threadpool::getInstanceForCompute(); |
| 3507 | tools::threadpool::waiter waiter(tpool); |
| 3508 | parsed_blocks.resize(blocks.size()); |
| 3509 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3510 | { |
| 3511 | tpool.submit(&waiter, boost::bind(&wallet2::parse_block_round, this, std::cref(blocks[i].block), |
| 3512 | std::ref(parsed_blocks[i].block), std::ref(parsed_blocks[i].hash), std::ref(parsed_blocks[i].error)), true); |
| 3513 | } |
| 3514 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 3515 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3516 | { |
| 3517 | if (parsed_blocks[i].error) |
| 3518 | { |
| 3519 | error = true; |
| 3520 | break; |
| 3521 | } |
| 3522 | |
| 3523 | if (!m_allow_mismatched_daemon_version) |
| 3524 | { |
| 3525 | // make sure block's hard fork version is expected at the block's height |
| 3526 | uint8_t hf_version = parsed_blocks[i].block.major_version; |
| 3527 | uint64_t height = blocks_start_height + i; |
| 3528 | bool wallet_is_outdated = false; |
| 3529 | bool daemon_is_outdated = false; |
| 3530 | check_block_hard_fork_version(m_nettype, hf_version, height, wallet_is_outdated, daemon_is_outdated); |
| 3531 | THROW_WALLET_EXCEPTION_IF(wallet_is_outdated || daemon_is_outdated, error::incorrect_fork_version, |
| 3532 | "Unexpected hard fork version v" + std::to_string(hf_version) + " at height " + std::to_string(height) + ". " + |
| 3533 | (wallet_is_outdated |
| 3534 | ? "Make sure your wallet is up to date" |
| 3535 | : "Make sure the node you are connected to is running the latest version") |
| 3536 | ); |
| 3537 | } |
| 3538 | |
| 3539 | parsed_blocks[i].o_indices = std::move(o_indices[i]); |
| 3540 | } |
| 3541 | |
| 3542 | boost::mutex error_lock; |
| 3543 | for (size_t i = 0; i < blocks.size(); ++i) |
| 3544 | { |
| 3545 | parsed_blocks[i].txes.resize(blocks[i].txs.size()); |
| 3546 | for (size_t j = 0; j < blocks[i].txs.size(); ++j) |
| 3547 | { |
| 3548 | tpool.submit(&waiter, [&, i, j](){ |
| 3549 | if (!parse_and_validate_tx_base_from_blob(blocks[i].txs[j].blob, parsed_blocks[i].txes[j])) |
| 3550 | { |
| 3551 | boost::unique_lock<boost::mutex> lock(error_lock); |
| 3552 | error = true; |
| 3553 | } |
| 3554 | }, true); |
| 3555 | } |
| 3556 | } |
| 3557 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 3558 | last = !blocks.empty() && cryptonote::get_block_height(parsed_blocks.back().block) + 1 == current_height; |
| 3559 | } |
| 3560 | catch(...) |
| 3561 | { |
| 3562 | error = true; |
| 3563 | exception = std::current_exception(); |
| 3564 | } |
| 3565 | } |
| 3566 | |
| 3567 | void wallet2::remove_obsolete_pool_txs(const std::vector<crypto::hash> &tx_hashes, bool remove_if_found) |
| 3568 | { |
| 3569 | // remove pool txes to us that aren't in the pool anymore (remove_if_found = false), |
| 3570 | // or remove pool txes to us that were reported as removed (remove_if_found = true) |
| 3571 | std::unordered_multimap<crypto::hash, wallet2::pool_payment_details>::iterator uit = m_unconfirmed_payments.begin(); |
| 3572 | while (uit != m_unconfirmed_payments.end()) |
| 3573 | { |
| 3574 | const crypto::hash &txid = uit->second.m_pd.m_tx_hash; |
| 3575 | bool found = false; |
| 3576 | for (const auto &it2: tx_hashes) |
| 3577 | { |
| 3578 | if (it2 == txid) |
| 3579 | { |
| 3580 | found = true; |
| 3581 | break; |
| 3582 | } |
| 3583 | } |
| 3584 | auto pit = uit++; |
| 3585 | if ((!remove_if_found && !found) || (remove_if_found && found)) |
| 3586 | { |
| 3587 | MDEBUG("Removing " << txid << " from unconfirmed payments"); |
| 3588 | m_unconfirmed_payments.erase(pit); |
| 3589 | if (0 != m_callback) |
| 3590 | m_callback->on_pool_tx_removed(txid); |
| 3591 | } |
| 3592 | } |
| 3593 | } |
| 3594 | |
| 3595 | //---------------------------------------------------------------------------------------------------- |
| 3596 | // Code that is common to 'update_pool_state_by_pool_query' and 'update_pool_state_from_pool_data': |
| 3597 | // Check wether a tx in the pool is worthy of processing because we did not see it |
| 3598 | // yet or because it is "interesting" out of special circumstances |
| 3599 | bool wallet2::accept_pool_tx_for_processing(const crypto::hash &txid) |
| 3600 | { |
| 3601 | bool txid_found_in_up = false; |
| 3602 | for (const auto &up: m_unconfirmed_payments) |
| 3603 | { |
| 3604 | if (up.second.m_pd.m_tx_hash == txid) |
| 3605 | { |
| 3606 | txid_found_in_up = true; |
| 3607 | break; |
| 3608 | } |
| 3609 | } |
| 3610 | if (m_scanned_pool_txs[0].find(txid) != m_scanned_pool_txs[0].end() || m_scanned_pool_txs[1].find(txid) != m_scanned_pool_txs[1].end()) |
| 3611 | { |
| 3612 | // if it's for us, we want to keep track of whether we saw a double spend, so don't bail out |
| 3613 | if (!txid_found_in_up) |
| 3614 | { |
| 3615 | LOG_PRINT_L2("Already seen " << txid << ", and not for us, skipped"); |
| 3616 | return false; |
| 3617 | } |
| 3618 | } |
| 3619 | if (!txid_found_in_up) |
| 3620 | { |
| 3621 | LOG_PRINT_L1("Found new pool tx: " << txid); |
| 3622 | bool found = false; |
| 3623 | for (const auto &i: m_unconfirmed_txs) |
| 3624 | { |
| 3625 | if (i.first == txid) |
| 3626 | { |
| 3627 | found = true; |
| 3628 | // if this is a payment to yourself at a different subaddress account, don't skip it |
| 3629 | // so that you can see the incoming pool tx with 'show_transfers' on that receiving subaddress account |
| 3630 | const unconfirmed_transfer_details& utd = i.second; |
| 3631 | for (const auto& dst : utd.m_dests) |
| 3632 | { |
| 3633 | auto subaddr_index = m_subaddresses.find(dst.addr.m_spend_public_key); |
| 3634 | if (subaddr_index != m_subaddresses.end() && subaddr_index->second.major != utd.m_subaddr_account) |
| 3635 | { |
| 3636 | found = false; |
| 3637 | break; |
| 3638 | } |
| 3639 | } |
| 3640 | break; |
| 3641 | } |
| 3642 | } |
| 3643 | if (!found) |
| 3644 | { |
| 3645 | // not one of those we sent ourselves |
| 3646 | return true; |
| 3647 | } |
| 3648 | else |
| 3649 | { |
| 3650 | LOG_PRINT_L1("We sent that one"); |
| 3651 | return false; |
| 3652 | } |
| 3653 | } |
| 3654 | else { |
| 3655 | return false; |
| 3656 | } |
| 3657 | } |
| 3658 | //---------------------------------------------------------------------------------------------------- |
| 3659 | // Code that is common to 'update_pool_state_by_pool_query' and 'update_pool_state_from_pool_data': |
| 3660 | // Process an unconfirmed transfer after we know whether it's in the pool or not |
| 3661 | void wallet2::process_unconfirmed_transfer(bool incremental, const crypto::hash &txid, wallet2::unconfirmed_transfer_details &tx_details, bool seen_in_pool, std::chrono::system_clock::time_point now, bool refreshed) |
| 3662 | { |
| 3663 | const auto set_tx_key_images_spent = [&](const bool spent) |
| 3664 | { |
| 3665 | for (size_t vini = 0; vini < tx_details.m_tx.vin.size(); ++vini) |
| 3666 | { |
| 3667 | if (tx_details.m_tx.vin[vini].type() != typeid(txin_to_key)) |
| 3668 | continue; |
| 3669 | |
| 3670 | const crypto::key_image &key_image = boost::get<txin_to_key>(tx_details.m_tx.vin[vini]).k_image; |
| 3671 | const auto it_ki = m_key_images.find(key_image); |
| 3672 | if (it_ki == m_key_images.end()) |
| 3673 | continue; |
| 3674 | |
| 3675 | const std::size_t i = it_ki->second; |
| 3676 | if (i >= m_transfers.size()) |
| 3677 | continue; |
| 3678 | const transfer_details &td = m_transfers.at(i); |
| 3679 | if (td.m_key_image != key_image) |
| 3680 | continue; |
| 3681 | if (td.m_spent == spent) |
| 3682 | continue; |
| 3683 | |
| 3684 | LOG_PRINT_L1("Resetting spent status for output " << vini << ": " << key_image << " (spent=" << spent << ")"); |
| 3685 | if (spent) |
| 3686 | set_spent(i, 0); |
| 3687 | else |
| 3688 | set_unspent(i); |
| 3689 | } |
| 3690 | }; |
| 3691 | |
| 3692 | // TODO: set tx_propagation_timeout to CRYPTONOTE_DANDELIONPP_EMBARGO_AVERAGE * 3 / 2 after v15 hardfork |
| 3693 | constexpr const std::chrono::seconds tx_propagation_timeout{500}; |
| 3694 | if (seen_in_pool) |
| 3695 | { |
| 3696 | if (tx_details.m_state != wallet2::unconfirmed_transfer_details::pending_in_pool) |
| 3697 | { |
| 3698 | tx_details.m_state = wallet2::unconfirmed_transfer_details::pending_in_pool; |
| 3699 | MINFO("Pending txid " << txid << " seen in pool, marking as pending in pool"); |
| 3700 | } |
| 3701 | |
| 3702 | // The inputs are spent, they're in the pool! It's possible the tx was previously marked as failed, so we |
| 3703 | // make sure to re-mark the outputs as spent. |
| 3704 | set_tx_key_images_spent(true/*spent*/); |
| 3705 | } |
| 3706 | else |
| 3707 | { |
| 3708 | if (!incremental) |
| 3709 | { |
| 3710 | if (tx_details.m_state == wallet2::unconfirmed_transfer_details::pending_in_pool) |
| 3711 | { |
| 3712 | // For the probably unlikely case that a tx once seen in the pool vanishes |
| 3713 | // again set back to 'pending' |
| 3714 | tx_details.m_state = wallet2::unconfirmed_transfer_details::pending; |
| 3715 | MINFO("Already seen txid " << txid << " vanished from pool, marking as pending"); |
| 3716 | } |
| 3717 | } |
| 3718 | // If a tx is pending for a "long time" without appearing in the pool, and if |
| 3719 | // we have refreshed and thus had a chance to really see it if it was there, |
| 3720 | // judge it as failed; the waiting for timeout and refresh happened avoids |
| 3721 | // false alarms with txs going to 'failed' too early |
| 3722 | if (tx_details.m_state == wallet2::unconfirmed_transfer_details::pending && refreshed && |
| 3723 | now > std::chrono::system_clock::from_time_t(tx_details.m_sent_time) + tx_propagation_timeout) |
| 3724 | { |
| 3725 | LOG_PRINT_L1("Pending txid " << txid << " not in pool after " << tx_propagation_timeout.count() << |
| 3726 | " seconds, marking as failed"); |
| 3727 | tx_details.m_state = wallet2::unconfirmed_transfer_details::failed; |
| 3728 | |
| 3729 | // the inputs aren't spent anymore, since the tx failed |
| 3730 | set_tx_key_images_spent(false/*spent*/); |
| 3731 | } |
| 3732 | } |
| 3733 | } |
| 3734 | //---------------------------------------------------------------------------------------------------- |
| 3735 | // This public method is typically called to make sure that the wallet's pool state is up-to-date by |
| 3736 | // clients like simplewallet and the RPC daemon. Before incremental update this was the same method |
| 3737 | // that 'refresh' also used, but now it's more complicated because for the time being we support |
| 3738 | // the "old" and the "new" way of updating the pool and because only the 'getblocks' call supports |
| 3739 | // incremental update but we don't want any blocks here. |
| 3740 | // |
| 3741 | // simplewallet does NOT update the pool info during automatic refresh to avoid disturbing interactive |
| 3742 | // messages and prompts. When it finally calls this method here "to catch up" so to say we can't use |
| 3743 | // incremental update anymore, because with that we might miss some txs altogether. |
| 3744 | void wallet2::update_pool_state(std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &process_txs, bool refreshed, bool try_incremental) |
| 3745 | { |
| 3746 | process_txs.clear(); |
| 3747 | if (m_background_syncing) |
| 3748 | return; |
| 3749 | bool updated = false; |
| 3750 | if (m_pool_info_query_time != 0 && try_incremental) |
| 3751 | { |
| 3752 | // We are connected to a daemon that supports giving back pool data with the 'getblocks' call, |
| 3753 | // thus use that, to get the chance to work incrementally and to keep working incrementally; |
| 3754 | // 'POOL_ONLY' was created to support this case |
| 3755 | cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::request req = AUTO_VAL_INIT(req); |
| 3756 | cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::response res = AUTO_VAL_INIT(res); |
| 3757 | |
| 3758 | req.requested_info = COMMAND_RPC_GET_BLOCKS_FAST::POOL_ONLY; |
| 3759 | req.pool_info_since = m_pool_info_query_time; |
| 3760 | req.prune = true; |
| 3761 | |
| 3762 | { |
| 3763 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 3764 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 3765 | req.client = get_client_signature(); |
| 3766 | bool r = net_utils::invoke_http_bin("/getblocks.bin", req, res, *m_http_client, rpc_timeout); |
| 3767 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "getblocks.bin", error::get_blocks_error, get_rpc_status(res.status)); |
| 3768 | uint64_t pool_info_cost = res.added_pool_txs.size() * COST_PER_TX + (res.remaining_added_pool_txids.size() + res.removed_pool_txids.size()) * COST_PER_POOL_HASH; |
| 3769 | check_rpc_cost("/getblocks.bin", res.credits, pre_call_credits, pool_info_cost); |
| 3770 | } |
| 3771 | |
| 3772 | m_pool_info_query_time = res.daemon_time; |
| 3773 | if (res.pool_info_extent != COMMAND_RPC_GET_BLOCKS_FAST::NONE) |
| 3774 | { |
| 3775 | process_pool_info_extent(res, process_txs, refreshed); |
| 3776 | updated = true; |
| 3777 | } |
| 3778 | // We SHOULD get pool data here, but if for some crazy reason we don't fall back to the "old" method |
| 3779 | } |
| 3780 | if (!updated) |
| 3781 | { |
| 3782 | update_pool_state_by_pool_query(process_txs, refreshed); |
| 3783 | } |
| 3784 | } |
| 3785 | //---------------------------------------------------------------------------------------------------- |
| 3786 | // This is the "old" way of updating the pool with separate queries to get the pool content, used before |
| 3787 | // the 'getblocks' command was able to give back pool data in addition to blocks. Before this code was |
| 3788 | // the public 'update_pool_state' method. The logic is unchanged. This is a candidate for elimination |
| 3789 | // when it's sure that no more "old" daemons can be possibly around. |
| 3790 | void wallet2::update_pool_state_by_pool_query(std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &process_txs, bool refreshed) |
| 3791 | { |
| 3792 | MTRACE("update_pool_state_by_pool_query start"); |
| 3793 | process_txs.clear(); |
| 3794 | |
| 3795 | auto keys_reencryptor = epee::misc_utils::create_scope_leave_handler([&, this]() { |
| 3796 | m_encrypt_keys_after_refresh.reset(); |
| 3797 | }); |
| 3798 | |
| 3799 | // get the pool state |
| 3800 | cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_HASHES_BIN::request req; |
| 3801 | cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_HASHES_BIN::response res; |
| 3802 | |
| 3803 | { |
| 3804 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 3805 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 3806 | req.client = get_client_signature(); |
| 3807 | bool r = epee::net_utils::invoke_http_json("/get_transaction_pool_hashes.bin", req, res, *m_http_client, rpc_timeout); |
| 3808 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "get_transaction_pool_hashes.bin", error::get_tx_pool_error); |
| 3809 | check_rpc_cost("/get_transaction_pool_hashes.bin", res.credits, pre_call_credits, 1 + res.tx_hashes.size() * COST_PER_POOL_HASH); |
| 3810 | } |
| 3811 | MTRACE("update_pool_state_by_pool_query got pool"); |
| 3812 | |
| 3813 | // remove any pending tx that's not in the pool |
| 3814 | const auto now = std::chrono::system_clock::now(); |
| 3815 | std::unordered_map<crypto::hash, wallet2::unconfirmed_transfer_details>::iterator it = m_unconfirmed_txs.begin(); |
| 3816 | while (it != m_unconfirmed_txs.end()) |
| 3817 | { |
| 3818 | const crypto::hash &txid = it->first; |
| 3819 | MDEBUG("Checking m_unconfirmed_txs entry " << txid); |
| 3820 | bool found = false; |
| 3821 | for (const auto &it2: res.tx_hashes) |
| 3822 | { |
| 3823 | if (it2 == txid) |
| 3824 | { |
| 3825 | found = true; |
| 3826 | break; |
| 3827 | } |
| 3828 | } |
| 3829 | auto pit = it++; |
| 3830 | process_unconfirmed_transfer(false, txid, pit->second, found, now, refreshed); |
| 3831 | MDEBUG("New state of that entry: " << pit->second.m_state); |
| 3832 | } |
| 3833 | MTRACE("update_pool_state_by_pool_query done first loop"); |
| 3834 | |
| 3835 | // remove pool txes to us that aren't in the pool anymore |
| 3836 | // but only if we just refreshed, so that the tx can go in |
| 3837 | // the in transfers list instead (or nowhere if it just |
| 3838 | // disappeared without being mined) |
| 3839 | if (refreshed) |
| 3840 | remove_obsolete_pool_txs(res.tx_hashes, false); |
| 3841 | |
| 3842 | MTRACE("update_pool_state_by_pool_query done second loop"); |
| 3843 | |
| 3844 | // gather txids of new pool txes to us |
| 3845 | std::vector<crypto::hash> txids; |
| 3846 | for (const auto &txid: res.tx_hashes) |
| 3847 | { |
| 3848 | if (accept_pool_tx_for_processing(txid)) |
| 3849 | txids.push_back(txid); |
| 3850 | } |
| 3851 | |
| 3852 | m_node_rpc_proxy.get_transactions(txids, |
| 3853 | [this, &txids, &process_txs](const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::request &req_t, const cryptonote::COMMAND_RPC_GET_TRANSACTIONS::response &resp_t, bool r) |
| 3854 | { |
| 3855 | read_pool_txs(req_t, resp_t, r, txids, process_txs); |
| 3856 | if (!r || resp_t.status != CORE_RPC_STATUS_OK) |
| 3857 | LOG_PRINT_L0("Error calling gettransactions daemon RPC: r " << r << ", status " << get_rpc_status(resp_t.status)); |
| 3858 | } |
| 3859 | ); |
| 3860 | |
| 3861 | MTRACE("update_pool_state_by_pool_query end"); |
| 3862 | } |
| 3863 | //---------------------------------------------------------------------------------------------------- |
| 3864 | // Update pool state from pool data we got together with block data, either incremental data with |
| 3865 | // txs that are new in the pool since the last time we queried and the ids of txs that were |
| 3866 | // removed from the pool since then, or the whole content of the pool if incremental was not |
| 3867 | // possible, e.g. because the server was just started or restarted. |
| 3868 | void wallet2::update_pool_state_from_pool_data(bool incremental, const std::vector<crypto::hash> &removed_pool_txids, const std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &added_pool_txs, std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &process_txs, bool refreshed) |
| 3869 | { |
| 3870 | MTRACE("update_pool_state_from_pool_data start"); |
| 3871 | auto keys_reencryptor = epee::misc_utils::create_scope_leave_handler([&, this]() { |
| 3872 | m_encrypt_keys_after_refresh.reset(); |
| 3873 | }); |
| 3874 | |
| 3875 | if (refreshed) |
| 3876 | { |
| 3877 | if (incremental) |
| 3878 | { |
| 3879 | // Delete from the list of unconfirmed payments what the daemon reported as tx that was removed from |
| 3880 | // pool; do so only after refresh to not delete too early and too eagerly; maybe we will find the tx |
| 3881 | // later in a block, or not, or find it again in the pool txs because it was first removed but then |
| 3882 | // somehow quickly "resurrected" - that all does not matter here, we retrace the removal |
| 3883 | remove_obsolete_pool_txs(removed_pool_txids, true); |
| 3884 | } |
| 3885 | else |
| 3886 | { |
| 3887 | // Delete from the list of unconfirmed payments what we don't find anymore in the pool; a bit |
| 3888 | // unfortunate that we have to build a new vector with ids first, but better than copying and |
| 3889 | // modifying the code of 'remove_obsolete_pool_txs' here |
| 3890 | std::vector<crypto::hash> txids; |
| 3891 | txids.reserve(added_pool_txs.size()); |
| 3892 | for (const auto &pool_tx: added_pool_txs) |
| 3893 | { |
| 3894 | txids.push_back(std::get<1>(pool_tx)); |
| 3895 | } |
| 3896 | remove_obsolete_pool_txs(txids, false); |
| 3897 | } |
| 3898 | } |
| 3899 | |
| 3900 | // Possibly remove any pending tx that's not in the pool |
| 3901 | const auto now = std::chrono::system_clock::now(); |
| 3902 | std::unordered_map<crypto::hash, wallet2::unconfirmed_transfer_details>::iterator it = m_unconfirmed_txs.begin(); |
| 3903 | while (it != m_unconfirmed_txs.end()) |
| 3904 | { |
| 3905 | const crypto::hash &txid = it->first; |
| 3906 | MDEBUG("Checking m_unconfirmed_txs entry " << txid); |
| 3907 | bool found = false; |
| 3908 | for (const auto &pool_tx: added_pool_txs) |
| 3909 | { |
| 3910 | if (std::get<1>(pool_tx) == txid) |
| 3911 | { |
| 3912 | found = true; |
| 3913 | break; |
| 3914 | } |
| 3915 | } |
| 3916 | auto pit = it++; |
| 3917 | process_unconfirmed_transfer(incremental, txid, pit->second, found, now, refreshed); |
| 3918 | MDEBUG("Resulting state of that entry: " << pit->second.m_state); |
| 3919 | } |
| 3920 | |
| 3921 | // Collect all pool txs that are "interesting" i.e. mostly those that we don't know about yet; |
| 3922 | // if we work incrementally and thus see only new pool txs since last time we asked it should |
| 3923 | // be rare that we know already about one of those, but check nevertheless |
| 3924 | process_txs.clear(); |
| 3925 | for (const auto &pool_tx: added_pool_txs) |
| 3926 | { |
| 3927 | if (accept_pool_tx_for_processing(std::get<1>(pool_tx))) |
| 3928 | { |
| 3929 | process_txs.push_back(pool_tx); |
| 3930 | } |
| 3931 | } |
| 3932 | |
| 3933 | MTRACE("update_pool_state_from_pool_data end"); |
| 3934 | } |
| 3935 | //---------------------------------------------------------------------------------------------------- |
| 3936 | void wallet2::process_pool_state(const std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> &txs) |
| 3937 | { |
| 3938 | MTRACE("process_pool_state start"); |
| 3939 | const time_t now = time(NULL); |
| 3940 | for (const auto &e: txs) |
| 3941 | { |
| 3942 | const cryptonote::transaction &tx = std::get<0>(e); |
| 3943 | const crypto::hash &tx_hash = std::get<1>(e); |
| 3944 | const bool double_spend_seen = std::get<2>(e); |
| 3945 | process_new_transaction(tx_hash, tx, std::vector<uint64_t>(), 0, 0, now, false, true, double_spend_seen, {}); |
| 3946 | m_scanned_pool_txs[0].insert(tx_hash); |
| 3947 | if (m_scanned_pool_txs[0].size() > 5000) |
| 3948 | { |
| 3949 | std::swap(m_scanned_pool_txs[0], m_scanned_pool_txs[1]); |
| 3950 | m_scanned_pool_txs[0].clear(); |
| 3951 | } |
| 3952 | } |
| 3953 | MTRACE("process_pool_state end"); |
| 3954 | } |
| 3955 | //---------------------------------------------------------------------------------------------------- |
| 3956 | void wallet2::fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, std::list<crypto::hash> &short_chain_history, bool force) |
| 3957 | { |
| 3958 | std::vector<crypto::hash> hashes; |
| 3959 | |
| 3960 | const uint64_t checkpoint_height = m_checkpoints.get_max_height(); |
| 3961 | if ((stop_height > checkpoint_height && m_blockchain.size()-1 < checkpoint_height) && !force) |
| 3962 | { |
| 3963 | // we will drop all these, so don't bother getting them |
| 3964 | uint64_t missing_blocks = m_checkpoints.get_max_height() - m_blockchain.size(); |
| 3965 | while (missing_blocks-- > 0) |
| 3966 | m_blockchain.push_back(crypto::null_hash); // maybe a bit suboptimal, but deque won't do huge reallocs like vector |
| 3967 | m_blockchain.push_back(m_checkpoints.get_points().at(checkpoint_height)); |
| 3968 | m_blockchain.trim(checkpoint_height); |
| 3969 | short_chain_history.clear(); |
| 3970 | get_short_chain_history(short_chain_history); |
| 3971 | } |
| 3972 | |
| 3973 | size_t current_index = m_blockchain.size(); |
| 3974 | while(m_run.load(std::memory_order_relaxed) && current_index < stop_height) |
| 3975 | { |
| 3976 | pull_hashes(0, blocks_start_height, short_chain_history, hashes); |
| 3977 | if (hashes.size() <= 3) |
| 3978 | return; |
| 3979 | if (blocks_start_height < m_blockchain.offset()) |
| 3980 | { |
| 3981 | MERROR("Blocks start before blockchain offset: " << blocks_start_height << " " << m_blockchain.offset()); |
| 3982 | return; |
| 3983 | } |
| 3984 | current_index = blocks_start_height; |
| 3985 | if (hashes.size() + current_index < stop_height) { |
| 3986 | drop_from_short_history(short_chain_history, 3); |
| 3987 | std::vector<crypto::hash>::iterator right = hashes.end(); |
| 3988 | // prepend 3 more |
| 3989 | for (int i = 0; i<3; i++) { |
| 3990 | right--; |
| 3991 | short_chain_history.push_front(*right); |
| 3992 | } |
| 3993 | } |
| 3994 | for(auto& bl_id: hashes) |
| 3995 | { |
| 3996 | if(current_index >= m_blockchain.size()) |
| 3997 | { |
| 3998 | if (!(current_index % 1024)) |
| 3999 | LOG_PRINT_L2( "Skipped block by height: " << current_index); |
| 4000 | m_blockchain.push_back(bl_id); |
| 4001 | |
| 4002 | if (0 != m_callback) |
| 4003 | { // FIXME: this isn't right, but simplewallet just logs that we got a block. |
| 4004 | cryptonote::block dummy; |
| 4005 | m_callback->on_new_block(current_index, dummy); |
| 4006 | } |
| 4007 | } |
| 4008 | else if(bl_id != m_blockchain[current_index]) |
| 4009 | { |
| 4010 | //split detected here !!! |
| 4011 | return; |
| 4012 | } |
| 4013 | ++current_index; |
| 4014 | if (current_index >= stop_height) |
| 4015 | return; |
| 4016 | } |
| 4017 | } |
| 4018 | } |
| 4019 | |
| 4020 | |
| 4021 | bool wallet2::add_address_book_row(const cryptonote::account_public_address &address, const crypto::hash8 *payment_id, const std::string &description, bool is_subaddress) |
| 4022 | { |
| 4023 | wallet2::address_book_row a; |
| 4024 | a.m_address = address; |
| 4025 | a.m_has_payment_id = !!payment_id; |
| 4026 | a.m_payment_id = payment_id ? *payment_id : crypto::null_hash8; |
| 4027 | a.m_description = description; |
| 4028 | a.m_is_subaddress = is_subaddress; |
| 4029 | |
| 4030 | auto old_size = m_address_book.size(); |
| 4031 | m_address_book.push_back(a); |
| 4032 | if(m_address_book.size() == old_size+1) |
| 4033 | return true; |
| 4034 | return false; |
| 4035 | } |
| 4036 | |
| 4037 | bool wallet2::set_address_book_row(size_t row_id, const cryptonote::account_public_address &address, const crypto::hash8 *payment_id, const std::string &description, bool is_subaddress) |
| 4038 | { |
| 4039 | wallet2::address_book_row a; |
| 4040 | a.m_address = address; |
| 4041 | a.m_has_payment_id = !!payment_id; |
| 4042 | a.m_payment_id = payment_id ? *payment_id : crypto::null_hash8; |
| 4043 | a.m_description = description; |
| 4044 | a.m_is_subaddress = is_subaddress; |
| 4045 | |
| 4046 | const auto size = m_address_book.size(); |
| 4047 | if (row_id >= size) |
| 4048 | return false; |
| 4049 | m_address_book[row_id] = a; |
| 4050 | return true; |
| 4051 | } |
| 4052 | |
| 4053 | bool wallet2::delete_address_book_row(std::size_t row_id) { |
| 4054 | if(m_address_book.size() <= row_id) |
| 4055 | return false; |
| 4056 | |
| 4057 | m_address_book.erase(m_address_book.begin()+row_id); |
| 4058 | |
| 4059 | return true; |
| 4060 | } |
| 4061 | |
| 4062 | //---------------------------------------------------------------------------------------------------- |
| 4063 | std::shared_ptr<std::map<std::pair<uint64_t, uint64_t>, size_t>> wallet2::create_output_tracker_cache() const |
| 4064 | { |
| 4065 | std::shared_ptr<std::map<std::pair<uint64_t, uint64_t>, size_t>> cache{new std::map<std::pair<uint64_t, uint64_t>, size_t>()}; |
| 4066 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 4067 | { |
| 4068 | const transfer_details &td = m_transfers[i]; |
| 4069 | (*cache)[std::make_pair(td.is_rct() ? 0 : td.amount(), td.m_global_output_index)] = i; |
| 4070 | } |
| 4071 | return cache; |
| 4072 | } |
| 4073 | //---------------------------------------------------------------------------------------------------- |
| 4074 | void wallet2::refresh(bool trusted_daemon, uint64_t start_height, uint64_t & blocks_fetched, bool& received_money, bool check_pool, bool try_incremental, uint64_t max_blocks) |
| 4075 | { |
| 4076 | if (m_offline) |
| 4077 | { |
| 4078 | blocks_fetched = 0; |
| 4079 | received_money = 0; |
| 4080 | return; |
| 4081 | } |
| 4082 | |
| 4083 | if(m_light_wallet) { |
| 4084 | |
| 4085 | // MyMonero get_address_info needs to be called occasionally to trigger wallet sync. |
| 4086 | // This call is not really needed for other purposes and can be removed if mymonero changes their backend. |
| 4087 | tools::COMMAND_RPC_GET_ADDRESS_INFO::response res; |
| 4088 | |
| 4089 | // Get basic info |
| 4090 | if(light_wallet_get_address_info(res)) { |
| 4091 | // Last stored block height |
| 4092 | uint64_t prev_height = m_light_wallet_blockchain_height; |
| 4093 | // Update lw heights |
| 4094 | m_light_wallet_scanned_block_height = res.scanned_block_height; |
| 4095 | m_light_wallet_blockchain_height = res.blockchain_height; |
| 4096 | // If new height - call new_block callback |
| 4097 | if(m_light_wallet_blockchain_height != prev_height) |
| 4098 | { |
| 4099 | MDEBUG("new block since last time!"); |
| 4100 | m_callback->on_lw_new_block(m_light_wallet_blockchain_height - 1); |
| 4101 | } |
| 4102 | m_light_wallet_connected = true; |
| 4103 | MDEBUG("lw scanned block height: " << m_light_wallet_scanned_block_height); |
| 4104 | MDEBUG("lw blockchain height: " << m_light_wallet_blockchain_height); |
| 4105 | MDEBUG(m_light_wallet_blockchain_height-m_light_wallet_scanned_block_height << " blocks behind"); |
| 4106 | // TODO: add wallet created block info |
| 4107 | |
| 4108 | light_wallet_get_address_txs(); |
| 4109 | } else |
| 4110 | m_light_wallet_connected = false; |
| 4111 | |
| 4112 | // Lighwallet refresh done |
| 4113 | return; |
| 4114 | } |
| 4115 | |
| 4116 | if (!m_first_refresh_done) |
| 4117 | { |
| 4118 | // We want to process the whole pool again, in case we identify received outputs in the chain we might have spent in the pool |
| 4119 | m_pool_info_query_time = 0; |
| 4120 | m_scanned_pool_txs[0].clear(); |
| 4121 | m_scanned_pool_txs[1].clear(); |
| 4122 | // Clear unconfirmed (received) payments because the data is 100% recovered when scanning |
| 4123 | m_unconfirmed_payments.clear(); |
| 4124 | // Don't clear unconfirmed (sent) txs because some data is not recover-able when scanning (dests) |
| 4125 | } |
| 4126 | |
| 4127 | received_money = false; |
| 4128 | blocks_fetched = 0; |
| 4129 | uint64_t added_blocks = 0; |
| 4130 | size_t try_count = 0; |
| 4131 | crypto::hash last_tx_hash_id = m_transfers.size() ? m_transfers.back().m_txid : null_hash; |
| 4132 | std::list<crypto::hash> short_chain_history; |
| 4133 | tools::threadpool& tpool = tools::threadpool::getInstanceForCompute(); |
| 4134 | tools::threadpool::waiter waiter(tpool); |
| 4135 | uint64_t blocks_start_height; |
| 4136 | std::vector<cryptonote::block_complete_entry> blocks; |
| 4137 | std::vector<parsed_block> parsed_blocks; |
| 4138 | bool refreshed = false; |
| 4139 | std::shared_ptr<std::map<std::pair<uint64_t, uint64_t>, size_t>> output_tracker_cache; |
| 4140 | hw::device &hwdev = m_account.get_device(); |
| 4141 | |
| 4142 | // pull the first set of blocks |
| 4143 | get_short_chain_history(short_chain_history, (m_first_refresh_done || trusted_daemon) ? 1 : FIRST_REFRESH_GRANULARITY); |
| 4144 | m_run.store(true, std::memory_order_relaxed); |
| 4145 | if (start_height > m_blockchain.size() || m_refresh_from_block_height > m_blockchain.size() || m_skip_to_height > m_blockchain.size()) { |
| 4146 | if (!start_height) |
| 4147 | start_height = std::max(m_refresh_from_block_height, m_skip_to_height);; |
| 4148 | // we can shortcut by only pulling hashes up to the start_height |
| 4149 | fast_refresh(start_height, blocks_start_height, short_chain_history); |
| 4150 | // regenerate the history now that we've got a full set of hashes |
| 4151 | short_chain_history.clear(); |
| 4152 | get_short_chain_history(short_chain_history, (m_first_refresh_done || trusted_daemon) ? 1 : FIRST_REFRESH_GRANULARITY); |
| 4153 | start_height = 0; |
| 4154 | // and then fall through to regular refresh processing |
| 4155 | } |
| 4156 | |
| 4157 | // If stop() is called during fast refresh we don't need to continue |
| 4158 | if(!m_run.load(std::memory_order_relaxed)) |
| 4159 | return; |
| 4160 | // always reset start_height to 0 to force short_chain_ history to be used on |
| 4161 | // subsequent pulls in this refresh. |
| 4162 | start_height = 0; |
| 4163 | |
| 4164 | auto keys_reencryptor = epee::misc_utils::create_scope_leave_handler([&, this]() { |
| 4165 | m_encrypt_keys_after_refresh.reset(); |
| 4166 | }); |
| 4167 | |
| 4168 | auto scope_exit_handler_hwdev = epee::misc_utils::create_scope_leave_handler([&](){hwdev.computing_key_images(false);}); |
| 4169 | |
| 4170 | m_process_pool_txs.clear(); |
| 4171 | // Getting and processing the pool state has moved down into method 'pull_blocks' to |
| 4172 | // allow for "conventional" as well as "incremental" update. However the following |
| 4173 | // principle of getting all info first (pool AND blocks) and only process txs afterwards |
| 4174 | // still holds and is still respected: |
| 4175 | // get updated pool state first, but do not process those txes just yet, |
| 4176 | // since that might cause a password prompt, which would introduce a data |
| 4177 | // leak allowing a passive adversary with traffic analysis capability to |
| 4178 | // infer when we get an incoming output |
| 4179 | |
| 4180 | bool first = true, last = false; |
| 4181 | while(m_run.load(std::memory_order_relaxed) && blocks_fetched < max_blocks) |
| 4182 | { |
| 4183 | uint64_t next_blocks_start_height; |
| 4184 | std::vector<cryptonote::block_complete_entry> next_blocks; |
| 4185 | std::vector<parsed_block> next_parsed_blocks; |
| 4186 | bool error; |
| 4187 | std::exception_ptr exception; |
| 4188 | try |
| 4189 | { |
| 4190 | // pull the next set of blocks while we're processing the current one |
| 4191 | error = false; |
| 4192 | exception = NULL; |
| 4193 | next_blocks.clear(); |
| 4194 | next_parsed_blocks.clear(); |
| 4195 | added_blocks = 0; |
| 4196 | if (!first && blocks.empty()) |
| 4197 | { |
| 4198 | m_node_rpc_proxy.set_height(m_blockchain.size()); |
| 4199 | break; |
| 4200 | } |
| 4201 | if (!last) |
| 4202 | tpool.submit(&waiter, [&]{pull_and_parse_next_blocks(first, try_incremental, start_height, next_blocks_start_height, short_chain_history, blocks, parsed_blocks, next_blocks, next_parsed_blocks, last, error, exception);}); |
| 4203 | |
| 4204 | if (!first) |
| 4205 | { |
| 4206 | try |
| 4207 | { |
| 4208 | process_parsed_blocks(blocks_start_height, blocks, parsed_blocks, added_blocks, output_tracker_cache.get()); |
| 4209 | } |
| 4210 | catch (const tools::error::out_of_hashchain_bounds_error&) |
| 4211 | { |
| 4212 | MINFO("Daemon claims next refresh block is out of hash chain bounds, resetting hash chain"); |
| 4213 | uint64_t stop_height = m_blockchain.offset(); |
| 4214 | std::vector<crypto::hash> tip(m_blockchain.size() - m_blockchain.offset()); |
| 4215 | for (size_t i = m_blockchain.offset(); i < m_blockchain.size(); ++i) |
| 4216 | tip[i - m_blockchain.offset()] = m_blockchain[i]; |
| 4217 | cryptonote::block b; |
| 4218 | generate_genesis(b); |
| 4219 | m_blockchain.clear(); |
| 4220 | m_blockchain.push_back(get_block_hash(b)); |
| 4221 | short_chain_history.clear(); |
| 4222 | get_short_chain_history(short_chain_history); |
| 4223 | fast_refresh(stop_height, blocks_start_height, short_chain_history, true); |
| 4224 | THROW_WALLET_EXCEPTION_IF((m_blockchain.size() == stop_height || (m_blockchain.size() == 1 && stop_height == 0) ? false : true), error::wallet_internal_error, "Unexpected hashchain size"); |
| 4225 | THROW_WALLET_EXCEPTION_IF(m_blockchain.offset() != 0, error::wallet_internal_error, "Unexpected hashchain offset"); |
| 4226 | for (const auto &h: tip) |
| 4227 | m_blockchain.push_back(h); |
| 4228 | short_chain_history.clear(); |
| 4229 | get_short_chain_history(short_chain_history); |
| 4230 | start_height = stop_height; |
| 4231 | throw std::runtime_error(""); // loop again |
| 4232 | } |
| 4233 | catch (const std::exception &e) |
| 4234 | { |
| 4235 | MERROR("Error parsing blocks: " << e.what()); |
| 4236 | exception = std::current_exception(); |
| 4237 | error = true; |
| 4238 | } |
| 4239 | blocks_fetched += added_blocks; |
| 4240 | } |
| 4241 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4242 | |
| 4243 | // handle error from async fetching thread |
| 4244 | if (error) |
| 4245 | { |
| 4246 | if (exception) |
| 4247 | std::rethrow_exception(exception); |
| 4248 | else |
| 4249 | throw std::runtime_error("proxy exception in refresh thread"); |
| 4250 | } |
| 4251 | |
| 4252 | m_has_ever_refreshed_from_node = true; |
| 4253 | |
| 4254 | if(!first && blocks_start_height == next_blocks_start_height) |
| 4255 | { |
| 4256 | m_node_rpc_proxy.set_height(m_blockchain.size()); |
| 4257 | break; |
| 4258 | } |
| 4259 | |
| 4260 | first = false; |
| 4261 | |
| 4262 | // if we've got at least 10 blocks to refresh, assume we're starting |
| 4263 | // a long refresh, and setup a tracking output cache if we need to |
| 4264 | if (m_track_uses && (!output_tracker_cache || output_tracker_cache->empty()) && next_blocks.size() >= 10) |
| 4265 | output_tracker_cache = create_output_tracker_cache(); |
| 4266 | |
| 4267 | // switch to the new blocks from the daemon |
| 4268 | blocks_start_height = next_blocks_start_height; |
| 4269 | blocks = std::move(next_blocks); |
| 4270 | parsed_blocks = std::move(next_parsed_blocks); |
| 4271 | } |
| 4272 | catch (const tools::error::password_needed&) |
| 4273 | { |
| 4274 | blocks_fetched += added_blocks; |
| 4275 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4276 | throw; |
| 4277 | } |
| 4278 | catch (const error::payment_required&) |
| 4279 | { |
| 4280 | // no point in trying again, it'd just eat up credits |
| 4281 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4282 | throw; |
| 4283 | } |
| 4284 | catch (const error::reorg_depth_error&) |
| 4285 | { |
| 4286 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4287 | throw; |
| 4288 | } |
| 4289 | catch (const error::incorrect_fork_version&) |
| 4290 | { |
| 4291 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4292 | throw; |
| 4293 | } |
| 4294 | catch (const std::exception&) |
| 4295 | { |
| 4296 | blocks_fetched += added_blocks; |
| 4297 | THROW_WALLET_EXCEPTION_IF(!waiter.wait(), error::wallet_internal_error, "Exception in thread pool"); |
| 4298 | if(try_count < 3) |
| 4299 | { |
| 4300 | LOG_PRINT_L1("Another try pull_blocks (try_count=" << try_count << ")..."); |
| 4301 | first = true; |
| 4302 | last = false; |
| 4303 | start_height = 0; |
| 4304 | blocks.clear(); |
| 4305 | parsed_blocks.clear(); |
| 4306 | short_chain_history.clear(); |
| 4307 | get_short_chain_history(short_chain_history, 1); |
| 4308 | ++try_count; |
| 4309 | } |
| 4310 | else |
| 4311 | { |
| 4312 | LOG_ERROR("pull_blocks failed, try_count=" << try_count); |
| 4313 | throw; |
| 4314 | } |
| 4315 | } |
| 4316 | } |
| 4317 | if(last_tx_hash_id != (m_transfers.size() ? m_transfers.back().m_txid : null_hash)) |
| 4318 | received_money = true; |
| 4319 | |
| 4320 | try |
| 4321 | { |
| 4322 | // If stop() is called we don't need to check pending transactions |
| 4323 | if (check_pool && m_run.load(std::memory_order_relaxed) && !m_process_pool_txs.empty()) |
| 4324 | process_pool_state(m_process_pool_txs); |
| 4325 | } |
| 4326 | catch (...) |
| 4327 | { |
| 4328 | LOG_PRINT_L1("Failed to check pending transactions"); |
| 4329 | } |
| 4330 | |
| 4331 | m_first_refresh_done = true; |
| 4332 | if (m_background_syncing || m_is_background_wallet) |
| 4333 | m_background_sync_data.first_refresh_done = true; |
| 4334 | |
| 4335 | m_multisig_rescan_info = std::vector<std::vector<tools::wallet2::multisig_info>>{}; |
| 4336 | for (auto &v: m_multisig_rescan_k) |
| 4337 | memwipe(v.data(), v.size() * sizeof(v[0])); |
| 4338 | |
| 4339 | m_multisig_rescan_k = std::vector<std::vector<rct::key>>{}; |
| 4340 | |
| 4341 | LOG_PRINT_L1("Refresh done, blocks received: " << blocks_fetched << ", balance (all accounts): " << print_money(balance_all(false)) << ", unlocked: " << print_money(unlocked_balance_all(false))); |
| 4342 | } |
| 4343 | //---------------------------------------------------------------------------------------------------- |
| 4344 | bool wallet2::refresh(bool trusted_daemon, uint64_t & blocks_fetched, bool& received_money, bool& ok) |
| 4345 | { |
| 4346 | try |
| 4347 | { |
| 4348 | refresh(trusted_daemon, 0, blocks_fetched, received_money); |
| 4349 | ok = true; |
| 4350 | } |
| 4351 | catch (...) |
| 4352 | { |
| 4353 | ok = false; |
| 4354 | } |
| 4355 | return ok; |
| 4356 | } |
| 4357 | //---------------------------------------------------------------------------------------------------- |
| 4358 | bool wallet2::get_rct_distribution(uint64_t &start_height, std::vector<uint64_t> &distribution) |
| 4359 | { |
| 4360 | MDEBUG("Requesting rct distribution"); |
| 4361 | |
| 4362 | cryptonote::COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::request req = AUTO_VAL_INIT(req); |
| 4363 | cryptonote::COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::response res = AUTO_VAL_INIT(res); |
| 4364 | req.amounts.push_back(0); |
| 4365 | req.from_height = 0; |
| 4366 | req.cumulative = false; |
| 4367 | req.binary = true; |
| 4368 | req.compress = true; |
| 4369 | |
| 4370 | bool r; |
| 4371 | try |
| 4372 | { |
| 4373 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 4374 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 4375 | req.client = get_client_signature(); |
| 4376 | r = net_utils::invoke_http_bin("/get_output_distribution.bin", req, res, *m_http_client, rpc_timeout); |
| 4377 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "/get_output_distribution.bin"); |
| 4378 | check_rpc_cost("/get_output_distribution.bin", res.credits, pre_call_credits, COST_PER_OUTPUT_DISTRIBUTION_0); |
| 4379 | } |
| 4380 | catch(...) |
| 4381 | { |
| 4382 | return false; |
| 4383 | } |
| 4384 | if (res.distributions.size() != 1) |
| 4385 | { |
| 4386 | MWARNING("Failed to request output distribution: not the expected single result"); |
| 4387 | return false; |
| 4388 | } |
| 4389 | if (res.distributions[0].amount != 0) |
| 4390 | { |
| 4391 | MWARNING("Failed to request output distribution: results are not for amount 0"); |
| 4392 | return false; |
| 4393 | } |
| 4394 | for (size_t i = 1; i < res.distributions[0].data.distribution.size(); ++i) |
| 4395 | res.distributions[0].data.distribution[i] += res.distributions[0].data.distribution[i-1]; |
| 4396 | start_height = res.distributions[0].data.start_height; |
| 4397 | distribution = std::move(res.distributions[0].data.distribution); |
| 4398 | return true; |
| 4399 | } |
| 4400 | //---------------------------------------------------------------------------------------------------- |
| 4401 | wallet2::detached_blockchain_data wallet2::detach_blockchain(uint64_t height, std::map<std::pair<uint64_t, uint64_t>, size_t> *output_tracker_cache) |
| 4402 | { |
| 4403 | LOG_PRINT_L0("Detaching blockchain on height " << height); |
| 4404 | detached_blockchain_data dbd; |
| 4405 | |
| 4406 | size_t transfers_detached = 0; |
| 4407 | |
| 4408 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 4409 | { |
| 4410 | wallet2::transfer_details &td = m_transfers[i]; |
| 4411 | if (td.m_spent && td.m_spent_height >= height) |
| 4412 | { |
| 4413 | LOG_PRINT_L1("Resetting spent/frozen status for output " << i << ": " << td.m_key_image); |
| 4414 | set_unspent(i); |
| 4415 | thaw(i); |
| 4416 | } |
| 4417 | } |
| 4418 | |
| 4419 | for (transfer_details &td: m_transfers) |
| 4420 | { |
| 4421 | while (!td.m_uses.empty() && td.m_uses.back().first >= height) |
| 4422 | td.m_uses.pop_back(); |
| 4423 | } |
| 4424 | |
| 4425 | for (auto it = m_background_sync_data.txs.begin(); it != m_background_sync_data.txs.end(); ) |
| 4426 | { |
| 4427 | if(height <= it->second.height) |
| 4428 | it = m_background_sync_data.txs.erase(it); |
| 4429 | else |
| 4430 | ++it; |
| 4431 | } |
| 4432 | |
| 4433 | if (output_tracker_cache) |
| 4434 | output_tracker_cache->clear(); |
| 4435 | |
| 4436 | auto it = std::find_if(m_transfers.begin(), m_transfers.end(), [&](const transfer_details& td){return td.m_block_height >= height;}); |
| 4437 | size_t i_start = it - m_transfers.begin(); |
| 4438 | |
| 4439 | for(size_t i = i_start; i!= m_transfers.size();i++) |
| 4440 | { |
| 4441 | if (!m_transfers[i].m_key_image_known || m_transfers[i].m_key_image_partial) |
| 4442 | continue; |
| 4443 | auto it_ki = m_key_images.find(m_transfers[i].m_key_image); |
| 4444 | THROW_WALLET_EXCEPTION_IF(it_ki == m_key_images.end(), error::wallet_internal_error, "key image not found: index " + std::to_string(i) + ", ki " + epee::string_tools::pod_to_hex(m_transfers[i].m_key_image) + ", " + std::to_string(m_key_images.size()) + " key images known"); |
| 4445 | m_key_images.erase(it_ki); |
| 4446 | } |
| 4447 | |
| 4448 | for(size_t i = i_start; i!= m_transfers.size();i++) |
| 4449 | { |
| 4450 | auto it_pk = m_pub_keys.find(m_transfers[i].get_public_key()); |
| 4451 | THROW_WALLET_EXCEPTION_IF(it_pk == m_pub_keys.end(), error::wallet_internal_error, "public key not found"); |
| 4452 | m_pub_keys.erase(it_pk); |
| 4453 | } |
| 4454 | |
| 4455 | transfers_detached = std::distance(it, m_transfers.end()); |
| 4456 | dbd.detached_tx_hashes.reserve(transfers_detached); |
| 4457 | for (size_t i = i_start; i!=m_transfers.size();i++) |
| 4458 | dbd.detached_tx_hashes.insert(std::move(m_transfers[i].m_txid)); |
| 4459 | MDEBUG(transfers_detached << " transfers detached / expected " << dbd.detached_tx_hashes.size()); |
| 4460 | m_transfers.erase(it, m_transfers.end()); |
| 4461 | |
| 4462 | size_t blocks_detached = 0; |
| 4463 | dbd.original_chain_size = m_blockchain.size(); |
| 4464 | if (height >= m_blockchain.offset()) |
| 4465 | { |
| 4466 | for (size_t i = height; i < m_blockchain.size(); ++i) |
| 4467 | dbd.detached_blockchain.push_back(m_blockchain[i]); |
| 4468 | blocks_detached = m_blockchain.size() - height; |
| 4469 | m_blockchain.crop(height); |
| 4470 | MDEBUG(blocks_detached << " blocks detached / expected " << dbd.detached_blockchain.size()); |
| 4471 | } |
| 4472 | |
| 4473 | for (auto it = m_payments.begin(); it != m_payments.end(); ) |
| 4474 | { |
| 4475 | if(height <= it->second.m_block_height) |
| 4476 | { |
| 4477 | dbd.detached_tx_hashes.insert(it->second.m_tx_hash); |
| 4478 | it = m_payments.erase(it); |
| 4479 | } |
| 4480 | else |
| 4481 | ++it; |
| 4482 | } |
| 4483 | |
| 4484 | for (auto it = m_confirmed_txs.begin(); it != m_confirmed_txs.end(); ) |
| 4485 | { |
| 4486 | if(height <= it->second.m_block_height) |
| 4487 | { |
| 4488 | dbd.detached_tx_hashes.insert(it->first); |
| 4489 | dbd.detached_confirmed_txs_dests[it->first] = std::move(it->second.m_dests); |
| 4490 | it = m_confirmed_txs.erase(it); |
| 4491 | } |
| 4492 | else |
| 4493 | ++it; |
| 4494 | } |
| 4495 | |
| 4496 | LOG_PRINT_L0("Detached blockchain on height " << height << ", transfers detached " << transfers_detached << ", blocks detached " << blocks_detached); |
| 4497 | return dbd; |
| 4498 | } |
| 4499 | //---------------------------------------------------------------------------------------------------- |
| 4500 | void wallet2::handle_reorg(uint64_t height, std::map<std::pair<uint64_t, uint64_t>, size_t> *output_tracker_cache) |
| 4501 | { |
| 4502 | // size 1 2 3 4 5 6 7 8 9 |
| 4503 | // block 0 1 2 3 4 5 6 7 8 |
| 4504 | // C |
| 4505 | THROW_WALLET_EXCEPTION_IF(height < m_blockchain.offset() && m_blockchain.size() > m_blockchain.offset(), |
| 4506 | error::wallet_internal_error, "Daemon claims reorg below last checkpoint"); |
| 4507 | |
| 4508 | detached_blockchain_data dbd = detach_blockchain(height, output_tracker_cache); |
| 4509 | |
| 4510 | if (m_background_syncing && height < m_background_sync_data.start_height) |
| 4511 | m_background_sync_data.start_height = height; |
| 4512 | |
| 4513 | if (m_callback) |
| 4514 | m_callback->on_reorg(height, dbd.detached_blockchain.size(), dbd.detached_tx_hashes.size()); |
| 4515 | } |
| 4516 | //---------------------------------------------------------------------------------------------------- |
| 4517 | bool wallet2::deinit() |
| 4518 | { |
| 4519 | if(m_is_initialized) { |
| 4520 | m_is_initialized = false; |
| 4521 | unlock_keys_file(); |
| 4522 | unlock_background_keys_file(); |
| 4523 | m_account.deinit(); |
| 4524 | } |
| 4525 | return true; |
| 4526 | } |
| 4527 | //---------------------------------------------------------------------------------------------------- |
| 4528 | bool wallet2::clear() |
| 4529 | { |
| 4530 | m_blockchain.clear(); |
| 4531 | m_transfers.clear(); |
| 4532 | m_key_images.clear(); |
| 4533 | m_pub_keys.clear(); |
| 4534 | m_unconfirmed_txs.clear(); |
| 4535 | m_payments.clear(); |
| 4536 | m_tx_keys.clear(); |
| 4537 | m_additional_tx_keys.clear(); |
| 4538 | m_confirmed_txs.clear(); |
| 4539 | m_unconfirmed_payments.clear(); |
| 4540 | m_scanned_pool_txs[0].clear(); |
| 4541 | m_scanned_pool_txs[1].clear(); |
| 4542 | m_address_book.clear(); |
| 4543 | m_subaddresses.clear(); |
| 4544 | m_subaddress_labels.clear(); |
| 4545 | m_multisig_rounds_passed = 0; |
| 4546 | m_device_last_key_image_sync = 0; |
| 4547 | m_pool_info_query_time = 0; |
| 4548 | m_skip_to_height = 0; |
| 4549 | m_background_sync_data = background_sync_data_t{}; |
| 4550 | return true; |
| 4551 | } |
| 4552 | //---------------------------------------------------------------------------------------------------- |
| 4553 | void wallet2::clear_soft(bool keep_key_images) |
| 4554 | { |
| 4555 | m_blockchain.clear(); |
| 4556 | m_transfers.clear(); |
| 4557 | if (!keep_key_images) |
| 4558 | m_key_images.clear(); |
| 4559 | m_pub_keys.clear(); |
| 4560 | m_unconfirmed_txs.clear(); |
| 4561 | m_payments.clear(); |
| 4562 | m_confirmed_txs.clear(); |
| 4563 | m_unconfirmed_payments.clear(); |
| 4564 | m_scanned_pool_txs[0].clear(); |
| 4565 | m_scanned_pool_txs[1].clear(); |
| 4566 | m_pool_info_query_time = 0; |
| 4567 | m_skip_to_height = 0; |
| 4568 | m_background_sync_data = background_sync_data_t{}; |
| 4569 | |
| 4570 | cryptonote::block b; |
| 4571 | generate_genesis(b); |
| 4572 | m_blockchain.push_back(get_block_hash(b)); |
| 4573 | m_last_block_reward = cryptonote::get_outs_money_amount(b.miner_tx); |
| 4574 | } |
| 4575 | //---------------------------------------------------------------------------------------------------- |
| 4576 | void wallet2::clear_user_data() |
| 4577 | { |
| 4578 | for (auto i = m_confirmed_txs.begin(); i != m_confirmed_txs.end(); ++i) |
| 4579 | i->second.m_dests.clear(); |
| 4580 | for (auto i = m_unconfirmed_txs.begin(); i != m_unconfirmed_txs.end(); ++i) |
| 4581 | i->second.m_dests.clear(); |
| 4582 | for (auto i = m_transfers.begin(); i != m_transfers.end(); ++i) |
| 4583 | i->m_frozen = false; |
| 4584 | m_tx_keys.clear(); |
| 4585 | m_tx_notes.clear(); |
| 4586 | m_address_book.clear(); |
| 4587 | m_subaddress_labels.clear(); |
| 4588 | m_attributes.clear(); |
| 4589 | m_account_tags = std::pair<serializable_map<std::string, std::string>, std::vector<std::string>>(); |
| 4590 | } |
| 4591 | //---------------------------------------------------------------------------------------------------- |
| 4592 | /*! |
| 4593 | * \brief Stores wallet information to wallet file. |
| 4594 | * \param keys_file_name Name of wallet file |
| 4595 | * \param password Password of wallet file |
| 4596 | * \param watch_only true to save only view key, false to save both spend and view keys |
| 4597 | * \return Whether it was successful. |
| 4598 | */ |
| 4599 | bool wallet2::store_keys(const std::string& keys_file_name, const epee::wipeable_string& password, bool watch_only) |
| 4600 | { |
| 4601 | boost::optional<wallet2::keys_file_data> keys_file_data = get_keys_file_data(password, watch_only); |
| 4602 | CHECK_AND_ASSERT_MES(keys_file_data != boost::none, false, "failed to generate wallet keys data"); |
| 4603 | return store_keys_file_data(keys_file_name, keys_file_data.get()); |
| 4604 | } |
| 4605 | //---------------------------------------------------------------------------------------------------- |
| 4606 | bool wallet2::store_keys(const std::string& keys_file_name, const crypto::chacha_key& key, bool watch_only, bool background_keys_file) |
| 4607 | { |
| 4608 | boost::optional<wallet2::keys_file_data> keys_file_data = get_keys_file_data(key, watch_only, background_keys_file); |
| 4609 | CHECK_AND_ASSERT_MES(keys_file_data != boost::none, false, "failed to generate wallet keys data"); |
| 4610 | return store_keys_file_data(keys_file_name, keys_file_data.get(), background_keys_file); |
| 4611 | } |
| 4612 | //---------------------------------------------------------------------------------------------------- |
| 4613 | bool wallet2::store_keys_file_data(const std::string& keys_file_name, wallet2::keys_file_data &keys_file_data, bool background_keys_file) |
| 4614 | { |
| 4615 | std::string tmp_file_name = keys_file_name + ".new"; |
| 4616 | std::string buf; |
| 4617 | bool r = ::serialization::dump_binary(keys_file_data, buf); |
| 4618 | r = r && save_to_file(tmp_file_name, buf); |
| 4619 | CHECK_AND_ASSERT_MES(r, false, "failed to generate wallet keys file " << tmp_file_name); |
| 4620 | |
| 4621 | if (!background_keys_file) |
| 4622 | unlock_keys_file(); |
| 4623 | else |
| 4624 | unlock_background_keys_file(); |
| 4625 | |
| 4626 | std::error_code e = tools::replace_file(tmp_file_name, keys_file_name); |
| 4627 | |
| 4628 | if (!background_keys_file) |
| 4629 | lock_keys_file(); |
| 4630 | else |
| 4631 | lock_background_keys_file(keys_file_name); |
| 4632 | |
| 4633 | if (e) { |
| 4634 | boost::filesystem::remove(tmp_file_name); |
| 4635 | LOG_ERROR("failed to update wallet keys file " << keys_file_name); |
| 4636 | return false; |
| 4637 | } |
| 4638 | |
| 4639 | return true; |
| 4640 | } |
| 4641 | //---------------------------------------------------------------------------------------------------- |
| 4642 | boost::optional<wallet2::keys_file_data> wallet2::get_keys_file_data(const epee::wipeable_string& password, bool watch_only) |
| 4643 | { |
| 4644 | crypto::chacha_key key; |
| 4645 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 4646 | verify_password_with_cached_key(key); |
| 4647 | return get_keys_file_data(key, watch_only); |
| 4648 | } |
| 4649 | //---------------------------------------------------------------------------------------------------- |
| 4650 | boost::optional<wallet2::keys_file_data> wallet2::get_keys_file_data(const crypto::chacha_key& key, bool watch_only, bool background_keys_file) |
| 4651 | { |
| 4652 | epee::byte_slice account_data; |
| 4653 | std::string multisig_signers; |
| 4654 | std::string multisig_derivations; |
| 4655 | cryptonote::account_base account = m_account; |
| 4656 | |
| 4657 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 4658 | { |
| 4659 | account.encrypt_viewkey(key); |
| 4660 | account.decrypt_keys(key); |
| 4661 | } |
| 4662 | |
| 4663 | if (watch_only || background_keys_file) |
| 4664 | account.forget_spend_key(); |
| 4665 | |
| 4666 | account.encrypt_keys(key); |
| 4667 | |
| 4668 | bool r = epee::serialization::store_t_to_binary(account, account_data); |
| 4669 | CHECK_AND_ASSERT_MES(r, boost::none, "failed to serialize wallet keys"); |
| 4670 | boost::optional<wallet2::keys_file_data> keys_file_data = (wallet2::keys_file_data) {}; |
| 4671 | |
| 4672 | // Create a JSON object with "key_data" and "seed_language" as keys. |
| 4673 | rapidjson::Document json; |
| 4674 | json.SetObject(); |
| 4675 | rapidjson::Value value(rapidjson::kStringType); |
| 4676 | value.SetString(reinterpret_cast<const char*>(account_data.data()), account_data.size()); |
| 4677 | json.AddMember("key_data", value, json.GetAllocator()); |
| 4678 | if (!seed_language.empty()) |
| 4679 | { |
| 4680 | value.SetString(seed_language.c_str(), seed_language.length()); |
| 4681 | json.AddMember("seed_language", value, json.GetAllocator()); |
| 4682 | } |
| 4683 | |
| 4684 | rapidjson::Value value2(rapidjson::kNumberType); |
| 4685 | |
| 4686 | value2.SetInt(m_key_device_type); |
| 4687 | json.AddMember("key_on_device", value2, json.GetAllocator()); |
| 4688 | |
| 4689 | value2.SetInt((watch_only || m_watch_only) ? 1 :0); // WTF ? JSON has different true and false types, and not boolean ?? |
| 4690 | json.AddMember("watch_only", value2, json.GetAllocator()); |
| 4691 | |
| 4692 | value2.SetInt(m_multisig ? 1 :0); |
| 4693 | json.AddMember("multisig", value2, json.GetAllocator()); |
| 4694 | |
| 4695 | value2.SetUint(m_multisig_threshold); |
| 4696 | json.AddMember("multisig_threshold", value2, json.GetAllocator()); |
| 4697 | |
| 4698 | if (m_multisig) |
| 4699 | { |
| 4700 | bool r = ::serialization::dump_binary(m_multisig_signers, multisig_signers); |
| 4701 | CHECK_AND_ASSERT_MES(r, boost::none, "failed to serialize wallet multisig signers"); |
| 4702 | value.SetString(multisig_signers.c_str(), multisig_signers.length()); |
| 4703 | json.AddMember("multisig_signers", value, json.GetAllocator()); |
| 4704 | |
| 4705 | r = ::serialization::dump_binary(m_multisig_derivations, multisig_derivations); |
| 4706 | CHECK_AND_ASSERT_MES(r, boost::none, "failed to serialize wallet multisig derivations"); |
| 4707 | value.SetString(multisig_derivations.c_str(), multisig_derivations.length()); |
| 4708 | json.AddMember("multisig_derivations", value, json.GetAllocator()); |
| 4709 | |
| 4710 | value2.SetUint(m_multisig_rounds_passed); |
| 4711 | json.AddMember("multisig_rounds_passed", value2, json.GetAllocator()); |
| 4712 | } |
| 4713 | |
| 4714 | value2.SetInt(m_always_confirm_transfers ? 1 :0); |
| 4715 | json.AddMember("always_confirm_transfers", value2, json.GetAllocator()); |
| 4716 | |
| 4717 | value2.SetInt(m_print_ring_members ? 1 :0); |
| 4718 | json.AddMember("print_ring_members", value2, json.GetAllocator()); |
| 4719 | |
| 4720 | value2.SetInt(m_store_tx_info ? 1 :0); |
| 4721 | json.AddMember("store_tx_info", value2, json.GetAllocator()); |
| 4722 | |
| 4723 | value2.SetUint(m_default_mixin); |
| 4724 | json.AddMember("default_mixin", value2, json.GetAllocator()); |
| 4725 | |
| 4726 | value2.SetUint(m_default_priority); |
| 4727 | json.AddMember("default_priority", value2, json.GetAllocator()); |
| 4728 | |
| 4729 | value2.SetInt(m_auto_refresh ? 1 :0); |
| 4730 | json.AddMember("auto_refresh", value2, json.GetAllocator()); |
| 4731 | |
| 4732 | value2.SetInt(m_refresh_type); |
| 4733 | json.AddMember("refresh_type", value2, json.GetAllocator()); |
| 4734 | |
| 4735 | value2.SetUint64(m_refresh_from_block_height); |
| 4736 | json.AddMember("refresh_height", value2, json.GetAllocator()); |
| 4737 | |
| 4738 | value2.SetUint64(m_skip_to_height); |
| 4739 | json.AddMember("skip_to_height", value2, json.GetAllocator()); |
| 4740 | |
| 4741 | value2.SetInt(m_confirm_non_default_ring_size ? 1 :0); |
| 4742 | json.AddMember("confirm_non_default_ring_size", value2, json.GetAllocator()); |
| 4743 | |
| 4744 | value2.SetInt(m_ask_password); |
| 4745 | json.AddMember("ask_password", value2, json.GetAllocator()); |
| 4746 | |
| 4747 | value2.SetUint64(m_max_reorg_depth); |
| 4748 | json.AddMember("max_reorg_depth", value2, json.GetAllocator()); |
| 4749 | |
| 4750 | value2.SetUint(m_min_output_count); |
| 4751 | json.AddMember("min_output_count", value2, json.GetAllocator()); |
| 4752 | |
| 4753 | value2.SetUint64(m_min_output_value); |
| 4754 | json.AddMember("min_output_value", value2, json.GetAllocator()); |
| 4755 | |
| 4756 | value2.SetInt(cryptonote::get_default_decimal_point()); |
| 4757 | json.AddMember("default_decimal_point", value2, json.GetAllocator()); |
| 4758 | |
| 4759 | value2.SetInt(m_merge_destinations ? 1 :0); |
| 4760 | json.AddMember("merge_destinations", value2, json.GetAllocator()); |
| 4761 | |
| 4762 | value2.SetInt(m_confirm_backlog ? 1 :0); |
| 4763 | json.AddMember("confirm_backlog", value2, json.GetAllocator()); |
| 4764 | |
| 4765 | value2.SetUint(m_confirm_backlog_threshold); |
| 4766 | json.AddMember("confirm_backlog_threshold", value2, json.GetAllocator()); |
| 4767 | |
| 4768 | value2.SetInt(m_confirm_export_overwrite ? 1 :0); |
| 4769 | json.AddMember("confirm_export_overwrite", value2, json.GetAllocator()); |
| 4770 | |
| 4771 | value2.SetInt(m_auto_low_priority ? 1 : 0); |
| 4772 | json.AddMember("auto_low_priority", value2, json.GetAllocator()); |
| 4773 | |
| 4774 | value2.SetUint(m_nettype); |
| 4775 | json.AddMember("nettype", value2, json.GetAllocator()); |
| 4776 | |
| 4777 | value2.SetInt(m_segregate_pre_fork_outputs ? 1 : 0); |
| 4778 | json.AddMember("segregate_pre_fork_outputs", value2, json.GetAllocator()); |
| 4779 | |
| 4780 | value2.SetInt(m_key_reuse_mitigation2 ? 1 : 0); |
| 4781 | json.AddMember("key_reuse_mitigation2", value2, json.GetAllocator()); |
| 4782 | |
| 4783 | value2.SetUint(m_segregation_height); |
| 4784 | json.AddMember("segregation_height", value2, json.GetAllocator()); |
| 4785 | |
| 4786 | value2.SetInt(m_ignore_fractional_outputs ? 1 : 0); |
| 4787 | json.AddMember("ignore_fractional_outputs", value2, json.GetAllocator()); |
| 4788 | |
| 4789 | value2.SetUint64(m_ignore_outputs_above); |
| 4790 | json.AddMember("ignore_outputs_above", value2, json.GetAllocator()); |
| 4791 | |
| 4792 | value2.SetUint64(m_ignore_outputs_below); |
| 4793 | json.AddMember("ignore_outputs_below", value2, json.GetAllocator()); |
| 4794 | |
| 4795 | value2.SetInt(m_track_uses ? 1 : 0); |
| 4796 | json.AddMember("track_uses", value2, json.GetAllocator()); |
| 4797 | |
| 4798 | value2.SetInt(m_background_sync_type); |
| 4799 | json.AddMember("background_sync_type", value2, json.GetAllocator()); |
| 4800 | |
| 4801 | value2.SetInt(m_show_wallet_name_when_locked ? 1 : 0); |
| 4802 | json.AddMember("show_wallet_name_when_locked", value2, json.GetAllocator()); |
| 4803 | |
| 4804 | value2.SetInt(m_inactivity_lock_timeout); |
| 4805 | json.AddMember("inactivity_lock_timeout", value2, json.GetAllocator()); |
| 4806 | |
| 4807 | value2.SetInt(m_setup_background_mining); |
| 4808 | json.AddMember("setup_background_mining", value2, json.GetAllocator()); |
| 4809 | |
| 4810 | value2.SetUint(m_subaddress_lookahead_major); |
| 4811 | json.AddMember("subaddress_lookahead_major", value2, json.GetAllocator()); |
| 4812 | |
| 4813 | value2.SetUint(m_subaddress_lookahead_minor); |
| 4814 | json.AddMember("subaddress_lookahead_minor", value2, json.GetAllocator()); |
| 4815 | |
| 4816 | value2.SetInt(m_original_keys_available ? 1 : 0); |
| 4817 | json.AddMember("original_keys_available", value2, json.GetAllocator()); |
| 4818 | |
| 4819 | value2.SetInt(m_export_format); |
| 4820 | json.AddMember("export_format", value2, json.GetAllocator()); |
| 4821 | |
| 4822 | value2.SetInt(m_load_deprecated_formats); |
| 4823 | json.AddMember("load_deprecated_formats", value2, json.GetAllocator()); |
| 4824 | |
| 4825 | value2.SetUint(1); |
| 4826 | json.AddMember("encrypted_secret_keys", value2, json.GetAllocator()); |
| 4827 | |
| 4828 | value.SetString(m_device_name.c_str(), m_device_name.size()); |
| 4829 | json.AddMember("device_name", value, json.GetAllocator()); |
| 4830 | |
| 4831 | value.SetString(m_device_derivation_path.c_str(), m_device_derivation_path.size()); |
| 4832 | json.AddMember("device_derivation_path", value, json.GetAllocator()); |
| 4833 | |
| 4834 | std::string original_address; |
| 4835 | std::string original_view_secret_key; |
| 4836 | if (m_original_keys_available) |
| 4837 | { |
| 4838 | original_address = get_account_address_as_str(m_nettype, false, m_original_address); |
| 4839 | value.SetString(original_address.c_str(), original_address.length()); |
| 4840 | json.AddMember("original_address", value, json.GetAllocator()); |
| 4841 | original_view_secret_key = epee::string_tools::pod_to_hex(unwrap(unwrap(m_original_view_secret_key))); |
| 4842 | value.SetString(original_view_secret_key.c_str(), original_view_secret_key.length()); |
| 4843 | json.AddMember("original_view_secret_key", value, json.GetAllocator()); |
| 4844 | } |
| 4845 | |
| 4846 | value2.SetInt(m_persistent_rpc_client_id ? 1 : 0); |
| 4847 | json.AddMember("persistent_rpc_client_id", value2, json.GetAllocator()); |
| 4848 | |
| 4849 | value2.SetFloat(m_auto_mine_for_rpc_payment_threshold); |
| 4850 | json.AddMember("auto_mine_for_rpc_payment", value2, json.GetAllocator()); |
| 4851 | |
| 4852 | value2.SetUint64(m_credits_target); |
| 4853 | json.AddMember("credits_target", value2, json.GetAllocator()); |
| 4854 | |
| 4855 | value2.SetInt(m_enable_multisig ? 1 : 0); |
| 4856 | json.AddMember("enable_multisig", value2, json.GetAllocator()); |
| 4857 | |
| 4858 | if (m_background_sync_type == BackgroundSyncCustomPassword && !background_keys_file && m_custom_background_key) |
| 4859 | { |
| 4860 | value.SetString(reinterpret_cast<const char*>(m_custom_background_key.get().data()), m_custom_background_key.get().size()); |
| 4861 | json.AddMember("custom_background_key", value, json.GetAllocator()); |
| 4862 | } |
| 4863 | |
| 4864 | // Serialize the JSON object |
| 4865 | rapidjson::StringBuffer buffer; |
| 4866 | rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); |
| 4867 | json.Accept(writer); |
| 4868 | |
| 4869 | // Encrypt the entire JSON object. |
| 4870 | std::string cipher; |
| 4871 | cipher.resize(buffer.GetSize()); |
| 4872 | keys_file_data.get().iv = crypto::rand<crypto::chacha_iv>(); |
| 4873 | crypto::chacha20(buffer.GetString(), buffer.GetSize(), key, keys_file_data.get().iv, &cipher[0]); |
| 4874 | keys_file_data.get().account_data = cipher; |
| 4875 | return keys_file_data; |
| 4876 | } |
| 4877 | //---------------------------------------------------------------------------------------------------- |
| 4878 | void wallet2::setup_keys(const epee::wipeable_string &password) |
| 4879 | { |
| 4880 | crypto::chacha_key key; |
| 4881 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 4882 | |
| 4883 | // re-encrypt, but keep viewkey unencrypted |
| 4884 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 4885 | { |
| 4886 | m_account.encrypt_keys(key); |
| 4887 | m_account.decrypt_viewkey(key); |
| 4888 | } |
| 4889 | |
| 4890 | m_cache_key = derive_cache_key(key, config::HASH_KEY_WALLET_CACHE); |
| 4891 | |
| 4892 | get_ringdb_key(); |
| 4893 | } |
| 4894 | //---------------------------------------------------------------------------------------------------- |
| 4895 | void validate_background_cache_password_usage(const tools::wallet2::BackgroundSyncType background_sync_type, const boost::optional<epee::wipeable_string> &background_cache_password, const bool multisig, const bool watch_only, const bool key_on_device) |
| 4896 | { |
| 4897 | THROW_WALLET_EXCEPTION_IF(multisig || watch_only || key_on_device, error::wallet_internal_error, multisig |
| 4898 | ? "Background sync not implemented for multisig wallets" : watch_only |
| 4899 | ? "Background sync not implemented for view only wallets" |
| 4900 | : "Background sync not implemented for HW wallets"); |
| 4901 | |
| 4902 | switch (background_sync_type) |
| 4903 | { |
| 4904 | case tools::wallet2::BackgroundSyncOff: |
| 4905 | { |
| 4906 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, "background sync is not enabled"); |
| 4907 | break; |
| 4908 | } |
| 4909 | case tools::wallet2::BackgroundSyncReusePassword: |
| 4910 | { |
| 4911 | THROW_WALLET_EXCEPTION_IF(background_cache_password, error::wallet_internal_error, |
| 4912 | "unexpected custom background cache password"); |
| 4913 | break; |
| 4914 | } |
| 4915 | case tools::wallet2::BackgroundSyncCustomPassword: |
| 4916 | { |
| 4917 | THROW_WALLET_EXCEPTION_IF(!background_cache_password, error::wallet_internal_error, |
| 4918 | "expected custom background cache password"); |
| 4919 | break; |
| 4920 | } |
| 4921 | default: THROW_WALLET_EXCEPTION(error::wallet_internal_error, "unknown background sync type"); |
| 4922 | } |
| 4923 | } |
| 4924 | //---------------------------------------------------------------------------------------------------- |
| 4925 | void get_custom_background_key(const epee::wipeable_string &password, crypto::chacha_key &custom_background_key, const uint64_t kdf_rounds) |
| 4926 | { |
| 4927 | crypto::chacha_key key; |
| 4928 | crypto::generate_chacha_key(password.data(), password.size(), key, kdf_rounds); |
| 4929 | custom_background_key = derive_cache_key(key, config::HASH_KEY_BACKGROUND_KEYS_FILE); |
| 4930 | } |
| 4931 | //---------------------------------------------------------------------------------------------------- |
| 4932 | const crypto::chacha_key wallet2::get_cache_key() |
| 4933 | { |
| 4934 | if (m_background_sync_type == BackgroundSyncCustomPassword && m_background_syncing) |
| 4935 | { |
| 4936 | THROW_WALLET_EXCEPTION_IF(!m_custom_background_key, error::wallet_internal_error, "Custom background key not set"); |
| 4937 | // Domain separate keys used to encrypt background keys file and cache |
| 4938 | return derive_cache_key(m_custom_background_key.get(), config::HASH_KEY_BACKGROUND_CACHE); |
| 4939 | } |
| 4940 | else |
| 4941 | { |
| 4942 | return m_cache_key; |
| 4943 | } |
| 4944 | } |
| 4945 | //---------------------------------------------------------------------------------------------------- |
| 4946 | void wallet2::verify_password_with_cached_key(const epee::wipeable_string &password) |
| 4947 | { |
| 4948 | crypto::chacha_key key; |
| 4949 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 4950 | verify_password_with_cached_key(key); |
| 4951 | } |
| 4952 | //---------------------------------------------------------------------------------------------------- |
| 4953 | void wallet2::verify_password_with_cached_key(const crypto::chacha_key &key) |
| 4954 | { |
| 4955 | // We use m_cache_key as a deterministic test to see if given key corresponds to original password |
| 4956 | const crypto::chacha_key cache_key = derive_cache_key(key, config::HASH_KEY_WALLET_CACHE); |
| 4957 | THROW_WALLET_EXCEPTION_IF(cache_key != m_cache_key, error::invalid_password); |
| 4958 | } |
| 4959 | //---------------------------------------------------------------------------------------------------- |
| 4960 | void wallet2::change_password(const std::string &filename, const epee::wipeable_string &original_password, const epee::wipeable_string &new_password) |
| 4961 | { |
| 4962 | THROW_WALLET_EXCEPTION_IF(m_background_syncing || m_is_background_wallet, error::wallet_internal_error, |
| 4963 | "cannot change password from background wallet"); |
| 4964 | |
| 4965 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 4966 | decrypt_keys(original_password); |
| 4967 | setup_keys(new_password); |
| 4968 | if (!filename.empty()) |
| 4969 | store_to(filename, new_password, true); // force rewrite keys file to possible new location |
| 4970 | } |
| 4971 | //---------------------------------------------------------------------------------------------------- |
| 4972 | /*! |
| 4973 | * \brief Load wallet information from wallet file. |
| 4974 | * \param keys_file_name Name of wallet file |
| 4975 | * \param password Password of wallet file |
| 4976 | */ |
| 4977 | bool wallet2::load_keys(const std::string& keys_file_name, const epee::wipeable_string& password) |
| 4978 | { |
| 4979 | std::string keys_file_buf; |
| 4980 | bool r = load_from_file(keys_file_name, keys_file_buf); |
| 4981 | THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, keys_file_name); |
| 4982 | |
| 4983 | // Load keys from buffer |
| 4984 | boost::optional<crypto::chacha_key> keys_to_encrypt; |
| 4985 | r = wallet2::load_keys_buf(keys_file_buf, password, keys_to_encrypt); |
| 4986 | |
| 4987 | // Rewrite with encrypted keys if unencrypted, ignore errors |
| 4988 | if (r && keys_to_encrypt != boost::none) |
| 4989 | { |
| 4990 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 4991 | encrypt_keys(keys_to_encrypt.get()); |
| 4992 | bool saved_ret = store_keys(keys_file_name, password, m_watch_only); |
| 4993 | if (!saved_ret) |
| 4994 | { |
| 4995 | // just moan a bit, but not fatal |
| 4996 | MERROR("Error saving keys file with encrypted keys, not fatal"); |
| 4997 | } |
| 4998 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 4999 | decrypt_keys(keys_to_encrypt.get()); |
| 5000 | m_keys_file_locker.reset(); |
| 5001 | } |
| 5002 | return r; |
| 5003 | } |
| 5004 | //---------------------------------------------------------------------------------------------------- |
| 5005 | bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_string& password) { |
| 5006 | boost::optional<crypto::chacha_key> keys_to_encrypt; |
| 5007 | return wallet2::load_keys_buf(keys_buf, password, keys_to_encrypt); |
| 5008 | } |
| 5009 | //---------------------------------------------------------------------------------------------------- |
| 5010 | bool wallet2::load_keys_buf(const std::string& keys_buf, const epee::wipeable_string& password, boost::optional<crypto::chacha_key>& keys_to_encrypt) { |
| 5011 | |
| 5012 | // Decrypt the contents |
| 5013 | rapidjson::Document json; |
| 5014 | wallet2::keys_file_data keys_file_data; |
| 5015 | bool encrypted_secret_keys = false; |
| 5016 | bool r = ::serialization::parse_binary(keys_buf, keys_file_data); |
| 5017 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "internal error: failed to deserialize keys buffer"); |
| 5018 | crypto::chacha_key key; |
| 5019 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 5020 | std::string account_data; |
| 5021 | account_data.resize(keys_file_data.account_data.size()); |
| 5022 | crypto::chacha20(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5023 | const bool try_v0_format = json.Parse(account_data.c_str()).HasParseError() || !json.IsObject(); |
| 5024 | if (try_v0_format) |
| 5025 | crypto::chacha8(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5026 | |
| 5027 | // Check if it's a background keys file if both of the above formats fail |
| 5028 | { |
| 5029 | m_is_background_wallet = false; |
| 5030 | m_background_syncing = false; |
| 5031 | cryptonote::account_base account_data_check; |
| 5032 | if (try_v0_format && !epee::serialization::load_t_from_binary(account_data_check, account_data)) |
| 5033 | { |
| 5034 | get_custom_background_key(password, key, m_kdf_rounds); |
| 5035 | crypto::chacha20(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5036 | m_is_background_wallet = !json.Parse(account_data.c_str()).HasParseError() && json.IsObject(); |
| 5037 | m_background_syncing = m_is_background_wallet; // start a background wallet background syncing |
| 5038 | } |
| 5039 | } |
| 5040 | |
| 5041 | // The contents should be JSON if the wallet follows the new format. |
| 5042 | if (json.Parse(account_data.c_str()).HasParseError()) |
| 5043 | { |
| 5044 | is_old_file_format = true; |
| 5045 | m_watch_only = false; |
| 5046 | m_multisig = false; |
| 5047 | m_multisig_threshold = 0; |
| 5048 | m_multisig_signers.clear(); |
| 5049 | m_multisig_rounds_passed = 0; |
| 5050 | m_multisig_derivations.clear(); |
| 5051 | m_always_confirm_transfers = false; |
| 5052 | m_print_ring_members = false; |
| 5053 | m_store_tx_info = true; |
| 5054 | m_default_mixin = 0; |
| 5055 | m_default_priority = 0; |
| 5056 | m_auto_refresh = true; |
| 5057 | m_refresh_type = RefreshType::RefreshDefault; |
| 5058 | m_refresh_from_block_height = 0; |
| 5059 | m_skip_to_height = 0; |
| 5060 | m_confirm_non_default_ring_size = true; |
| 5061 | m_ask_password = AskPasswordToDecrypt; |
| 5062 | cryptonote::set_default_decimal_point(CRYPTONOTE_DISPLAY_DECIMAL_POINT); |
| 5063 | m_max_reorg_depth = ORPHANED_BLOCKS_MAX_COUNT; |
| 5064 | m_min_output_count = 0; |
| 5065 | m_min_output_value = 0; |
| 5066 | m_merge_destinations = false; |
| 5067 | m_confirm_backlog = true; |
| 5068 | m_confirm_backlog_threshold = 0; |
| 5069 | m_confirm_export_overwrite = true; |
| 5070 | m_auto_low_priority = true; |
| 5071 | m_segregate_pre_fork_outputs = true; |
| 5072 | m_key_reuse_mitigation2 = true; |
| 5073 | m_segregation_height = 0; |
| 5074 | m_ignore_fractional_outputs = true; |
| 5075 | m_ignore_outputs_above = MONEY_SUPPLY; |
| 5076 | m_ignore_outputs_below = 0; |
| 5077 | m_track_uses = false; |
| 5078 | m_background_sync_type = BackgroundSyncOff; |
| 5079 | m_show_wallet_name_when_locked = false; |
| 5080 | m_inactivity_lock_timeout = DEFAULT_INACTIVITY_LOCK_TIMEOUT; |
| 5081 | m_setup_background_mining = BackgroundMiningMaybe; |
| 5082 | m_subaddress_lookahead_major = SUBADDRESS_LOOKAHEAD_MAJOR; |
| 5083 | m_subaddress_lookahead_minor = SUBADDRESS_LOOKAHEAD_MINOR; |
| 5084 | m_original_keys_available = false; |
| 5085 | m_export_format = ExportFormat::Binary; |
| 5086 | m_load_deprecated_formats = false; |
| 5087 | m_device_name = ""; |
| 5088 | m_device_derivation_path = ""; |
| 5089 | m_key_device_type = hw::device::device_type::SOFTWARE; |
| 5090 | encrypted_secret_keys = false; |
| 5091 | m_persistent_rpc_client_id = false; |
| 5092 | m_auto_mine_for_rpc_payment_threshold = -1.0f; |
| 5093 | m_credits_target = 0; |
| 5094 | m_enable_multisig = false; |
| 5095 | m_allow_mismatched_daemon_version = false; |
| 5096 | m_custom_background_key = boost::none; |
| 5097 | } |
| 5098 | else if(json.IsObject()) |
| 5099 | { |
| 5100 | if (!json.HasMember("key_data")) |
| 5101 | { |
| 5102 | LOG_ERROR("Field key_data not found in JSON"); |
| 5103 | return false; |
| 5104 | } |
| 5105 | if (!json["key_data"].IsString()) |
| 5106 | { |
| 5107 | LOG_ERROR("Field key_data found in JSON, but not String"); |
| 5108 | return false; |
| 5109 | } |
| 5110 | const char *field_key_data = json["key_data"].GetString(); |
| 5111 | account_data = std::string(field_key_data, field_key_data + json["key_data"].GetStringLength()); |
| 5112 | |
| 5113 | if (json.HasMember("key_on_device")) |
| 5114 | { |
| 5115 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, key_on_device, int, Int, false, hw::device::device_type::SOFTWARE); |
| 5116 | m_key_device_type = static_cast<hw::device::device_type>(field_key_on_device); |
| 5117 | } |
| 5118 | |
| 5119 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, seed_language, std::string, String, false, std::string()); |
| 5120 | if (field_seed_language_found) |
| 5121 | { |
| 5122 | set_seed_language(field_seed_language); |
| 5123 | } |
| 5124 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, watch_only, int, Int, false, false); |
| 5125 | m_watch_only = field_watch_only; |
| 5126 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, multisig, int, Int, false, false); |
| 5127 | m_multisig = field_multisig; |
| 5128 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, multisig_threshold, unsigned int, Uint, m_multisig, 0); |
| 5129 | m_multisig_threshold = field_multisig_threshold; |
| 5130 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, multisig_rounds_passed, unsigned int, Uint, false, 0); |
| 5131 | m_multisig_rounds_passed = field_multisig_rounds_passed; |
| 5132 | if (m_multisig) |
| 5133 | { |
| 5134 | if (!json.HasMember("multisig_signers")) |
| 5135 | { |
| 5136 | LOG_ERROR("Field multisig_signers not found in JSON"); |
| 5137 | return false; |
| 5138 | } |
| 5139 | if (!json["multisig_signers"].IsString()) |
| 5140 | { |
| 5141 | LOG_ERROR("Field multisig_signers found in JSON, but not String"); |
| 5142 | return false; |
| 5143 | } |
| 5144 | const char *field_multisig_signers = json["multisig_signers"].GetString(); |
| 5145 | std::string multisig_signers = std::string(field_multisig_signers, field_multisig_signers + json["multisig_signers"].GetStringLength()); |
| 5146 | r = ::serialization::parse_binary(multisig_signers, m_multisig_signers); |
| 5147 | if (!r) |
| 5148 | { |
| 5149 | LOG_ERROR("Field multisig_signers found in JSON, but failed to parse"); |
| 5150 | return false; |
| 5151 | } |
| 5152 | |
| 5153 | //previous version of multisig does not have this field |
| 5154 | if (json.HasMember("multisig_derivations")) |
| 5155 | { |
| 5156 | if (!json["multisig_derivations"].IsString()) |
| 5157 | { |
| 5158 | LOG_ERROR("Field multisig_derivations found in JSON, but not String"); |
| 5159 | return false; |
| 5160 | } |
| 5161 | const char *field_multisig_derivations = json["multisig_derivations"].GetString(); |
| 5162 | std::string multisig_derivations = std::string(field_multisig_derivations, field_multisig_derivations + json["multisig_derivations"].GetStringLength()); |
| 5163 | r = ::serialization::parse_binary(multisig_derivations, m_multisig_derivations); |
| 5164 | if (!r) |
| 5165 | { |
| 5166 | LOG_ERROR("Field multisig_derivations found in JSON, but failed to parse"); |
| 5167 | return false; |
| 5168 | } |
| 5169 | } |
| 5170 | } |
| 5171 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, always_confirm_transfers, int, Int, false, true); |
| 5172 | m_always_confirm_transfers = field_always_confirm_transfers; |
| 5173 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, print_ring_members, int, Int, false, true); |
| 5174 | m_print_ring_members = field_print_ring_members; |
| 5175 | if (json.HasMember("store_tx_info")) |
| 5176 | { |
| 5177 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, store_tx_info, int, Int, true, true); |
| 5178 | m_store_tx_info = field_store_tx_info; |
| 5179 | } |
| 5180 | else if (json.HasMember("store_tx_keys")) // backward compatibility |
| 5181 | { |
| 5182 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, store_tx_keys, int, Int, true, true); |
| 5183 | m_store_tx_info = field_store_tx_keys; |
| 5184 | } |
| 5185 | else |
| 5186 | m_store_tx_info = true; |
| 5187 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, default_mixin, unsigned int, Uint, false, 0); |
| 5188 | m_default_mixin = field_default_mixin; |
| 5189 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, default_priority, unsigned int, Uint, false, 0); |
| 5190 | if (field_default_priority_found) |
| 5191 | { |
| 5192 | m_default_priority = field_default_priority; |
| 5193 | } |
| 5194 | else |
| 5195 | { |
| 5196 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, default_fee_multiplier, unsigned int, Uint, false, 0); |
| 5197 | if (field_default_fee_multiplier_found) |
| 5198 | m_default_priority = field_default_fee_multiplier; |
| 5199 | else |
| 5200 | m_default_priority = 0; |
| 5201 | } |
| 5202 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, auto_refresh, int, Int, false, true); |
| 5203 | m_auto_refresh = field_auto_refresh; |
| 5204 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, refresh_type, int, Int, false, RefreshType::RefreshDefault); |
| 5205 | m_refresh_type = RefreshType::RefreshDefault; |
| 5206 | if (field_refresh_type_found) |
| 5207 | { |
| 5208 | if (field_refresh_type == RefreshFull || field_refresh_type == RefreshOptimizeCoinbase || field_refresh_type == RefreshNoCoinbase) |
| 5209 | m_refresh_type = (RefreshType)field_refresh_type; |
| 5210 | else |
| 5211 | LOG_PRINT_L0("Unknown refresh-type value (" << field_refresh_type << "), using default"); |
| 5212 | } |
| 5213 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, refresh_height, uint64_t, Uint64, false, 0); |
| 5214 | m_refresh_from_block_height = field_refresh_height; |
| 5215 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, skip_to_height, uint64_t, Uint64, false, 0); |
| 5216 | m_skip_to_height = field_skip_to_height; |
| 5217 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, confirm_non_default_ring_size, int, Int, false, true); |
| 5218 | m_confirm_non_default_ring_size = field_confirm_non_default_ring_size; |
| 5219 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, ask_password, AskPasswordType, Int, false, AskPasswordToDecrypt); |
| 5220 | m_ask_password = field_ask_password; |
| 5221 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, default_decimal_point, int, Int, false, CRYPTONOTE_DISPLAY_DECIMAL_POINT); |
| 5222 | cryptonote::set_default_decimal_point(field_default_decimal_point); |
| 5223 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, max_reorg_depth, uint64_t, Uint64, false, ORPHANED_BLOCKS_MAX_COUNT); |
| 5224 | m_max_reorg_depth = field_max_reorg_depth; |
| 5225 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, min_output_count, uint32_t, Uint, false, 0); |
| 5226 | m_min_output_count = field_min_output_count; |
| 5227 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, min_output_value, uint64_t, Uint64, false, 0); |
| 5228 | m_min_output_value = field_min_output_value; |
| 5229 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, merge_destinations, int, Int, false, false); |
| 5230 | m_merge_destinations = field_merge_destinations; |
| 5231 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, confirm_backlog, int, Int, false, true); |
| 5232 | m_confirm_backlog = field_confirm_backlog; |
| 5233 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, confirm_backlog_threshold, uint32_t, Uint, false, 0); |
| 5234 | m_confirm_backlog_threshold = field_confirm_backlog_threshold; |
| 5235 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, confirm_export_overwrite, int, Int, false, true); |
| 5236 | m_confirm_export_overwrite = field_confirm_export_overwrite; |
| 5237 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, auto_low_priority, int, Int, false, true); |
| 5238 | m_auto_low_priority = field_auto_low_priority; |
| 5239 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, nettype, uint8_t, Uint, false, static_cast<uint8_t>(m_nettype)); |
| 5240 | // The network type given in the program argument is inconsistent with the network type saved in the wallet |
| 5241 | THROW_WALLET_EXCEPTION_IF(static_cast<uint8_t>(m_nettype) != field_nettype, error::wallet_internal_error, |
| 5242 | (boost::format("%s wallet cannot be opened as %s wallet") |
| 5243 | % (field_nettype == 0 ? "Mainnet" : field_nettype == 1 ? "Testnet" : "Stagenet") |
| 5244 | % (m_nettype == MAINNET ? "mainnet" : m_nettype == TESTNET ? "testnet" : "stagenet")).str()); |
| 5245 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, segregate_pre_fork_outputs, int, Int, false, true); |
| 5246 | m_segregate_pre_fork_outputs = field_segregate_pre_fork_outputs; |
| 5247 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, key_reuse_mitigation2, int, Int, false, true); |
| 5248 | m_key_reuse_mitigation2 = field_key_reuse_mitigation2; |
| 5249 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, segregation_height, int, Uint, false, 0); |
| 5250 | m_segregation_height = field_segregation_height; |
| 5251 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, ignore_fractional_outputs, int, Int, false, true); |
| 5252 | m_ignore_fractional_outputs = field_ignore_fractional_outputs; |
| 5253 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, ignore_outputs_above, uint64_t, Uint64, false, MONEY_SUPPLY); |
| 5254 | m_ignore_outputs_above = field_ignore_outputs_above; |
| 5255 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, ignore_outputs_below, uint64_t, Uint64, false, 0); |
| 5256 | m_ignore_outputs_below = field_ignore_outputs_below; |
| 5257 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, track_uses, int, Int, false, false); |
| 5258 | m_track_uses = field_track_uses; |
| 5259 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, show_wallet_name_when_locked, int, Int, false, false); |
| 5260 | m_show_wallet_name_when_locked = field_show_wallet_name_when_locked; |
| 5261 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, inactivity_lock_timeout, uint32_t, Uint, false, DEFAULT_INACTIVITY_LOCK_TIMEOUT); |
| 5262 | m_inactivity_lock_timeout = field_inactivity_lock_timeout; |
| 5263 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, setup_background_mining, BackgroundMiningSetupType, Int, false, BackgroundMiningMaybe); |
| 5264 | m_setup_background_mining = field_setup_background_mining; |
| 5265 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, subaddress_lookahead_major, uint32_t, Uint, false, SUBADDRESS_LOOKAHEAD_MAJOR); |
| 5266 | m_subaddress_lookahead_major = field_subaddress_lookahead_major; |
| 5267 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, subaddress_lookahead_minor, uint32_t, Uint, false, SUBADDRESS_LOOKAHEAD_MINOR); |
| 5268 | m_subaddress_lookahead_minor = field_subaddress_lookahead_minor; |
| 5269 | |
| 5270 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, encrypted_secret_keys, uint32_t, Uint, false, false); |
| 5271 | encrypted_secret_keys = field_encrypted_secret_keys; |
| 5272 | |
| 5273 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, export_format, ExportFormat, Int, false, Binary); |
| 5274 | m_export_format = field_export_format; |
| 5275 | |
| 5276 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, load_deprecated_formats, int, Int, false, false); |
| 5277 | m_load_deprecated_formats = field_load_deprecated_formats; |
| 5278 | |
| 5279 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, device_name, std::string, String, false, std::string()); |
| 5280 | if (m_device_name.empty()) |
| 5281 | { |
| 5282 | if (field_device_name_found) |
| 5283 | { |
| 5284 | m_device_name = field_device_name; |
| 5285 | } |
| 5286 | else |
| 5287 | { |
| 5288 | m_device_name = m_key_device_type == hw::device::device_type::LEDGER ? "Ledger" : "default"; |
| 5289 | } |
| 5290 | } |
| 5291 | |
| 5292 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, device_derivation_path, std::string, String, false, std::string()); |
| 5293 | m_device_derivation_path = field_device_derivation_path; |
| 5294 | |
| 5295 | if (json.HasMember("original_keys_available")) |
| 5296 | { |
| 5297 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, original_keys_available, int, Int, false, false); |
| 5298 | m_original_keys_available = field_original_keys_available; |
| 5299 | if (m_original_keys_available) |
| 5300 | { |
| 5301 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, original_address, std::string, String, true, std::string()); |
| 5302 | address_parse_info info; |
| 5303 | bool ok = get_account_address_from_str(info, m_nettype, field_original_address); |
| 5304 | if (!ok) |
| 5305 | { |
| 5306 | LOG_ERROR("Failed to parse original_address from JSON"); |
| 5307 | return false; |
| 5308 | } |
| 5309 | m_original_address = info.address; |
| 5310 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, original_view_secret_key, std::string, String, true, std::string()); |
| 5311 | ok = epee::string_tools::hex_to_pod(field_original_view_secret_key, m_original_view_secret_key); |
| 5312 | if (!ok) |
| 5313 | { |
| 5314 | LOG_ERROR("Failed to parse original_view_secret_key from JSON"); |
| 5315 | return false; |
| 5316 | } |
| 5317 | } |
| 5318 | } |
| 5319 | else |
| 5320 | { |
| 5321 | m_original_keys_available = false; |
| 5322 | } |
| 5323 | |
| 5324 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, persistent_rpc_client_id, int, Int, false, false); |
| 5325 | m_persistent_rpc_client_id = field_persistent_rpc_client_id; |
| 5326 | // save as float, load as double, because it can happen you can't load back as float... |
| 5327 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, auto_mine_for_rpc_payment, float, Double, false, FLT_MAX); |
| 5328 | m_auto_mine_for_rpc_payment_threshold = field_auto_mine_for_rpc_payment; |
| 5329 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, credits_target, uint64_t, Uint64, false, 0); |
| 5330 | m_credits_target = field_credits_target; |
| 5331 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, enable_multisig, int, Int, false, false); |
| 5332 | m_enable_multisig = field_enable_multisig; |
| 5333 | |
| 5334 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, background_sync_type, BackgroundSyncType, Int, false, BackgroundSyncOff); |
| 5335 | m_background_sync_type = field_background_sync_type; |
| 5336 | |
| 5337 | // Load encryption key used to encrypt background cache |
| 5338 | crypto::chacha_key custom_background_key; |
| 5339 | m_custom_background_key = boost::none; |
| 5340 | if (m_background_sync_type == BackgroundSyncCustomPassword && !m_is_background_wallet) |
| 5341 | { |
| 5342 | if (!json.HasMember("custom_background_key")) |
| 5343 | { |
| 5344 | LOG_ERROR("Field custom_background_key not found in JSON"); |
| 5345 | return false; |
| 5346 | } |
| 5347 | else if (!json["custom_background_key"].IsString()) |
| 5348 | { |
| 5349 | LOG_ERROR("Field custom_background_key found in JSON, but not String"); |
| 5350 | return false; |
| 5351 | } |
| 5352 | else if (json["custom_background_key"].GetStringLength() != sizeof(crypto::chacha_key)) |
| 5353 | { |
| 5354 | LOG_ERROR("Field custom_background_key found in JSON, but not correct length"); |
| 5355 | return false; |
| 5356 | } |
| 5357 | const char *field_custom_background_key = json["custom_background_key"].GetString(); |
| 5358 | memcpy(custom_background_key.data(), field_custom_background_key, sizeof(crypto::chacha_key)); |
| 5359 | m_custom_background_key = boost::optional<crypto::chacha_key>(custom_background_key); |
| 5360 | LOG_PRINT_L1("Loaded custom background key derived from custom password"); |
| 5361 | } |
| 5362 | else if (json.HasMember("custom_background_key")) |
| 5363 | { |
| 5364 | LOG_ERROR("Unexpected field custom_background_key found in JSON"); |
| 5365 | } |
| 5366 | } |
| 5367 | else |
| 5368 | { |
| 5369 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, "invalid password"); |
| 5370 | return false; |
| 5371 | } |
| 5372 | |
| 5373 | r = epee::serialization::load_t_from_binary(m_account, account_data); |
| 5374 | THROW_WALLET_EXCEPTION_IF(!r, error::invalid_password); |
| 5375 | if (m_key_device_type == hw::device::device_type::LEDGER || m_key_device_type == hw::device::device_type::TREZOR) { |
| 5376 | LOG_PRINT_L0("Account on device. Initing device..."); |
| 5377 | hw::device &hwdev = lookup_device(m_device_name); |
| 5378 | THROW_WALLET_EXCEPTION_IF(!hwdev.set_name(m_device_name), error::wallet_internal_error, "Could not set device name " + m_device_name); |
| 5379 | hwdev.set_network_type(m_nettype); |
| 5380 | hwdev.set_derivation_path(m_device_derivation_path); |
| 5381 | hwdev.set_callback(get_device_callback()); |
| 5382 | THROW_WALLET_EXCEPTION_IF(!hwdev.init(), error::wallet_internal_error, "Could not initialize the device " + m_device_name); |
| 5383 | THROW_WALLET_EXCEPTION_IF(!hwdev.connect(), error::wallet_internal_error, "Could not connect to the device " + m_device_name); |
| 5384 | m_account.set_device(hwdev); |
| 5385 | |
| 5386 | account_public_address device_account_public_address; |
| 5387 | bool fetch_device_address = true; |
| 5388 | |
| 5389 | ::hw::device_cold* dev_cold = nullptr; |
| 5390 | if (m_key_device_type == hw::device::device_type::TREZOR && (dev_cold = dynamic_cast<::hw::device_cold*>(&hwdev)) != nullptr) { |
| 5391 | THROW_WALLET_EXCEPTION_IF(!dev_cold->get_public_address_with_no_passphrase(device_account_public_address), error::wallet_internal_error, "Cannot get a device address"); |
| 5392 | if (device_account_public_address == m_account.get_keys().m_account_address) { |
| 5393 | LOG_PRINT_L0("Wallet opened with an empty passphrase"); |
| 5394 | fetch_device_address = false; |
| 5395 | dev_cold->set_use_empty_passphrase(true); |
| 5396 | } else { |
| 5397 | fetch_device_address = true; |
| 5398 | LOG_PRINT_L0("Wallet opening with an empty passphrase failed. Retry again: " << fetch_device_address); |
| 5399 | dev_cold->reset_session(); |
| 5400 | } |
| 5401 | } |
| 5402 | |
| 5403 | if (fetch_device_address) { |
| 5404 | THROW_WALLET_EXCEPTION_IF(!hwdev.get_public_address(device_account_public_address), error::wallet_internal_error, "Cannot get a device address"); |
| 5405 | } |
| 5406 | |
| 5407 | THROW_WALLET_EXCEPTION_IF(device_account_public_address != m_account.get_keys().m_account_address, error::wallet_internal_error, "Device wallet does not match wallet address. If the device uses the passphrase feature, please check whether the passphrase was entered correctly (it may have been misspelled - different passphrases generate different wallets, passphrase is case-sensitive). " |
| 5408 | "Device address: " + cryptonote::get_account_address_as_str(m_nettype, false, device_account_public_address) + |
| 5409 | ", wallet address: " + m_account.get_public_address_str(m_nettype)); |
| 5410 | LOG_PRINT_L0("Device inited..."); |
| 5411 | } else if (key_on_device()) { |
| 5412 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, "hardware device not supported"); |
| 5413 | } |
| 5414 | |
| 5415 | if (r) |
| 5416 | { |
| 5417 | if (encrypted_secret_keys) |
| 5418 | { |
| 5419 | m_account.decrypt_keys(key); |
| 5420 | } |
| 5421 | else |
| 5422 | { |
| 5423 | keys_to_encrypt = key; |
| 5424 | } |
| 5425 | } |
| 5426 | const cryptonote::account_keys& keys = m_account.get_keys(); |
| 5427 | hw::device &hwdev = m_account.get_device(); |
| 5428 | r = r && hwdev.verify_keys(keys.m_view_secret_key, keys.m_account_address.m_view_public_key); |
| 5429 | if (!m_watch_only && !m_multisig && hwdev.device_protocol() != hw::device::PROTOCOL_COLD && !m_is_background_wallet) |
| 5430 | r = r && hwdev.verify_keys(keys.m_spend_secret_key, keys.m_account_address.m_spend_public_key); |
| 5431 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_files_doesnt_correspond, m_keys_file, m_wallet_file); |
| 5432 | |
| 5433 | if (r) |
| 5434 | { |
| 5435 | if (!m_is_background_wallet) |
| 5436 | setup_keys(password); |
| 5437 | else |
| 5438 | m_custom_background_key = boost::optional<crypto::chacha_key>(key); |
| 5439 | } |
| 5440 | |
| 5441 | return true; |
| 5442 | } |
| 5443 | |
| 5444 | /*! |
| 5445 | * \brief verify password for default wallet keys file. |
| 5446 | * \param password Password to verify |
| 5447 | * \return true if password is correct |
| 5448 | * |
| 5449 | * for verification only |
| 5450 | * should not mutate state, unlike load_keys() |
| 5451 | * can be used prior to rewriting wallet keys file, to ensure user has entered the correct password |
| 5452 | * |
| 5453 | */ |
| 5454 | bool wallet2::verify_password(const epee::wipeable_string& password, crypto::secret_key &spend_key_out) |
| 5455 | { |
| 5456 | // this temporary unlocking is necessary for Windows (otherwise the file couldn't be loaded). |
| 5457 | unlock_keys_file(); |
| 5458 | const bool no_spend_key = m_account.get_device().device_protocol() == hw::device::PROTOCOL_COLD || m_watch_only || m_multisig || m_is_background_wallet; |
| 5459 | bool r = verify_password(m_keys_file, password, no_spend_key, m_account.get_device(), m_kdf_rounds, spend_key_out); |
| 5460 | lock_keys_file(); |
| 5461 | return r; |
| 5462 | } |
| 5463 | |
| 5464 | /*! |
| 5465 | * \brief verify password for specified wallet keys file. |
| 5466 | * \param keys_file_name Keys file to verify password for |
| 5467 | * \param password Password to verify |
| 5468 | * \param no_spend_key If set = only verify view keys, otherwise also spend keys |
| 5469 | * \param hwdev The hardware device to use |
| 5470 | * \return true if password is correct |
| 5471 | * |
| 5472 | * for verification only |
| 5473 | * should not mutate state, unlike load_keys() |
| 5474 | * can be used prior to rewriting wallet keys file, to ensure user has entered the correct password |
| 5475 | * |
| 5476 | */ |
| 5477 | bool wallet2::verify_password(const std::string& keys_file_name, const epee::wipeable_string& password, bool no_spend_key, hw::device &hwdev, uint64_t kdf_rounds, crypto::secret_key &spend_key_out) |
| 5478 | { |
| 5479 | rapidjson::Document json; |
| 5480 | wallet2::keys_file_data keys_file_data; |
| 5481 | std::string buf; |
| 5482 | bool encrypted_secret_keys = false; |
| 5483 | bool r = load_from_file(keys_file_name, buf); |
| 5484 | THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, keys_file_name); |
| 5485 | |
| 5486 | // Decrypt the contents |
| 5487 | r = ::serialization::parse_binary(buf, keys_file_data); |
| 5488 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "internal error: failed to deserialize \"" + keys_file_name + '\"'); |
| 5489 | crypto::chacha_key key; |
| 5490 | crypto::generate_chacha_key(password.data(), password.size(), key, kdf_rounds); |
| 5491 | std::string account_data; |
| 5492 | account_data.resize(keys_file_data.account_data.size()); |
| 5493 | crypto::chacha20(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5494 | const bool try_v0_format = json.Parse(account_data.c_str()).HasParseError() || !json.IsObject(); |
| 5495 | if (try_v0_format) |
| 5496 | crypto::chacha8(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5497 | |
| 5498 | // Check if it's a background keys file if both of the above formats fail |
| 5499 | { |
| 5500 | cryptonote::account_base account_data_check; |
| 5501 | if (try_v0_format && !epee::serialization::load_t_from_binary(account_data_check, account_data)) |
| 5502 | { |
| 5503 | get_custom_background_key(password, key, kdf_rounds); |
| 5504 | crypto::chacha20(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5505 | const bool is_background_wallet = !json.Parse(account_data.c_str()).HasParseError() && json.IsObject(); |
| 5506 | no_spend_key = no_spend_key || is_background_wallet; |
| 5507 | } |
| 5508 | } |
| 5509 | |
| 5510 | // The contents should be JSON if the wallet follows the new format. |
| 5511 | if (json.Parse(account_data.c_str()).HasParseError()) |
| 5512 | { |
| 5513 | // old format before JSON wallet key file format |
| 5514 | } |
| 5515 | else |
| 5516 | { |
| 5517 | account_data = std::string(json["key_data"].GetString(), json["key_data"].GetString() + |
| 5518 | json["key_data"].GetStringLength()); |
| 5519 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, encrypted_secret_keys, uint32_t, Uint, false, false); |
| 5520 | encrypted_secret_keys = field_encrypted_secret_keys; |
| 5521 | } |
| 5522 | |
| 5523 | cryptonote::account_base account_data_check; |
| 5524 | |
| 5525 | r = epee::serialization::load_t_from_binary(account_data_check, account_data); |
| 5526 | |
| 5527 | if (encrypted_secret_keys) |
| 5528 | account_data_check.decrypt_keys(key); |
| 5529 | |
| 5530 | const cryptonote::account_keys& keys = account_data_check.get_keys(); |
| 5531 | r = r && hwdev.verify_keys(keys.m_view_secret_key, keys.m_account_address.m_view_public_key); |
| 5532 | if(!no_spend_key) |
| 5533 | r = r && hwdev.verify_keys(keys.m_spend_secret_key, keys.m_account_address.m_spend_public_key); |
| 5534 | spend_key_out = (!no_spend_key && r) ? keys.m_spend_secret_key : crypto::null_skey; |
| 5535 | return r; |
| 5536 | } |
| 5537 | |
| 5538 | void wallet2::encrypt_keys(const crypto::chacha_key &key) |
| 5539 | { |
| 5540 | m_account.encrypt_keys(key); |
| 5541 | m_account.decrypt_viewkey(key); |
| 5542 | } |
| 5543 | |
| 5544 | void wallet2::decrypt_keys(const crypto::chacha_key &key) |
| 5545 | { |
| 5546 | verify_password_with_cached_key(key); |
| 5547 | |
| 5548 | m_account.encrypt_viewkey(key); |
| 5549 | m_account.decrypt_keys(key); |
| 5550 | } |
| 5551 | |
| 5552 | void wallet2::encrypt_keys(const epee::wipeable_string &password) |
| 5553 | { |
| 5554 | crypto::chacha_key key; |
| 5555 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 5556 | encrypt_keys(key); |
| 5557 | } |
| 5558 | |
| 5559 | void wallet2::decrypt_keys(const epee::wipeable_string &password) |
| 5560 | { |
| 5561 | crypto::chacha_key key; |
| 5562 | crypto::generate_chacha_key(password.data(), password.size(), key, m_kdf_rounds); |
| 5563 | decrypt_keys(key); |
| 5564 | } |
| 5565 | |
| 5566 | void wallet2::setup_new_blockchain() |
| 5567 | { |
| 5568 | cryptonote::block b; |
| 5569 | generate_genesis(b); |
| 5570 | m_blockchain.push_back(get_block_hash(b)); |
| 5571 | m_last_block_reward = cryptonote::get_outs_money_amount(b.miner_tx); |
| 5572 | add_subaddress_account(tr("Primary account")); |
| 5573 | } |
| 5574 | |
| 5575 | void wallet2::create_keys_file(const std::string &wallet_, bool watch_only, const epee::wipeable_string &password, bool create_address_file) |
| 5576 | { |
| 5577 | if (!wallet_.empty()) |
| 5578 | { |
| 5579 | bool r = store_keys(m_keys_file, password, watch_only); |
| 5580 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); |
| 5581 | |
| 5582 | if (create_address_file) |
| 5583 | { |
| 5584 | r = save_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str(m_nettype), true); |
| 5585 | if(!r) MERROR("String with address text not saved"); |
| 5586 | } |
| 5587 | } |
| 5588 | } |
| 5589 | |
| 5590 | |
| 5591 | /*! |
| 5592 | * \brief determine the key storage for the specified wallet file |
| 5593 | * \param device_type (OUT) wallet backend as enumerated in hw::device::device_type |
| 5594 | * \param keys_file_name Keys file to verify password for |
| 5595 | * \param password Password to verify |
| 5596 | * \return true if password correct, else false |
| 5597 | * |
| 5598 | * for verification only - determines key storage hardware |
| 5599 | * |
| 5600 | */ |
| 5601 | bool wallet2::query_device(hw::device::device_type& device_type, const std::string& keys_file_name, const epee::wipeable_string& password, uint64_t kdf_rounds) |
| 5602 | { |
| 5603 | rapidjson::Document json; |
| 5604 | wallet2::keys_file_data keys_file_data; |
| 5605 | std::string buf; |
| 5606 | bool r = load_from_file(keys_file_name, buf); |
| 5607 | THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, keys_file_name); |
| 5608 | |
| 5609 | // Decrypt the contents |
| 5610 | r = ::serialization::parse_binary(buf, keys_file_data); |
| 5611 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "internal error: failed to deserialize \"" + keys_file_name + '\"'); |
| 5612 | crypto::chacha_key key; |
| 5613 | crypto::generate_chacha_key(password.data(), password.size(), key, kdf_rounds); |
| 5614 | std::string account_data; |
| 5615 | account_data.resize(keys_file_data.account_data.size()); |
| 5616 | crypto::chacha20(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5617 | if (json.Parse(account_data.c_str()).HasParseError() || !json.IsObject()) |
| 5618 | crypto::chacha8(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]); |
| 5619 | |
| 5620 | device_type = hw::device::device_type::SOFTWARE; |
| 5621 | // The contents should be JSON if the wallet follows the new format. |
| 5622 | if (json.Parse(account_data.c_str()).HasParseError()) |
| 5623 | { |
| 5624 | // old format before JSON wallet key file format |
| 5625 | } |
| 5626 | else |
| 5627 | { |
| 5628 | account_data = std::string(json["key_data"].GetString(), json["key_data"].GetString() + |
| 5629 | json["key_data"].GetStringLength()); |
| 5630 | |
| 5631 | if (json.HasMember("key_on_device")) |
| 5632 | { |
| 5633 | GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, key_on_device, int, Int, false, hw::device::device_type::SOFTWARE); |
| 5634 | device_type = static_cast<hw::device::device_type>(field_key_on_device); |
| 5635 | } |
| 5636 | } |
| 5637 | |
| 5638 | cryptonote::account_base account_data_check; |
| 5639 | |
| 5640 | r = epee::serialization::load_t_from_binary(account_data_check, account_data); |
| 5641 | if (!r) return false; |
| 5642 | return true; |
| 5643 | } |
| 5644 | |
| 5645 | void wallet2::init_type(hw::device::device_type device_type) |
| 5646 | { |
| 5647 | m_account_public_address = m_account.get_keys().m_account_address; |
| 5648 | m_watch_only = false; |
| 5649 | m_multisig = false; |
| 5650 | m_multisig_threshold = 0; |
| 5651 | m_multisig_signers.clear(); |
| 5652 | m_original_keys_available = false; |
| 5653 | m_key_device_type = device_type; |
| 5654 | } |
| 5655 | |
| 5656 | /*! |
| 5657 | * \brief Generates a wallet or restores one. Assumes the multisig setup |
| 5658 | * has already completed for the provided multisig info. |
| 5659 | * \param wallet_ Name of wallet file |
| 5660 | * \param password Password of wallet file |
| 5661 | * \param multisig_data The multisig restore info and keys |
| 5662 | * \param create_address_file Whether to create an address file |
| 5663 | */ |
| 5664 | void wallet2::generate(const std::string& wallet_, const epee::wipeable_string& password, |
| 5665 | const epee::wipeable_string& multisig_data, bool create_address_file) |
| 5666 | { |
| 5667 | clear(); |
| 5668 | prepare_file_names(wallet_); |
| 5669 | |
| 5670 | if (!wallet_.empty()) |
| 5671 | { |
| 5672 | boost::system::error_code ignored_ec; |
| 5673 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file); |
| 5674 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file, ignored_ec), error::file_exists, m_keys_file); |
| 5675 | } |
| 5676 | |
| 5677 | m_account.generate(rct::rct2sk(rct::zero()), true, false); |
| 5678 | |
| 5679 | THROW_WALLET_EXCEPTION_IF(multisig_data.size() < 32, error::invalid_multisig_seed); |
| 5680 | size_t offset = 0; |
| 5681 | uint32_t threshold = *(uint32_t*)(multisig_data.data() + offset); |
| 5682 | offset += sizeof(uint32_t); |
| 5683 | uint32_t total = *(uint32_t*)(multisig_data.data() + offset); |
| 5684 | offset += sizeof(uint32_t); |
| 5685 | |
| 5686 | THROW_WALLET_EXCEPTION_IF(threshold < 1, error::invalid_multisig_seed); |
| 5687 | THROW_WALLET_EXCEPTION_IF(total < threshold, error::invalid_multisig_seed); |
| 5688 | THROW_WALLET_EXCEPTION_IF(threshold > 16, error::invalid_multisig_seed); // doing N choose (N - M + 1) might overflow |
| 5689 | const uint64_t n_multisig_keys = num_priv_multisig_keys_post_setup(threshold, total); |
| 5690 | THROW_WALLET_EXCEPTION_IF(multisig_data.size() != 8 + 32 * (4 + n_multisig_keys + total), error::invalid_multisig_seed); |
| 5691 | |
| 5692 | std::vector<crypto::secret_key> multisig_keys; |
| 5693 | std::vector<crypto::public_key> multisig_signers; |
| 5694 | crypto::secret_key spend_secret_key = *(crypto::secret_key*)(multisig_data.data() + offset); |
| 5695 | offset += sizeof(crypto::secret_key); |
| 5696 | crypto::public_key spend_public_key = *(crypto::public_key*)(multisig_data.data() + offset); |
| 5697 | offset += sizeof(crypto::public_key); |
| 5698 | crypto::secret_key view_secret_key = *(crypto::secret_key*)(multisig_data.data() + offset); |
| 5699 | offset += sizeof(crypto::secret_key); |
| 5700 | crypto::public_key view_public_key = *(crypto::public_key*)(multisig_data.data() + offset); |
| 5701 | offset += sizeof(crypto::public_key); |
| 5702 | for (size_t n = 0; n < n_multisig_keys; ++n) |
| 5703 | { |
| 5704 | multisig_keys.push_back(*(crypto::secret_key*)(multisig_data.data() + offset)); |
| 5705 | offset += sizeof(crypto::secret_key); |
| 5706 | } |
| 5707 | for (size_t n = 0; n < total; ++n) |
| 5708 | { |
| 5709 | multisig_signers.push_back(*(crypto::public_key*)(multisig_data.data() + offset)); |
| 5710 | offset += sizeof(crypto::public_key); |
| 5711 | } |
| 5712 | |
| 5713 | crypto::public_key calculated_view_public_key; |
| 5714 | THROW_WALLET_EXCEPTION_IF(!crypto::secret_key_to_public_key(view_secret_key, calculated_view_public_key), error::invalid_multisig_seed); |
| 5715 | THROW_WALLET_EXCEPTION_IF(view_public_key != calculated_view_public_key, error::invalid_multisig_seed); |
| 5716 | crypto::public_key local_signer; |
| 5717 | THROW_WALLET_EXCEPTION_IF(!crypto::secret_key_to_public_key(spend_secret_key, local_signer), error::invalid_multisig_seed); |
| 5718 | THROW_WALLET_EXCEPTION_IF(std::find(multisig_signers.begin(), multisig_signers.end(), local_signer) == multisig_signers.end(), error::invalid_multisig_seed); |
| 5719 | |
| 5720 | m_account.make_multisig(view_secret_key, spend_secret_key, spend_public_key, multisig_keys); |
| 5721 | |
| 5722 | // Not possible to restore a multisig wallet that is able to activate the MMS |
| 5723 | // (because the original keys are not (yet) part of the restore info), so |
| 5724 | // keep m_original_keys_available to false |
| 5725 | init_type(hw::device::device_type::SOFTWARE); |
| 5726 | m_multisig = true; |
| 5727 | m_multisig_threshold = threshold; |
| 5728 | m_multisig_signers = multisig_signers; |
| 5729 | // wallet is assumed already finalized |
| 5730 | m_multisig_rounds_passed = multisig::multisig_setup_rounds_required(m_multisig_signers.size(), m_multisig_threshold); |
| 5731 | setup_keys(password); |
| 5732 | |
| 5733 | create_keys_file(wallet_, false, password, m_nettype != MAINNET || create_address_file); |
| 5734 | setup_new_blockchain(); |
| 5735 | |
| 5736 | if (!wallet_.empty()) |
| 5737 | store(); |
| 5738 | } |
| 5739 | |
| 5740 | /*! |
| 5741 | * \brief Generates a wallet or restores one. |
| 5742 | * \param wallet_ Name of wallet file |
| 5743 | * \param password Password of wallet file |
| 5744 | * \param recovery_param If it is a restore, the recovery key |
| 5745 | * \param recover Whether it is a restore |
| 5746 | * \param two_random Whether it is a non-deterministic wallet |
| 5747 | * \param create_address_file Whether to create an address file |
| 5748 | * \return The secret key of the generated wallet |
| 5749 | */ |
| 5750 | crypto::secret_key wallet2::generate(const std::string& wallet_, const epee::wipeable_string& password, |
| 5751 | const crypto::secret_key& recovery_param, bool recover, bool two_random, bool create_address_file) |
| 5752 | { |
| 5753 | clear(); |
| 5754 | prepare_file_names(wallet_); |
| 5755 | |
| 5756 | if (!wallet_.empty()) |
| 5757 | { |
| 5758 | boost::system::error_code ignored_ec; |
| 5759 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file); |
| 5760 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file, ignored_ec), error::file_exists, m_keys_file); |
| 5761 | } |
| 5762 | |
| 5763 | crypto::secret_key retval = m_account.generate(recovery_param, recover, two_random); |
| 5764 | |
| 5765 | init_type(hw::device::device_type::SOFTWARE); |
| 5766 | setup_keys(password); |
| 5767 | |
| 5768 | // calculate a starting refresh height |
| 5769 | if(m_refresh_from_block_height == 0 && !recover){ |
| 5770 | m_refresh_from_block_height = estimate_blockchain_height(); |
| 5771 | } |
| 5772 | |
| 5773 | create_keys_file(wallet_, false, password, m_nettype != MAINNET || create_address_file); |
| 5774 | |
| 5775 | setup_new_blockchain(); |
| 5776 | |
| 5777 | if (!wallet_.empty()) |
| 5778 | store(); |
| 5779 | |
| 5780 | return retval; |
| 5781 | } |
| 5782 | |
| 5783 | uint64_t wallet2::estimate_blockchain_height() |
| 5784 | { |
| 5785 | // -1 month for fluctuations in block time and machine date/time setup. |
| 5786 | // avg seconds per block |
| 5787 | const int seconds_per_block = DIFFICULTY_TARGET_V2; |
| 5788 | // ~num blocks per month |
| 5789 | const uint64_t blocks_per_month = 60*60*24*30/seconds_per_block; |
| 5790 | |
| 5791 | // try asking the daemon first |
| 5792 | std::string err; |
| 5793 | uint64_t height = 0; |
| 5794 | |
| 5795 | // we get the max of approximated height and local height. |
| 5796 | // approximated height is the least of daemon target height |
| 5797 | // (the max of what the other daemons are claiming is their |
| 5798 | // height) and the theoretical height based on the local |
| 5799 | // clock. This will be wrong only if both the local clock |
| 5800 | // is bad *and* a peer daemon claims a highest height than |
| 5801 | // the real chain. |
| 5802 | // local height is the height the local daemon is currently |
| 5803 | // synced to, it will be lower than the real chain height if |
| 5804 | // the daemon is currently syncing. |
| 5805 | // If we use the approximate height we subtract one month as |
| 5806 | // a safety margin. |
| 5807 | height = get_approximate_blockchain_height(); |
| 5808 | uint64_t target_height = get_daemon_blockchain_target_height(err); |
| 5809 | if (err.empty()) { |
| 5810 | if (target_height < height) |
| 5811 | height = target_height; |
| 5812 | } else { |
| 5813 | // if we couldn't talk to the daemon, check safety margin. |
| 5814 | if (height > blocks_per_month) |
| 5815 | height -= blocks_per_month; |
| 5816 | else |
| 5817 | height = 0; |
| 5818 | } |
| 5819 | uint64_t local_height = get_daemon_blockchain_height(err); |
| 5820 | if (err.empty() && local_height > height) |
| 5821 | height = local_height; |
| 5822 | return height; |
| 5823 | } |
| 5824 | |
| 5825 | /*! |
| 5826 | * \brief Creates a watch only wallet from a public address and a view secret key. |
| 5827 | * \param wallet_ Name of wallet file |
| 5828 | * \param password Password of wallet file |
| 5829 | * \param account_public_address The account's public address |
| 5830 | * \param viewkey view secret key |
| 5831 | * \param create_address_file Whether to create an address file |
| 5832 | */ |
| 5833 | void wallet2::generate(const std::string& wallet_, const epee::wipeable_string& password, |
| 5834 | const cryptonote::account_public_address &account_public_address, |
| 5835 | const crypto::secret_key& viewkey, bool create_address_file) |
| 5836 | { |
| 5837 | clear(); |
| 5838 | prepare_file_names(wallet_); |
| 5839 | |
| 5840 | if (!wallet_.empty()) |
| 5841 | { |
| 5842 | boost::system::error_code ignored_ec; |
| 5843 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file); |
| 5844 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file, ignored_ec), error::file_exists, m_keys_file); |
| 5845 | } |
| 5846 | |
| 5847 | m_account.create_from_viewkey(account_public_address, viewkey); |
| 5848 | init_type(hw::device::device_type::SOFTWARE); |
| 5849 | m_watch_only = true; |
| 5850 | m_account_public_address = account_public_address; |
| 5851 | setup_keys(password); |
| 5852 | |
| 5853 | create_keys_file(wallet_, true, password, m_nettype != MAINNET || create_address_file); |
| 5854 | |
| 5855 | setup_new_blockchain(); |
| 5856 | |
| 5857 | if (!wallet_.empty()) |
| 5858 | store(); |
| 5859 | } |
| 5860 | |
| 5861 | /*! |
| 5862 | * \brief Creates a wallet from a public address and a spend/view secret key pair. |
| 5863 | * \param wallet_ Name of wallet file |
| 5864 | * \param password Password of wallet file |
| 5865 | * \param account_public_address The account's public address |
| 5866 | * \param spendkey spend secret key |
| 5867 | * \param viewkey view secret key |
| 5868 | * \param create_address_file Whether to create an address file |
| 5869 | */ |
| 5870 | void wallet2::generate(const std::string& wallet_, const epee::wipeable_string& password, |
| 5871 | const cryptonote::account_public_address &account_public_address, |
| 5872 | const crypto::secret_key& spendkey, const crypto::secret_key& viewkey, bool create_address_file) |
| 5873 | { |
| 5874 | clear(); |
| 5875 | prepare_file_names(wallet_); |
| 5876 | |
| 5877 | if (!wallet_.empty()) |
| 5878 | { |
| 5879 | boost::system::error_code ignored_ec; |
| 5880 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file); |
| 5881 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file, ignored_ec), error::file_exists, m_keys_file); |
| 5882 | } |
| 5883 | |
| 5884 | m_account.create_from_keys(account_public_address, spendkey, viewkey); |
| 5885 | init_type(hw::device::device_type::SOFTWARE); |
| 5886 | m_account_public_address = account_public_address; |
| 5887 | setup_keys(password); |
| 5888 | |
| 5889 | create_keys_file(wallet_, false, password, create_address_file); |
| 5890 | |
| 5891 | setup_new_blockchain(); |
| 5892 | |
| 5893 | if (!wallet_.empty()) |
| 5894 | store(); |
| 5895 | } |
| 5896 | |
| 5897 | /*! |
| 5898 | * \brief Creates a wallet from a device |
| 5899 | * \param wallet_ Name of wallet file |
| 5900 | * \param password Password of wallet file |
| 5901 | * \param device_name device string address |
| 5902 | */ |
| 5903 | void wallet2::restore(const std::string& wallet_, const epee::wipeable_string& password, const std::string &device_name, bool create_address_file) |
| 5904 | { |
| 5905 | clear(); |
| 5906 | prepare_file_names(wallet_); |
| 5907 | |
| 5908 | boost::system::error_code ignored_ec; |
| 5909 | if (!wallet_.empty()) { |
| 5910 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file); |
| 5911 | THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file, ignored_ec), error::file_exists, m_keys_file); |
| 5912 | } |
| 5913 | |
| 5914 | auto &hwdev = lookup_device(device_name); |
| 5915 | hwdev.set_name(device_name); |
| 5916 | hwdev.set_network_type(m_nettype); |
| 5917 | hwdev.set_derivation_path(m_device_derivation_path); |
| 5918 | hwdev.set_callback(get_device_callback()); |
| 5919 | |
| 5920 | m_account.create_from_device(hwdev); |
| 5921 | init_type(m_account.get_device().get_type()); |
| 5922 | setup_keys(password); |
| 5923 | m_device_name = device_name; |
| 5924 | |
| 5925 | create_keys_file(wallet_, false, password, m_nettype != MAINNET || create_address_file); |
| 5926 | if (m_subaddress_lookahead_major == SUBADDRESS_LOOKAHEAD_MAJOR && m_subaddress_lookahead_minor == SUBADDRESS_LOOKAHEAD_MINOR) |
| 5927 | { |
| 5928 | // the default lookahead setting (50:200) is clearly too much for hardware wallet |
| 5929 | m_subaddress_lookahead_major = 5; |
| 5930 | m_subaddress_lookahead_minor = 20; |
| 5931 | } |
| 5932 | setup_new_blockchain(); |
| 5933 | if (!wallet_.empty()) { |
| 5934 | store(); |
| 5935 | } |
| 5936 | } |
| 5937 | //---------------------------------------------------------------------------------------------------- |
| 5938 | std::string wallet2::make_multisig(const epee::wipeable_string &password, |
| 5939 | const std::vector<std::string> &initial_kex_msgs, |
| 5940 | const std::uint32_t threshold) |
| 5941 | { |
| 5942 | // decrypt account keys |
| 5943 | epee::misc_utils::auto_scope_leave_caller keys_reencryptor; |
| 5944 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 5945 | { |
| 5946 | crypto::chacha_key chacha_key; |
| 5947 | crypto::generate_chacha_key(password.data(), password.size(), chacha_key, m_kdf_rounds); |
| 5948 | m_account.encrypt_viewkey(chacha_key); |
| 5949 | m_account.decrypt_keys(chacha_key); |
| 5950 | keys_reencryptor = epee::misc_utils::create_scope_leave_handler( |
| 5951 | [&, this, chacha_key]() |
| 5952 | { |
| 5953 | m_account.encrypt_keys(chacha_key); |
| 5954 | m_account.decrypt_viewkey(chacha_key); |
| 5955 | } |
| 5956 | ); |
| 5957 | } |
| 5958 | |
| 5959 | // create multisig account |
| 5960 | multisig::multisig_account multisig_account{ |
| 5961 | multisig::get_multisig_blinded_secret_key(get_account().get_keys().m_spend_secret_key), |
| 5962 | multisig::get_multisig_blinded_secret_key(get_account().get_keys().m_view_secret_key) |
| 5963 | }; |
| 5964 | |
| 5965 | // open initial kex messages, validate them, extract signers |
| 5966 | std::vector<multisig::multisig_kex_msg> expanded_msgs; |
| 5967 | std::vector<crypto::public_key> signers; |
| 5968 | expanded_msgs.reserve(initial_kex_msgs.size()); |
| 5969 | signers.reserve(initial_kex_msgs.size() + 1); |
| 5970 | |
| 5971 | for (const auto &msg : initial_kex_msgs) |
| 5972 | { |
| 5973 | expanded_msgs.emplace_back(msg); |
| 5974 | |
| 5975 | // validate each message |
| 5976 | // 1. must be 'round 1' |
| 5977 | CHECK_AND_ASSERT_THROW_MES(expanded_msgs.back().get_round() == 1, |
| 5978 | "Trying to make multisig with message that has invalid multisig kex round (should be '1')."); |
| 5979 | |
| 5980 | // 2. duplicate signers not allowed |
| 5981 | CHECK_AND_ASSERT_THROW_MES(std::find(signers.begin(), signers.end(), expanded_msgs.back().get_signing_pubkey()) == signers.end(), |
| 5982 | "Duplicate signers not allowed when converting a wallet to multisig."); |
| 5983 | |
| 5984 | // add signer (skip self for now) |
| 5985 | if (expanded_msgs.back().get_signing_pubkey() != multisig_account.get_base_pubkey()) |
| 5986 | signers.push_back(expanded_msgs.back().get_signing_pubkey()); |
| 5987 | } |
| 5988 | |
| 5989 | // add self to signers |
| 5990 | signers.push_back(multisig_account.get_base_pubkey()); |
| 5991 | |
| 5992 | // intialize key exchange |
| 5993 | multisig_account.initialize_kex(threshold, signers, expanded_msgs); |
| 5994 | CHECK_AND_ASSERT_THROW_MES(multisig_account.account_is_active(), "Failed to activate multisig account."); |
| 5995 | |
| 5996 | // update wallet state |
| 5997 | if (!m_original_keys_available) |
| 5998 | { |
| 5999 | // Save the original i.e. non-multisig keys so the MMS can continue to use them to encrypt and decrypt messages |
| 6000 | // (making a wallet multisig overwrites those keys, see account_base::make_multisig) |
| 6001 | m_original_address = get_account().get_keys().m_account_address; |
| 6002 | m_original_view_secret_key = get_account().get_keys().m_view_secret_key; |
| 6003 | m_original_keys_available = true; |
| 6004 | } |
| 6005 | |
| 6006 | clear(); |
| 6007 | |
| 6008 | // account base |
| 6009 | MINFO("Creating multisig address..."); |
| 6010 | CHECK_AND_ASSERT_THROW_MES(m_account.make_multisig(multisig_account.get_common_privkey(), |
| 6011 | multisig_account.get_base_privkey(), |
| 6012 | multisig_account.get_multisig_pubkey(), |
| 6013 | multisig_account.get_multisig_privkeys()), |
| 6014 | "Failed to create multisig wallet account due to bad keys"); |
| 6015 | |
| 6016 | init_type(hw::device::device_type::SOFTWARE); |
| 6017 | m_original_keys_available = true; |
| 6018 | m_multisig = true; |
| 6019 | m_multisig_threshold = threshold; |
| 6020 | m_multisig_signers = signers; |
| 6021 | m_multisig_rounds_passed = 1; |
| 6022 | |
| 6023 | // derivations stored (should be empty in last round) |
| 6024 | m_multisig_derivations.clear(); |
| 6025 | m_multisig_derivations.reserve(multisig_account.get_kex_keys_to_origins_map().size()); |
| 6026 | |
| 6027 | for (const auto &key_to_origins : multisig_account.get_kex_keys_to_origins_map()) |
| 6028 | m_multisig_derivations.push_back(key_to_origins.first); |
| 6029 | |
| 6030 | // address |
| 6031 | m_account_public_address.m_spend_public_key = multisig_account.get_multisig_pubkey(); |
| 6032 | |
| 6033 | // re-encrypt keys |
| 6034 | keys_reencryptor = epee::misc_utils::auto_scope_leave_caller(); |
| 6035 | |
| 6036 | if (!m_wallet_file.empty()) |
| 6037 | create_keys_file(m_wallet_file, false, password, boost::filesystem::exists(m_wallet_file + ".address.txt")); |
| 6038 | |
| 6039 | setup_new_blockchain(); |
| 6040 | |
| 6041 | if (!m_wallet_file.empty()) |
| 6042 | store(); |
| 6043 | |
| 6044 | return multisig_account.get_next_kex_round_msg(); |
| 6045 | } |
| 6046 | //---------------------------------------------------------------------------------------------------- |
| 6047 | std::string wallet2::exchange_multisig_keys(const epee::wipeable_string &password, |
| 6048 | const std::vector<std::string> &kex_messages, |
| 6049 | const bool force_update_use_with_caution /*= false*/) |
| 6050 | { |
| 6051 | bool ready{false}; |
| 6052 | CHECK_AND_ASSERT_THROW_MES(multisig(&ready), "The wallet is not multisig"); |
| 6053 | |
| 6054 | // decrypt account keys |
| 6055 | epee::misc_utils::auto_scope_leave_caller keys_reencryptor; |
| 6056 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 6057 | { |
| 6058 | crypto::chacha_key chacha_key; |
| 6059 | crypto::generate_chacha_key(password.data(), password.size(), chacha_key, m_kdf_rounds); |
| 6060 | m_account.encrypt_viewkey(chacha_key); |
| 6061 | m_account.decrypt_keys(chacha_key); |
| 6062 | keys_reencryptor = epee::misc_utils::create_scope_leave_handler( |
| 6063 | [&, this, chacha_key]() |
| 6064 | { |
| 6065 | m_account.encrypt_keys(chacha_key); |
| 6066 | m_account.decrypt_viewkey(chacha_key); |
| 6067 | } |
| 6068 | ); |
| 6069 | } |
| 6070 | |
| 6071 | // reconstruct multisig account |
| 6072 | multisig::multisig_keyset_map_memsafe_t kex_origins_map; |
| 6073 | |
| 6074 | for (const auto &derivation : m_multisig_derivations) |
| 6075 | kex_origins_map[derivation]; |
| 6076 | |
| 6077 | multisig::multisig_account multisig_account{ |
| 6078 | m_multisig_threshold, |
| 6079 | m_multisig_signers, |
| 6080 | get_account().get_keys().m_spend_secret_key, |
| 6081 | crypto::null_skey, //base common privkey: not used |
| 6082 | get_account().get_keys().m_multisig_keys, |
| 6083 | get_account().get_keys().m_view_secret_key, |
| 6084 | m_account_public_address.m_spend_public_key, |
| 6085 | m_account_public_address.m_view_public_key, |
| 6086 | m_multisig_rounds_passed, |
| 6087 | std::move(kex_origins_map), |
| 6088 | "" |
| 6089 | }; |
| 6090 | |
| 6091 | // KLUDGE: early return if there are no kex messages and main kex is complete (will return the post-kex verification round |
| 6092 | // message) (it's a kludge because this behavior would be more appropriate for a standalone wallet method) |
| 6093 | if (kex_messages.size() == 0) |
| 6094 | { |
| 6095 | CHECK_AND_ASSERT_THROW_MES(multisig_account.main_kex_rounds_done(), |
| 6096 | "Exchange multisig keys: there are no kex messages but the main kex rounds are not done."); |
| 6097 | |
| 6098 | return multisig_account.get_next_kex_round_msg(); |
| 6099 | } |
| 6100 | |
| 6101 | // open kex messages |
| 6102 | std::vector<multisig::multisig_kex_msg> expanded_msgs; |
| 6103 | expanded_msgs.reserve(kex_messages.size()); |
| 6104 | |
| 6105 | for (const auto &msg : kex_messages) |
| 6106 | expanded_msgs.emplace_back(msg); |
| 6107 | |
| 6108 | // update multisig kex |
| 6109 | multisig_account.kex_update(expanded_msgs, force_update_use_with_caution); |
| 6110 | |
| 6111 | // update wallet state |
| 6112 | |
| 6113 | // address |
| 6114 | m_account_public_address.m_spend_public_key = multisig_account.get_multisig_pubkey(); |
| 6115 | |
| 6116 | // account base |
| 6117 | CHECK_AND_ASSERT_THROW_MES(m_account.make_multisig(multisig_account.get_common_privkey(), |
| 6118 | multisig_account.get_base_privkey(), |
| 6119 | multisig_account.get_multisig_pubkey(), |
| 6120 | multisig_account.get_multisig_privkeys()), |
| 6121 | "Failed to update multisig wallet account due to bad keys"); |
| 6122 | |
| 6123 | // derivations stored (should be empty in last round) |
| 6124 | m_multisig_derivations.clear(); |
| 6125 | m_multisig_derivations.reserve(multisig_account.get_kex_keys_to_origins_map().size()); |
| 6126 | |
| 6127 | for (const auto &key_to_origins : multisig_account.get_kex_keys_to_origins_map()) |
| 6128 | m_multisig_derivations.push_back(key_to_origins.first); |
| 6129 | |
| 6130 | // rounds passed |
| 6131 | m_multisig_rounds_passed = multisig_account.get_kex_rounds_complete(); |
| 6132 | |
| 6133 | // why is this necessary? who knows... |
| 6134 | if (multisig_account.multisig_is_ready()) |
| 6135 | { |
| 6136 | // keys are encrypted again |
| 6137 | keys_reencryptor = epee::misc_utils::auto_scope_leave_caller(); |
| 6138 | |
| 6139 | if (!m_wallet_file.empty()) |
| 6140 | { |
| 6141 | bool r = store_keys(m_keys_file, password, false); |
| 6142 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); |
| 6143 | |
| 6144 | if (boost::filesystem::exists(m_wallet_file + ".address.txt")) |
| 6145 | { |
| 6146 | r = save_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str(m_nettype), true); |
| 6147 | if(!r) MERROR("String with address text not saved"); |
| 6148 | } |
| 6149 | } |
| 6150 | |
| 6151 | m_subaddresses.clear(); |
| 6152 | m_subaddress_labels.clear(); |
| 6153 | add_subaddress_account(tr("Primary account")); |
| 6154 | |
| 6155 | if (!m_wallet_file.empty()) |
| 6156 | store(); |
| 6157 | } |
| 6158 | |
| 6159 | // wallet/file relationship |
| 6160 | if (!m_wallet_file.empty()) |
| 6161 | create_keys_file(m_wallet_file, false, password, boost::filesystem::exists(m_wallet_file + ".address.txt")); |
| 6162 | |
| 6163 | return multisig_account.get_next_kex_round_msg(); |
| 6164 | } |
| 6165 | //---------------------------------------------------------------------------------------------------- |
| 6166 | std::string wallet2::get_multisig_first_kex_msg() const |
| 6167 | { |
| 6168 | // create multisig account |
| 6169 | multisig::multisig_account multisig_account{ |
| 6170 | // k_base = H(normal private spend key) |
| 6171 | multisig::get_multisig_blinded_secret_key(get_account().get_keys().m_spend_secret_key), |
| 6172 | // k_view = H(normal private view key) |
| 6173 | multisig::get_multisig_blinded_secret_key(get_account().get_keys().m_view_secret_key) |
| 6174 | }; |
| 6175 | |
| 6176 | return multisig_account.get_next_kex_round_msg(); |
| 6177 | } |
| 6178 | //---------------------------------------------------------------------------------------------------- |
| 6179 | bool wallet2::multisig(bool *ready, uint32_t *threshold, uint32_t *total) const |
| 6180 | { |
| 6181 | if (!m_multisig) |
| 6182 | return false; |
| 6183 | if (threshold) |
| 6184 | *threshold = m_multisig_threshold; |
| 6185 | if (total) |
| 6186 | *total = m_multisig_signers.size(); |
| 6187 | if (ready) |
| 6188 | { |
| 6189 | *ready = !(get_account().get_keys().m_account_address.m_spend_public_key == rct::rct2pk(rct::identity())) && |
| 6190 | (m_multisig_rounds_passed == multisig::multisig_setup_rounds_required(m_multisig_signers.size(), m_multisig_threshold)); |
| 6191 | } |
| 6192 | return true; |
| 6193 | } |
| 6194 | //---------------------------------------------------------------------------------------------------- |
| 6195 | bool wallet2::has_multisig_partial_key_images() const |
| 6196 | { |
| 6197 | if (!m_multisig) |
| 6198 | return false; |
| 6199 | for (const auto &td: m_transfers) |
| 6200 | if (td.m_key_image_partial) |
| 6201 | return true; |
| 6202 | return false; |
| 6203 | } |
| 6204 | //---------------------------------------------------------------------------------------------------- |
| 6205 | bool wallet2::has_unknown_key_images() const |
| 6206 | { |
| 6207 | for (const auto &td: m_transfers) |
| 6208 | if (!td.m_key_image_known) |
| 6209 | return true; |
| 6210 | return false; |
| 6211 | } |
| 6212 | |
| 6213 | /*! |
| 6214 | * \brief Rewrites to the wallet file for wallet upgrade (doesn't generate key, assumes it's already there) |
| 6215 | * \param wallet_name Name of wallet file (should exist) |
| 6216 | * \param password Password for wallet file |
| 6217 | */ |
| 6218 | void wallet2::rewrite(const std::string& wallet_name, const epee::wipeable_string& password) |
| 6219 | { |
| 6220 | if (wallet_name.empty()) |
| 6221 | return; |
| 6222 | THROW_WALLET_EXCEPTION_IF(m_background_syncing || m_is_background_wallet, error::wallet_internal_error, |
| 6223 | "cannot change wallet settings from background wallet"); |
| 6224 | prepare_file_names(wallet_name); |
| 6225 | boost::system::error_code ignored_ec; |
| 6226 | THROW_WALLET_EXCEPTION_IF(!boost::filesystem::exists(m_keys_file, ignored_ec), error::file_not_found, m_keys_file); |
| 6227 | bool r = store_keys(m_keys_file, password, m_watch_only); |
| 6228 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); |
| 6229 | |
| 6230 | // Update the background keys file when we rewrite the main wallet keys file |
| 6231 | if (m_background_sync_type == BackgroundSyncCustomPassword && m_custom_background_key) |
| 6232 | { |
| 6233 | const std::string background_keys_filename = make_background_keys_file_name(wallet_name); |
| 6234 | if (!lock_background_keys_file(background_keys_filename)) |
| 6235 | { |
| 6236 | LOG_ERROR("Background keys file " << background_keys_filename << " is opened by another wallet program and cannot be rewritten"); |
| 6237 | return; // not fatal, background keys file will just have different wallet settings |
| 6238 | } |
| 6239 | store_background_keys(m_custom_background_key.get()); |
| 6240 | store_background_cache(m_custom_background_key.get(), true/*do_reset_background_sync_data*/); |
| 6241 | } |
| 6242 | else if (m_background_sync_type == BackgroundSyncReusePassword) |
| 6243 | { |
| 6244 | reset_background_sync_data(m_background_sync_data); |
| 6245 | } |
| 6246 | } |
| 6247 | /*! |
| 6248 | * \brief Writes to a file named based on the normal wallet (doesn't generate key, assumes it's already there) |
| 6249 | * \param wallet_name Base name of wallet file |
| 6250 | * \param password Password for wallet file |
| 6251 | * \param new_keys_filename [OUT] Name of new keys file |
| 6252 | */ |
| 6253 | void wallet2::write_watch_only_wallet(const std::string& wallet_name, const epee::wipeable_string& password, std::string &new_keys_filename) |
| 6254 | { |
| 6255 | prepare_file_names(wallet_name); |
| 6256 | boost::system::error_code ignored_ec; |
| 6257 | new_keys_filename = m_wallet_file + "-watchonly.keys"; |
| 6258 | bool watch_only_keys_file_exists = boost::filesystem::exists(new_keys_filename, ignored_ec); |
| 6259 | THROW_WALLET_EXCEPTION_IF(watch_only_keys_file_exists, error::file_save_error, new_keys_filename); |
| 6260 | bool r = store_keys(new_keys_filename, password, true); |
| 6261 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, new_keys_filename); |
| 6262 | } |
| 6263 | //---------------------------------------------------------------------------------------------------- |
| 6264 | void wallet2::wallet_exists(const std::string& file_path, bool& keys_file_exists, bool& wallet_file_exists) |
| 6265 | { |
| 6266 | std::string keys_file, wallet_file, mms_file; |
| 6267 | do_prepare_file_names(file_path, keys_file, wallet_file, mms_file); |
| 6268 | |
| 6269 | boost::system::error_code ignore; |
| 6270 | keys_file_exists = boost::filesystem::exists(keys_file, ignore); |
| 6271 | wallet_file_exists = boost::filesystem::exists(wallet_file, ignore); |
| 6272 | } |
| 6273 | //---------------------------------------------------------------------------------------------------- |
| 6274 | bool wallet2::wallet_valid_path_format(const std::string& file_path) |
| 6275 | { |
| 6276 | return !file_path.empty(); |
| 6277 | } |
| 6278 | //---------------------------------------------------------------------------------------------------- |
| 6279 | std::string wallet2::make_background_wallet_file_name(const std::string &wallet_file) |
| 6280 | { |
| 6281 | return wallet_file + BACKGROUND_WALLET_SUFFIX; |
| 6282 | } |
| 6283 | //---------------------------------------------------------------------------------------------------- |
| 6284 | std::string wallet2::make_background_keys_file_name(const std::string &wallet_file) |
| 6285 | { |
| 6286 | return make_background_wallet_file_name(wallet_file) + ".keys"; |
| 6287 | } |
| 6288 | //---------------------------------------------------------------------------------------------------- |
| 6289 | bool wallet2::parse_long_payment_id(const std::string& payment_id_str, crypto::hash& payment_id) |
| 6290 | { |
| 6291 | cryptonote::blobdata payment_id_data; |
| 6292 | if(!epee::string_tools::parse_hexstr_to_binbuff(payment_id_str, payment_id_data)) |
| 6293 | return false; |
| 6294 | |
| 6295 | if(sizeof(crypto::hash) != payment_id_data.size()) |
| 6296 | return false; |
| 6297 | |
| 6298 | payment_id = *reinterpret_cast<const crypto::hash*>(payment_id_data.data()); |
| 6299 | return true; |
| 6300 | } |
| 6301 | //---------------------------------------------------------------------------------------------------- |
| 6302 | bool wallet2::parse_short_payment_id(const std::string& payment_id_str, crypto::hash8& payment_id) |
| 6303 | { |
| 6304 | cryptonote::blobdata payment_id_data; |
| 6305 | if(!epee::string_tools::parse_hexstr_to_binbuff(payment_id_str, payment_id_data)) |
| 6306 | return false; |
| 6307 | |
| 6308 | if(sizeof(crypto::hash8) != payment_id_data.size()) |
| 6309 | return false; |
| 6310 | |
| 6311 | payment_id = *reinterpret_cast<const crypto::hash8*>(payment_id_data.data()); |
| 6312 | return true; |
| 6313 | } |
| 6314 | //---------------------------------------------------------------------------------------------------- |
| 6315 | bool wallet2::parse_payment_id(const std::string& payment_id_str, crypto::hash& payment_id) |
| 6316 | { |
| 6317 | if (parse_long_payment_id(payment_id_str, payment_id)) |
| 6318 | return true; |
| 6319 | crypto::hash8 payment_id8; |
| 6320 | if (parse_short_payment_id(payment_id_str, payment_id8)) |
| 6321 | { |
| 6322 | memcpy(payment_id.data, payment_id8.data, 8); |
| 6323 | memset(payment_id.data + 8, 0, 24); |
| 6324 | return true; |
| 6325 | } |
| 6326 | return false; |
| 6327 | } |
| 6328 | //---------------------------------------------------------------------------------------------------- |
| 6329 | bool wallet2::prepare_file_names(const std::string& file_path) |
| 6330 | { |
| 6331 | do_prepare_file_names(file_path, m_keys_file, m_wallet_file, m_mms_file); |
| 6332 | return true; |
| 6333 | } |
| 6334 | //---------------------------------------------------------------------------------------------------- |
| 6335 | bool wallet2::check_connection(uint32_t *version, bool *ssl, uint32_t timeout, bool *wallet_is_outdated, bool *daemon_is_outdated) |
| 6336 | { |
| 6337 | THROW_WALLET_EXCEPTION_IF(!m_is_initialized, error::wallet_not_initialized); |
| 6338 | |
| 6339 | if (m_offline) |
| 6340 | { |
| 6341 | m_rpc_version = 0; |
| 6342 | if (version) |
| 6343 | *version = 0; |
| 6344 | if (ssl) |
| 6345 | *ssl = false; |
| 6346 | return false; |
| 6347 | } |
| 6348 | |
| 6349 | // TODO: Add light wallet version check. |
| 6350 | if(m_light_wallet) { |
| 6351 | m_rpc_version = 0; |
| 6352 | if (version) |
| 6353 | *version = 0; |
| 6354 | if (ssl) |
| 6355 | *ssl = m_light_wallet_connected; // light wallet is always SSL |
| 6356 | return m_light_wallet_connected; |
| 6357 | } |
| 6358 | |
| 6359 | { |
| 6360 | boost::lock_guard<boost::recursive_mutex> lock(m_daemon_rpc_mutex); |
| 6361 | if(!m_http_client->is_connected(ssl)) |
| 6362 | { |
| 6363 | m_rpc_version = 0; |
| 6364 | m_node_rpc_proxy.invalidate(); |
| 6365 | if (!m_http_client->connect(std::chrono::milliseconds(timeout))) |
| 6366 | return false; |
| 6367 | if(!m_http_client->is_connected(ssl)) |
| 6368 | return false; |
| 6369 | } |
| 6370 | } |
| 6371 | |
| 6372 | if (!m_rpc_version && !check_version(version, wallet_is_outdated, daemon_is_outdated)) |
| 6373 | return false; |
| 6374 | if (version) |
| 6375 | *version = m_rpc_version; |
| 6376 | |
| 6377 | return true; |
| 6378 | } |
| 6379 | //---------------------------------------------------------------------------------------------------- |
| 6380 | bool wallet2::check_version(uint32_t *version, bool *wallet_is_outdated, bool *daemon_is_outdated) |
| 6381 | { |
| 6382 | uint32_t rpc_version; |
| 6383 | std::vector<std::pair<uint8_t, uint64_t>> daemon_hard_forks; |
| 6384 | uint64_t height; |
| 6385 | uint64_t target_height; |
| 6386 | if (m_node_rpc_proxy.get_rpc_version(rpc_version, daemon_hard_forks, height, target_height)) |
| 6387 | { |
| 6388 | if(version) |
| 6389 | *version = 0; |
| 6390 | return false; |
| 6391 | } |
| 6392 | |
| 6393 | // check wallet compatibility with daemon's hard fork version |
| 6394 | if (!m_allow_mismatched_daemon_version) |
| 6395 | if (!check_hard_fork_version(m_nettype, daemon_hard_forks, height, target_height, wallet_is_outdated, daemon_is_outdated)) |
| 6396 | return false; |
| 6397 | |
| 6398 | m_rpc_version = rpc_version; |
| 6399 | return true; |
| 6400 | } |
| 6401 | //---------------------------------------------------------------------------------------------------- |
| 6402 | bool wallet2::check_hard_fork_version(cryptonote::network_type nettype, const std::vector<std::pair<uint8_t, uint64_t>> &daemon_hard_forks, const uint64_t height, const uint64_t target_height, bool *wallet_is_outdated, bool *daemon_is_outdated) |
| 6403 | { |
| 6404 | const size_t wallet_num_hard_forks = nettype == TESTNET ? num_testnet_hard_forks |
| 6405 | : nettype == STAGENET ? num_stagenet_hard_forks : num_mainnet_hard_forks; |
| 6406 | const hardfork_t *wallet_hard_forks = nettype == TESTNET ? testnet_hard_forks |
| 6407 | : nettype == STAGENET ? stagenet_hard_forks : mainnet_hard_forks; |
| 6408 | |
| 6409 | // First check if wallet or daemon is outdated (whether either are unaware of |
| 6410 | // a hard fork). Then check if fork has passed rendering versions incompatible |
| 6411 | if (daemon_hard_forks.size() > 0) |
| 6412 | { |
| 6413 | bool daemon_outdated = daemon_hard_forks.size() < wallet_num_hard_forks; |
| 6414 | bool wallet_outdated = daemon_hard_forks.size() > wallet_num_hard_forks; |
| 6415 | |
| 6416 | if (daemon_is_outdated) |
| 6417 | *daemon_is_outdated = daemon_outdated; |
| 6418 | if (wallet_is_outdated) |
| 6419 | *wallet_is_outdated = wallet_outdated; |
| 6420 | |
| 6421 | if (daemon_outdated) |
| 6422 | { |
| 6423 | uint64_t daemon_missed_fork_height = wallet_hard_forks[daemon_hard_forks.size()].height; |
| 6424 | |
| 6425 | // If the daemon missed the fork, then technically it is no longer part of |
| 6426 | // the Monero network. Don't connect. |
| 6427 | bool daemon_missed_fork = height >= daemon_missed_fork_height || target_height >= daemon_missed_fork_height; |
| 6428 | if (daemon_missed_fork) |
| 6429 | return false; |
| 6430 | } |
| 6431 | else if (wallet_outdated) |
| 6432 | { |
| 6433 | uint64_t wallet_missed_fork_height = daemon_hard_forks[wallet_num_hard_forks].second; |
| 6434 | |
| 6435 | // If the wallet missed the fork, then technically it is no longer able |
| 6436 | // to communicate with the Monero network. Don't connect. |
| 6437 | bool wallet_missed_fork = height >= wallet_missed_fork_height || target_height >= wallet_missed_fork_height; |
| 6438 | if (wallet_missed_fork) |
| 6439 | return false; |
| 6440 | } |
| 6441 | } |
| 6442 | else |
| 6443 | { |
| 6444 | // Non-updated daemons won't return daemon_hard_forks in response to |
| 6445 | // get_version. Fall back to extra call to get_hard_fork_info by version. |
| 6446 | uint64_t daemon_fork_height; |
| 6447 | get_hard_fork_info(wallet_num_hard_forks-1/* wallet expects "double fork" pattern */, daemon_fork_height); |
| 6448 | bool daemon_outdated = daemon_fork_height == std::numeric_limits<uint64_t>::max(); |
| 6449 | |
| 6450 | if (daemon_is_outdated) |
| 6451 | *daemon_is_outdated = daemon_outdated; |
| 6452 | |
| 6453 | if (daemon_outdated) |
| 6454 | { |
| 6455 | uint64_t daemon_missed_fork_height = wallet_hard_forks[wallet_num_hard_forks-2].height; |
| 6456 | bool daemon_missed_fork = height >= daemon_missed_fork_height || target_height >= daemon_missed_fork_height; |
| 6457 | if (daemon_missed_fork) |
| 6458 | return false; |
| 6459 | } |
| 6460 | |
| 6461 | // Don't need to check if wallet is outdated here because the daemons updated |
| 6462 | // for a future hard fork will serve daemon_hard_forks above. The check for |
| 6463 | // an outdated wallet is done above using daemon_hard_forks. |
| 6464 | } |
| 6465 | |
| 6466 | return true; |
| 6467 | } |
| 6468 | //---------------------------------------------------------------------------------------------------- |
| 6469 | void wallet2::set_offline(bool offline) |
| 6470 | { |
| 6471 | m_offline = offline; |
| 6472 | m_node_rpc_proxy.set_offline(offline); |
| 6473 | m_http_client->set_auto_connect(!offline); |
| 6474 | if (offline) |
| 6475 | { |
| 6476 | boost::lock_guard<boost::recursive_mutex> lock(m_daemon_rpc_mutex); |
| 6477 | if(m_http_client->is_connected()) |
| 6478 | m_http_client->disconnect(); |
| 6479 | } |
| 6480 | } |
| 6481 | //---------------------------------------------------------------------------------------------------- |
| 6482 | bool wallet2::generate_chacha_key_from_secret_keys(crypto::chacha_key &key) const |
| 6483 | { |
| 6484 | hw::device &hwdev = m_account.get_device(); |
| 6485 | return hwdev.generate_chacha_key(m_account.get_keys(), key, m_kdf_rounds); |
| 6486 | } |
| 6487 | //---------------------------------------------------------------------------------------------------- |
| 6488 | void wallet2::generate_chacha_key_from_password(const epee::wipeable_string &pass, crypto::chacha_key &key) const |
| 6489 | { |
| 6490 | crypto::generate_chacha_key(pass.data(), pass.size(), key, m_kdf_rounds); |
| 6491 | } |
| 6492 | //---------------------------------------------------------------------------------------------------- |
| 6493 | void wallet2::load(const std::string& wallet_, const epee::wipeable_string& password, const std::string& keys_buf, const std::string& cache_buf) |
| 6494 | { |
| 6495 | clear(); |
| 6496 | prepare_file_names(wallet_); |
| 6497 | |
| 6498 | // determine if loading from file system or string buffer |
| 6499 | bool use_fs = !wallet_.empty(); |
| 6500 | THROW_WALLET_EXCEPTION_IF((use_fs && !keys_buf.empty()) || (!use_fs && keys_buf.empty()), error::file_read_error, "must load keys either from file system or from buffer");\ |
| 6501 | |
| 6502 | boost::system::error_code e; |
| 6503 | if (use_fs) |
| 6504 | { |
| 6505 | bool exists = boost::filesystem::exists(m_keys_file, e); |
| 6506 | THROW_WALLET_EXCEPTION_IF(e || !exists, error::file_not_found, m_keys_file); |
| 6507 | lock_keys_file(); |
| 6508 | THROW_WALLET_EXCEPTION_IF(!is_keys_file_locked(), error::wallet_internal_error, "internal error: \"" + m_keys_file + "\" is opened by another wallet program"); |
| 6509 | |
| 6510 | // this temporary unlocking is necessary for Windows (otherwise the file couldn't be loaded). |
| 6511 | unlock_keys_file(); |
| 6512 | if (!load_keys(m_keys_file, password)) |
| 6513 | { |
| 6514 | THROW_WALLET_EXCEPTION_IF(true, error::file_read_error, m_keys_file); |
| 6515 | } |
| 6516 | LOG_PRINT_L0("Loaded wallet keys file, with public address: " << m_account.get_public_address_str(m_nettype)); |
| 6517 | lock_keys_file(); |
| 6518 | } |
| 6519 | else if (!load_keys_buf(keys_buf, password)) |
| 6520 | { |
| 6521 | THROW_WALLET_EXCEPTION_IF(true, error::file_read_error, "failed to load keys from buffer"); |
| 6522 | } |
| 6523 | |
| 6524 | wallet_keys_unlocker unlocker(*this, m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only && !m_is_background_wallet, password); |
| 6525 | |
| 6526 | //keys loaded ok! |
| 6527 | //try to load wallet cache. but even if we failed, it is not big problem |
| 6528 | load_wallet_cache(use_fs, cache_buf); |
| 6529 | |
| 6530 | if (!m_persistent_rpc_client_id) |
| 6531 | set_rpc_client_secret_key(rct::rct2sk(rct::skGen())); |
| 6532 | |
| 6533 | // Wallets used to wipe, but not erase, old unused multisig key info, which lead to huge memory leaks. |
| 6534 | // Here we erase these multisig keys if they're zero'd out to free up space. |
| 6535 | for (auto &td : m_transfers) |
| 6536 | { |
| 6537 | auto mk_it = td.m_multisig_k.begin(); |
| 6538 | while (mk_it != td.m_multisig_k.end()) |
| 6539 | { |
| 6540 | if (*mk_it == rct::zero()) |
| 6541 | mk_it = td.m_multisig_k.erase(mk_it); |
| 6542 | else |
| 6543 | ++mk_it; |
| 6544 | } |
| 6545 | } |
| 6546 | |
| 6547 | cryptonote::block genesis; |
| 6548 | generate_genesis(genesis); |
| 6549 | crypto::hash genesis_hash = get_block_hash(genesis); |
| 6550 | |
| 6551 | if (m_blockchain.empty()) |
| 6552 | { |
| 6553 | m_blockchain.push_back(genesis_hash); |
| 6554 | m_last_block_reward = cryptonote::get_outs_money_amount(genesis.miner_tx); |
| 6555 | } |
| 6556 | else |
| 6557 | { |
| 6558 | check_genesis(genesis_hash); |
| 6559 | } |
| 6560 | |
| 6561 | trim_hashchain(); |
| 6562 | |
| 6563 | if (get_num_subaddress_accounts() == 0) |
| 6564 | add_subaddress_account(tr("Primary account")); |
| 6565 | |
| 6566 | try |
| 6567 | { |
| 6568 | if (use_fs) |
| 6569 | m_message_store.read_from_file(get_multisig_wallet_state(), m_mms_file, m_load_deprecated_formats); |
| 6570 | } |
| 6571 | catch (const std::exception &e) |
| 6572 | { |
| 6573 | MERROR("Failed to initialize MMS, it will be unusable"); |
| 6574 | } |
| 6575 | |
| 6576 | try |
| 6577 | { |
| 6578 | if (use_fs) |
| 6579 | process_background_cache_on_open(); |
| 6580 | } |
| 6581 | catch (const std::exception &e) |
| 6582 | { |
| 6583 | MERROR("Failed to process background cache on open: " << e.what()); |
| 6584 | } |
| 6585 | } |
| 6586 | //---------------------------------------------------------------------------------------------------- |
| 6587 | void wallet2::load_wallet_cache(const bool use_fs, const std::string& cache_buf) |
| 6588 | { |
| 6589 | boost::system::error_code e; |
| 6590 | bool cache_missing = use_fs ? (!boost::filesystem::exists(m_wallet_file, e) || e) : cache_buf.empty(); |
| 6591 | if (cache_missing) |
| 6592 | { |
| 6593 | LOG_PRINT_L0("wallet cache missing: " << m_wallet_file << ", starting with empty blockchain"); |
| 6594 | m_account_public_address = m_account.get_keys().m_account_address; |
| 6595 | } |
| 6596 | else |
| 6597 | { |
| 6598 | wallet2::cache_file_data cache_file_data; |
| 6599 | std::string cache_file_buf; |
| 6600 | bool r = true; |
| 6601 | if (use_fs) |
| 6602 | { |
| 6603 | r = load_from_file(m_wallet_file, cache_file_buf, std::numeric_limits<size_t>::max()); |
| 6604 | THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, m_wallet_file); |
| 6605 | } |
| 6606 | |
| 6607 | // try to read it as an encrypted cache |
| 6608 | try |
| 6609 | { |
| 6610 | LOG_PRINT_L1("Trying to decrypt cache data"); |
| 6611 | |
| 6612 | r = ::serialization::parse_binary(use_fs ? cache_file_buf : cache_buf, cache_file_data); |
| 6613 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "internal error: failed to deserialize \"" + m_wallet_file + '\"'); |
| 6614 | std::string cache_data; |
| 6615 | cache_data.resize(cache_file_data.cache_data.size()); |
| 6616 | crypto::chacha20(cache_file_data.cache_data.data(), cache_file_data.cache_data.size(), get_cache_key(), cache_file_data.iv, &cache_data[0]); |
| 6617 | |
| 6618 | try { |
| 6619 | bool loaded = false; |
| 6620 | |
| 6621 | try |
| 6622 | { |
| 6623 | binary_archive<false> ar{epee::strspan<std::uint8_t>(cache_data)}; |
| 6624 | if (::serialization::serialize(ar, *this)) |
| 6625 | if (::serialization::check_stream_state(ar)) |
| 6626 | loaded = true; |
| 6627 | if (!loaded) |
| 6628 | { |
| 6629 | binary_archive<false> ar{epee::strspan<std::uint8_t>(cache_data)}; |
| 6630 | ar.enable_varint_bug_backward_compatibility(); |
| 6631 | if (::serialization::serialize(ar, *this)) |
| 6632 | if (::serialization::check_stream_state(ar)) |
| 6633 | loaded = true; |
| 6634 | } |
| 6635 | } |
| 6636 | catch(...) { } |
| 6637 | |
| 6638 | if (!loaded) |
| 6639 | { |
| 6640 | std::stringstream iss; |
| 6641 | iss << cache_data; |
| 6642 | boost::archive::portable_binary_iarchive ar(iss); |
| 6643 | ar >> *this; |
| 6644 | } |
| 6645 | } |
| 6646 | catch(...) |
| 6647 | { |
| 6648 | // try with previous scheme: direct from keys |
| 6649 | crypto::chacha_key key; |
| 6650 | generate_chacha_key_from_secret_keys(key); |
| 6651 | crypto::chacha20(cache_file_data.cache_data.data(), cache_file_data.cache_data.size(), key, cache_file_data.iv, &cache_data[0]); |
| 6652 | try { |
| 6653 | std::stringstream iss; |
| 6654 | iss << cache_data; |
| 6655 | boost::archive::portable_binary_iarchive ar(iss); |
| 6656 | ar >> *this; |
| 6657 | } |
| 6658 | catch (...) |
| 6659 | { |
| 6660 | crypto::chacha8(cache_file_data.cache_data.data(), cache_file_data.cache_data.size(), key, cache_file_data.iv, &cache_data[0]); |
| 6661 | try |
| 6662 | { |
| 6663 | std::stringstream iss; |
| 6664 | iss << cache_data; |
| 6665 | boost::archive::portable_binary_iarchive ar(iss); |
| 6666 | ar >> *this; |
| 6667 | } |
| 6668 | catch (...) |
| 6669 | { |
| 6670 | LOG_PRINT_L0("Failed to open portable binary, trying unportable"); |
| 6671 | if (use_fs) tools::copy_file(m_wallet_file, m_wallet_file + ".unportable"); |
| 6672 | std::stringstream iss; |
| 6673 | iss.str(""); |
| 6674 | iss << cache_data; |
| 6675 | boost::archive::binary_iarchive ar(iss); |
| 6676 | ar >> *this; |
| 6677 | } |
| 6678 | } |
| 6679 | } |
| 6680 | } |
| 6681 | catch (...) |
| 6682 | { |
| 6683 | LOG_PRINT_L1("Failed to load encrypted cache, trying unencrypted"); |
| 6684 | try { |
| 6685 | std::stringstream iss; |
| 6686 | iss << cache_file_buf; |
| 6687 | boost::archive::portable_binary_iarchive ar(iss); |
| 6688 | ar >> *this; |
| 6689 | } |
| 6690 | catch (...) |
| 6691 | { |
| 6692 | LOG_PRINT_L0("Failed to open portable binary, trying unportable"); |
| 6693 | if (use_fs) tools::copy_file(m_wallet_file, m_wallet_file + ".unportable"); |
| 6694 | std::stringstream iss; |
| 6695 | iss.str(""); |
| 6696 | iss << cache_file_buf; |
| 6697 | boost::archive::binary_iarchive ar(iss); |
| 6698 | ar >> *this; |
| 6699 | } |
| 6700 | } |
| 6701 | THROW_WALLET_EXCEPTION_IF( |
| 6702 | m_account_public_address.m_spend_public_key != m_account.get_keys().m_account_address.m_spend_public_key || |
| 6703 | m_account_public_address.m_view_public_key != m_account.get_keys().m_account_address.m_view_public_key, |
| 6704 | error::wallet_files_doesnt_correspond, m_keys_file, m_wallet_file); |
| 6705 | } |
| 6706 | } |
| 6707 | //---------------------------------------------------------------------------------------------------- |
| 6708 | void wallet2::process_background_cache_on_open() |
| 6709 | { |
| 6710 | if (m_wallet_file.empty()) |
| 6711 | return; |
| 6712 | if (m_background_syncing || m_is_background_wallet) |
| 6713 | return; |
| 6714 | if (m_background_sync_type == BackgroundSyncOff) |
| 6715 | return; |
| 6716 | |
| 6717 | if (m_background_sync_type == BackgroundSyncReusePassword) |
| 6718 | { |
| 6719 | const background_sync_data_t background_sync_data = m_background_sync_data; |
| 6720 | const hashchain blockchain = m_blockchain; |
| 6721 | process_background_cache(background_sync_data, blockchain, m_last_block_reward); |
| 6722 | |
| 6723 | // Reset the background cache after processing |
| 6724 | reset_background_sync_data(m_background_sync_data); |
| 6725 | } |
| 6726 | else if (m_background_sync_type == BackgroundSyncCustomPassword) |
| 6727 | { |
| 6728 | // If the background wallet files don't exist, recreate them |
| 6729 | const std::string background_keys_file = make_background_keys_file_name(m_wallet_file); |
| 6730 | const std::string background_wallet_file = make_background_wallet_file_name(m_wallet_file); |
| 6731 | const bool background_keys_file_exists = boost::filesystem::exists(background_keys_file); |
| 6732 | const bool background_wallet_exists = boost::filesystem::exists(background_wallet_file); |
| 6733 | |
| 6734 | THROW_WALLET_EXCEPTION_IF(!lock_background_keys_file(background_keys_file), error::background_wallet_already_open, background_wallet_file); |
| 6735 | THROW_WALLET_EXCEPTION_IF(!m_custom_background_key, error::wallet_internal_error, "Custom background key not set"); |
| 6736 | |
| 6737 | if (!background_keys_file_exists) |
| 6738 | { |
| 6739 | MDEBUG("Background keys file not found, restoring"); |
| 6740 | store_background_keys(m_custom_background_key.get()); |
| 6741 | } |
| 6742 | |
| 6743 | if (!background_wallet_exists) |
| 6744 | { |
| 6745 | MDEBUG("Background cache not found, restoring"); |
| 6746 | store_background_cache(m_custom_background_key.get(), true/*do_reset_background_sync_data*/); |
| 6747 | return; |
| 6748 | } |
| 6749 | |
| 6750 | MDEBUG("Loading background cache"); |
| 6751 | |
| 6752 | // Set up a minimal background wallet2 instance |
| 6753 | std::unique_ptr<wallet2> background_w2(new wallet2(m_nettype)); |
| 6754 | background_w2->m_is_background_wallet = true; |
| 6755 | background_w2->m_background_syncing = true; |
| 6756 | background_w2->m_background_sync_type = m_background_sync_type; |
| 6757 | background_w2->m_custom_background_key = m_custom_background_key; |
| 6758 | |
| 6759 | cryptonote::account_base account = m_account; |
| 6760 | account.forget_spend_key(); |
| 6761 | background_w2->m_account = account; |
| 6762 | |
| 6763 | // Load background cache from file |
| 6764 | background_w2->clear(); |
| 6765 | background_w2->prepare_file_names(background_wallet_file); |
| 6766 | background_w2->load_wallet_cache(true/*use_fs*/); |
| 6767 | |
| 6768 | process_background_cache(background_w2->m_background_sync_data, background_w2->m_blockchain, background_w2->m_last_block_reward); |
| 6769 | |
| 6770 | // Reset the background cache after processing |
| 6771 | store_background_cache(m_custom_background_key.get(), true/*do_reset_background_sync_data*/); |
| 6772 | } |
| 6773 | else |
| 6774 | { |
| 6775 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, "unknown background sync type"); |
| 6776 | } |
| 6777 | } |
| 6778 | //---------------------------------------------------------------------------------------------------- |
| 6779 | void wallet2::trim_hashchain() |
| 6780 | { |
| 6781 | uint64_t height = m_checkpoints.get_max_height(); |
| 6782 | |
| 6783 | for (const transfer_details &td: m_transfers) |
| 6784 | if (td.m_block_height < height) |
| 6785 | height = td.m_block_height; |
| 6786 | |
| 6787 | if (!m_blockchain.empty() && m_blockchain.size() == m_blockchain.offset()) |
| 6788 | { |
| 6789 | MINFO("Fixing empty hashchain"); |
| 6790 | try |
| 6791 | { |
| 6792 | cryptonote::block_header_response block_header; |
| 6793 | if (m_node_rpc_proxy.get_block_header_by_height(m_blockchain.size() - 1, block_header)) |
| 6794 | throw std::runtime_error("Failed to request block header by height"); |
| 6795 | crypto::hash hash; |
| 6796 | epee::string_tools::hex_to_pod(block_header.hash, hash); |
| 6797 | m_blockchain.refill(hash); |
| 6798 | } |
| 6799 | catch(...) |
| 6800 | { |
| 6801 | MERROR("Failed to request block header from daemon, hash chain may be unable to sync till the wallet is loaded with a usable daemon"); |
| 6802 | } |
| 6803 | } |
| 6804 | if (height > 0 && m_blockchain.size() > height) |
| 6805 | { |
| 6806 | --height; |
| 6807 | MDEBUG("trimming to " << height << ", offset " << m_blockchain.offset()); |
| 6808 | m_blockchain.trim(height); |
| 6809 | } |
| 6810 | } |
| 6811 | //---------------------------------------------------------------------------------------------------- |
| 6812 | void wallet2::check_genesis(const crypto::hash& genesis_hash) const { |
| 6813 | std::string what("Genesis block mismatch. You probably use wallet without testnet (or stagenet) flag with blockchain from test (or stage) network or vice versa"); |
| 6814 | |
| 6815 | THROW_WALLET_EXCEPTION_IF(genesis_hash != m_blockchain.genesis(), error::wallet_internal_error, what); |
| 6816 | } |
| 6817 | //---------------------------------------------------------------------------------------------------- |
| 6818 | std::string wallet2::path() const |
| 6819 | { |
| 6820 | return m_wallet_file; |
| 6821 | } |
| 6822 | //---------------------------------------------------------------------------------------------------- |
| 6823 | void wallet2::store() |
| 6824 | { |
| 6825 | if (!m_wallet_file.empty()) |
| 6826 | store_to("", epee::wipeable_string()); |
| 6827 | } |
| 6828 | //---------------------------------------------------------------------------------------------------- |
| 6829 | void wallet2::store_to(const std::string &path, const epee::wipeable_string &password, bool force_rewrite_keys) |
| 6830 | { |
| 6831 | trim_hashchain(); |
| 6832 | |
| 6833 | const bool had_old_wallet_files = !m_wallet_file.empty(); |
| 6834 | THROW_WALLET_EXCEPTION_IF(!had_old_wallet_files && path.empty(), error::wallet_internal_error, |
| 6835 | "Cannot resave wallet to current file since wallet was not loaded from file to begin with"); |
| 6836 | |
| 6837 | // if file is the same, we do: |
| 6838 | // 1. overwrite the keys file iff force_rewrite_keys is specified |
| 6839 | // 2. save cache to the *.new file |
| 6840 | // 3. rename *.new to wallet_name, replacing old cache file |
| 6841 | // else we do: |
| 6842 | // 1. prepare new file names with "path" variable |
| 6843 | // 2. store new keys files |
| 6844 | // 3. remove old keys file |
| 6845 | // 4. store new cache file |
| 6846 | // 5. remove old cache file |
| 6847 | |
| 6848 | // handle if we want just store wallet state to current files (ex store() replacement); |
| 6849 | bool same_file = had_old_wallet_files && path.empty(); |
| 6850 | if (had_old_wallet_files && !path.empty()) |
| 6851 | { |
| 6852 | const std::string canonical_old_path = boost::filesystem::canonical(m_wallet_file).string(); |
| 6853 | const std::string canonical_new_path = boost::filesystem::weakly_canonical(path).string(); |
| 6854 | same_file = canonical_old_path == canonical_new_path; |
| 6855 | } |
| 6856 | |
| 6857 | THROW_WALLET_EXCEPTION_IF(m_is_background_wallet && !same_file, error::wallet_internal_error, |
| 6858 | "Cannot save background wallet files to a different location"); |
| 6859 | |
| 6860 | if (!same_file) |
| 6861 | { |
| 6862 | // check if we want to store to directory which doesn't exists yet |
| 6863 | boost::filesystem::path parent_path = boost::filesystem::path(path).parent_path(); |
| 6864 | |
| 6865 | // if path is not exists, try to create it |
| 6866 | if (!parent_path.empty() && !boost::filesystem::exists(parent_path)) |
| 6867 | { |
| 6868 | boost::system::error_code ec; |
| 6869 | if (!boost::filesystem::create_directories(parent_path, ec)) |
| 6870 | { |
| 6871 | throw std::logic_error(ec.message()); |
| 6872 | } |
| 6873 | } |
| 6874 | } |
| 6875 | else if (m_background_sync_type == BackgroundSyncCustomPassword && m_background_syncing && !m_is_background_wallet) |
| 6876 | { |
| 6877 | // We're background syncing, so store the wallet cache as a background cache |
| 6878 | // keeping the background sync data |
| 6879 | try |
| 6880 | { |
| 6881 | THROW_WALLET_EXCEPTION_IF(!m_custom_background_key, error::wallet_internal_error, "Custom background key not set"); |
| 6882 | store_background_cache(m_custom_background_key.get(), false/*do_reset_background_sync_data*/); |
| 6883 | } |
| 6884 | catch (const std::exception &e) |
| 6885 | { |
| 6886 | MERROR("Failed to store background cache while background syncing: " << e.what()); |
| 6887 | } |
| 6888 | return; |
| 6889 | } |
| 6890 | |
| 6891 | // get wallet cache data |
| 6892 | boost::optional<wallet2::cache_file_data> cache_file_data = get_cache_file_data(); |
| 6893 | THROW_WALLET_EXCEPTION_IF(cache_file_data == boost::none, error::wallet_internal_error, "failed to generate wallet cache data"); |
| 6894 | |
| 6895 | const std::string new_file = same_file ? m_wallet_file + ".new" : path; |
| 6896 | const std::string old_file = m_wallet_file; |
| 6897 | const std::string old_keys_file = m_keys_file; |
| 6898 | const std::string old_address_file = m_wallet_file + ".address.txt"; |
| 6899 | const std::string old_mms_file = m_mms_file; |
| 6900 | |
| 6901 | if (!same_file) |
| 6902 | { |
| 6903 | prepare_file_names(path); |
| 6904 | } |
| 6905 | |
| 6906 | if (!same_file || force_rewrite_keys) |
| 6907 | { |
| 6908 | bool r = store_keys(m_keys_file, password, m_watch_only); |
| 6909 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); |
| 6910 | } |
| 6911 | |
| 6912 | if (!same_file && had_old_wallet_files) |
| 6913 | { |
| 6914 | bool r = false; |
| 6915 | if (boost::filesystem::exists(old_address_file)) |
| 6916 | { |
| 6917 | // save address to the new file |
| 6918 | const std::string address_file = m_wallet_file + ".address.txt"; |
| 6919 | r = save_to_file(address_file, m_account.get_public_address_str(m_nettype), true); |
| 6920 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_wallet_file); |
| 6921 | // remove old address file |
| 6922 | r = boost::filesystem::remove(old_address_file); |
| 6923 | if (!r) { |
| 6924 | LOG_ERROR("error removing file: " << old_address_file); |
| 6925 | } |
| 6926 | } |
| 6927 | // remove old keys file |
| 6928 | r = boost::filesystem::remove(old_keys_file); |
| 6929 | if (!r) { |
| 6930 | LOG_ERROR("error removing file: " << old_keys_file); |
| 6931 | } |
| 6932 | // remove old message store file |
| 6933 | if (boost::filesystem::exists(old_mms_file)) |
| 6934 | { |
| 6935 | r = boost::filesystem::remove(old_mms_file); |
| 6936 | if (!r) { |
| 6937 | LOG_ERROR("error removing file: " << old_mms_file); |
| 6938 | } |
| 6939 | } |
| 6940 | } |
| 6941 | |
| 6942 | // Save cache to new file. If storing to the same file, the temp path has the ".new" extension |
| 6943 | #ifdef WIN32 |
| 6944 | // On Windows avoid using std::ofstream which does not work with UTF-8 filenames |
| 6945 | // The price to pay is temporary higher memory consumption for string stream + binary archive |
| 6946 | std::ostringstream oss; |
| 6947 | binary_archive<true> oar(oss); |
| 6948 | bool success = ::serialization::serialize(oar, cache_file_data.get()); |
| 6949 | if (success) { |
| 6950 | success = save_to_file(new_file, oss.str()); |
| 6951 | } |
| 6952 | THROW_WALLET_EXCEPTION_IF(!success, error::file_save_error, new_file); |
| 6953 | #else |
| 6954 | std::ofstream ostr; |
| 6955 | ostr.open(new_file, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc); |
| 6956 | binary_archive<true> oar(ostr); |
| 6957 | bool success = ::serialization::serialize(oar, cache_file_data.get()); |
| 6958 | ostr.close(); |
| 6959 | THROW_WALLET_EXCEPTION_IF(!success || !ostr.good(), error::file_save_error, new_file); |
| 6960 | #endif |
| 6961 | |
| 6962 | if (same_file) |
| 6963 | { |
| 6964 | // here we have "*.new" file, we need to rename it to be without ".new" |
| 6965 | std::error_code e = tools::replace_file(new_file, m_wallet_file); |
| 6966 | THROW_WALLET_EXCEPTION_IF(e, error::file_save_error, m_wallet_file, e); |
| 6967 | } |
| 6968 | else if (!same_file && had_old_wallet_files) |
| 6969 | { |
| 6970 | // remove old wallet file |
| 6971 | bool r = boost::filesystem::remove(old_file); |
| 6972 | if (!r) { |
| 6973 | LOG_ERROR("error removing file: " << old_file); |
| 6974 | } |
| 6975 | } |
| 6976 | |
| 6977 | if (m_message_store.get_active()) |
| 6978 | { |
| 6979 | // While the "m_message_store" object of course always exist, a file for the message |
| 6980 | // store should only exist if the MMS is really active |
| 6981 | m_message_store.write_to_file(get_multisig_wallet_state(), m_mms_file); |
| 6982 | } |
| 6983 | |
| 6984 | if (m_background_sync_type == BackgroundSyncCustomPassword && !m_background_syncing && !m_is_background_wallet) |
| 6985 | { |
| 6986 | // Update the background wallet cache when we store the main wallet cache |
| 6987 | // Note: if background syncing when this is called, it means the background |
| 6988 | // wallet is open and was already stored above |
| 6989 | try |
| 6990 | { |
| 6991 | THROW_WALLET_EXCEPTION_IF(!m_custom_background_key, error::wallet_internal_error, "Custom background key not set"); |
| 6992 | store_background_cache(m_custom_background_key.get(), true/*do_reset_background_sync_data*/); |
| 6993 | } |
| 6994 | catch (const std::exception &e) |
| 6995 | { |
| 6996 | MERROR("Failed to update background cache: " << e.what()); |
| 6997 | } |
| 6998 | } |
| 6999 | } |
| 7000 | //---------------------------------------------------------------------------------------------------- |
| 7001 | boost::optional<wallet2::cache_file_data> wallet2::get_cache_file_data() |
| 7002 | { |
| 7003 | trim_hashchain(); |
| 7004 | try |
| 7005 | { |
| 7006 | std::stringstream oss; |
| 7007 | binary_archive<true> ar(oss); |
| 7008 | if (!::serialization::serialize(ar, *this)) |
| 7009 | return boost::none; |
| 7010 | |
| 7011 | boost::optional<wallet2::cache_file_data> cache_file_data = (wallet2::cache_file_data) {}; |
| 7012 | cache_file_data.get().cache_data = oss.str(); |
| 7013 | std::string cipher; |
| 7014 | cipher.resize(cache_file_data.get().cache_data.size()); |
| 7015 | cache_file_data.get().iv = crypto::rand<crypto::chacha_iv>(); |
| 7016 | crypto::chacha20(cache_file_data.get().cache_data.data(), cache_file_data.get().cache_data.size(), get_cache_key(), cache_file_data.get().iv, &cipher[0]); |
| 7017 | cache_file_data.get().cache_data = cipher; |
| 7018 | return cache_file_data; |
| 7019 | } |
| 7020 | catch(...) |
| 7021 | { |
| 7022 | return boost::none; |
| 7023 | } |
| 7024 | } |
| 7025 | //---------------------------------------------------------------------------------------------------- |
| 7026 | uint64_t wallet2::balance(uint32_t index_major, bool strict) const |
| 7027 | { |
| 7028 | uint64_t amount = 0; |
| 7029 | if(m_light_wallet) |
| 7030 | return m_light_wallet_balance; |
| 7031 | for (const auto& i : balance_per_subaddress(index_major, strict)) |
| 7032 | amount += i.second; |
| 7033 | return amount; |
| 7034 | } |
| 7035 | //---------------------------------------------------------------------------------------------------- |
| 7036 | uint64_t wallet2::unlocked_balance(uint32_t index_major, bool strict, uint64_t *blocks_to_unlock, uint64_t *time_to_unlock) |
| 7037 | { |
| 7038 | uint64_t amount = 0; |
| 7039 | if (blocks_to_unlock) |
| 7040 | *blocks_to_unlock = 0; |
| 7041 | if (time_to_unlock) |
| 7042 | *time_to_unlock = 0; |
| 7043 | if(m_light_wallet) |
| 7044 | return m_light_wallet_unlocked_balance; |
| 7045 | for (const auto& i : unlocked_balance_per_subaddress(index_major, strict)) |
| 7046 | { |
| 7047 | amount += i.second.first; |
| 7048 | if (blocks_to_unlock && i.second.second.first > *blocks_to_unlock) |
| 7049 | *blocks_to_unlock = i.second.second.first; |
| 7050 | if (time_to_unlock && i.second.second.second > *time_to_unlock) |
| 7051 | *time_to_unlock = i.second.second.second; |
| 7052 | } |
| 7053 | return amount; |
| 7054 | } |
| 7055 | //---------------------------------------------------------------------------------------------------- |
| 7056 | std::map<uint32_t, uint64_t> wallet2::balance_per_subaddress(uint32_t index_major, bool strict) const |
| 7057 | { |
| 7058 | std::map<uint32_t, uint64_t> amount_per_subaddr; |
| 7059 | for (const auto& td: m_transfers) |
| 7060 | { |
| 7061 | if (td.m_subaddr_index.major == index_major && !is_spent(td, strict) && !td.m_frozen) |
| 7062 | { |
| 7063 | auto found = amount_per_subaddr.find(td.m_subaddr_index.minor); |
| 7064 | if (found == amount_per_subaddr.end()) |
| 7065 | amount_per_subaddr[td.m_subaddr_index.minor] = td.amount(); |
| 7066 | else |
| 7067 | found->second += td.amount(); |
| 7068 | } |
| 7069 | } |
| 7070 | if (!strict) |
| 7071 | { |
| 7072 | for (const auto& utx: m_unconfirmed_txs) |
| 7073 | { |
| 7074 | if (utx.second.m_subaddr_account == index_major && utx.second.m_state != wallet2::unconfirmed_transfer_details::failed) |
| 7075 | { |
| 7076 | // all changes go to 0-th subaddress (in the current subaddress account) |
| 7077 | auto found = amount_per_subaddr.find(0); |
| 7078 | if (found == amount_per_subaddr.end()) |
| 7079 | amount_per_subaddr[0] = utx.second.m_change; |
| 7080 | else |
| 7081 | found->second += utx.second.m_change; |
| 7082 | |
| 7083 | // add transfers to same wallet |
| 7084 | for (const auto &dest: utx.second.m_dests) { |
| 7085 | auto index = get_subaddress_index(dest.addr); |
| 7086 | if (index && (*index).major == index_major) |
| 7087 | { |
| 7088 | auto found = amount_per_subaddr.find((*index).minor); |
| 7089 | if (found == amount_per_subaddr.end()) |
| 7090 | amount_per_subaddr[(*index).minor] = dest.amount; |
| 7091 | else |
| 7092 | found->second += dest.amount; |
| 7093 | } |
| 7094 | } |
| 7095 | } |
| 7096 | } |
| 7097 | |
| 7098 | for (const auto& utx: m_unconfirmed_payments) |
| 7099 | { |
| 7100 | if (utx.second.m_pd.m_subaddr_index.major == index_major) |
| 7101 | { |
| 7102 | amount_per_subaddr[utx.second.m_pd.m_subaddr_index.minor] += utx.second.m_pd.m_amount; |
| 7103 | } |
| 7104 | } |
| 7105 | } |
| 7106 | return amount_per_subaddr; |
| 7107 | } |
| 7108 | //---------------------------------------------------------------------------------------------------- |
| 7109 | std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> wallet2::unlocked_balance_per_subaddress(uint32_t index_major, bool strict) |
| 7110 | { |
| 7111 | std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> amount_per_subaddr; |
| 7112 | const uint64_t blockchain_height = get_blockchain_current_height(); |
| 7113 | const uint64_t now = time(NULL); |
| 7114 | for(const transfer_details& td: m_transfers) |
| 7115 | { |
| 7116 | if(td.m_subaddr_index.major == index_major && !is_spent(td, strict) && !td.m_frozen) |
| 7117 | { |
| 7118 | uint64_t amount = 0, blocks_to_unlock = 0, time_to_unlock = 0; |
| 7119 | if (is_transfer_unlocked(td)) |
| 7120 | { |
| 7121 | amount = td.amount(); |
| 7122 | blocks_to_unlock = 0; |
| 7123 | time_to_unlock = 0; |
| 7124 | } |
| 7125 | else |
| 7126 | { |
| 7127 | uint64_t unlock_height = td.m_block_height + std::max<uint64_t>(CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE, CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS); |
| 7128 | if (td.m_tx.unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER && td.m_tx.unlock_time > unlock_height) |
| 7129 | unlock_height = td.m_tx.unlock_time; |
| 7130 | uint64_t unlock_time = td.m_tx.unlock_time >= CRYPTONOTE_MAX_BLOCK_NUMBER ? td.m_tx.unlock_time : 0; |
| 7131 | blocks_to_unlock = unlock_height > blockchain_height ? unlock_height - blockchain_height : 0; |
| 7132 | time_to_unlock = unlock_time > now ? unlock_time - now : 0; |
| 7133 | amount = 0; |
| 7134 | } |
| 7135 | auto found = amount_per_subaddr.find(td.m_subaddr_index.minor); |
| 7136 | if (found == amount_per_subaddr.end()) |
| 7137 | amount_per_subaddr[td.m_subaddr_index.minor] = std::make_pair(amount, std::make_pair(blocks_to_unlock, time_to_unlock)); |
| 7138 | else |
| 7139 | { |
| 7140 | found->second.first += amount; |
| 7141 | found->second.second.first = std::max(found->second.second.first, blocks_to_unlock); |
| 7142 | found->second.second.second = std::max(found->second.second.second, time_to_unlock); |
| 7143 | } |
| 7144 | } |
| 7145 | } |
| 7146 | return amount_per_subaddr; |
| 7147 | } |
| 7148 | //---------------------------------------------------------------------------------------------------- |
| 7149 | uint64_t wallet2::balance_all(bool strict) const |
| 7150 | { |
| 7151 | uint64_t r = 0; |
| 7152 | for (uint32_t index_major = 0; index_major < get_num_subaddress_accounts(); ++index_major) |
| 7153 | r += balance(index_major, strict); |
| 7154 | return r; |
| 7155 | } |
| 7156 | //---------------------------------------------------------------------------------------------------- |
| 7157 | uint64_t wallet2::unlocked_balance_all(bool strict, uint64_t *blocks_to_unlock, uint64_t *time_to_unlock) |
| 7158 | { |
| 7159 | uint64_t r = 0; |
| 7160 | if (blocks_to_unlock) |
| 7161 | *blocks_to_unlock = 0; |
| 7162 | if (time_to_unlock) |
| 7163 | *time_to_unlock = 0; |
| 7164 | for (uint32_t index_major = 0; index_major < get_num_subaddress_accounts(); ++index_major) |
| 7165 | { |
| 7166 | uint64_t local_blocks_to_unlock, local_time_to_unlock; |
| 7167 | r += unlocked_balance(index_major, strict, blocks_to_unlock ? &local_blocks_to_unlock : NULL, time_to_unlock ? &local_time_to_unlock : NULL); |
| 7168 | if (blocks_to_unlock) |
| 7169 | *blocks_to_unlock = std::max(*blocks_to_unlock, local_blocks_to_unlock); |
| 7170 | if (time_to_unlock) |
| 7171 | *time_to_unlock = std::max(*time_to_unlock, local_time_to_unlock); |
| 7172 | } |
| 7173 | return r; |
| 7174 | } |
| 7175 | //---------------------------------------------------------------------------------------------------- |
| 7176 | void wallet2::get_transfers(wallet2::transfer_container& incoming_transfers) const |
| 7177 | { |
| 7178 | incoming_transfers = m_transfers; |
| 7179 | } |
| 7180 | //---------------------------------------------------------------------------------------------------- |
| 7181 | void wallet2::get_payments(const crypto::hash& payment_id, std::list<wallet2::payment_details>& payments, uint64_t min_height, const boost::optional<uint32_t>& subaddr_account, const std::set<uint32_t>& subaddr_indices) const |
| 7182 | { |
| 7183 | auto range = m_payments.equal_range(payment_id); |
| 7184 | std::for_each(range.first, range.second, [&payments, &min_height, &subaddr_account, &subaddr_indices](const payment_container::value_type& x) { |
| 7185 | if (min_height < x.second.m_block_height && |
| 7186 | (!subaddr_account || *subaddr_account == x.second.m_subaddr_index.major) && |
| 7187 | (subaddr_indices.empty() || subaddr_indices.count(x.second.m_subaddr_index.minor) == 1)) |
| 7188 | { |
| 7189 | payments.push_back(x.second); |
| 7190 | } |
| 7191 | }); |
| 7192 | } |
| 7193 | //---------------------------------------------------------------------------------------------------- |
| 7194 | void wallet2::get_payments(std::list<std::pair<crypto::hash,wallet2::payment_details>>& payments, uint64_t min_height, uint64_t max_height, const boost::optional<uint32_t>& subaddr_account, const std::set<uint32_t>& subaddr_indices) const |
| 7195 | { |
| 7196 | auto range = std::make_pair(m_payments.begin(), m_payments.end()); |
| 7197 | std::for_each(range.first, range.second, [&payments, &min_height, &max_height, &subaddr_account, &subaddr_indices](const payment_container::value_type& x) { |
| 7198 | if (min_height < x.second.m_block_height && max_height >= x.second.m_block_height && |
| 7199 | (!subaddr_account || *subaddr_account == x.second.m_subaddr_index.major) && |
| 7200 | (subaddr_indices.empty() || subaddr_indices.count(x.second.m_subaddr_index.minor) == 1)) |
| 7201 | { |
| 7202 | payments.push_back(x); |
| 7203 | } |
| 7204 | }); |
| 7205 | } |
| 7206 | //---------------------------------------------------------------------------------------------------- |
| 7207 | void wallet2::get_payments_out(std::list<std::pair<crypto::hash,wallet2::confirmed_transfer_details>>& confirmed_payments, |
| 7208 | uint64_t min_height, uint64_t max_height, const boost::optional<uint32_t>& subaddr_account, const std::set<uint32_t>& subaddr_indices) const |
| 7209 | { |
| 7210 | for (auto i = m_confirmed_txs.begin(); i != m_confirmed_txs.end(); ++i) { |
| 7211 | if (i->second.m_block_height <= min_height || i->second.m_block_height > max_height) |
| 7212 | continue; |
| 7213 | if (subaddr_account && *subaddr_account != i->second.m_subaddr_account) |
| 7214 | continue; |
| 7215 | if (!subaddr_indices.empty() && std::count_if(i->second.m_subaddr_indices.begin(), i->second.m_subaddr_indices.end(), [&subaddr_indices](uint32_t index) { return subaddr_indices.count(index) == 1; }) == 0) |
| 7216 | continue; |
| 7217 | confirmed_payments.push_back(*i); |
| 7218 | } |
| 7219 | } |
| 7220 | //---------------------------------------------------------------------------------------------------- |
| 7221 | void wallet2::get_unconfirmed_payments_out(std::list<std::pair<crypto::hash,wallet2::unconfirmed_transfer_details>>& unconfirmed_payments, const boost::optional<uint32_t>& subaddr_account, const std::set<uint32_t>& subaddr_indices) const |
| 7222 | { |
| 7223 | for (auto i = m_unconfirmed_txs.begin(); i != m_unconfirmed_txs.end(); ++i) { |
| 7224 | if (subaddr_account && *subaddr_account != i->second.m_subaddr_account) |
| 7225 | continue; |
| 7226 | if (!subaddr_indices.empty() && std::count_if(i->second.m_subaddr_indices.begin(), i->second.m_subaddr_indices.end(), [&subaddr_indices](uint32_t index) { return subaddr_indices.count(index) == 1; }) == 0) |
| 7227 | continue; |
| 7228 | unconfirmed_payments.push_back(*i); |
| 7229 | } |
| 7230 | } |
| 7231 | //---------------------------------------------------------------------------------------------------- |
| 7232 | void wallet2::get_unconfirmed_payments(std::list<std::pair<crypto::hash,wallet2::pool_payment_details>>& unconfirmed_payments, const boost::optional<uint32_t>& subaddr_account, const std::set<uint32_t>& subaddr_indices) const |
| 7233 | { |
| 7234 | for (auto i = m_unconfirmed_payments.begin(); i != m_unconfirmed_payments.end(); ++i) { |
| 7235 | if ((!subaddr_account || *subaddr_account == i->second.m_pd.m_subaddr_index.major) && |
| 7236 | (subaddr_indices.empty() || subaddr_indices.count(i->second.m_pd.m_subaddr_index.minor) == 1)) |
| 7237 | unconfirmed_payments.push_back(*i); |
| 7238 | } |
| 7239 | } |
| 7240 | //---------------------------------------------------------------------------------------------------- |
| 7241 | void wallet2::rescan_spent() |
| 7242 | { |
| 7243 | // This is RPC call that can take a long time if there are many outputs, |
| 7244 | // so we call it several times, in stripes, so we don't time out spuriously |
| 7245 | std::vector<int> spent_status; |
| 7246 | spent_status.reserve(m_transfers.size()); |
| 7247 | const size_t chunk_size = 1000; |
| 7248 | for (size_t start_offset = 0; start_offset < m_transfers.size(); start_offset += chunk_size) |
| 7249 | { |
| 7250 | const size_t n_outputs = std::min<size_t>(chunk_size, m_transfers.size() - start_offset); |
| 7251 | MDEBUG("Calling is_key_image_spent on " << start_offset << " - " << (start_offset + n_outputs - 1) << ", out of " << m_transfers.size()); |
| 7252 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::request req = AUTO_VAL_INIT(req); |
| 7253 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::response daemon_resp = AUTO_VAL_INIT(daemon_resp); |
| 7254 | for (size_t n = start_offset; n < start_offset + n_outputs; ++n) |
| 7255 | req.key_images.push_back(string_tools::pod_to_hex(m_transfers[n].m_key_image)); |
| 7256 | |
| 7257 | { |
| 7258 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 7259 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 7260 | req.client = get_client_signature(); |
| 7261 | bool r = epee::net_utils::invoke_http_json("/is_key_image_spent", req, daemon_resp, *m_http_client, rpc_timeout); |
| 7262 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, daemon_resp, "is_key_image_spent", error::is_key_image_spent_error, get_rpc_status(daemon_resp.status)); |
| 7263 | THROW_WALLET_EXCEPTION_IF(daemon_resp.spent_status.size() != n_outputs, error::wallet_internal_error, |
| 7264 | "daemon returned wrong response for is_key_image_spent, wrong amounts count = " + |
| 7265 | std::to_string(daemon_resp.spent_status.size()) + ", expected " + std::to_string(n_outputs)); |
| 7266 | check_rpc_cost("/is_key_image_spent", daemon_resp.credits, pre_call_credits, n_outputs * COST_PER_KEY_IMAGE); |
| 7267 | } |
| 7268 | |
| 7269 | std::copy(daemon_resp.spent_status.begin(), daemon_resp.spent_status.end(), std::back_inserter(spent_status)); |
| 7270 | } |
| 7271 | |
| 7272 | // update spent status |
| 7273 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 7274 | { |
| 7275 | transfer_details& td = m_transfers[i]; |
| 7276 | // a view wallet may not know about key images |
| 7277 | if (!td.m_key_image_known || td.m_key_image_partial) |
| 7278 | continue; |
| 7279 | if (td.m_spent != (spent_status[i] != COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT)) |
| 7280 | { |
| 7281 | if (td.m_spent) |
| 7282 | { |
| 7283 | LOG_PRINT_L0("Marking output " << i << "(" << td.m_key_image << ") as unspent, it was marked as spent"); |
| 7284 | set_unspent(i); |
| 7285 | td.m_spent_height = 0; |
| 7286 | } |
| 7287 | else |
| 7288 | { |
| 7289 | LOG_PRINT_L0("Marking output " << i << "(" << td.m_key_image << ") as spent, it was marked as unspent"); |
| 7290 | set_spent(i, td.m_spent_height); |
| 7291 | // unknown height, if this gets reorged, it might still be missed |
| 7292 | } |
| 7293 | } |
| 7294 | } |
| 7295 | } |
| 7296 | //---------------------------------------------------------------------------------------------------- |
| 7297 | void wallet2::rescan_blockchain(bool hard, bool refresh, bool keep_key_images) |
| 7298 | { |
| 7299 | CHECK_AND_ASSERT_THROW_MES(!hard || !keep_key_images, "Cannot preserve key images on hard rescan"); |
| 7300 | const size_t transfers_cnt = m_transfers.size(); |
| 7301 | crypto::hash transfers_hash{}; |
| 7302 | |
| 7303 | if(hard) |
| 7304 | { |
| 7305 | clear(); |
| 7306 | setup_new_blockchain(); |
| 7307 | } |
| 7308 | else |
| 7309 | { |
| 7310 | if (keep_key_images && refresh) |
| 7311 | hash_m_transfers((int64_t) transfers_cnt, transfers_hash); |
| 7312 | clear_soft(keep_key_images); |
| 7313 | } |
| 7314 | |
| 7315 | if (refresh) |
| 7316 | this->refresh(false); |
| 7317 | |
| 7318 | if (refresh && keep_key_images) |
| 7319 | finish_rescan_bc_keep_key_images(transfers_cnt, transfers_hash); |
| 7320 | } |
| 7321 | //---------------------------------------------------------------------------------------------------- |
| 7322 | bool wallet2::is_transfer_unlocked(const transfer_details& td) |
| 7323 | { |
| 7324 | return is_transfer_unlocked(td.m_tx.unlock_time, td.m_block_height); |
| 7325 | } |
| 7326 | //---------------------------------------------------------------------------------------------------- |
| 7327 | bool wallet2::is_transfer_unlocked(uint64_t unlock_time, uint64_t block_height) |
| 7328 | { |
| 7329 | if(!is_tx_spendtime_unlocked(unlock_time, block_height)) |
| 7330 | return false; |
| 7331 | |
| 7332 | if(block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE > get_blockchain_current_height()) |
| 7333 | return false; |
| 7334 | |
| 7335 | return true; |
| 7336 | } |
| 7337 | //---------------------------------------------------------------------------------------------------- |
| 7338 | bool wallet2::is_tx_spendtime_unlocked(uint64_t unlock_time, uint64_t block_height) |
| 7339 | { |
| 7340 | if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER) |
| 7341 | { |
| 7342 | //interpret as block index |
| 7343 | if(get_blockchain_current_height()-1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time) |
| 7344 | return true; |
| 7345 | else |
| 7346 | return false; |
| 7347 | }else |
| 7348 | { |
| 7349 | //interpret as time |
| 7350 | uint64_t adjusted_time; |
| 7351 | try { adjusted_time = get_daemon_adjusted_time(); } |
| 7352 | catch(...) { adjusted_time = time(NULL); } // use local time if no daemon to report blockchain time |
| 7353 | // XXX: this needs to be fast, so we'd need to get the starting heights |
| 7354 | // from the daemon to be correct once voting kicks in |
| 7355 | uint64_t v2height = m_nettype == TESTNET ? 624634 : m_nettype == STAGENET ? 32000 : 1009827; |
| 7356 | uint64_t leeway = block_height < v2height ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2; |
| 7357 | if(adjusted_time + leeway >= unlock_time) |
| 7358 | return true; |
| 7359 | else |
| 7360 | return false; |
| 7361 | } |
| 7362 | return false; |
| 7363 | } |
| 7364 | //---------------------------------------------------------------------------------------------------- |
| 7365 | namespace |
| 7366 | { |
| 7367 | template<typename T> |
| 7368 | T pop_index(std::vector<T>& vec, size_t idx) |
| 7369 | { |
| 7370 | CHECK_AND_ASSERT_MES(!vec.empty(), T(), "Vector must be non-empty"); |
| 7371 | CHECK_AND_ASSERT_MES(idx < vec.size(), T(), "idx out of bounds"); |
| 7372 | |
| 7373 | T res = vec[idx]; |
| 7374 | if (idx + 1 != vec.size()) |
| 7375 | { |
| 7376 | vec[idx] = vec.back(); |
| 7377 | } |
| 7378 | vec.resize(vec.size() - 1); |
| 7379 | |
| 7380 | return res; |
| 7381 | } |
| 7382 | |
| 7383 | template<typename T> |
| 7384 | T pop_random_value(std::vector<T>& vec) |
| 7385 | { |
| 7386 | CHECK_AND_ASSERT_MES(!vec.empty(), T(), "Vector must be non-empty"); |
| 7387 | |
| 7388 | size_t idx = crypto::rand_idx(vec.size()); |
| 7389 | return pop_index (vec, idx); |
| 7390 | } |
| 7391 | |
| 7392 | template<typename T> |
| 7393 | T pop_back(std::vector<T>& vec) |
| 7394 | { |
| 7395 | CHECK_AND_ASSERT_MES(!vec.empty(), T(), "Vector must be non-empty"); |
| 7396 | |
| 7397 | T res = vec.back(); |
| 7398 | vec.pop_back(); |
| 7399 | return res; |
| 7400 | } |
| 7401 | |
| 7402 | template<typename T> |
| 7403 | void pop_if_present(std::vector<T>& vec, T e) |
| 7404 | { |
| 7405 | for (size_t i = 0; i < vec.size(); ++i) |
| 7406 | { |
| 7407 | if (e == vec[i]) |
| 7408 | { |
| 7409 | pop_index (vec, i); |
| 7410 | return; |
| 7411 | } |
| 7412 | } |
| 7413 | } |
| 7414 | } |
| 7415 | //---------------------------------------------------------------------------------------------------- |
| 7416 | // This returns a handwavy estimation of how much two outputs are related |
| 7417 | // If they're from the same tx, then they're fully related. From close block |
| 7418 | // heights, they're kinda related. The actual values don't matter, just |
| 7419 | // their ordering, but it could become more murky if we add scores later. |
| 7420 | float wallet2::get_output_relatedness(const transfer_details &td0, const transfer_details &td1) const |
| 7421 | { |
| 7422 | int dh; |
| 7423 | |
| 7424 | // expensive test, and same tx will fall onto the same block height below |
| 7425 | if (td0.m_txid == td1.m_txid) |
| 7426 | return 1.0f; |
| 7427 | |
| 7428 | // same block height -> possibly tx burst, or same tx (since above is disabled) |
| 7429 | dh = td0.m_block_height > td1.m_block_height ? td0.m_block_height - td1.m_block_height : td1.m_block_height - td0.m_block_height; |
| 7430 | if (dh == 0) |
| 7431 | return 0.9f; |
| 7432 | |
| 7433 | // adjacent blocks -> possibly tx burst |
| 7434 | if (dh == 1) |
| 7435 | return 0.8f; |
| 7436 | |
| 7437 | // could extract the payment id, and compare them, but this is a bit expensive too |
| 7438 | |
| 7439 | // similar block heights |
| 7440 | if (dh < 10) |
| 7441 | return 0.2f; |
| 7442 | |
| 7443 | // don't think these are particularly related |
| 7444 | return 0.0f; |
| 7445 | } |
| 7446 | //---------------------------------------------------------------------------------------------------- |
| 7447 | size_t wallet2::pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_indices, const std::vector<size_t>& selected_transfers, bool smallest) const |
| 7448 | { |
| 7449 | std::vector<size_t> candidates; |
| 7450 | float best_relatedness = 1.0f; |
| 7451 | for (size_t n = 0; n < unused_indices.size(); ++n) |
| 7452 | { |
| 7453 | const transfer_details &candidate = transfers[unused_indices[n]]; |
| 7454 | float relatedness = 0.0f; |
| 7455 | for (std::vector<size_t>::const_iterator i = selected_transfers.begin(); i != selected_transfers.end(); ++i) |
| 7456 | { |
| 7457 | float r = get_output_relatedness(candidate, transfers[*i]); |
| 7458 | if (r > relatedness) |
| 7459 | { |
| 7460 | relatedness = r; |
| 7461 | if (relatedness == 1.0f) |
| 7462 | break; |
| 7463 | } |
| 7464 | } |
| 7465 | |
| 7466 | if (relatedness < best_relatedness) |
| 7467 | { |
| 7468 | best_relatedness = relatedness; |
| 7469 | candidates.clear(); |
| 7470 | } |
| 7471 | |
| 7472 | if (relatedness == best_relatedness) |
| 7473 | candidates.push_back(n); |
| 7474 | } |
| 7475 | |
| 7476 | // we have all the least related outputs in candidates, so we can pick either |
| 7477 | // the smallest, or a random one, depending on request |
| 7478 | size_t idx; |
| 7479 | if (smallest) |
| 7480 | { |
| 7481 | idx = 0; |
| 7482 | for (size_t n = 0; n < candidates.size(); ++n) |
| 7483 | { |
| 7484 | const transfer_details &td = transfers[unused_indices[candidates[n]]]; |
| 7485 | if (td.amount() < transfers[unused_indices[candidates[idx]]].amount()) |
| 7486 | idx = n; |
| 7487 | } |
| 7488 | } |
| 7489 | else |
| 7490 | { |
| 7491 | idx = crypto::rand_idx(candidates.size()); |
| 7492 | } |
| 7493 | return pop_index (unused_indices, candidates[idx]); |
| 7494 | } |
| 7495 | //---------------------------------------------------------------------------------------------------- |
| 7496 | size_t wallet2::pop_best_value(std::vector<size_t> &unused_indices, const std::vector<size_t>& selected_transfers, bool smallest) const |
| 7497 | { |
| 7498 | return pop_best_value_from(m_transfers, unused_indices, selected_transfers, smallest); |
| 7499 | } |
| 7500 | //---------------------------------------------------------------------------------------------------- |
| 7501 | // Select random input sources for transaction. |
| 7502 | // returns: |
| 7503 | // direct return: amount of money found |
| 7504 | // modified reference: selected_transfers, a list of iterators/indices of input sources |
| 7505 | uint64_t wallet2::select_transfers(uint64_t needed_money, std::vector<size_t> unused_transfers_indices, std::vector<size_t>& selected_transfers) const |
| 7506 | { |
| 7507 | uint64_t found_money = 0; |
| 7508 | selected_transfers.reserve(unused_transfers_indices.size()); |
| 7509 | while (found_money < needed_money && !unused_transfers_indices.empty()) |
| 7510 | { |
| 7511 | size_t idx = pop_best_value(unused_transfers_indices, selected_transfers); |
| 7512 | |
| 7513 | const transfer_container::const_iterator it = m_transfers.begin() + idx; |
| 7514 | selected_transfers.push_back(idx); |
| 7515 | found_money += it->amount(); |
| 7516 | } |
| 7517 | |
| 7518 | return found_money; |
| 7519 | } |
| 7520 | //---------------------------------------------------------------------------------------------------- |
| 7521 | void wallet2::add_unconfirmed_tx(const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount_in, const std::vector<cryptonote::tx_destination_entry> &dests, const crypto::hash &payment_id, uint64_t change_amount, uint32_t subaddr_account, const std::set<uint32_t>& subaddr_indices) |
| 7522 | { |
| 7523 | unconfirmed_transfer_details& utd = m_unconfirmed_txs[txid]; |
| 7524 | utd.m_amount_in = amount_in; |
| 7525 | utd.m_amount_out = 0; |
| 7526 | for (const auto &d: dests) |
| 7527 | utd.m_amount_out += d.amount; |
| 7528 | utd.m_amount_out += change_amount; // dests does not contain change |
| 7529 | utd.m_change = change_amount; |
| 7530 | utd.m_sent_time = time(NULL); |
| 7531 | utd.m_tx = (const cryptonote::transaction_prefix&)tx; |
| 7532 | utd.m_dests = dests; |
| 7533 | utd.m_payment_id = payment_id; |
| 7534 | utd.m_state = wallet2::unconfirmed_transfer_details::pending; |
| 7535 | utd.m_timestamp = time(NULL); |
| 7536 | utd.m_subaddr_account = subaddr_account; |
| 7537 | utd.m_subaddr_indices = subaddr_indices; |
| 7538 | for (const auto &in: tx.vin) |
| 7539 | { |
| 7540 | if (in.type() != typeid(cryptonote::txin_to_key)) |
| 7541 | continue; |
| 7542 | const auto &txin = boost::get<cryptonote::txin_to_key>(in); |
| 7543 | utd.m_rings.push_back(std::make_pair(txin.k_image, txin.key_offsets)); |
| 7544 | } |
| 7545 | } |
| 7546 | |
| 7547 | //---------------------------------------------------------------------------------------------------- |
| 7548 | crypto::hash wallet2::get_payment_id(const pending_tx &ptx) const |
| 7549 | { |
| 7550 | std::vector<tx_extra_field> tx_extra_fields; |
| 7551 | parse_tx_extra(ptx.tx.extra, tx_extra_fields); // ok if partially parsed |
| 7552 | tx_extra_nonce extra_nonce; |
| 7553 | crypto::hash payment_id = null_hash; |
| 7554 | if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce)) |
| 7555 | { |
| 7556 | crypto::hash8 payment_id8 = null_hash8; |
| 7557 | if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8)) |
| 7558 | { |
| 7559 | if (ptx.dests.empty()) |
| 7560 | { |
| 7561 | MWARNING("Encrypted payment id found, but no destinations public key, cannot decrypt"); |
| 7562 | return crypto::null_hash; |
| 7563 | } |
| 7564 | if (m_account.get_device().decrypt_payment_id(payment_id8, ptx.dests[0].addr.m_view_public_key, ptx.tx_key)) |
| 7565 | { |
| 7566 | memcpy(payment_id.data, payment_id8.data, 8); |
| 7567 | } |
| 7568 | } |
| 7569 | else if (!get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id)) |
| 7570 | { |
| 7571 | payment_id = crypto::null_hash; |
| 7572 | } |
| 7573 | } |
| 7574 | return payment_id; |
| 7575 | } |
| 7576 | |
| 7577 | //---------------------------------------------------------------------------------------------------- |
| 7578 | // take a pending tx and actually send it to the daemon |
| 7579 | void wallet2::commit_tx(pending_tx& ptx) |
| 7580 | { |
| 7581 | using namespace cryptonote; |
| 7582 | |
| 7583 | if(m_light_wallet) |
| 7584 | { |
| 7585 | cryptonote::COMMAND_RPC_SUBMIT_RAW_TX::request oreq; |
| 7586 | cryptonote::COMMAND_RPC_SUBMIT_RAW_TX::response ores; |
| 7587 | oreq.address = get_account().get_public_address_str(m_nettype); |
| 7588 | oreq.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 7589 | oreq.tx = epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(ptx.tx)); |
| 7590 | { |
| 7591 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 7592 | bool r = epee::net_utils::invoke_http_json("/submit_raw_tx", oreq, ores, *m_http_client, rpc_timeout, "POST"); |
| 7593 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "submit_raw_tx"); |
| 7594 | // MyMonero and OpenMonero use different status strings |
| 7595 | THROW_WALLET_EXCEPTION_IF(ores.status != "OK" && ores.status != "success" , error::tx_rejected, ptx.tx, get_rpc_status(ores.status), ores.error); |
| 7596 | } |
| 7597 | } |
| 7598 | else |
| 7599 | { |
| 7600 | // Normal submit |
| 7601 | COMMAND_RPC_SEND_RAW_TX::request req; |
| 7602 | req.tx_as_hex = epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(ptx.tx)); |
| 7603 | req.do_not_relay = false; |
| 7604 | req.do_sanity_checks = true; |
| 7605 | COMMAND_RPC_SEND_RAW_TX::response daemon_send_resp; |
| 7606 | |
| 7607 | { |
| 7608 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 7609 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 7610 | req.client = get_client_signature(); |
| 7611 | bool r = epee::net_utils::invoke_http_json("/sendrawtransaction", req, daemon_send_resp, *m_http_client, rpc_timeout); |
| 7612 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, daemon_send_resp, "sendrawtransaction", error::tx_rejected, ptx.tx, get_rpc_status(daemon_send_resp.status), get_text_reason(daemon_send_resp)); |
| 7613 | check_rpc_cost("/sendrawtransaction", daemon_send_resp.credits, pre_call_credits, COST_PER_TX_RELAY); |
| 7614 | } |
| 7615 | |
| 7616 | // sanity checks |
| 7617 | for (size_t idx: ptx.selected_transfers) |
| 7618 | { |
| 7619 | THROW_WALLET_EXCEPTION_IF(idx >= m_transfers.size(), error::wallet_internal_error, |
| 7620 | "Bad output index in selected transfers: " + boost::lexical_cast<std::string>(idx)); |
| 7621 | } |
| 7622 | } |
| 7623 | crypto::hash txid; |
| 7624 | |
| 7625 | txid = get_transaction_hash(ptx.tx); |
| 7626 | crypto::hash payment_id = crypto::null_hash; |
| 7627 | std::vector<cryptonote::tx_destination_entry> dests; |
| 7628 | uint64_t amount_in = 0; |
| 7629 | if (store_tx_info()) |
| 7630 | { |
| 7631 | payment_id = get_payment_id(ptx); |
| 7632 | dests = ptx.dests; |
| 7633 | for(size_t idx: ptx.selected_transfers) |
| 7634 | amount_in += m_transfers[idx].amount(); |
| 7635 | } |
| 7636 | add_unconfirmed_tx(txid, ptx.tx, amount_in, dests, payment_id, ptx.change_dts.amount, ptx.construction_data.subaddr_account, ptx.construction_data.subaddr_indices); |
| 7637 | if (store_tx_info() && ptx.tx_key != crypto::null_skey) |
| 7638 | { |
| 7639 | m_tx_keys[txid] = ptx.tx_key; |
| 7640 | m_additional_tx_keys[txid] = ptx.additional_tx_keys; |
| 7641 | } |
| 7642 | |
| 7643 | LOG_PRINT_L2("transaction " << txid << " generated ok and sent to daemon, key_images: [" << ptx.key_images << "]"); |
| 7644 | |
| 7645 | for(size_t idx: ptx.selected_transfers) |
| 7646 | { |
| 7647 | set_spent(idx, 0); |
| 7648 | } |
| 7649 | |
| 7650 | // tx generated, get rid of used k values |
| 7651 | for (size_t idx: ptx.selected_transfers) |
| 7652 | { |
| 7653 | memwipe(m_transfers[idx].m_multisig_k.data(), m_transfers[idx].m_multisig_k.size() * sizeof(m_transfers[idx].m_multisig_k[0])); |
| 7654 | m_transfers[idx].m_multisig_k.clear(); |
| 7655 | } |
| 7656 | |
| 7657 | //fee includes dust if dust policy specified it. |
| 7658 | LOG_PRINT_L1("Transaction successfully sent. <" << txid << ">" << ENDL |
| 7659 | << "Commission: " << print_money(ptx.fee) << " (dust sent to dust addr: " << print_money((ptx.dust_added_to_fee ? 0 : ptx.dust)) << ")" << ENDL |
| 7660 | << "Balance: " << print_money(balance(ptx.construction_data.subaddr_account, false)) << ENDL |
| 7661 | << "Unlocked: " << print_money(unlocked_balance(ptx.construction_data.subaddr_account, false)) << ENDL |
| 7662 | << "Please, wait for confirmation for your balance to be unlocked."); |
| 7663 | } |
| 7664 | |
| 7665 | void wallet2::commit_tx(std::vector<pending_tx>& ptx_vector) |
| 7666 | { |
| 7667 | for (auto & ptx : ptx_vector) |
| 7668 | { |
| 7669 | commit_tx(ptx); |
| 7670 | } |
| 7671 | } |
| 7672 | //---------------------------------------------------------------------------------------------------- |
| 7673 | bool wallet2::save_tx(const std::vector<pending_tx>& ptx_vector, const std::string &filename) const |
| 7674 | { |
| 7675 | LOG_PRINT_L0("saving " << ptx_vector.size() << " transactions"); |
| 7676 | std::string ciphertext = dump_tx_to_str(ptx_vector); |
| 7677 | if (ciphertext.empty()) |
| 7678 | return false; |
| 7679 | return save_to_file(filename, ciphertext); |
| 7680 | } |
| 7681 | //---------------------------------------------------------------------------------------------------- |
| 7682 | std::string wallet2::dump_tx_to_str(const std::vector<pending_tx> &ptx_vector) const |
| 7683 | { |
| 7684 | LOG_PRINT_L0("saving " << ptx_vector.size() << " transactions"); |
| 7685 | unsigned_tx_set txs; |
| 7686 | for (auto &tx: ptx_vector) |
| 7687 | { |
| 7688 | // Short payment id is encrypted with tx_key. |
| 7689 | // Since sign_tx() generates new tx_keys and encrypts the payment id, we need to save the decrypted payment ID |
| 7690 | // Save tx construction_data to unsigned_tx_set |
| 7691 | txs.txes.push_back(get_construction_data_with_decrypted_short_payment_id(tx, m_account.get_device())); |
| 7692 | } |
| 7693 | |
| 7694 | txs.new_transfers = export_outputs(); |
| 7695 | // save as binary |
| 7696 | std::ostringstream oss; |
| 7697 | binary_archive<true> ar(oss); |
| 7698 | try |
| 7699 | { |
| 7700 | if (!::serialization::serialize(ar, txs)) |
| 7701 | return std::string(); |
| 7702 | } |
| 7703 | catch (...) |
| 7704 | { |
| 7705 | return std::string(); |
| 7706 | } |
| 7707 | LOG_PRINT_L2("Saving unsigned tx data: " << oss.str()); |
| 7708 | std::string ciphertext = encrypt_with_view_secret_key(oss.str()); |
| 7709 | return std::string(UNSIGNED_TX_PREFIX) + ciphertext; |
| 7710 | } |
| 7711 | //---------------------------------------------------------------------------------------------------- |
| 7712 | bool wallet2::load_unsigned_tx(const std::string &unsigned_filename, unsigned_tx_set &exported_txs) const |
| 7713 | { |
| 7714 | std::string s; |
| 7715 | boost::system::error_code errcode; |
| 7716 | |
| 7717 | if (!boost::filesystem::exists(unsigned_filename, errcode)) |
| 7718 | { |
| 7719 | LOG_PRINT_L0("File " << unsigned_filename << " does not exist: " << errcode); |
| 7720 | return false; |
| 7721 | } |
| 7722 | if (!load_from_file(unsigned_filename.c_str(), s)) |
| 7723 | { |
| 7724 | LOG_PRINT_L0("Failed to load from " << unsigned_filename); |
| 7725 | return false; |
| 7726 | } |
| 7727 | |
| 7728 | return parse_unsigned_tx_from_str(s, exported_txs); |
| 7729 | } |
| 7730 | //---------------------------------------------------------------------------------------------------- |
| 7731 | bool wallet2::parse_unsigned_tx_from_str(const std::string &unsigned_tx_st, unsigned_tx_set &exported_txs) const |
| 7732 | { |
| 7733 | std::string s = unsigned_tx_st; |
| 7734 | const size_t magiclen = strlen(UNSIGNED_TX_PREFIX) - 1; |
| 7735 | if (strncmp(s.c_str(), UNSIGNED_TX_PREFIX, magiclen)) |
| 7736 | { |
| 7737 | LOG_PRINT_L0("Bad magic from unsigned tx"); |
| 7738 | return false; |
| 7739 | } |
| 7740 | s = s.substr(magiclen); |
| 7741 | const char version = s[0]; |
| 7742 | s = s.substr(1); |
| 7743 | if (version == '\003') |
| 7744 | { |
| 7745 | if (!m_load_deprecated_formats) |
| 7746 | { |
| 7747 | LOG_PRINT_L0("Not loading deprecated format"); |
| 7748 | return false; |
| 7749 | } |
| 7750 | try |
| 7751 | { |
| 7752 | std::istringstream iss(s); |
| 7753 | boost::archive::portable_binary_iarchive ar(iss); |
| 7754 | ar >> exported_txs; |
| 7755 | } |
| 7756 | catch (...) |
| 7757 | { |
| 7758 | LOG_PRINT_L0("Failed to parse data from unsigned tx"); |
| 7759 | return false; |
| 7760 | } |
| 7761 | } |
| 7762 | else if (version == '\004') |
| 7763 | { |
| 7764 | if (!m_load_deprecated_formats) |
| 7765 | { |
| 7766 | LOG_PRINT_L0("Not loading deprecated format"); |
| 7767 | return false; |
| 7768 | } |
| 7769 | try |
| 7770 | { |
| 7771 | s = decrypt_with_view_secret_key(s); |
| 7772 | try |
| 7773 | { |
| 7774 | std::istringstream iss(s); |
| 7775 | boost::archive::portable_binary_iarchive ar(iss); |
| 7776 | ar >> exported_txs; |
| 7777 | } |
| 7778 | catch (...) |
| 7779 | { |
| 7780 | LOG_PRINT_L0("Failed to parse data from unsigned tx"); |
| 7781 | return false; |
| 7782 | } |
| 7783 | } |
| 7784 | catch (const std::exception &e) |
| 7785 | { |
| 7786 | LOG_PRINT_L0("Failed to decrypt unsigned tx: " << e.what()); |
| 7787 | return false; |
| 7788 | } |
| 7789 | } |
| 7790 | else if (version == '\005') |
| 7791 | { |
| 7792 | try { s = decrypt_with_view_secret_key(s); } |
| 7793 | catch(const std::exception &e) { LOG_PRINT_L0("Failed to decrypt unsigned tx: " << e.what()); return false; } |
| 7794 | try |
| 7795 | { |
| 7796 | binary_archive<false> ar{epee::strspan<std::uint8_t>(s)}; |
| 7797 | if (!::serialization::serialize(ar, exported_txs)) |
| 7798 | { |
| 7799 | LOG_PRINT_L0("Failed to parse data from unsigned tx"); |
| 7800 | return false; |
| 7801 | } |
| 7802 | } |
| 7803 | catch (...) |
| 7804 | { |
| 7805 | LOG_PRINT_L0("Failed to parse data from unsigned tx"); |
| 7806 | return false; |
| 7807 | } |
| 7808 | } |
| 7809 | else |
| 7810 | { |
| 7811 | LOG_PRINT_L0("Unsupported version in unsigned tx"); |
| 7812 | return false; |
| 7813 | } |
| 7814 | LOG_PRINT_L1("Loaded tx unsigned data from binary: " << exported_txs.txes.size() << " transactions"); |
| 7815 | |
| 7816 | return true; |
| 7817 | } |
| 7818 | //---------------------------------------------------------------------------------------------------- |
| 7819 | bool wallet2::sign_tx(const std::string &unsigned_filename, const std::string &signed_filename, std::vector<wallet2::pending_tx> &txs, std::function<bool(const unsigned_tx_set&)> accept_func, bool export_raw) |
| 7820 | { |
| 7821 | unsigned_tx_set exported_txs; |
| 7822 | if(!load_unsigned_tx(unsigned_filename, exported_txs)) |
| 7823 | return false; |
| 7824 | |
| 7825 | if (accept_func && !accept_func(exported_txs)) |
| 7826 | { |
| 7827 | LOG_PRINT_L1("Transactions rejected by callback"); |
| 7828 | return false; |
| 7829 | } |
| 7830 | return sign_tx(exported_txs, signed_filename, txs, export_raw); |
| 7831 | } |
| 7832 | //---------------------------------------------------------------------------------------------------- |
| 7833 | bool wallet2::sign_tx(unsigned_tx_set &exported_txs, std::vector<wallet2::pending_tx> &txs, signed_tx_set &signed_txes) |
| 7834 | { |
| 7835 | if (!std::get<2>(exported_txs.new_transfers).empty()) |
| 7836 | import_outputs(exported_txs.new_transfers); |
| 7837 | else if (!std::get<2>(exported_txs.transfers).empty()) |
| 7838 | import_outputs(exported_txs.transfers); |
| 7839 | |
| 7840 | // sign the transactions |
| 7841 | for (size_t n = 0; n < exported_txs.txes.size(); ++n) |
| 7842 | { |
| 7843 | tools::wallet2::tx_construction_data &sd = exported_txs.txes[n]; |
| 7844 | THROW_WALLET_EXCEPTION_IF(sd.sources.empty(), error::wallet_internal_error, "Empty sources"); |
| 7845 | THROW_WALLET_EXCEPTION_IF(sd.unlock_time, error::nonzero_unlock_time); |
| 7846 | LOG_PRINT_L1(" " << (n+1) << ": " << sd.sources.size() << " inputs, ring size " << sd.sources[0].outputs.size()); |
| 7847 | signed_txes.ptx.push_back(pending_tx()); |
| 7848 | tools::wallet2::pending_tx &ptx = signed_txes.ptx.back(); |
| 7849 | rct::RCTConfig rct_config = sd.rct_config; |
| 7850 | crypto::secret_key tx_key; |
| 7851 | std::vector<crypto::secret_key> additional_tx_keys; |
| 7852 | bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), m_subaddresses, sd.sources, sd.splitted_dsts, sd.change_dts.addr, sd.extra, ptx.tx, tx_key, additional_tx_keys, sd.use_rct, rct_config, sd.use_view_tags); |
| 7853 | THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sd.sources, sd.splitted_dsts, m_nettype); |
| 7854 | // we don't test tx size, because we don't know the current limit, due to not having a blockchain, |
| 7855 | // and it's a bit pointless to fail there anyway, since it'd be a (good) guess only. We sign anyway, |
| 7856 | // and if we really go over limit, the daemon will reject when it gets submitted. Chances are it's |
| 7857 | // OK anyway since it was generated in the first place, and rerolling should be within a few bytes. |
| 7858 | |
| 7859 | // normally, the tx keys are saved in commit_tx, when the tx is actually sent to the daemon. |
| 7860 | // we can't do that here since the tx will be sent from the compromised wallet, which we don't want |
| 7861 | // to see that info, so we save it here |
| 7862 | if (store_tx_info() && tx_key != crypto::null_skey) |
| 7863 | { |
| 7864 | const crypto::hash txid = get_transaction_hash(ptx.tx); |
| 7865 | m_tx_keys[txid] = tx_key; |
| 7866 | m_additional_tx_keys[txid] = additional_tx_keys; |
| 7867 | } |
| 7868 | |
| 7869 | std::string key_images; |
| 7870 | bool all_are_txin_to_key = std::all_of(ptx.tx.vin.begin(), ptx.tx.vin.end(), [&](const txin_v& s_e) -> bool |
| 7871 | { |
| 7872 | CHECKED_GET_SPECIFIC_VARIANT(s_e, const txin_to_key, in, false); |
| 7873 | key_images += boost::to_string(in.k_image) + " "; |
| 7874 | return true; |
| 7875 | }); |
| 7876 | THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, ptx.tx); |
| 7877 | |
| 7878 | ptx.key_images = key_images; |
| 7879 | ptx.fee = 0; |
| 7880 | for (const auto &i: sd.sources) ptx.fee += i.amount; |
| 7881 | for (const auto &i: sd.splitted_dsts) ptx.fee -= i.amount; |
| 7882 | ptx.dust = 0; |
| 7883 | ptx.dust_added_to_fee = false; |
| 7884 | ptx.change_dts = sd.change_dts; |
| 7885 | ptx.selected_transfers = sd.selected_transfers; |
| 7886 | ptx.tx_key = rct::rct2sk(rct::identity()); // don't send it back to the untrusted view wallet |
| 7887 | ptx.dests = sd.dests; |
| 7888 | ptx.construction_data = sd; |
| 7889 | |
| 7890 | txs.push_back(ptx); |
| 7891 | |
| 7892 | // add tx keys only to ptx |
| 7893 | txs.back().tx_key = tx_key; |
| 7894 | txs.back().additional_tx_keys = additional_tx_keys; |
| 7895 | } |
| 7896 | |
| 7897 | // add key image mapping for these txes |
| 7898 | const account_keys &keys = get_account().get_keys(); |
| 7899 | hw::device &hwdev = m_account.get_device(); |
| 7900 | for (size_t n = 0; n < exported_txs.txes.size(); ++n) |
| 7901 | { |
| 7902 | const cryptonote::transaction &tx = signed_txes.ptx[n].tx; |
| 7903 | |
| 7904 | crypto::key_derivation derivation; |
| 7905 | std::vector<crypto::key_derivation> additional_derivations; |
| 7906 | |
| 7907 | // compute public keys from out secret keys |
| 7908 | crypto::public_key tx_pub_key; |
| 7909 | crypto::secret_key_to_public_key(txs[n].tx_key, tx_pub_key); |
| 7910 | std::vector<crypto::public_key> additional_tx_pub_keys; |
| 7911 | for (const crypto::secret_key &skey: txs[n].additional_tx_keys) |
| 7912 | { |
| 7913 | additional_tx_pub_keys.resize(additional_tx_pub_keys.size() + 1); |
| 7914 | crypto::secret_key_to_public_key(skey, additional_tx_pub_keys.back()); |
| 7915 | } |
| 7916 | |
| 7917 | // compute derivations |
| 7918 | hwdev.set_mode(hw::device::TRANSACTION_PARSE); |
| 7919 | if (!hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation)) |
| 7920 | { |
| 7921 | MWARNING("Failed to generate key derivation from tx pubkey in " << cryptonote::get_transaction_hash(tx) << ", skipping"); |
| 7922 | static_assert(sizeof(derivation) == sizeof(rct::key), "Mismatched sizes of key_derivation and rct::key"); |
| 7923 | memcpy(&derivation, rct::identity().bytes, sizeof(derivation)); |
| 7924 | } |
| 7925 | for (size_t i = 0; i < additional_tx_pub_keys.size(); ++i) |
| 7926 | { |
| 7927 | additional_derivations.push_back({}); |
| 7928 | if (!hwdev.generate_key_derivation(additional_tx_pub_keys[i], keys.m_view_secret_key, additional_derivations.back())) |
| 7929 | { |
| 7930 | MWARNING("Failed to generate key derivation from additional tx pubkey in " << cryptonote::get_transaction_hash(tx) << ", skipping"); |
| 7931 | memcpy(&additional_derivations.back(), rct::identity().bytes, sizeof(crypto::key_derivation)); |
| 7932 | } |
| 7933 | } |
| 7934 | |
| 7935 | for (size_t i = 0; i < tx.vout.size(); ++i) |
| 7936 | { |
| 7937 | crypto::public_key output_public_key; |
| 7938 | if (!get_output_public_key(tx.vout[i], output_public_key)) |
| 7939 | continue; |
| 7940 | |
| 7941 | // if this output is back to this wallet, we can calculate its key image already |
| 7942 | if (!is_out_to_acc_precomp(m_subaddresses, output_public_key, derivation, additional_derivations, i, hwdev, get_output_view_tag(tx.vout[i]))) |
| 7943 | continue; |
| 7944 | crypto::key_image ki; |
| 7945 | cryptonote::keypair in_ephemeral; |
| 7946 | if (generate_key_image_helper(keys, m_subaddresses, output_public_key, tx_pub_key, additional_tx_pub_keys, i, in_ephemeral, ki, hwdev)) |
| 7947 | signed_txes.tx_key_images[output_public_key] = ki; |
| 7948 | else |
| 7949 | MERROR("Failed to calculate key image"); |
| 7950 | } |
| 7951 | } |
| 7952 | |
| 7953 | // add key images |
| 7954 | signed_txes.key_images.resize(m_transfers.size()); |
| 7955 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 7956 | { |
| 7957 | if (!m_transfers[i].m_key_image_known || m_transfers[i].m_key_image_partial) |
| 7958 | LOG_PRINT_L0("WARNING: key image not known in signing wallet at index " << i); |
| 7959 | signed_txes.key_images[i] = m_transfers[i].m_key_image; |
| 7960 | } |
| 7961 | |
| 7962 | return true; |
| 7963 | } |
| 7964 | //---------------------------------------------------------------------------------------------------- |
| 7965 | bool wallet2::sign_tx(unsigned_tx_set &exported_txs, const std::string &signed_filename, std::vector<wallet2::pending_tx> &txs, bool export_raw) |
| 7966 | { |
| 7967 | // sign the transactions |
| 7968 | signed_tx_set signed_txes; |
| 7969 | std::string ciphertext = sign_tx_dump_to_str(exported_txs, txs, signed_txes); |
| 7970 | if (ciphertext.empty()) |
| 7971 | { |
| 7972 | LOG_PRINT_L0("Failed to sign unsigned_tx_set"); |
| 7973 | return false; |
| 7974 | } |
| 7975 | |
| 7976 | if (!save_to_file(signed_filename, ciphertext)) |
| 7977 | { |
| 7978 | LOG_PRINT_L0("Failed to save file to " << signed_filename); |
| 7979 | return false; |
| 7980 | } |
| 7981 | // export signed raw tx without encryption |
| 7982 | if (export_raw) |
| 7983 | { |
| 7984 | for (size_t i = 0; i < signed_txes.ptx.size(); ++i) |
| 7985 | { |
| 7986 | std::string tx_as_hex = epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(signed_txes.ptx[i].tx)); |
| 7987 | std::string raw_filename = signed_filename + "_raw" + (signed_txes.ptx.size() == 1 ? "" : ("_" + std::to_string(i))); |
| 7988 | if (!save_to_file(raw_filename, tx_as_hex)) |
| 7989 | { |
| 7990 | LOG_PRINT_L0("Failed to save file to " << raw_filename); |
| 7991 | return false; |
| 7992 | } |
| 7993 | } |
| 7994 | } |
| 7995 | return true; |
| 7996 | } |
| 7997 | //---------------------------------------------------------------------------------------------------- |
| 7998 | std::string wallet2::sign_tx_dump_to_str(unsigned_tx_set &exported_txs, std::vector<wallet2::pending_tx> &ptx, signed_tx_set &signed_txes) |
| 7999 | { |
| 8000 | // sign the transactions |
| 8001 | bool r = sign_tx(exported_txs, ptx, signed_txes); |
| 8002 | if (!r) |
| 8003 | { |
| 8004 | LOG_PRINT_L0("Failed to sign unsigned_tx_set"); |
| 8005 | return std::string(); |
| 8006 | } |
| 8007 | |
| 8008 | // save as binary |
| 8009 | std::ostringstream oss; |
| 8010 | binary_archive<true> ar(oss); |
| 8011 | try |
| 8012 | { |
| 8013 | if (!::serialization::serialize(ar, signed_txes)) |
| 8014 | return std::string(); |
| 8015 | } |
| 8016 | catch(...) |
| 8017 | { |
| 8018 | return std::string(); |
| 8019 | } |
| 8020 | LOG_PRINT_L3("Saving signed tx data (with encryption): " << oss.str()); |
| 8021 | std::string ciphertext = encrypt_with_view_secret_key(oss.str()); |
| 8022 | return std::string(SIGNED_TX_PREFIX) + ciphertext; |
| 8023 | } |
| 8024 | //---------------------------------------------------------------------------------------------------- |
| 8025 | bool wallet2::load_tx(const std::string &signed_filename, std::vector<tools::wallet2::pending_tx> &ptx, std::function<bool(const signed_tx_set&)> accept_func) |
| 8026 | { |
| 8027 | std::string s; |
| 8028 | boost::system::error_code errcode; |
| 8029 | signed_tx_set signed_txs; |
| 8030 | |
| 8031 | if (!boost::filesystem::exists(signed_filename, errcode)) |
| 8032 | { |
| 8033 | LOG_PRINT_L0("File " << signed_filename << " does not exist: " << errcode); |
| 8034 | return false; |
| 8035 | } |
| 8036 | |
| 8037 | if (!load_from_file(signed_filename.c_str(), s)) |
| 8038 | { |
| 8039 | LOG_PRINT_L0("Failed to load from " << signed_filename); |
| 8040 | return false; |
| 8041 | } |
| 8042 | |
| 8043 | return parse_tx_from_str(s, ptx, accept_func); |
| 8044 | } |
| 8045 | //---------------------------------------------------------------------------------------------------- |
| 8046 | bool wallet2::parse_tx_from_str(const std::string &signed_tx_st, std::vector<tools::wallet2::pending_tx> &ptx, std::function<bool(const signed_tx_set &)> accept_func) |
| 8047 | { |
| 8048 | std::string s = signed_tx_st; |
| 8049 | signed_tx_set signed_txs; |
| 8050 | |
| 8051 | const size_t magiclen = strlen(SIGNED_TX_PREFIX) - 1; |
| 8052 | if (strncmp(s.c_str(), SIGNED_TX_PREFIX, magiclen)) |
| 8053 | { |
| 8054 | LOG_PRINT_L0("Bad magic from signed transaction"); |
| 8055 | return false; |
| 8056 | } |
| 8057 | s = s.substr(magiclen); |
| 8058 | const char version = s[0]; |
| 8059 | s = s.substr(1); |
| 8060 | if (version == '\003') |
| 8061 | { |
| 8062 | if (!m_load_deprecated_formats) |
| 8063 | { |
| 8064 | LOG_PRINT_L0("Not loading deprecated format"); |
| 8065 | return false; |
| 8066 | } |
| 8067 | try |
| 8068 | { |
| 8069 | std::istringstream iss(s); |
| 8070 | boost::archive::portable_binary_iarchive ar(iss); |
| 8071 | ar >> signed_txs; |
| 8072 | } |
| 8073 | catch (...) |
| 8074 | { |
| 8075 | LOG_PRINT_L0("Failed to parse data from signed transaction"); |
| 8076 | return false; |
| 8077 | } |
| 8078 | } |
| 8079 | else if (version == '\004') |
| 8080 | { |
| 8081 | if (!m_load_deprecated_formats) |
| 8082 | { |
| 8083 | LOG_PRINT_L0("Not loading deprecated format"); |
| 8084 | return false; |
| 8085 | } |
| 8086 | try |
| 8087 | { |
| 8088 | s = decrypt_with_view_secret_key(s); |
| 8089 | try |
| 8090 | { |
| 8091 | std::istringstream iss(s); |
| 8092 | boost::archive::portable_binary_iarchive ar(iss); |
| 8093 | ar >> signed_txs; |
| 8094 | } |
| 8095 | catch (...) |
| 8096 | { |
| 8097 | LOG_PRINT_L0("Failed to parse decrypted data from signed transaction"); |
| 8098 | return false; |
| 8099 | } |
| 8100 | } |
| 8101 | catch (const std::exception &e) |
| 8102 | { |
| 8103 | LOG_PRINT_L0("Failed to decrypt signed transaction: " << e.what()); |
| 8104 | return false; |
| 8105 | } |
| 8106 | } |
| 8107 | else if (version == '\005') |
| 8108 | { |
| 8109 | try { s = decrypt_with_view_secret_key(s); } |
| 8110 | catch (const std::exception &e) { LOG_PRINT_L0("Failed to decrypt signed transaction: " << e.what()); return false; } |
| 8111 | try |
| 8112 | { |
| 8113 | binary_archive<false> ar{epee::strspan<std::uint8_t>(s)}; |
| 8114 | if (!::serialization::serialize(ar, signed_txs)) |
| 8115 | { |
| 8116 | LOG_PRINT_L0("Failed to deserialize signed transaction"); |
| 8117 | return false; |
| 8118 | } |
| 8119 | } |
| 8120 | catch (const std::exception &e) |
| 8121 | { |
| 8122 | LOG_PRINT_L0("Failed to decrypt signed transaction: " << e.what()); |
| 8123 | return false; |
| 8124 | } |
| 8125 | } |
| 8126 | else |
| 8127 | { |
| 8128 | LOG_PRINT_L0("Unsupported version in signed transaction"); |
| 8129 | return false; |
| 8130 | } |
| 8131 | LOG_PRINT_L0("Loaded signed tx data from binary: " << signed_txs.ptx.size() << " transactions"); |
| 8132 | for (auto &c_ptx: signed_txs.ptx) LOG_PRINT_L0(cryptonote::obj_to_json_str(c_ptx.tx)); |
| 8133 | |
| 8134 | if (accept_func && !accept_func(signed_txs)) |
| 8135 | { |
| 8136 | LOG_PRINT_L1("Transactions rejected by callback"); |
| 8137 | return false; |
| 8138 | } |
| 8139 | |
| 8140 | // import key images |
| 8141 | bool r = import_key_images(signed_txs.key_images); |
| 8142 | if (!r) return false; |
| 8143 | |
| 8144 | // remember key images for this tx, for when we get those txes from the blockchain |
| 8145 | for (const auto &e: signed_txs.tx_key_images) |
| 8146 | m_cold_key_images.insert(e); |
| 8147 | |
| 8148 | ptx = signed_txs.ptx; |
| 8149 | |
| 8150 | return true; |
| 8151 | } |
| 8152 | //---------------------------------------------------------------------------------------------------- |
| 8153 | std::string wallet2::save_multisig_tx(multisig_tx_set txs) |
| 8154 | { |
| 8155 | LOG_PRINT_L0("saving " << txs.m_ptx.size() << " multisig transactions"); |
| 8156 | |
| 8157 | // txes generated, get rid of used k values |
| 8158 | for (size_t n = 0; n < txs.m_ptx.size(); ++n) |
| 8159 | for (size_t idx: txs.m_ptx[n].construction_data.selected_transfers) |
| 8160 | { |
| 8161 | memwipe(m_transfers[idx].m_multisig_k.data(), m_transfers[idx].m_multisig_k.size() * sizeof(m_transfers[idx].m_multisig_k[0])); |
| 8162 | m_transfers[idx].m_multisig_k.clear(); |
| 8163 | } |
| 8164 | |
| 8165 | // zero out some data we don't want to share |
| 8166 | for (auto &ptx: txs.m_ptx) |
| 8167 | { |
| 8168 | for (auto &e: ptx.construction_data.sources) |
| 8169 | memwipe(&e.multisig_kLRki.k, sizeof(e.multisig_kLRki.k)); |
| 8170 | } |
| 8171 | |
| 8172 | for (auto &ptx: txs.m_ptx) |
| 8173 | { |
| 8174 | // Get decrypted payment id from pending_tx |
| 8175 | ptx.construction_data = get_construction_data_with_decrypted_short_payment_id(ptx, m_account.get_device()); |
| 8176 | } |
| 8177 | |
| 8178 | // save as binary |
| 8179 | std::ostringstream oss; |
| 8180 | binary_archive<true> ar(oss); |
| 8181 | try |
| 8182 | { |
| 8183 | if (!::serialization::serialize(ar, txs)) |
| 8184 | return std::string(); |
| 8185 | } |
| 8186 | catch (...) |
| 8187 | { |
| 8188 | return std::string(); |
| 8189 | } |
| 8190 | LOG_PRINT_L2("Saving multisig unsigned tx data: " << oss.str()); |
| 8191 | std::string ciphertext = encrypt_with_view_secret_key(oss.str()); |
| 8192 | return std::string(MULTISIG_UNSIGNED_TX_PREFIX) + ciphertext; |
| 8193 | } |
| 8194 | //---------------------------------------------------------------------------------------------------- |
| 8195 | bool wallet2::save_multisig_tx(const multisig_tx_set &txs, const std::string &filename) |
| 8196 | { |
| 8197 | std::string ciphertext = save_multisig_tx(txs); |
| 8198 | if (ciphertext.empty()) |
| 8199 | return false; |
| 8200 | return save_to_file(filename, ciphertext); |
| 8201 | } |
| 8202 | //---------------------------------------------------------------------------------------------------- |
| 8203 | wallet2::multisig_tx_set wallet2::make_multisig_tx_set(const std::vector<pending_tx>& ptx_vector) const |
| 8204 | { |
| 8205 | multisig_tx_set txs; |
| 8206 | txs.m_ptx = ptx_vector; |
| 8207 | |
| 8208 | for (const auto &msk: get_account().get_multisig_keys()) |
| 8209 | { |
| 8210 | crypto::public_key pkey = get_multisig_signing_public_key(msk); |
| 8211 | for (auto &ptx: txs.m_ptx) for (auto &sig: ptx.multisig_sigs) sig.signing_keys.insert(pkey); |
| 8212 | } |
| 8213 | |
| 8214 | txs.m_signers.insert(get_multisig_signer_public_key()); |
| 8215 | return txs; |
| 8216 | } |
| 8217 | |
| 8218 | std::string wallet2::save_multisig_tx(const std::vector<pending_tx>& ptx_vector) |
| 8219 | { |
| 8220 | return save_multisig_tx(make_multisig_tx_set(ptx_vector)); |
| 8221 | } |
| 8222 | //---------------------------------------------------------------------------------------------------- |
| 8223 | bool wallet2::save_multisig_tx(const std::vector<pending_tx>& ptx_vector, const std::string &filename) |
| 8224 | { |
| 8225 | std::string ciphertext = save_multisig_tx(ptx_vector); |
| 8226 | if (ciphertext.empty()) |
| 8227 | return false; |
| 8228 | return save_to_file(filename, ciphertext); |
| 8229 | } |
| 8230 | //---------------------------------------------------------------------------------------------------- |
| 8231 | bool wallet2::parse_multisig_tx_from_str(std::string multisig_tx_st, multisig_tx_set &exported_txs) const |
| 8232 | { |
| 8233 | const size_t magiclen = strlen(MULTISIG_UNSIGNED_TX_PREFIX); |
| 8234 | if (strncmp(multisig_tx_st.c_str(), MULTISIG_UNSIGNED_TX_PREFIX, magiclen)) |
| 8235 | { |
| 8236 | LOG_PRINT_L0("Bad magic from multisig tx data"); |
| 8237 | return false; |
| 8238 | } |
| 8239 | try |
| 8240 | { |
| 8241 | multisig_tx_st = decrypt_with_view_secret_key(std::string(multisig_tx_st, magiclen)); |
| 8242 | } |
| 8243 | catch (const std::exception &e) |
| 8244 | { |
| 8245 | LOG_PRINT_L0("Failed to decrypt multisig tx data: " << e.what()); |
| 8246 | return false; |
| 8247 | } |
| 8248 | bool loaded = false; |
| 8249 | try |
| 8250 | { |
| 8251 | binary_archive<false> ar{epee::strspan<std::uint8_t>(multisig_tx_st)}; |
| 8252 | if (::serialization::serialize(ar, exported_txs)) |
| 8253 | if (::serialization::check_stream_state(ar)) |
| 8254 | loaded = true; |
| 8255 | } |
| 8256 | catch (...) {} |
| 8257 | try |
| 8258 | { |
| 8259 | if (!loaded && m_load_deprecated_formats) |
| 8260 | { |
| 8261 | std::istringstream iss(multisig_tx_st); |
| 8262 | boost::archive::portable_binary_iarchive ar(iss); |
| 8263 | ar >> exported_txs; |
| 8264 | loaded = true; |
| 8265 | } |
| 8266 | } |
| 8267 | catch(...) {} |
| 8268 | |
| 8269 | if (!loaded) |
| 8270 | { |
| 8271 | LOG_PRINT_L0("Failed to parse multisig tx data"); |
| 8272 | return false; |
| 8273 | } |
| 8274 | |
| 8275 | // sanity checks |
| 8276 | for (const auto &ptx: exported_txs.m_ptx) |
| 8277 | { |
| 8278 | CHECK_AND_ASSERT_MES(ptx.selected_transfers.size() == ptx.tx.vin.size(), false, "Mismatched selected_transfers/vin sizes"); |
| 8279 | for (size_t idx: ptx.selected_transfers) |
| 8280 | CHECK_AND_ASSERT_MES(idx < m_transfers.size(), false, "Transfer index out of range"); |
| 8281 | CHECK_AND_ASSERT_MES(ptx.construction_data.selected_transfers.size() == ptx.tx.vin.size(), false, "Mismatched cd selected_transfers/vin sizes"); |
| 8282 | for (size_t idx: ptx.construction_data.selected_transfers) |
| 8283 | CHECK_AND_ASSERT_MES(idx < m_transfers.size(), false, "Transfer index out of range"); |
| 8284 | CHECK_AND_ASSERT_MES(ptx.construction_data.sources.size() == ptx.tx.vin.size(), false, "Mismatched sources/vin sizes"); |
| 8285 | CHECK_AND_ASSERT_MES(!ptx.tx.vin.empty(), false, "Multisig tx has no inputs"); |
| 8286 | CHECK_AND_ASSERT_MES(!ptx.construction_data.sources.empty(), false, "Multisig tx has no sources"); |
| 8287 | } |
| 8288 | |
| 8289 | return true; |
| 8290 | } |
| 8291 | //---------------------------------------------------------------------------------------------------- |
| 8292 | bool wallet2::load_multisig_tx(cryptonote::blobdata s, multisig_tx_set &exported_txs, std::function<bool(const multisig_tx_set&)> accept_func) |
| 8293 | { |
| 8294 | if(!parse_multisig_tx_from_str(s, exported_txs)) |
| 8295 | { |
| 8296 | LOG_PRINT_L0("Failed to parse multisig transaction from string"); |
| 8297 | return false; |
| 8298 | } |
| 8299 | |
| 8300 | LOG_PRINT_L1("Loaded multisig tx unsigned data from binary: " << exported_txs.m_ptx.size() << " transactions"); |
| 8301 | for (auto &ptx: exported_txs.m_ptx) LOG_PRINT_L0(cryptonote::obj_to_json_str(ptx.tx)); |
| 8302 | |
| 8303 | if (accept_func && !accept_func(exported_txs)) |
| 8304 | { |
| 8305 | LOG_PRINT_L1("Transactions rejected by callback"); |
| 8306 | return false; |
| 8307 | } |
| 8308 | |
| 8309 | const bool is_signed = exported_txs.m_signers.size() >= m_multisig_threshold; |
| 8310 | if (is_signed) |
| 8311 | { |
| 8312 | for (const auto &ptx: exported_txs.m_ptx) |
| 8313 | { |
| 8314 | const crypto::hash txid = get_transaction_hash(ptx.tx); |
| 8315 | if (store_tx_info()) |
| 8316 | { |
| 8317 | m_tx_keys[txid] = ptx.tx_key; |
| 8318 | m_additional_tx_keys[txid] = ptx.additional_tx_keys; |
| 8319 | } |
| 8320 | } |
| 8321 | } |
| 8322 | |
| 8323 | return true; |
| 8324 | } |
| 8325 | //---------------------------------------------------------------------------------------------------- |
| 8326 | bool wallet2::load_multisig_tx_from_file(const std::string &filename, multisig_tx_set &exported_txs, std::function<bool(const multisig_tx_set&)> accept_func) |
| 8327 | { |
| 8328 | std::string s; |
| 8329 | boost::system::error_code errcode; |
| 8330 | |
| 8331 | if (!boost::filesystem::exists(filename, errcode)) |
| 8332 | { |
| 8333 | LOG_PRINT_L0("File " << filename << " does not exist: " << errcode); |
| 8334 | return false; |
| 8335 | } |
| 8336 | if (!load_from_file(filename.c_str(), s)) |
| 8337 | { |
| 8338 | LOG_PRINT_L0("Failed to load from " << filename); |
| 8339 | return false; |
| 8340 | } |
| 8341 | |
| 8342 | if (!load_multisig_tx(s, exported_txs, accept_func)) |
| 8343 | { |
| 8344 | LOG_PRINT_L0("Failed to parse multisig tx data from " << filename); |
| 8345 | return false; |
| 8346 | } |
| 8347 | return true; |
| 8348 | } |
| 8349 | //---------------------------------------------------------------------------------------------------- |
| 8350 | bool wallet2::sign_multisig_tx(multisig_tx_set &exported_txs, std::vector<crypto::hash> &txids) |
| 8351 | { |
| 8352 | THROW_WALLET_EXCEPTION_IF(exported_txs.m_ptx.empty(), error::wallet_internal_error, "No tx found"); |
| 8353 | |
| 8354 | const crypto::public_key local_signer = get_multisig_signer_public_key(); |
| 8355 | |
| 8356 | THROW_WALLET_EXCEPTION_IF(exported_txs.m_signers.find(local_signer) != exported_txs.m_signers.end(), |
| 8357 | error::wallet_internal_error, "Transaction already signed by this private key"); |
| 8358 | THROW_WALLET_EXCEPTION_IF(exported_txs.m_signers.size() > m_multisig_threshold, |
| 8359 | error::wallet_internal_error, "Transaction was signed by too many signers"); |
| 8360 | THROW_WALLET_EXCEPTION_IF(exported_txs.m_signers.size() == m_multisig_threshold, |
| 8361 | error::wallet_internal_error, "Transaction is already fully signed"); |
| 8362 | THROW_WALLET_EXCEPTION_IF(frozen(exported_txs), |
| 8363 | error::wallet_internal_error, "Will not sign multisig tx containing frozen outputs") |
| 8364 | |
| 8365 | txids.clear(); |
| 8366 | |
| 8367 | // The 'exported_txs' contains a set of different transactions for the multisig group to try to sign. Each of those |
| 8368 | // transactions has a set of 'signing attempts' corresponding to all the possible signing groups within the multisig. |
| 8369 | // - Here, we will partially sign as many of those signing attempts as possible, for each proposed transaction. |
| 8370 | for (size_t n = 0; n < exported_txs.m_ptx.size(); ++n) |
| 8371 | { |
| 8372 | tools::wallet2::pending_tx &ptx = exported_txs.m_ptx[n]; |
| 8373 | THROW_WALLET_EXCEPTION_IF(ptx.multisig_sigs.empty(), error::wallet_internal_error, "No signatures found in multisig tx"); |
| 8374 | const tools::wallet2::tx_construction_data &sd = ptx.construction_data; |
| 8375 | LOG_PRINT_L1(" " << (n+1) << ": " << sd.sources.size() << " inputs, ring size " << (sd.sources[0].outputs.size()) << |
| 8376 | ", signed by " << exported_txs.m_signers.size() << "/" << m_multisig_threshold); |
| 8377 | |
| 8378 | // reconstruct the partially-signed transaction attempt to verify we are signing something that at least looks like a transaction |
| 8379 | // note: the caller should further verify that the tx details are acceptable (inputs/outputs/memos/tx type) |
| 8380 | multisig::signing::tx_builder_ringct_t multisig_tx_builder; |
| 8381 | THROW_WALLET_EXCEPTION_IF( |
| 8382 | not multisig_tx_builder.init( |
| 8383 | m_account.get_keys(), |
| 8384 | ptx.construction_data.extra, |
| 8385 | ptx.construction_data.subaddr_account, |
| 8386 | ptx.construction_data.subaddr_indices, |
| 8387 | ptx.construction_data.sources, |
| 8388 | ptx.construction_data.splitted_dsts, |
| 8389 | ptx.construction_data.change_dts, |
| 8390 | ptx.construction_data.rct_config, |
| 8391 | ptx.construction_data.use_rct, |
| 8392 | true, //true = we are reconstructing the tx (it was first constructed by the tx proposer) |
| 8393 | ptx.tx_key, |
| 8394 | ptx.additional_tx_keys, |
| 8395 | ptx.multisig_tx_key_entropy, |
| 8396 | ptx.tx |
| 8397 | ), |
| 8398 | error::wallet_internal_error, |
| 8399 | "error: multisig::signing::tx_builder_ringct_t::init" |
| 8400 | ); |
| 8401 | |
| 8402 | // go through each signing attempt for this transaction (each signing attempt corresponds to some subgroup of signers |
| 8403 | // of size 'threshold') |
| 8404 | for (auto &sig: ptx.multisig_sigs) |
| 8405 | { |
| 8406 | // skip this partial tx if it's intended for a subgroup of signers that doesn't include the local signer |
| 8407 | // note: this check can only weed out signers who provided multisig_infos to the multisig tx proposer's |
| 8408 | // (initial author's) last call to import_multisig() before making this tx proposal; all other signers |
| 8409 | // will encounter a 'need to export multisig' wallet error in get_multisig_k() below |
| 8410 | // note2: the 'need to export multisig' wallet error can also appear if a bad/buggy tx proposer adds duplicate |
| 8411 | // 'used_L' to the set of tx attempts, or if two different tx proposals use the same 'used_L' values and the |
| 8412 | // local signer calls this function on both of them |
| 8413 | if (sig.ignore.find(local_signer) == sig.ignore.end()) |
| 8414 | { |
| 8415 | rct::keyM local_nonces_k(sd.selected_transfers.size(), rct::keyV(multisig::signing::kAlphaComponents)); |
| 8416 | rct::key skey = rct::zero(); |
| 8417 | auto wiper = epee::misc_utils::create_scope_leave_handler([&]{ |
| 8418 | for (auto& e: local_nonces_k) |
| 8419 | memwipe(e.data(), e.size() * sizeof(rct::key)); |
| 8420 | memwipe(&skey, sizeof(rct::key)); |
| 8421 | }); |
| 8422 | |
| 8423 | // get local signer's nonces for this transaction attempt's inputs |
| 8424 | // note: whoever created 'exported_txs' has full power to match proposed tx inputs (selected_transfers) |
| 8425 | // with the public nonces of the multisig signers who call this function (via 'used_L' as identifiers), however |
| 8426 | // the local signer will only use a given nonce exactly once (even if a used_L is repeated) |
| 8427 | for (std::size_t i = 0; i < local_nonces_k.size(); ++i) { |
| 8428 | for (std::size_t j = 0; j < multisig::signing::kAlphaComponents; ++j) { |
| 8429 | get_multisig_k(sd.selected_transfers[i], sig.used_L, local_nonces_k[i][j]); |
| 8430 | } |
| 8431 | } |
| 8432 | |
| 8433 | // round-robin signing: sign with all local multisig key shares that other signers have not signed with yet |
| 8434 | for (const auto &multisig_skey: get_account().get_multisig_keys()) |
| 8435 | { |
| 8436 | crypto::public_key multisig_pkey = get_multisig_signing_public_key(multisig_skey); |
| 8437 | |
| 8438 | if (sig.signing_keys.find(multisig_pkey) == sig.signing_keys.end()) |
| 8439 | { |
| 8440 | sc_add(skey.bytes, skey.bytes, rct::sk2rct(multisig_skey).bytes); |
| 8441 | sig.signing_keys.insert(multisig_pkey); |
| 8442 | } |
| 8443 | } |
| 8444 | |
| 8445 | THROW_WALLET_EXCEPTION_IF( |
| 8446 | not multisig_tx_builder.next_partial_sign(sig.total_alpha_G, sig.total_alpha_H, local_nonces_k, skey, sig.c_0, sig.s), |
| 8447 | error::wallet_internal_error, |
| 8448 | "error: multisig::signing::tx_builder_ringct_t::next_partial_sign" |
| 8449 | ); |
| 8450 | } |
| 8451 | } |
| 8452 | |
| 8453 | const bool is_last = exported_txs.m_signers.size() + 1 >= m_multisig_threshold; |
| 8454 | if (is_last) |
| 8455 | { |
| 8456 | // if there are signatures from enough signers (assuming the local signer signed 1+ tx attempts), find the tx |
| 8457 | // attempt with a full set of signatures so this tx can be finalized |
| 8458 | bool found = false; |
| 8459 | for (const auto &sig: ptx.multisig_sigs) |
| 8460 | { |
| 8461 | if (sig.ignore.find(local_signer) == sig.ignore.end() && !keys_intersect(sig.ignore, exported_txs.m_signers)) |
| 8462 | { |
| 8463 | THROW_WALLET_EXCEPTION_IF(found, error::wallet_internal_error, "More than one transaction is final"); |
| 8464 | THROW_WALLET_EXCEPTION_IF( |
| 8465 | not multisig_tx_builder.finalize_tx(ptx.construction_data.sources, sig.c_0, sig.s, ptx.tx), |
| 8466 | error::wallet_internal_error, |
| 8467 | "error: multisig::signing::tx_builder_ringct_t::finalize_tx" |
| 8468 | ); |
| 8469 | found = true; |
| 8470 | } |
| 8471 | } |
| 8472 | THROW_WALLET_EXCEPTION_IF(!found, error::wallet_internal_error, |
| 8473 | "Unable to finalize the transaction: the ignore sets for these tx attempts seem to be malformed."); |
| 8474 | const crypto::hash txid = get_transaction_hash(ptx.tx); |
| 8475 | if (store_tx_info()) |
| 8476 | { |
| 8477 | m_tx_keys[txid] = ptx.tx_key; |
| 8478 | m_additional_tx_keys[txid] = ptx.additional_tx_keys; |
| 8479 | } |
| 8480 | txids.push_back(txid); |
| 8481 | } |
| 8482 | } |
| 8483 | |
| 8484 | // signatures generated, get rid of any unused k values (must do export_multisig() to make more tx attempts with the |
| 8485 | // inputs in the transactions worked on here) |
| 8486 | for (size_t n = 0; n < exported_txs.m_ptx.size(); ++n) |
| 8487 | for (size_t idx: exported_txs.m_ptx[n].construction_data.selected_transfers) |
| 8488 | { |
| 8489 | memwipe(m_transfers[idx].m_multisig_k.data(), m_transfers[idx].m_multisig_k.size() * sizeof(m_transfers[idx].m_multisig_k[0])); |
| 8490 | m_transfers[idx].m_multisig_k.clear(); |
| 8491 | } |
| 8492 | |
| 8493 | exported_txs.m_signers.insert(get_multisig_signer_public_key()); |
| 8494 | |
| 8495 | return true; |
| 8496 | } |
| 8497 | //---------------------------------------------------------------------------------------------------- |
| 8498 | bool wallet2::sign_multisig_tx_to_file(multisig_tx_set &exported_txs, const std::string &filename, std::vector<crypto::hash> &txids) |
| 8499 | { |
| 8500 | bool r = sign_multisig_tx(exported_txs, txids); |
| 8501 | if (!r) |
| 8502 | return false; |
| 8503 | return save_multisig_tx(exported_txs, filename); |
| 8504 | } |
| 8505 | //---------------------------------------------------------------------------------------------------- |
| 8506 | bool wallet2::sign_multisig_tx_from_file(const std::string &filename, std::vector<crypto::hash> &txids, std::function<bool(const multisig_tx_set&)> accept_func) |
| 8507 | { |
| 8508 | multisig_tx_set exported_txs; |
| 8509 | if(!load_multisig_tx_from_file(filename, exported_txs)) |
| 8510 | return false; |
| 8511 | |
| 8512 | if (accept_func && !accept_func(exported_txs)) |
| 8513 | { |
| 8514 | LOG_PRINT_L1("Transactions rejected by callback"); |
| 8515 | return false; |
| 8516 | } |
| 8517 | return sign_multisig_tx_to_file(exported_txs, filename, txids); |
| 8518 | } |
| 8519 | //---------------------------------------------------------------------------------------------------- |
| 8520 | uint64_t wallet2::estimate_fee(bool use_per_byte_fee, bool use_rct, int n_inputs, int mixin, int n_outputs, size_t extra_size, bool bulletproof, bool clsag, bool bulletproof_plus, bool use_view_tags, uint64_t base_fee, uint64_t fee_quantization_mask) |
| 8521 | { |
| 8522 | if (use_per_byte_fee) |
| 8523 | { |
| 8524 | const size_t estimated_tx_weight = estimate_tx_weight(use_rct, n_inputs, mixin, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 8525 | return calculate_fee_from_weight(base_fee, estimated_tx_weight, fee_quantization_mask); |
| 8526 | } |
| 8527 | else |
| 8528 | { |
| 8529 | const size_t estimated_tx_size = estimate_tx_size(use_rct, n_inputs, mixin, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 8530 | return calculate_fee(base_fee, estimated_tx_size); |
| 8531 | } |
| 8532 | } |
| 8533 | |
| 8534 | uint64_t wallet2::get_fee_multiplier(uint32_t priority, int fee_algorithm) |
| 8535 | { |
| 8536 | static const struct |
| 8537 | { |
| 8538 | size_t count; |
| 8539 | uint64_t multipliers[4]; |
| 8540 | } |
| 8541 | multipliers[] = |
| 8542 | { |
| 8543 | { 3, {1, 2, 3} }, |
| 8544 | { 3, {1, 20, 166} }, |
| 8545 | { 4, {1, 4, 20, 166} }, |
| 8546 | { 4, {1, 5, 25, 1000} }, |
| 8547 | }; |
| 8548 | |
| 8549 | if (fee_algorithm == -1) |
| 8550 | fee_algorithm = get_fee_algorithm(); |
| 8551 | |
| 8552 | // 0 -> default (here, x1 till fee algorithm 2, x4 from it) |
| 8553 | if (priority == 0) |
| 8554 | priority = m_default_priority; |
| 8555 | if (priority == 0) |
| 8556 | { |
| 8557 | if (fee_algorithm >= 2) |
| 8558 | priority = 2; |
| 8559 | else |
| 8560 | priority = 1; |
| 8561 | } |
| 8562 | |
| 8563 | THROW_WALLET_EXCEPTION_IF(fee_algorithm < 0 || fee_algorithm > 3, error::invalid_priority); |
| 8564 | |
| 8565 | // 1 to 3/4 are allowed as priorities |
| 8566 | const uint32_t max_priority = multipliers[fee_algorithm].count; |
| 8567 | if (priority >= 1 && priority <= max_priority) |
| 8568 | { |
| 8569 | return multipliers[fee_algorithm].multipliers[priority-1]; |
| 8570 | } |
| 8571 | |
| 8572 | THROW_WALLET_EXCEPTION_IF (false, error::invalid_priority); |
| 8573 | return 1; |
| 8574 | } |
| 8575 | //---------------------------------------------------------------------------------------------------- |
| 8576 | uint64_t wallet2::get_dynamic_base_fee_estimate() |
| 8577 | { |
| 8578 | uint64_t fee; |
| 8579 | boost::optional<std::string> result = m_node_rpc_proxy.get_dynamic_base_fee_estimate(FEE_ESTIMATE_GRACE_BLOCKS, fee); |
| 8580 | if (!result) |
| 8581 | return fee; |
| 8582 | const uint64_t base_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE) ? FEE_PER_BYTE : FEE_PER_KB; |
| 8583 | LOG_PRINT_L1("Failed to query base fee, using " << print_money(base_fee)); |
| 8584 | return base_fee; |
| 8585 | } |
| 8586 | //---------------------------------------------------------------------------------------------------- |
| 8587 | uint64_t wallet2::get_base_fee() |
| 8588 | { |
| 8589 | if(m_light_wallet) |
| 8590 | { |
| 8591 | if (use_fork_rules(HF_VERSION_PER_BYTE_FEE)) |
| 8592 | return m_light_wallet_per_kb_fee / 1024; |
| 8593 | else |
| 8594 | return m_light_wallet_per_kb_fee; |
| 8595 | } |
| 8596 | bool use_dyn_fee = use_fork_rules(HF_VERSION_DYNAMIC_FEE, -30 * 1); |
| 8597 | if (!use_dyn_fee) |
| 8598 | return FEE_PER_KB; |
| 8599 | |
| 8600 | return get_dynamic_base_fee_estimate(); |
| 8601 | } |
| 8602 | //---------------------------------------------------------------------------------------------------- |
| 8603 | uint64_t wallet2::get_base_fee(uint32_t priority) |
| 8604 | { |
| 8605 | const bool use_2021_scaling = use_fork_rules(HF_VERSION_2021_SCALING, -30 * 1); |
| 8606 | if (use_2021_scaling) |
| 8607 | { |
| 8608 | // clamp and map to 0..3 indices, mapping 0 (default, but should not end up here) to 0, and 1..4 to 0..3 |
| 8609 | if (priority == 0) |
| 8610 | priority = 1; |
| 8611 | else if (priority > 4) |
| 8612 | priority = 4; |
| 8613 | --priority; |
| 8614 | |
| 8615 | std::vector<uint64_t> fees; |
| 8616 | boost::optional<std::string> result = m_node_rpc_proxy.get_dynamic_base_fee_estimate_2021_scaling(FEE_ESTIMATE_GRACE_BLOCKS, fees); |
| 8617 | if (result) |
| 8618 | { |
| 8619 | MERROR("Failed to determine base fee, using default"); |
| 8620 | return FEE_PER_BYTE; |
| 8621 | } |
| 8622 | if (priority >= fees.size()) |
| 8623 | { |
| 8624 | MERROR("Failed to determine base fee for priority " << priority << ", using default"); |
| 8625 | return FEE_PER_BYTE; |
| 8626 | } |
| 8627 | return fees[priority]; |
| 8628 | } |
| 8629 | else |
| 8630 | { |
| 8631 | const uint64_t base_fee = get_base_fee(); |
| 8632 | const uint64_t fee_multiplier = get_fee_multiplier(priority); |
| 8633 | return base_fee * fee_multiplier; |
| 8634 | } |
| 8635 | } |
| 8636 | //---------------------------------------------------------------------------------------------------- |
| 8637 | uint64_t wallet2::get_fee_quantization_mask() |
| 8638 | { |
| 8639 | if(m_light_wallet) |
| 8640 | { |
| 8641 | return 1; // TODO |
| 8642 | } |
| 8643 | bool use_per_byte_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0); |
| 8644 | if (!use_per_byte_fee) |
| 8645 | return 1; |
| 8646 | |
| 8647 | uint64_t fee_quantization_mask; |
| 8648 | boost::optional<std::string> result = m_node_rpc_proxy.get_fee_quantization_mask(fee_quantization_mask); |
| 8649 | if (result) |
| 8650 | return 1; |
| 8651 | return fee_quantization_mask; |
| 8652 | } |
| 8653 | //---------------------------------------------------------------------------------------------------- |
| 8654 | int wallet2::get_fee_algorithm() |
| 8655 | { |
| 8656 | // changes at v3, v5, v8 |
| 8657 | if (use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0)) |
| 8658 | return 3; |
| 8659 | if (use_fork_rules(5, 0)) |
| 8660 | return 2; |
| 8661 | if (use_fork_rules(3, -30 * 14)) |
| 8662 | return 1; |
| 8663 | return 0; |
| 8664 | } |
| 8665 | //------------------------------------------------------------------------------------------------------------------------------ |
| 8666 | uint64_t wallet2::get_min_ring_size() |
| 8667 | { |
| 8668 | if (use_fork_rules(HF_VERSION_MIN_MIXIN_15, 0)) |
| 8669 | return 16; |
| 8670 | if (use_fork_rules(8, 10)) |
| 8671 | return 11; |
| 8672 | if (use_fork_rules(7, 10)) |
| 8673 | return 7; |
| 8674 | if (use_fork_rules(6, 10)) |
| 8675 | return 5; |
| 8676 | if (use_fork_rules(2, 10)) |
| 8677 | return 3; |
| 8678 | return 0; |
| 8679 | } |
| 8680 | //------------------------------------------------------------------------------------------------------------------------------ |
| 8681 | uint64_t wallet2::get_max_ring_size() |
| 8682 | { |
| 8683 | if (use_fork_rules(HF_VERSION_MIN_MIXIN_15, 0)) |
| 8684 | return 16; |
| 8685 | if (use_fork_rules(8, 10)) |
| 8686 | return 11; |
| 8687 | return 0; |
| 8688 | } |
| 8689 | //------------------------------------------------------------------------------------------------------------------------------ |
| 8690 | uint64_t wallet2::adjust_mixin(uint64_t mixin) |
| 8691 | { |
| 8692 | const uint64_t min_ring_size = get_min_ring_size(); |
| 8693 | if (mixin + 1 < min_ring_size) |
| 8694 | { |
| 8695 | MWARNING("Requested ring size " << (mixin + 1) << " too low, using " << min_ring_size); |
| 8696 | mixin = min_ring_size-1; |
| 8697 | } |
| 8698 | const uint64_t max_ring_size = get_max_ring_size(); |
| 8699 | if (max_ring_size && mixin + 1 > max_ring_size) |
| 8700 | { |
| 8701 | MWARNING("Requested ring size " << (mixin + 1) << " too high, using " << max_ring_size); |
| 8702 | mixin = max_ring_size-1; |
| 8703 | } |
| 8704 | return mixin; |
| 8705 | } |
| 8706 | //---------------------------------------------------------------------------------------------------- |
| 8707 | uint32_t wallet2::adjust_priority(uint32_t priority) |
| 8708 | { |
| 8709 | if (priority == 0 && m_default_priority == 0 && auto_low_priority()) |
| 8710 | { |
| 8711 | try |
| 8712 | { |
| 8713 | // check if there's a backlog in the tx pool |
| 8714 | const bool use_per_byte_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0); |
| 8715 | const uint64_t base_fee = get_base_fee(1); |
| 8716 | const double fee_level = base_fee * (use_per_byte_fee ? 1 : (12/(double)13 / (double)1024)); |
| 8717 | const std::vector<std::pair<uint64_t, uint64_t>> blocks = estimate_backlog({std::make_pair(fee_level, fee_level)}); |
| 8718 | if (blocks.size() != 1) |
| 8719 | { |
| 8720 | MERROR("Bad estimated backlog array size"); |
| 8721 | return priority; |
| 8722 | } |
| 8723 | else if (blocks[0].first > 0) |
| 8724 | { |
| 8725 | MINFO("We don't use the low priority because there's a backlog in the tx pool."); |
| 8726 | return 2; |
| 8727 | } |
| 8728 | |
| 8729 | // get the current full reward zone |
| 8730 | uint64_t block_weight_limit = 0; |
| 8731 | const auto result = m_node_rpc_proxy.get_block_weight_limit(block_weight_limit); |
| 8732 | if (result) |
| 8733 | return priority; |
| 8734 | const uint64_t full_reward_zone = block_weight_limit / 2; |
| 8735 | |
| 8736 | // get the last N block headers and sum the block sizes |
| 8737 | const size_t N = 10; |
| 8738 | if (m_blockchain.size() < N) |
| 8739 | { |
| 8740 | MERROR("The blockchain is too short"); |
| 8741 | return priority; |
| 8742 | } |
| 8743 | cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request getbh_req = AUTO_VAL_INIT(getbh_req); |
| 8744 | cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response getbh_res = AUTO_VAL_INIT(getbh_res); |
| 8745 | getbh_req.start_height = m_blockchain.size() - N; |
| 8746 | getbh_req.end_height = m_blockchain.size() - 1; |
| 8747 | |
| 8748 | { |
| 8749 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 8750 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 8751 | getbh_req.client = get_client_signature(); |
| 8752 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "getblockheadersrange", getbh_req, getbh_res, *m_http_client, rpc_timeout); |
| 8753 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, getbh_res, "getblockheadersrange", error::get_blocks_error, get_rpc_status(getbh_res.status)); |
| 8754 | check_rpc_cost("/getblockheadersrange", getbh_res.credits, pre_call_credits, N * COST_PER_BLOCK_HEADER); |
| 8755 | } |
| 8756 | |
| 8757 | if (getbh_res.headers.size() != N) |
| 8758 | { |
| 8759 | MERROR("Bad blockheaders size"); |
| 8760 | return priority; |
| 8761 | } |
| 8762 | size_t block_weight_sum = 0; |
| 8763 | for (const cryptonote::block_header_response &i : getbh_res.headers) |
| 8764 | { |
| 8765 | block_weight_sum += i.block_weight; |
| 8766 | } |
| 8767 | |
| 8768 | // estimate how 'full' the last N blocks are |
| 8769 | const size_t P = 100 * block_weight_sum / (N * full_reward_zone); |
| 8770 | MINFO((boost::format("The last %d blocks fill roughly %d%% of the full reward zone.") % N % P).str()); |
| 8771 | if (P > 80) |
| 8772 | { |
| 8773 | MINFO("We don't use the low priority because recent blocks are quite full."); |
| 8774 | return 2; |
| 8775 | } |
| 8776 | MINFO("We'll use the low priority because probably it's safe to do so."); |
| 8777 | return 1; |
| 8778 | } |
| 8779 | catch (const std::exception &e) |
| 8780 | { |
| 8781 | MERROR(e.what()); |
| 8782 | } |
| 8783 | } |
| 8784 | return priority; |
| 8785 | } |
| 8786 | //---------------------------------------------------------------------------------------------------- |
| 8787 | bool wallet2::set_ring_database(const std::string &filename) |
| 8788 | { |
| 8789 | m_ring_database = filename; |
| 8790 | MINFO("ringdb path set to " << filename); |
| 8791 | m_ringdb.reset(); |
| 8792 | if (!m_ring_database.empty()) |
| 8793 | { |
| 8794 | try |
| 8795 | { |
| 8796 | cryptonote::block b; |
| 8797 | generate_genesis(b); |
| 8798 | m_ringdb.reset(new tools::ringdb(m_ring_database, epee::string_tools::pod_to_hex(get_block_hash(b)))); |
| 8799 | } |
| 8800 | catch (const std::exception &e) |
| 8801 | { |
| 8802 | MERROR("Failed to initialize ringdb: " << e.what()); |
| 8803 | m_ring_database = ""; |
| 8804 | return false; |
| 8805 | } |
| 8806 | } |
| 8807 | return true; |
| 8808 | } |
| 8809 | |
| 8810 | crypto::chacha_key wallet2::get_ringdb_key() |
| 8811 | { |
| 8812 | if (!m_ringdb_key) |
| 8813 | { |
| 8814 | MINFO("caching ringdb key"); |
| 8815 | crypto::chacha_key key; |
| 8816 | generate_chacha_key_from_secret_keys(key); |
| 8817 | m_ringdb_key = key; |
| 8818 | } |
| 8819 | return *m_ringdb_key; |
| 8820 | } |
| 8821 | |
| 8822 | void wallet2::register_devices(){ |
| 8823 | hw::trezor::register_all(); |
| 8824 | } |
| 8825 | |
| 8826 | hw::device& wallet2::lookup_device(const std::string & device_descriptor){ |
| 8827 | if (!m_devices_registered){ |
| 8828 | m_devices_registered = true; |
| 8829 | register_devices(); |
| 8830 | } |
| 8831 | |
| 8832 | return hw::get_device(device_descriptor); |
| 8833 | } |
| 8834 | |
| 8835 | bool wallet2::add_rings(const crypto::chacha_key &key, const cryptonote::transaction_prefix &tx) |
| 8836 | { |
| 8837 | if (!m_ringdb) |
| 8838 | return false; |
| 8839 | try { return m_ringdb->add_rings(key, tx); } |
| 8840 | catch (const std::exception &e) { return false; } |
| 8841 | } |
| 8842 | |
| 8843 | bool wallet2::add_rings(const cryptonote::transaction_prefix &tx) |
| 8844 | { |
| 8845 | try { return add_rings(get_ringdb_key(), tx); } |
| 8846 | catch (const std::exception &e) { return false; } |
| 8847 | } |
| 8848 | |
| 8849 | bool wallet2::remove_rings(const cryptonote::transaction_prefix &tx) |
| 8850 | { |
| 8851 | if (!m_ringdb) |
| 8852 | return false; |
| 8853 | try { return m_ringdb->remove_rings(get_ringdb_key(), tx); } |
| 8854 | catch (const std::exception &e) { return false; } |
| 8855 | } |
| 8856 | |
| 8857 | bool wallet2::get_ring(const crypto::chacha_key &key, const crypto::key_image &key_image, std::vector<uint64_t> &outs) |
| 8858 | { |
| 8859 | if (!m_ringdb) |
| 8860 | return false; |
| 8861 | try { return m_ringdb->get_ring(key, key_image, outs); } |
| 8862 | catch (const std::exception &e) { return false; } |
| 8863 | } |
| 8864 | |
| 8865 | bool wallet2::get_rings(const crypto::chacha_key &key, const std::vector<crypto::key_image> &key_images, std::vector<std::vector<uint64_t>> &outs) |
| 8866 | { |
| 8867 | if (!m_ringdb) |
| 8868 | return false; |
| 8869 | try { return m_ringdb->get_rings(key, key_images, outs); } |
| 8870 | catch (const std::exception &e) { return false; } |
| 8871 | } |
| 8872 | |
| 8873 | bool wallet2::get_rings(const crypto::hash &txid, std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> &outs) |
| 8874 | { |
| 8875 | for (auto i: m_confirmed_txs) |
| 8876 | { |
| 8877 | if (txid == i.first) |
| 8878 | { |
| 8879 | for (const auto &x: i.second.m_rings) |
| 8880 | outs.push_back({x.first, cryptonote::relative_output_offsets_to_absolute(x.second)}); |
| 8881 | return true; |
| 8882 | } |
| 8883 | } |
| 8884 | for (auto i: m_unconfirmed_txs) |
| 8885 | { |
| 8886 | if (txid == i.first) |
| 8887 | { |
| 8888 | for (const auto &x: i.second.m_rings) |
| 8889 | outs.push_back({x.first, cryptonote::relative_output_offsets_to_absolute(x.second)}); |
| 8890 | return true; |
| 8891 | } |
| 8892 | } |
| 8893 | return false; |
| 8894 | } |
| 8895 | |
| 8896 | bool wallet2::get_ring(const crypto::key_image &key_image, std::vector<uint64_t> &outs) |
| 8897 | { |
| 8898 | try { return get_ring(get_ringdb_key(), key_image, outs); } |
| 8899 | catch (const std::exception &e) { return false; } |
| 8900 | } |
| 8901 | |
| 8902 | bool wallet2::set_ring(const crypto::key_image &key_image, const std::vector<uint64_t> &outs, bool relative) |
| 8903 | { |
| 8904 | if (!m_ringdb) |
| 8905 | return false; |
| 8906 | |
| 8907 | try { return m_ringdb->set_ring(get_ringdb_key(), key_image, outs, relative); } |
| 8908 | catch (const std::exception &e) { return false; } |
| 8909 | } |
| 8910 | |
| 8911 | bool wallet2::set_rings(const std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> &rings, bool relative) |
| 8912 | { |
| 8913 | if (!m_ringdb) |
| 8914 | return false; |
| 8915 | |
| 8916 | try { return m_ringdb->set_rings(get_ringdb_key(), rings, relative); } |
| 8917 | catch (const std::exception &e) { return false; } |
| 8918 | } |
| 8919 | |
| 8920 | bool wallet2::unset_ring(const std::vector<crypto::key_image> &key_images) |
| 8921 | { |
| 8922 | if (!m_ringdb) |
| 8923 | return false; |
| 8924 | |
| 8925 | try { return m_ringdb->remove_rings(get_ringdb_key(), key_images); } |
| 8926 | catch (const std::exception &e) { return false; } |
| 8927 | } |
| 8928 | |
| 8929 | bool wallet2::unset_ring(const crypto::hash &txid) |
| 8930 | { |
| 8931 | if (!m_ringdb) |
| 8932 | return false; |
| 8933 | |
| 8934 | COMMAND_RPC_GET_TRANSACTIONS::request req; |
| 8935 | COMMAND_RPC_GET_TRANSACTIONS::response res; |
| 8936 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 8937 | req.decode_as_json = false; |
| 8938 | req.prune = true; |
| 8939 | m_daemon_rpc_mutex.lock(); |
| 8940 | bool ok = invoke_http_json("/gettransactions", req, res, rpc_timeout); |
| 8941 | m_daemon_rpc_mutex.unlock(); |
| 8942 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 8943 | THROW_WALLET_EXCEPTION_IF(res.txs.size() != 1, error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 8944 | |
| 8945 | cryptonote::transaction tx; |
| 8946 | crypto::hash tx_hash; |
| 8947 | if (!get_pruned_tx(res.txs.front(), tx, tx_hash)) |
| 8948 | return false; |
| 8949 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 8950 | |
| 8951 | try { return m_ringdb->remove_rings(get_ringdb_key(), tx); } |
| 8952 | catch (const std::exception &e) { return false; } |
| 8953 | } |
| 8954 | |
| 8955 | bool wallet2::find_and_save_rings(bool force) |
| 8956 | { |
| 8957 | if (force) |
| 8958 | { |
| 8959 | MWARNING("wallet2::find_and_save_rings() is deprecated"); |
| 8960 | return false; |
| 8961 | } |
| 8962 | m_ring_history_saved = true; |
| 8963 | return true; |
| 8964 | } |
| 8965 | |
| 8966 | bool wallet2::blackball_output(const std::pair<uint64_t, uint64_t> &output) |
| 8967 | { |
| 8968 | if (!m_ringdb) |
| 8969 | return false; |
| 8970 | try { return m_ringdb->blackball(output); } |
| 8971 | catch (const std::exception &e) { return false; } |
| 8972 | } |
| 8973 | |
| 8974 | bool wallet2::set_blackballed_outputs(const std::vector<std::pair<uint64_t, uint64_t>> &outputs, bool add) |
| 8975 | { |
| 8976 | if (!m_ringdb) |
| 8977 | return false; |
| 8978 | try |
| 8979 | { |
| 8980 | bool ret = true; |
| 8981 | if (!add) |
| 8982 | ret &= m_ringdb->clear_blackballs(); |
| 8983 | ret &= m_ringdb->blackball(outputs); |
| 8984 | return ret; |
| 8985 | } |
| 8986 | catch (const std::exception &e) { return false; } |
| 8987 | } |
| 8988 | |
| 8989 | bool wallet2::unblackball_output(const std::pair<uint64_t, uint64_t> &output) |
| 8990 | { |
| 8991 | if (!m_ringdb) |
| 8992 | return false; |
| 8993 | try { return m_ringdb->unblackball(output); } |
| 8994 | catch (const std::exception &e) { return false; } |
| 8995 | } |
| 8996 | |
| 8997 | bool wallet2::is_output_blackballed(const std::pair<uint64_t, uint64_t> &output) const |
| 8998 | { |
| 8999 | if (!m_ringdb) |
| 9000 | return false; |
| 9001 | try { return m_ringdb->blackballed(output); } |
| 9002 | catch (const std::exception &e) { return false; } |
| 9003 | } |
| 9004 | |
| 9005 | bool wallet2::lock_keys_file() |
| 9006 | { |
| 9007 | if (m_wallet_file.empty()) |
| 9008 | return true; |
| 9009 | if (m_keys_file_locker) |
| 9010 | { |
| 9011 | MDEBUG(m_keys_file << " is already locked."); |
| 9012 | return false; |
| 9013 | } |
| 9014 | m_keys_file_locker.reset(new tools::file_locker(m_keys_file)); |
| 9015 | return true; |
| 9016 | } |
| 9017 | |
| 9018 | bool wallet2::unlock_keys_file() |
| 9019 | { |
| 9020 | if (m_wallet_file.empty()) |
| 9021 | return true; |
| 9022 | if (!m_keys_file_locker) |
| 9023 | { |
| 9024 | MDEBUG(m_keys_file << " is already unlocked."); |
| 9025 | return false; |
| 9026 | } |
| 9027 | m_keys_file_locker.reset(); |
| 9028 | return true; |
| 9029 | } |
| 9030 | |
| 9031 | bool wallet2::is_keys_file_locked() const |
| 9032 | { |
| 9033 | if (m_wallet_file.empty()) |
| 9034 | return false; |
| 9035 | return m_keys_file_locker->locked(); |
| 9036 | } |
| 9037 | |
| 9038 | bool wallet2::lock_background_keys_file(const std::string &background_keys_file) |
| 9039 | { |
| 9040 | if (background_keys_file.empty() || !boost::filesystem::exists(background_keys_file)) |
| 9041 | return true; |
| 9042 | if (m_background_keys_file_locker && m_background_keys_file_locker->locked()) |
| 9043 | return true; |
| 9044 | m_background_keys_file_locker.reset(new tools::file_locker(background_keys_file)); |
| 9045 | return m_background_keys_file_locker->locked(); |
| 9046 | } |
| 9047 | |
| 9048 | bool wallet2::unlock_background_keys_file() |
| 9049 | { |
| 9050 | if (!m_background_keys_file_locker) |
| 9051 | { |
| 9052 | MDEBUG("background keys file locker is not set"); |
| 9053 | return false; |
| 9054 | } |
| 9055 | m_background_keys_file_locker.reset(); |
| 9056 | return true; |
| 9057 | } |
| 9058 | |
| 9059 | bool wallet2::is_background_keys_file_locked() const |
| 9060 | { |
| 9061 | if (!m_background_keys_file_locker) |
| 9062 | return false; |
| 9063 | return m_background_keys_file_locker->locked(); |
| 9064 | } |
| 9065 | |
| 9066 | bool wallet2::tx_add_fake_output(std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, uint64_t global_index, const crypto::public_key& output_public_key, const rct::key& mask, uint64_t real_index, bool unlocked, std::unordered_set<crypto::public_key> &valid_public_keys_cache) const |
| 9067 | { |
| 9068 | if (!unlocked) // don't add locked outs |
| 9069 | return false; |
| 9070 | if (global_index == real_index) // don't re-add real one |
| 9071 | return false; |
| 9072 | auto item = std::make_tuple(global_index, output_public_key, mask); |
| 9073 | CHECK_AND_ASSERT_MES(!outs.empty(), false, "internal error: outs is empty"); |
| 9074 | if (std::find(outs.back().begin(), outs.back().end(), item) != outs.back().end()) // don't add duplicates |
| 9075 | return false; |
| 9076 | // check the keys are valid |
| 9077 | if (valid_public_keys_cache.find(output_public_key) == valid_public_keys_cache.end() && !rct::isInMainSubgroup(rct::pk2rct(output_public_key))) |
| 9078 | { |
| 9079 | MWARNING("Key " << output_public_key << " at index " << global_index << " is not in the main subgroup"); |
| 9080 | return false; |
| 9081 | } |
| 9082 | valid_public_keys_cache.insert(output_public_key); |
| 9083 | if (valid_public_keys_cache.find(rct::rct2pk(mask)) == valid_public_keys_cache.end() && !rct::isInMainSubgroup(mask)) |
| 9084 | { |
| 9085 | MWARNING("Commitment " << mask << " at index " << global_index << " is not in the main subgroup"); |
| 9086 | return false; |
| 9087 | } |
| 9088 | valid_public_keys_cache.insert(rct::rct2pk(mask)); |
| 9089 | // if (is_output_blackballed(output_public_key)) // don't add blackballed outputs |
| 9090 | // return false; |
| 9091 | outs.back().push_back(item); |
| 9092 | return true; |
| 9093 | } |
| 9094 | |
| 9095 | void wallet2::light_wallet_get_outs(std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, const std::vector<size_t> &selected_transfers, size_t fake_outputs_count) { |
| 9096 | |
| 9097 | MDEBUG("LIGHTWALLET - Getting random outs"); |
| 9098 | |
| 9099 | tools::COMMAND_RPC_GET_RANDOM_OUTS::request oreq; |
| 9100 | tools::COMMAND_RPC_GET_RANDOM_OUTS::response ores; |
| 9101 | |
| 9102 | size_t light_wallet_requested_outputs_count = (size_t)((fake_outputs_count + 1) * 1.5 + 1); |
| 9103 | |
| 9104 | // Amounts to ask for |
| 9105 | // MyMonero api handle amounts and fees as strings |
| 9106 | for(size_t idx: selected_transfers) { |
| 9107 | const uint64_t ask_amount = m_transfers[idx].is_rct() ? 0 : m_transfers[idx].amount(); |
| 9108 | std::ostringstream amount_ss; |
| 9109 | amount_ss << ask_amount; |
| 9110 | oreq.amounts.push_back(amount_ss.str()); |
| 9111 | } |
| 9112 | |
| 9113 | oreq.count = light_wallet_requested_outputs_count; |
| 9114 | |
| 9115 | { |
| 9116 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 9117 | bool r = epee::net_utils::invoke_http_json("/get_random_outs", oreq, ores, *m_http_client, rpc_timeout, "POST"); |
| 9118 | m_daemon_rpc_mutex.unlock(); |
| 9119 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_random_outs"); |
| 9120 | THROW_WALLET_EXCEPTION_IF(ores.amount_outs.empty() , error::wallet_internal_error, "No outputs received from light wallet node. Error: " + ores.Error); |
| 9121 | } |
| 9122 | |
| 9123 | // Check if we got enough outputs for each amount |
| 9124 | for(auto& out: ores.amount_outs) { |
| 9125 | THROW_WALLET_EXCEPTION_IF(out.outputs.size() < light_wallet_requested_outputs_count , error::wallet_internal_error, "Not enough outputs for amount: " + boost::lexical_cast<std::string>(out.amount)); |
| 9126 | MDEBUG(out.outputs.size() << " outputs for amount "+ boost::lexical_cast<std::string>(out.amount) + " received from light wallet node"); |
| 9127 | } |
| 9128 | |
| 9129 | MDEBUG("selected transfers size: " << selected_transfers.size()); |
| 9130 | |
| 9131 | std::unordered_set<crypto::public_key> valid_public_keys_cache; |
| 9132 | for(size_t idx: selected_transfers) |
| 9133 | { |
| 9134 | // Create new index |
| 9135 | outs.push_back(std::vector<get_outs_entry>()); |
| 9136 | outs.back().reserve(fake_outputs_count + 1); |
| 9137 | |
| 9138 | // add real output first |
| 9139 | const transfer_details &td = m_transfers[idx]; |
| 9140 | const uint64_t amount = td.is_rct() ? 0 : td.amount(); |
| 9141 | outs.back().push_back(std::make_tuple(td.m_global_output_index, td.get_public_key(), rct::commit(td.amount(), td.m_mask))); |
| 9142 | MDEBUG("added real output " << string_tools::pod_to_hex(td.get_public_key())); |
| 9143 | |
| 9144 | // Even if the lightwallet server returns random outputs, we pick them randomly. |
| 9145 | std::vector<size_t> order; |
| 9146 | order.resize(light_wallet_requested_outputs_count); |
| 9147 | for (size_t n = 0; n < order.size(); ++n) |
| 9148 | order[n] = n; |
| 9149 | std::shuffle(order.begin(), order.end(), crypto::random_device{}); |
| 9150 | |
| 9151 | |
| 9152 | LOG_PRINT_L2("Looking for " << (fake_outputs_count+1) << " outputs with amounts " << print_money(td.is_rct() ? 0 : td.amount())); |
| 9153 | MDEBUG("OUTS SIZE: " << outs.back().size()); |
| 9154 | for (size_t o = 0; o < light_wallet_requested_outputs_count && outs.back().size() < fake_outputs_count + 1; ++o) |
| 9155 | { |
| 9156 | // Random pick |
| 9157 | size_t i = order[o]; |
| 9158 | |
| 9159 | // Find which random output key to use |
| 9160 | bool found_amount = false; |
| 9161 | size_t amount_key; |
| 9162 | for(amount_key = 0; amount_key < ores.amount_outs.size(); ++amount_key) |
| 9163 | { |
| 9164 | if(boost::lexical_cast<uint64_t>(ores.amount_outs[amount_key].amount) == amount) { |
| 9165 | found_amount = true; |
| 9166 | break; |
| 9167 | } |
| 9168 | } |
| 9169 | THROW_WALLET_EXCEPTION_IF(!found_amount , error::wallet_internal_error, "Outputs for amount " + boost::lexical_cast<std::string>(ores.amount_outs[amount_key].amount) + " not found" ); |
| 9170 | |
| 9171 | LOG_PRINT_L2("Index " << i << "/" << light_wallet_requested_outputs_count << ": idx " << ores.amount_outs[amount_key].outputs[i].global_index << " (real " << td.m_global_output_index << "), unlocked " << "(always in light)" << ", key " << ores.amount_outs[0].outputs[i].public_key); |
| 9172 | |
| 9173 | // Convert light wallet string data to proper data structures |
| 9174 | crypto::public_key tx_public_key; |
| 9175 | rct::key mask = AUTO_VAL_INIT(mask); // decrypted mask - not used here |
| 9176 | rct::key rct_commit = AUTO_VAL_INIT(rct_commit); |
| 9177 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, ores.amount_outs[amount_key].outputs[i].public_key), error::wallet_internal_error, "Invalid public_key"); |
| 9178 | string_tools::hex_to_pod(ores.amount_outs[amount_key].outputs[i].public_key, tx_public_key); |
| 9179 | const uint64_t global_index = ores.amount_outs[amount_key].outputs[i].global_index; |
| 9180 | if(!light_wallet_parse_rct_str(ores.amount_outs[amount_key].outputs[i].rct, tx_public_key, 0, mask, rct_commit, false)) |
| 9181 | rct_commit = rct::zeroCommit(td.amount()); |
| 9182 | |
| 9183 | if (tx_add_fake_output(outs, global_index, tx_public_key, rct_commit, td.m_global_output_index, true, valid_public_keys_cache)) { |
| 9184 | MDEBUG("added fake output " << ores.amount_outs[amount_key].outputs[i].public_key); |
| 9185 | MDEBUG("index " << global_index); |
| 9186 | } |
| 9187 | } |
| 9188 | |
| 9189 | THROW_WALLET_EXCEPTION_IF(outs.back().size() < fake_outputs_count + 1 , error::wallet_internal_error, "Not enough fake outputs found" ); |
| 9190 | |
| 9191 | // Real output is the first. Shuffle outputs |
| 9192 | MTRACE(outs.back().size() << " outputs added. Sorting outputs by index:"); |
| 9193 | 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); }); |
| 9194 | |
| 9195 | // Print output order |
| 9196 | for(auto added_out: outs.back()) |
| 9197 | MTRACE(std::get<0>(added_out)); |
| 9198 | |
| 9199 | } |
| 9200 | } |
| 9201 | |
| 9202 | std::pair<std::set<uint64_t>, size_t> outs_unique(const std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs) |
| 9203 | { |
| 9204 | std::set<uint64_t> unique; |
| 9205 | size_t total = 0; |
| 9206 | |
| 9207 | for (const auto &it : outs) |
| 9208 | { |
| 9209 | for (const auto &out : it) |
| 9210 | { |
| 9211 | const uint64_t global_index = std::get<0>(out); |
| 9212 | unique.insert(global_index); |
| 9213 | } |
| 9214 | total += it.size(); |
| 9215 | } |
| 9216 | |
| 9217 | return std::make_pair(std::move(unique), total); |
| 9218 | } |
| 9219 | |
| 9220 | void wallet2::get_outs(std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, const std::vector<size_t> &selected_transfers, size_t fake_outputs_count, bool rct, std::unordered_set<crypto::public_key> &valid_public_keys_cache) |
| 9221 | { |
| 9222 | std::vector<uint64_t> rct_offsets; |
| 9223 | for (size_t attempts = 3; attempts > 0; --attempts) |
| 9224 | { |
| 9225 | get_outs(outs, selected_transfers, fake_outputs_count, rct_offsets, valid_public_keys_cache); |
| 9226 | |
| 9227 | if (!rct) |
| 9228 | return; |
| 9229 | |
| 9230 | const auto unique = outs_unique(outs); |
| 9231 | if (tx_sanity_check(unique.first, unique.second, rct_offsets.empty() ? 0 : rct_offsets.back())) |
| 9232 | { |
| 9233 | return; |
| 9234 | } |
| 9235 | |
| 9236 | std::vector<crypto::key_image> key_images; |
| 9237 | key_images.reserve(selected_transfers.size()); |
| 9238 | std::for_each(selected_transfers.begin(), selected_transfers.end(), [this, &key_images](size_t index) { |
| 9239 | key_images.push_back(m_transfers[index].m_key_image); |
| 9240 | }); |
| 9241 | unset_ring(key_images); |
| 9242 | } |
| 9243 | |
| 9244 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, tr("Transaction sanity check failed")); |
| 9245 | } |
| 9246 | |
| 9247 | void wallet2::get_outs(std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, const std::vector<size_t> &selected_transfers, size_t fake_outputs_count, std::vector<uint64_t> &rct_offsets, std::unordered_set<crypto::public_key> &valid_public_keys_cache) |
| 9248 | { |
| 9249 | LOG_PRINT_L2("fake_outputs_count: " << fake_outputs_count); |
| 9250 | outs.clear(); |
| 9251 | |
| 9252 | if(m_light_wallet && fake_outputs_count > 0) { |
| 9253 | light_wallet_get_outs(outs, selected_transfers, fake_outputs_count); |
| 9254 | return; |
| 9255 | } |
| 9256 | |
| 9257 | if (fake_outputs_count > 0) |
| 9258 | { |
| 9259 | uint64_t segregation_fork_height = get_segregation_fork_height(); |
| 9260 | // check whether we're shortly after the fork |
| 9261 | uint64_t height; |
| 9262 | boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); |
| 9263 | THROW_WALLET_EXCEPTION_IF(result, error::wallet_internal_error, "Failed to get height"); |
| 9264 | bool is_shortly_after_segregation_fork = height >= segregation_fork_height && height < segregation_fork_height + SEGREGATION_FORK_VICINITY; |
| 9265 | bool is_after_segregation_fork = height >= segregation_fork_height; |
| 9266 | |
| 9267 | // if we have at least one rct out, get the distribution, or fall back to the previous system |
| 9268 | uint64_t rct_start_height; |
| 9269 | bool has_rct = false; |
| 9270 | uint64_t max_rct_index = 0; |
| 9271 | for (size_t idx: selected_transfers) |
| 9272 | if (m_transfers[idx].is_rct()) |
| 9273 | { |
| 9274 | has_rct = true; |
| 9275 | max_rct_index = std::max(max_rct_index, m_transfers[idx].m_global_output_index); |
| 9276 | } |
| 9277 | |
| 9278 | if (has_rct && rct_offsets.empty()) { |
| 9279 | THROW_WALLET_EXCEPTION_IF(!get_rct_distribution(rct_start_height, rct_offsets), |
| 9280 | error::get_output_distribution, "Could not obtain output distribution."); |
| 9281 | } |
| 9282 | |
| 9283 | if (has_rct) |
| 9284 | { |
| 9285 | // check we're clear enough of rct start, to avoid corner cases below |
| 9286 | THROW_WALLET_EXCEPTION_IF(rct_offsets.size() <= CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE, |
| 9287 | error::get_output_distribution, "Not enough rct outputs"); |
| 9288 | THROW_WALLET_EXCEPTION_IF(rct_offsets.back() <= max_rct_index, |
| 9289 | error::get_output_distribution, "Daemon reports suspicious number of rct outputs"); |
| 9290 | } |
| 9291 | |
| 9292 | // get histogram for the amounts we need |
| 9293 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request req_t = AUTO_VAL_INIT(req_t); |
| 9294 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response resp_t = AUTO_VAL_INIT(resp_t); |
| 9295 | // request histogram for all pre-rct outputs |
| 9296 | req_t.amounts.reserve(selected_transfers.size()); |
| 9297 | for(size_t idx: selected_transfers) |
| 9298 | if (!m_transfers[idx].is_rct()) |
| 9299 | req_t.amounts.push_back(m_transfers[idx].amount()); |
| 9300 | if (!req_t.amounts.empty()) |
| 9301 | { |
| 9302 | std::sort(req_t.amounts.begin(), req_t.amounts.end()); |
| 9303 | auto end = std::unique(req_t.amounts.begin(), req_t.amounts.end()); |
| 9304 | req_t.amounts.resize(std::distance(req_t.amounts.begin(), end)); |
| 9305 | req_t.unlocked = true; |
| 9306 | req_t.recent_cutoff = time(NULL) - RECENT_OUTPUT_ZONE; |
| 9307 | |
| 9308 | { |
| 9309 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 9310 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 9311 | req_t.client = get_client_signature(); |
| 9312 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "get_output_histogram", req_t, resp_t, *m_http_client, rpc_timeout); |
| 9313 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, resp_t, "get_output_histogram", error::get_histogram_error, get_rpc_status(resp_t.status)); |
| 9314 | check_rpc_cost("get_output_histogram", resp_t.credits, pre_call_credits, COST_PER_OUTPUT_HISTOGRAM * req_t.amounts.size()); |
| 9315 | } |
| 9316 | } |
| 9317 | |
| 9318 | // if we want to segregate fake outs pre or post fork, get distribution |
| 9319 | std::unordered_map<uint64_t, std::pair<uint64_t, uint64_t>> segregation_limit; |
| 9320 | if (is_after_segregation_fork && (m_segregate_pre_fork_outputs || m_key_reuse_mitigation2)) |
| 9321 | { |
| 9322 | cryptonote::COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::request req_t = AUTO_VAL_INIT(req_t); |
| 9323 | cryptonote::COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::response resp_t = AUTO_VAL_INIT(resp_t); |
| 9324 | req_t.amounts.reserve(req_t.amounts.size() + selected_transfers.size()); |
| 9325 | for(size_t idx: selected_transfers) |
| 9326 | req_t.amounts.push_back(m_transfers[idx].is_rct() ? 0 : m_transfers[idx].amount()); |
| 9327 | std::sort(req_t.amounts.begin(), req_t.amounts.end()); |
| 9328 | auto end = std::unique(req_t.amounts.begin(), req_t.amounts.end()); |
| 9329 | req_t.amounts.resize(std::distance(req_t.amounts.begin(), end)); |
| 9330 | req_t.from_height = std::max<uint64_t>(segregation_fork_height, RECENT_OUTPUT_BLOCKS) - RECENT_OUTPUT_BLOCKS; |
| 9331 | req_t.to_height = segregation_fork_height + 1; |
| 9332 | req_t.cumulative = true; |
| 9333 | req_t.binary = true; |
| 9334 | |
| 9335 | { |
| 9336 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 9337 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 9338 | req_t.client = get_client_signature(); |
| 9339 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "get_output_distribution", req_t, resp_t, *m_http_client, rpc_timeout * 1000); |
| 9340 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, resp_t, "get_output_distribution", error::get_output_distribution, get_rpc_status(resp_t.status)); |
| 9341 | uint64_t expected_cost = 0; |
| 9342 | for (uint64_t amount: req_t.amounts) expected_cost += (amount ? COST_PER_OUTPUT_DISTRIBUTION : COST_PER_OUTPUT_DISTRIBUTION_0); |
| 9343 | check_rpc_cost("get_output_distribution", resp_t.credits, pre_call_credits, expected_cost); |
| 9344 | } |
| 9345 | |
| 9346 | // check we got all data |
| 9347 | for(size_t idx: selected_transfers) |
| 9348 | { |
| 9349 | const uint64_t amount = m_transfers[idx].is_rct() ? 0 : m_transfers[idx].amount(); |
| 9350 | bool found = false; |
| 9351 | for (const auto &d: resp_t.distributions) |
| 9352 | { |
| 9353 | if (d.amount == amount) |
| 9354 | { |
| 9355 | THROW_WALLET_EXCEPTION_IF(d.data.start_height > segregation_fork_height, error::get_output_distribution, "Distribution start_height too high"); |
| 9356 | THROW_WALLET_EXCEPTION_IF(segregation_fork_height - d.data.start_height >= d.data.distribution.size(), error::get_output_distribution, "Distribution size too small"); |
| 9357 | THROW_WALLET_EXCEPTION_IF(segregation_fork_height - RECENT_OUTPUT_BLOCKS - d.data.start_height >= d.data.distribution.size(), error::get_output_distribution, "Distribution size too small"); |
| 9358 | THROW_WALLET_EXCEPTION_IF(segregation_fork_height <= RECENT_OUTPUT_BLOCKS, error::wallet_internal_error, "Fork height too low"); |
| 9359 | THROW_WALLET_EXCEPTION_IF(segregation_fork_height - RECENT_OUTPUT_BLOCKS < d.data.start_height, error::get_output_distribution, "Bad start height"); |
| 9360 | uint64_t till_fork = d.data.distribution[segregation_fork_height - d.data.start_height]; |
| 9361 | uint64_t recent = till_fork - d.data.distribution[segregation_fork_height - RECENT_OUTPUT_BLOCKS - d.data.start_height]; |
| 9362 | segregation_limit[amount] = std::make_pair(till_fork, recent); |
| 9363 | found = true; |
| 9364 | break; |
| 9365 | } |
| 9366 | } |
| 9367 | THROW_WALLET_EXCEPTION_IF(!found, error::get_output_distribution, "Requested amount not found in response"); |
| 9368 | } |
| 9369 | } |
| 9370 | |
| 9371 | std::vector<crypto::key_image> ring_key_images; |
| 9372 | ring_key_images.reserve(selected_transfers.size()); |
| 9373 | std::unordered_map<crypto::key_image, std::vector<uint64_t>> existing_rings; |
| 9374 | for(size_t idx: selected_transfers) |
| 9375 | { |
| 9376 | const transfer_details &td = m_transfers[idx]; |
| 9377 | if (td.m_key_image_known && !td.m_key_image_partial) |
| 9378 | ring_key_images.push_back(td.m_key_image); |
| 9379 | } |
| 9380 | if (!ring_key_images.empty()) |
| 9381 | { |
| 9382 | std::vector<std::vector<uint64_t>> all_outs; |
| 9383 | if (get_rings(get_ringdb_key(), ring_key_images, all_outs)) |
| 9384 | { |
| 9385 | for (size_t i = 0; i < ring_key_images.size(); ++i) |
| 9386 | existing_rings[ring_key_images[i]] = std::move(all_outs[i]); |
| 9387 | } |
| 9388 | } |
| 9389 | |
| 9390 | // we ask for more, to have spares if some outputs are still locked |
| 9391 | size_t base_requested_outputs_count = (size_t)((fake_outputs_count + 1) * 1.5 + 1); |
| 9392 | LOG_PRINT_L2("base_requested_outputs_count: " << base_requested_outputs_count); |
| 9393 | |
| 9394 | // generate output indices to request |
| 9395 | COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req); |
| 9396 | COMMAND_RPC_GET_OUTPUTS_BIN::response daemon_resp = AUTO_VAL_INIT(daemon_resp); |
| 9397 | |
| 9398 | // The secret picking order contains outputs in the order that we selected them. |
| 9399 | // |
| 9400 | // We will later sort the output request entries in a pre-determined order so that the daemon |
| 9401 | // that we're requesting information from doesn't learn any information about the true spend |
| 9402 | // for each ring. However, internally, we want to prefer to construct our rings using the |
| 9403 | // outputs that we picked first versus outputs picked later. |
| 9404 | // |
| 9405 | // The reason why is because each consecutive output pick within a ring becomes increasing less |
| 9406 | // statistically independent from other picks, since we pick outputs from a finite set |
| 9407 | // *without replacement*, due to the protocol not allowing duplicate ring members. This effect |
| 9408 | // is exacerbated by the fact that we pick 1.5x + 75 as many outputs as we need per RPC |
| 9409 | // request to account for unusable outputs. This effect is small, but non-neglibile and gets |
| 9410 | // worse with larger ring sizes. |
| 9411 | std::vector<get_outputs_out> secret_picking_order; |
| 9412 | |
| 9413 | // Convenience/safety lambda to make sure that both output lists req.outputs and secret_picking_order are updated together |
| 9414 | // Each ring section of req.outputs gets sorted later after selecting all outputs for that ring |
| 9415 | const auto add_output_to_lists = [&req, &secret_picking_order](const get_outputs_out &goo) |
| 9416 | { req.outputs.push_back(goo); secret_picking_order.push_back(goo); }; |
| 9417 | |
| 9418 | std::unique_ptr<gamma_picker> gamma; |
| 9419 | if (has_rct) |
| 9420 | gamma.reset(new gamma_picker(rct_offsets)); |
| 9421 | |
| 9422 | size_t num_selected_transfers = 0; |
| 9423 | req.outputs.reserve(selected_transfers.size() * (base_requested_outputs_count + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW)); |
| 9424 | daemon_resp.outs.reserve(selected_transfers.size() * (base_requested_outputs_count + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW)); |
| 9425 | for(size_t idx: selected_transfers) |
| 9426 | { |
| 9427 | ++num_selected_transfers; |
| 9428 | const transfer_details &td = m_transfers[idx]; |
| 9429 | const uint64_t amount = td.is_rct() ? 0 : td.amount(); |
| 9430 | std::unordered_set<uint64_t> seen_indices; |
| 9431 | // request more for rct in base recent (locked) coinbases are picked, since they're locked for longer |
| 9432 | size_t requested_outputs_count = base_requested_outputs_count + (td.is_rct() ? CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW - CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE : 0); |
| 9433 | size_t start = req.outputs.size(); |
| 9434 | bool use_histogram = amount != 0; |
| 9435 | |
| 9436 | const bool output_is_pre_fork = td.m_block_height < segregation_fork_height; |
| 9437 | uint64_t num_outs = 0, num_recent_outs = 0; |
| 9438 | uint64_t num_post_fork_outs = 0; |
| 9439 | float pre_fork_num_out_ratio = 0.0f; |
| 9440 | float post_fork_num_out_ratio = 0.0f; |
| 9441 | |
| 9442 | if (is_after_segregation_fork && m_segregate_pre_fork_outputs && output_is_pre_fork) |
| 9443 | { |
| 9444 | num_outs = segregation_limit[amount].first; |
| 9445 | num_recent_outs = segregation_limit[amount].second; |
| 9446 | } |
| 9447 | else |
| 9448 | { |
| 9449 | // if there are just enough outputs to mix with, use all of them. |
| 9450 | // Eventually this should become impossible. |
| 9451 | for (const auto &he: resp_t.histogram) |
| 9452 | { |
| 9453 | if (he.amount == amount) |
| 9454 | { |
| 9455 | LOG_PRINT_L2("Found " << print_money(amount) << ": " << he.total_instances << " total, " |
| 9456 | << he.unlocked_instances << " unlocked, " << he.recent_instances << " recent"); |
| 9457 | num_outs = he.unlocked_instances; |
| 9458 | num_recent_outs = he.recent_instances; |
| 9459 | break; |
| 9460 | } |
| 9461 | } |
| 9462 | if (is_after_segregation_fork && m_key_reuse_mitigation2) |
| 9463 | { |
| 9464 | if (output_is_pre_fork) |
| 9465 | { |
| 9466 | if (is_shortly_after_segregation_fork) |
| 9467 | { |
| 9468 | pre_fork_num_out_ratio = 33.4/100.0f * (1.0f - RECENT_OUTPUT_RATIO); |
| 9469 | } |
| 9470 | else |
| 9471 | { |
| 9472 | pre_fork_num_out_ratio = 33.4/100.0f * (1.0f - RECENT_OUTPUT_RATIO); |
| 9473 | post_fork_num_out_ratio = 33.4/100.0f * (1.0f - RECENT_OUTPUT_RATIO); |
| 9474 | } |
| 9475 | } |
| 9476 | else |
| 9477 | { |
| 9478 | if (is_shortly_after_segregation_fork) |
| 9479 | { |
| 9480 | } |
| 9481 | else |
| 9482 | { |
| 9483 | post_fork_num_out_ratio = 67.8/100.0f * (1.0f - RECENT_OUTPUT_RATIO); |
| 9484 | } |
| 9485 | } |
| 9486 | } |
| 9487 | num_post_fork_outs = num_outs - segregation_limit[amount].first; |
| 9488 | } |
| 9489 | |
| 9490 | if (use_histogram) |
| 9491 | { |
| 9492 | LOG_PRINT_L1("" << num_outs << " unlocked outputs of size " << print_money(amount)); |
| 9493 | THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, |
| 9494 | "histogram reports no unlocked outputs for " + boost::lexical_cast<std::string>(amount) + ", not even ours"); |
| 9495 | THROW_WALLET_EXCEPTION_IF(num_recent_outs > num_outs, error::wallet_internal_error, |
| 9496 | "histogram reports more recent outs than outs for " + boost::lexical_cast<std::string>(amount)); |
| 9497 | } |
| 9498 | else |
| 9499 | { |
| 9500 | // the base offset of the first rct output in the first unlocked block (or the one to be if there's none) |
| 9501 | num_outs = gamma->get_num_rct_outs(); |
| 9502 | LOG_PRINT_L1("" << num_outs << " unlocked rct outputs"); |
| 9503 | THROW_WALLET_EXCEPTION_IF(num_outs == 0, error::wallet_internal_error, |
| 9504 | "histogram reports no unlocked rct outputs, not even ours"); |
| 9505 | } |
| 9506 | |
| 9507 | // how many fake outs to draw on a pre-fork distribution |
| 9508 | size_t pre_fork_outputs_count = requested_outputs_count * pre_fork_num_out_ratio; |
| 9509 | size_t post_fork_outputs_count = requested_outputs_count * post_fork_num_out_ratio; |
| 9510 | // how many fake outs to draw otherwise |
| 9511 | size_t normal_output_count = requested_outputs_count - pre_fork_outputs_count - post_fork_outputs_count; |
| 9512 | |
| 9513 | size_t recent_outputs_count = 0; |
| 9514 | if (use_histogram) |
| 9515 | { |
| 9516 | // X% of those outs are to be taken from recent outputs |
| 9517 | recent_outputs_count = normal_output_count * RECENT_OUTPUT_RATIO; |
| 9518 | if (recent_outputs_count == 0) |
| 9519 | recent_outputs_count = 1; // ensure we have at least one, if possible |
| 9520 | if (recent_outputs_count > num_recent_outs) |
| 9521 | recent_outputs_count = num_recent_outs; |
| 9522 | if (td.m_global_output_index >= num_outs - num_recent_outs && recent_outputs_count > 0) |
| 9523 | --recent_outputs_count; // if the real out is recent, pick one less recent fake out |
| 9524 | } |
| 9525 | LOG_PRINT_L1("Fake output makeup: " << requested_outputs_count << " requested: " << recent_outputs_count << " recent, " << |
| 9526 | pre_fork_outputs_count << " pre-fork, " << post_fork_outputs_count << " post-fork, " << |
| 9527 | (requested_outputs_count - recent_outputs_count - pre_fork_outputs_count - post_fork_outputs_count) << " full-chain"); |
| 9528 | |
| 9529 | uint64_t num_found = 0; |
| 9530 | |
| 9531 | // if we have a known ring, use it |
| 9532 | if (td.m_key_image_known && !td.m_key_image_partial) |
| 9533 | { |
| 9534 | |
| 9535 | const auto it = existing_rings.find(td.m_key_image); |
| 9536 | const bool has_ring = it != existing_rings.end(); |
| 9537 | if (has_ring) |
| 9538 | { |
| 9539 | const std::vector<uint64_t> &ring = it->second; |
| 9540 | MINFO("This output has a known ring, reusing (size " << ring.size() << ")"); |
| 9541 | THROW_WALLET_EXCEPTION_IF(ring.size() > fake_outputs_count + 1, error::wallet_internal_error, |
| 9542 | "An output in this transaction was previously spent on another chain with ring size " + |
| 9543 | std::to_string(ring.size()) + ", it cannot be spent now with ring size " + |
| 9544 | std::to_string(fake_outputs_count + 1) + " as it is smaller: use a higher ring size"); |
| 9545 | bool own_found = false; |
| 9546 | for (const auto &out: ring) |
| 9547 | { |
| 9548 | MINFO("Ring has output " << out); |
| 9549 | if (out < num_outs) |
| 9550 | { |
| 9551 | MINFO("Using it"); |
| 9552 | add_output_to_lists({amount, out}); |
| 9553 | ++num_found; |
| 9554 | seen_indices.emplace(out); |
| 9555 | if (out == td.m_global_output_index) |
| 9556 | { |
| 9557 | MINFO("This is the real output"); |
| 9558 | own_found = true; |
| 9559 | } |
| 9560 | } |
| 9561 | else |
| 9562 | { |
| 9563 | MINFO("Ignoring output " << out << ", too recent"); |
| 9564 | } |
| 9565 | } |
| 9566 | if (!own_found) |
| 9567 | { |
| 9568 | MWARNING("Known ring does not include the spent output: " + std::to_string(td.m_global_output_index) |
| 9569 | + ", there may have been a reorg that moved the spent output's position in the chain"); |
| 9570 | } |
| 9571 | } |
| 9572 | } |
| 9573 | |
| 9574 | if (num_outs <= requested_outputs_count) |
| 9575 | { |
| 9576 | for (uint64_t i = 0; i < num_outs; i++) |
| 9577 | add_output_to_lists({amount, i}); |
| 9578 | // duplicate to make up shortfall: this will be caught after the RPC call, |
| 9579 | // so we can also output the amounts for which we can't reach the required |
| 9580 | // mixin after checking the actual unlockedness |
| 9581 | for (uint64_t i = num_outs; i < requested_outputs_count; ++i) |
| 9582 | add_output_to_lists({amount, num_outs - 1}); |
| 9583 | } |
| 9584 | else |
| 9585 | { |
| 9586 | // start with real one |
| 9587 | if (num_found == 0) |
| 9588 | { |
| 9589 | num_found = 1; |
| 9590 | seen_indices.emplace(td.m_global_output_index); |
| 9591 | add_output_to_lists({amount, td.m_global_output_index}); |
| 9592 | LOG_PRINT_L1("Selecting real output: " << td.m_global_output_index << " for " << print_money(amount)); |
| 9593 | } |
| 9594 | |
| 9595 | std::unordered_map<const char*, std::set<uint64_t>> picks; |
| 9596 | |
| 9597 | // while we still need more mixins |
| 9598 | uint64_t num_usable_outs = num_outs; |
| 9599 | bool allow_blackballed = false; |
| 9600 | MDEBUG("Starting gamma picking with " << num_outs << ", num_usable_outs " << num_usable_outs |
| 9601 | << ", requested_outputs_count " << requested_outputs_count); |
| 9602 | while (num_found < requested_outputs_count) |
| 9603 | { |
| 9604 | // if we've gone through every possible output, we've gotten all we can |
| 9605 | if (seen_indices.size() == num_usable_outs) |
| 9606 | { |
| 9607 | // there is a first pass which rejects blackballed outputs, then a second pass |
| 9608 | // which allows them if we don't have enough non blackballed outputs to reach |
| 9609 | // the required amount of outputs (since consensus does not care about blackballed |
| 9610 | // outputs, we still need to reach the minimum ring size) |
| 9611 | if (allow_blackballed) |
| 9612 | break; |
| 9613 | MINFO("Not enough output not marked as spent, we'll allow outputs marked as spent"); |
| 9614 | allow_blackballed = true; |
| 9615 | num_usable_outs = num_outs; |
| 9616 | } |
| 9617 | |
| 9618 | // get a random output index from the DB. If we've already seen it, |
| 9619 | // return to the top of the loop and try again, otherwise add it to the |
| 9620 | // list of output indices we've seen. |
| 9621 | |
| 9622 | uint64_t i; |
| 9623 | const char *type = ""; |
| 9624 | if (amount == 0) |
| 9625 | { |
| 9626 | THROW_WALLET_EXCEPTION_IF(!gamma, error::wallet_internal_error, "No gamma picker"); |
| 9627 | // gamma distribution |
| 9628 | if (num_found -1 < recent_outputs_count + pre_fork_outputs_count) |
| 9629 | { |
| 9630 | do i = gamma->pick(); while (i >= segregation_limit[amount].first); |
| 9631 | type = "pre-fork gamma"; |
| 9632 | } |
| 9633 | else if (num_found -1 < recent_outputs_count + pre_fork_outputs_count + post_fork_outputs_count) |
| 9634 | { |
| 9635 | do i = gamma->pick(); while (i < segregation_limit[amount].first || i >= num_outs); |
| 9636 | type = "post-fork gamma"; |
| 9637 | } |
| 9638 | else |
| 9639 | { |
| 9640 | do i = gamma->pick(); while (i >= num_outs); |
| 9641 | type = "gamma"; |
| 9642 | } |
| 9643 | } |
| 9644 | else if (num_found - 1 < recent_outputs_count) // -1 to account for the real one we seeded with |
| 9645 | { |
| 9646 | // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit |
| 9647 | uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); |
| 9648 | double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); |
| 9649 | i = (uint64_t)(frac*num_recent_outs) + num_outs - num_recent_outs; |
| 9650 | // just in case rounding up to 1 occurs after calc |
| 9651 | if (i == num_outs) |
| 9652 | --i; |
| 9653 | type = "recent"; |
| 9654 | } |
| 9655 | else if (num_found -1 < recent_outputs_count + pre_fork_outputs_count) |
| 9656 | { |
| 9657 | // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit |
| 9658 | uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); |
| 9659 | double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); |
| 9660 | i = (uint64_t)(frac*segregation_limit[amount].first); |
| 9661 | // just in case rounding up to 1 occurs after calc |
| 9662 | if (i == num_outs) |
| 9663 | --i; |
| 9664 | type = " pre-fork"; |
| 9665 | } |
| 9666 | else if (num_found -1 < recent_outputs_count + pre_fork_outputs_count + post_fork_outputs_count) |
| 9667 | { |
| 9668 | // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit |
| 9669 | uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); |
| 9670 | double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); |
| 9671 | i = (uint64_t)(frac*num_post_fork_outs) + segregation_limit[amount].first; |
| 9672 | // just in case rounding up to 1 occurs after calc |
| 9673 | if (i == num_post_fork_outs+segregation_limit[amount].first) |
| 9674 | --i; |
| 9675 | type = "post-fork"; |
| 9676 | } |
| 9677 | else |
| 9678 | { |
| 9679 | // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit |
| 9680 | uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); |
| 9681 | double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); |
| 9682 | i = (uint64_t)(frac*num_outs); |
| 9683 | // just in case rounding up to 1 occurs after calc |
| 9684 | if (i == num_outs) |
| 9685 | --i; |
| 9686 | type = "triangular"; |
| 9687 | } |
| 9688 | |
| 9689 | if (seen_indices.count(i)) |
| 9690 | continue; |
| 9691 | if (!allow_blackballed && is_output_blackballed(std::make_pair(amount, i))) // don't add blackballed outputs |
| 9692 | { |
| 9693 | --num_usable_outs; |
| 9694 | continue; |
| 9695 | } |
| 9696 | seen_indices.emplace(i); |
| 9697 | |
| 9698 | picks[type].insert(i); |
| 9699 | add_output_to_lists({amount, i}); |
| 9700 | ++num_found; |
| 9701 | MDEBUG("picked " << i << ", " << num_found << " now picked"); |
| 9702 | } |
| 9703 | |
| 9704 | for (const auto &pick: picks) |
| 9705 | MDEBUG("picking " << pick.first << " outputs: " << |
| 9706 | boost::join(pick.second | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " ")); |
| 9707 | |
| 9708 | // if we had enough unusable outputs, we might fall off here and still |
| 9709 | // have too few outputs, so we stuff with one to keep counts good, and |
| 9710 | // we'll error out later |
| 9711 | while (num_found < requested_outputs_count) |
| 9712 | { |
| 9713 | add_output_to_lists({amount, 0}); |
| 9714 | ++num_found; |
| 9715 | } |
| 9716 | } |
| 9717 | |
| 9718 | // sort the subsection, to ensure the daemon doesn't know which output is ours |
| 9719 | std::sort(req.outputs.begin() + start, req.outputs.end(), |
| 9720 | [](const get_outputs_out &a, const get_outputs_out &b) { return a.index < b.index; }); |
| 9721 | } |
| 9722 | |
| 9723 | THROW_WALLET_EXCEPTION_IF(req.outputs.size() != secret_picking_order.size(), error::wallet_internal_error, |
| 9724 | "bug: we did not update req.outputs/secret_picking_order in tandem"); |
| 9725 | |
| 9726 | // List all requested outputs to debug log |
| 9727 | if (ELPP->vRegistry()->allowed(el::Level::Debug, MONERO_DEFAULT_LOG_CATEGORY)) |
| 9728 | { |
| 9729 | std::map<uint64_t, std::set<uint64_t>> outs; |
| 9730 | for (const auto &i: req.outputs) |
| 9731 | outs[i.amount].insert(i.index); |
| 9732 | for (const auto &o: outs) |
| 9733 | MDEBUG("asking for outputs with amount " << print_money(o.first) << ": " << |
| 9734 | boost::join(o.second | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " ")); |
| 9735 | } |
| 9736 | |
| 9737 | // get the keys for those |
| 9738 | // the response can get large and end up rejected by the anti DoS limits, so chunk it if needed |
| 9739 | size_t offset = 0; |
| 9740 | while (offset < req.outputs.size()) |
| 9741 | { |
| 9742 | static const size_t chunk_size = 1000; |
| 9743 | COMMAND_RPC_GET_OUTPUTS_BIN::request chunk_req = AUTO_VAL_INIT(chunk_req); |
| 9744 | COMMAND_RPC_GET_OUTPUTS_BIN::response chunk_daemon_resp = AUTO_VAL_INIT(chunk_daemon_resp); |
| 9745 | chunk_req.get_txid = false; |
| 9746 | const size_t this_chunk_size = std::min<size_t>(req.outputs.size() - offset, chunk_size); |
| 9747 | chunk_req.outputs.reserve(this_chunk_size); |
| 9748 | for (size_t i = 0; i < this_chunk_size; ++i) |
| 9749 | chunk_req.outputs.push_back(req.outputs[offset + i]); |
| 9750 | |
| 9751 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 9752 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 9753 | chunk_req.client = get_client_signature(); |
| 9754 | bool r = epee::net_utils::invoke_http_bin("/get_outs.bin", chunk_req, chunk_daemon_resp, *m_http_client, rpc_timeout); |
| 9755 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, chunk_daemon_resp, "get_outs.bin", error::get_outs_error, get_rpc_status(chunk_daemon_resp.status)); |
| 9756 | THROW_WALLET_EXCEPTION_IF(chunk_daemon_resp.outs.size() != chunk_req.outputs.size(), error::wallet_internal_error, |
| 9757 | "daemon returned wrong response for get_outs.bin, wrong amounts count = " + |
| 9758 | std::to_string(chunk_daemon_resp.outs.size()) + ", expected " + std::to_string(chunk_req.outputs.size())); |
| 9759 | check_rpc_cost("/get_outs.bin", chunk_daemon_resp.credits, pre_call_credits, chunk_daemon_resp.outs.size() * COST_PER_OUT); |
| 9760 | |
| 9761 | offset += chunk_size; |
| 9762 | for (size_t i = 0; i < chunk_daemon_resp.outs.size(); ++i) |
| 9763 | daemon_resp.outs.push_back(std::move(chunk_daemon_resp.outs[i])); |
| 9764 | } |
| 9765 | |
| 9766 | std::unordered_map<uint64_t, uint64_t> scanty_outs; |
| 9767 | size_t base = 0; |
| 9768 | outs.reserve(num_selected_transfers); |
| 9769 | for(size_t idx: selected_transfers) |
| 9770 | { |
| 9771 | const transfer_details &td = m_transfers[idx]; |
| 9772 | size_t requested_outputs_count = base_requested_outputs_count + (td.is_rct() ? CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW - CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE : 0); |
| 9773 | outs.push_back(std::vector<get_outs_entry>()); |
| 9774 | outs.back().reserve(fake_outputs_count + 1); |
| 9775 | const rct::key mask = td.is_rct() ? rct::commit(td.amount(), td.m_mask) : rct::zeroCommit(td.amount()); |
| 9776 | |
| 9777 | uint64_t num_outs = 0; |
| 9778 | const uint64_t amount = td.is_rct() ? 0 : td.amount(); |
| 9779 | const bool output_is_pre_fork = td.m_block_height < segregation_fork_height; |
| 9780 | if (is_after_segregation_fork && m_segregate_pre_fork_outputs && output_is_pre_fork) |
| 9781 | num_outs = segregation_limit[amount].first; |
| 9782 | else for (const auto &he: resp_t.histogram) |
| 9783 | { |
| 9784 | if (he.amount == amount) |
| 9785 | { |
| 9786 | num_outs = he.unlocked_instances; |
| 9787 | break; |
| 9788 | } |
| 9789 | } |
| 9790 | bool use_histogram = amount != 0; |
| 9791 | if (!use_histogram) |
| 9792 | num_outs = gamma->get_num_rct_outs(); |
| 9793 | |
| 9794 | // make sure the real outputs we asked for are really included, along |
| 9795 | // with the correct key and mask: this guards against an active attack |
| 9796 | // where the node sends dummy data for all outputs, and we then send |
| 9797 | // the real one, which the node can then tell from the fake outputs, |
| 9798 | // as it has different data than the dummy data it had sent earlier |
| 9799 | bool real_out_found = false; |
| 9800 | for (size_t n = 0; n < requested_outputs_count; ++n) |
| 9801 | { |
| 9802 | size_t i = base + n; |
| 9803 | if (req.outputs[i].index == td.m_global_output_index) |
| 9804 | if (daemon_resp.outs[i].key == td.get_public_key()) |
| 9805 | if (daemon_resp.outs[i].mask == mask) |
| 9806 | if (daemon_resp.outs[i].unlocked) |
| 9807 | real_out_found = true; |
| 9808 | } |
| 9809 | THROW_WALLET_EXCEPTION_IF(!real_out_found, error::wallet_internal_error, |
| 9810 | "Daemon response did not include the requested real output"); |
| 9811 | |
| 9812 | // pick real out first (it will be sorted when done) |
| 9813 | outs.back().push_back(std::make_tuple(td.m_global_output_index, td.get_public_key(), mask)); |
| 9814 | |
| 9815 | // then pick outs from an existing ring, if any |
| 9816 | if (td.m_key_image_known && !td.m_key_image_partial) |
| 9817 | { |
| 9818 | const auto it = existing_rings.find(td.m_key_image); |
| 9819 | if (it != existing_rings.end()) |
| 9820 | { |
| 9821 | const std::vector<uint64_t> &ring = it->second; |
| 9822 | for (uint64_t out: ring) |
| 9823 | { |
| 9824 | if (out < num_outs) |
| 9825 | { |
| 9826 | if (out != td.m_global_output_index) |
| 9827 | { |
| 9828 | bool found = false; |
| 9829 | for (size_t o = 0; o < requested_outputs_count; ++o) |
| 9830 | { |
| 9831 | size_t i = base + o; |
| 9832 | if (req.outputs[i].index == out) |
| 9833 | { |
| 9834 | LOG_PRINT_L2("Index " << i << "/" << requested_outputs_count << ": idx " << req.outputs[i].index << " (real " << td.m_global_output_index << "), unlocked " << daemon_resp.outs[i].unlocked << ", key " << daemon_resp.outs[i].key << " (from existing ring)"); |
| 9835 | tx_add_fake_output(outs, req.outputs[i].index, daemon_resp.outs[i].key, daemon_resp.outs[i].mask, td.m_global_output_index, daemon_resp.outs[i].unlocked, valid_public_keys_cache); |
| 9836 | found = true; |
| 9837 | break; |
| 9838 | } |
| 9839 | } |
| 9840 | THROW_WALLET_EXCEPTION_IF(!found, error::wallet_internal_error, "Falied to find existing ring output in daemon out data"); |
| 9841 | } |
| 9842 | } |
| 9843 | } |
| 9844 | } |
| 9845 | } |
| 9846 | |
| 9847 | // While we are still lacking outputs in this result ring, in our secret pick order... |
| 9848 | LOG_PRINT_L2("Looking for " << (fake_outputs_count+1) << " outputs of size " << print_money(td.is_rct() ? 0 : td.amount())); |
| 9849 | for (size_t ring_pick_idx = base; ring_pick_idx < base + requested_outputs_count && outs.back().size() < fake_outputs_count + 1; ++ring_pick_idx) |
| 9850 | { |
| 9851 | const get_outputs_out attempted_output = secret_picking_order[ring_pick_idx]; |
| 9852 | |
| 9853 | // Find the index i of our pick in the request/response arrays |
| 9854 | size_t i; |
| 9855 | for (i = base; i < base + requested_outputs_count; ++i) |
| 9856 | if (req.outputs[i].index == attempted_output.index) |
| 9857 | break; |
| 9858 | THROW_WALLET_EXCEPTION_IF(i == base + requested_outputs_count, error::wallet_internal_error, |
| 9859 | "Could not find index of picked output in requested outputs"); |
| 9860 | |
| 9861 | // Try adding this output's information to result ring if output isn't invalid |
| 9862 | LOG_PRINT_L2("Index " << i << "/" << requested_outputs_count << ": idx " << req.outputs[i].index << " (real " << td.m_global_output_index << "), unlocked " << daemon_resp.outs[i].unlocked << ", key " << daemon_resp.outs[i].key); |
| 9863 | tx_add_fake_output(outs, req.outputs[i].index, daemon_resp.outs[i].key, daemon_resp.outs[i].mask, td.m_global_output_index, daemon_resp.outs[i].unlocked, valid_public_keys_cache); |
| 9864 | } |
| 9865 | if (outs.back().size() < fake_outputs_count + 1) |
| 9866 | { |
| 9867 | scanty_outs[td.is_rct() ? 0 : td.amount()] = outs.back().size(); |
| 9868 | } |
| 9869 | else |
| 9870 | { |
| 9871 | // sort the subsection, so any spares are reset in order |
| 9872 | 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); }); |
| 9873 | } |
| 9874 | base += requested_outputs_count; |
| 9875 | } |
| 9876 | THROW_WALLET_EXCEPTION_IF(!scanty_outs.empty(), error::not_enough_outs_to_mix, scanty_outs, fake_outputs_count); |
| 9877 | } |
| 9878 | else |
| 9879 | { |
| 9880 | for (size_t idx: selected_transfers) |
| 9881 | { |
| 9882 | const transfer_details &td = m_transfers[idx]; |
| 9883 | std::vector<get_outs_entry> v; |
| 9884 | const rct::key mask = td.is_rct() ? rct::commit(td.amount(), td.m_mask) : rct::zeroCommit(td.amount()); |
| 9885 | v.push_back(std::make_tuple(td.m_global_output_index, td.get_public_key(), mask)); |
| 9886 | outs.push_back(v); |
| 9887 | } |
| 9888 | } |
| 9889 | |
| 9890 | // save those outs in the ringdb for reuse |
| 9891 | std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings; |
| 9892 | rings.reserve(selected_transfers.size()); |
| 9893 | for (size_t i = 0; i < selected_transfers.size(); ++i) |
| 9894 | { |
| 9895 | const size_t idx = selected_transfers[i]; |
| 9896 | THROW_WALLET_EXCEPTION_IF(idx >= m_transfers.size(), error::wallet_internal_error, "selected_transfers entry out of range"); |
| 9897 | const transfer_details &td = m_transfers[idx]; |
| 9898 | std::vector<uint64_t> ring; |
| 9899 | ring.reserve(outs[i].size()); |
| 9900 | for (const auto &e: outs[i]) |
| 9901 | ring.push_back(std::get<0>(e)); |
| 9902 | rings.push_back(std::make_pair(td.m_key_image, std::move(ring))); |
| 9903 | } |
| 9904 | if (!set_rings(rings, false)) |
| 9905 | MERROR("Failed to set rings"); |
| 9906 | } |
| 9907 | |
| 9908 | template<typename T> |
| 9909 | void wallet2::transfer_selected(const std::vector<cryptonote::tx_destination_entry>& dsts, const std::vector<size_t>& selected_transfers, size_t fake_outputs_count, |
| 9910 | std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, std::unordered_set<crypto::public_key> &valid_public_keys_cache, |
| 9911 | 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, |
| 9912 | bool use_view_tags) |
| 9913 | { |
| 9914 | using namespace cryptonote; |
| 9915 | // throw if attempting a transaction with no destinations |
| 9916 | THROW_WALLET_EXCEPTION_IF(dsts.empty(), error::zero_destination); |
| 9917 | |
| 9918 | THROW_WALLET_EXCEPTION_IF(m_multisig, error::wallet_internal_error, "Multisig wallets cannot spend non rct outputs"); |
| 9919 | |
| 9920 | uint64_t upper_transaction_weight_limit = get_upper_transaction_weight_limit(); |
| 9921 | uint64_t needed_money = fee; |
| 9922 | LOG_PRINT_L2("transfer: starting with fee " << print_money (needed_money)); |
| 9923 | |
| 9924 | // calculate total amount being sent to all destinations |
| 9925 | // throw if total amount overflows uint64_t |
| 9926 | for(auto& dt: dsts) |
| 9927 | { |
| 9928 | THROW_WALLET_EXCEPTION_IF(0 == dt.amount, error::zero_amount); |
| 9929 | needed_money += dt.amount; |
| 9930 | LOG_PRINT_L2("transfer: adding " << print_money(dt.amount) << ", for a total of " << print_money (needed_money)); |
| 9931 | THROW_WALLET_EXCEPTION_IF(needed_money < dt.amount, error::tx_sum_overflow, dsts, fee, m_nettype); |
| 9932 | } |
| 9933 | |
| 9934 | uint64_t found_money = 0; |
| 9935 | for(size_t idx: selected_transfers) |
| 9936 | { |
| 9937 | found_money += m_transfers[idx].amount(); |
| 9938 | } |
| 9939 | |
| 9940 | LOG_PRINT_L2("wanted " << print_money(needed_money) << ", found " << print_money(found_money) << ", fee " << print_money(fee)); |
| 9941 | THROW_WALLET_EXCEPTION_IF(found_money < needed_money, error::not_enough_unlocked_money, found_money, needed_money - fee, fee); |
| 9942 | |
| 9943 | uint32_t subaddr_account = m_transfers[*selected_transfers.begin()].m_subaddr_index.major; |
| 9944 | for (auto i = ++selected_transfers.begin(); i != selected_transfers.end(); ++i) |
| 9945 | THROW_WALLET_EXCEPTION_IF(subaddr_account != m_transfers[*i].m_subaddr_index.major, error::wallet_internal_error, "the tx uses funds from multiple accounts"); |
| 9946 | |
| 9947 | if (outs.empty()) |
| 9948 | get_outs(outs, selected_transfers, fake_outputs_count, false, valid_public_keys_cache); // may throw |
| 9949 | |
| 9950 | //prepare inputs |
| 9951 | LOG_PRINT_L2("preparing outputs"); |
| 9952 | typedef cryptonote::tx_source_entry::output_entry tx_output_entry; |
| 9953 | size_t i = 0, out_index = 0; |
| 9954 | std::vector<cryptonote::tx_source_entry> sources; |
| 9955 | for(size_t idx: selected_transfers) |
| 9956 | { |
| 9957 | sources.resize(sources.size()+1); |
| 9958 | cryptonote::tx_source_entry& src = sources.back(); |
| 9959 | const transfer_details& td = m_transfers[idx]; |
| 9960 | src.amount = td.amount(); |
| 9961 | src.rct = td.is_rct(); |
| 9962 | //paste keys (fake and real) |
| 9963 | |
| 9964 | for (size_t n = 0; n < fake_outputs_count + 1; ++n) |
| 9965 | { |
| 9966 | tx_output_entry oe; |
| 9967 | oe.first = std::get<0>(outs[out_index][n]); |
| 9968 | oe.second.dest = rct::pk2rct(std::get<1>(outs[out_index][n])); |
| 9969 | oe.second.mask = std::get<2>(outs[out_index][n]); |
| 9970 | |
| 9971 | src.outputs.push_back(oe); |
| 9972 | ++i; |
| 9973 | } |
| 9974 | |
| 9975 | //paste real transaction to the random index |
| 9976 | auto it_to_replace = std::find_if(src.outputs.begin(), src.outputs.end(), [&](const tx_output_entry& a) |
| 9977 | { |
| 9978 | return a.first == td.m_global_output_index; |
| 9979 | }); |
| 9980 | THROW_WALLET_EXCEPTION_IF(it_to_replace == src.outputs.end(), error::wallet_internal_error, |
| 9981 | "real output not found"); |
| 9982 | |
| 9983 | tx_output_entry real_oe; |
| 9984 | real_oe.first = td.m_global_output_index; |
| 9985 | real_oe.second.dest = rct::pk2rct(td.get_public_key()); |
| 9986 | real_oe.second.mask = rct::commit(td.amount(), td.m_mask); |
| 9987 | *it_to_replace = real_oe; |
| 9988 | src.real_out_tx_key = get_tx_pub_key_from_extra(td.m_tx, td.m_pk_index); |
| 9989 | src.real_out_additional_tx_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 9990 | src.real_output = it_to_replace - src.outputs.begin(); |
| 9991 | src.real_output_in_tx_index = td.m_internal_output_index; |
| 9992 | src.multisig_kLRki = rct::multisig_kLRki({rct::zero(), rct::zero(), rct::zero(), rct::zero()}); |
| 9993 | detail::print_source_entry(src); |
| 9994 | ++out_index; |
| 9995 | } |
| 9996 | LOG_PRINT_L2("outputs prepared"); |
| 9997 | |
| 9998 | cryptonote::tx_destination_entry change_dts = AUTO_VAL_INIT(change_dts); |
| 9999 | if (needed_money < found_money) |
| 10000 | { |
| 10001 | change_dts.addr = get_subaddress({subaddr_account, 0}); |
| 10002 | change_dts.is_subaddress = subaddr_account != 0; |
| 10003 | change_dts.amount = found_money - needed_money; |
| 10004 | } |
| 10005 | |
| 10006 | std::vector<cryptonote::tx_destination_entry> splitted_dsts, dust_dsts; |
| 10007 | uint64_t dust = 0; |
| 10008 | destination_split_strategy(dsts, change_dts, dust_policy.dust_threshold, splitted_dsts, dust_dsts); |
| 10009 | for(auto& d: dust_dsts) { |
| 10010 | THROW_WALLET_EXCEPTION_IF(dust_policy.dust_threshold < d.amount, error::wallet_internal_error, "invalid dust value: dust = " + |
| 10011 | std::to_string(d.amount) + ", dust_threshold = " + std::to_string(dust_policy.dust_threshold)); |
| 10012 | } |
| 10013 | for(auto& d: dust_dsts) { |
| 10014 | if (!dust_policy.add_to_fee) |
| 10015 | splitted_dsts.push_back(cryptonote::tx_destination_entry(d.amount, dust_policy.addr_for_dust, d.is_subaddress)); |
| 10016 | dust += d.amount; |
| 10017 | } |
| 10018 | |
| 10019 | crypto::secret_key tx_key; |
| 10020 | std::vector<crypto::secret_key> additional_tx_keys; |
| 10021 | LOG_PRINT_L2("constructing tx"); |
| 10022 | bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), m_subaddresses, sources, splitted_dsts, change_dts.addr, extra, tx, tx_key, additional_tx_keys, false, {}, use_view_tags); |
| 10023 | LOG_PRINT_L2("constructed tx, r="<<r); |
| 10024 | THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sources, splitted_dsts, m_nettype); |
| 10025 | THROW_WALLET_EXCEPTION_IF(upper_transaction_weight_limit <= get_transaction_weight(tx), error::tx_too_big, tx, upper_transaction_weight_limit); |
| 10026 | |
| 10027 | std::string key_images; |
| 10028 | bool all_are_txin_to_key = std::all_of(tx.vin.begin(), tx.vin.end(), [&](const txin_v& s_e) -> bool |
| 10029 | { |
| 10030 | CHECKED_GET_SPECIFIC_VARIANT(s_e, const txin_to_key, in, false); |
| 10031 | key_images += boost::to_string(in.k_image) + " "; |
| 10032 | return true; |
| 10033 | }); |
| 10034 | THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, tx); |
| 10035 | |
| 10036 | |
| 10037 | bool dust_sent_elsewhere = (dust_policy.addr_for_dust.m_view_public_key != change_dts.addr.m_view_public_key |
| 10038 | || dust_policy.addr_for_dust.m_spend_public_key != change_dts.addr.m_spend_public_key); |
| 10039 | |
| 10040 | if (dust_policy.add_to_fee || dust_sent_elsewhere) change_dts.amount -= dust; |
| 10041 | |
| 10042 | ptx.key_images = key_images; |
| 10043 | ptx.fee = (dust_policy.add_to_fee ? fee+dust : fee); |
| 10044 | ptx.dust = ((dust_policy.add_to_fee || dust_sent_elsewhere) ? dust : 0); |
| 10045 | ptx.dust_added_to_fee = dust_policy.add_to_fee; |
| 10046 | ptx.tx = tx; |
| 10047 | ptx.change_dts = change_dts; |
| 10048 | ptx.selected_transfers = selected_transfers; |
| 10049 | ptx.tx_key = tx_key; |
| 10050 | ptx.additional_tx_keys = additional_tx_keys; |
| 10051 | ptx.dests = dsts; |
| 10052 | ptx.construction_data.sources = sources; |
| 10053 | ptx.construction_data.change_dts = change_dts; |
| 10054 | ptx.construction_data.splitted_dsts = splitted_dsts; |
| 10055 | ptx.construction_data.selected_transfers = selected_transfers; |
| 10056 | ptx.construction_data.extra = tx.extra; |
| 10057 | ptx.construction_data.unlock_time = 0; |
| 10058 | ptx.construction_data.use_rct = false; |
| 10059 | ptx.construction_data.rct_config = { rct::RangeProofBorromean, 0 }; |
| 10060 | ptx.construction_data.use_view_tags = use_view_tags; |
| 10061 | ptx.construction_data.dests = dsts; |
| 10062 | // record which subaddress indices are being used as inputs |
| 10063 | ptx.construction_data.subaddr_account = subaddr_account; |
| 10064 | ptx.construction_data.subaddr_indices.clear(); |
| 10065 | for (size_t idx: selected_transfers) |
| 10066 | ptx.construction_data.subaddr_indices.insert(m_transfers[idx].m_subaddr_index.minor); |
| 10067 | LOG_PRINT_L2("transfer_selected done"); |
| 10068 | } |
| 10069 | |
| 10070 | void wallet2::transfer_selected_rct(std::vector<cryptonote::tx_destination_entry> dsts, const std::vector<size_t>& selected_transfers, size_t fake_outputs_count, |
| 10071 | std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, std::unordered_set<crypto::public_key> &valid_public_keys_cache, |
| 10072 | uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx &ptx, const rct::RCTConfig &rct_config, bool use_view_tags) |
| 10073 | { |
| 10074 | using namespace cryptonote; |
| 10075 | // throw if attempting a transaction with no destinations |
| 10076 | THROW_WALLET_EXCEPTION_IF(dsts.empty(), error::zero_destination); |
| 10077 | |
| 10078 | uint64_t upper_transaction_weight_limit = get_upper_transaction_weight_limit(); |
| 10079 | uint64_t needed_money = fee; |
| 10080 | LOG_PRINT_L2("transfer_selected_rct: starting with fee " << print_money (needed_money)); |
| 10081 | LOG_PRINT_L2("selected transfers: " << strjoin(selected_transfers, " ")); |
| 10082 | |
| 10083 | // calculate total amount being sent to all destinations |
| 10084 | // throw if total amount overflows uint64_t |
| 10085 | for(auto& dt: dsts) |
| 10086 | { |
| 10087 | THROW_WALLET_EXCEPTION_IF(0 == dt.amount, error::zero_amount); |
| 10088 | needed_money += dt.amount; |
| 10089 | LOG_PRINT_L2("transfer: adding " << print_money(dt.amount) << ", for a total of " << print_money (needed_money)); |
| 10090 | THROW_WALLET_EXCEPTION_IF(needed_money < dt.amount, error::tx_sum_overflow, dsts, fee, m_nettype); |
| 10091 | } |
| 10092 | |
| 10093 | // if this is a multisig wallet, create a list of multisig signers we can use |
| 10094 | std::deque<crypto::public_key> multisig_signers; |
| 10095 | size_t n_multisig_txes = 0; |
| 10096 | std::vector<std::unordered_set<crypto::public_key>> ignore_sets; |
| 10097 | if (m_multisig && !m_transfers.empty()) |
| 10098 | { |
| 10099 | const crypto::public_key local_signer = get_multisig_signer_public_key(); |
| 10100 | size_t n_available_signers = 1; |
| 10101 | |
| 10102 | // At this step we need to define set of participants available for signature, |
| 10103 | // i.e. those of them who exchanged with multisig info's |
| 10104 | // note: The oldest unspent owned output's multisig info (in m_transfers) will contain the most recent result of |
| 10105 | // 'import_multisig()', which means only 'fresh' multisig infos (public nonces) will be used to make tx attempts. |
| 10106 | // - If a signer's info was missing from the latest call to 'import_multisig()', then they won't be able to participate! |
| 10107 | // - If a newly-acquired output doesn't have enouch nonces from multisig infos, then it can't be spent! |
| 10108 | for (const crypto::public_key &signer: m_multisig_signers) |
| 10109 | { |
| 10110 | if (signer == local_signer) |
| 10111 | continue; |
| 10112 | for (const auto &i: m_transfers[0].m_multisig_info) |
| 10113 | { |
| 10114 | if (i.m_signer == signer) |
| 10115 | { |
| 10116 | multisig_signers.push_back(signer); |
| 10117 | ++n_available_signers; |
| 10118 | break; |
| 10119 | } |
| 10120 | } |
| 10121 | } |
| 10122 | // n_available_signers includes the transaction creator, but multisig_signers doesn't |
| 10123 | MDEBUG("We can use " << n_available_signers << "/" << m_multisig_signers.size() << " other signers"); |
| 10124 | THROW_WALLET_EXCEPTION_IF(n_available_signers < m_multisig_threshold, error::multisig_import_needed); |
| 10125 | if (n_available_signers > m_multisig_threshold) |
| 10126 | { |
| 10127 | // If there more potential signers (those who exchanged with multisig info) |
| 10128 | // than threshold needed some of them should be skipped since we don't know |
| 10129 | // who will sign tx and who won't. Hence we don't contribute their LR pairs to the signature. |
| 10130 | |
| 10131 | // We create as many transactions as many combinations of excluded signers may be. |
| 10132 | // For example, if we have 2/4 wallet and wallets are: A, B, C and D. Let A be |
| 10133 | // transaction creator, so we need just 1 signature from set of B, C, D. |
| 10134 | // Using "excluding" logic here we have to exclude 2-of-3 wallets. Combinations go as follows: |
| 10135 | // BC, BD, and CD. We save these sets to use later and counting the number of required txs. |
| 10136 | tools::Combinator<crypto::public_key> c(std::vector<crypto::public_key>(multisig_signers.begin(), multisig_signers.end())); |
| 10137 | auto ignore_combinations = c.combine(multisig_signers.size() + 1 - m_multisig_threshold); |
| 10138 | for (const auto& combination: ignore_combinations) |
| 10139 | { |
| 10140 | ignore_sets.push_back(std::unordered_set<crypto::public_key>(combination.begin(), combination.end())); |
| 10141 | } |
| 10142 | |
| 10143 | n_multisig_txes = ignore_sets.size(); |
| 10144 | } |
| 10145 | else |
| 10146 | { |
| 10147 | // If we have exact count of signers just to fit in threshold we don't exclude anyone and create 1 transaction |
| 10148 | n_multisig_txes = 1; |
| 10149 | } |
| 10150 | MDEBUG("We will create " << n_multisig_txes << " txes"); |
| 10151 | } |
| 10152 | |
| 10153 | bool all_rct = true; |
| 10154 | uint64_t found_money = 0; |
| 10155 | for(size_t idx: selected_transfers) |
| 10156 | { |
| 10157 | found_money += m_transfers[idx].amount(); |
| 10158 | all_rct &= m_transfers[idx].is_rct(); |
| 10159 | } |
| 10160 | |
| 10161 | LOG_PRINT_L2("wanted " << print_money(needed_money) << ", found " << print_money(found_money) << ", fee " << print_money(fee)); |
| 10162 | THROW_WALLET_EXCEPTION_IF(found_money < needed_money, error::not_enough_unlocked_money, found_money, needed_money - fee, fee); |
| 10163 | |
| 10164 | uint32_t subaddr_account = m_transfers[*selected_transfers.begin()].m_subaddr_index.major; |
| 10165 | for (auto i = ++selected_transfers.begin(); i != selected_transfers.end(); ++i) |
| 10166 | THROW_WALLET_EXCEPTION_IF(subaddr_account != m_transfers[*i].m_subaddr_index.major, error::wallet_internal_error, "the tx uses funds from multiple accounts"); |
| 10167 | |
| 10168 | if (outs.empty()) |
| 10169 | get_outs(outs, selected_transfers, fake_outputs_count, all_rct, valid_public_keys_cache); // may throw |
| 10170 | |
| 10171 | //prepare inputs |
| 10172 | LOG_PRINT_L2("preparing outputs"); |
| 10173 | size_t i = 0, out_index = 0; |
| 10174 | std::vector<cryptonote::tx_source_entry> sources; |
| 10175 | for(size_t idx: selected_transfers) |
| 10176 | { |
| 10177 | sources.resize(sources.size()+1); |
| 10178 | cryptonote::tx_source_entry& src = sources.back(); |
| 10179 | const transfer_details& td = m_transfers[idx]; |
| 10180 | src.amount = td.amount(); |
| 10181 | src.rct = td.is_rct(); |
| 10182 | //paste mixin transaction |
| 10183 | |
| 10184 | THROW_WALLET_EXCEPTION_IF(outs.size() < out_index + 1 , error::wallet_internal_error, "outs.size() < out_index + 1"); |
| 10185 | THROW_WALLET_EXCEPTION_IF(outs[out_index].size() < fake_outputs_count , error::wallet_internal_error, "fake_outputs_count > random outputs found"); |
| 10186 | |
| 10187 | typedef cryptonote::tx_source_entry::output_entry tx_output_entry; |
| 10188 | for (size_t n = 0; n < fake_outputs_count + 1; ++n) |
| 10189 | { |
| 10190 | tx_output_entry oe; |
| 10191 | oe.first = std::get<0>(outs[out_index][n]); |
| 10192 | oe.second.dest = rct::pk2rct(std::get<1>(outs[out_index][n])); |
| 10193 | oe.second.mask = std::get<2>(outs[out_index][n]); |
| 10194 | src.outputs.push_back(oe); |
| 10195 | } |
| 10196 | ++i; |
| 10197 | |
| 10198 | //paste real transaction to the random index |
| 10199 | auto it_to_replace = std::find_if(src.outputs.begin(), src.outputs.end(), [&](const tx_output_entry& a) |
| 10200 | { |
| 10201 | return a.first == td.m_global_output_index; |
| 10202 | }); |
| 10203 | THROW_WALLET_EXCEPTION_IF(it_to_replace == src.outputs.end(), error::wallet_internal_error, |
| 10204 | "real output not found"); |
| 10205 | |
| 10206 | tx_output_entry real_oe; |
| 10207 | real_oe.first = td.m_global_output_index; |
| 10208 | real_oe.second.dest = rct::pk2rct(td.get_public_key()); |
| 10209 | real_oe.second.mask = rct::commit(td.amount(), td.m_mask); |
| 10210 | *it_to_replace = real_oe; |
| 10211 | src.real_out_tx_key = get_tx_pub_key_from_extra(td.m_tx, td.m_pk_index); |
| 10212 | src.real_out_additional_tx_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 10213 | src.real_output = it_to_replace - src.outputs.begin(); |
| 10214 | src.real_output_in_tx_index = td.m_internal_output_index; |
| 10215 | src.mask = td.m_mask; |
| 10216 | if (m_multisig) |
| 10217 | // note: multisig_kLRki is a legacy struct, currently only used as a key image shuttle into the multisig tx builder |
| 10218 | src.multisig_kLRki = {.k = {}, .L = {}, .R = {}, .ki = rct::ki2rct(td.m_key_image)}; |
| 10219 | else |
| 10220 | src.multisig_kLRki = rct::multisig_kLRki({rct::zero(), rct::zero(), rct::zero(), rct::zero()}); |
| 10221 | detail::print_source_entry(src); |
| 10222 | ++out_index; |
| 10223 | } |
| 10224 | LOG_PRINT_L2("outputs prepared"); |
| 10225 | |
| 10226 | // we still keep a copy, since we want to keep dsts free of change for user feedback purposes |
| 10227 | std::vector<cryptonote::tx_destination_entry> splitted_dsts = dsts; |
| 10228 | cryptonote::tx_destination_entry change_dts = AUTO_VAL_INIT(change_dts); |
| 10229 | change_dts.amount = found_money - needed_money; |
| 10230 | if (change_dts.amount == 0) |
| 10231 | { |
| 10232 | if (splitted_dsts.size() == 1) |
| 10233 | { |
| 10234 | // If the change is 0, send it to a random address, to avoid confusing |
| 10235 | // the sender with a 0 amount output. We send a 0 amount in order to avoid |
| 10236 | // letting the destination be able to work out which of the inputs is the |
| 10237 | // real one in our rings |
| 10238 | LOG_PRINT_L2("generating dummy address for 0 change"); |
| 10239 | cryptonote::account_base dummy; |
| 10240 | dummy.generate(); |
| 10241 | change_dts.addr = dummy.get_keys().m_account_address; |
| 10242 | LOG_PRINT_L2("generated dummy address for 0 change"); |
| 10243 | splitted_dsts.push_back(change_dts); |
| 10244 | } |
| 10245 | } |
| 10246 | else |
| 10247 | { |
| 10248 | change_dts.addr = get_subaddress({subaddr_account, 0}); |
| 10249 | change_dts.is_subaddress = subaddr_account != 0; |
| 10250 | splitted_dsts.push_back(change_dts); |
| 10251 | } |
| 10252 | |
| 10253 | crypto::secret_key tx_key; |
| 10254 | std::vector<crypto::secret_key> additional_tx_keys; |
| 10255 | crypto::secret_key multisig_tx_key_entropy; |
| 10256 | LOG_PRINT_L2("constructing tx"); |
| 10257 | auto sources_copy = sources; |
| 10258 | multisig::signing::tx_builder_ringct_t multisig_tx_builder; |
| 10259 | if (m_multisig) { |
| 10260 | // prepare the core part of a multisig tx (many tx attempts for different signer groups can be spun off this core piece) |
| 10261 | std::set<std::uint32_t> subaddr_minor_indices; |
| 10262 | for (size_t idx: selected_transfers) { |
| 10263 | subaddr_minor_indices.insert(m_transfers[idx].m_subaddr_index.minor); |
| 10264 | } |
| 10265 | THROW_WALLET_EXCEPTION_IF( |
| 10266 | not multisig_tx_builder.init(m_account.get_keys(), |
| 10267 | extra, |
| 10268 | subaddr_account, |
| 10269 | subaddr_minor_indices, |
| 10270 | sources, |
| 10271 | splitted_dsts, |
| 10272 | change_dts, |
| 10273 | rct_config, |
| 10274 | true, |
| 10275 | false, |
| 10276 | tx_key, |
| 10277 | additional_tx_keys, |
| 10278 | multisig_tx_key_entropy, |
| 10279 | tx |
| 10280 | ), |
| 10281 | error::wallet_internal_error, |
| 10282 | "error: multisig::signing::tx_builder_ringct_t::init" |
| 10283 | ); |
| 10284 | } |
| 10285 | else { |
| 10286 | // make a normal tx |
| 10287 | bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), m_subaddresses, sources, splitted_dsts, change_dts.addr, extra, tx, tx_key, additional_tx_keys, true, rct_config, use_view_tags); |
| 10288 | LOG_PRINT_L2("constructed tx, r="<<r); |
| 10289 | THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sources, dsts, m_nettype); |
| 10290 | } |
| 10291 | THROW_WALLET_EXCEPTION_IF(upper_transaction_weight_limit <= get_transaction_weight(tx), error::tx_too_big, tx, upper_transaction_weight_limit); |
| 10292 | |
| 10293 | // work out the permutation done on sources |
| 10294 | std::vector<size_t> ins_order; |
| 10295 | for (size_t n = 0; n < sources.size(); ++n) |
| 10296 | { |
| 10297 | for (size_t idx = 0; idx < sources_copy.size(); ++idx) |
| 10298 | { |
| 10299 | THROW_WALLET_EXCEPTION_IF((size_t)sources_copy[idx].real_output >= sources_copy[idx].outputs.size(), |
| 10300 | error::wallet_internal_error, "Invalid real_output"); |
| 10301 | if (sources_copy[idx].outputs[sources_copy[idx].real_output].second.dest == sources[n].outputs[sources[n].real_output].second.dest) |
| 10302 | ins_order.push_back(idx); |
| 10303 | } |
| 10304 | } |
| 10305 | THROW_WALLET_EXCEPTION_IF(ins_order.size() != sources.size(), error::wallet_internal_error, "Failed to work out sources permutation"); |
| 10306 | |
| 10307 | std::vector<tools::wallet2::multisig_sig> multisig_sigs; |
| 10308 | if (m_multisig) { |
| 10309 | if (ignore_sets.empty()) |
| 10310 | ignore_sets.emplace_back(); |
| 10311 | const std::size_t num_multisig_attempts = ignore_sets.size(); |
| 10312 | multisig_sigs.resize(num_multisig_attempts); |
| 10313 | std::unordered_set<rct::key> all_used_L; |
| 10314 | std::unordered_set<crypto::public_key> signing_keys; |
| 10315 | for (const crypto::secret_key &multisig_skey: get_account().get_multisig_keys()) |
| 10316 | signing_keys.insert(get_multisig_signing_public_key(multisig_skey)); |
| 10317 | const std::size_t num_sources = sources.size(); |
| 10318 | const std::size_t num_alpha_components = multisig::signing::kAlphaComponents; |
| 10319 | |
| 10320 | // initiate a multisig tx attempt for each unique set of signers that |
| 10321 | // a) includes the local signer |
| 10322 | // b) includes other signers who most recently sent the local signer LR public nonces via 'export_multisig() -> import_multisig()' |
| 10323 | for (std::size_t i = 0; i < num_multisig_attempts; ++i) { |
| 10324 | multisig_sig& sig = multisig_sigs[i]; |
| 10325 | sig.total_alpha_G.resize(num_sources, rct::keyV(num_alpha_components)); |
| 10326 | sig.total_alpha_H.resize(num_sources, rct::keyV(num_alpha_components)); |
| 10327 | sig.s.resize(num_sources); |
| 10328 | sig.c_0.resize(num_sources); |
| 10329 | |
| 10330 | // for each tx input, get public musig2-style nonces from |
| 10331 | // a) temporary local-generated private nonces (used to make the local partial signatures on each tx attempt) |
| 10332 | // b) other signers' public nonces, sent to the local signer via 'export_multisig() -> import_multisig()' |
| 10333 | // - WARNING: If two multisig players initiate multisig tx attempts separately, but spend the same funds (and hence rely on the same LR public nonces), |
| 10334 | // then if two signers partially sign different tx attempt sets, then all attempts that require both signers will become garbage, |
| 10335 | // because LR nonces can only be used for one tx attempt. |
| 10336 | for (std::size_t j = 0; j < num_sources; ++j) { |
| 10337 | rct::keyV alpha(num_alpha_components); |
| 10338 | auto alpha_wiper = epee::misc_utils::create_scope_leave_handler([&]{ |
| 10339 | memwipe(static_cast<rct::key *>(alpha.data()), alpha.size() * sizeof(rct::key)); |
| 10340 | }); |
| 10341 | for (std::size_t m = 0; m < num_alpha_components; ++m) { |
| 10342 | const rct::multisig_kLRki kLRki = get_multisig_composite_kLRki( |
| 10343 | selected_transfers[ins_order[j]], |
| 10344 | ignore_sets[i], |
| 10345 | all_used_L, //collect all public L nonces used by this tx proposal (set of tx attempts) to avoid duplicates |
| 10346 | sig.used_L //record the public L nonces used by this tx input to this tx attempt, for coordination with other signers |
| 10347 | ); |
| 10348 | alpha[m] = kLRki.k; |
| 10349 | sig.total_alpha_G[j][m] = kLRki.L; |
| 10350 | sig.total_alpha_H[j][m] = kLRki.R; |
| 10351 | } |
| 10352 | |
| 10353 | // local signer: initial partial signature on this tx input for this tx attempt |
| 10354 | // note: sign here with sender-receiver secret component, subaddress component, and ALL of the local signer's multisig key shares |
| 10355 | // (this ultimately occurs deep in generate_key_image_helper_precomp()) |
| 10356 | THROW_WALLET_EXCEPTION_IF( |
| 10357 | not multisig_tx_builder.first_partial_sign(j, sig.total_alpha_G[j], sig.total_alpha_H[j], alpha, sig.c_0[j], sig.s[j]), |
| 10358 | error::wallet_internal_error, |
| 10359 | "error: multisig::signing::tx_builder_ringct_t::first_partial_sign" |
| 10360 | ); |
| 10361 | } |
| 10362 | |
| 10363 | // note: record the ignore set so when other signers go to add their signatures (sign_multisig_tx()), they |
| 10364 | // can skip this tx attempt if they aren't supposed to sign it; this only works for signers who provided |
| 10365 | // multisig_infos to the last 'import_multisig()' call by the local signer, all 'other signers' will encounter |
| 10366 | // a 'need to export multisig_info' wallet error if they try to sign this partial tx, which means if they want to sign a tx |
| 10367 | // they need to export_multisig() -> send to the local signer -> local signer calls import_multisig() with fresh |
| 10368 | // multisig_infos from all signers -> local signer makes completely new tx attempts (or a different signer makes tx attempts) |
| 10369 | sig.ignore = ignore_sets[i]; |
| 10370 | sig.signing_keys = signing_keys; //the local signer signed with ALL of their multisig key shares, record their pubkeys for reference by other signers |
| 10371 | } |
| 10372 | if (m_multisig_threshold <= 1) { |
| 10373 | // local signer: finish signing the tx inputs if we are the only signer (ignore all but the first 'attempt') |
| 10374 | THROW_WALLET_EXCEPTION_IF( |
| 10375 | not multisig_tx_builder.finalize_tx(sources, multisig_sigs[0].c_0, multisig_sigs[0].s, tx), |
| 10376 | error::wallet_internal_error, |
| 10377 | "error: multisig::signing::tx_builder_ringct_t::finalize_tx" |
| 10378 | ); |
| 10379 | } |
| 10380 | } |
| 10381 | |
| 10382 | LOG_PRINT_L2("gathering key images"); |
| 10383 | std::string key_images; |
| 10384 | bool all_are_txin_to_key = std::all_of(tx.vin.begin(), tx.vin.end(), [&](const txin_v& s_e) -> bool |
| 10385 | { |
| 10386 | CHECKED_GET_SPECIFIC_VARIANT(s_e, const txin_to_key, in, false); |
| 10387 | key_images += boost::to_string(in.k_image) + " "; |
| 10388 | return true; |
| 10389 | }); |
| 10390 | THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, tx); |
| 10391 | LOG_PRINT_L2("gathered key images"); |
| 10392 | |
| 10393 | ptx.key_images = key_images; |
| 10394 | ptx.fee = fee; |
| 10395 | ptx.dust = 0; |
| 10396 | ptx.dust_added_to_fee = false; |
| 10397 | ptx.tx = tx; |
| 10398 | ptx.change_dts = change_dts; |
| 10399 | ptx.selected_transfers = selected_transfers; |
| 10400 | tools::apply_permutation(ins_order, ptx.selected_transfers); |
| 10401 | ptx.tx_key = tx_key; |
| 10402 | ptx.additional_tx_keys = additional_tx_keys; |
| 10403 | ptx.dests = dsts; |
| 10404 | ptx.multisig_sigs = multisig_sigs; |
| 10405 | ptx.multisig_tx_key_entropy = multisig_tx_key_entropy; |
| 10406 | ptx.construction_data.sources = sources_copy; |
| 10407 | ptx.construction_data.change_dts = change_dts; |
| 10408 | ptx.construction_data.splitted_dsts = splitted_dsts; |
| 10409 | ptx.construction_data.selected_transfers = ptx.selected_transfers; |
| 10410 | ptx.construction_data.extra = tx.extra; |
| 10411 | ptx.construction_data.unlock_time = 0; |
| 10412 | ptx.construction_data.use_rct = true; |
| 10413 | ptx.construction_data.rct_config = { |
| 10414 | rct::RangeProofPaddedBulletproof, |
| 10415 | use_fork_rules(HF_VERSION_BULLETPROOF_PLUS, -10) ? 4 : 3 |
| 10416 | }; |
| 10417 | ptx.construction_data.use_view_tags = use_fork_rules(get_view_tag_fork(), 0); |
| 10418 | ptx.construction_data.dests = dsts; |
| 10419 | // record which subaddress indices are being used as inputs |
| 10420 | ptx.construction_data.subaddr_account = subaddr_account; |
| 10421 | ptx.construction_data.subaddr_indices.clear(); |
| 10422 | for (size_t idx: selected_transfers) |
| 10423 | ptx.construction_data.subaddr_indices.insert(m_transfers[idx].m_subaddr_index.minor); |
| 10424 | LOG_PRINT_L2("transfer_selected_rct done"); |
| 10425 | } |
| 10426 | |
| 10427 | std::vector<size_t> wallet2::pick_preferred_rct_inputs(uint64_t needed_money, uint32_t subaddr_account, const std::set<uint32_t> &subaddr_indices) |
| 10428 | { |
| 10429 | std::vector<size_t> picks; |
| 10430 | float current_output_relatdness = 1.0f; |
| 10431 | |
| 10432 | LOG_PRINT_L2("pick_preferred_rct_inputs: needed_money " << print_money(needed_money)); |
| 10433 | |
| 10434 | // try to find a rct input of enough size |
| 10435 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 10436 | { |
| 10437 | const transfer_details& td = m_transfers[i]; |
| 10438 | if (!is_spent(td, false) && !td.m_frozen && td.is_rct() && td.amount() >= needed_money && is_transfer_unlocked(td) && td.m_subaddr_index.major == subaddr_account && subaddr_indices.count(td.m_subaddr_index.minor) == 1) |
| 10439 | { |
| 10440 | if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) |
| 10441 | { |
| 10442 | MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); |
| 10443 | continue; |
| 10444 | } |
| 10445 | LOG_PRINT_L2("We can use " << i << " alone: " << print_money(td.amount())); |
| 10446 | picks.push_back(i); |
| 10447 | return picks; |
| 10448 | } |
| 10449 | } |
| 10450 | |
| 10451 | // then try to find two outputs |
| 10452 | // this could be made better by picking one of the outputs to be a small one, since those |
| 10453 | // are less useful since often below the needed money, so if one can be used in a pair, |
| 10454 | // it gets rid of it for the future |
| 10455 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 10456 | { |
| 10457 | const transfer_details& td = m_transfers[i]; |
| 10458 | if (!is_spent(td, false) && !td.m_frozen && !td.m_key_image_partial && td.is_rct() && is_transfer_unlocked(td) && td.m_subaddr_index.major == subaddr_account && subaddr_indices.count(td.m_subaddr_index.minor) == 1) |
| 10459 | { |
| 10460 | if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) |
| 10461 | { |
| 10462 | MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); |
| 10463 | continue; |
| 10464 | } |
| 10465 | LOG_PRINT_L2("Considering input " << i << ", " << print_money(td.amount())); |
| 10466 | for (size_t j = i + 1; j < m_transfers.size(); ++j) |
| 10467 | { |
| 10468 | const transfer_details& td2 = m_transfers[j]; |
| 10469 | if (td2.amount() > m_ignore_outputs_above || td2.amount() < m_ignore_outputs_below) |
| 10470 | { |
| 10471 | MDEBUG("Ignoring output " << j << " of amount " << print_money(td2.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); |
| 10472 | continue; |
| 10473 | } |
| 10474 | if (!is_spent(td2, false) && !td2.m_frozen && !td2.m_key_image_partial && td2.is_rct() && td.amount() + td2.amount() >= needed_money && is_transfer_unlocked(td2) && td2.m_subaddr_index == td.m_subaddr_index) |
| 10475 | { |
| 10476 | // update our picks if those outputs are less related than any we |
| 10477 | // already found. If the same, don't update, and oldest suitable outputs |
| 10478 | // will be used in preference. |
| 10479 | float relatedness = get_output_relatedness(td, td2); |
| 10480 | LOG_PRINT_L2(" with input " << j << ", " << print_money(td2.amount()) << ", relatedness " << relatedness); |
| 10481 | if (relatedness < current_output_relatdness) |
| 10482 | { |
| 10483 | // reset the current picks with those, and return them directly |
| 10484 | // if they're unrelated. If they are related, we'll end up returning |
| 10485 | // them if we find nothing better |
| 10486 | picks.clear(); |
| 10487 | picks.push_back(i); |
| 10488 | picks.push_back(j); |
| 10489 | LOG_PRINT_L0("we could use " << i << " and " << j); |
| 10490 | if (relatedness == 0.0f) |
| 10491 | return picks; |
| 10492 | current_output_relatdness = relatedness; |
| 10493 | } |
| 10494 | } |
| 10495 | } |
| 10496 | } |
| 10497 | } |
| 10498 | |
| 10499 | return picks; |
| 10500 | } |
| 10501 | |
| 10502 | bool wallet2::should_pick_a_second_output(bool use_rct, size_t n_transfers, const std::vector<size_t> &unused_transfers_indices, const std::vector<size_t> &unused_dust_indices) const |
| 10503 | { |
| 10504 | if (!use_rct) |
| 10505 | return false; |
| 10506 | if (n_transfers > 1) |
| 10507 | return false; |
| 10508 | if (unused_dust_indices.empty() && unused_transfers_indices.empty()) |
| 10509 | return false; |
| 10510 | // we want at least one free rct output to avoid a corner case where |
| 10511 | // we'd choose a non rct output which doesn't have enough "siblings" |
| 10512 | // value-wise on the chain, and thus can't be mixed |
| 10513 | bool found = false; |
| 10514 | for (auto i: unused_dust_indices) |
| 10515 | { |
| 10516 | if (m_transfers[i].is_rct()) |
| 10517 | { |
| 10518 | found = true; |
| 10519 | break; |
| 10520 | } |
| 10521 | } |
| 10522 | if (!found) for (auto i: unused_transfers_indices) |
| 10523 | { |
| 10524 | if (m_transfers[i].is_rct()) |
| 10525 | { |
| 10526 | found = true; |
| 10527 | break; |
| 10528 | } |
| 10529 | } |
| 10530 | if (!found) |
| 10531 | return false; |
| 10532 | return true; |
| 10533 | } |
| 10534 | |
| 10535 | std::vector<size_t> wallet2::get_only_rct(const std::vector<size_t> &unused_dust_indices, const std::vector<size_t> &unused_transfers_indices) const |
| 10536 | { |
| 10537 | std::vector<size_t> indices; |
| 10538 | for (size_t n: unused_dust_indices) |
| 10539 | if (m_transfers[n].is_rct()) |
| 10540 | indices.push_back(n); |
| 10541 | for (size_t n: unused_transfers_indices) |
| 10542 | if (m_transfers[n].is_rct()) |
| 10543 | indices.push_back(n); |
| 10544 | return indices; |
| 10545 | } |
| 10546 | |
| 10547 | static uint32_t get_count_above(const std::vector<wallet2::transfer_details> &transfers, const std::vector<size_t> &indices, uint64_t threshold) |
| 10548 | { |
| 10549 | uint32_t count = 0; |
| 10550 | for (size_t idx: indices) |
| 10551 | if (transfers[idx].amount() >= threshold) |
| 10552 | ++count; |
| 10553 | return count; |
| 10554 | } |
| 10555 | |
| 10556 | bool wallet2::light_wallet_login(bool &new_address) |
| 10557 | { |
| 10558 | MDEBUG("Light wallet login request"); |
| 10559 | m_light_wallet_connected = false; |
| 10560 | tools::COMMAND_RPC_LOGIN::request request; |
| 10561 | tools::COMMAND_RPC_LOGIN::response response; |
| 10562 | request.address = get_account().get_public_address_str(m_nettype); |
| 10563 | request.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 10564 | // Always create account if it doesn't exist. |
| 10565 | request.create_account = true; |
| 10566 | m_daemon_rpc_mutex.lock(); |
| 10567 | bool connected = invoke_http_json("/login", request, response, rpc_timeout, "POST"); |
| 10568 | m_daemon_rpc_mutex.unlock(); |
| 10569 | // MyMonero doesn't send any status message. OpenMonero does. |
| 10570 | m_light_wallet_connected = connected && (response.status.empty() || response.status == "success"); |
| 10571 | new_address = response.new_address; |
| 10572 | MDEBUG("Status: " << response.status); |
| 10573 | MDEBUG("Reason: " << response.reason); |
| 10574 | MDEBUG("New wallet: " << response.new_address); |
| 10575 | if(m_light_wallet_connected) |
| 10576 | { |
| 10577 | // Clear old data on successful login. |
| 10578 | // m_transfers.clear(); |
| 10579 | // m_payments.clear(); |
| 10580 | // m_unconfirmed_payments.clear(); |
| 10581 | } |
| 10582 | return m_light_wallet_connected; |
| 10583 | } |
| 10584 | |
| 10585 | bool wallet2::light_wallet_import_wallet_request(tools::COMMAND_RPC_IMPORT_WALLET_REQUEST::response &response) |
| 10586 | { |
| 10587 | MDEBUG("Light wallet import wallet request"); |
| 10588 | tools::COMMAND_RPC_IMPORT_WALLET_REQUEST::request oreq; |
| 10589 | oreq.address = get_account().get_public_address_str(m_nettype); |
| 10590 | oreq.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 10591 | m_daemon_rpc_mutex.lock(); |
| 10592 | bool r = invoke_http_json("/import_wallet_request", oreq, response, rpc_timeout, "POST"); |
| 10593 | m_daemon_rpc_mutex.unlock(); |
| 10594 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "import_wallet_request"); |
| 10595 | |
| 10596 | |
| 10597 | return true; |
| 10598 | } |
| 10599 | |
| 10600 | void wallet2::light_wallet_get_unspent_outs() |
| 10601 | { |
| 10602 | MDEBUG("Getting unspent outs"); |
| 10603 | |
| 10604 | tools::COMMAND_RPC_GET_UNSPENT_OUTS::request oreq; |
| 10605 | tools::COMMAND_RPC_GET_UNSPENT_OUTS::response ores; |
| 10606 | |
| 10607 | oreq.amount = "0"; |
| 10608 | oreq.address = get_account().get_public_address_str(m_nettype); |
| 10609 | oreq.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 10610 | // openMonero specific |
| 10611 | oreq.dust_threshold = boost::lexical_cast<std::string>(::config::DEFAULT_DUST_THRESHOLD); |
| 10612 | // below are required by openMonero api - but are not used. |
| 10613 | oreq.mixin = 0; |
| 10614 | oreq.use_dust = true; |
| 10615 | |
| 10616 | |
| 10617 | m_daemon_rpc_mutex.lock(); |
| 10618 | bool r = invoke_http_json("/get_unspent_outs", oreq, ores, rpc_timeout, "POST"); |
| 10619 | m_daemon_rpc_mutex.unlock(); |
| 10620 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_unspent_outs"); |
| 10621 | THROW_WALLET_EXCEPTION_IF(ores.status == "error", error::wallet_internal_error, ores.reason); |
| 10622 | |
| 10623 | m_light_wallet_per_kb_fee = ores.per_kb_fee; |
| 10624 | |
| 10625 | std::unordered_map<crypto::hash,bool> transfers_txs; |
| 10626 | for(const auto &t: m_transfers) |
| 10627 | transfers_txs.emplace(t.m_txid,t.m_spent); |
| 10628 | |
| 10629 | MDEBUG("FOUND " << ores.outputs.size() <<" outputs"); |
| 10630 | |
| 10631 | // return if no outputs found |
| 10632 | if(ores.outputs.empty()) |
| 10633 | return; |
| 10634 | |
| 10635 | // Clear old outputs |
| 10636 | m_transfers.clear(); |
| 10637 | |
| 10638 | for (const auto &o: ores.outputs) { |
| 10639 | bool spent = false; |
| 10640 | bool add_transfer = true; |
| 10641 | crypto::key_image unspent_key_image; |
| 10642 | crypto::public_key tx_public_key = AUTO_VAL_INIT(tx_public_key); |
| 10643 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, o.tx_pub_key), error::wallet_internal_error, "Invalid tx_pub_key field"); |
| 10644 | string_tools::hex_to_pod(o.tx_pub_key, tx_public_key); |
| 10645 | |
| 10646 | for (const std::string &ski: o.spend_key_images) { |
| 10647 | spent = false; |
| 10648 | |
| 10649 | // Check if key image is ours |
| 10650 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, ski), error::wallet_internal_error, "Invalid key image"); |
| 10651 | string_tools::hex_to_pod(ski, unspent_key_image); |
| 10652 | if(light_wallet_key_image_is_ours(unspent_key_image, tx_public_key, o.index)){ |
| 10653 | MTRACE("Output " << o.public_key << " is spent. Key image: " << ski); |
| 10654 | spent = true; |
| 10655 | break; |
| 10656 | } { |
| 10657 | MTRACE("Unspent output found. " << o.public_key); |
| 10658 | } |
| 10659 | } |
| 10660 | |
| 10661 | // Check if tx already exists in m_transfers. |
| 10662 | crypto::hash txid; |
| 10663 | crypto::public_key tx_pub_key; |
| 10664 | crypto::public_key public_key; |
| 10665 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, o.tx_hash), error::wallet_internal_error, "Invalid tx_hash field"); |
| 10666 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, o.public_key), error::wallet_internal_error, "Invalid public_key field"); |
| 10667 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, o.tx_pub_key), error::wallet_internal_error, "Invalid tx_pub_key field"); |
| 10668 | string_tools::hex_to_pod(o.tx_hash, txid); |
| 10669 | string_tools::hex_to_pod(o.public_key, public_key); |
| 10670 | string_tools::hex_to_pod(o.tx_pub_key, tx_pub_key); |
| 10671 | |
| 10672 | for(auto &t: m_transfers){ |
| 10673 | if(t.get_public_key() == public_key) { |
| 10674 | t.m_spent = spent; |
| 10675 | add_transfer = false; |
| 10676 | break; |
| 10677 | } |
| 10678 | } |
| 10679 | |
| 10680 | if(!add_transfer) |
| 10681 | continue; |
| 10682 | |
| 10683 | m_transfers.push_back(transfer_details{}); |
| 10684 | transfer_details& td = m_transfers.back(); |
| 10685 | |
| 10686 | td.m_block_height = o.height; |
| 10687 | td.m_global_output_index = o.global_index; |
| 10688 | td.m_txid = txid; |
| 10689 | |
| 10690 | // Add to extra |
| 10691 | add_tx_pub_key_to_extra(td.m_tx, tx_pub_key); |
| 10692 | |
| 10693 | td.m_key_image = unspent_key_image; |
| 10694 | td.m_key_image_known = !m_watch_only && !m_multisig; |
| 10695 | td.m_key_image_request = false; |
| 10696 | td.m_key_image_partial = m_multisig; |
| 10697 | td.m_amount = o.amount; |
| 10698 | td.m_pk_index = 0; |
| 10699 | td.m_internal_output_index = o.index; |
| 10700 | td.m_spent = spent; |
| 10701 | td.m_frozen = false; |
| 10702 | |
| 10703 | tx_out txout; |
| 10704 | txout.target = txout_to_key(public_key); |
| 10705 | txout.amount = td.m_amount; |
| 10706 | |
| 10707 | td.m_tx.vout.resize(td.m_internal_output_index + 1); |
| 10708 | td.m_tx.vout[td.m_internal_output_index] = txout; |
| 10709 | |
| 10710 | // Add unlock time and coinbase bool got from get_address_txs api call |
| 10711 | std::unordered_map<crypto::hash,address_tx>::const_iterator found = m_light_wallet_address_txs.find(txid); |
| 10712 | THROW_WALLET_EXCEPTION_IF(found == m_light_wallet_address_txs.end(), error::wallet_internal_error, "Lightwallet: tx not found in m_light_wallet_address_txs"); |
| 10713 | bool miner_tx = found->second.m_coinbase; |
| 10714 | td.m_tx.unlock_time = found->second.m_unlock_time; |
| 10715 | |
| 10716 | if (!o.rct.empty()) |
| 10717 | { |
| 10718 | // Coinbase tx's |
| 10719 | if(miner_tx) |
| 10720 | { |
| 10721 | td.m_mask = rct::identity(); |
| 10722 | } |
| 10723 | else |
| 10724 | { |
| 10725 | // rct txs |
| 10726 | // decrypt rct mask, calculate commit hash and compare against blockchain commit hash |
| 10727 | rct::key rct_commit; |
| 10728 | light_wallet_parse_rct_str(o.rct, tx_pub_key, td.m_internal_output_index, td.m_mask, rct_commit, true); |
| 10729 | bool valid_commit = (rct_commit == rct::commit(td.amount(), td.m_mask)); |
| 10730 | if(!valid_commit) |
| 10731 | { |
| 10732 | MDEBUG("output index: " << o.global_index); |
| 10733 | MDEBUG("mask: " + string_tools::pod_to_hex(td.m_mask)); |
| 10734 | MDEBUG("calculated commit: " + string_tools::pod_to_hex(rct::commit(td.amount(), td.m_mask))); |
| 10735 | MDEBUG("expected commit: " + string_tools::pod_to_hex(rct_commit)); |
| 10736 | MDEBUG("amount: " << td.amount()); |
| 10737 | } |
| 10738 | THROW_WALLET_EXCEPTION_IF(!valid_commit, error::wallet_internal_error, "Lightwallet: rct commit hash mismatch!"); |
| 10739 | } |
| 10740 | td.m_rct = true; |
| 10741 | } |
| 10742 | else |
| 10743 | { |
| 10744 | td.m_mask = rct::identity(); |
| 10745 | td.m_rct = false; |
| 10746 | } |
| 10747 | if(!spent) |
| 10748 | set_unspent(m_transfers.size()-1); |
| 10749 | m_key_images[td.m_key_image] = m_transfers.size()-1; |
| 10750 | m_pub_keys[td.get_public_key()] = m_transfers.size()-1; |
| 10751 | } |
| 10752 | } |
| 10753 | |
| 10754 | bool wallet2::light_wallet_get_address_info(tools::COMMAND_RPC_GET_ADDRESS_INFO::response &response) |
| 10755 | { |
| 10756 | MTRACE(__FUNCTION__); |
| 10757 | |
| 10758 | tools::COMMAND_RPC_GET_ADDRESS_INFO::request request; |
| 10759 | |
| 10760 | request.address = get_account().get_public_address_str(m_nettype); |
| 10761 | request.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 10762 | m_daemon_rpc_mutex.lock(); |
| 10763 | bool r = invoke_http_json("/get_address_info", request, response, rpc_timeout, "POST"); |
| 10764 | m_daemon_rpc_mutex.unlock(); |
| 10765 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_address_info"); |
| 10766 | // TODO: Validate result |
| 10767 | return true; |
| 10768 | } |
| 10769 | |
| 10770 | void wallet2::light_wallet_get_address_txs() |
| 10771 | { |
| 10772 | MDEBUG("Refreshing light wallet"); |
| 10773 | |
| 10774 | tools::COMMAND_RPC_GET_ADDRESS_TXS::request ireq; |
| 10775 | tools::COMMAND_RPC_GET_ADDRESS_TXS::response ires; |
| 10776 | |
| 10777 | ireq.address = get_account().get_public_address_str(m_nettype); |
| 10778 | ireq.view_key = string_tools::pod_to_hex(unwrap(unwrap(get_account().get_keys().m_view_secret_key))); |
| 10779 | m_daemon_rpc_mutex.lock(); |
| 10780 | bool r = invoke_http_json("/get_address_txs", ireq, ires, rpc_timeout, "POST"); |
| 10781 | m_daemon_rpc_mutex.unlock(); |
| 10782 | THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_address_txs"); |
| 10783 | //OpenMonero sends status=success, Mymonero doesn't. |
| 10784 | THROW_WALLET_EXCEPTION_IF((!ires.status.empty() && ires.status != "success"), error::no_connection_to_daemon, "get_address_txs"); |
| 10785 | |
| 10786 | |
| 10787 | // Abort if no transactions |
| 10788 | if(ires.transactions.empty()) |
| 10789 | return; |
| 10790 | |
| 10791 | // Create searchable vectors |
| 10792 | std::vector<crypto::hash> payments_txs; |
| 10793 | for(const auto &p: m_payments) |
| 10794 | payments_txs.push_back(p.second.m_tx_hash); |
| 10795 | std::vector<crypto::hash> unconfirmed_payments_txs; |
| 10796 | for(const auto &up: m_unconfirmed_payments) |
| 10797 | unconfirmed_payments_txs.push_back(up.second.m_pd.m_tx_hash); |
| 10798 | |
| 10799 | // for balance calculation |
| 10800 | uint64_t wallet_total_sent = 0; |
| 10801 | // txs in pool |
| 10802 | std::vector<crypto::hash> pool_txs; |
| 10803 | |
| 10804 | for (const auto &t: ires.transactions) { |
| 10805 | const uint64_t total_received = t.total_received; |
| 10806 | uint64_t total_sent = t.total_sent; |
| 10807 | |
| 10808 | // Check key images - subtract fake outputs from total_sent |
| 10809 | for(const auto &so: t.spent_outputs) |
| 10810 | { |
| 10811 | crypto::public_key tx_public_key; |
| 10812 | crypto::key_image key_image; |
| 10813 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, so.tx_pub_key), error::wallet_internal_error, "Invalid tx_pub_key field"); |
| 10814 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, so.key_image), error::wallet_internal_error, "Invalid key_image field"); |
| 10815 | string_tools::hex_to_pod(so.tx_pub_key, tx_public_key); |
| 10816 | string_tools::hex_to_pod(so.key_image, key_image); |
| 10817 | |
| 10818 | if(!light_wallet_key_image_is_ours(key_image, tx_public_key, so.out_index)) { |
| 10819 | THROW_WALLET_EXCEPTION_IF(so.amount > t.total_sent, error::wallet_internal_error, "Lightwallet: total sent is negative!"); |
| 10820 | total_sent -= so.amount; |
| 10821 | } |
| 10822 | } |
| 10823 | |
| 10824 | // Do not add tx if empty. |
| 10825 | if(total_sent == 0 && total_received == 0) |
| 10826 | continue; |
| 10827 | |
| 10828 | crypto::hash payment_id = null_hash; |
| 10829 | crypto::hash tx_hash; |
| 10830 | |
| 10831 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, t.payment_id), error::wallet_internal_error, "Invalid payment_id field"); |
| 10832 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, t.hash), error::wallet_internal_error, "Invalid hash field"); |
| 10833 | string_tools::hex_to_pod(t.payment_id, payment_id); |
| 10834 | string_tools::hex_to_pod(t.hash, tx_hash); |
| 10835 | |
| 10836 | // lightwallet specific info |
| 10837 | bool incoming = (total_received > total_sent); |
| 10838 | address_tx address_tx; |
| 10839 | address_tx.m_tx_hash = tx_hash; |
| 10840 | address_tx.m_incoming = incoming; |
| 10841 | address_tx.m_amount = incoming ? total_received - total_sent : total_sent - total_received; |
| 10842 | address_tx.m_fee = 0; // TODO |
| 10843 | address_tx.m_block_height = t.height; |
| 10844 | address_tx.m_unlock_time = t.unlock_time; |
| 10845 | address_tx.m_timestamp = t.timestamp; |
| 10846 | address_tx.m_coinbase = t.coinbase; |
| 10847 | address_tx.m_mempool = t.mempool; |
| 10848 | m_light_wallet_address_txs.emplace(tx_hash,address_tx); |
| 10849 | |
| 10850 | // populate data needed for history (m_payments, m_unconfirmed_payments, m_confirmed_txs) |
| 10851 | // INCOMING transfers |
| 10852 | if(total_received > total_sent) { |
| 10853 | payment_details payment; |
| 10854 | payment.m_tx_hash = tx_hash; |
| 10855 | payment.m_amount = total_received - total_sent; |
| 10856 | payment.m_fee = 0; // TODO |
| 10857 | payment.m_block_height = t.height; |
| 10858 | payment.m_unlock_time = t.unlock_time; |
| 10859 | payment.m_timestamp = t.timestamp; |
| 10860 | payment.m_coinbase = t.coinbase; |
| 10861 | |
| 10862 | if (t.mempool) { |
| 10863 | if (std::find(unconfirmed_payments_txs.begin(), unconfirmed_payments_txs.end(), tx_hash) == unconfirmed_payments_txs.end()) { |
| 10864 | pool_txs.push_back(tx_hash); |
| 10865 | // assume false as we don't get that info from the light wallet server |
| 10866 | crypto::hash payment_id; |
| 10867 | THROW_WALLET_EXCEPTION_IF(!epee::string_tools::hex_to_pod(t.payment_id, payment_id), |
| 10868 | error::wallet_internal_error, "Failed to parse payment id"); |
| 10869 | emplace_or_replace(m_unconfirmed_payments, payment_id, pool_payment_details{payment, false}); |
| 10870 | if (0 != m_callback) { |
| 10871 | m_callback->on_lw_unconfirmed_money_received(t.height, payment.m_tx_hash, payment.m_amount); |
| 10872 | } |
| 10873 | } |
| 10874 | } else { |
| 10875 | if (std::find(payments_txs.begin(), payments_txs.end(), tx_hash) == payments_txs.end()) { |
| 10876 | m_payments.emplace(tx_hash, payment); |
| 10877 | if (0 != m_callback) { |
| 10878 | m_callback->on_lw_money_received(t.height, payment.m_tx_hash, payment.m_amount); |
| 10879 | } |
| 10880 | } |
| 10881 | } |
| 10882 | // Outgoing transfers |
| 10883 | } else { |
| 10884 | uint64_t amount_sent = total_sent - total_received; |
| 10885 | cryptonote::transaction dummy_tx; // not used by light wallet |
| 10886 | // increase wallet total sent |
| 10887 | wallet_total_sent += total_sent; |
| 10888 | if (t.mempool) |
| 10889 | { |
| 10890 | // Handled by add_unconfirmed_tx in commit_tx |
| 10891 | // If sent from another wallet instance we need to add it |
| 10892 | if(m_unconfirmed_txs.find(tx_hash) == m_unconfirmed_txs.end()) |
| 10893 | { |
| 10894 | unconfirmed_transfer_details utd; |
| 10895 | utd.m_amount_in = amount_sent; |
| 10896 | utd.m_amount_out = amount_sent; |
| 10897 | utd.m_change = 0; |
| 10898 | utd.m_payment_id = payment_id; |
| 10899 | utd.m_timestamp = t.timestamp; |
| 10900 | utd.m_state = wallet2::unconfirmed_transfer_details::pending; |
| 10901 | m_unconfirmed_txs.emplace(tx_hash,utd); |
| 10902 | } |
| 10903 | } |
| 10904 | else |
| 10905 | { |
| 10906 | // Only add if new |
| 10907 | auto confirmed_tx = m_confirmed_txs.find(tx_hash); |
| 10908 | if(confirmed_tx == m_confirmed_txs.end()) { |
| 10909 | // tx is added to m_unconfirmed_txs - move to confirmed |
| 10910 | if(m_unconfirmed_txs.find(tx_hash) != m_unconfirmed_txs.end()) |
| 10911 | { |
| 10912 | process_unconfirmed(tx_hash, dummy_tx, t.height); |
| 10913 | } |
| 10914 | // Tx sent by another wallet instance |
| 10915 | else |
| 10916 | { |
| 10917 | confirmed_transfer_details ctd; |
| 10918 | ctd.m_amount_in = amount_sent; |
| 10919 | ctd.m_amount_out = amount_sent; |
| 10920 | ctd.m_change = 0; |
| 10921 | ctd.m_payment_id = payment_id; |
| 10922 | ctd.m_block_height = t.height; |
| 10923 | ctd.m_timestamp = t.timestamp; |
| 10924 | m_confirmed_txs.emplace(tx_hash,ctd); |
| 10925 | } |
| 10926 | if (0 != m_callback) |
| 10927 | { |
| 10928 | m_callback->on_lw_money_spent(t.height, tx_hash, amount_sent); |
| 10929 | } |
| 10930 | } |
| 10931 | // If not new - check the amount and update if necessary. |
| 10932 | // when sending a tx to same wallet the receiving amount has to be credited |
| 10933 | else |
| 10934 | { |
| 10935 | if(confirmed_tx->second.m_amount_in != amount_sent || confirmed_tx->second.m_amount_out != amount_sent) |
| 10936 | { |
| 10937 | MDEBUG("Adjusting amount sent/received for tx: <" + t.hash + ">. Is tx sent to own wallet? " << print_money(amount_sent) << " != " << print_money(confirmed_tx->second.m_amount_in)); |
| 10938 | confirmed_tx->second.m_amount_in = amount_sent; |
| 10939 | confirmed_tx->second.m_amount_out = amount_sent; |
| 10940 | confirmed_tx->second.m_change = 0; |
| 10941 | } |
| 10942 | } |
| 10943 | } |
| 10944 | } |
| 10945 | } |
| 10946 | // TODO: purge old unconfirmed_txs |
| 10947 | remove_obsolete_pool_txs(pool_txs, false); |
| 10948 | |
| 10949 | // Calculate wallet balance |
| 10950 | m_light_wallet_balance = ires.total_received-wallet_total_sent; |
| 10951 | // MyMonero doesn't send unlocked balance |
| 10952 | if(ires.total_received_unlocked > 0) |
| 10953 | m_light_wallet_unlocked_balance = ires.total_received_unlocked-wallet_total_sent; |
| 10954 | else |
| 10955 | m_light_wallet_unlocked_balance = m_light_wallet_balance; |
| 10956 | } |
| 10957 | |
| 10958 | bool wallet2::light_wallet_parse_rct_str(const std::string& rct_string, const crypto::public_key& tx_pub_key, uint64_t internal_output_index, rct::key& decrypted_mask, rct::key& rct_commit, bool decrypt) const |
| 10959 | { |
| 10960 | // rct string is empty if output is non RCT |
| 10961 | if (rct_string.empty()) |
| 10962 | return false; |
| 10963 | // rct_string is a string with length 64+64+64 (<rct commit> + <encrypted mask> + <rct amount>) |
| 10964 | rct::key encrypted_mask; |
| 10965 | std::string rct_commit_str = rct_string.substr(0,64); |
| 10966 | std::string encrypted_mask_str = rct_string.substr(64,64); |
| 10967 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, rct_commit_str), error::wallet_internal_error, "Invalid rct commit hash: " + rct_commit_str); |
| 10968 | THROW_WALLET_EXCEPTION_IF(string_tools::validate_hex(64, encrypted_mask_str), error::wallet_internal_error, "Invalid rct mask: " + encrypted_mask_str); |
| 10969 | string_tools::hex_to_pod(rct_commit_str, rct_commit); |
| 10970 | string_tools::hex_to_pod(encrypted_mask_str, encrypted_mask); |
| 10971 | if (decrypt) { |
| 10972 | // Decrypt the mask |
| 10973 | crypto::key_derivation derivation; |
| 10974 | bool r = generate_key_derivation(tx_pub_key, get_account().get_keys().m_view_secret_key, derivation); |
| 10975 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key derivation"); |
| 10976 | crypto::secret_key scalar; |
| 10977 | crypto::derivation_to_scalar(derivation, internal_output_index, scalar); |
| 10978 | sc_sub(decrypted_mask.bytes,encrypted_mask.bytes,rct::hash_to_scalar(rct::sk2rct(scalar)).bytes); |
| 10979 | } |
| 10980 | return true; |
| 10981 | } |
| 10982 | |
| 10983 | bool wallet2::light_wallet_key_image_is_ours(const crypto::key_image& key_image, const crypto::public_key& tx_public_key, uint64_t out_index) |
| 10984 | { |
| 10985 | // Lookup key image from cache |
| 10986 | serializable_map<uint64_t, crypto::key_image> index_keyimage_map; |
| 10987 | serializable_unordered_map<crypto::public_key, serializable_map<uint64_t, crypto::key_image> >::const_iterator found_pub_key = m_key_image_cache.find(tx_public_key); |
| 10988 | if(found_pub_key != m_key_image_cache.end()) { |
| 10989 | // pub key found. key image for index cached? |
| 10990 | index_keyimage_map = found_pub_key->second; |
| 10991 | std::map<uint64_t,crypto::key_image>::const_iterator index_found = index_keyimage_map.find(out_index); |
| 10992 | if(index_found != index_keyimage_map.end()) |
| 10993 | return key_image == index_found->second; |
| 10994 | } |
| 10995 | |
| 10996 | // Not in cache - calculate key image |
| 10997 | crypto::key_image calculated_key_image; |
| 10998 | cryptonote::keypair in_ephemeral; |
| 10999 | |
| 11000 | // Subaddresses aren't supported in mymonero/openmonero yet. Roll out the original scheme: |
| 11001 | // compute D = a*R |
| 11002 | // compute P = Hs(D || i)*G + B |
| 11003 | // compute x = Hs(D || i) + b (and check if P==x*G) |
| 11004 | // compute I = x*Hp(P) |
| 11005 | const account_keys& ack = get_account().get_keys(); |
| 11006 | crypto::key_derivation derivation; |
| 11007 | bool r = crypto::generate_key_derivation(tx_public_key, ack.m_view_secret_key, derivation); |
| 11008 | CHECK_AND_ASSERT_MES(r, false, "failed to generate_key_derivation(" << tx_public_key << ", " << crypto::secret_key_explicit_print_ref{ack.m_view_secret_key} << ")"); |
| 11009 | |
| 11010 | r = crypto::derive_public_key(derivation, out_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub); |
| 11011 | CHECK_AND_ASSERT_MES(r, false, "failed to derive_public_key (" << derivation << ", " << out_index << ", " << ack.m_account_address.m_spend_public_key << ")"); |
| 11012 | |
| 11013 | crypto::derive_secret_key(derivation, out_index, ack.m_spend_secret_key, in_ephemeral.sec); |
| 11014 | crypto::public_key out_pkey_test; |
| 11015 | r = crypto::secret_key_to_public_key(in_ephemeral.sec, out_pkey_test); |
| 11016 | CHECK_AND_ASSERT_MES(r, false, "failed to secret_key_to_public_key(" << crypto::secret_key_explicit_print_ref{in_ephemeral.sec} << ")"); |
| 11017 | CHECK_AND_ASSERT_MES(in_ephemeral.pub == out_pkey_test, false, "derived secret key doesn't match derived public key"); |
| 11018 | |
| 11019 | crypto::generate_key_image(in_ephemeral.pub, in_ephemeral.sec, calculated_key_image); |
| 11020 | |
| 11021 | index_keyimage_map.emplace(out_index, calculated_key_image); |
| 11022 | m_key_image_cache.emplace(tx_public_key, index_keyimage_map); |
| 11023 | return key_image == calculated_key_image; |
| 11024 | } |
| 11025 | |
| 11026 | // Another implementation of transaction creation that is hopefully better |
| 11027 | // While there is anything left to pay, it goes through random outputs and tries |
| 11028 | // to fill the next destination/amount. If it fully fills it, it will use the |
| 11029 | // remainder to try to fill the next one as well. |
| 11030 | // The tx size if roughly estimated as a linear function of only inputs, and a |
| 11031 | // new tx will be created when that size goes above a given fraction of the |
| 11032 | // max tx size. At that point, more outputs may be added if the fee cannot be |
| 11033 | // satisfied. |
| 11034 | // If the next output in the next tx would go to the same destination (ie, we |
| 11035 | // cut off at a tx boundary in the middle of paying a given destination), the |
| 11036 | // fee will be carved out of the current input if possible, to avoid having to |
| 11037 | // add another output just for the fee and getting change. |
| 11038 | // This system allows for sending (almost) the entire balance, since it does |
| 11039 | // not generate spurious change in all txes, thus decreasing the instantaneous |
| 11040 | // usable balance. |
| 11041 | std::vector<wallet2::pending_tx> wallet2::create_transactions_2(std::vector<cryptonote::tx_destination_entry> dsts, const size_t fake_outs_count, uint32_t priority, const std::vector<uint8_t>& extra, uint32_t subaddr_account, std::set<uint32_t> subaddr_indices, const unique_index_container& subtract_fee_from_outputs) |
| 11042 | { |
| 11043 | //ensure device is let in NONE mode in any case |
| 11044 | hw::device &hwdev = m_account.get_device(); |
| 11045 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 11046 | hw::reset_mode rst(hwdev); |
| 11047 | |
| 11048 | auto original_dsts = dsts; |
| 11049 | |
| 11050 | if(m_light_wallet) { |
| 11051 | // Populate m_transfers |
| 11052 | light_wallet_get_unspent_outs(); |
| 11053 | } |
| 11054 | std::vector<std::pair<uint32_t, std::vector<size_t>>> unused_transfers_indices_per_subaddr; |
| 11055 | std::vector<std::pair<uint32_t, std::vector<size_t>>> unused_dust_indices_per_subaddr; |
| 11056 | uint64_t needed_money, total_needed_money; // 'needed_money' is the sum of the destination amounts, while 'total_needed_money' includes 'needed_money' plus the fee if not 'subtract_fee_from_outputs' |
| 11057 | uint64_t accumulated_fee, accumulated_change; |
| 11058 | struct TX { |
| 11059 | std::vector<size_t> selected_transfers; |
| 11060 | std::vector<cryptonote::tx_destination_entry> dsts; |
| 11061 | std::vector<bool> dsts_are_fee_subtractable; |
| 11062 | cryptonote::transaction tx; |
| 11063 | pending_tx ptx; |
| 11064 | size_t weight; |
| 11065 | uint64_t needed_fee; |
| 11066 | std::vector<std::vector<tools::wallet2::get_outs_entry>> outs; |
| 11067 | |
| 11068 | TX() : weight(0), needed_fee(0) {} |
| 11069 | |
| 11070 | /* Add an output to the transaction. |
| 11071 | * If merge_destinations is true, when adding a destination with an existing address, to increment the amount of the existing tx output instead of creating a new one |
| 11072 | * If subtracting_fee is true, when we generate a final list of destinations for transfer_selected[_rct], this destination will be used to fund the tx fee |
| 11073 | * Returns True if the output was added, False if there are no more available output slots. |
| 11074 | */ |
| 11075 | bool add(const cryptonote::tx_destination_entry &de, uint64_t amount, unsigned int original_output_index, bool merge_destinations, size_t max_dsts, bool subtracting_fee) { |
| 11076 | if (merge_destinations) |
| 11077 | { |
| 11078 | std::vector<cryptonote::tx_destination_entry>::iterator i; |
| 11079 | i = std::find_if(dsts.begin(), dsts.end(), [&](const cryptonote::tx_destination_entry &d) { return !memcmp (&d.addr, &de.addr, sizeof(de.addr)); }); |
| 11080 | if (i == dsts.end()) |
| 11081 | { |
| 11082 | if (dsts.size() >= max_dsts) |
| 11083 | return false; |
| 11084 | dsts.push_back(de); |
| 11085 | dsts_are_fee_subtractable.push_back(subtracting_fee); |
| 11086 | i = dsts.end() - 1; |
| 11087 | i->amount = 0; |
| 11088 | } |
| 11089 | i->amount += amount; |
| 11090 | } |
| 11091 | else |
| 11092 | { |
| 11093 | THROW_WALLET_EXCEPTION_IF(original_output_index > dsts.size(), error::wallet_internal_error, |
| 11094 | std::string("original_output_index too large: ") + std::to_string(original_output_index) + " > " + std::to_string(dsts.size())); |
| 11095 | if (original_output_index == dsts.size()) |
| 11096 | { |
| 11097 | if (dsts.size() >= max_dsts) |
| 11098 | return false; |
| 11099 | dsts.push_back(de); |
| 11100 | dsts.back().amount = 0; |
| 11101 | dsts_are_fee_subtractable.push_back(subtracting_fee); |
| 11102 | } |
| 11103 | THROW_WALLET_EXCEPTION_IF(memcmp(&dsts[original_output_index].addr, &de.addr, sizeof(de.addr)), error::wallet_internal_error, "Mismatched destination address"); |
| 11104 | dsts[original_output_index].amount += amount; |
| 11105 | } |
| 11106 | return true; |
| 11107 | } |
| 11108 | |
| 11109 | // Returns destinations adjusted for given fee if subtract_fee_from_outputs is enabled |
| 11110 | std::vector<cryptonote::tx_destination_entry> get_adjusted_dsts(uint64_t needed_fee) const |
| 11111 | { |
| 11112 | uint64_t dest_total = 0; |
| 11113 | uint64_t subtractable_dest_total = 0; |
| 11114 | std::vector<size_t> subtractable_indices; |
| 11115 | subtractable_indices.reserve(dsts.size()); |
| 11116 | for (size_t i = 0; i < dsts.size(); ++i) |
| 11117 | { |
| 11118 | dest_total += dsts[i].amount; |
| 11119 | if (dsts_are_fee_subtractable[i]) |
| 11120 | { |
| 11121 | subtractable_dest_total += dsts[i].amount; |
| 11122 | subtractable_indices.push_back(i); |
| 11123 | } |
| 11124 | } |
| 11125 | |
| 11126 | if (subtractable_indices.empty()) // if subtract_fee_from_outputs is not enabled for this tx |
| 11127 | return dsts; |
| 11128 | |
| 11129 | THROW_WALLET_EXCEPTION_IF(subtractable_dest_total < needed_fee, error::tx_not_possible, |
| 11130 | subtractable_dest_total, dest_total, needed_fee); |
| 11131 | |
| 11132 | std::vector<cryptonote::tx_destination_entry> res = dsts; |
| 11133 | |
| 11134 | // subtract fees from destinations equally, rounded down, until dust is left where we subtract 1 |
| 11135 | uint64_t subtractable_remaining = needed_fee; |
| 11136 | auto si_it = subtractable_indices.cbegin(); |
| 11137 | uint64_t amount_to_subtract = 0; |
| 11138 | while (subtractable_remaining) |
| 11139 | { |
| 11140 | // Set the amount to subtract iterating at the beginning of the list so equal amounts are |
| 11141 | // subtracted throughout the list of destinations. We use max(x, 1) so that we we still step |
| 11142 | // forwards even when the amount remaining is less than the number of subtractable indices |
| 11143 | if (si_it == subtractable_indices.cbegin()) |
| 11144 | amount_to_subtract = std::max<uint64_t>(subtractable_remaining / subtractable_indices.size(), 1); |
| 11145 | |
| 11146 | cryptonote::tx_destination_entry& d = res[*si_it]; |
| 11147 | THROW_WALLET_EXCEPTION_IF(d.amount <= amount_to_subtract, error::zero_amount); |
| 11148 | |
| 11149 | subtractable_remaining -= amount_to_subtract; |
| 11150 | d.amount -= amount_to_subtract; |
| 11151 | ++si_it; |
| 11152 | |
| 11153 | // Wrap around to first subtractable index once we hit the end of the list |
| 11154 | if (si_it == subtractable_indices.cend()) |
| 11155 | si_it = subtractable_indices.cbegin(); |
| 11156 | } |
| 11157 | |
| 11158 | return res; |
| 11159 | } |
| 11160 | }; |
| 11161 | |
| 11162 | std::vector<TX> txes; |
| 11163 | bool adding_fee; // true if new outputs go towards fee, rather than destinations |
| 11164 | uint64_t needed_fee, available_for_fee = 0; |
| 11165 | uint64_t upper_transaction_weight_limit = get_upper_transaction_weight_limit(); |
| 11166 | const bool use_per_byte_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0); |
| 11167 | const bool use_rct = use_fork_rules(4, 0); |
| 11168 | const bool bulletproof = use_fork_rules(get_bulletproof_fork(), 0); |
| 11169 | const bool bulletproof_plus = use_fork_rules(get_bulletproof_plus_fork(), 0); |
| 11170 | const bool clsag = use_fork_rules(get_clsag_fork(), 0); |
| 11171 | const rct::RCTConfig rct_config { |
| 11172 | rct::RangeProofPaddedBulletproof, |
| 11173 | bulletproof_plus ? 4 : 3 |
| 11174 | }; |
| 11175 | const bool use_view_tags = use_fork_rules(get_view_tag_fork(), 0); |
| 11176 | std::unordered_set<crypto::public_key> valid_public_keys_cache; |
| 11177 | |
| 11178 | const uint64_t base_fee = get_base_fee(priority); |
| 11179 | const uint64_t fee_quantization_mask = get_fee_quantization_mask(); |
| 11180 | |
| 11181 | // throw if attempting a transaction with no destinations |
| 11182 | THROW_WALLET_EXCEPTION_IF(dsts.empty(), error::zero_destination); |
| 11183 | |
| 11184 | // throw if subtract_fee_from_outputs has a bad index |
| 11185 | THROW_WALLET_EXCEPTION_IF(subtract_fee_from_outputs.size() && *subtract_fee_from_outputs.crbegin() >= dsts.size(), |
| 11186 | error::subtract_fee_from_bad_index, *subtract_fee_from_outputs.crbegin()); |
| 11187 | |
| 11188 | // throw if subtract_fee_from_outputs is enabled and we have too many outputs to fit into one tx |
| 11189 | THROW_WALLET_EXCEPTION_IF(subtract_fee_from_outputs.size() && dsts.size() > BULLETPROOF_MAX_OUTPUTS - 1, |
| 11190 | error::wallet_internal_error, "subtractfeefrom transfers cannot be split over multiple transactions yet"); |
| 11191 | |
| 11192 | // calculate total amount being sent to all destinations |
| 11193 | // throw if total amount overflows uint64_t |
| 11194 | needed_money = 0; |
| 11195 | for(auto& dt: dsts) |
| 11196 | { |
| 11197 | THROW_WALLET_EXCEPTION_IF(0 == dt.amount, error::zero_amount); |
| 11198 | needed_money += dt.amount; |
| 11199 | LOG_PRINT_L2("transfer: adding " << print_money(dt.amount) << ", for a total of " << print_money (needed_money)); |
| 11200 | THROW_WALLET_EXCEPTION_IF(needed_money < dt.amount, error::tx_sum_overflow, dsts, 0, m_nettype); |
| 11201 | } |
| 11202 | |
| 11203 | // throw if attempting a transaction with no money |
| 11204 | THROW_WALLET_EXCEPTION_IF(needed_money == 0, error::zero_amount); |
| 11205 | |
| 11206 | std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> unlocked_balance_per_subaddr = unlocked_balance_per_subaddress(subaddr_account, false); |
| 11207 | std::map<uint32_t, uint64_t> balance_per_subaddr = balance_per_subaddress(subaddr_account, false); |
| 11208 | |
| 11209 | if (subaddr_indices.empty()) // "index=<N1>[,<N2>,...]" wasn't specified -> use all the indices with non-zero unlocked balance |
| 11210 | { |
| 11211 | for (const auto& i : balance_per_subaddr) |
| 11212 | subaddr_indices.insert(i.first); |
| 11213 | } |
| 11214 | |
| 11215 | // early out if we know we can't make it anyway |
| 11216 | // we could also check for being within FEE_PER_KB, but if the fee calculation |
| 11217 | // ever changes, this might be missed, so let this go through |
| 11218 | const uint64_t min_fee = (base_fee * estimate_tx_size(use_rct, 1, fake_outs_count, 2, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags)); |
| 11219 | total_needed_money = needed_money + (subtract_fee_from_outputs.size() ? 0 : min_fee); |
| 11220 | uint64_t balance_subtotal = 0; |
| 11221 | uint64_t unlocked_balance_subtotal = 0; |
| 11222 | for (uint32_t index_minor : subaddr_indices) |
| 11223 | { |
| 11224 | balance_subtotal += balance_per_subaddr[index_minor]; |
| 11225 | unlocked_balance_subtotal += unlocked_balance_per_subaddr[index_minor].first; |
| 11226 | } |
| 11227 | THROW_WALLET_EXCEPTION_IF(total_needed_money > balance_subtotal || min_fee > balance_subtotal, error::not_enough_money, |
| 11228 | balance_subtotal, needed_money, 0); |
| 11229 | // first check overall balance is enough, then unlocked one, so we throw distinct exceptions |
| 11230 | THROW_WALLET_EXCEPTION_IF(total_needed_money > unlocked_balance_subtotal || min_fee > unlocked_balance_subtotal, error::not_enough_unlocked_money, |
| 11231 | unlocked_balance_subtotal, needed_money, 0); |
| 11232 | |
| 11233 | for (uint32_t i : subaddr_indices) |
| 11234 | LOG_PRINT_L2("Candidate subaddress index for spending: " << i); |
| 11235 | |
| 11236 | // determine threshold for fractional amount |
| 11237 | const size_t tx_weight_one_ring = estimate_tx_weight(use_rct, 1, fake_outs_count, 2, 0, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11238 | const size_t tx_weight_two_rings = estimate_tx_weight(use_rct, 2, fake_outs_count, 2, 0, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11239 | THROW_WALLET_EXCEPTION_IF(tx_weight_one_ring > tx_weight_two_rings, error::wallet_internal_error, "Estimated tx weight with 1 input is larger than with 2 inputs!"); |
| 11240 | const size_t tx_weight_per_ring = tx_weight_two_rings - tx_weight_one_ring; |
| 11241 | const uint64_t fractional_threshold = (base_fee * tx_weight_per_ring) / (use_per_byte_fee ? 1 : 1024); |
| 11242 | |
| 11243 | // gather all dust and non-dust outputs belonging to specified subaddresses |
| 11244 | size_t num_nondust_outputs = 0; |
| 11245 | size_t num_dust_outputs = 0; |
| 11246 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 11247 | { |
| 11248 | const transfer_details& td = m_transfers[i]; |
| 11249 | if (m_ignore_fractional_outputs && td.amount() < fractional_threshold) |
| 11250 | { |
| 11251 | MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is below fractional threshold " << print_money(fractional_threshold)); |
| 11252 | continue; |
| 11253 | } |
| 11254 | if (!is_spent(td, false) && !td.m_frozen && !td.m_key_image_partial && (use_rct ? true : !td.is_rct()) && is_transfer_unlocked(td) && td.m_subaddr_index.major == subaddr_account && subaddr_indices.count(td.m_subaddr_index.minor) == 1) |
| 11255 | { |
| 11256 | if (td.amount() > m_ignore_outputs_above || td.amount() < m_ignore_outputs_below) |
| 11257 | { |
| 11258 | MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is outside prescribed range [" << print_money(m_ignore_outputs_below) << ", " << print_money(m_ignore_outputs_above) << "]"); |
| 11259 | continue; |
| 11260 | } |
| 11261 | const uint32_t index_minor = td.m_subaddr_index.minor; |
| 11262 | auto find_predicate = [&index_minor](const std::pair<uint32_t, std::vector<size_t>>& x) { return x.first == index_minor; }; |
| 11263 | if ((td.is_rct()) || is_valid_decomposed_amount(td.amount())) |
| 11264 | { |
| 11265 | auto found = std::find_if(unused_transfers_indices_per_subaddr.begin(), unused_transfers_indices_per_subaddr.end(), find_predicate); |
| 11266 | if (found == unused_transfers_indices_per_subaddr.end()) |
| 11267 | { |
| 11268 | unused_transfers_indices_per_subaddr.push_back({index_minor, {i}}); |
| 11269 | } |
| 11270 | else |
| 11271 | { |
| 11272 | found->second.push_back(i); |
| 11273 | } |
| 11274 | ++num_nondust_outputs; |
| 11275 | } |
| 11276 | else |
| 11277 | { |
| 11278 | auto found = std::find_if(unused_dust_indices_per_subaddr.begin(), unused_dust_indices_per_subaddr.end(), find_predicate); |
| 11279 | if (found == unused_dust_indices_per_subaddr.end()) |
| 11280 | { |
| 11281 | unused_dust_indices_per_subaddr.push_back({index_minor, {i}}); |
| 11282 | } |
| 11283 | else |
| 11284 | { |
| 11285 | found->second.push_back(i); |
| 11286 | } |
| 11287 | ++num_dust_outputs; |
| 11288 | } |
| 11289 | } |
| 11290 | } |
| 11291 | |
| 11292 | // sort output indices |
| 11293 | { |
| 11294 | auto sort_predicate = [&unlocked_balance_per_subaddr] (const std::pair<uint32_t, std::vector<size_t>>& x, const std::pair<uint32_t, std::vector<size_t>>& y) |
| 11295 | { |
| 11296 | return unlocked_balance_per_subaddr[x.first].first > unlocked_balance_per_subaddr[y.first].first; |
| 11297 | }; |
| 11298 | std::sort(unused_transfers_indices_per_subaddr.begin(), unused_transfers_indices_per_subaddr.end(), sort_predicate); |
| 11299 | std::sort(unused_dust_indices_per_subaddr.begin(), unused_dust_indices_per_subaddr.end(), sort_predicate); |
| 11300 | } |
| 11301 | |
| 11302 | LOG_PRINT_L2("Starting with " << num_nondust_outputs << " non-dust outputs and " << num_dust_outputs << " dust outputs"); |
| 11303 | |
| 11304 | if (unused_dust_indices_per_subaddr.empty() && unused_transfers_indices_per_subaddr.empty()) |
| 11305 | return std::vector<wallet2::pending_tx>(); |
| 11306 | |
| 11307 | // if empty, put dummy entry so that the front can be referenced later in the loop |
| 11308 | if (unused_dust_indices_per_subaddr.empty()) |
| 11309 | unused_dust_indices_per_subaddr.push_back({}); |
| 11310 | if (unused_transfers_indices_per_subaddr.empty()) |
| 11311 | unused_transfers_indices_per_subaddr.push_back({}); |
| 11312 | |
| 11313 | // start with an empty tx |
| 11314 | txes.push_back(TX()); |
| 11315 | accumulated_fee = 0; |
| 11316 | accumulated_change = 0; |
| 11317 | adding_fee = false; |
| 11318 | needed_fee = 0; |
| 11319 | std::vector<std::vector<tools::wallet2::get_outs_entry>> outs; |
| 11320 | |
| 11321 | // for rct, since we don't see the amounts, we will try to make all transactions |
| 11322 | // look the same, with 1 or 2 inputs, and 2 outputs. One input is preferable, as |
| 11323 | // this prevents linking to another by provenance analysis, but two is ok if we |
| 11324 | // try to pick outputs not from the same block. We will get two outputs, one for |
| 11325 | // the destination, and one for change. |
| 11326 | LOG_PRINT_L2("checking preferred"); |
| 11327 | std::vector<size_t> preferred_inputs; |
| 11328 | if (use_rct) |
| 11329 | { |
| 11330 | // this is used to build a tx that's 1 or 2 inputs, and 2 outputs, which |
| 11331 | // will get us a known fee. |
| 11332 | uint64_t estimated_fee = estimate_fee(use_per_byte_fee, use_rct, 2, fake_outs_count, 2, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags, base_fee, fee_quantization_mask); |
| 11333 | total_needed_money = needed_money + (subtract_fee_from_outputs.size() ? 0 : estimated_fee); |
| 11334 | preferred_inputs = pick_preferred_rct_inputs(total_needed_money, subaddr_account, subaddr_indices); |
| 11335 | if (!preferred_inputs.empty()) |
| 11336 | { |
| 11337 | string s; |
| 11338 | for (auto i: preferred_inputs) s += boost::lexical_cast<std::string>(i) + " (" + print_money(m_transfers[i].amount()) + ") "; |
| 11339 | LOG_PRINT_L1("Found preferred rct inputs for rct tx: " << s); |
| 11340 | |
| 11341 | // bring the list of available outputs stored by the same subaddress index to the front of the list |
| 11342 | uint32_t index_minor = m_transfers[preferred_inputs[0]].m_subaddr_index.minor; |
| 11343 | for (size_t i = 1; i < unused_transfers_indices_per_subaddr.size(); ++i) |
| 11344 | { |
| 11345 | if (unused_transfers_indices_per_subaddr[i].first == index_minor) |
| 11346 | { |
| 11347 | std::swap(unused_transfers_indices_per_subaddr[0], unused_transfers_indices_per_subaddr[i]); |
| 11348 | break; |
| 11349 | } |
| 11350 | } |
| 11351 | for (size_t i = 1; i < unused_dust_indices_per_subaddr.size(); ++i) |
| 11352 | { |
| 11353 | if (unused_dust_indices_per_subaddr[i].first == index_minor) |
| 11354 | { |
| 11355 | std::swap(unused_dust_indices_per_subaddr[0], unused_dust_indices_per_subaddr[i]); |
| 11356 | break; |
| 11357 | } |
| 11358 | } |
| 11359 | } |
| 11360 | } |
| 11361 | LOG_PRINT_L2("done checking preferred"); |
| 11362 | |
| 11363 | // while: |
| 11364 | // - we have something to send |
| 11365 | // - or we need to gather more fee |
| 11366 | // - or we have just one input in that tx, which is rct (to try and make all/most rct txes 2/2) |
| 11367 | unsigned int original_output_index = 0, destination_index = 0; |
| 11368 | std::vector<size_t>* unused_transfers_indices = &unused_transfers_indices_per_subaddr[0].second; |
| 11369 | std::vector<size_t>* unused_dust_indices = &unused_dust_indices_per_subaddr[0].second; |
| 11370 | |
| 11371 | hwdev.set_mode(hw::device::TRANSACTION_CREATE_FAKE); |
| 11372 | while ((!dsts.empty() && dsts[0].amount > 0) || adding_fee || !preferred_inputs.empty() || should_pick_a_second_output(use_rct, txes.back().selected_transfers.size(), *unused_transfers_indices, *unused_dust_indices)) { |
| 11373 | TX &tx = txes.back(); |
| 11374 | |
| 11375 | LOG_PRINT_L2("Start of loop with " << unused_transfers_indices->size() << " " << unused_dust_indices->size() << ", tx.dsts.size() " << tx.dsts.size()); |
| 11376 | LOG_PRINT_L2("unused_transfers_indices: " << strjoin(*unused_transfers_indices, " ")); |
| 11377 | LOG_PRINT_L2("unused_dust_indices: " << strjoin(*unused_dust_indices, " ")); |
| 11378 | LOG_PRINT_L2("dsts size " << dsts.size() << ", first " << (dsts.empty() ? "-" : cryptonote::print_money(dsts[0].amount))); |
| 11379 | LOG_PRINT_L2("adding_fee " << adding_fee << ", use_rct " << use_rct); |
| 11380 | |
| 11381 | // if we need to spend money and don't have any left, we fail |
| 11382 | if (unused_dust_indices->empty() && unused_transfers_indices->empty()) { |
| 11383 | LOG_PRINT_L2("No more outputs to choose from"); |
| 11384 | THROW_WALLET_EXCEPTION_IF(1, error::tx_not_possible, unlocked_balance(subaddr_account, false), needed_money, accumulated_fee + needed_fee); |
| 11385 | } |
| 11386 | |
| 11387 | // get a random unspent output and use it to pay part (or all) of the current destination (and maybe next one, etc) |
| 11388 | // This could be more clever, but maybe at the cost of making probabilistic inferences easier |
| 11389 | size_t idx; |
| 11390 | if (!preferred_inputs.empty()) { |
| 11391 | idx = pop_back(preferred_inputs); |
| 11392 | pop_if_present(*unused_transfers_indices, idx); |
| 11393 | pop_if_present(*unused_dust_indices, idx); |
| 11394 | } else if ((dsts.empty() || dsts[0].amount == 0) && !adding_fee) { |
| 11395 | // the "make rct txes 2/2" case - we pick a small value output to "clean up" the wallet too |
| 11396 | std::vector<size_t> indices = get_only_rct(*unused_dust_indices, *unused_transfers_indices); |
| 11397 | idx = pop_best_value(indices, tx.selected_transfers, true); |
| 11398 | |
| 11399 | // we might not want to add it if it's a large output and we don't have many left |
| 11400 | uint64_t min_output_value = m_min_output_value; |
| 11401 | uint32_t min_output_count = m_min_output_count; |
| 11402 | if (min_output_value == 0 && min_output_count == 0) |
| 11403 | { |
| 11404 | min_output_value = DEFAULT_MIN_OUTPUT_VALUE; |
| 11405 | min_output_count = DEFAULT_MIN_OUTPUT_COUNT; |
| 11406 | } |
| 11407 | if (m_transfers[idx].amount() >= min_output_value) { |
| 11408 | if (get_count_above(m_transfers, *unused_transfers_indices, min_output_value) < min_output_count) { |
| 11409 | LOG_PRINT_L2("Second output was not strictly needed, and we're running out of outputs above " << print_money(min_output_value) << ", not adding"); |
| 11410 | break; |
| 11411 | } |
| 11412 | } |
| 11413 | |
| 11414 | // since we're trying to add a second output which is not strictly needed, |
| 11415 | // we only add it if it's unrelated enough to the first one |
| 11416 | float relatedness = get_output_relatedness(m_transfers[idx], m_transfers[tx.selected_transfers.front()]); |
| 11417 | if (relatedness > SECOND_OUTPUT_RELATEDNESS_THRESHOLD) |
| 11418 | { |
| 11419 | LOG_PRINT_L2("Second output was not strictly needed, and relatedness " << relatedness << ", not adding"); |
| 11420 | break; |
| 11421 | } |
| 11422 | pop_if_present(*unused_transfers_indices, idx); |
| 11423 | pop_if_present(*unused_dust_indices, idx); |
| 11424 | } else |
| 11425 | idx = pop_best_value(unused_transfers_indices->empty() ? *unused_dust_indices : *unused_transfers_indices, tx.selected_transfers); |
| 11426 | |
| 11427 | const transfer_details &td = m_transfers[idx]; |
| 11428 | LOG_PRINT_L2("Picking output " << idx << ", amount " << print_money(td.amount()) << ", ki " << td.m_key_image); |
| 11429 | |
| 11430 | // add this output to the list to spend |
| 11431 | tx.selected_transfers.push_back(idx); |
| 11432 | uint64_t available_amount = td.amount(); |
| 11433 | |
| 11434 | // clear any fake outs we'd already gathered, since we'll need a new set |
| 11435 | outs.clear(); |
| 11436 | |
| 11437 | bool out_slots_exhausted = false; |
| 11438 | if (adding_fee) |
| 11439 | { |
| 11440 | LOG_PRINT_L2("We need more fee, adding it to fee"); |
| 11441 | available_for_fee += available_amount; |
| 11442 | } |
| 11443 | else |
| 11444 | { |
| 11445 | while (!dsts.empty() && dsts[0].amount <= available_amount && estimate_tx_weight(use_rct, tx.selected_transfers.size(), fake_outs_count, tx.dsts.size()+1, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags) < TX_WEIGHT_TARGET(upper_transaction_weight_limit)) |
| 11446 | { |
| 11447 | // we can fully pay that destination |
| 11448 | LOG_PRINT_L2("We can fully pay " << get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr) << |
| 11449 | " for " << print_money(dsts[0].amount)); |
| 11450 | const bool subtract_fee_from_this_dest = subtract_fee_from_outputs.count(destination_index); |
| 11451 | if (!tx.add(dsts[0], dsts[0].amount, original_output_index, m_merge_destinations, BULLETPROOF_MAX_OUTPUTS-1, subtract_fee_from_this_dest)) |
| 11452 | { |
| 11453 | LOG_PRINT_L2("Didn't pay: ran out of output slots"); |
| 11454 | out_slots_exhausted = true; |
| 11455 | break; |
| 11456 | } |
| 11457 | available_amount -= dsts[0].amount; |
| 11458 | dsts[0].amount = 0; |
| 11459 | pop_index(dsts, 0); |
| 11460 | ++original_output_index; |
| 11461 | ++destination_index; |
| 11462 | } |
| 11463 | |
| 11464 | if (!out_slots_exhausted && available_amount > 0 && !dsts.empty() && |
| 11465 | estimate_tx_weight(use_rct, tx.selected_transfers.size(), fake_outs_count, tx.dsts.size()+1, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags) < TX_WEIGHT_TARGET(upper_transaction_weight_limit)) { |
| 11466 | // we can partially fill that destination |
| 11467 | LOG_PRINT_L2("We can partially pay " << get_account_address_as_str(m_nettype, dsts[0].is_subaddress, dsts[0].addr) << |
| 11468 | " for " << print_money(available_amount) << "/" << print_money(dsts[0].amount)); |
| 11469 | const bool subtract_fee_from_this_dest = subtract_fee_from_outputs.count(destination_index); |
| 11470 | if (tx.add(dsts[0], available_amount, original_output_index, m_merge_destinations, BULLETPROOF_MAX_OUTPUTS-1, subtract_fee_from_this_dest)) |
| 11471 | { |
| 11472 | dsts[0].amount -= available_amount; |
| 11473 | available_amount = 0; |
| 11474 | } |
| 11475 | else |
| 11476 | { |
| 11477 | LOG_PRINT_L2("Didn't pay: ran out of output slots"); |
| 11478 | out_slots_exhausted = true; |
| 11479 | } |
| 11480 | } |
| 11481 | } |
| 11482 | |
| 11483 | // here, check if we need to sent tx and start a new one |
| 11484 | LOG_PRINT_L2("Considering whether to create a tx now, " << tx.selected_transfers.size() << " inputs, tx limit " |
| 11485 | << upper_transaction_weight_limit); |
| 11486 | bool try_tx = false; |
| 11487 | |
| 11488 | // If the new transaction is full, create it and start a new one |
| 11489 | if (out_slots_exhausted) |
| 11490 | { |
| 11491 | LOG_PRINT_L2("Transaction is full, will create it and start a new tx"); |
| 11492 | try_tx = true; |
| 11493 | } |
| 11494 | // if we have preferred picks, but haven't yet used all of them, continue |
| 11495 | else if (preferred_inputs.empty()) |
| 11496 | { |
| 11497 | if (adding_fee) |
| 11498 | { |
| 11499 | /* might not actually be enough if adding this output bumps size to next kB, but we need to try */ |
| 11500 | try_tx = available_for_fee >= needed_fee; |
| 11501 | } |
| 11502 | else |
| 11503 | { |
| 11504 | const size_t estimated_rct_tx_weight = estimate_tx_weight(use_rct, tx.selected_transfers.size(), fake_outs_count, tx.dsts.size()+1, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11505 | try_tx = dsts.empty() || (estimated_rct_tx_weight >= TX_WEIGHT_TARGET(upper_transaction_weight_limit)); |
| 11506 | THROW_WALLET_EXCEPTION_IF(try_tx && tx.dsts.empty(), error::tx_too_big, estimated_rct_tx_weight, upper_transaction_weight_limit); |
| 11507 | } |
| 11508 | } |
| 11509 | |
| 11510 | if (try_tx) { |
| 11511 | cryptonote::transaction test_tx; |
| 11512 | pending_tx test_ptx; |
| 11513 | |
| 11514 | const size_t num_outputs = get_num_outputs(tx.dsts, m_transfers, tx.selected_transfers); |
| 11515 | needed_fee = estimate_fee(use_per_byte_fee, use_rct ,tx.selected_transfers.size(), fake_outs_count, num_outputs, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags, base_fee, fee_quantization_mask); |
| 11516 | |
| 11517 | auto try_carving_from_partial_payment = [&](uint64_t needed_fee, uint64_t available_for_fee) |
| 11518 | { |
| 11519 | // The check against original_output_index is to ensure the last entry in tx.dsts is really |
| 11520 | // a partial payment. Otherwise multiple requested outputs to the same address could |
| 11521 | // fool this logic into thinking there is a partial payment. |
| 11522 | if (needed_fee > available_for_fee && !dsts.empty() && dsts[0].amount > 0 && tx.dsts.size() > original_output_index) |
| 11523 | { |
| 11524 | // we don't have enough for the fee, but we've only partially paid the current address, |
| 11525 | // so we can take the fee from the paid amount, since we'll have to make another tx anyway |
| 11526 | LOG_PRINT_L2("Attempting to carve tx fee " << print_money(needed_fee) << " from partial payment (first pass)"); |
| 11527 | std::vector<cryptonote::tx_destination_entry>::iterator i; |
| 11528 | i = std::find_if(tx.dsts.begin(), tx.dsts.end(), |
| 11529 | [&](const cryptonote::tx_destination_entry &d) { return !memcmp (&d.addr, &dsts[0].addr, sizeof(dsts[0].addr)); }); |
| 11530 | THROW_WALLET_EXCEPTION_IF(i == tx.dsts.end(), error::wallet_internal_error, "paid address not found in outputs"); |
| 11531 | if (i->amount > needed_fee) |
| 11532 | { |
| 11533 | uint64_t new_paid_amount = i->amount /*+ test_ptx.fee*/ - needed_fee; |
| 11534 | LOG_PRINT_L2("Adjusting amount paid to " << get_account_address_as_str(m_nettype, i->is_subaddress, i->addr) << " from " << |
| 11535 | print_money(i->amount) << " to " << print_money(new_paid_amount) << " to accommodate " << |
| 11536 | print_money(needed_fee) << " fee"); |
| 11537 | dsts[0].amount += i->amount - new_paid_amount; |
| 11538 | i->amount = new_paid_amount; |
| 11539 | test_ptx.fee = needed_fee; |
| 11540 | available_for_fee = needed_fee; |
| 11541 | } |
| 11542 | } |
| 11543 | return available_for_fee; |
| 11544 | }; |
| 11545 | |
| 11546 | // Try to carve the estimated fee from the partial payment (if there is one) |
| 11547 | available_for_fee = try_carving_from_partial_payment(needed_fee, available_for_fee); |
| 11548 | |
| 11549 | uint64_t inputs = 0, outputs = 0; |
| 11550 | for (size_t idx: tx.selected_transfers) inputs += m_transfers[idx].amount(); |
| 11551 | for (const auto &o: tx.dsts) outputs += o.amount; |
| 11552 | if (subtract_fee_from_outputs.empty()) // if normal tx that doesn't subtract fees |
| 11553 | { |
| 11554 | outputs += needed_fee; |
| 11555 | } |
| 11556 | |
| 11557 | if (inputs < outputs) |
| 11558 | { |
| 11559 | LOG_PRINT_L2("We don't have enough for the basic fee, switching to adding_fee"); |
| 11560 | adding_fee = true; |
| 11561 | goto skip_tx; |
| 11562 | } |
| 11563 | |
| 11564 | LOG_PRINT_L2("Trying to create a tx now, with " << tx.dsts.size() << " outputs and " << |
| 11565 | tx.selected_transfers.size() << " inputs"); |
| 11566 | auto tx_dsts = tx.get_adjusted_dsts(needed_fee); |
| 11567 | if (use_rct) |
| 11568 | transfer_selected_rct(tx_dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 11569 | test_tx, test_ptx, rct_config, use_view_tags); |
| 11570 | else |
| 11571 | transfer_selected(tx_dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 11572 | detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx, use_view_tags); |
| 11573 | auto txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 11574 | needed_fee = calculate_fee(use_per_byte_fee, test_ptx.tx, txBlob.size(), base_fee, fee_quantization_mask); |
| 11575 | |
| 11576 | // Depending on the mode, we take extra fees from either our change output or the destination outputs for which subtract_fee_from_outputs is true |
| 11577 | uint64_t output_available_for_fee = 0; |
| 11578 | bool tx_has_subtractable_output = false; |
| 11579 | for (size_t di = 0; di < tx.dsts.size(); ++di) |
| 11580 | { |
| 11581 | if (tx.dsts_are_fee_subtractable[di]) |
| 11582 | { |
| 11583 | output_available_for_fee += tx.dsts[di].amount; |
| 11584 | tx_has_subtractable_output = true; |
| 11585 | } |
| 11586 | } |
| 11587 | if (!tx_has_subtractable_output) |
| 11588 | { |
| 11589 | output_available_for_fee = test_ptx.change_dts.amount; |
| 11590 | } |
| 11591 | available_for_fee = test_ptx.fee + output_available_for_fee + (!test_ptx.dust_added_to_fee ? test_ptx.dust : 0); |
| 11592 | LOG_PRINT_L2("Made a " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(available_for_fee) << " available for fee (" << |
| 11593 | print_money(needed_fee) << " needed)"); |
| 11594 | |
| 11595 | // Try to carve the fee from the partial payment again after updating from estimate to actual |
| 11596 | available_for_fee = try_carving_from_partial_payment(needed_fee, available_for_fee); |
| 11597 | |
| 11598 | if (needed_fee > available_for_fee) |
| 11599 | { |
| 11600 | LOG_PRINT_L2("We could not make a tx, switching to fee accumulation"); |
| 11601 | |
| 11602 | adding_fee = true; |
| 11603 | } |
| 11604 | else |
| 11605 | { |
| 11606 | LOG_PRINT_L2("We made a tx, adjusting fee and saving it, we need " << print_money(needed_fee) << " and we have " << print_money(test_ptx.fee)); |
| 11607 | size_t fee_tries = 0; |
| 11608 | do { |
| 11609 | tx_dsts = tx.get_adjusted_dsts(needed_fee); |
| 11610 | |
| 11611 | if (use_rct) |
| 11612 | transfer_selected_rct(tx_dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 11613 | test_tx, test_ptx, rct_config, use_view_tags); |
| 11614 | else |
| 11615 | transfer_selected(tx_dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 11616 | detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx, use_view_tags); |
| 11617 | txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 11618 | needed_fee = calculate_fee(use_per_byte_fee, test_ptx.tx, txBlob.size(), base_fee, fee_quantization_mask); |
| 11619 | LOG_PRINT_L2("Made an attempt at a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << |
| 11620 | " fee and " << print_money(test_ptx.change_dts.amount) << " change"); |
| 11621 | } while (needed_fee > test_ptx.fee && ++fee_tries < 10); |
| 11622 | |
| 11623 | THROW_WALLET_EXCEPTION_IF(fee_tries == 10, error::wallet_internal_error, |
| 11624 | "Too many attempts to raise pending tx fee to level of needed fee"); |
| 11625 | |
| 11626 | LOG_PRINT_L2("Made a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << |
| 11627 | " fee and " << print_money(test_ptx.change_dts.amount) << " change"); |
| 11628 | |
| 11629 | tx.tx = test_tx; |
| 11630 | tx.ptx = test_ptx; |
| 11631 | tx.weight = get_transaction_weight(test_tx, txBlob.size()); |
| 11632 | tx.outs = outs; |
| 11633 | tx.needed_fee = test_ptx.fee; |
| 11634 | accumulated_fee += test_ptx.fee; |
| 11635 | accumulated_change += test_ptx.change_dts.amount; |
| 11636 | adding_fee = false; |
| 11637 | if (!dsts.empty()) |
| 11638 | { |
| 11639 | LOG_PRINT_L2("We have more to pay, starting another tx"); |
| 11640 | txes.push_back(TX()); |
| 11641 | original_output_index = 0; |
| 11642 | } |
| 11643 | } |
| 11644 | } |
| 11645 | |
| 11646 | skip_tx: |
| 11647 | // if unused_*_indices is empty while unused_*_indices_per_subaddr has multiple elements, and if we still have something to pay, |
| 11648 | // pop front of unused_*_indices_per_subaddr and have unused_*_indices point to the front of unused_*_indices_per_subaddr |
| 11649 | if ((!dsts.empty() && dsts[0].amount > 0) || adding_fee) |
| 11650 | { |
| 11651 | if (unused_transfers_indices->empty() && unused_transfers_indices_per_subaddr.size() > 1) |
| 11652 | { |
| 11653 | unused_transfers_indices_per_subaddr.erase(unused_transfers_indices_per_subaddr.begin()); |
| 11654 | unused_transfers_indices = &unused_transfers_indices_per_subaddr[0].second; |
| 11655 | } |
| 11656 | if (unused_dust_indices->empty() && unused_dust_indices_per_subaddr.size() > 1) |
| 11657 | { |
| 11658 | unused_dust_indices_per_subaddr.erase(unused_dust_indices_per_subaddr.begin()); |
| 11659 | unused_dust_indices = &unused_dust_indices_per_subaddr[0].second; |
| 11660 | } |
| 11661 | } |
| 11662 | } |
| 11663 | |
| 11664 | if (adding_fee) |
| 11665 | { |
| 11666 | LOG_PRINT_L1("We ran out of outputs while trying to gather final fee"); |
| 11667 | THROW_WALLET_EXCEPTION_IF(1, error::tx_not_possible, unlocked_balance(subaddr_account, false), needed_money, accumulated_fee + needed_fee); |
| 11668 | } |
| 11669 | |
| 11670 | LOG_PRINT_L1("Done creating " << txes.size() << " transactions, " << print_money(accumulated_fee) << |
| 11671 | " total fee, " << print_money(accumulated_change) << " total change"); |
| 11672 | |
| 11673 | hwdev.set_mode(hw::device::TRANSACTION_CREATE_REAL); |
| 11674 | for (std::vector<TX>::iterator i = txes.begin(); i != txes.end(); ++i) |
| 11675 | { |
| 11676 | TX &tx = *i; |
| 11677 | |
| 11678 | const auto tx_dsts = tx.get_adjusted_dsts(tx.needed_fee); |
| 11679 | |
| 11680 | cryptonote::transaction test_tx; |
| 11681 | pending_tx test_ptx; |
| 11682 | if (use_rct) { |
| 11683 | transfer_selected_rct(tx_dsts, /* NOMOD std::vector<cryptonote::tx_destination_entry> dsts,*/ |
| 11684 | tx.selected_transfers, /* const std::list<size_t> selected_transfers */ |
| 11685 | fake_outs_count, /* CONST size_t fake_outputs_count, */ |
| 11686 | tx.outs, /* MOD std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs, */ |
| 11687 | valid_public_keys_cache, |
| 11688 | tx.needed_fee, /* CONST uint64_t fee, */ |
| 11689 | extra, /* const std::vector<uint8_t>& extra, */ |
| 11690 | test_tx, /* OUT cryptonote::transaction& tx, */ |
| 11691 | test_ptx, /* OUT cryptonote::transaction& tx, */ |
| 11692 | rct_config, |
| 11693 | use_view_tags); /* const bool use_view_tags */ |
| 11694 | } else { |
| 11695 | transfer_selected(tx_dsts, |
| 11696 | tx.selected_transfers, |
| 11697 | fake_outs_count, |
| 11698 | tx.outs, |
| 11699 | valid_public_keys_cache, |
| 11700 | tx.needed_fee, |
| 11701 | extra, |
| 11702 | detail::digit_split_strategy, |
| 11703 | tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), |
| 11704 | test_tx, |
| 11705 | test_ptx, |
| 11706 | use_view_tags); |
| 11707 | } |
| 11708 | auto txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 11709 | tx.tx = test_tx; |
| 11710 | tx.ptx = test_ptx; |
| 11711 | tx.weight = get_transaction_weight(test_tx, txBlob.size()); |
| 11712 | } |
| 11713 | |
| 11714 | std::vector<wallet2::pending_tx> ptx_vector; |
| 11715 | for (std::vector<TX>::iterator i = txes.begin(); i != txes.end(); ++i) |
| 11716 | { |
| 11717 | TX &tx = *i; |
| 11718 | uint64_t tx_money = 0; |
| 11719 | for (size_t idx: tx.selected_transfers) |
| 11720 | tx_money += m_transfers[idx].amount(); |
| 11721 | LOG_PRINT_L1(" Transaction " << (1+std::distance(txes.begin(), i)) << "/" << txes.size() << |
| 11722 | " " << get_transaction_hash(tx.ptx.tx) << ": " << get_weight_string(tx.weight) << ", sending " << print_money(tx_money) << " in " << tx.selected_transfers.size() << |
| 11723 | " outputs to " << tx.dsts.size() << " destination(s), including " << |
| 11724 | print_money(tx.ptx.fee) << " fee, " << print_money(tx.ptx.change_dts.amount) << " change"); |
| 11725 | ptx_vector.push_back(tx.ptx); |
| 11726 | } |
| 11727 | |
| 11728 | THROW_WALLET_EXCEPTION_IF(!sanity_check(ptx_vector, original_dsts, subtract_fee_from_outputs), error::wallet_internal_error, "Created transaction(s) failed sanity check"); |
| 11729 | |
| 11730 | // if we made it this far, we're OK to actually send the transactions |
| 11731 | return ptx_vector; |
| 11732 | } |
| 11733 | |
| 11734 | bool wallet2::sanity_check(const std::vector<wallet2::pending_tx> &ptx_vector, const std::vector<cryptonote::tx_destination_entry>& dsts, const unique_index_container& subtract_fee_from_outputs) const |
| 11735 | { |
| 11736 | MDEBUG("sanity_check: " << ptx_vector.size() << " txes, " << dsts.size() << " destinations, subtract_fee_from_outputs " << |
| 11737 | (subtract_fee_from_outputs.size() ? "enabled" : "disabled")); |
| 11738 | |
| 11739 | THROW_WALLET_EXCEPTION_IF(ptx_vector.empty(), error::wallet_internal_error, "No transactions"); |
| 11740 | THROW_WALLET_EXCEPTION_IF(!subtract_fee_from_outputs.empty() && ptx_vector.size() != 1, |
| 11741 | error::wallet_internal_error, "feature subtractfeefrom not supported for split transactions"); |
| 11742 | |
| 11743 | // For destinations from where the fee is subtracted, the required amount has to be at least |
| 11744 | // target amount - (tx fee / num_subtractable + 1). +1 since fee might not be evenly divisble by |
| 11745 | // the number of subtractble destinations. For non-subtractable destinations, we need at least |
| 11746 | // the target amount. |
| 11747 | const size_t num_subtractable_dests = subtract_fee_from_outputs.size(); |
| 11748 | const uint64_t fee0 = ptx_vector[0].fee; |
| 11749 | const uint64_t subtractable_fee_deduction = fee0 / std::max<size_t>(num_subtractable_dests, 1) + 1; |
| 11750 | |
| 11751 | // check every party in there does receive at least the required amount |
| 11752 | std::unordered_map<account_public_address, std::pair<uint64_t, bool>> required; |
| 11753 | for (size_t i = 0; i < dsts.size(); ++i) |
| 11754 | { |
| 11755 | const cryptonote::tx_destination_entry& d = dsts[i]; |
| 11756 | const bool dest_is_subtractable = subtract_fee_from_outputs.count(i); |
| 11757 | const uint64_t fee_deduction = dest_is_subtractable ? subtractable_fee_deduction : 0; |
| 11758 | const uint64_t required_amount = d.amount - std::min(fee_deduction, d.amount); |
| 11759 | required[d.addr].first += required_amount; |
| 11760 | required[d.addr].second = d.is_subaddress; |
| 11761 | } |
| 11762 | |
| 11763 | // add change |
| 11764 | uint64_t change = 0; |
| 11765 | for (const auto &ptx: ptx_vector) |
| 11766 | { |
| 11767 | for (size_t idx: ptx.selected_transfers) |
| 11768 | change += m_transfers[idx].amount(); |
| 11769 | change -= ptx.fee; |
| 11770 | } |
| 11771 | for (const auto &r: required) |
| 11772 | change -= r.second.first; |
| 11773 | MDEBUG("Adding " << cryptonote::print_money(change) << " expected change"); |
| 11774 | |
| 11775 | // for all txes that have actual change, check change is coming back to the sending wallet |
| 11776 | for (const pending_tx &ptx: ptx_vector) |
| 11777 | { |
| 11778 | if (ptx.change_dts.amount == 0) |
| 11779 | continue; |
| 11780 | THROW_WALLET_EXCEPTION_IF(m_subaddresses.find(ptx.change_dts.addr.m_spend_public_key) == m_subaddresses.end(), |
| 11781 | error::wallet_internal_error, "Change address is not ours"); |
| 11782 | required[ptx.change_dts.addr].first += ptx.change_dts.amount; |
| 11783 | required[ptx.change_dts.addr].second = ptx.change_dts.is_subaddress; |
| 11784 | } |
| 11785 | |
| 11786 | for (const auto &r: required) |
| 11787 | { |
| 11788 | const account_public_address &address = r.first; |
| 11789 | |
| 11790 | uint64_t total_received = 0; |
| 11791 | for (const auto &ptx: ptx_vector) |
| 11792 | { |
| 11793 | uint64_t received = 0; |
| 11794 | try |
| 11795 | { |
| 11796 | std::string proof = get_tx_proof(ptx.tx, ptx.tx_key, ptx.additional_tx_keys, address, r.second.second, "automatic-sanity-check"); |
| 11797 | check_tx_proof(ptx.tx, address, r.second.second, "automatic-sanity-check", proof, received); |
| 11798 | } |
| 11799 | catch (const std::exception &e) { received = 0; } |
| 11800 | total_received += received; |
| 11801 | } |
| 11802 | |
| 11803 | std::stringstream ss; |
| 11804 | ss << "Total received by " << cryptonote::get_account_address_as_str(m_nettype, r.second.second, address) << ": " |
| 11805 | << cryptonote::print_money(total_received) << ", expected " << cryptonote::print_money(r.second.first); |
| 11806 | MDEBUG(ss.str()); |
| 11807 | THROW_WALLET_EXCEPTION_IF(total_received < r.second.first, error::wallet_internal_error, ss.str()); |
| 11808 | } |
| 11809 | |
| 11810 | return true; |
| 11811 | } |
| 11812 | |
| 11813 | std::vector<wallet2::pending_tx> wallet2::create_transactions_all(uint64_t below, const cryptonote::account_public_address &address, bool is_subaddress, const size_t outputs, const size_t fake_outs_count, uint32_t priority, const std::vector<uint8_t>& extra, uint32_t subaddr_account, std::set<uint32_t> subaddr_indices) |
| 11814 | { |
| 11815 | std::vector<size_t> unused_transfers_indices; |
| 11816 | std::vector<size_t> unused_dust_indices; |
| 11817 | const bool use_rct = use_fork_rules(4, 0); |
| 11818 | |
| 11819 | // determine threshold for fractional amount |
| 11820 | const bool use_per_byte_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0); |
| 11821 | const bool bulletproof = use_fork_rules(get_bulletproof_fork(), 0); |
| 11822 | const bool bulletproof_plus = use_fork_rules(get_bulletproof_plus_fork(), 0); |
| 11823 | const bool clsag = use_fork_rules(get_clsag_fork(), 0); |
| 11824 | const bool use_view_tags = use_fork_rules(get_view_tag_fork(), 0); |
| 11825 | const uint64_t base_fee = get_base_fee(priority); |
| 11826 | const size_t tx_weight_one_ring = estimate_tx_weight(use_rct, 1, fake_outs_count, 2, 0, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11827 | const size_t tx_weight_two_rings = estimate_tx_weight(use_rct, 2, fake_outs_count, 2, 0, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11828 | THROW_WALLET_EXCEPTION_IF(tx_weight_one_ring > tx_weight_two_rings, error::wallet_internal_error, "Estimated tx weight with 1 input is larger than with 2 inputs!"); |
| 11829 | const size_t tx_weight_per_ring = tx_weight_two_rings - tx_weight_one_ring; |
| 11830 | const uint64_t fractional_threshold = (base_fee * tx_weight_per_ring) / (use_per_byte_fee ? 1 : 1024); |
| 11831 | std::unordered_set<crypto::public_key> valid_public_keys_cache; |
| 11832 | |
| 11833 | THROW_WALLET_EXCEPTION_IF(unlocked_balance(subaddr_account, false) == 0, error::wallet_internal_error, "No unlocked balance in the specified account"); |
| 11834 | |
| 11835 | std::map<uint32_t, std::pair<std::vector<size_t>, std::vector<size_t>>> unused_transfer_dust_indices_per_subaddr; |
| 11836 | |
| 11837 | // gather all dust and non-dust outputs of specified subaddress (if any) and below specified threshold (if any) |
| 11838 | bool fund_found = false; |
| 11839 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 11840 | { |
| 11841 | const transfer_details& td = m_transfers[i]; |
| 11842 | if (m_ignore_fractional_outputs && td.amount() < fractional_threshold) |
| 11843 | { |
| 11844 | MDEBUG("Ignoring output " << i << " of amount " << print_money(td.amount()) << " which is below threshold " << print_money(fractional_threshold)); |
| 11845 | continue; |
| 11846 | } |
| 11847 | if (!is_spent(td, false) && !td.m_frozen && !td.m_key_image_partial && (use_rct ? true : !td.is_rct()) && is_transfer_unlocked(td) && td.m_subaddr_index.major == subaddr_account && (subaddr_indices.empty() || subaddr_indices.count(td.m_subaddr_index.minor) == 1)) |
| 11848 | { |
| 11849 | fund_found = true; |
| 11850 | if (below == 0 || td.amount() < below) |
| 11851 | { |
| 11852 | if ((td.is_rct()) || is_valid_decomposed_amount(td.amount())) |
| 11853 | unused_transfer_dust_indices_per_subaddr[td.m_subaddr_index.minor].first.push_back(i); |
| 11854 | else |
| 11855 | unused_transfer_dust_indices_per_subaddr[td.m_subaddr_index.minor].second.push_back(i); |
| 11856 | } |
| 11857 | } |
| 11858 | } |
| 11859 | THROW_WALLET_EXCEPTION_IF(!fund_found, error::wallet_internal_error, "No unlocked balance in the specified subaddress(es)"); |
| 11860 | THROW_WALLET_EXCEPTION_IF(unused_transfer_dust_indices_per_subaddr.empty(), error::wallet_internal_error, "The smallest amount found is not below the specified threshold"); |
| 11861 | |
| 11862 | if (subaddr_indices.empty()) |
| 11863 | { |
| 11864 | // in case subaddress index wasn't specified, choose non-empty subaddress randomly (with index=0 being chosen last) |
| 11865 | if (unused_transfer_dust_indices_per_subaddr.count(0) == 1 && unused_transfer_dust_indices_per_subaddr.size() > 1) |
| 11866 | unused_transfer_dust_indices_per_subaddr.erase(0); |
| 11867 | auto i = unused_transfer_dust_indices_per_subaddr.begin(); |
| 11868 | std::advance(i, crypto::rand_idx(unused_transfer_dust_indices_per_subaddr.size())); |
| 11869 | unused_transfers_indices = i->second.first; |
| 11870 | unused_dust_indices = i->second.second; |
| 11871 | LOG_PRINT_L2("Spending from subaddress index " << i->first); |
| 11872 | } |
| 11873 | else |
| 11874 | { |
| 11875 | for (const auto& p : unused_transfer_dust_indices_per_subaddr) |
| 11876 | { |
| 11877 | unused_transfers_indices.insert(unused_transfers_indices.end(), p.second.first.begin(), p.second.first.end()); |
| 11878 | unused_dust_indices.insert(unused_dust_indices.end(), p.second.second.begin(), p.second.second.end()); |
| 11879 | LOG_PRINT_L2("Spending from subaddress index " << p.first); |
| 11880 | } |
| 11881 | } |
| 11882 | |
| 11883 | return create_transactions_from(address, is_subaddress, outputs, unused_transfers_indices, unused_dust_indices, fake_outs_count, priority, extra); |
| 11884 | } |
| 11885 | |
| 11886 | std::vector<wallet2::pending_tx> wallet2::create_transactions_single(const crypto::key_image &ki, const cryptonote::account_public_address &address, bool is_subaddress, const size_t outputs, const size_t fake_outs_count, uint32_t priority, const std::vector<uint8_t>& extra) |
| 11887 | { |
| 11888 | std::vector<size_t> unused_transfers_indices; |
| 11889 | std::vector<size_t> unused_dust_indices; |
| 11890 | const bool use_rct = use_fork_rules(4, 0); |
| 11891 | // find output with the given key image |
| 11892 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 11893 | { |
| 11894 | const transfer_details& td = m_transfers[i]; |
| 11895 | if (td.m_key_image_known && td.m_key_image == ki && !is_spent(td, false) && !td.m_frozen && (use_rct ? true : !td.is_rct()) && is_transfer_unlocked(td)) |
| 11896 | { |
| 11897 | if (td.is_rct() || is_valid_decomposed_amount(td.amount())) |
| 11898 | unused_transfers_indices.push_back(i); |
| 11899 | else |
| 11900 | unused_dust_indices.push_back(i); |
| 11901 | break; |
| 11902 | } |
| 11903 | } |
| 11904 | return create_transactions_from(address, is_subaddress, outputs, unused_transfers_indices, unused_dust_indices, fake_outs_count, priority, extra); |
| 11905 | } |
| 11906 | |
| 11907 | std::vector<wallet2::pending_tx> wallet2::create_transactions_from(const cryptonote::account_public_address &address, bool is_subaddress, const size_t outputs, std::vector<size_t> unused_transfers_indices, std::vector<size_t> unused_dust_indices, const size_t fake_outs_count, uint32_t priority, const std::vector<uint8_t>& extra) |
| 11908 | { |
| 11909 | //ensure device is let in NONE mode in any case |
| 11910 | hw::device &hwdev = m_account.get_device(); |
| 11911 | boost::unique_lock<hw::device> hwdev_lock (hwdev); |
| 11912 | hw::reset_mode rst(hwdev); |
| 11913 | std::unordered_set<crypto::public_key> valid_public_keys_cache; |
| 11914 | |
| 11915 | uint64_t accumulated_fee, accumulated_outputs, accumulated_change; |
| 11916 | struct TX { |
| 11917 | std::vector<size_t> selected_transfers; |
| 11918 | std::vector<cryptonote::tx_destination_entry> dsts; |
| 11919 | cryptonote::transaction tx; |
| 11920 | pending_tx ptx; |
| 11921 | size_t weight; |
| 11922 | uint64_t needed_fee; |
| 11923 | std::vector<std::vector<get_outs_entry>> outs; |
| 11924 | |
| 11925 | TX() : weight(0), needed_fee(0) {} |
| 11926 | }; |
| 11927 | std::vector<TX> txes; |
| 11928 | uint64_t needed_fee, available_for_fee = 0; |
| 11929 | uint64_t upper_transaction_weight_limit = get_upper_transaction_weight_limit(); |
| 11930 | std::vector<std::vector<get_outs_entry>> outs; |
| 11931 | |
| 11932 | const bool use_per_byte_fee = use_fork_rules(HF_VERSION_PER_BYTE_FEE); |
| 11933 | const bool use_rct = fake_outs_count > 0 && use_fork_rules(4, 0); |
| 11934 | const bool bulletproof = use_fork_rules(get_bulletproof_fork(), 0); |
| 11935 | const bool bulletproof_plus = use_fork_rules(get_bulletproof_plus_fork(), 0); |
| 11936 | const bool clsag = use_fork_rules(get_clsag_fork(), 0); |
| 11937 | const rct::RCTConfig rct_config { |
| 11938 | rct::RangeProofPaddedBulletproof, |
| 11939 | bulletproof_plus ? 4 : 3 |
| 11940 | }; |
| 11941 | const bool use_view_tags = use_fork_rules(get_view_tag_fork(), 0); |
| 11942 | const uint64_t base_fee = get_base_fee(priority); |
| 11943 | const uint64_t fee_quantization_mask = get_fee_quantization_mask(); |
| 11944 | |
| 11945 | LOG_PRINT_L2("Starting with " << unused_transfers_indices.size() << " non-dust outputs and " << unused_dust_indices.size() << " dust outputs"); |
| 11946 | |
| 11947 | if (unused_dust_indices.empty() && unused_transfers_indices.empty()) |
| 11948 | return std::vector<wallet2::pending_tx>(); |
| 11949 | |
| 11950 | // start with an empty tx |
| 11951 | txes.push_back(TX()); |
| 11952 | accumulated_fee = 0; |
| 11953 | accumulated_outputs = 0; |
| 11954 | accumulated_change = 0; |
| 11955 | needed_fee = 0; |
| 11956 | |
| 11957 | // while we have something to send |
| 11958 | hwdev.set_mode(hw::device::TRANSACTION_CREATE_FAKE); |
| 11959 | while (!unused_dust_indices.empty() || !unused_transfers_indices.empty()) { |
| 11960 | TX &tx = txes.back(); |
| 11961 | |
| 11962 | // get a random unspent output and use it to pay next chunk. We try to alternate |
| 11963 | // dust and non dust to ensure we never get with only dust, from which we might |
| 11964 | // get a tx that can't pay for itself |
| 11965 | uint64_t fee_dust_threshold; |
| 11966 | if (use_fork_rules(HF_VERSION_PER_BYTE_FEE)) |
| 11967 | { |
| 11968 | const uint64_t estimated_tx_weight_with_one_extra_output = estimate_tx_weight(use_rct, tx.selected_transfers.size() + 1, fake_outs_count, tx.dsts.size()+1, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 11969 | fee_dust_threshold = calculate_fee_from_weight(base_fee, estimated_tx_weight_with_one_extra_output, fee_quantization_mask); |
| 11970 | } |
| 11971 | else |
| 11972 | { |
| 11973 | fee_dust_threshold = base_fee * (upper_transaction_weight_limit + 1023) / 1024; |
| 11974 | } |
| 11975 | |
| 11976 | size_t idx = |
| 11977 | unused_transfers_indices.empty() |
| 11978 | ? pop_best_value(unused_dust_indices, tx.selected_transfers) |
| 11979 | : unused_dust_indices.empty() |
| 11980 | ? pop_best_value(unused_transfers_indices, tx.selected_transfers) |
| 11981 | : ((tx.selected_transfers.size() & 1) || accumulated_outputs > fee_dust_threshold) |
| 11982 | ? pop_best_value(unused_dust_indices, tx.selected_transfers) |
| 11983 | : pop_best_value(unused_transfers_indices, tx.selected_transfers); |
| 11984 | |
| 11985 | const transfer_details &td = m_transfers[idx]; |
| 11986 | LOG_PRINT_L2("Picking output " << idx << ", amount " << print_money(td.amount())); |
| 11987 | |
| 11988 | // add this output to the list to spend |
| 11989 | tx.selected_transfers.push_back(idx); |
| 11990 | uint64_t available_amount = td.amount(); |
| 11991 | accumulated_outputs += available_amount; |
| 11992 | |
| 11993 | // clear any fake outs we'd already gathered, since we'll need a new set |
| 11994 | outs.clear(); |
| 11995 | |
| 11996 | // here, check if we need to sent tx and start a new one |
| 11997 | LOG_PRINT_L2("Considering whether to create a tx now, " << tx.selected_transfers.size() << " inputs, tx limit " |
| 11998 | << upper_transaction_weight_limit); |
| 11999 | const size_t estimated_rct_tx_weight = estimate_tx_weight(use_rct, tx.selected_transfers.size(), fake_outs_count, tx.dsts.size() + 2, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 12000 | bool try_tx = (unused_dust_indices.empty() && unused_transfers_indices.empty()) || ( estimated_rct_tx_weight >= TX_WEIGHT_TARGET(upper_transaction_weight_limit)); |
| 12001 | |
| 12002 | if (try_tx) { |
| 12003 | cryptonote::transaction test_tx; |
| 12004 | pending_tx test_ptx; |
| 12005 | |
| 12006 | const size_t num_outputs = get_num_outputs(tx.dsts, m_transfers, tx.selected_transfers); |
| 12007 | needed_fee = estimate_fee(use_per_byte_fee, use_rct, tx.selected_transfers.size(), fake_outs_count, num_outputs, extra.size(), bulletproof, clsag, bulletproof_plus, use_view_tags, base_fee, fee_quantization_mask); |
| 12008 | |
| 12009 | // add N - 1 outputs for correct initial fee estimation |
| 12010 | for (size_t i = 0; i < ((outputs > 1) ? outputs - 1 : outputs); ++i) |
| 12011 | tx.dsts.push_back(tx_destination_entry(1, address, is_subaddress)); |
| 12012 | |
| 12013 | LOG_PRINT_L2("Trying to create a tx now, with " << tx.dsts.size() << " destinations and " << |
| 12014 | tx.selected_transfers.size() << " outputs"); |
| 12015 | if (use_rct) |
| 12016 | transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 12017 | test_tx, test_ptx, rct_config, use_view_tags); |
| 12018 | else |
| 12019 | transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 12020 | detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx, use_view_tags); |
| 12021 | auto txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 12022 | needed_fee = calculate_fee(use_per_byte_fee, test_ptx.tx, txBlob.size(), base_fee, fee_quantization_mask); |
| 12023 | available_for_fee = test_ptx.fee + test_ptx.change_dts.amount; |
| 12024 | for (auto &dt: test_ptx.dests) |
| 12025 | available_for_fee += dt.amount; |
| 12026 | LOG_PRINT_L2("Made a " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(available_for_fee) << " available for fee (" << |
| 12027 | print_money(needed_fee) << " needed)"); |
| 12028 | |
| 12029 | // add last output, missed for fee estimation |
| 12030 | if (outputs > 1) |
| 12031 | tx.dsts.push_back(tx_destination_entry(1, address, is_subaddress)); |
| 12032 | |
| 12033 | THROW_WALLET_EXCEPTION_IF(needed_fee > available_for_fee, error::wallet_internal_error, "Transaction cannot pay for itself"); |
| 12034 | |
| 12035 | do { |
| 12036 | LOG_PRINT_L2("We made a tx, adjusting fee and saving it, we need " << print_money(needed_fee) << " and we have " << print_money(test_ptx.fee)); |
| 12037 | // distribute total transferred amount between outputs |
| 12038 | uint64_t amount_transferred = available_for_fee - needed_fee; |
| 12039 | uint64_t dt_amount = amount_transferred / outputs; |
| 12040 | // residue is distributed as one atomic unit per output until it reaches zero |
| 12041 | uint64_t residue = amount_transferred % outputs; |
| 12042 | for (auto &dt: tx.dsts) |
| 12043 | { |
| 12044 | uint64_t dt_residue = 0; |
| 12045 | if (residue > 0) |
| 12046 | { |
| 12047 | dt_residue = 1; |
| 12048 | residue -= 1; |
| 12049 | } |
| 12050 | dt.amount = dt_amount + dt_residue; |
| 12051 | } |
| 12052 | if (use_rct) |
| 12053 | transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 12054 | test_tx, test_ptx, rct_config, use_view_tags); |
| 12055 | else |
| 12056 | transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, outs, valid_public_keys_cache, needed_fee, extra, |
| 12057 | detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx, use_view_tags); |
| 12058 | txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 12059 | needed_fee = calculate_fee(use_per_byte_fee, test_ptx.tx, txBlob.size(), base_fee, fee_quantization_mask); |
| 12060 | LOG_PRINT_L2("Made an attempt at a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << |
| 12061 | " fee and " << print_money(test_ptx.change_dts.amount) << " change"); |
| 12062 | } while (needed_fee > test_ptx.fee); |
| 12063 | |
| 12064 | LOG_PRINT_L2("Made a final " << get_weight_string(test_ptx.tx, txBlob.size()) << " tx, with " << print_money(test_ptx.fee) << |
| 12065 | " fee and " << print_money(test_ptx.change_dts.amount) << " change"); |
| 12066 | |
| 12067 | tx.tx = test_tx; |
| 12068 | tx.ptx = test_ptx; |
| 12069 | tx.weight = get_transaction_weight(test_tx, txBlob.size()); |
| 12070 | tx.outs = outs; |
| 12071 | tx.needed_fee = test_ptx.fee; |
| 12072 | accumulated_fee += test_ptx.fee; |
| 12073 | accumulated_change += test_ptx.change_dts.amount; |
| 12074 | if (!unused_transfers_indices.empty() || !unused_dust_indices.empty()) |
| 12075 | { |
| 12076 | LOG_PRINT_L2("We have more to pay, starting another tx"); |
| 12077 | txes.push_back(TX()); |
| 12078 | } |
| 12079 | } |
| 12080 | } |
| 12081 | |
| 12082 | LOG_PRINT_L1("Done creating " << txes.size() << " transactions, " << print_money(accumulated_fee) << |
| 12083 | " total fee, " << print_money(accumulated_change) << " total change"); |
| 12084 | |
| 12085 | hwdev.set_mode(hw::device::TRANSACTION_CREATE_REAL); |
| 12086 | for (std::vector<TX>::iterator i = txes.begin(); i != txes.end(); ++i) |
| 12087 | { |
| 12088 | TX &tx = *i; |
| 12089 | cryptonote::transaction test_tx; |
| 12090 | pending_tx test_ptx; |
| 12091 | if (use_rct) { |
| 12092 | transfer_selected_rct(tx.dsts, tx.selected_transfers, fake_outs_count, tx.outs, valid_public_keys_cache, tx.needed_fee, extra, |
| 12093 | test_tx, test_ptx, rct_config, use_view_tags); |
| 12094 | } else { |
| 12095 | transfer_selected(tx.dsts, tx.selected_transfers, fake_outs_count, tx.outs, valid_public_keys_cache, tx.needed_fee, extra, |
| 12096 | detail::digit_split_strategy, tx_dust_policy(::config::DEFAULT_DUST_THRESHOLD), test_tx, test_ptx, use_view_tags); |
| 12097 | } |
| 12098 | auto txBlob = t_serializable_object_to_blob(test_ptx.tx); |
| 12099 | tx.tx = test_tx; |
| 12100 | tx.ptx = test_ptx; |
| 12101 | tx.weight = get_transaction_weight(test_tx, txBlob.size()); |
| 12102 | } |
| 12103 | |
| 12104 | std::vector<wallet2::pending_tx> ptx_vector; |
| 12105 | for (std::vector<TX>::iterator i = txes.begin(); i != txes.end(); ++i) |
| 12106 | { |
| 12107 | TX &tx = *i; |
| 12108 | uint64_t tx_money = 0; |
| 12109 | for (size_t idx: tx.selected_transfers) |
| 12110 | tx_money += m_transfers[idx].amount(); |
| 12111 | LOG_PRINT_L1(" Transaction " << (1+std::distance(txes.begin(), i)) << "/" << txes.size() << |
| 12112 | " " << get_transaction_hash(tx.ptx.tx) << ": " << get_weight_string(tx.weight) << ", sending " << print_money(tx_money) << " in " << tx.selected_transfers.size() << |
| 12113 | " outputs to " << tx.dsts.size() << " destination(s), including " << |
| 12114 | print_money(tx.ptx.fee) << " fee, " << print_money(tx.ptx.change_dts.amount) << " change"); |
| 12115 | ptx_vector.push_back(tx.ptx); |
| 12116 | } |
| 12117 | |
| 12118 | uint64_t a = 0; |
| 12119 | for (const TX &tx: txes) |
| 12120 | { |
| 12121 | for (size_t idx: tx.selected_transfers) |
| 12122 | { |
| 12123 | a += m_transfers[idx].amount(); |
| 12124 | } |
| 12125 | a -= tx.ptx.fee; |
| 12126 | } |
| 12127 | std::vector<cryptonote::tx_destination_entry> synthetic_dsts(1, cryptonote::tx_destination_entry("", a, address, is_subaddress)); |
| 12128 | THROW_WALLET_EXCEPTION_IF(!sanity_check(ptx_vector, synthetic_dsts), error::wallet_internal_error, "Created transaction(s) failed sanity check"); |
| 12129 | |
| 12130 | // if we made it this far, we're OK to actually send the transactions |
| 12131 | return ptx_vector; |
| 12132 | } |
| 12133 | //---------------------------------------------------------------------------------------------------- |
| 12134 | void wallet2::cold_tx_aux_import(const std::vector<pending_tx> & ptx, const std::vector<std::string> & tx_device_aux) |
| 12135 | { |
| 12136 | CHECK_AND_ASSERT_THROW_MES(ptx.size() == tx_device_aux.size(), "TX aux has invalid size"); |
| 12137 | for (size_t i = 0; i < ptx.size(); ++i){ |
| 12138 | crypto::hash txid; |
| 12139 | txid = get_transaction_hash(ptx[i].tx); |
| 12140 | set_tx_device_aux(txid, tx_device_aux[i]); |
| 12141 | } |
| 12142 | } |
| 12143 | //---------------------------------------------------------------------------------------------------- |
| 12144 | void wallet2::cold_sign_tx(const std::vector<pending_tx>& ptx_vector, signed_tx_set &exported_txs, std::vector<cryptonote::address_parse_info> &dsts_info, std::vector<std::string> & tx_device_aux) |
| 12145 | { |
| 12146 | auto & hwdev = get_account().get_device(); |
| 12147 | if (!hwdev.has_tx_cold_sign()){ |
| 12148 | throw std::invalid_argument("Device does not support cold sign protocol"); |
| 12149 | } |
| 12150 | |
| 12151 | unsigned_tx_set txs; |
| 12152 | for (auto &tx: ptx_vector) |
| 12153 | { |
| 12154 | txs.txes.push_back(get_construction_data_with_decrypted_short_payment_id(tx, m_account.get_device())); |
| 12155 | } |
| 12156 | txs.transfers = std::make_tuple(0, m_transfers.size(), m_transfers); |
| 12157 | |
| 12158 | auto dev_cold = dynamic_cast<::hw::device_cold*>(&hwdev); |
| 12159 | CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); |
| 12160 | |
| 12161 | hw::tx_aux_data aux_data; |
| 12162 | hw::wallet_shim wallet_shim; |
| 12163 | setup_shim(&wallet_shim, this); |
| 12164 | aux_data.tx_recipients = dsts_info; |
| 12165 | aux_data.bp_version = (use_fork_rules(HF_VERSION_BULLETPROOF_PLUS, -10) ? 4 : use_fork_rules(HF_VERSION_CLSAG, -10) ? 3 : use_fork_rules(HF_VERSION_SMALLER_BP, -10) ? 2 : 1); |
| 12166 | aux_data.hard_fork = get_current_hard_fork(); |
| 12167 | dev_cold->tx_sign(&wallet_shim, txs, exported_txs, aux_data); |
| 12168 | tx_device_aux = aux_data.tx_device_aux; |
| 12169 | |
| 12170 | MDEBUG("Signed tx data from hw: " << exported_txs.ptx.size() << " transactions"); |
| 12171 | for (auto &c_ptx: exported_txs.ptx) LOG_PRINT_L0(cryptonote::obj_to_json_str(c_ptx.tx)); |
| 12172 | } |
| 12173 | //---------------------------------------------------------------------------------------------------- |
| 12174 | uint64_t wallet2::cold_key_image_sync(uint64_t &spent, uint64_t &unspent) { |
| 12175 | auto & hwdev = get_account().get_device(); |
| 12176 | CHECK_AND_ASSERT_THROW_MES(hwdev.has_ki_cold_sync(), "Device does not support cold ki sync protocol"); |
| 12177 | |
| 12178 | auto dev_cold = dynamic_cast<::hw::device_cold*>(&hwdev); |
| 12179 | CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); |
| 12180 | |
| 12181 | std::vector<std::pair<crypto::key_image, crypto::signature>> ski; |
| 12182 | hw::wallet_shim wallet_shim; |
| 12183 | setup_shim(&wallet_shim, this); |
| 12184 | |
| 12185 | dev_cold->ki_sync(&wallet_shim, m_transfers, ski); |
| 12186 | |
| 12187 | // Call COMMAND_RPC_IS_KEY_IMAGE_SPENT only if daemon is trusted. |
| 12188 | uint64_t import_res = import_key_images(ski, 0, spent, unspent, is_trusted_daemon()); |
| 12189 | m_device_last_key_image_sync = time(NULL); |
| 12190 | |
| 12191 | return import_res; |
| 12192 | } |
| 12193 | //---------------------------------------------------------------------------------------------------- |
| 12194 | void wallet2::device_show_address(uint32_t account_index, uint32_t address_index, const boost::optional<crypto::hash8> &payment_id) |
| 12195 | { |
| 12196 | if (!key_on_device()) |
| 12197 | { |
| 12198 | return; |
| 12199 | } |
| 12200 | |
| 12201 | auto & hwdev = get_account().get_device(); |
| 12202 | hwdev.display_address(subaddress_index{account_index, address_index}, payment_id); |
| 12203 | } |
| 12204 | //---------------------------------------------------------------------------------------------------- |
| 12205 | uint8_t wallet2::get_current_hard_fork() |
| 12206 | { |
| 12207 | if (m_offline) |
| 12208 | return 0; |
| 12209 | |
| 12210 | cryptonote::COMMAND_RPC_HARD_FORK_INFO::request req_t = AUTO_VAL_INIT(req_t); |
| 12211 | cryptonote::COMMAND_RPC_HARD_FORK_INFO::response resp_t = AUTO_VAL_INIT(resp_t); |
| 12212 | |
| 12213 | m_daemon_rpc_mutex.lock(); |
| 12214 | req_t.version = 0; |
| 12215 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "hard_fork_info", req_t, resp_t, *m_http_client, rpc_timeout); |
| 12216 | m_daemon_rpc_mutex.unlock(); |
| 12217 | THROW_WALLET_EXCEPTION_IF(!r, tools::error::no_connection_to_daemon, "hard_fork_info"); |
| 12218 | THROW_WALLET_EXCEPTION_IF(resp_t.status == CORE_RPC_STATUS_BUSY, tools::error::daemon_busy, "hard_fork_info"); |
| 12219 | THROW_WALLET_EXCEPTION_IF(resp_t.status != CORE_RPC_STATUS_OK, tools::error::wallet_generic_rpc_error, "hard_fork_info", m_trusted_daemon ? resp_t.status : "daemon error"); |
| 12220 | return resp_t.version; |
| 12221 | } |
| 12222 | //---------------------------------------------------------------------------------------------------- |
| 12223 | void wallet2::get_hard_fork_info(uint8_t version, uint64_t &earliest_height) |
| 12224 | { |
| 12225 | boost::optional<std::string> result = m_node_rpc_proxy.get_earliest_height(version, earliest_height); |
| 12226 | } |
| 12227 | //---------------------------------------------------------------------------------------------------- |
| 12228 | bool wallet2::use_fork_rules(uint8_t version, int64_t early_blocks) |
| 12229 | { |
| 12230 | // TODO: How to get fork rule info from light wallet node? |
| 12231 | if(m_light_wallet) |
| 12232 | return true; |
| 12233 | uint64_t height, earliest_height; |
| 12234 | boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); |
| 12235 | THROW_WALLET_EXCEPTION_IF(result, error::wallet_internal_error, "Failed to get height"); |
| 12236 | result = m_node_rpc_proxy.get_earliest_height(version, earliest_height); |
| 12237 | THROW_WALLET_EXCEPTION_IF(result, error::wallet_internal_error, "Failed to get earliest fork height"); |
| 12238 | |
| 12239 | bool close_enough = (int64_t)height >= (int64_t)earliest_height - early_blocks && earliest_height != std::numeric_limits<uint64_t>::max(); // start using the rules that many blocks beforehand |
| 12240 | if (close_enough) |
| 12241 | LOG_PRINT_L2("Using v" << (unsigned)version << " rules"); |
| 12242 | else |
| 12243 | LOG_PRINT_L2("Not using v" << (unsigned)version << " rules"); |
| 12244 | return close_enough; |
| 12245 | } |
| 12246 | //---------------------------------------------------------------------------------------------------- |
| 12247 | uint64_t wallet2::get_upper_transaction_weight_limit() |
| 12248 | { |
| 12249 | if (m_upper_transaction_weight_limit > 0) |
| 12250 | return m_upper_transaction_weight_limit; |
| 12251 | uint64_t full_reward_zone = use_fork_rules(5, 10) ? CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5 : use_fork_rules(2, 10) ? CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2 : CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1; |
| 12252 | if (use_fork_rules(8, 10)) |
| 12253 | return full_reward_zone / 2 - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; |
| 12254 | else |
| 12255 | return full_reward_zone - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; |
| 12256 | } |
| 12257 | //---------------------------------------------------------------------------------------------------- |
| 12258 | std::vector<size_t> wallet2::select_available_outputs(const std::function<bool(const transfer_details &td)> &f) |
| 12259 | { |
| 12260 | std::vector<size_t> outputs; |
| 12261 | size_t n = 0; |
| 12262 | for (transfer_container::const_iterator i = m_transfers.begin(); i != m_transfers.end(); ++i, ++n) |
| 12263 | { |
| 12264 | if (is_spent(*i, false)) |
| 12265 | continue; |
| 12266 | if (i->m_frozen) |
| 12267 | continue; |
| 12268 | if (i->m_key_image_partial) |
| 12269 | continue; |
| 12270 | if (!is_transfer_unlocked(*i)) |
| 12271 | continue; |
| 12272 | if (f(*i)) |
| 12273 | outputs.push_back(n); |
| 12274 | } |
| 12275 | return outputs; |
| 12276 | } |
| 12277 | //---------------------------------------------------------------------------------------------------- |
| 12278 | std::vector<uint64_t> wallet2::get_unspent_amounts_vector(bool strict) |
| 12279 | { |
| 12280 | std::set<uint64_t> set; |
| 12281 | for (const auto &td: m_transfers) |
| 12282 | { |
| 12283 | if (!is_spent(td, strict) && !td.m_frozen) |
| 12284 | set.insert(td.is_rct() ? 0 : td.amount()); |
| 12285 | } |
| 12286 | std::vector<uint64_t> vector; |
| 12287 | vector.reserve(set.size()); |
| 12288 | for (const auto &i: set) |
| 12289 | { |
| 12290 | vector.push_back(i); |
| 12291 | } |
| 12292 | return vector; |
| 12293 | } |
| 12294 | //---------------------------------------------------------------------------------------------------- |
| 12295 | std::vector<size_t> wallet2::select_available_outputs_from_histogram(uint64_t count, bool atleast, bool unlocked, bool allow_rct) |
| 12296 | { |
| 12297 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request req_t = AUTO_VAL_INIT(req_t); |
| 12298 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response resp_t = AUTO_VAL_INIT(resp_t); |
| 12299 | if (is_trusted_daemon()) |
| 12300 | req_t.amounts = get_unspent_amounts_vector(false); |
| 12301 | req_t.min_count = count; |
| 12302 | req_t.max_count = 0; |
| 12303 | req_t.unlocked = unlocked; |
| 12304 | req_t.recent_cutoff = 0; |
| 12305 | |
| 12306 | { |
| 12307 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12308 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 12309 | req_t.client = get_client_signature(); |
| 12310 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "get_output_histogram", req_t, resp_t, *m_http_client, rpc_timeout); |
| 12311 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, resp_t, "get_output_histogram", error::get_histogram_error, resp_t.status); |
| 12312 | uint64_t cost = req_t.amounts.empty() ? COST_PER_FULL_OUTPUT_HISTOGRAM : (COST_PER_OUTPUT_HISTOGRAM * req_t.amounts.size()); |
| 12313 | check_rpc_cost("get_output_histogram", resp_t.credits, pre_call_credits, cost); |
| 12314 | } |
| 12315 | |
| 12316 | std::set<uint64_t> mixable; |
| 12317 | for (const auto &i: resp_t.histogram) |
| 12318 | { |
| 12319 | mixable.insert(i.amount); |
| 12320 | } |
| 12321 | |
| 12322 | return select_available_outputs([mixable, atleast, allow_rct](const transfer_details &td) { |
| 12323 | if (!allow_rct && td.is_rct()) |
| 12324 | return false; |
| 12325 | const uint64_t amount = td.is_rct() ? 0 : td.amount(); |
| 12326 | if (atleast) { |
| 12327 | if (mixable.find(amount) != mixable.end()) |
| 12328 | return true; |
| 12329 | } |
| 12330 | else { |
| 12331 | if (mixable.find(amount) == mixable.end()) |
| 12332 | return true; |
| 12333 | } |
| 12334 | return false; |
| 12335 | }); |
| 12336 | } |
| 12337 | //---------------------------------------------------------------------------------------------------- |
| 12338 | uint64_t wallet2::get_num_rct_outputs() |
| 12339 | { |
| 12340 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request req_t = AUTO_VAL_INIT(req_t); |
| 12341 | cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response resp_t = AUTO_VAL_INIT(resp_t); |
| 12342 | req_t.amounts.push_back(0); |
| 12343 | req_t.min_count = 0; |
| 12344 | req_t.max_count = 0; |
| 12345 | req_t.unlocked = true; |
| 12346 | req_t.recent_cutoff = 0; |
| 12347 | |
| 12348 | { |
| 12349 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12350 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 12351 | req_t.client = get_client_signature(); |
| 12352 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "get_output_histogram", req_t, resp_t, *m_http_client, rpc_timeout); |
| 12353 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, resp_t, "get_output_histogram", error::get_histogram_error, resp_t.status); |
| 12354 | THROW_WALLET_EXCEPTION_IF(resp_t.histogram.size() != 1, error::get_histogram_error, "Expected exactly one response"); |
| 12355 | THROW_WALLET_EXCEPTION_IF(resp_t.histogram[0].amount != 0, error::get_histogram_error, "Expected 0 amount"); |
| 12356 | check_rpc_cost("get_output_histogram", resp_t.credits, pre_call_credits, COST_PER_OUTPUT_HISTOGRAM); |
| 12357 | } |
| 12358 | |
| 12359 | return resp_t.histogram[0].total_instances; |
| 12360 | } |
| 12361 | //---------------------------------------------------------------------------------------------------- |
| 12362 | const wallet2::transfer_details &wallet2::get_transfer_details(size_t idx) const |
| 12363 | { |
| 12364 | THROW_WALLET_EXCEPTION_IF(idx >= m_transfers.size(), error::wallet_internal_error, "Bad transfer index"); |
| 12365 | return m_transfers[idx]; |
| 12366 | } |
| 12367 | //---------------------------------------------------------------------------------------------------- |
| 12368 | std::vector<size_t> wallet2::select_available_unmixable_outputs() |
| 12369 | { |
| 12370 | // request all outputs with less instances than the min ring size |
| 12371 | return select_available_outputs_from_histogram(get_min_ring_size(), false, true, false); |
| 12372 | } |
| 12373 | //---------------------------------------------------------------------------------------------------- |
| 12374 | std::vector<size_t> wallet2::select_available_mixable_outputs() |
| 12375 | { |
| 12376 | // request all outputs with at least as many instances as the min ring size |
| 12377 | return select_available_outputs_from_histogram(get_min_ring_size(), true, true, true); |
| 12378 | } |
| 12379 | //---------------------------------------------------------------------------------------------------- |
| 12380 | std::vector<wallet2::pending_tx> wallet2::create_unmixable_sweep_transactions() |
| 12381 | { |
| 12382 | // From hard fork 1, we don't consider small amounts to be dust anymore |
| 12383 | const bool hf1_rules = use_fork_rules(2, 10); // first hard fork has version 2 |
| 12384 | tx_dust_policy dust_policy(hf1_rules ? 0 : ::config::DEFAULT_DUST_THRESHOLD); |
| 12385 | |
| 12386 | const uint64_t base_fee = get_base_fee(1); |
| 12387 | |
| 12388 | // may throw |
| 12389 | std::vector<size_t> unmixable_outputs = select_available_unmixable_outputs(); |
| 12390 | size_t num_dust_outputs = unmixable_outputs.size(); |
| 12391 | |
| 12392 | if (num_dust_outputs == 0) |
| 12393 | { |
| 12394 | return std::vector<wallet2::pending_tx>(); |
| 12395 | } |
| 12396 | |
| 12397 | // split in "dust" and "non dust" to make it easier to select outputs |
| 12398 | std::vector<size_t> unmixable_transfer_outputs, unmixable_dust_outputs; |
| 12399 | for (auto n: unmixable_outputs) |
| 12400 | { |
| 12401 | if (m_transfers[n].amount() < base_fee) |
| 12402 | unmixable_dust_outputs.push_back(n); |
| 12403 | else |
| 12404 | unmixable_transfer_outputs.push_back(n); |
| 12405 | } |
| 12406 | |
| 12407 | return create_transactions_from(m_account_public_address, false, 1, unmixable_transfer_outputs, unmixable_dust_outputs, 0 /*fake_outs_count */, 1 /*priority */, std::vector<uint8_t>()); |
| 12408 | } |
| 12409 | //---------------------------------------------------------------------------------------------------- |
| 12410 | void wallet2::discard_unmixable_outputs() |
| 12411 | { |
| 12412 | // may throw |
| 12413 | std::vector<size_t> unmixable_outputs = select_available_unmixable_outputs(); |
| 12414 | for (size_t idx : unmixable_outputs) |
| 12415 | { |
| 12416 | freeze(idx); |
| 12417 | } |
| 12418 | } |
| 12419 | |
| 12420 | bool wallet2::get_tx_key_cached(const crypto::hash &txid, crypto::secret_key &tx_key, std::vector<crypto::secret_key> &additional_tx_keys) const |
| 12421 | { |
| 12422 | additional_tx_keys.clear(); |
| 12423 | const std::unordered_map<crypto::hash, crypto::secret_key>::const_iterator i = m_tx_keys.find(txid); |
| 12424 | if (i == m_tx_keys.end()) |
| 12425 | return false; |
| 12426 | tx_key = i->second; |
| 12427 | if (tx_key == crypto::null_skey) |
| 12428 | return false; |
| 12429 | const auto j = m_additional_tx_keys.find(txid); |
| 12430 | if (j != m_additional_tx_keys.end()) |
| 12431 | additional_tx_keys = j->second; |
| 12432 | return true; |
| 12433 | } |
| 12434 | //---------------------------------------------------------------------------------------------------- |
| 12435 | bool wallet2::get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key, std::vector<crypto::secret_key> &additional_tx_keys) |
| 12436 | { |
| 12437 | bool r = get_tx_key_cached(txid, tx_key, additional_tx_keys); |
| 12438 | if (r) |
| 12439 | { |
| 12440 | MDEBUG("tx key cached for txid: " << txid); |
| 12441 | return true; |
| 12442 | } |
| 12443 | |
| 12444 | auto & hwdev = get_account().get_device(); |
| 12445 | |
| 12446 | // So far only Cold protocol devices are supported. |
| 12447 | if (hwdev.device_protocol() != hw::device::PROTOCOL_COLD) |
| 12448 | { |
| 12449 | return false; |
| 12450 | } |
| 12451 | |
| 12452 | const auto tx_data_it = m_tx_device.find(txid); |
| 12453 | if (tx_data_it == m_tx_device.end()) |
| 12454 | { |
| 12455 | MDEBUG("Aux data not found for txid: " << txid); |
| 12456 | return false; |
| 12457 | } |
| 12458 | |
| 12459 | auto dev_cold = dynamic_cast<::hw::device_cold*>(&hwdev); |
| 12460 | CHECK_AND_ASSERT_THROW_MES(dev_cold, "Device does not implement cold signing interface"); |
| 12461 | if (!dev_cold->is_get_tx_key_supported()) |
| 12462 | { |
| 12463 | MDEBUG("get_tx_key not supported by the device"); |
| 12464 | return false; |
| 12465 | } |
| 12466 | |
| 12467 | hw::device_cold::tx_key_data_t tx_key_data; |
| 12468 | dev_cold->load_tx_key_data(tx_key_data, tx_data_it->second); |
| 12469 | |
| 12470 | // Load missing tx prefix hash |
| 12471 | if (tx_key_data.tx_prefix_hash.empty()) |
| 12472 | { |
| 12473 | COMMAND_RPC_GET_TRANSACTIONS::request req; |
| 12474 | COMMAND_RPC_GET_TRANSACTIONS::response res; |
| 12475 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12476 | req.decode_as_json = false; |
| 12477 | req.prune = true; |
| 12478 | |
| 12479 | { |
| 12480 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12481 | req.client = get_client_signature(); |
| 12482 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 12483 | bool ok = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client); |
| 12484 | THROW_WALLET_EXCEPTION_IF(!ok || res.txs.size() != 1, |
| 12485 | error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 12486 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, res.txs.size() * COST_PER_TX); |
| 12487 | } |
| 12488 | |
| 12489 | cryptonote::transaction tx; |
| 12490 | crypto::hash tx_hash{}; |
| 12491 | cryptonote::blobdata tx_data; |
| 12492 | bool ok = get_pruned_tx(res.txs.front(), tx, tx_hash); |
| 12493 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to parse transaction from daemon"); |
| 12494 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, |
| 12495 | "Failed to get the right transaction from daemon"); |
| 12496 | |
| 12497 | tx_key_data.tx_prefix_hash = std::string(get_transaction_prefix_hash(tx).data, 32); |
| 12498 | } |
| 12499 | |
| 12500 | std::vector<crypto::secret_key> tx_keys; |
| 12501 | dev_cold->get_tx_key(tx_keys, tx_key_data, m_account.get_keys().m_view_secret_key); |
| 12502 | if (tx_keys.empty()) |
| 12503 | { |
| 12504 | MDEBUG("Empty tx keys for txid: " << txid); |
| 12505 | return false; |
| 12506 | } |
| 12507 | |
| 12508 | if (tx_keys[0] == crypto::null_skey) |
| 12509 | { |
| 12510 | return false; |
| 12511 | } |
| 12512 | |
| 12513 | tx_key = tx_keys[0]; |
| 12514 | tx_keys.erase(tx_keys.begin()); |
| 12515 | additional_tx_keys = tx_keys; |
| 12516 | return true; |
| 12517 | } |
| 12518 | //---------------------------------------------------------------------------------------------------- |
| 12519 | void wallet2::set_tx_key(const crypto::hash &txid, const crypto::secret_key &tx_key, const std::vector<crypto::secret_key> &additional_tx_keys, const boost::optional<cryptonote::account_public_address> &single_destination_subaddress) |
| 12520 | { |
| 12521 | // fetch tx from daemon and check if secret keys agree with corresponding public keys |
| 12522 | COMMAND_RPC_GET_TRANSACTIONS::request req = AUTO_VAL_INIT(req); |
| 12523 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12524 | req.decode_as_json = false; |
| 12525 | req.prune = true; |
| 12526 | COMMAND_RPC_GET_TRANSACTIONS::response res = AUTO_VAL_INIT(res); |
| 12527 | bool r; |
| 12528 | uint64_t pre_call_credits; |
| 12529 | { |
| 12530 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12531 | pre_call_credits = m_rpc_payment_state.credits; |
| 12532 | req.client = get_client_signature(); |
| 12533 | r = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client, rpc_timeout); |
| 12534 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "/gettransactions"); |
| 12535 | THROW_WALLET_EXCEPTION_IF(res.txs.size() != 1, error::wallet_internal_error, |
| 12536 | "daemon returned wrong response for gettransactions, wrong txs count = " + |
| 12537 | std::to_string(res.txs.size()) + ", expected 1"); |
| 12538 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 12539 | } |
| 12540 | |
| 12541 | cryptonote::transaction tx; |
| 12542 | crypto::hash tx_hash; |
| 12543 | THROW_WALLET_EXCEPTION_IF(!get_pruned_tx(res.txs[0], tx, tx_hash), error::wallet_internal_error, |
| 12544 | "Failed to get transaction from daemon"); |
| 12545 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "txid mismatch"); |
| 12546 | std::vector<tx_extra_field> tx_extra_fields; |
| 12547 | THROW_WALLET_EXCEPTION_IF(!parse_tx_extra(tx.extra, tx_extra_fields), error::wallet_internal_error, "Transaction extra has unsupported format"); |
| 12548 | tx_extra_pub_key pub_key_field; |
| 12549 | bool found = false; |
| 12550 | size_t index = 0; |
| 12551 | while (find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, index++)) |
| 12552 | { |
| 12553 | crypto::public_key calculated_pub_key; |
| 12554 | crypto::secret_key_to_public_key(tx_key, calculated_pub_key); |
| 12555 | if (calculated_pub_key == pub_key_field.pub_key) |
| 12556 | { |
| 12557 | found = true; |
| 12558 | break; |
| 12559 | } |
| 12560 | // when sent to a single subaddress, the derivation is different |
| 12561 | if (single_destination_subaddress) |
| 12562 | { |
| 12563 | calculated_pub_key = rct::rct2pk(rct::scalarmultKey(rct::pk2rct(single_destination_subaddress->m_spend_public_key), rct::sk2rct(tx_key))); |
| 12564 | if (calculated_pub_key == pub_key_field.pub_key) |
| 12565 | { |
| 12566 | found = true; |
| 12567 | break; |
| 12568 | } |
| 12569 | } |
| 12570 | } |
| 12571 | THROW_WALLET_EXCEPTION_IF(!found, error::wallet_internal_error, "Given tx secret key doesn't agree with the tx public key in the blockchain"); |
| 12572 | tx_extra_additional_pub_keys additional_tx_pub_keys; |
| 12573 | find_tx_extra_field_by_type(tx_extra_fields, additional_tx_pub_keys); |
| 12574 | THROW_WALLET_EXCEPTION_IF(additional_tx_keys.size() != additional_tx_pub_keys.data.size(), error::wallet_internal_error, "The number of additional tx secret keys doesn't agree with the number of additional tx public keys in the blockchain" ); |
| 12575 | m_tx_keys[txid] = tx_key; |
| 12576 | m_additional_tx_keys[txid] = additional_tx_keys; |
| 12577 | } |
| 12578 | //---------------------------------------------------------------------------------------------------- |
| 12579 | std::string wallet2::get_spend_proof(const crypto::hash &txid, const std::string &message) |
| 12580 | { |
| 12581 | THROW_WALLET_EXCEPTION_IF(m_watch_only, error::wallet_internal_error, |
| 12582 | "get_spend_proof requires spend secret key and is not available for a watch-only wallet"); |
| 12583 | |
| 12584 | // fetch tx from daemon |
| 12585 | COMMAND_RPC_GET_TRANSACTIONS::request req = AUTO_VAL_INIT(req); |
| 12586 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12587 | req.decode_as_json = false; |
| 12588 | req.prune = true; |
| 12589 | COMMAND_RPC_GET_TRANSACTIONS::response res = AUTO_VAL_INIT(res); |
| 12590 | bool r; |
| 12591 | uint64_t pre_call_credits; |
| 12592 | { |
| 12593 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12594 | pre_call_credits = m_rpc_payment_state.credits; |
| 12595 | req.client = get_client_signature(); |
| 12596 | r = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client, rpc_timeout); |
| 12597 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "gettransactions"); |
| 12598 | THROW_WALLET_EXCEPTION_IF(res.txs.size() != 1, error::wallet_internal_error, |
| 12599 | "daemon returned wrong response for gettransactions, wrong txs count = " + |
| 12600 | std::to_string(res.txs.size()) + ", expected 1"); |
| 12601 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 12602 | } |
| 12603 | |
| 12604 | cryptonote::transaction tx; |
| 12605 | crypto::hash tx_hash; |
| 12606 | THROW_WALLET_EXCEPTION_IF(!get_pruned_tx(res.txs[0], tx, tx_hash), error::wallet_internal_error, "Failed to get tx from daemon"); |
| 12607 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 12608 | |
| 12609 | std::vector<std::vector<crypto::signature>> signatures; |
| 12610 | |
| 12611 | // get signature prefix hash |
| 12612 | std::string sig_prefix_data((const char*)&txid, sizeof(crypto::hash)); |
| 12613 | sig_prefix_data += message; |
| 12614 | crypto::hash sig_prefix_hash; |
| 12615 | crypto::cn_fast_hash(sig_prefix_data.data(), sig_prefix_data.size(), sig_prefix_hash); |
| 12616 | |
| 12617 | for(size_t i = 0; i < tx.vin.size(); ++i) |
| 12618 | { |
| 12619 | const txin_to_key* const in_key = boost::get<txin_to_key>(std::addressof(tx.vin[i])); |
| 12620 | if (in_key == nullptr) |
| 12621 | continue; |
| 12622 | |
| 12623 | // check if the key image belongs to us |
| 12624 | const auto found = m_key_images.find(in_key->k_image); |
| 12625 | if(found == m_key_images.end()) |
| 12626 | { |
| 12627 | THROW_WALLET_EXCEPTION_IF(i > 0, error::wallet_internal_error, "subset of key images belong to us, very weird!"); |
| 12628 | THROW_WALLET_EXCEPTION_IF(true, error::wallet_internal_error, "This tx wasn't generated by this wallet!"); |
| 12629 | } |
| 12630 | |
| 12631 | // derive the real output keypair |
| 12632 | const transfer_details& in_td = m_transfers[found->second]; |
| 12633 | crypto::public_key in_tx_out_pkey = in_td.get_public_key(); |
| 12634 | const crypto::public_key in_tx_pub_key = get_tx_pub_key_from_extra(in_td.m_tx, in_td.m_pk_index); |
| 12635 | const std::vector<crypto::public_key> in_additionakl_tx_pub_keys = get_additional_tx_pub_keys_from_extra(in_td.m_tx); |
| 12636 | keypair in_ephemeral; |
| 12637 | crypto::key_image in_img; |
| 12638 | THROW_WALLET_EXCEPTION_IF(!generate_key_image_helper(m_account.get_keys(), m_subaddresses, in_tx_out_pkey, in_tx_pub_key, in_additionakl_tx_pub_keys, in_td.m_internal_output_index, in_ephemeral, in_img, m_account.get_device()), |
| 12639 | error::wallet_internal_error, "failed to generate key image"); |
| 12640 | THROW_WALLET_EXCEPTION_IF(in_key->k_image != in_img, error::wallet_internal_error, "key image mismatch"); |
| 12641 | |
| 12642 | // get output pubkeys in the ring |
| 12643 | const std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key->key_offsets); |
| 12644 | const size_t ring_size = in_key->key_offsets.size(); |
| 12645 | THROW_WALLET_EXCEPTION_IF(absolute_offsets.size() != ring_size, error::wallet_internal_error, "absolute offsets size is wrong"); |
| 12646 | COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req); |
| 12647 | req.outputs.resize(ring_size); |
| 12648 | for (size_t j = 0; j < ring_size; ++j) |
| 12649 | { |
| 12650 | req.outputs[j].amount = in_key->amount; |
| 12651 | req.outputs[j].index = absolute_offsets[j]; |
| 12652 | } |
| 12653 | COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res); |
| 12654 | bool r; |
| 12655 | uint64_t pre_call_credits; |
| 12656 | { |
| 12657 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12658 | pre_call_credits = m_rpc_payment_state.credits; |
| 12659 | req.client = get_client_signature(); |
| 12660 | r = epee::net_utils::invoke_http_bin("/get_outs.bin", req, res, *m_http_client, rpc_timeout); |
| 12661 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "get_outs.bin", error::get_outs_error, res.status); |
| 12662 | THROW_WALLET_EXCEPTION_IF(res.outs.size() != ring_size, error::wallet_internal_error, |
| 12663 | "daemon returned wrong response for get_outs.bin, wrong amounts count = " + |
| 12664 | std::to_string(res.outs.size()) + ", expected " + std::to_string(ring_size)); |
| 12665 | check_rpc_cost("/get_outs.bin", res.credits, pre_call_credits, ring_size * COST_PER_OUT); |
| 12666 | } |
| 12667 | |
| 12668 | // copy pubkey pointers |
| 12669 | std::vector<const crypto::public_key *> p_output_keys; |
| 12670 | for (const COMMAND_RPC_GET_OUTPUTS_BIN::outkey &out : res.outs) |
| 12671 | p_output_keys.push_back(&out.key); |
| 12672 | |
| 12673 | // figure out real output index and secret key |
| 12674 | size_t sec_index = -1; |
| 12675 | for (size_t j = 0; j < ring_size; ++j) |
| 12676 | { |
| 12677 | if (res.outs[j].key == in_ephemeral.pub) |
| 12678 | { |
| 12679 | sec_index = j; |
| 12680 | break; |
| 12681 | } |
| 12682 | } |
| 12683 | THROW_WALLET_EXCEPTION_IF(sec_index >= ring_size, error::wallet_internal_error, "secret index not found"); |
| 12684 | |
| 12685 | // generate ring sig for this input |
| 12686 | signatures.push_back(std::vector<crypto::signature>()); |
| 12687 | std::vector<crypto::signature>& sigs = signatures.back(); |
| 12688 | sigs.resize(in_key->key_offsets.size()); |
| 12689 | crypto::generate_ring_signature(sig_prefix_hash, in_key->k_image, p_output_keys, in_ephemeral.sec, sec_index, sigs.data()); |
| 12690 | } |
| 12691 | |
| 12692 | std::string sig_str = "SpendProofV1"; |
| 12693 | for (const std::vector<crypto::signature>& ring_sig : signatures) |
| 12694 | for (const crypto::signature& sig : ring_sig) |
| 12695 | sig_str += tools::base58::encode(std::string((const char *)&sig, sizeof(crypto::signature))); |
| 12696 | return sig_str; |
| 12697 | } |
| 12698 | //---------------------------------------------------------------------------------------------------- |
| 12699 | bool wallet2::check_spend_proof(const crypto::hash &txid, const std::string &message, const std::string &sig_str) |
| 12700 | { |
| 12701 | const std::string header = "SpendProofV1"; |
| 12702 | const size_t header_len = header.size(); |
| 12703 | THROW_WALLET_EXCEPTION_IF(sig_str.size() < header_len || sig_str.substr(0, header_len) != header, error::wallet_internal_error, |
| 12704 | "Signature header check error"); |
| 12705 | |
| 12706 | // fetch tx from daemon |
| 12707 | COMMAND_RPC_GET_TRANSACTIONS::request req = AUTO_VAL_INIT(req); |
| 12708 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12709 | req.decode_as_json = false; |
| 12710 | req.prune = true; |
| 12711 | COMMAND_RPC_GET_TRANSACTIONS::response res = AUTO_VAL_INIT(res); |
| 12712 | bool r; |
| 12713 | uint64_t pre_call_credits; |
| 12714 | { |
| 12715 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12716 | pre_call_credits = m_rpc_payment_state.credits; |
| 12717 | req.client = get_client_signature(); |
| 12718 | r = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client, rpc_timeout); |
| 12719 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "gettransactions"); |
| 12720 | THROW_WALLET_EXCEPTION_IF(res.txs.size() != 1, error::wallet_internal_error, |
| 12721 | "daemon returned wrong response for gettransactions, wrong txs count = " + |
| 12722 | std::to_string(res.txs.size()) + ", expected 1"); |
| 12723 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 12724 | } |
| 12725 | |
| 12726 | cryptonote::transaction tx; |
| 12727 | crypto::hash tx_hash; |
| 12728 | THROW_WALLET_EXCEPTION_IF(!get_pruned_tx(res.txs[0], tx, tx_hash), error::wallet_internal_error, "failed to get tx from daemon"); |
| 12729 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 12730 | |
| 12731 | // check signature size |
| 12732 | size_t num_sigs = 0; |
| 12733 | for(size_t i = 0; i < tx.vin.size(); ++i) |
| 12734 | { |
| 12735 | const txin_to_key* const in_key = boost::get<txin_to_key>(std::addressof(tx.vin[i])); |
| 12736 | if (in_key != nullptr) |
| 12737 | num_sigs += in_key->key_offsets.size(); |
| 12738 | } |
| 12739 | std::vector<std::vector<crypto::signature>> signatures = { std::vector<crypto::signature>(1) }; |
| 12740 | const size_t sig_len = tools::base58::encode(std::string((const char *)&signatures[0][0], sizeof(crypto::signature))).size(); |
| 12741 | if( sig_str.size() != header_len + num_sigs * sig_len ) { |
| 12742 | return false; |
| 12743 | } |
| 12744 | |
| 12745 | // decode base58 |
| 12746 | signatures.clear(); |
| 12747 | size_t offset = header_len; |
| 12748 | for(size_t i = 0; i < tx.vin.size(); ++i) |
| 12749 | { |
| 12750 | const txin_to_key* const in_key = boost::get<txin_to_key>(std::addressof(tx.vin[i])); |
| 12751 | if (in_key == nullptr) |
| 12752 | continue; |
| 12753 | signatures.resize(signatures.size() + 1); |
| 12754 | signatures.back().resize(in_key->key_offsets.size()); |
| 12755 | for (size_t j = 0; j < in_key->key_offsets.size(); ++j) |
| 12756 | { |
| 12757 | std::string sig_decoded; |
| 12758 | THROW_WALLET_EXCEPTION_IF(!tools::base58::decode(sig_str.substr(offset, sig_len), sig_decoded), error::wallet_internal_error, "Signature decoding error"); |
| 12759 | THROW_WALLET_EXCEPTION_IF(sizeof(crypto::signature) != sig_decoded.size(), error::wallet_internal_error, "Signature decoding error"); |
| 12760 | memcpy(&signatures.back()[j], sig_decoded.data(), sizeof(crypto::signature)); |
| 12761 | offset += sig_len; |
| 12762 | } |
| 12763 | } |
| 12764 | |
| 12765 | // get signature prefix hash |
| 12766 | std::string sig_prefix_data((const char*)&txid, sizeof(crypto::hash)); |
| 12767 | sig_prefix_data += message; |
| 12768 | crypto::hash sig_prefix_hash; |
| 12769 | crypto::cn_fast_hash(sig_prefix_data.data(), sig_prefix_data.size(), sig_prefix_hash); |
| 12770 | |
| 12771 | std::vector<std::vector<crypto::signature>>::const_iterator sig_iter = signatures.cbegin(); |
| 12772 | for(size_t i = 0; i < tx.vin.size(); ++i) |
| 12773 | { |
| 12774 | const txin_to_key* const in_key = boost::get<txin_to_key>(std::addressof(tx.vin[i])); |
| 12775 | if (in_key == nullptr) |
| 12776 | continue; |
| 12777 | |
| 12778 | // get output pubkeys in the ring |
| 12779 | COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req); |
| 12780 | const std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key->key_offsets); |
| 12781 | req.outputs.resize(absolute_offsets.size()); |
| 12782 | for (size_t j = 0; j < absolute_offsets.size(); ++j) |
| 12783 | { |
| 12784 | req.outputs[j].amount = in_key->amount; |
| 12785 | req.outputs[j].index = absolute_offsets[j]; |
| 12786 | } |
| 12787 | COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res); |
| 12788 | bool r; |
| 12789 | uint64_t pre_call_credits; |
| 12790 | { |
| 12791 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12792 | pre_call_credits = m_rpc_payment_state.credits; |
| 12793 | req.client = get_client_signature(); |
| 12794 | r = epee::net_utils::invoke_http_bin("/get_outs.bin", req, res, *m_http_client, rpc_timeout); |
| 12795 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "get_outs.bin", error::get_outs_error, res.status); |
| 12796 | THROW_WALLET_EXCEPTION_IF(res.outs.size() != req.outputs.size(), error::wallet_internal_error, |
| 12797 | "daemon returned wrong response for get_outs.bin, wrong amounts count = " + |
| 12798 | std::to_string(res.outs.size()) + ", expected " + std::to_string(req.outputs.size())); |
| 12799 | check_rpc_cost("/get_outs.bin", res.credits, pre_call_credits, req.outputs.size() * COST_PER_OUT); |
| 12800 | } |
| 12801 | |
| 12802 | // copy pointers |
| 12803 | std::vector<const crypto::public_key *> p_output_keys; |
| 12804 | for (const COMMAND_RPC_GET_OUTPUTS_BIN::outkey &out : res.outs) |
| 12805 | p_output_keys.push_back(&out.key); |
| 12806 | |
| 12807 | // check this ring |
| 12808 | if (!crypto::check_ring_signature(sig_prefix_hash, in_key->k_image, p_output_keys, sig_iter->data())) |
| 12809 | return false; |
| 12810 | ++sig_iter; |
| 12811 | } |
| 12812 | THROW_WALLET_EXCEPTION_IF(sig_iter != signatures.cend(), error::wallet_internal_error, "Signature iterator didn't reach the end"); |
| 12813 | return true; |
| 12814 | } |
| 12815 | //---------------------------------------------------------------------------------------------------- |
| 12816 | |
| 12817 | void wallet2::check_tx_key(const crypto::hash &txid, const crypto::secret_key &tx_key, const std::vector<crypto::secret_key> &additional_tx_keys, const cryptonote::account_public_address &address, uint64_t &received, bool &in_pool, uint64_t &confirmations) |
| 12818 | { |
| 12819 | crypto::key_derivation derivation; |
| 12820 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(address.m_view_public_key, tx_key, derivation), error::wallet_internal_error, |
| 12821 | "Failed to generate key derivation from supplied parameters"); |
| 12822 | |
| 12823 | std::vector<crypto::key_derivation> additional_derivations; |
| 12824 | additional_derivations.resize(additional_tx_keys.size()); |
| 12825 | for (size_t i = 0; i < additional_tx_keys.size(); ++i) |
| 12826 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(address.m_view_public_key, additional_tx_keys[i], additional_derivations[i]), error::wallet_internal_error, |
| 12827 | "Failed to generate key derivation from supplied parameters"); |
| 12828 | |
| 12829 | check_tx_key_helper(txid, derivation, additional_derivations, address, received, in_pool, confirmations); |
| 12830 | } |
| 12831 | |
| 12832 | void wallet2::check_tx_key_helper(const cryptonote::transaction &tx, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, const cryptonote::account_public_address &address, uint64_t &received) const |
| 12833 | { |
| 12834 | received = 0; |
| 12835 | |
| 12836 | for (size_t n = 0; n < tx.vout.size(); ++n) |
| 12837 | { |
| 12838 | crypto::public_key output_public_key; |
| 12839 | if (!get_output_public_key(tx.vout[n], output_public_key)) |
| 12840 | continue; |
| 12841 | |
| 12842 | crypto::key_derivation found_derivation; |
| 12843 | if (is_out_to_acc(address, output_public_key, derivation, additional_derivations, n, get_output_view_tag(tx.vout[n]), found_derivation)) |
| 12844 | { |
| 12845 | uint64_t amount; |
| 12846 | if (tx.version == 1 || tx.rct_signatures.type == rct::RCTTypeNull) |
| 12847 | { |
| 12848 | amount = tx.vout[n].amount; |
| 12849 | } |
| 12850 | else |
| 12851 | { |
| 12852 | rct::key mask; |
| 12853 | amount = decodeRct(tx.rct_signatures, found_derivation, n, mask, hw::get_device("default")); |
| 12854 | } |
| 12855 | received += amount; |
| 12856 | } |
| 12857 | } |
| 12858 | } |
| 12859 | |
| 12860 | void wallet2::check_tx_key_helper(const crypto::hash &txid, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, const cryptonote::account_public_address &address, uint64_t &received, bool &in_pool, uint64_t &confirmations) |
| 12861 | { |
| 12862 | uint32_t rpc_version; |
| 12863 | THROW_WALLET_EXCEPTION_IF(!check_connection(&rpc_version), error::wallet_internal_error, "Failed to connect to daemon: " + get_daemon_address()); |
| 12864 | |
| 12865 | COMMAND_RPC_GET_TRANSACTIONS::request req; |
| 12866 | COMMAND_RPC_GET_TRANSACTIONS::response res; |
| 12867 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12868 | req.decode_as_json = false; |
| 12869 | req.prune = true; |
| 12870 | |
| 12871 | bool ok; |
| 12872 | { |
| 12873 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12874 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 12875 | req.client = get_client_signature(); |
| 12876 | ok = epee::net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client); |
| 12877 | THROW_WALLET_EXCEPTION_IF(!ok || res.txs.size() != 1, |
| 12878 | error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 12879 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 12880 | } |
| 12881 | |
| 12882 | cryptonote::transaction tx; |
| 12883 | crypto::hash tx_hash; |
| 12884 | ok = get_pruned_tx(res.txs.front(), tx, tx_hash); |
| 12885 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to parse transaction from daemon"); |
| 12886 | |
| 12887 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, |
| 12888 | "Failed to get the right transaction from daemon"); |
| 12889 | THROW_WALLET_EXCEPTION_IF(!additional_derivations.empty() && additional_derivations.size() != tx.vout.size(), error::wallet_internal_error, |
| 12890 | "The size of additional derivations is wrong"); |
| 12891 | |
| 12892 | check_tx_key_helper(tx, derivation, additional_derivations, address, received); |
| 12893 | |
| 12894 | in_pool = res.txs.front().in_pool; |
| 12895 | confirmations = 0; |
| 12896 | if (!in_pool) |
| 12897 | { |
| 12898 | if (rpc_version < MAKE_CORE_RPC_VERSION(3, 7)) |
| 12899 | { |
| 12900 | std::string err; |
| 12901 | uint64_t bc_height = get_daemon_blockchain_height(err); |
| 12902 | if (err.empty() && bc_height > res.txs.front().block_height) |
| 12903 | confirmations = bc_height - res.txs.front().block_height; |
| 12904 | } |
| 12905 | else |
| 12906 | { |
| 12907 | confirmations = res.txs.front().confirmations; |
| 12908 | } |
| 12909 | } |
| 12910 | } |
| 12911 | |
| 12912 | bool wallet2::is_out_to_acc(const cryptonote::account_public_address &address, const crypto::public_key& out_key, const crypto::key_derivation &derivation, const std::vector<crypto::key_derivation> &additional_derivations, const size_t output_index, const boost::optional<crypto::view_tag> &view_tag_opt, crypto::key_derivation &found_derivation) const |
| 12913 | { |
| 12914 | crypto::public_key derived_out_key; |
| 12915 | bool found = false; |
| 12916 | bool r; |
| 12917 | // first run quick check if output has matching view tag, otherwise output should not belong to account |
| 12918 | if (out_can_be_to_acc(view_tag_opt, derivation, output_index)) |
| 12919 | { |
| 12920 | // if view tag match, run slower check deriving output pub key and comparing to expected |
| 12921 | r = crypto::derive_public_key(derivation, output_index, address.m_spend_public_key, derived_out_key); |
| 12922 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to derive public key"); |
| 12923 | if (out_key == derived_out_key) |
| 12924 | { |
| 12925 | found = true; |
| 12926 | found_derivation = derivation; |
| 12927 | } |
| 12928 | } |
| 12929 | |
| 12930 | if (!found && !additional_derivations.empty()) |
| 12931 | { |
| 12932 | const crypto::key_derivation &additional_derivation = additional_derivations[output_index]; |
| 12933 | if (out_can_be_to_acc(view_tag_opt, additional_derivation, output_index)) |
| 12934 | { |
| 12935 | r = crypto::derive_public_key(additional_derivation, output_index, address.m_spend_public_key, derived_out_key); |
| 12936 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to derive public key"); |
| 12937 | if (out_key == derived_out_key) |
| 12938 | { |
| 12939 | found = true; |
| 12940 | found_derivation = additional_derivation; |
| 12941 | } |
| 12942 | } |
| 12943 | } |
| 12944 | |
| 12945 | return found; |
| 12946 | } |
| 12947 | |
| 12948 | std::string wallet2::get_tx_proof(const crypto::hash &txid, const cryptonote::account_public_address &address, bool is_subaddress, const std::string &message) |
| 12949 | { |
| 12950 | // fetch tx pubkey from the daemon |
| 12951 | COMMAND_RPC_GET_TRANSACTIONS::request req; |
| 12952 | COMMAND_RPC_GET_TRANSACTIONS::response res; |
| 12953 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 12954 | req.decode_as_json = false; |
| 12955 | req.prune = true; |
| 12956 | |
| 12957 | bool ok; |
| 12958 | { |
| 12959 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 12960 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 12961 | req.client = get_client_signature(); |
| 12962 | ok = net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client); |
| 12963 | THROW_WALLET_EXCEPTION_IF(!ok || res.txs.size() != 1, |
| 12964 | error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 12965 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 12966 | } |
| 12967 | |
| 12968 | cryptonote::transaction tx; |
| 12969 | crypto::hash tx_hash; |
| 12970 | ok = get_pruned_tx(res.txs.front(), tx, tx_hash); |
| 12971 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to parse transaction from daemon"); |
| 12972 | |
| 12973 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 12974 | |
| 12975 | // determine if the address is found in the subaddress hash table (i.e. whether the proof is outbound or inbound) |
| 12976 | crypto::secret_key tx_key = crypto::null_skey; |
| 12977 | std::vector<crypto::secret_key> additional_tx_keys; |
| 12978 | const bool is_out = m_subaddresses.count(address.m_spend_public_key) == 0; |
| 12979 | if (is_out) |
| 12980 | { |
| 12981 | THROW_WALLET_EXCEPTION_IF(!get_tx_key(txid, tx_key, additional_tx_keys), error::wallet_internal_error, "Tx secret key wasn't found in the wallet file."); |
| 12982 | } |
| 12983 | |
| 12984 | return get_tx_proof(tx, tx_key, additional_tx_keys, address, is_subaddress, message); |
| 12985 | } |
| 12986 | |
| 12987 | std::string wallet2::get_tx_proof(const cryptonote::transaction &tx, const crypto::secret_key &tx_key, const std::vector<crypto::secret_key> &additional_tx_keys, const cryptonote::account_public_address &address, bool is_subaddress, const std::string &message) const |
| 12988 | { |
| 12989 | hw::device &hwdev = m_account.get_device(); |
| 12990 | rct::key aP; |
| 12991 | // determine if the address is found in the subaddress hash table (i.e. whether the proof is outbound or inbound) |
| 12992 | const bool is_out = m_subaddresses.count(address.m_spend_public_key) == 0; |
| 12993 | |
| 12994 | const crypto::hash txid = cryptonote::get_transaction_hash(tx); |
| 12995 | std::string prefix_data((const char*)&txid, sizeof(crypto::hash)); |
| 12996 | prefix_data += message; |
| 12997 | crypto::hash prefix_hash; |
| 12998 | crypto::cn_fast_hash(prefix_data.data(), prefix_data.size(), prefix_hash); |
| 12999 | |
| 13000 | std::vector<crypto::public_key> shared_secret; |
| 13001 | std::vector<crypto::signature> sig; |
| 13002 | std::string sig_str; |
| 13003 | if (is_out) |
| 13004 | { |
| 13005 | const size_t num_sigs = 1 + additional_tx_keys.size(); |
| 13006 | shared_secret.resize(num_sigs); |
| 13007 | sig.resize(num_sigs); |
| 13008 | |
| 13009 | hwdev.scalarmultKey(aP, rct::pk2rct(address.m_view_public_key), rct::sk2rct(tx_key)); |
| 13010 | shared_secret[0] = rct::rct2pk(aP); |
| 13011 | crypto::public_key tx_pub_key; |
| 13012 | if (is_subaddress) |
| 13013 | { |
| 13014 | hwdev.scalarmultKey(aP, rct::pk2rct(address.m_spend_public_key), rct::sk2rct(tx_key)); |
| 13015 | tx_pub_key = rct2pk(aP); |
| 13016 | hwdev.generate_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, address.m_spend_public_key, shared_secret[0], tx_key, sig[0]); |
| 13017 | } |
| 13018 | else |
| 13019 | { |
| 13020 | hwdev.secret_key_to_public_key(tx_key, tx_pub_key); |
| 13021 | hwdev.generate_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, boost::none, shared_secret[0], tx_key, sig[0]); |
| 13022 | } |
| 13023 | for (size_t i = 1; i < num_sigs; ++i) |
| 13024 | { |
| 13025 | hwdev.scalarmultKey(aP, rct::pk2rct(address.m_view_public_key), rct::sk2rct(additional_tx_keys[i - 1])); |
| 13026 | shared_secret[i] = rct::rct2pk(aP); |
| 13027 | if (is_subaddress) |
| 13028 | { |
| 13029 | hwdev.scalarmultKey(aP, rct::pk2rct(address.m_spend_public_key), rct::sk2rct(additional_tx_keys[i - 1])); |
| 13030 | tx_pub_key = rct2pk(aP); |
| 13031 | hwdev.generate_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, address.m_spend_public_key, shared_secret[i], additional_tx_keys[i - 1], sig[i]); |
| 13032 | } |
| 13033 | else |
| 13034 | { |
| 13035 | hwdev.secret_key_to_public_key(additional_tx_keys[i - 1], tx_pub_key); |
| 13036 | hwdev.generate_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, boost::none, shared_secret[i], additional_tx_keys[i - 1], sig[i]); |
| 13037 | } |
| 13038 | } |
| 13039 | sig_str = std::string("OutProofV2"); |
| 13040 | } |
| 13041 | else |
| 13042 | { |
| 13043 | crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); |
| 13044 | THROW_WALLET_EXCEPTION_IF(tx_pub_key == null_pkey, error::wallet_internal_error, "Tx pubkey was not found"); |
| 13045 | |
| 13046 | std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); |
| 13047 | const size_t num_sigs = 1 + additional_tx_pub_keys.size(); |
| 13048 | shared_secret.resize(num_sigs); |
| 13049 | sig.resize(num_sigs); |
| 13050 | |
| 13051 | const crypto::secret_key& a = m_account.get_keys().m_view_secret_key; |
| 13052 | hwdev.scalarmultKey(aP, rct::pk2rct(tx_pub_key), rct::sk2rct(a)); |
| 13053 | shared_secret[0] = rct2pk(aP); |
| 13054 | if (is_subaddress) |
| 13055 | { |
| 13056 | hwdev.generate_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, address.m_spend_public_key, shared_secret[0], a, sig[0]); |
| 13057 | } |
| 13058 | else |
| 13059 | { |
| 13060 | hwdev.generate_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, boost::none, shared_secret[0], a, sig[0]); |
| 13061 | } |
| 13062 | for (size_t i = 1; i < num_sigs; ++i) |
| 13063 | { |
| 13064 | hwdev.scalarmultKey(aP,rct::pk2rct(additional_tx_pub_keys[i - 1]), rct::sk2rct(a)); |
| 13065 | shared_secret[i] = rct2pk(aP); |
| 13066 | if (is_subaddress) |
| 13067 | { |
| 13068 | hwdev.generate_tx_proof(prefix_hash, address.m_view_public_key, additional_tx_pub_keys[i - 1], address.m_spend_public_key, shared_secret[i], a, sig[i]); |
| 13069 | } |
| 13070 | else |
| 13071 | { |
| 13072 | hwdev.generate_tx_proof(prefix_hash, address.m_view_public_key, additional_tx_pub_keys[i - 1], boost::none, shared_secret[i], a, sig[i]); |
| 13073 | } |
| 13074 | } |
| 13075 | sig_str = std::string("InProofV2"); |
| 13076 | } |
| 13077 | const size_t num_sigs = shared_secret.size(); |
| 13078 | |
| 13079 | // check if this address actually received any funds |
| 13080 | crypto::key_derivation derivation; |
| 13081 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(shared_secret[0], rct::rct2sk(rct::I), derivation), error::wallet_internal_error, "Failed to generate key derivation"); |
| 13082 | std::vector<crypto::key_derivation> additional_derivations(num_sigs - 1); |
| 13083 | for (size_t i = 1; i < num_sigs; ++i) |
| 13084 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(shared_secret[i], rct::rct2sk(rct::I), additional_derivations[i - 1]), error::wallet_internal_error, "Failed to generate key derivation"); |
| 13085 | uint64_t received; |
| 13086 | check_tx_key_helper(tx, derivation, additional_derivations, address, received); |
| 13087 | THROW_WALLET_EXCEPTION_IF(!received, error::wallet_internal_error, tr("No funds received in this tx.")); |
| 13088 | |
| 13089 | // concatenate all signature strings |
| 13090 | for (size_t i = 0; i < num_sigs; ++i) |
| 13091 | sig_str += |
| 13092 | tools::base58::encode(std::string((const char *)&shared_secret[i], sizeof(crypto::public_key))) + |
| 13093 | tools::base58::encode(std::string((const char *)&sig[i], sizeof(crypto::signature))); |
| 13094 | return sig_str; |
| 13095 | } |
| 13096 | |
| 13097 | bool wallet2::check_tx_proof(const crypto::hash &txid, const cryptonote::account_public_address &address, bool is_subaddress, const std::string &message, const std::string &sig_str, uint64_t &received, bool &in_pool, uint64_t &confirmations) |
| 13098 | { |
| 13099 | // fetch tx pubkey from the daemon |
| 13100 | COMMAND_RPC_GET_TRANSACTIONS::request req; |
| 13101 | COMMAND_RPC_GET_TRANSACTIONS::response res; |
| 13102 | req.txs_hashes.push_back(epee::string_tools::pod_to_hex(txid)); |
| 13103 | req.decode_as_json = false; |
| 13104 | req.prune = true; |
| 13105 | |
| 13106 | bool ok; |
| 13107 | { |
| 13108 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 13109 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 13110 | req.client = get_client_signature(); |
| 13111 | ok = net_utils::invoke_http_json("/gettransactions", req, res, *m_http_client); |
| 13112 | THROW_WALLET_EXCEPTION_IF(!ok || res.txs.size() != 1, |
| 13113 | error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 13114 | check_rpc_cost("/gettransactions", res.credits, pre_call_credits, COST_PER_TX); |
| 13115 | } |
| 13116 | |
| 13117 | cryptonote::transaction tx; |
| 13118 | crypto::hash tx_hash; |
| 13119 | ok = get_pruned_tx(res.txs.front(), tx, tx_hash); |
| 13120 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to parse transaction from daemon"); |
| 13121 | |
| 13122 | THROW_WALLET_EXCEPTION_IF(tx_hash != txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 13123 | |
| 13124 | if (!check_tx_proof(tx, address, is_subaddress, message, sig_str, received)) |
| 13125 | return false; |
| 13126 | |
| 13127 | in_pool = res.txs.front().in_pool; |
| 13128 | confirmations = 0; |
| 13129 | if (!in_pool) |
| 13130 | { |
| 13131 | std::string err; |
| 13132 | uint64_t bc_height = get_daemon_blockchain_height(err); |
| 13133 | if (err.empty() && bc_height > res.txs.front().block_height) |
| 13134 | confirmations = bc_height - res.txs.front().block_height; |
| 13135 | } |
| 13136 | |
| 13137 | return true; |
| 13138 | } |
| 13139 | |
| 13140 | bool wallet2::check_tx_proof(const cryptonote::transaction &tx, const cryptonote::account_public_address &address, bool is_subaddress, const std::string &message, const std::string &sig_str, uint64_t &received) const |
| 13141 | { |
| 13142 | // InProofV1, InProofV2, OutProofV1, OutProofV2 |
| 13143 | const bool is_out = sig_str.substr(0, 3) == "Out"; |
| 13144 | const std::string header = is_out ? sig_str.substr(0,10) : sig_str.substr(0,9); |
| 13145 | int version = 2; // InProofV2 |
| 13146 | if (is_out && sig_str.substr(8,2) == "V1") version = 1; // OutProofV1 |
| 13147 | else if (is_out) version = 2; // OutProofV2 |
| 13148 | else if (sig_str.substr(7,2) == "V1") version = 1; // InProofV1 |
| 13149 | |
| 13150 | const size_t header_len = header.size(); |
| 13151 | THROW_WALLET_EXCEPTION_IF(sig_str.size() < header_len || sig_str.substr(0, header_len) != header, error::wallet_internal_error, |
| 13152 | "Signature header check error"); |
| 13153 | |
| 13154 | // decode base58 |
| 13155 | std::vector<crypto::public_key> shared_secret(1); |
| 13156 | std::vector<crypto::signature> sig(1); |
| 13157 | const size_t pk_len = tools::base58::encode(std::string((const char *)&shared_secret[0], sizeof(crypto::public_key))).size(); |
| 13158 | const size_t sig_len = tools::base58::encode(std::string((const char *)&sig[0], sizeof(crypto::signature))).size(); |
| 13159 | const size_t num_sigs = (sig_str.size() - header_len) / (pk_len + sig_len); |
| 13160 | THROW_WALLET_EXCEPTION_IF(sig_str.size() != header_len + num_sigs * (pk_len + sig_len), error::wallet_internal_error, |
| 13161 | "Wrong signature size"); |
| 13162 | shared_secret.resize(num_sigs); |
| 13163 | sig.resize(num_sigs); |
| 13164 | for (size_t i = 0; i < num_sigs; ++i) |
| 13165 | { |
| 13166 | std::string pk_decoded; |
| 13167 | std::string sig_decoded; |
| 13168 | const size_t offset = header_len + i * (pk_len + sig_len); |
| 13169 | THROW_WALLET_EXCEPTION_IF(!tools::base58::decode(sig_str.substr(offset, pk_len), pk_decoded), error::wallet_internal_error, |
| 13170 | "Signature decoding error"); |
| 13171 | THROW_WALLET_EXCEPTION_IF(!tools::base58::decode(sig_str.substr(offset + pk_len, sig_len), sig_decoded), error::wallet_internal_error, |
| 13172 | "Signature decoding error"); |
| 13173 | THROW_WALLET_EXCEPTION_IF(sizeof(crypto::public_key) != pk_decoded.size() || sizeof(crypto::signature) != sig_decoded.size(), error::wallet_internal_error, |
| 13174 | "Signature decoding error"); |
| 13175 | memcpy(&shared_secret[i], pk_decoded.data(), sizeof(crypto::public_key)); |
| 13176 | memcpy(&sig[i], sig_decoded.data(), sizeof(crypto::signature)); |
| 13177 | } |
| 13178 | |
| 13179 | crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); |
| 13180 | THROW_WALLET_EXCEPTION_IF(tx_pub_key == null_pkey, error::wallet_internal_error, "Tx pubkey was not found"); |
| 13181 | |
| 13182 | std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); |
| 13183 | THROW_WALLET_EXCEPTION_IF(additional_tx_pub_keys.size() + 1 != num_sigs, error::wallet_internal_error, "Signature size mismatch with additional tx pubkeys"); |
| 13184 | |
| 13185 | const crypto::hash txid = cryptonote::get_transaction_hash(tx); |
| 13186 | std::string prefix_data((const char*)&txid, sizeof(crypto::hash)); |
| 13187 | prefix_data += message; |
| 13188 | crypto::hash prefix_hash; |
| 13189 | crypto::cn_fast_hash(prefix_data.data(), prefix_data.size(), prefix_hash); |
| 13190 | |
| 13191 | // check signature |
| 13192 | std::vector<int> good_signature(num_sigs, 0); |
| 13193 | if (is_out) |
| 13194 | { |
| 13195 | good_signature[0] = is_subaddress ? |
| 13196 | crypto::check_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, address.m_spend_public_key, shared_secret[0], sig[0], version) : |
| 13197 | crypto::check_tx_proof(prefix_hash, tx_pub_key, address.m_view_public_key, boost::none, shared_secret[0], sig[0], version); |
| 13198 | |
| 13199 | for (size_t i = 0; i < additional_tx_pub_keys.size(); ++i) |
| 13200 | { |
| 13201 | good_signature[i + 1] = is_subaddress ? |
| 13202 | crypto::check_tx_proof(prefix_hash, additional_tx_pub_keys[i], address.m_view_public_key, address.m_spend_public_key, shared_secret[i + 1], sig[i + 1], version) : |
| 13203 | crypto::check_tx_proof(prefix_hash, additional_tx_pub_keys[i], address.m_view_public_key, boost::none, shared_secret[i + 1], sig[i + 1], version); |
| 13204 | } |
| 13205 | } |
| 13206 | else |
| 13207 | { |
| 13208 | good_signature[0] = is_subaddress ? |
| 13209 | crypto::check_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, address.m_spend_public_key, shared_secret[0], sig[0], version) : |
| 13210 | crypto::check_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, boost::none, shared_secret[0], sig[0], version); |
| 13211 | |
| 13212 | for (size_t i = 0; i < additional_tx_pub_keys.size(); ++i) |
| 13213 | { |
| 13214 | good_signature[i + 1] = is_subaddress ? |
| 13215 | crypto::check_tx_proof(prefix_hash, address.m_view_public_key, additional_tx_pub_keys[i], address.m_spend_public_key, shared_secret[i + 1], sig[i + 1], version) : |
| 13216 | crypto::check_tx_proof(prefix_hash, address.m_view_public_key, additional_tx_pub_keys[i], boost::none, shared_secret[i + 1], sig[i + 1], version); |
| 13217 | } |
| 13218 | } |
| 13219 | |
| 13220 | if (std::any_of(good_signature.begin(), good_signature.end(), [](int i) { return i > 0; })) |
| 13221 | { |
| 13222 | // obtain key derivation by multiplying scalar 1 to the shared secret |
| 13223 | crypto::key_derivation derivation; |
| 13224 | if (good_signature[0]) |
| 13225 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(shared_secret[0], rct::rct2sk(rct::I), derivation), error::wallet_internal_error, "Failed to generate key derivation"); |
| 13226 | |
| 13227 | std::vector<crypto::key_derivation> additional_derivations(num_sigs - 1); |
| 13228 | for (size_t i = 1; i < num_sigs; ++i) |
| 13229 | if (good_signature[i]) |
| 13230 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(shared_secret[i], rct::rct2sk(rct::I), additional_derivations[i - 1]), error::wallet_internal_error, "Failed to generate key derivation"); |
| 13231 | |
| 13232 | check_tx_key_helper(tx, derivation, additional_derivations, address, received); |
| 13233 | return true; |
| 13234 | } |
| 13235 | return false; |
| 13236 | } |
| 13237 | |
| 13238 | std::string wallet2::get_reserve_proof(const boost::optional<std::pair<uint32_t, uint64_t>> &account_minreserve, const std::string &message) |
| 13239 | { |
| 13240 | THROW_WALLET_EXCEPTION_IF(m_watch_only || m_multisig, error::wallet_internal_error, "Reserve proof can only be generated by a full wallet"); |
| 13241 | THROW_WALLET_EXCEPTION_IF(balance_all(true) == 0, error::wallet_internal_error, "Zero balance"); |
| 13242 | THROW_WALLET_EXCEPTION_IF(account_minreserve && balance(account_minreserve->first, true) < account_minreserve->second, error::wallet_internal_error, |
| 13243 | "Not enough balance in this account for the requested minimum reserve amount"); |
| 13244 | |
| 13245 | // determine which outputs to include in the proof |
| 13246 | std::vector<size_t> selected_transfers; |
| 13247 | for (size_t i = 0; i < m_transfers.size(); ++i) |
| 13248 | { |
| 13249 | const transfer_details &td = m_transfers[i]; |
| 13250 | if (!is_spent(td, true) && !td.m_frozen && (!account_minreserve || account_minreserve->first == td.m_subaddr_index.major)) |
| 13251 | selected_transfers.push_back(i); |
| 13252 | } |
| 13253 | |
| 13254 | if (account_minreserve) |
| 13255 | { |
| 13256 | THROW_WALLET_EXCEPTION_IF(account_minreserve->second == 0, error::wallet_internal_error, "Proved amount must be greater than 0"); |
| 13257 | // minimize the number of outputs included in the proof, by only picking the N largest outputs that can cover the requested min reserve amount |
| 13258 | std::sort(selected_transfers.begin(), selected_transfers.end(), [&](const size_t a, const size_t b) |
| 13259 | { return m_transfers[a].amount() > m_transfers[b].amount(); }); |
| 13260 | while (selected_transfers.size() >= 2 && m_transfers[selected_transfers[1]].amount() >= account_minreserve->second) |
| 13261 | selected_transfers.erase(selected_transfers.begin()); |
| 13262 | size_t sz = 0; |
| 13263 | uint64_t total = 0; |
| 13264 | while (total < account_minreserve->second) |
| 13265 | { |
| 13266 | total += m_transfers[selected_transfers[sz]].amount(); |
| 13267 | ++sz; |
| 13268 | } |
| 13269 | selected_transfers.resize(sz); |
| 13270 | } |
| 13271 | |
| 13272 | // compute signature prefix hash |
| 13273 | std::string prefix_data = message; |
| 13274 | prefix_data.append((const char*)&m_account.get_keys().m_account_address, sizeof(cryptonote::account_public_address)); |
| 13275 | for (size_t i = 0; i < selected_transfers.size(); ++i) |
| 13276 | { |
| 13277 | prefix_data.append((const char*)&m_transfers[selected_transfers[i]].m_key_image, sizeof(crypto::key_image)); |
| 13278 | } |
| 13279 | crypto::hash prefix_hash; |
| 13280 | crypto::cn_fast_hash(prefix_data.data(), prefix_data.size(), prefix_hash); |
| 13281 | |
| 13282 | // generate proof entries |
| 13283 | std::vector<reserve_proof_entry> proofs(selected_transfers.size()); |
| 13284 | std::unordered_set<cryptonote::subaddress_index> subaddr_indices = { {0,0} }; |
| 13285 | for (size_t i = 0; i < selected_transfers.size(); ++i) |
| 13286 | { |
| 13287 | const transfer_details &td = m_transfers[selected_transfers[i]]; |
| 13288 | reserve_proof_entry& proof = proofs[i]; |
| 13289 | proof.txid = td.m_txid; |
| 13290 | proof.index_in_tx = td.m_internal_output_index; |
| 13291 | proof.key_image = td.m_key_image; |
| 13292 | subaddr_indices.insert(td.m_subaddr_index); |
| 13293 | |
| 13294 | // get tx pub key |
| 13295 | const crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(td.m_tx, td.m_pk_index); |
| 13296 | THROW_WALLET_EXCEPTION_IF(tx_pub_key == crypto::null_pkey, error::wallet_internal_error, "The tx public key isn't found"); |
| 13297 | const std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 13298 | |
| 13299 | // determine which tx pub key was used for deriving the output key |
| 13300 | const crypto::public_key *tx_pub_key_used = &tx_pub_key; |
| 13301 | for (int i = 0; i < 2; ++i) |
| 13302 | { |
| 13303 | proof.shared_secret = rct::rct2pk(rct::scalarmultKey(rct::pk2rct(*tx_pub_key_used), rct::sk2rct(m_account.get_keys().m_view_secret_key))); |
| 13304 | crypto::key_derivation derivation; |
| 13305 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(proof.shared_secret, rct::rct2sk(rct::I), derivation), |
| 13306 | error::wallet_internal_error, "Failed to generate key derivation"); |
| 13307 | crypto::public_key subaddress_spendkey; |
| 13308 | THROW_WALLET_EXCEPTION_IF(!derive_subaddress_public_key(td.get_public_key(), derivation, proof.index_in_tx, subaddress_spendkey), |
| 13309 | error::wallet_internal_error, "Failed to derive subaddress public key"); |
| 13310 | if (m_subaddresses.count(subaddress_spendkey) == 1) |
| 13311 | break; |
| 13312 | THROW_WALLET_EXCEPTION_IF(additional_tx_pub_keys.empty(), error::wallet_internal_error, |
| 13313 | "Normal tx pub key doesn't derive the expected output, while the additional tx pub keys are empty"); |
| 13314 | THROW_WALLET_EXCEPTION_IF(i == 1, error::wallet_internal_error, |
| 13315 | "Neither normal tx pub key nor additional tx pub key derive the expected output key"); |
| 13316 | tx_pub_key_used = &additional_tx_pub_keys[proof.index_in_tx]; |
| 13317 | } |
| 13318 | |
| 13319 | // generate signature for shared secret |
| 13320 | crypto::generate_tx_proof(prefix_hash, m_account.get_keys().m_account_address.m_view_public_key, *tx_pub_key_used, boost::none, proof.shared_secret, m_account.get_keys().m_view_secret_key, proof.shared_secret_sig); |
| 13321 | |
| 13322 | // derive ephemeral secret key |
| 13323 | crypto::key_image ki; |
| 13324 | cryptonote::keypair ephemeral; |
| 13325 | const bool r = cryptonote::generate_key_image_helper(m_account.get_keys(), m_subaddresses, td.get_public_key(), tx_pub_key, additional_tx_pub_keys, td.m_internal_output_index, ephemeral, ki, m_account.get_device()); |
| 13326 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 13327 | THROW_WALLET_EXCEPTION_IF(ephemeral.pub != td.get_public_key(), error::wallet_internal_error, "Derived public key doesn't agree with the stored one"); |
| 13328 | |
| 13329 | // generate signature for key image |
| 13330 | const std::vector<const crypto::public_key*> pubs = { &ephemeral.pub }; |
| 13331 | crypto::generate_ring_signature(prefix_hash, td.m_key_image, &pubs[0], 1, ephemeral.sec, 0, &proof.key_image_sig); |
| 13332 | } |
| 13333 | |
| 13334 | // collect all subaddress spend keys that received those outputs and generate their signatures |
| 13335 | serializable_unordered_map<crypto::public_key, crypto::signature> subaddr_spendkeys; |
| 13336 | for (const cryptonote::subaddress_index &index : subaddr_indices) |
| 13337 | { |
| 13338 | crypto::secret_key subaddr_spend_skey = m_account.get_keys().m_spend_secret_key; |
| 13339 | if (!index.is_zero()) |
| 13340 | { |
| 13341 | crypto::secret_key m = m_account.get_device().get_subaddress_secret_key(m_account.get_keys().m_view_secret_key, index); |
| 13342 | crypto::secret_key tmp = subaddr_spend_skey; |
| 13343 | sc_add((unsigned char*)&subaddr_spend_skey, (unsigned char*)&m, (unsigned char*)&tmp); |
| 13344 | } |
| 13345 | crypto::public_key subaddr_spend_pkey; |
| 13346 | secret_key_to_public_key(subaddr_spend_skey, subaddr_spend_pkey); |
| 13347 | crypto::generate_signature(prefix_hash, subaddr_spend_pkey, subaddr_spend_skey, subaddr_spendkeys[subaddr_spend_pkey]); |
| 13348 | } |
| 13349 | |
| 13350 | // serialize & encode |
| 13351 | std::ostringstream oss; |
| 13352 | binary_archive<true> ar(oss); |
| 13353 | THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, proofs), error::wallet_internal_error, "Failed to serialize proof"); |
| 13354 | THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, subaddr_spendkeys), error::wallet_internal_error, "Failed to serialize proof"); |
| 13355 | return "ReserveProofV2" + tools::base58::encode(oss.str()); |
| 13356 | } |
| 13357 | |
| 13358 | bool wallet2::check_reserve_proof(const cryptonote::account_public_address &address, const std::string &message, const std::string &sig_str, uint64_t &total, uint64_t &spent) |
| 13359 | { |
| 13360 | uint32_t rpc_version; |
| 13361 | THROW_WALLET_EXCEPTION_IF(!check_connection(&rpc_version), error::wallet_internal_error, "Failed to connect to daemon: " + get_daemon_address()); |
| 13362 | THROW_WALLET_EXCEPTION_IF(rpc_version < MAKE_CORE_RPC_VERSION(1, 0), error::wallet_internal_error, "Daemon RPC version is too old"); |
| 13363 | |
| 13364 | static constexpr char header_v1[] = "ReserveProofV1"; |
| 13365 | static constexpr char header_v2[] = "ReserveProofV2"; // assumes same length as header_v1 |
| 13366 | THROW_WALLET_EXCEPTION_IF(!boost::string_ref{sig_str}.starts_with(header_v1) && !boost::string_ref{sig_str}.starts_with(header_v2), error::wallet_internal_error, |
| 13367 | "Signature header check error"); |
| 13368 | int version = 2; // assume newest version |
| 13369 | if (boost::string_ref{sig_str}.starts_with(header_v1)) |
| 13370 | version = 1; |
| 13371 | else if (boost::string_ref{sig_str}.starts_with(header_v2)) |
| 13372 | version = 2; |
| 13373 | |
| 13374 | std::string sig_decoded; |
| 13375 | THROW_WALLET_EXCEPTION_IF(!tools::base58::decode(sig_str.substr(std::strlen(header_v1)), sig_decoded), error::wallet_internal_error, |
| 13376 | "Signature decoding error"); |
| 13377 | |
| 13378 | bool loaded = false; |
| 13379 | std::vector<reserve_proof_entry> proofs; |
| 13380 | serializable_unordered_map<crypto::public_key, crypto::signature> subaddr_spendkeys; |
| 13381 | try |
| 13382 | { |
| 13383 | binary_archive<false> ar{epee::strspan<std::uint8_t>(sig_decoded)}; |
| 13384 | if (::serialization::serialize_noeof(ar, proofs)) |
| 13385 | if (::serialization::serialize_noeof(ar, subaddr_spendkeys)) |
| 13386 | if (::serialization::check_stream_state(ar)) |
| 13387 | loaded = true; |
| 13388 | } |
| 13389 | catch(...) {} |
| 13390 | try |
| 13391 | { |
| 13392 | if (!loaded && m_load_deprecated_formats) |
| 13393 | { |
| 13394 | std::istringstream iss(sig_decoded); |
| 13395 | boost::archive::portable_binary_iarchive ar(iss); |
| 13396 | ar >> proofs >> subaddr_spendkeys.parent(); |
| 13397 | loaded = true; |
| 13398 | } |
| 13399 | } |
| 13400 | catch(...) {} |
| 13401 | |
| 13402 | THROW_WALLET_EXCEPTION_IF(!loaded, error::wallet_internal_error, "Failed to parse reserve proof signature data"); |
| 13403 | |
| 13404 | std::unordered_set<crypto::key_image> seen_key_images; |
| 13405 | std::set<std::pair<crypto::hash, uint64_t>> seen_outputs; |
| 13406 | for (const reserve_proof_entry &proof : proofs) |
| 13407 | { |
| 13408 | THROW_WALLET_EXCEPTION_IF(!seen_key_images.insert(proof.key_image).second, error::wallet_internal_error, "Duplicate key image in reserve proof"); |
| 13409 | THROW_WALLET_EXCEPTION_IF(!seen_outputs.emplace(proof.txid, proof.index_in_tx).second, error::wallet_internal_error, "Duplicate output in reserve proof"); |
| 13410 | } |
| 13411 | |
| 13412 | THROW_WALLET_EXCEPTION_IF(subaddr_spendkeys.count(address.m_spend_public_key) == 0, error::wallet_internal_error, |
| 13413 | "The given address isn't found in the proof"); |
| 13414 | |
| 13415 | // compute signature prefix hash |
| 13416 | std::string prefix_data = message; |
| 13417 | prefix_data.append((const char*)&address, sizeof(cryptonote::account_public_address)); |
| 13418 | for (size_t i = 0; i < proofs.size(); ++i) |
| 13419 | { |
| 13420 | prefix_data.append((const char*)&proofs[i].key_image, sizeof(crypto::key_image)); |
| 13421 | } |
| 13422 | crypto::hash prefix_hash; |
| 13423 | crypto::cn_fast_hash(prefix_data.data(), prefix_data.size(), prefix_hash); |
| 13424 | |
| 13425 | // fetch txes from daemon |
| 13426 | COMMAND_RPC_GET_TRANSACTIONS::request gettx_req; |
| 13427 | COMMAND_RPC_GET_TRANSACTIONS::response gettx_res; |
| 13428 | for (size_t i = 0; i < proofs.size(); ++i) |
| 13429 | gettx_req.txs_hashes.push_back(epee::string_tools::pod_to_hex(proofs[i].txid)); |
| 13430 | gettx_req.decode_as_json = false; |
| 13431 | gettx_req.prune = true; |
| 13432 | |
| 13433 | { |
| 13434 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 13435 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 13436 | gettx_req.client = get_client_signature(); |
| 13437 | bool ok = net_utils::invoke_http_json("/gettransactions", gettx_req, gettx_res, *m_http_client); |
| 13438 | THROW_WALLET_EXCEPTION_IF(!ok || gettx_res.txs.size() != proofs.size(), |
| 13439 | error::wallet_internal_error, "Failed to get transaction from daemon"); |
| 13440 | check_rpc_cost("/gettransactions", gettx_res.credits, pre_call_credits, gettx_res.txs.size() * COST_PER_TX); |
| 13441 | } |
| 13442 | |
| 13443 | // check spent status |
| 13444 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::request kispent_req; |
| 13445 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::response kispent_res; |
| 13446 | for (size_t i = 0; i < proofs.size(); ++i) |
| 13447 | kispent_req.key_images.push_back(epee::string_tools::pod_to_hex(proofs[i].key_image)); |
| 13448 | |
| 13449 | bool ok; |
| 13450 | { |
| 13451 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 13452 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 13453 | kispent_req.client = get_client_signature(); |
| 13454 | ok = epee::net_utils::invoke_http_json("/is_key_image_spent", kispent_req, kispent_res, *m_http_client, rpc_timeout); |
| 13455 | THROW_WALLET_EXCEPTION_IF(!ok || kispent_res.spent_status.size() != proofs.size(), |
| 13456 | error::wallet_internal_error, "Failed to get key image spent status from daemon"); |
| 13457 | check_rpc_cost("/is_key_image_spent", kispent_res.credits, pre_call_credits, kispent_res.spent_status.size() * COST_PER_KEY_IMAGE); |
| 13458 | } |
| 13459 | |
| 13460 | total = spent = 0; |
| 13461 | for (size_t i = 0; i < proofs.size(); ++i) |
| 13462 | { |
| 13463 | const reserve_proof_entry& proof = proofs[i]; |
| 13464 | THROW_WALLET_EXCEPTION_IF(gettx_res.txs[i].in_pool, error::wallet_internal_error, "Tx is unconfirmed"); |
| 13465 | |
| 13466 | cryptonote::transaction tx; |
| 13467 | crypto::hash tx_hash; |
| 13468 | ok = get_pruned_tx(gettx_res.txs[i], tx, tx_hash); |
| 13469 | THROW_WALLET_EXCEPTION_IF(!ok, error::wallet_internal_error, "Failed to parse transaction from daemon"); |
| 13470 | |
| 13471 | THROW_WALLET_EXCEPTION_IF(tx_hash != proof.txid, error::wallet_internal_error, "Failed to get the right transaction from daemon"); |
| 13472 | |
| 13473 | THROW_WALLET_EXCEPTION_IF(proof.index_in_tx >= tx.vout.size(), error::wallet_internal_error, "index_in_tx is out of bound"); |
| 13474 | |
| 13475 | crypto::public_key output_public_key; |
| 13476 | THROW_WALLET_EXCEPTION_IF(!get_output_public_key(tx.vout[proof.index_in_tx], output_public_key), error::wallet_internal_error, "Output key wasn't found"); |
| 13477 | |
| 13478 | // get tx pub key |
| 13479 | const crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); |
| 13480 | THROW_WALLET_EXCEPTION_IF(tx_pub_key == crypto::null_pkey, error::wallet_internal_error, "The tx public key isn't found"); |
| 13481 | const std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); |
| 13482 | |
| 13483 | // check singature for shared secret |
| 13484 | ok = crypto::check_tx_proof(prefix_hash, address.m_view_public_key, tx_pub_key, boost::none, proof.shared_secret, proof.shared_secret_sig, version); |
| 13485 | if (!ok && additional_tx_pub_keys.size() == tx.vout.size()) |
| 13486 | ok = crypto::check_tx_proof(prefix_hash, address.m_view_public_key, additional_tx_pub_keys[proof.index_in_tx], boost::none, proof.shared_secret, proof.shared_secret_sig, version); |
| 13487 | if (!ok) |
| 13488 | return false; |
| 13489 | |
| 13490 | // check signature for key image |
| 13491 | const std::vector<const crypto::public_key*> pubs = { &output_public_key }; |
| 13492 | ok = crypto::check_ring_signature(prefix_hash, proof.key_image, &pubs[0], 1, &proof.key_image_sig); |
| 13493 | if (!ok) |
| 13494 | return false; |
| 13495 | |
| 13496 | // check if the address really received the fund |
| 13497 | crypto::key_derivation derivation; |
| 13498 | THROW_WALLET_EXCEPTION_IF(!crypto::generate_key_derivation(proof.shared_secret, rct::rct2sk(rct::I), derivation), error::wallet_internal_error, "Failed to generate key derivation"); |
| 13499 | crypto::public_key subaddr_spendkey; |
| 13500 | THROW_WALLET_EXCEPTION_IF(!crypto::derive_subaddress_public_key(output_public_key, derivation, proof.index_in_tx, subaddr_spendkey), |
| 13501 | error::wallet_internal_error, "Failed to derive subaddress public key"); |
| 13502 | THROW_WALLET_EXCEPTION_IF(subaddr_spendkeys.count(subaddr_spendkey) == 0, error::wallet_internal_error, |
| 13503 | "The address doesn't seem to have received the fund"); |
| 13504 | |
| 13505 | // check amount |
| 13506 | uint64_t amount = tx.vout[proof.index_in_tx].amount; |
| 13507 | if (amount == 0) |
| 13508 | { |
| 13509 | // decode rct |
| 13510 | rct::key mask_; |
| 13511 | amount = decodeRct(tx.rct_signatures, derivation, proof.index_in_tx, mask_, hw::get_device("default")); |
| 13512 | } |
| 13513 | total += amount; |
| 13514 | if (kispent_res.spent_status[i]) |
| 13515 | spent += amount; |
| 13516 | } |
| 13517 | |
| 13518 | // check signatures for all subaddress spend keys |
| 13519 | for (const auto &i : subaddr_spendkeys) |
| 13520 | { |
| 13521 | if (!crypto::check_signature(prefix_hash, i.first, i.second)) |
| 13522 | return false; |
| 13523 | } |
| 13524 | return true; |
| 13525 | } |
| 13526 | |
| 13527 | std::string wallet2::get_wallet_file() const |
| 13528 | { |
| 13529 | return m_wallet_file; |
| 13530 | } |
| 13531 | |
| 13532 | std::string wallet2::get_keys_file() const |
| 13533 | { |
| 13534 | return m_keys_file; |
| 13535 | } |
| 13536 | |
| 13537 | std::string wallet2::get_daemon_address() const |
| 13538 | { |
| 13539 | return m_daemon_address; |
| 13540 | } |
| 13541 | |
| 13542 | uint64_t wallet2::get_daemon_blockchain_height(string &err) |
| 13543 | { |
| 13544 | uint64_t height; |
| 13545 | |
| 13546 | boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); |
| 13547 | if (result) |
| 13548 | { |
| 13549 | if (m_trusted_daemon) |
| 13550 | err = *result; |
| 13551 | else |
| 13552 | err = "daemon error"; |
| 13553 | return 0; |
| 13554 | } |
| 13555 | |
| 13556 | err = ""; |
| 13557 | return height; |
| 13558 | } |
| 13559 | |
| 13560 | uint64_t wallet2::get_daemon_adjusted_time() |
| 13561 | { |
| 13562 | uint64_t adjusted_time; |
| 13563 | |
| 13564 | boost::optional<std::string> result = m_node_rpc_proxy.get_adjusted_time(adjusted_time); |
| 13565 | THROW_WALLET_EXCEPTION_IF(result, error::wallet_internal_error, "Invalid adjusted time from daemon"); |
| 13566 | return adjusted_time; |
| 13567 | } |
| 13568 | |
| 13569 | uint64_t wallet2::get_daemon_blockchain_target_height(string &err) |
| 13570 | { |
| 13571 | err = ""; |
| 13572 | uint64_t target_height = 0; |
| 13573 | const auto result = m_node_rpc_proxy.get_target_height(target_height); |
| 13574 | if (result && *result != CORE_RPC_STATUS_OK) |
| 13575 | { |
| 13576 | if (m_trusted_daemon) |
| 13577 | err = *result; |
| 13578 | else |
| 13579 | err = "daemon error"; |
| 13580 | return 0; |
| 13581 | } |
| 13582 | return target_height; |
| 13583 | } |
| 13584 | |
| 13585 | uint64_t wallet2::get_approximate_blockchain_height() const |
| 13586 | { |
| 13587 | // time of v2 fork |
| 13588 | const time_t fork_time = m_nettype == TESTNET ? 1448285909 : m_nettype == STAGENET ? 1520937818 : 1458748658; |
| 13589 | // v2 fork block |
| 13590 | const uint64_t fork_block = m_nettype == TESTNET ? 624634 : m_nettype == STAGENET ? 32000 : 1009827; |
| 13591 | // avg seconds per block |
| 13592 | const int seconds_per_block = DIFFICULTY_TARGET_V2; |
| 13593 | // Calculated blockchain height |
| 13594 | uint64_t approx_blockchain_height = fork_block + (time(NULL) - fork_time)/seconds_per_block; |
| 13595 | // testnet and stagenet got some huge rollbacks, so the estimation is way off |
| 13596 | static const uint64_t approximate_rolled_back_blocks = m_nettype == TESTNET ? 342100 : m_nettype == STAGENET ? 60000 : 30000; |
| 13597 | if ((m_nettype == TESTNET || m_nettype == STAGENET) && approx_blockchain_height > approximate_rolled_back_blocks) |
| 13598 | approx_blockchain_height -= approximate_rolled_back_blocks; |
| 13599 | LOG_PRINT_L2("Calculated blockchain height: " << approx_blockchain_height); |
| 13600 | return approx_blockchain_height; |
| 13601 | } |
| 13602 | |
| 13603 | void wallet2::set_tx_note(const crypto::hash &txid, const std::string ¬e) |
| 13604 | { |
| 13605 | m_tx_notes[txid] = note; |
| 13606 | } |
| 13607 | |
| 13608 | std::string wallet2::get_tx_note(const crypto::hash &txid) const |
| 13609 | { |
| 13610 | std::unordered_map<crypto::hash, std::string>::const_iterator i = m_tx_notes.find(txid); |
| 13611 | if (i == m_tx_notes.end()) |
| 13612 | return std::string(); |
| 13613 | return i->second; |
| 13614 | } |
| 13615 | |
| 13616 | void wallet2::set_tx_device_aux(const crypto::hash &txid, const std::string &aux) |
| 13617 | { |
| 13618 | m_tx_device[txid] = aux; |
| 13619 | } |
| 13620 | |
| 13621 | std::string wallet2::get_tx_device_aux(const crypto::hash &txid) const |
| 13622 | { |
| 13623 | std::unordered_map<crypto::hash, std::string>::const_iterator i = m_tx_device.find(txid); |
| 13624 | if (i == m_tx_device.end()) |
| 13625 | return std::string(); |
| 13626 | return i->second; |
| 13627 | } |
| 13628 | |
| 13629 | void wallet2::set_attribute(const std::string &key, const std::string &value) |
| 13630 | { |
| 13631 | m_attributes[key] = value; |
| 13632 | } |
| 13633 | |
| 13634 | bool wallet2::get_attribute(const std::string &key, std::string &value) const |
| 13635 | { |
| 13636 | std::unordered_map<std::string, std::string>::const_iterator i = m_attributes.find(key); |
| 13637 | if (i == m_attributes.end()) |
| 13638 | return false; |
| 13639 | value = i->second; |
| 13640 | return true; |
| 13641 | } |
| 13642 | |
| 13643 | void wallet2::set_description(const std::string &description) |
| 13644 | { |
| 13645 | set_attribute(ATTRIBUTE_DESCRIPTION, description); |
| 13646 | } |
| 13647 | |
| 13648 | std::string wallet2::get_description() const |
| 13649 | { |
| 13650 | std::string s; |
| 13651 | if (get_attribute(ATTRIBUTE_DESCRIPTION, s)) |
| 13652 | return s; |
| 13653 | return ""; |
| 13654 | } |
| 13655 | |
| 13656 | const std::pair<serializable_map<std::string, std::string>, std::vector<std::string>>& wallet2::get_account_tags() |
| 13657 | { |
| 13658 | // ensure consistency |
| 13659 | if (m_account_tags.second.size() != get_num_subaddress_accounts()) |
| 13660 | m_account_tags.second.resize(get_num_subaddress_accounts(), ""); |
| 13661 | for (const std::string& tag : m_account_tags.second) |
| 13662 | { |
| 13663 | if (!tag.empty() && m_account_tags.first.count(tag) == 0) |
| 13664 | m_account_tags.first.insert({tag, ""}); |
| 13665 | } |
| 13666 | for (auto i = m_account_tags.first.begin(); i != m_account_tags.first.end(); ) |
| 13667 | { |
| 13668 | if (std::find(m_account_tags.second.begin(), m_account_tags.second.end(), i->first) == m_account_tags.second.end()) |
| 13669 | i = m_account_tags.first.erase(i); |
| 13670 | else |
| 13671 | ++i; |
| 13672 | } |
| 13673 | return m_account_tags; |
| 13674 | } |
| 13675 | |
| 13676 | void wallet2::set_account_tag(const std::set<uint32_t> &account_indices, const std::string& tag) |
| 13677 | { |
| 13678 | for (uint32_t account_index : account_indices) |
| 13679 | { |
| 13680 | THROW_WALLET_EXCEPTION_IF(account_index >= get_num_subaddress_accounts(), error::wallet_internal_error, "Account index out of bound"); |
| 13681 | if (m_account_tags.second[account_index] == tag) |
| 13682 | MDEBUG("This tag is already assigned to this account"); |
| 13683 | else |
| 13684 | m_account_tags.second[account_index] = tag; |
| 13685 | } |
| 13686 | get_account_tags(); |
| 13687 | } |
| 13688 | |
| 13689 | void wallet2::set_account_tag_description(const std::string& tag, const std::string& description) |
| 13690 | { |
| 13691 | THROW_WALLET_EXCEPTION_IF(tag.empty(), error::wallet_internal_error, "Tag must not be empty"); |
| 13692 | THROW_WALLET_EXCEPTION_IF(m_account_tags.first.count(tag) == 0, error::wallet_internal_error, "Tag is unregistered"); |
| 13693 | m_account_tags.first[tag] = description; |
| 13694 | } |
| 13695 | |
| 13696 | // Set up an address signature message hash |
| 13697 | // Hash data: domain separator, spend public key, view public key, mode identifier, payload data |
| 13698 | static crypto::hash get_message_hash(const std::string &data, const crypto::public_key &spend_key, const crypto::public_key &view_key, const uint8_t mode) |
| 13699 | { |
| 13700 | KECCAK_CTX ctx; |
| 13701 | keccak_init(&ctx); |
| 13702 | keccak_update(&ctx, (const uint8_t*)config::HASH_KEY_MESSAGE_SIGNING, sizeof(config::HASH_KEY_MESSAGE_SIGNING)); // includes NUL |
| 13703 | keccak_update(&ctx, (const uint8_t*)&spend_key, sizeof(crypto::public_key)); |
| 13704 | keccak_update(&ctx, (const uint8_t*)&view_key, sizeof(crypto::public_key)); |
| 13705 | keccak_update(&ctx, (const uint8_t*)&mode, sizeof(uint8_t)); |
| 13706 | char len_buf[(sizeof(size_t) * 8 + 6) / 7]; |
| 13707 | char *ptr = len_buf; |
| 13708 | tools::write_varint(ptr, data.size()); |
| 13709 | CHECK_AND_ASSERT_THROW_MES(ptr > len_buf && ptr <= len_buf + sizeof(len_buf), "Length overflow"); |
| 13710 | keccak_update(&ctx, (const uint8_t*)len_buf, ptr - len_buf); |
| 13711 | keccak_update(&ctx, (const uint8_t*)data.data(), data.size()); |
| 13712 | crypto::hash hash; |
| 13713 | keccak_finish(&ctx, (uint8_t*)&hash); |
| 13714 | return hash; |
| 13715 | } |
| 13716 | |
| 13717 | // Sign a message with a private key from either the base address or a subaddress |
| 13718 | // The signature is also bound to both keys and the signature mode (spend, view) to prevent unintended reuse |
| 13719 | std::string wallet2::sign(const std::string &data, message_signature_type_t signature_type, cryptonote::subaddress_index index) const |
| 13720 | { |
| 13721 | const cryptonote::account_keys &keys = m_account.get_keys(); |
| 13722 | crypto::signature signature; |
| 13723 | crypto::secret_key skey, m; |
| 13724 | crypto::secret_key skey_spend, skey_view; |
| 13725 | crypto::public_key pkey; |
| 13726 | crypto::public_key pkey_spend, pkey_view; // to include both in hash |
| 13727 | crypto::hash hash; |
| 13728 | uint8_t mode; |
| 13729 | |
| 13730 | // Use the base address |
| 13731 | if (index.is_zero()) |
| 13732 | { |
| 13733 | switch (signature_type) |
| 13734 | { |
| 13735 | case sign_with_spend_key: |
| 13736 | skey = keys.m_spend_secret_key; |
| 13737 | pkey = keys.m_account_address.m_spend_public_key; |
| 13738 | mode = 0; |
| 13739 | break; |
| 13740 | case sign_with_view_key: |
| 13741 | skey = keys.m_view_secret_key; |
| 13742 | pkey = keys.m_account_address.m_view_public_key; |
| 13743 | mode = 1; |
| 13744 | break; |
| 13745 | default: CHECK_AND_ASSERT_THROW_MES(false, "Invalid signature type requested"); |
| 13746 | } |
| 13747 | hash = get_message_hash(data,keys.m_account_address.m_spend_public_key,keys.m_account_address.m_view_public_key,mode); |
| 13748 | } |
| 13749 | // Use a subaddress |
| 13750 | else |
| 13751 | { |
| 13752 | skey_spend = keys.m_spend_secret_key; |
| 13753 | m = m_account.get_device().get_subaddress_secret_key(keys.m_view_secret_key, index); |
| 13754 | sc_add((unsigned char*)&skey_spend, (unsigned char*)&m, (unsigned char*)&skey_spend); |
| 13755 | secret_key_to_public_key(skey_spend,pkey_spend); |
| 13756 | sc_mul((unsigned char*)&skey_view, (unsigned char*)&keys.m_view_secret_key, (unsigned char*)&skey_spend); |
| 13757 | secret_key_to_public_key(skey_view,pkey_view); |
| 13758 | switch (signature_type) |
| 13759 | { |
| 13760 | case sign_with_spend_key: |
| 13761 | skey = skey_spend; |
| 13762 | pkey = pkey_spend; |
| 13763 | mode = 0; |
| 13764 | break; |
| 13765 | case sign_with_view_key: |
| 13766 | skey = skey_view; |
| 13767 | pkey = pkey_view; |
| 13768 | mode = 1; |
| 13769 | break; |
| 13770 | default: CHECK_AND_ASSERT_THROW_MES(false, "Invalid signature type requested"); |
| 13771 | } |
| 13772 | secret_key_to_public_key(skey, pkey); |
| 13773 | hash = get_message_hash(data,pkey_spend,pkey_view,mode); |
| 13774 | } |
| 13775 | crypto::generate_signature(hash, pkey, skey, signature); |
| 13776 | return std::string("SigV2") + tools::base58::encode(std::string((const char *)&signature, sizeof(signature))); |
| 13777 | } |
| 13778 | |
| 13779 | tools::wallet2::message_signature_result_t wallet2::verify(const std::string &data, const cryptonote::account_public_address &address, const std::string &signature) const |
| 13780 | { |
| 13781 | static const size_t v1_header_len = strlen("SigV1"); |
| 13782 | static const size_t v2_header_len = strlen("SigV2"); |
| 13783 | const bool v1 = signature.size() >= v1_header_len && signature.substr(0, v1_header_len) == "SigV1"; |
| 13784 | const bool v2 = signature.size() >= v2_header_len && signature.substr(0, v2_header_len) == "SigV2"; |
| 13785 | if (!v1 && !v2) |
| 13786 | { |
| 13787 | LOG_PRINT_L0("Signature header check error"); |
| 13788 | return {}; |
| 13789 | } |
| 13790 | crypto::hash hash; |
| 13791 | if (v1) |
| 13792 | { |
| 13793 | crypto::cn_fast_hash(data.data(), data.size(), hash); |
| 13794 | } |
| 13795 | std::string decoded; |
| 13796 | if (!tools::base58::decode(signature.substr(v1 ? v1_header_len : v2_header_len), decoded)) { |
| 13797 | LOG_PRINT_L0("Signature decoding error"); |
| 13798 | return {}; |
| 13799 | } |
| 13800 | crypto::signature s; |
| 13801 | if (sizeof(s) != decoded.size()) { |
| 13802 | LOG_PRINT_L0("Signature decoding error"); |
| 13803 | return {}; |
| 13804 | } |
| 13805 | memcpy(&s, decoded.data(), sizeof(s)); |
| 13806 | |
| 13807 | // Test each mode and return which mode, if either, succeeded |
| 13808 | if (v2) |
| 13809 | hash = get_message_hash(data,address.m_spend_public_key,address.m_view_public_key,(uint8_t) 0); |
| 13810 | if (crypto::check_signature(hash, address.m_spend_public_key, s)) |
| 13811 | return {true, v1 ? 1u : 2u, !v2, sign_with_spend_key }; |
| 13812 | |
| 13813 | if (v2) |
| 13814 | hash = get_message_hash(data,address.m_spend_public_key,address.m_view_public_key,(uint8_t) 1); |
| 13815 | if (crypto::check_signature(hash, address.m_view_public_key, s)) |
| 13816 | return {true, v1 ? 1u : 2u, !v2, sign_with_view_key }; |
| 13817 | |
| 13818 | // Both modes failed |
| 13819 | return {}; |
| 13820 | } |
| 13821 | |
| 13822 | std::string wallet2::sign_multisig_participant(const std::string& data) const |
| 13823 | { |
| 13824 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 13825 | |
| 13826 | crypto::hash hash; |
| 13827 | crypto::cn_fast_hash(data.data(), data.size(), hash); |
| 13828 | const cryptonote::account_keys &keys = m_account.get_keys(); |
| 13829 | crypto::signature signature; |
| 13830 | crypto::generate_signature(hash, get_multisig_signer_public_key(), keys.m_spend_secret_key, signature); |
| 13831 | return MULTISIG_SIGNATURE_MAGIC + tools::base58::encode(std::string((const char *)&signature, sizeof(signature))); |
| 13832 | } |
| 13833 | |
| 13834 | bool wallet2::verify_with_public_key(const std::string &data, const crypto::public_key &public_key, const std::string &signature) const |
| 13835 | { |
| 13836 | if (signature.size() < MULTISIG_SIGNATURE_MAGIC.size() || signature.substr(0, MULTISIG_SIGNATURE_MAGIC.size()) != MULTISIG_SIGNATURE_MAGIC) { |
| 13837 | MERROR("Signature header check error"); |
| 13838 | return false; |
| 13839 | } |
| 13840 | crypto::hash hash; |
| 13841 | crypto::cn_fast_hash(data.data(), data.size(), hash); |
| 13842 | std::string decoded; |
| 13843 | if (!tools::base58::decode(signature.substr(MULTISIG_SIGNATURE_MAGIC.size()), decoded)) { |
| 13844 | MERROR("Signature decoding error"); |
| 13845 | return false; |
| 13846 | } |
| 13847 | crypto::signature s; |
| 13848 | if (sizeof(s) != decoded.size()) { |
| 13849 | MERROR("Signature decoding error"); |
| 13850 | return false; |
| 13851 | } |
| 13852 | memcpy(&s, decoded.data(), sizeof(s)); |
| 13853 | return crypto::check_signature(hash, public_key, s); |
| 13854 | } |
| 13855 | //---------------------------------------------------------------------------------------------------- |
| 13856 | crypto::public_key wallet2::get_tx_pub_key_from_received_outs(const tools::wallet2::transfer_details &td) const |
| 13857 | { |
| 13858 | std::vector<tx_extra_field> tx_extra_fields; |
| 13859 | if(!parse_tx_extra(td.m_tx.extra, tx_extra_fields)) |
| 13860 | { |
| 13861 | // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key |
| 13862 | } |
| 13863 | |
| 13864 | // Due to a previous bug, there might be more than one tx pubkey in extra, one being |
| 13865 | // the result of a previously discarded signature. |
| 13866 | // For speed, since scanning for outputs is a slow process, we check whether extra |
| 13867 | // contains more than one pubkey. If not, the first one is returned. If yes, they're |
| 13868 | // checked for whether they yield at least one output |
| 13869 | tx_extra_pub_key pub_key_field; |
| 13870 | THROW_WALLET_EXCEPTION_IF(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, 0), error::wallet_internal_error, |
| 13871 | "Public key wasn't found in the transaction extra"); |
| 13872 | const crypto::public_key tx_pub_key = pub_key_field.pub_key; |
| 13873 | bool two_found = find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, 1); |
| 13874 | if (!two_found) { |
| 13875 | // easy case, just one found |
| 13876 | return tx_pub_key; |
| 13877 | } |
| 13878 | |
| 13879 | // more than one, loop and search |
| 13880 | const cryptonote::account_keys& keys = m_account.get_keys(); |
| 13881 | size_t pk_index = 0; |
| 13882 | hw::device &hwdev = m_account.get_device(); |
| 13883 | |
| 13884 | while (find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index++)) { |
| 13885 | const crypto::public_key tx_pub_key = pub_key_field.pub_key; |
| 13886 | crypto::key_derivation derivation; |
| 13887 | bool r = hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation); |
| 13888 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key derivation"); |
| 13889 | |
| 13890 | for (size_t i = 0; i < td.m_tx.vout.size(); ++i) |
| 13891 | { |
| 13892 | tx_scan_info_t tx_scan_info; |
| 13893 | check_acc_out_precomp(td.m_tx.vout[i], derivation, {}, i, tx_scan_info); |
| 13894 | if (!tx_scan_info.error && tx_scan_info.received) |
| 13895 | return tx_pub_key; |
| 13896 | } |
| 13897 | } |
| 13898 | |
| 13899 | // we found no key yielding an output, but it might be in the additional |
| 13900 | // tx pub keys only, which we do not need to check, so return the first one |
| 13901 | return tx_pub_key; |
| 13902 | } |
| 13903 | |
| 13904 | bool wallet2::export_key_images(const std::string &filename, bool all) const |
| 13905 | { |
| 13906 | PERF_TIMER(export_key_images); |
| 13907 | std::pair<uint64_t, std::vector<std::pair<crypto::key_image, crypto::signature>>> ski = export_key_images(all); |
| 13908 | std::string magic(KEY_IMAGE_EXPORT_FILE_MAGIC, strlen(KEY_IMAGE_EXPORT_FILE_MAGIC)); |
| 13909 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 13910 | const uint32_t offset = ski.first; |
| 13911 | |
| 13912 | std::string data; |
| 13913 | data.reserve(4 + ski.second.size() * (sizeof(crypto::key_image) + sizeof(crypto::signature)) + 2 * sizeof(crypto::public_key)); |
| 13914 | data.resize(4); |
| 13915 | data[0] = offset & 0xff; |
| 13916 | data[1] = (offset >> 8) & 0xff; |
| 13917 | data[2] = (offset >> 16) & 0xff; |
| 13918 | data[3] = (offset >> 24) & 0xff; |
| 13919 | data += std::string((const char *)&keys.m_spend_public_key, sizeof(crypto::public_key)); |
| 13920 | data += std::string((const char *)&keys.m_view_public_key, sizeof(crypto::public_key)); |
| 13921 | for (const auto &i: ski.second) |
| 13922 | { |
| 13923 | data += std::string((const char *)&i.first, sizeof(crypto::key_image)); |
| 13924 | data += std::string((const char *)&i.second, sizeof(crypto::signature)); |
| 13925 | } |
| 13926 | |
| 13927 | // encrypt data, keep magic plaintext |
| 13928 | PERF_TIMER(export_key_images_encrypt); |
| 13929 | std::string ciphertext = encrypt_with_view_secret_key(data); |
| 13930 | return save_to_file(filename, magic + ciphertext); |
| 13931 | } |
| 13932 | |
| 13933 | //---------------------------------------------------------------------------------------------------- |
| 13934 | std::pair<uint64_t, std::vector<std::pair<crypto::key_image, crypto::signature>>> wallet2::export_key_images(bool all) const |
| 13935 | { |
| 13936 | PERF_TIMER(export_key_images_raw); |
| 13937 | std::vector<std::pair<crypto::key_image, crypto::signature>> ski; |
| 13938 | |
| 13939 | size_t offset = 0; |
| 13940 | if (!all) |
| 13941 | { |
| 13942 | while (offset < m_transfers.size() && !m_transfers[offset].m_key_image_request) |
| 13943 | ++offset; |
| 13944 | } |
| 13945 | |
| 13946 | ski.reserve(m_transfers.size() - offset); |
| 13947 | for (size_t n = offset; n < m_transfers.size(); ++n) |
| 13948 | { |
| 13949 | const transfer_details &td = m_transfers[n]; |
| 13950 | |
| 13951 | // get ephemeral public key |
| 13952 | const crypto::public_key pkey = td.get_public_key(); |
| 13953 | |
| 13954 | // get tx pub key |
| 13955 | std::vector<tx_extra_field> tx_extra_fields; |
| 13956 | if(!parse_tx_extra(td.m_tx.extra, tx_extra_fields)) |
| 13957 | { |
| 13958 | // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key |
| 13959 | } |
| 13960 | |
| 13961 | crypto::public_key tx_pub_key = get_tx_pub_key_from_received_outs(td); |
| 13962 | const std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 13963 | |
| 13964 | // generate ephemeral secret key |
| 13965 | crypto::key_image ki; |
| 13966 | cryptonote::keypair in_ephemeral; |
| 13967 | bool r = cryptonote::generate_key_image_helper(m_account.get_keys(), m_subaddresses, pkey, tx_pub_key, additional_tx_pub_keys, td.m_internal_output_index, in_ephemeral, ki, m_account.get_device()); |
| 13968 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 13969 | |
| 13970 | THROW_WALLET_EXCEPTION_IF(td.m_key_image_known && !td.m_key_image_partial && ki != td.m_key_image, |
| 13971 | error::wallet_internal_error, "key_image generated not matched with cached key image"); |
| 13972 | THROW_WALLET_EXCEPTION_IF(in_ephemeral.pub != pkey, |
| 13973 | error::wallet_internal_error, "key_image generated ephemeral public key not matched with output_key"); |
| 13974 | |
| 13975 | // sign the key image with the output secret key |
| 13976 | crypto::signature signature; |
| 13977 | std::vector<const crypto::public_key*> key_ptrs; |
| 13978 | key_ptrs.push_back(&pkey); |
| 13979 | |
| 13980 | crypto::generate_ring_signature((const crypto::hash&)td.m_key_image, td.m_key_image, key_ptrs, in_ephemeral.sec, 0, &signature); |
| 13981 | |
| 13982 | ski.push_back(std::make_pair(td.m_key_image, signature)); |
| 13983 | } |
| 13984 | return std::make_pair(offset, ski); |
| 13985 | } |
| 13986 | |
| 13987 | uint64_t wallet2::import_key_images(const std::string &filename, uint64_t &spent, uint64_t &unspent) |
| 13988 | { |
| 13989 | PERF_TIMER(import_key_images_fsu); |
| 13990 | std::string data; |
| 13991 | bool r = load_from_file(filename, data); |
| 13992 | |
| 13993 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, std::string(tr("failed to read file ")) + filename); |
| 13994 | |
| 13995 | const size_t magiclen = strlen(KEY_IMAGE_EXPORT_FILE_MAGIC); |
| 13996 | if (data.size() < magiclen || memcmp(data.data(), KEY_IMAGE_EXPORT_FILE_MAGIC, magiclen)) |
| 13997 | { |
| 13998 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Bad key image export file magic in ") + filename); |
| 13999 | } |
| 14000 | |
| 14001 | try |
| 14002 | { |
| 14003 | PERF_TIMER(import_key_images_decrypt); |
| 14004 | data = decrypt_with_view_secret_key(std::string(data, magiclen)); |
| 14005 | } |
| 14006 | catch (const std::exception &e) |
| 14007 | { |
| 14008 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Failed to decrypt ") + filename + ": " + e.what()); |
| 14009 | } |
| 14010 | |
| 14011 | const size_t headerlen = 4 + 2 * sizeof(crypto::public_key); |
| 14012 | THROW_WALLET_EXCEPTION_IF(data.size() < headerlen, error::wallet_internal_error, std::string("Bad data size from file ") + filename); |
| 14013 | const uint32_t offset = (uint8_t)data[0] | (((uint8_t)data[1]) << 8) | (((uint8_t)data[2]) << 16) | (((uint8_t)data[3]) << 24); |
| 14014 | const crypto::public_key &public_spend_key = *(const crypto::public_key*)&data[4]; |
| 14015 | const crypto::public_key &public_view_key = *(const crypto::public_key*)&data[4 + sizeof(crypto::public_key)]; |
| 14016 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 14017 | if (public_spend_key != keys.m_spend_public_key || public_view_key != keys.m_view_public_key) |
| 14018 | { |
| 14019 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string( "Key images from ") + filename + " are for a different account"); |
| 14020 | } |
| 14021 | THROW_WALLET_EXCEPTION_IF(offset > m_transfers.size(), error::wallet_internal_error, "Offset larger than known outputs"); |
| 14022 | |
| 14023 | const size_t record_size = sizeof(crypto::key_image) + sizeof(crypto::signature); |
| 14024 | THROW_WALLET_EXCEPTION_IF((data.size() - headerlen) % record_size, |
| 14025 | error::wallet_internal_error, std::string("Bad data size from file ") + filename); |
| 14026 | size_t nki = (data.size() - headerlen) / record_size; |
| 14027 | |
| 14028 | std::vector<std::pair<crypto::key_image, crypto::signature>> ski; |
| 14029 | ski.reserve(nki); |
| 14030 | for (size_t n = 0; n < nki; ++n) |
| 14031 | { |
| 14032 | crypto::key_image key_image = *reinterpret_cast<const crypto::key_image*>(&data[headerlen + n * record_size]); |
| 14033 | crypto::signature signature = *reinterpret_cast<const crypto::signature*>(&data[headerlen + n * record_size + sizeof(crypto::key_image)]); |
| 14034 | |
| 14035 | ski.push_back(std::make_pair(key_image, signature)); |
| 14036 | } |
| 14037 | |
| 14038 | return import_key_images(ski, offset, spent, unspent); |
| 14039 | } |
| 14040 | |
| 14041 | //---------------------------------------------------------------------------------------------------- |
| 14042 | uint64_t wallet2::import_key_images(const std::vector<std::pair<crypto::key_image, crypto::signature>> &signed_key_images, size_t offset, uint64_t &spent, uint64_t &unspent, bool check_spent) |
| 14043 | { |
| 14044 | PERF_TIMER(import_key_images_lots); |
| 14045 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::request req = AUTO_VAL_INIT(req); |
| 14046 | COMMAND_RPC_IS_KEY_IMAGE_SPENT::response daemon_resp = AUTO_VAL_INIT(daemon_resp); |
| 14047 | |
| 14048 | THROW_WALLET_EXCEPTION_IF(offset > m_transfers.size(), error::wallet_internal_error, "Offset larger than known outputs"); |
| 14049 | THROW_WALLET_EXCEPTION_IF(signed_key_images.size() > m_transfers.size() - offset, error::wallet_internal_error, |
| 14050 | "The blockchain is out of date compared to the signed key images"); |
| 14051 | |
| 14052 | if (signed_key_images.empty() && offset == 0) |
| 14053 | { |
| 14054 | spent = 0; |
| 14055 | unspent = 0; |
| 14056 | return 0; |
| 14057 | } |
| 14058 | |
| 14059 | req.key_images.reserve(signed_key_images.size()); |
| 14060 | |
| 14061 | PERF_TIMER_START(import_key_images_A); |
| 14062 | for (size_t n = 0; n < signed_key_images.size(); ++n) |
| 14063 | { |
| 14064 | const transfer_details &td = m_transfers[n + offset]; |
| 14065 | const crypto::key_image &key_image = signed_key_images[n].first; |
| 14066 | const crypto::signature &signature = signed_key_images[n].second; |
| 14067 | |
| 14068 | // get ephemeral public key |
| 14069 | const crypto::public_key pkey = td.get_public_key(); |
| 14070 | |
| 14071 | if (!td.m_key_image_known || !(key_image == td.m_key_image)) |
| 14072 | { |
| 14073 | std::vector<const crypto::public_key*> pkeys; |
| 14074 | pkeys.push_back(&pkey); |
| 14075 | THROW_WALLET_EXCEPTION_IF(!(rct::scalarmultKey(rct::ki2rct(key_image), rct::curveOrder()) == rct::identity()), |
| 14076 | error::wallet_internal_error, "Key image out of validity domain: input " + boost::lexical_cast<std::string>(n + offset) + "/" |
| 14077 | + boost::lexical_cast<std::string>(signed_key_images.size()) + ", key image " + epee::string_tools::pod_to_hex(key_image)); |
| 14078 | |
| 14079 | THROW_WALLET_EXCEPTION_IF(!crypto::check_ring_signature((const crypto::hash&)key_image, key_image, pkeys, &signature), |
| 14080 | error::signature_check_failed, boost::lexical_cast<std::string>(n + offset) + "/" |
| 14081 | + boost::lexical_cast<std::string>(signed_key_images.size()) + ", key image " + epee::string_tools::pod_to_hex(key_image) |
| 14082 | + ", signature " + epee::string_tools::pod_to_hex(signature) + ", pubkey " + epee::string_tools::pod_to_hex(*pkeys[0])); |
| 14083 | } |
| 14084 | req.key_images.push_back(epee::string_tools::pod_to_hex(key_image)); |
| 14085 | } |
| 14086 | PERF_TIMER_STOP(import_key_images_A); |
| 14087 | |
| 14088 | PERF_TIMER_START(import_key_images_B); |
| 14089 | for (size_t n = 0; n < signed_key_images.size(); ++n) |
| 14090 | { |
| 14091 | m_transfers[n + offset].m_key_image = signed_key_images[n].first; |
| 14092 | m_key_images[m_transfers[n + offset].m_key_image] = n + offset; |
| 14093 | m_transfers[n + offset].m_key_image_known = true; |
| 14094 | m_transfers[n + offset].m_key_image_request = false; |
| 14095 | m_transfers[n + offset].m_key_image_partial = false; |
| 14096 | } |
| 14097 | PERF_TIMER_STOP(import_key_images_B); |
| 14098 | |
| 14099 | if(check_spent) |
| 14100 | { |
| 14101 | PERF_TIMER(import_key_images_RPC); |
| 14102 | { |
| 14103 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 14104 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 14105 | req.client = get_client_signature(); |
| 14106 | bool r = epee::net_utils::invoke_http_json("/is_key_image_spent", req, daemon_resp, *m_http_client, rpc_timeout); |
| 14107 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, daemon_resp, "is_key_image_spent"); |
| 14108 | THROW_WALLET_EXCEPTION_IF(daemon_resp.spent_status.size() != signed_key_images.size(), error::wallet_internal_error, |
| 14109 | "daemon returned wrong response for is_key_image_spent, wrong amounts count = " + |
| 14110 | std::to_string(daemon_resp.spent_status.size()) + ", expected " + std::to_string(signed_key_images.size())); |
| 14111 | check_rpc_cost("/is_key_image_spent", daemon_resp.credits, pre_call_credits, daemon_resp.spent_status.size() * COST_PER_KEY_IMAGE); |
| 14112 | } |
| 14113 | |
| 14114 | for (size_t n = 0; n < daemon_resp.spent_status.size(); ++n) |
| 14115 | { |
| 14116 | transfer_details &td = m_transfers[n + offset]; |
| 14117 | td.m_spent = daemon_resp.spent_status[n] != COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT; |
| 14118 | } |
| 14119 | } |
| 14120 | spent = 0; |
| 14121 | unspent = 0; |
| 14122 | std::unordered_set<crypto::hash> spent_txids; // For each spent key image, search for a tx in m_transfers that uses it as input. |
| 14123 | std::vector<size_t> swept_transfers; // If such a spending tx wasn't found in m_transfers, this means the spending tx |
| 14124 | // was created by sweep_all, so we can't know the spent height and other detailed info. |
| 14125 | std::unordered_map<crypto::key_image, crypto::hash> spent_key_images; |
| 14126 | |
| 14127 | PERF_TIMER_START(import_key_images_C); |
| 14128 | for (const transfer_details &td: m_transfers) |
| 14129 | { |
| 14130 | for (const cryptonote::txin_v& in : td.m_tx.vin) |
| 14131 | { |
| 14132 | if (in.type() == typeid(cryptonote::txin_to_key)) |
| 14133 | spent_key_images.insert(std::make_pair(boost::get<cryptonote::txin_to_key>(in).k_image, td.m_txid)); |
| 14134 | } |
| 14135 | } |
| 14136 | PERF_TIMER_STOP(import_key_images_C); |
| 14137 | |
| 14138 | // accumulate outputs before the updated data |
| 14139 | for(size_t i = 0; i < offset; ++i) |
| 14140 | { |
| 14141 | const transfer_details &td = m_transfers[i]; |
| 14142 | if (td.m_frozen) |
| 14143 | continue; |
| 14144 | uint64_t amount = td.amount(); |
| 14145 | if (td.m_spent) |
| 14146 | spent += amount; |
| 14147 | else |
| 14148 | unspent += amount; |
| 14149 | } |
| 14150 | |
| 14151 | PERF_TIMER_START(import_key_images_D); |
| 14152 | for(size_t i = 0; i < signed_key_images.size(); ++i) |
| 14153 | { |
| 14154 | const transfer_details &td = m_transfers[i + offset]; |
| 14155 | if (td.m_frozen) |
| 14156 | continue; |
| 14157 | uint64_t amount = td.amount(); |
| 14158 | if (td.m_spent) |
| 14159 | spent += amount; |
| 14160 | else |
| 14161 | unspent += amount; |
| 14162 | LOG_PRINT_L2("Transfer " << i << ": " << print_money(amount) << " (" << td.m_global_output_index << "): " |
| 14163 | << (td.m_spent ? "spent" : "unspent") << " (key image " << req.key_images[i] << ")"); |
| 14164 | |
| 14165 | if (i < daemon_resp.spent_status.size() && daemon_resp.spent_status[i] == COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_BLOCKCHAIN) |
| 14166 | { |
| 14167 | const std::unordered_map<crypto::key_image, crypto::hash>::const_iterator skii = spent_key_images.find(td.m_key_image); |
| 14168 | if (skii == spent_key_images.end()) |
| 14169 | swept_transfers.push_back(i); |
| 14170 | else |
| 14171 | spent_txids.insert(skii->second); |
| 14172 | } |
| 14173 | } |
| 14174 | PERF_TIMER_STOP(import_key_images_D); |
| 14175 | |
| 14176 | MDEBUG("Total: " << print_money(spent) << " spent, " << print_money(unspent) << " unspent"); |
| 14177 | |
| 14178 | if (check_spent) |
| 14179 | { |
| 14180 | // query outgoing txes |
| 14181 | COMMAND_RPC_GET_TRANSACTIONS::request gettxs_req; |
| 14182 | COMMAND_RPC_GET_TRANSACTIONS::response gettxs_res; |
| 14183 | gettxs_req.decode_as_json = false; |
| 14184 | gettxs_req.prune = true; |
| 14185 | gettxs_req.txs_hashes.reserve(spent_txids.size()); |
| 14186 | for (const crypto::hash& spent_txid : spent_txids) |
| 14187 | gettxs_req.txs_hashes.push_back(epee::string_tools::pod_to_hex(spent_txid)); |
| 14188 | |
| 14189 | |
| 14190 | PERF_TIMER_START(import_key_images_E); |
| 14191 | { |
| 14192 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 14193 | gettxs_req.client = get_client_signature(); |
| 14194 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 14195 | bool r = epee::net_utils::invoke_http_json("/gettransactions", gettxs_req, gettxs_res, *m_http_client, rpc_timeout); |
| 14196 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, gettxs_res, "gettransactions"); |
| 14197 | THROW_WALLET_EXCEPTION_IF(gettxs_res.txs.size() != spent_txids.size(), error::wallet_internal_error, |
| 14198 | "daemon returned wrong response for gettransactions, wrong count = " + std::to_string(gettxs_res.txs.size()) + ", expected " + std::to_string(spent_txids.size())); |
| 14199 | check_rpc_cost("/gettransactions", gettxs_res.credits, pre_call_credits, spent_txids.size() * COST_PER_TX); |
| 14200 | } |
| 14201 | PERF_TIMER_STOP(import_key_images_E); |
| 14202 | |
| 14203 | // process each outgoing tx |
| 14204 | PERF_TIMER_START(import_key_images_F); |
| 14205 | auto spent_txid = spent_txids.begin(); |
| 14206 | hw::device &hwdev = m_account.get_device(); |
| 14207 | auto it = spent_txids.begin(); |
| 14208 | for (const COMMAND_RPC_GET_TRANSACTIONS::entry& e : gettxs_res.txs) |
| 14209 | { |
| 14210 | THROW_WALLET_EXCEPTION_IF(e.in_pool, error::wallet_internal_error, "spent tx isn't supposed to be in txpool"); |
| 14211 | |
| 14212 | cryptonote::transaction spent_tx; |
| 14213 | crypto::hash spnet_txid_parsed; |
| 14214 | THROW_WALLET_EXCEPTION_IF(!get_pruned_tx(e, spent_tx, spnet_txid_parsed), error::wallet_internal_error, "Failed to get tx from daemon"); |
| 14215 | THROW_WALLET_EXCEPTION_IF(!(spnet_txid_parsed == *it), error::wallet_internal_error, "parsed txid mismatch"); |
| 14216 | ++it; |
| 14217 | |
| 14218 | // get received (change) amount |
| 14219 | uint64_t tx_money_got_in_outs = 0; |
| 14220 | const cryptonote::account_keys& keys = m_account.get_keys(); |
| 14221 | const crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(spent_tx); |
| 14222 | crypto::key_derivation derivation; |
| 14223 | bool r = hwdev.generate_key_derivation(tx_pub_key, keys.m_view_secret_key, derivation); |
| 14224 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key derivation"); |
| 14225 | const std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(spent_tx); |
| 14226 | std::vector<crypto::key_derivation> additional_derivations; |
| 14227 | for (size_t i = 0; i < additional_tx_pub_keys.size(); ++i) |
| 14228 | { |
| 14229 | additional_derivations.push_back({}); |
| 14230 | r = hwdev.generate_key_derivation(additional_tx_pub_keys[i], keys.m_view_secret_key, additional_derivations.back()); |
| 14231 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key derivation"); |
| 14232 | } |
| 14233 | size_t output_index = 0; |
| 14234 | bool miner_tx = cryptonote::is_coinbase(spent_tx); |
| 14235 | for (const cryptonote::tx_out& out : spent_tx.vout) |
| 14236 | { |
| 14237 | tx_scan_info_t tx_scan_info; |
| 14238 | check_acc_out_precomp(out, derivation, additional_derivations, output_index, tx_scan_info); |
| 14239 | THROW_WALLET_EXCEPTION_IF(tx_scan_info.error, error::wallet_internal_error, "check_acc_out_precomp failed"); |
| 14240 | if (tx_scan_info.received) |
| 14241 | { |
| 14242 | if (tx_scan_info.money_transfered == 0 && !miner_tx) |
| 14243 | { |
| 14244 | rct::key mask; |
| 14245 | tx_scan_info.money_transfered = tools::decodeRct(spent_tx.rct_signatures, tx_scan_info.received->derivation, output_index, mask, hwdev); |
| 14246 | } |
| 14247 | THROW_WALLET_EXCEPTION_IF(tx_money_got_in_outs >= std::numeric_limits<uint64_t>::max() - tx_scan_info.money_transfered, |
| 14248 | error::wallet_internal_error, "Overflow in received amounts"); |
| 14249 | tx_money_got_in_outs += tx_scan_info.money_transfered; |
| 14250 | } |
| 14251 | ++output_index; |
| 14252 | } |
| 14253 | |
| 14254 | // get spent amount |
| 14255 | uint64_t tx_money_spent_in_ins = 0; |
| 14256 | uint32_t subaddr_account = (uint32_t)-1; |
| 14257 | std::set<uint32_t> subaddr_indices; |
| 14258 | for (const cryptonote::txin_v& in : spent_tx.vin) |
| 14259 | { |
| 14260 | if (in.type() != typeid(cryptonote::txin_to_key)) |
| 14261 | continue; |
| 14262 | auto it = m_key_images.find(boost::get<cryptonote::txin_to_key>(in).k_image); |
| 14263 | if (it != m_key_images.end()) |
| 14264 | { |
| 14265 | THROW_WALLET_EXCEPTION_IF(it->second >= m_transfers.size(), error::wallet_internal_error, std::string("Key images cache contains illegal transfer offset: ") + std::to_string(it->second) + std::string(" m_transfers.size() = ") + std::to_string(m_transfers.size())); |
| 14266 | const transfer_details& td = m_transfers[it->second]; |
| 14267 | uint64_t amount = boost::get<cryptonote::txin_to_key>(in).amount; |
| 14268 | if (amount > 0) |
| 14269 | { |
| 14270 | THROW_WALLET_EXCEPTION_IF(amount != td.amount(), error::wallet_internal_error, |
| 14271 | std::string("Inconsistent amount in tx input: got ") + print_money(amount) + |
| 14272 | std::string(", expected ") + print_money(td.amount())); |
| 14273 | } |
| 14274 | amount = td.amount(); |
| 14275 | tx_money_spent_in_ins += amount; |
| 14276 | |
| 14277 | LOG_PRINT_L0("Spent money: " << print_money(amount) << ", with tx: " << *spent_txid); |
| 14278 | set_spent(it->second, e.block_height); |
| 14279 | if (m_callback) |
| 14280 | m_callback->on_money_spent(e.block_height, *spent_txid, spent_tx, amount, spent_tx, td.m_subaddr_index); |
| 14281 | if (subaddr_account != (uint32_t)-1 && subaddr_account != td.m_subaddr_index.major) |
| 14282 | LOG_PRINT_L0("WARNING: This tx spends outputs received by different subaddress accounts, which isn't supposed to happen"); |
| 14283 | subaddr_account = td.m_subaddr_index.major; |
| 14284 | subaddr_indices.insert(td.m_subaddr_index.minor); |
| 14285 | } |
| 14286 | } |
| 14287 | |
| 14288 | // create outgoing payment |
| 14289 | process_outgoing(*spent_txid, spent_tx, e.block_height, e.block_timestamp, tx_money_spent_in_ins, tx_money_got_in_outs, subaddr_account, subaddr_indices); |
| 14290 | |
| 14291 | // erase corresponding incoming payment |
| 14292 | for (auto j = m_payments.begin(); j != m_payments.end(); ++j) |
| 14293 | { |
| 14294 | if (j->second.m_tx_hash == *spent_txid) |
| 14295 | { |
| 14296 | m_payments.erase(j); |
| 14297 | break; |
| 14298 | } |
| 14299 | } |
| 14300 | |
| 14301 | ++spent_txid; |
| 14302 | } |
| 14303 | PERF_TIMER_STOP(import_key_images_F); |
| 14304 | |
| 14305 | PERF_TIMER_START(import_key_images_G); |
| 14306 | for (size_t n : swept_transfers) |
| 14307 | { |
| 14308 | const transfer_details& td = m_transfers[n]; |
| 14309 | confirmed_transfer_details pd; |
| 14310 | pd.m_change = (uint64_t)-1; // change is unknown |
| 14311 | pd.m_amount_in = pd.m_amount_out = td.amount(); // fee is unknown |
| 14312 | pd.m_block_height = 0; // spent block height is unknown |
| 14313 | const crypto::hash &spent_txid = crypto::null_hash; // spent txid is unknown |
| 14314 | m_confirmed_txs.insert(std::make_pair(spent_txid, pd)); |
| 14315 | } |
| 14316 | PERF_TIMER_STOP(import_key_images_G); |
| 14317 | } |
| 14318 | |
| 14319 | // this can be 0 if we do not know the height |
| 14320 | return m_transfers[signed_key_images.size() + offset - 1].m_block_height; |
| 14321 | } |
| 14322 | |
| 14323 | bool wallet2::import_key_images(std::vector<crypto::key_image> key_images, size_t offset, boost::optional<std::unordered_set<size_t>> selected_transfers) |
| 14324 | { |
| 14325 | if (key_images.size() + offset > m_transfers.size()) |
| 14326 | { |
| 14327 | LOG_PRINT_L1("More key images returned that we know outputs for"); |
| 14328 | return false; |
| 14329 | } |
| 14330 | for (size_t ki_idx = 0; ki_idx < key_images.size(); ++ki_idx) |
| 14331 | { |
| 14332 | const size_t transfer_idx = ki_idx + offset; |
| 14333 | if (selected_transfers && selected_transfers.get().find(transfer_idx) == selected_transfers.get().end()) |
| 14334 | continue; |
| 14335 | |
| 14336 | transfer_details &td = m_transfers[transfer_idx]; |
| 14337 | if (td.m_key_image_known && !td.m_key_image_partial && td.m_key_image != key_images[ki_idx]) |
| 14338 | LOG_PRINT_L0("WARNING: imported key image differs from previously known key image at index " << ki_idx << ": trusting imported one"); |
| 14339 | td.m_key_image = key_images[ki_idx]; |
| 14340 | m_key_images[td.m_key_image] = transfer_idx; |
| 14341 | td.m_key_image_known = true; |
| 14342 | td.m_key_image_request = false; |
| 14343 | td.m_key_image_partial = false; |
| 14344 | m_pub_keys[td.get_public_key()] = transfer_idx; |
| 14345 | } |
| 14346 | |
| 14347 | return true; |
| 14348 | } |
| 14349 | |
| 14350 | bool wallet2::import_key_images(signed_tx_set & signed_tx, size_t offset, bool only_selected_transfers) |
| 14351 | { |
| 14352 | std::unordered_set<size_t> selected_transfers; |
| 14353 | if (only_selected_transfers) |
| 14354 | { |
| 14355 | for (const pending_tx & ptx : signed_tx.ptx) |
| 14356 | { |
| 14357 | for (const size_t s: ptx.selected_transfers) |
| 14358 | selected_transfers.insert(s); |
| 14359 | } |
| 14360 | } |
| 14361 | |
| 14362 | return import_key_images(signed_tx.key_images, offset, only_selected_transfers ? boost::make_optional(selected_transfers) : boost::none); |
| 14363 | } |
| 14364 | |
| 14365 | /* |
| 14366 | In background sync mode, we use just the view key when the wallet is scanning |
| 14367 | to identify all txs where: |
| 14368 | |
| 14369 | 1. We received an output. |
| 14370 | 2. We spent an output. |
| 14371 | 3. We *may* have spent a received output but we didn't know for sure because |
| 14372 | the spend key was not loaded while background sync was enabled. |
| 14373 | |
| 14374 | When the user is ready to use the spend key again, we call this function to |
| 14375 | process all those background synced transactions with the spend key loaded, |
| 14376 | so that we can properly generate key images for the transactions which we |
| 14377 | we were not able to do so for while background sync was enabled. This allows |
| 14378 | us to determine *all* receives and spends the user completed while the wallet |
| 14379 | had background sync enabled. Once this function completes, we can continue |
| 14380 | scanning from where the background sync left off. |
| 14381 | |
| 14382 | Txs of type 3 (txs which we *may* have spent received output(s)) are txs where |
| 14383 | 1+ rings contain an output that the user received and the wallet does not know |
| 14384 | the associated key image for that output. We don't know if the user spent in |
| 14385 | this type of tx or not. This function will generate key images for all outputs |
| 14386 | we don't know key images for, and then check if those outputs were spent in |
| 14387 | the txs of type 3. |
| 14388 | |
| 14389 | By storing this type of "plausible spend tx" when scanning in background sync |
| 14390 | mode, we avoid the need to query the daemon with key images when background |
| 14391 | sync mode is disabled to see if those key images were spent. This would |
| 14392 | reveal key images to 3rd party nodes for users who don't run their own. |
| 14393 | Although this is not a perfect solution to avoid revealing key images to a 3rd |
| 14394 | party node (since tx submission trivially reveals key images to a node), it's |
| 14395 | probably better than revealing *unused* key images to a 3rd party node, which |
| 14396 | would enable the 3rd party to deduce that a tx is spending an output at least |
| 14397 | X old when the key image is included in the chain. |
| 14398 | */ |
| 14399 | void wallet2::process_background_cache(const background_sync_data_t &background_sync_data, const hashchain &background_synced_chain, uint64_t last_block_reward) |
| 14400 | { |
| 14401 | // We expect the spend key to be in a decrypted state while |
| 14402 | // m_processing_background_cache is true |
| 14403 | m_processing_background_cache = true; |
| 14404 | auto done_processing = epee::misc_utils::create_scope_leave_handler([&, this]() { |
| 14405 | m_processing_background_cache = false; |
| 14406 | }); |
| 14407 | |
| 14408 | if (m_background_syncing || m_multisig || m_watch_only || key_on_device()) |
| 14409 | return; |
| 14410 | |
| 14411 | if (!background_sync_data.first_refresh_done) |
| 14412 | { |
| 14413 | MDEBUG("Skipping processing background cache, background cache has not synced yet"); |
| 14414 | return; |
| 14415 | } |
| 14416 | |
| 14417 | // Skip processing if wallet cache is synced higher than background cache |
| 14418 | const uint64_t current_height = m_blockchain.size(); |
| 14419 | const uint64_t background_height = background_synced_chain.size(); |
| 14420 | MDEBUG("Background cache height " << background_height << " , wallet height " << current_height); |
| 14421 | if (current_height > background_height) |
| 14422 | { |
| 14423 | MWARNING("Skipping processing background cache, synced height is higher than background cache"); |
| 14424 | return; |
| 14425 | } |
| 14426 | |
| 14427 | if (m_refresh_from_block_height < background_sync_data.wallet_refresh_from_block_height || |
| 14428 | m_subaddress_lookahead_major > background_sync_data.subaddress_lookahead_major || |
| 14429 | m_subaddress_lookahead_minor > background_sync_data.subaddress_lookahead_minor || |
| 14430 | m_refresh_type < background_sync_data.wallet_refresh_type) |
| 14431 | { |
| 14432 | MWARNING("Skipping processing background cache, background wallet sync settings did not match main wallet's"); |
| 14433 | MDEBUG("Wallet settings: " << |
| 14434 | ", m_refresh_from_block_height: " << m_refresh_from_block_height << " vs " << background_sync_data.wallet_refresh_from_block_height << |
| 14435 | ", m_subaddress_lookahead_major: " << m_subaddress_lookahead_major << " vs " << background_sync_data.subaddress_lookahead_major << |
| 14436 | ", m_subaddress_lookahead_minor: " << m_subaddress_lookahead_minor << " vs " << background_sync_data.subaddress_lookahead_minor << |
| 14437 | ", m_refresh_type: " << m_refresh_type << " vs " << background_sync_data.wallet_refresh_type); |
| 14438 | return; |
| 14439 | } |
| 14440 | |
| 14441 | // Sort background synced txs in the order they appeared in the cache so that |
| 14442 | // we process them in the order they appeared in the chain. Thus if tx2 spends |
| 14443 | // from tx1, we will know because tx1 is processed before tx2. |
| 14444 | std::vector<std::pair<crypto::hash, background_synced_tx_t>> sorted_bgs_cache(background_sync_data.txs.begin(), background_sync_data.txs.end()); |
| 14445 | std::sort(sorted_bgs_cache.begin(), sorted_bgs_cache.end(), |
| 14446 | [](const std::pair<crypto::hash, background_synced_tx_t>& l, const std::pair<crypto::hash, background_synced_tx_t>& r) |
| 14447 | { |
| 14448 | uint64_t left_index = l.second.index_in_background_sync_data; |
| 14449 | uint64_t right_index = r.second.index_in_background_sync_data; |
| 14450 | THROW_WALLET_EXCEPTION_IF( |
| 14451 | (left_index < right_index && l.second.height > r.second.height) || |
| 14452 | (left_index > right_index && l.second.height < r.second.height), |
| 14453 | error::wallet_internal_error, "Unexpected background sync data order"); |
| 14454 | return left_index < right_index; |
| 14455 | }); |
| 14456 | |
| 14457 | // All txs in the background cache should have height >= sync start height, |
| 14458 | // but not fatal if not |
| 14459 | if (!sorted_bgs_cache.empty() && sorted_bgs_cache[0].second.height < background_sync_data.start_height) |
| 14460 | MWARNING("First tx in background cache has height (" << sorted_bgs_cache[0].second.height << ") lower than sync start height (" << background_sync_data.start_height << ")"); |
| 14461 | |
| 14462 | // We want to process all background synced txs in order to make sure |
| 14463 | // the wallet state updates correctly. First we remove all txs from the wallet |
| 14464 | // from before the background sync start height, then re-process them in |
| 14465 | // chronological order. The background cache should contain a superset of |
| 14466 | // *all* the wallet's txs from after the background sync start height. |
| 14467 | MDEBUG("Processing " << background_sync_data.txs.size() << " background synced txs starting from height " << background_sync_data.start_height); |
| 14468 | detached_blockchain_data dbd = detach_blockchain(background_sync_data.start_height); |
| 14469 | |
| 14470 | for (const auto &bgs_tx : sorted_bgs_cache) |
| 14471 | { |
| 14472 | MDEBUG("Processing background synced tx " << bgs_tx.first); |
| 14473 | |
| 14474 | process_new_transaction(bgs_tx.first, bgs_tx.second.tx, bgs_tx.second.output_indices, bgs_tx.second.height, 0, bgs_tx.second.block_timestamp, |
| 14475 | cryptonote::is_coinbase(bgs_tx.second.tx), false/*pool*/, bgs_tx.second.double_spend_seen, {}, {}, true/*ignore_callbacks*/); |
| 14476 | |
| 14477 | // Re-set destination addresses if they were previously set |
| 14478 | if (m_confirmed_txs.find(bgs_tx.first) != m_confirmed_txs.end() && |
| 14479 | dbd.detached_confirmed_txs_dests.find(bgs_tx.first) != dbd.detached_confirmed_txs_dests.end()) |
| 14480 | { |
| 14481 | m_confirmed_txs[bgs_tx.first].m_dests = std::move(dbd.detached_confirmed_txs_dests[bgs_tx.first]); |
| 14482 | } |
| 14483 | } |
| 14484 | |
| 14485 | m_blockchain = background_synced_chain; |
| 14486 | m_last_block_reward = last_block_reward; |
| 14487 | |
| 14488 | MDEBUG("Finished processing background sync data"); |
| 14489 | } |
| 14490 | //---------------------------------------------------------------------------------------------------- |
| 14491 | void wallet2::reset_background_sync_data(background_sync_data_t &background_sync_data) |
| 14492 | { |
| 14493 | background_sync_data.first_refresh_done = false; |
| 14494 | background_sync_data.start_height = get_blockchain_current_height(); |
| 14495 | background_sync_data.txs.clear(); |
| 14496 | |
| 14497 | background_sync_data.wallet_refresh_from_block_height = m_refresh_from_block_height; |
| 14498 | background_sync_data.subaddress_lookahead_major = m_subaddress_lookahead_major; |
| 14499 | background_sync_data.subaddress_lookahead_minor = m_subaddress_lookahead_minor; |
| 14500 | background_sync_data.wallet_refresh_type = m_refresh_type; |
| 14501 | } |
| 14502 | //---------------------------------------------------------------------------------------------------- |
| 14503 | void wallet2::store_background_cache(const crypto::chacha_key &custom_background_key, const bool do_reset_background_sync_data) |
| 14504 | { |
| 14505 | MDEBUG("Storing background cache (do_reset_background_sync_data=" << do_reset_background_sync_data << ")"); |
| 14506 | |
| 14507 | THROW_WALLET_EXCEPTION_IF(m_background_sync_type != BackgroundSyncCustomPassword, error::wallet_internal_error, |
| 14508 | "Can only write a background cache when using a custom background password"); |
| 14509 | THROW_WALLET_EXCEPTION_IF(m_wallet_file.empty(), error::wallet_internal_error, |
| 14510 | "No wallet file known, can't store background cache"); |
| 14511 | |
| 14512 | std::unique_ptr<wallet2> background_w2(new wallet2(m_nettype)); |
| 14513 | background_w2->prepare_file_names(make_background_wallet_file_name(m_wallet_file)); |
| 14514 | |
| 14515 | // Make sure background wallet is opened by this wallet |
| 14516 | THROW_WALLET_EXCEPTION_IF(!lock_background_keys_file(background_w2->m_keys_file), |
| 14517 | error::background_wallet_already_open, background_w2->m_wallet_file); |
| 14518 | |
| 14519 | // Load a background wallet2 instance using this wallet2 instance |
| 14520 | std::string this_wallet2; |
| 14521 | bool r = ::serialization::dump_binary(*this, this_wallet2); |
| 14522 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to serialize wallet cache"); |
| 14523 | |
| 14524 | background_w2->clear(); |
| 14525 | r = ::serialization::parse_binary(this_wallet2, *background_w2); |
| 14526 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to deserialize wallet cache"); |
| 14527 | |
| 14528 | // Clear sensitive data from background cache not needed to sync |
| 14529 | background_w2->clear_user_data(); |
| 14530 | |
| 14531 | background_w2->m_is_background_wallet = true; |
| 14532 | if (do_reset_background_sync_data) |
| 14533 | reset_background_sync_data(background_w2->m_background_sync_data); |
| 14534 | else |
| 14535 | background_w2->m_background_sync_data = m_background_sync_data; |
| 14536 | background_w2->m_background_syncing = true; |
| 14537 | |
| 14538 | background_w2->m_custom_background_key = boost::optional<crypto::chacha_key>(custom_background_key); |
| 14539 | background_w2->m_background_sync_type = m_background_sync_type; |
| 14540 | background_w2->store(); |
| 14541 | |
| 14542 | MDEBUG("Background cache stored (" << background_w2->m_transfers.size() << " transfers, " << background_w2->m_background_sync_data.txs.size() << " background synced txs)"); |
| 14543 | } |
| 14544 | //---------------------------------------------------------------------------------------------------- |
| 14545 | void wallet2::store_background_keys(const crypto::chacha_key &custom_background_key) |
| 14546 | { |
| 14547 | MDEBUG("Storing background keys"); |
| 14548 | |
| 14549 | THROW_WALLET_EXCEPTION_IF(m_wallet_file.empty(), error::wallet_internal_error, |
| 14550 | "No wallet file known, can't store background keys"); |
| 14551 | |
| 14552 | const std::string background_keys_file = make_background_keys_file_name(m_wallet_file); |
| 14553 | bool r = store_keys(background_keys_file, custom_background_key, false/*watch_only*/, true/*background_keys_file*/); |
| 14554 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, background_keys_file); |
| 14555 | THROW_WALLET_EXCEPTION_IF(!is_background_keys_file_locked(), error::wallet_internal_error, background_keys_file + "\" should be locked"); |
| 14556 | |
| 14557 | // GUI uses the address file to differentiate non-mainnet wallets in the UI |
| 14558 | const std::string background_address_file = make_background_wallet_file_name(m_wallet_file) + ".address.txt"; |
| 14559 | if (m_nettype != MAINNET && !boost::filesystem::exists(background_address_file)) |
| 14560 | { |
| 14561 | r = save_to_file(background_address_file, m_account.get_public_address_str(m_nettype), true); |
| 14562 | if (!r) MERROR("String with address text not saved"); |
| 14563 | } |
| 14564 | |
| 14565 | MDEBUG("Background keys stored"); |
| 14566 | } |
| 14567 | //---------------------------------------------------------------------------------------------------- |
| 14568 | void wallet2::write_background_sync_wallet(const epee::wipeable_string &wallet_password, const epee::wipeable_string &background_cache_password) |
| 14569 | { |
| 14570 | MDEBUG("Storing background sync wallet"); |
| 14571 | THROW_WALLET_EXCEPTION_IF(m_background_sync_type != BackgroundSyncCustomPassword, error::wallet_internal_error, |
| 14572 | "Can only write a background sync wallet when using a custom background password"); |
| 14573 | THROW_WALLET_EXCEPTION_IF(m_background_syncing || m_is_background_wallet, error::wallet_internal_error, |
| 14574 | "Can't write background sync wallet from an existing background cache"); |
| 14575 | THROW_WALLET_EXCEPTION_IF(wallet_password == background_cache_password, |
| 14576 | error::background_custom_password_same_as_wallet_password); |
| 14577 | |
| 14578 | // Set the background encryption key |
| 14579 | crypto::chacha_key custom_background_key; |
| 14580 | get_custom_background_key(background_cache_password, custom_background_key, m_kdf_rounds); |
| 14581 | |
| 14582 | // Keep the background encryption key in memory so the main wallet can update |
| 14583 | // the background cache when it stores the main wallet cache |
| 14584 | m_custom_background_key = boost::optional<crypto::chacha_key>(custom_background_key); |
| 14585 | |
| 14586 | if (m_wallet_file.empty() || m_keys_file.empty()) |
| 14587 | return; |
| 14588 | |
| 14589 | // Save background keys file, then background cache, then update main wallet settings |
| 14590 | store_background_keys(custom_background_key); |
| 14591 | store_background_cache(custom_background_key, true/*do_reset_background_sync_data*/); |
| 14592 | bool r = store_keys(m_keys_file, wallet_password, false/*watch_only*/); |
| 14593 | THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file); |
| 14594 | |
| 14595 | MDEBUG("Background sync wallet saved successfully"); |
| 14596 | } |
| 14597 | //---------------------------------------------------------------------------------------------------- |
| 14598 | void wallet2::setup_background_sync(BackgroundSyncType background_sync_type, const epee::wipeable_string &wallet_password, const boost::optional<epee::wipeable_string> &background_cache_password) |
| 14599 | { |
| 14600 | MDEBUG("Setting background sync to type " << background_sync_type); |
| 14601 | THROW_WALLET_EXCEPTION_IF(m_background_syncing || m_is_background_wallet, error::wallet_internal_error, |
| 14602 | "Can't set background sync type from an existing background cache"); |
| 14603 | verify_password_with_cached_key(wallet_password); |
| 14604 | |
| 14605 | if (background_sync_type != BackgroundSyncOff) |
| 14606 | validate_background_cache_password_usage(background_sync_type, background_cache_password, m_multisig, m_watch_only, key_on_device()); |
| 14607 | |
| 14608 | THROW_WALLET_EXCEPTION_IF(background_sync_type == BackgroundSyncCustomPassword && wallet_password == background_cache_password, |
| 14609 | error::background_custom_password_same_as_wallet_password); |
| 14610 | |
| 14611 | if (m_background_sync_type == background_sync_type && background_sync_type != BackgroundSyncCustomPassword) |
| 14612 | return; // No need to make any changes |
| 14613 | |
| 14614 | if (!m_wallet_file.empty()) |
| 14615 | { |
| 14616 | // Delete existing background files if they already exist |
| 14617 | const std::string old_background_wallet_file = make_background_wallet_file_name(m_wallet_file); |
| 14618 | const std::string old_background_keys_file = make_background_keys_file_name(m_wallet_file); |
| 14619 | const std::string old_background_address_file = old_background_wallet_file + ".address.txt"; |
| 14620 | |
| 14621 | // Make sure no other program is using the background wallet |
| 14622 | THROW_WALLET_EXCEPTION_IF(!lock_background_keys_file(old_background_keys_file), |
| 14623 | error::background_wallet_already_open, old_background_wallet_file); |
| 14624 | |
| 14625 | if (boost::filesystem::exists(old_background_wallet_file)) |
| 14626 | if (!boost::filesystem::remove(old_background_wallet_file)) |
| 14627 | LOG_ERROR("Error deleting background wallet file: " << old_background_wallet_file); |
| 14628 | |
| 14629 | if (boost::filesystem::exists(old_background_keys_file)) |
| 14630 | if (!boost::filesystem::remove(old_background_keys_file)) |
| 14631 | LOG_ERROR("Error deleting background keys file: " << old_background_keys_file); |
| 14632 | |
| 14633 | if (boost::filesystem::exists(old_background_address_file)) |
| 14634 | if (!boost::filesystem::remove(old_background_address_file)) |
| 14635 | LOG_ERROR("Error deleting background address file: " << old_background_address_file); |
| 14636 | } |
| 14637 | |
| 14638 | m_background_sync_type = background_sync_type; |
| 14639 | m_custom_background_key = boost::none; |
| 14640 | |
| 14641 | // Write the new files |
| 14642 | switch (background_sync_type) |
| 14643 | { |
| 14644 | case BackgroundSyncOff: |
| 14645 | case BackgroundSyncReusePassword: rewrite(m_wallet_file, wallet_password); break; |
| 14646 | case BackgroundSyncCustomPassword: write_background_sync_wallet(wallet_password, background_cache_password.get()); break; |
| 14647 | default: THROW_WALLET_EXCEPTION(error::wallet_internal_error, "unknown background sync type"); |
| 14648 | } |
| 14649 | |
| 14650 | MDEBUG("Done setting background sync type"); |
| 14651 | } |
| 14652 | //---------------------------------------------------------------------------------------------------- |
| 14653 | /* |
| 14654 | When background syncing, the wallet scans using just the view key, without |
| 14655 | keeping the spend key in decrypted state. When a user returns to the wallet |
| 14656 | and decrypts the spend key, the wallet processes the background synced txs, |
| 14657 | then the wallet picks up scanning normally right where the background sync |
| 14658 | left off. |
| 14659 | */ |
| 14660 | void wallet2::start_background_sync() |
| 14661 | { |
| 14662 | THROW_WALLET_EXCEPTION_IF(m_background_sync_type == BackgroundSyncOff, error::wallet_internal_error, |
| 14663 | "must setup background sync first before using background sync"); |
| 14664 | THROW_WALLET_EXCEPTION_IF(m_is_background_wallet, error::wallet_internal_error, |
| 14665 | "Can't start background syncing from a background wallet (it is always background syncing)"); |
| 14666 | |
| 14667 | MDEBUG("Starting background sync"); |
| 14668 | |
| 14669 | if (m_background_syncing) |
| 14670 | { |
| 14671 | MDEBUG("Already background syncing"); |
| 14672 | return; |
| 14673 | } |
| 14674 | |
| 14675 | if (m_background_sync_type == BackgroundSyncCustomPassword && !m_wallet_file.empty()) |
| 14676 | { |
| 14677 | // Save the current state of the wallet cache. Only necessary when using a |
| 14678 | // custom background password which uses distinct background wallet to sync. |
| 14679 | // When reusing wallet password to sync we reuse the main wallet cache. |
| 14680 | store(); |
| 14681 | |
| 14682 | // Wipe user data from the background wallet cache not needed to sync. |
| 14683 | // Only wipe user data from background cache if wallet cache is stored |
| 14684 | // on disk; otherwise we could lose the data. |
| 14685 | clear_user_data(); |
| 14686 | |
| 14687 | // Wipe m_cache_key since it can be used to decrypt main wallet cache |
| 14688 | m_cache_key.scrub(); |
| 14689 | } |
| 14690 | |
| 14691 | reset_background_sync_data(m_background_sync_data); |
| 14692 | m_background_syncing = true; |
| 14693 | |
| 14694 | // Wipe the spend key from memory |
| 14695 | m_account.forget_spend_key(); |
| 14696 | |
| 14697 | MDEBUG("Background sync started at height " << m_background_sync_data.start_height); |
| 14698 | } |
| 14699 | //---------------------------------------------------------------------------------------------------- |
| 14700 | void wallet2::stop_background_sync(const epee::wipeable_string &wallet_password, const crypto::secret_key &spend_secret_key) |
| 14701 | { |
| 14702 | MDEBUG("Stopping background sync"); |
| 14703 | |
| 14704 | // Verify provided password and spend secret key. If no spend secret key is |
| 14705 | // provided, recover it from the wallet keys file |
| 14706 | crypto::secret_key recovered_spend_key = crypto::null_skey; |
| 14707 | if (!m_wallet_file.empty()) |
| 14708 | { |
| 14709 | THROW_WALLET_EXCEPTION_IF(!verify_password(wallet_password, recovered_spend_key), error::invalid_password); |
| 14710 | } |
| 14711 | else |
| 14712 | { |
| 14713 | verify_password_with_cached_key(wallet_password); |
| 14714 | } |
| 14715 | |
| 14716 | if (spend_secret_key != crypto::null_skey) |
| 14717 | { |
| 14718 | THROW_WALLET_EXCEPTION_IF(!m_wallet_file.empty() && spend_secret_key != recovered_spend_key, |
| 14719 | error::invalid_spend_key); |
| 14720 | MDEBUG("Setting spend secret key with the provided key"); |
| 14721 | recovered_spend_key = spend_secret_key; |
| 14722 | } |
| 14723 | |
| 14724 | // Verify private spend key derives to wallet's public spend key |
| 14725 | const auto verify_spend_key = [this](crypto::secret_key &recovered_spend_key) -> bool |
| 14726 | { |
| 14727 | crypto::public_key spend_public_key; |
| 14728 | return recovered_spend_key != crypto::null_skey && |
| 14729 | crypto::secret_key_to_public_key(recovered_spend_key, spend_public_key) && |
| 14730 | m_account.get_keys().m_account_address.m_spend_public_key == spend_public_key; |
| 14731 | }; |
| 14732 | THROW_WALLET_EXCEPTION_IF(!verify_spend_key(recovered_spend_key), error::invalid_spend_key); |
| 14733 | |
| 14734 | THROW_WALLET_EXCEPTION_IF(m_background_sync_type == BackgroundSyncOff, error::wallet_internal_error, |
| 14735 | "must setup background sync first before using background sync"); |
| 14736 | THROW_WALLET_EXCEPTION_IF(m_is_background_wallet, error::wallet_internal_error, |
| 14737 | "Can't stop background syncing from a background wallet"); |
| 14738 | |
| 14739 | if (!m_background_syncing) |
| 14740 | return; |
| 14741 | |
| 14742 | // Copy background cache, we're about to overwrite it |
| 14743 | const background_sync_data_t background_sync_data = m_background_sync_data; |
| 14744 | const hashchain background_synced_chain = m_blockchain; |
| 14745 | const uint64_t last_block_reward = m_last_block_reward; |
| 14746 | |
| 14747 | if (m_background_sync_type == BackgroundSyncCustomPassword && !m_wallet_file.empty()) |
| 14748 | { |
| 14749 | // Reload the wallet from disk |
| 14750 | load(m_wallet_file, wallet_password); |
| 14751 | THROW_WALLET_EXCEPTION_IF(!verify_spend_key(recovered_spend_key), error::invalid_spend_key); |
| 14752 | } |
| 14753 | m_background_syncing = false; |
| 14754 | |
| 14755 | // Set the plaintext spend key |
| 14756 | m_account.set_spend_key(recovered_spend_key); |
| 14757 | |
| 14758 | // Encrypt the spend key when done if needed |
| 14759 | epee::misc_utils::auto_scope_leave_caller keys_reencryptor; |
| 14760 | if (m_ask_password == AskPasswordToDecrypt && !m_unattended && !m_watch_only) |
| 14761 | keys_reencryptor = epee::misc_utils::create_scope_leave_handler([&, this]{encrypt_keys(wallet_password);}); |
| 14762 | |
| 14763 | // Now we can use the decrypted spend key to process background cache |
| 14764 | process_background_cache(background_sync_data, background_synced_chain, last_block_reward); |
| 14765 | |
| 14766 | // Reset the background cache after processing |
| 14767 | reset_background_sync_data(m_background_sync_data); |
| 14768 | |
| 14769 | MDEBUG("Background sync stopped"); |
| 14770 | } |
| 14771 | //---------------------------------------------------------------------------------------------------- |
| 14772 | wallet2::payment_container wallet2::export_payments() const |
| 14773 | { |
| 14774 | payment_container payments; |
| 14775 | for (auto const &p : m_payments) |
| 14776 | { |
| 14777 | payments.emplace(p); |
| 14778 | } |
| 14779 | return payments; |
| 14780 | } |
| 14781 | void wallet2::import_payments(const payment_container &payments) |
| 14782 | { |
| 14783 | m_payments.clear(); |
| 14784 | for (auto const &p : payments) |
| 14785 | { |
| 14786 | m_payments.emplace(p); |
| 14787 | } |
| 14788 | } |
| 14789 | void wallet2::import_payments_out(const std::list<std::pair<crypto::hash,wallet2::confirmed_transfer_details>> &confirmed_payments) |
| 14790 | { |
| 14791 | m_confirmed_txs.clear(); |
| 14792 | for (auto const &p : confirmed_payments) |
| 14793 | { |
| 14794 | m_confirmed_txs.emplace(p); |
| 14795 | } |
| 14796 | } |
| 14797 | |
| 14798 | std::tuple<size_t,crypto::hash,std::vector<crypto::hash>> wallet2::export_blockchain() const |
| 14799 | { |
| 14800 | std::tuple<size_t, crypto::hash, std::vector<crypto::hash>> bc; |
| 14801 | std::get<0>(bc) = m_blockchain.offset(); |
| 14802 | std::get<1>(bc) = m_blockchain.empty() ? crypto::null_hash: m_blockchain.genesis(); |
| 14803 | for (size_t n = m_blockchain.offset(); n < m_blockchain.size(); ++n) |
| 14804 | { |
| 14805 | std::get<2>(bc).push_back(m_blockchain[n]); |
| 14806 | } |
| 14807 | return bc; |
| 14808 | } |
| 14809 | |
| 14810 | void wallet2::import_blockchain(const std::tuple<size_t, crypto::hash, std::vector<crypto::hash>> &bc) |
| 14811 | { |
| 14812 | m_blockchain.clear(); |
| 14813 | if (std::get<0>(bc)) |
| 14814 | { |
| 14815 | for (size_t n = std::get<0>(bc); n > 0; --n) |
| 14816 | m_blockchain.push_back(std::get<1>(bc)); |
| 14817 | m_blockchain.trim(std::get<0>(bc)); |
| 14818 | } |
| 14819 | for (auto const &b : std::get<2>(bc)) |
| 14820 | { |
| 14821 | m_blockchain.push_back(b); |
| 14822 | } |
| 14823 | cryptonote::block genesis; |
| 14824 | generate_genesis(genesis); |
| 14825 | crypto::hash genesis_hash = get_block_hash(genesis); |
| 14826 | check_genesis(genesis_hash); |
| 14827 | m_last_block_reward = cryptonote::get_outs_money_amount(genesis.miner_tx); |
| 14828 | } |
| 14829 | //---------------------------------------------------------------------------------------------------- |
| 14830 | std::tuple<uint64_t, uint64_t, std::vector<tools::wallet2::exported_transfer_details>> wallet2::export_outputs(bool all, uint32_t start, uint32_t count) const |
| 14831 | { |
| 14832 | PERF_TIMER(export_outputs); |
| 14833 | std::vector<tools::wallet2::exported_transfer_details> outs; |
| 14834 | |
| 14835 | // invalid cases |
| 14836 | THROW_WALLET_EXCEPTION_IF(count == 0, error::wallet_internal_error, "Nothing requested"); |
| 14837 | THROW_WALLET_EXCEPTION_IF(!all && start > 0, error::wallet_internal_error, "Incremental mode is incompatible with non-zero start"); |
| 14838 | |
| 14839 | // valid cases: |
| 14840 | // all: all outputs, subject to start/count |
| 14841 | // !all: incremental, subject to count |
| 14842 | // for convenience, start/count are allowed to go past the valid range, then nothing is returned |
| 14843 | |
| 14844 | size_t offset = 0; |
| 14845 | if (!all) |
| 14846 | while (offset < m_transfers.size() && (m_transfers[offset].m_key_image_known && !m_transfers[offset].m_key_image_request)) |
| 14847 | ++offset; |
| 14848 | else |
| 14849 | offset = start; |
| 14850 | |
| 14851 | outs.reserve(m_transfers.size() - offset); |
| 14852 | for (size_t n = offset; n < m_transfers.size() && n - offset < count; ++n) |
| 14853 | { |
| 14854 | const transfer_details &td = m_transfers[n]; |
| 14855 | |
| 14856 | exported_transfer_details etd; |
| 14857 | etd.m_pubkey = td.get_public_key(); |
| 14858 | etd.m_tx_pubkey = get_tx_pub_key_from_extra(td.m_tx, td.m_pk_index); |
| 14859 | etd.m_internal_output_index = td.m_internal_output_index; |
| 14860 | etd.m_global_output_index = td.m_global_output_index; |
| 14861 | etd.m_flags.flags = 0; |
| 14862 | etd.m_flags.m_spent = td.m_spent; |
| 14863 | etd.m_flags.m_frozen = td.m_frozen; |
| 14864 | etd.m_flags.m_rct = td.m_rct; |
| 14865 | etd.m_flags.m_key_image_known = td.m_key_image_known; |
| 14866 | etd.m_flags.m_key_image_request = td.m_key_image_request; |
| 14867 | etd.m_flags.m_key_image_partial = td.m_key_image_partial; |
| 14868 | etd.m_amount = td.m_amount; |
| 14869 | etd.m_additional_tx_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 14870 | etd.m_subaddr_index_major = td.m_subaddr_index.major; |
| 14871 | etd.m_subaddr_index_minor = td.m_subaddr_index.minor; |
| 14872 | |
| 14873 | outs.push_back(etd); |
| 14874 | } |
| 14875 | |
| 14876 | return std::make_tuple(offset, m_transfers.size(), outs); |
| 14877 | } |
| 14878 | //---------------------------------------------------------------------------------------------------- |
| 14879 | std::string wallet2::export_outputs_to_str(bool all, uint32_t start, uint32_t count) const |
| 14880 | { |
| 14881 | PERF_TIMER(export_outputs_to_str); |
| 14882 | |
| 14883 | std::stringstream oss; |
| 14884 | binary_archive<true> ar(oss); |
| 14885 | auto outputs = export_outputs(all, start, count); |
| 14886 | THROW_WALLET_EXCEPTION_IF(!::serialization::serialize(ar, outputs), error::wallet_internal_error, "Failed to serialize output data"); |
| 14887 | |
| 14888 | std::string magic(OUTPUT_EXPORT_FILE_MAGIC, strlen(OUTPUT_EXPORT_FILE_MAGIC)); |
| 14889 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 14890 | std::string header; |
| 14891 | header += std::string((const char *)&keys.m_spend_public_key, sizeof(crypto::public_key)); |
| 14892 | header += std::string((const char *)&keys.m_view_public_key, sizeof(crypto::public_key)); |
| 14893 | PERF_TIMER(export_outputs_encryption); |
| 14894 | std::string ciphertext = encrypt_with_view_secret_key(header + oss.str()); |
| 14895 | return magic + ciphertext; |
| 14896 | } |
| 14897 | //---------------------------------------------------------------------------------------------------- |
| 14898 | size_t wallet2::import_outputs(const std::tuple<uint64_t, uint64_t, std::vector<tools::wallet2::transfer_details>> &outputs) |
| 14899 | { |
| 14900 | PERF_TIMER(import_outputs); |
| 14901 | |
| 14902 | THROW_WALLET_EXCEPTION_IF(m_has_ever_refreshed_from_node, error::wallet_internal_error, |
| 14903 | "Hot wallets cannot import outputs"); |
| 14904 | |
| 14905 | // we can now import piecemeal |
| 14906 | const size_t offset = std::get<0>(outputs); |
| 14907 | const size_t num_outputs = std::get<1>(outputs); |
| 14908 | const std::vector<tools::wallet2::transfer_details> &output_array = std::get<2>(outputs); |
| 14909 | |
| 14910 | THROW_WALLET_EXCEPTION_IF(offset > m_transfers.size(), error::wallet_internal_error, |
| 14911 | "Imported outputs omit more outputs that we know of"); |
| 14912 | |
| 14913 | THROW_WALLET_EXCEPTION_IF(offset + output_array.size() > num_outputs, error::wallet_internal_error, |
| 14914 | "Offset is larger than total outputs"); |
| 14915 | |
| 14916 | const size_t original_size = m_transfers.size(); |
| 14917 | if (offset + output_array.size() > m_transfers.size()) |
| 14918 | m_transfers.resize(offset + output_array.size()); |
| 14919 | else if (num_outputs < m_transfers.size()) |
| 14920 | m_transfers.resize(num_outputs); |
| 14921 | |
| 14922 | for (size_t i = 0; i < output_array.size(); ++i) |
| 14923 | { |
| 14924 | transfer_details td = output_array[i]; |
| 14925 | |
| 14926 | // skip those we've already imported, or which have different data |
| 14927 | if (i + offset < original_size) |
| 14928 | { |
| 14929 | // compare the data used to create the key image below |
| 14930 | const transfer_details &org_td = m_transfers[i + offset]; |
| 14931 | if (!org_td.m_key_image_known) |
| 14932 | goto process; |
| 14933 | #define CMPF(f) if (!(td.f == org_td.f)) goto process |
| 14934 | CMPF(m_txid); |
| 14935 | CMPF(m_key_image); |
| 14936 | CMPF(m_internal_output_index); |
| 14937 | #undef CMPF |
| 14938 | if (!(get_transaction_prefix_hash(td.m_tx) == get_transaction_prefix_hash(org_td.m_tx))) |
| 14939 | goto process; |
| 14940 | |
| 14941 | // copy anyway, since the comparison does not include ancillary fields which may have changed |
| 14942 | m_transfers[i + offset] = std::move(td); |
| 14943 | continue; |
| 14944 | } |
| 14945 | |
| 14946 | process: |
| 14947 | |
| 14948 | // the hot wallet wouldn't have known about key images (except if we already exported them) |
| 14949 | cryptonote::keypair in_ephemeral; |
| 14950 | |
| 14951 | THROW_WALLET_EXCEPTION_IF(td.m_tx.vout.empty(), error::wallet_internal_error, "tx with no outputs at index " + boost::lexical_cast<std::string>(i + offset)); |
| 14952 | crypto::public_key tx_pub_key = get_tx_pub_key_from_received_outs(td); |
| 14953 | const std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 14954 | |
| 14955 | THROW_WALLET_EXCEPTION_IF(td.m_internal_output_index >= td.m_tx.vout.size(), |
| 14956 | error::wallet_internal_error, "Internal index is out of range"); |
| 14957 | crypto::public_key out_key = td.get_public_key(); |
| 14958 | if (should_expand(td.m_subaddr_index)) |
| 14959 | create_one_off_subaddress(td.m_subaddr_index); |
| 14960 | bool r = cryptonote::generate_key_image_helper(m_account.get_keys(), m_subaddresses, out_key, tx_pub_key, additional_tx_pub_keys, td.m_internal_output_index, in_ephemeral, td.m_key_image, m_account.get_device()); |
| 14961 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 14962 | if (should_expand(td.m_subaddr_index)) |
| 14963 | expand_subaddresses(td.m_subaddr_index); |
| 14964 | td.m_key_image_known = true; |
| 14965 | td.m_key_image_request = true; |
| 14966 | td.m_key_image_partial = false; |
| 14967 | THROW_WALLET_EXCEPTION_IF(in_ephemeral.pub != out_key, |
| 14968 | error::wallet_internal_error, "key_image generated ephemeral public key not matched with output_key at index " + boost::lexical_cast<std::string>(i + offset)); |
| 14969 | |
| 14970 | m_key_images[td.m_key_image] = i + offset; |
| 14971 | m_pub_keys[td.get_public_key()] = i + offset; |
| 14972 | m_transfers[i + offset] = std::move(td); |
| 14973 | } |
| 14974 | |
| 14975 | return m_transfers.size(); |
| 14976 | } |
| 14977 | //---------------------------------------------------------------------------------------------------- |
| 14978 | size_t wallet2::import_outputs(const std::tuple<uint64_t, uint64_t, std::vector<tools::wallet2::exported_transfer_details>> &outputs) |
| 14979 | { |
| 14980 | PERF_TIMER(import_outputs); |
| 14981 | |
| 14982 | THROW_WALLET_EXCEPTION_IF(m_has_ever_refreshed_from_node, error::wallet_internal_error, |
| 14983 | "Hot wallets cannot import outputs"); |
| 14984 | |
| 14985 | // we can now import piecemeal |
| 14986 | const size_t offset = std::get<0>(outputs); |
| 14987 | const size_t num_outputs = std::get<1>(outputs); |
| 14988 | const std::vector<tools::wallet2::exported_transfer_details> &output_array = std::get<2>(outputs); |
| 14989 | |
| 14990 | THROW_WALLET_EXCEPTION_IF(offset > m_transfers.size(), error::wallet_internal_error, |
| 14991 | "Imported outputs omit more outputs that we know of. Try using export_outputs all."); |
| 14992 | |
| 14993 | THROW_WALLET_EXCEPTION_IF(offset + output_array.size() > num_outputs, error::wallet_internal_error, |
| 14994 | "Offset is larger than total outputs"); |
| 14995 | |
| 14996 | const size_t original_size = m_transfers.size(); |
| 14997 | if (offset + output_array.size() > m_transfers.size()) |
| 14998 | m_transfers.resize(offset + output_array.size()); |
| 14999 | else if (num_outputs < m_transfers.size()) |
| 15000 | m_transfers.resize(num_outputs); |
| 15001 | |
| 15002 | for (size_t i = 0; i < output_array.size(); ++i) |
| 15003 | { |
| 15004 | exported_transfer_details etd = output_array[i]; |
| 15005 | transfer_details &td = m_transfers[i + offset]; |
| 15006 | |
| 15007 | // setup td with "cheap" loaded data |
| 15008 | td.m_block_height = 0; |
| 15009 | td.m_txid = crypto::null_hash; |
| 15010 | td.m_global_output_index = etd.m_global_output_index; |
| 15011 | td.m_spent = etd.m_flags.m_spent; |
| 15012 | td.m_frozen = etd.m_flags.m_frozen; |
| 15013 | td.m_spent_height = 0; |
| 15014 | td.m_mask = rct::identity(); |
| 15015 | td.m_amount = etd.m_amount; |
| 15016 | td.m_rct = etd.m_flags.m_rct; |
| 15017 | td.m_key_image_known = etd.m_flags.m_key_image_known; |
| 15018 | td.m_key_image_request = etd.m_flags.m_key_image_request; |
| 15019 | td.m_key_image_partial = false; |
| 15020 | td.m_subaddr_index.major = etd.m_subaddr_index_major; |
| 15021 | td.m_subaddr_index.minor = etd.m_subaddr_index_minor; |
| 15022 | |
| 15023 | // skip those we've already imported, or which have different data |
| 15024 | if (i + offset < original_size) |
| 15025 | { |
| 15026 | bool needs_processing = false; |
| 15027 | if (!td.m_key_image_known) |
| 15028 | needs_processing = true; |
| 15029 | else if (!(etd.m_internal_output_index == td.m_internal_output_index)) |
| 15030 | needs_processing = true; |
| 15031 | else if (!(etd.m_pubkey == td.get_public_key())) |
| 15032 | needs_processing = true; |
| 15033 | |
| 15034 | if (!needs_processing) |
| 15035 | continue; |
| 15036 | } |
| 15037 | |
| 15038 | // construct a synthetix tx prefix that has the info we'll need: the output with its pubkey, the tx pubkey in extra |
| 15039 | td.m_tx = {}; |
| 15040 | |
| 15041 | THROW_WALLET_EXCEPTION_IF(etd.m_internal_output_index >= 65536, error::wallet_internal_error, "internal output index seems outrageously high, rejecting"); |
| 15042 | td.m_internal_output_index = etd.m_internal_output_index; |
| 15043 | cryptonote::txout_to_key tk; |
| 15044 | tk.key = etd.m_pubkey; |
| 15045 | cryptonote::tx_out out; |
| 15046 | out.amount = etd.m_amount; |
| 15047 | out.target = tk; |
| 15048 | td.m_tx.vout.resize(etd.m_internal_output_index); |
| 15049 | td.m_tx.vout.push_back(out); |
| 15050 | |
| 15051 | td.m_pk_index = 0; |
| 15052 | add_tx_pub_key_to_extra(td.m_tx, etd.m_tx_pubkey); |
| 15053 | if (!etd.m_additional_tx_keys.empty()) |
| 15054 | add_additional_tx_pub_keys_to_extra(td.m_tx.extra, etd.m_additional_tx_keys); |
| 15055 | |
| 15056 | // the hot wallet wouldn't have known about key images (except if we already exported them) |
| 15057 | cryptonote::keypair in_ephemeral; |
| 15058 | |
| 15059 | const crypto::public_key &tx_pub_key = etd.m_tx_pubkey; |
| 15060 | const std::vector<crypto::public_key> &additional_tx_pub_keys = etd.m_additional_tx_keys; |
| 15061 | const crypto::public_key& out_key = etd.m_pubkey; |
| 15062 | if (should_expand(td.m_subaddr_index)) |
| 15063 | create_one_off_subaddress(td.m_subaddr_index); |
| 15064 | bool r = cryptonote::generate_key_image_helper(m_account.get_keys(), m_subaddresses, out_key, tx_pub_key, additional_tx_pub_keys, td.m_internal_output_index, in_ephemeral, td.m_key_image, m_account.get_device()); |
| 15065 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 15066 | if (should_expand(td.m_subaddr_index)) |
| 15067 | expand_subaddresses(td.m_subaddr_index); |
| 15068 | td.m_key_image_known = true; |
| 15069 | td.m_key_image_request = true; |
| 15070 | td.m_key_image_partial = false; |
| 15071 | THROW_WALLET_EXCEPTION_IF(in_ephemeral.pub != out_key, |
| 15072 | error::wallet_internal_error, "key_image generated ephemeral public key not matched with output_key at index " + boost::lexical_cast<std::string>(i + offset)); |
| 15073 | |
| 15074 | m_key_images[td.m_key_image] = i + offset; |
| 15075 | m_pub_keys[td.get_public_key()] = i + offset; |
| 15076 | } |
| 15077 | |
| 15078 | return m_transfers.size(); |
| 15079 | } |
| 15080 | //---------------------------------------------------------------------------------------------------- |
| 15081 | size_t wallet2::import_outputs_from_str(const std::string &outputs_st) |
| 15082 | { |
| 15083 | PERF_TIMER(import_outputs_from_str); |
| 15084 | std::string data = outputs_st; |
| 15085 | const size_t magiclen = strlen(OUTPUT_EXPORT_FILE_MAGIC); |
| 15086 | if (data.size() < magiclen || memcmp(data.data(), OUTPUT_EXPORT_FILE_MAGIC, magiclen)) |
| 15087 | { |
| 15088 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Bad magic from outputs")); |
| 15089 | } |
| 15090 | |
| 15091 | try |
| 15092 | { |
| 15093 | PERF_TIMER(import_outputs_decrypt); |
| 15094 | data = decrypt_with_view_secret_key(std::string(data, magiclen)); |
| 15095 | } |
| 15096 | catch (const std::exception &e) |
| 15097 | { |
| 15098 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Failed to decrypt outputs: ") + e.what()); |
| 15099 | } |
| 15100 | |
| 15101 | const size_t headerlen = 2 * sizeof(crypto::public_key); |
| 15102 | if (data.size() < headerlen) |
| 15103 | { |
| 15104 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Bad data size for outputs")); |
| 15105 | } |
| 15106 | const crypto::public_key &public_spend_key = *(const crypto::public_key*)&data[0]; |
| 15107 | const crypto::public_key &public_view_key = *(const crypto::public_key*)&data[sizeof(crypto::public_key)]; |
| 15108 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 15109 | if (public_spend_key != keys.m_spend_public_key || public_view_key != keys.m_view_public_key) |
| 15110 | { |
| 15111 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Outputs from are for a different account")); |
| 15112 | } |
| 15113 | |
| 15114 | size_t imported_outputs = 0; |
| 15115 | bool loaded = false; |
| 15116 | try |
| 15117 | { |
| 15118 | std::string body(data, headerlen); |
| 15119 | |
| 15120 | std::tuple<uint64_t, uint64_t, std::vector<tools::wallet2::exported_transfer_details>> new_outputs; |
| 15121 | try |
| 15122 | { |
| 15123 | binary_archive<false> ar{epee::strspan<std::uint8_t>(body)}; |
| 15124 | if (::serialization::serialize(ar, new_outputs)) |
| 15125 | if (::serialization::check_stream_state(ar)) |
| 15126 | loaded = true; |
| 15127 | } |
| 15128 | catch (...) {} |
| 15129 | if (!loaded) |
| 15130 | std::get<2>(new_outputs).clear(); |
| 15131 | |
| 15132 | std::tuple<uint64_t, uint64_t, std::vector<tools::wallet2::transfer_details>> outputs; |
| 15133 | if (!loaded) try |
| 15134 | { |
| 15135 | binary_archive<false> ar{epee::strspan<std::uint8_t>(body)}; |
| 15136 | if (::serialization::serialize(ar, outputs)) |
| 15137 | if (::serialization::check_stream_state(ar)) |
| 15138 | loaded = true; |
| 15139 | } |
| 15140 | catch (...) {} |
| 15141 | |
| 15142 | if (!loaded && m_load_deprecated_formats) |
| 15143 | { |
| 15144 | try |
| 15145 | { |
| 15146 | std::stringstream iss; |
| 15147 | iss << body; |
| 15148 | boost::archive::portable_binary_iarchive ar(iss); |
| 15149 | ar >> outputs; |
| 15150 | loaded = true; |
| 15151 | } |
| 15152 | catch (...) {} |
| 15153 | } |
| 15154 | |
| 15155 | if (!loaded) |
| 15156 | { |
| 15157 | std::get<0>(outputs) = 0; |
| 15158 | std::get<1>(outputs) = 0; |
| 15159 | std::get<2>(outputs) = {}; |
| 15160 | } |
| 15161 | |
| 15162 | imported_outputs = !std::get<2>(new_outputs).empty() ? import_outputs(new_outputs) : !std::get<2>(outputs).empty() ? import_outputs(outputs) : 0; |
| 15163 | } |
| 15164 | catch (const std::exception &e) |
| 15165 | { |
| 15166 | THROW_WALLET_EXCEPTION(error::wallet_internal_error, std::string("Failed to import outputs: ") + e.what()); |
| 15167 | } |
| 15168 | |
| 15169 | return imported_outputs; |
| 15170 | } |
| 15171 | //---------------------------------------------------------------------------------------------------- |
| 15172 | crypto::public_key wallet2::get_multisig_signer_public_key() const |
| 15173 | { |
| 15174 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 15175 | crypto::public_key signer; |
| 15176 | CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(get_account().get_keys().m_spend_secret_key, signer), "Failed to generate signer public key"); |
| 15177 | return signer; |
| 15178 | } |
| 15179 | //---------------------------------------------------------------------------------------------------- |
| 15180 | crypto::public_key wallet2::get_multisig_signing_public_key(const crypto::secret_key &msk) const |
| 15181 | { |
| 15182 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 15183 | crypto::public_key pkey; |
| 15184 | CHECK_AND_ASSERT_THROW_MES(crypto::secret_key_to_public_key(msk, pkey), "Failed to derive public key"); |
| 15185 | return pkey; |
| 15186 | } |
| 15187 | //---------------------------------------------------------------------------------------------------- |
| 15188 | crypto::public_key wallet2::get_multisig_signing_public_key(size_t idx) const |
| 15189 | { |
| 15190 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 15191 | CHECK_AND_ASSERT_THROW_MES(idx < get_account().get_multisig_keys().size(), "Multisig signing key index out of range"); |
| 15192 | return get_multisig_signing_public_key(get_account().get_multisig_keys()[idx]); |
| 15193 | } |
| 15194 | //---------------------------------------------------------------------------------------------------- |
| 15195 | void wallet2::get_multisig_k(size_t idx, const std::unordered_set<rct::key> &used_L, rct::key &nonce) |
| 15196 | { |
| 15197 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 15198 | CHECK_AND_ASSERT_THROW_MES(idx < m_transfers.size(), "idx out of range"); |
| 15199 | for (auto &k: m_transfers[idx].m_multisig_k) |
| 15200 | { |
| 15201 | if (k == rct::zero()) |
| 15202 | continue; |
| 15203 | |
| 15204 | // decide whether or not to return a nonce just based on if its pubkey 'L = k*G' is attached to the transfer 'idx' |
| 15205 | rct::key L; |
| 15206 | rct::scalarmultBase(L, k); |
| 15207 | if (used_L.find(L) != used_L.end()) |
| 15208 | { |
| 15209 | nonce = k; |
| 15210 | memwipe(static_cast<rct::key *>(&k), sizeof(rct::key)); //CRITICAL: a nonce may only be used once! |
| 15211 | return; |
| 15212 | } |
| 15213 | } |
| 15214 | THROW_WALLET_EXCEPTION(tools::error::multisig_export_needed); |
| 15215 | } |
| 15216 | //---------------------------------------------------------------------------------------------------- |
| 15217 | rct::multisig_kLRki wallet2::get_multisig_kLRki(size_t n, const rct::key &k) const |
| 15218 | { |
| 15219 | CHECK_AND_ASSERT_THROW_MES(n < m_transfers.size(), "Bad m_transfers index"); |
| 15220 | rct::multisig_kLRki kLRki; |
| 15221 | kLRki.k = k; |
| 15222 | multisig::generate_multisig_LR(m_transfers[n].get_public_key(), rct::rct2sk(kLRki.k), (crypto::public_key&)kLRki.L, (crypto::public_key&)kLRki.R); |
| 15223 | kLRki.ki = rct::ki2rct(m_transfers[n].m_key_image); |
| 15224 | return kLRki; |
| 15225 | } |
| 15226 | //---------------------------------------------------------------------------------------------------- |
| 15227 | rct::multisig_kLRki wallet2::get_multisig_composite_kLRki(size_t n, const std::unordered_set<crypto::public_key> &ignore_set, std::unordered_set<rct::key> &used_L, std::unordered_set<rct::key> &new_used_L) const |
| 15228 | { |
| 15229 | CHECK_AND_ASSERT_THROW_MES(n < m_transfers.size(), "Bad transfer index"); |
| 15230 | |
| 15231 | rct::multisig_kLRki kLRki = get_multisig_kLRki(n, rct::skGen()); |
| 15232 | |
| 15233 | // pick a L/R pair from every other participant but one |
| 15234 | size_t n_signers_used = 1; |
| 15235 | for (const auto &p: m_transfers[n].m_multisig_info) |
| 15236 | { |
| 15237 | if (ignore_set.find(p.m_signer) != ignore_set.end()) |
| 15238 | continue; |
| 15239 | |
| 15240 | for (const auto &lr: p.m_LR) |
| 15241 | { |
| 15242 | if (used_L.find(lr.m_L) != used_L.end()) |
| 15243 | continue; |
| 15244 | used_L.insert(lr.m_L); |
| 15245 | new_used_L.insert(lr.m_L); |
| 15246 | rct::addKeys(kLRki.L, kLRki.L, lr.m_L); |
| 15247 | rct::addKeys(kLRki.R, kLRki.R, lr.m_R); |
| 15248 | ++n_signers_used; |
| 15249 | break; |
| 15250 | } |
| 15251 | } |
| 15252 | CHECK_AND_ASSERT_THROW_MES(n_signers_used >= m_multisig_threshold, "LR not found for enough participants"); |
| 15253 | |
| 15254 | return kLRki; |
| 15255 | } |
| 15256 | //---------------------------------------------------------------------------------------------------- |
| 15257 | crypto::key_image wallet2::get_multisig_composite_key_image(size_t n) const |
| 15258 | { |
| 15259 | CHECK_AND_ASSERT_THROW_MES(n < m_transfers.size(), "Bad output index"); |
| 15260 | |
| 15261 | const transfer_details &td = m_transfers[n]; |
| 15262 | const crypto::public_key tx_key = get_tx_pub_key_from_received_outs(td); |
| 15263 | const std::vector<crypto::public_key> additional_tx_keys = cryptonote::get_additional_tx_pub_keys_from_extra(td.m_tx); |
| 15264 | crypto::key_image ki; |
| 15265 | std::vector<crypto::key_image> pkis; |
| 15266 | for (const auto &info: td.m_multisig_info) |
| 15267 | for (const auto &pki: info.m_partial_key_images) |
| 15268 | pkis.push_back(pki); |
| 15269 | bool r = multisig::generate_multisig_composite_key_image(get_account().get_keys(), m_subaddresses, td.get_public_key(), tx_key, additional_tx_keys, td.m_internal_output_index, pkis, ki); |
| 15270 | THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "Failed to generate key image"); |
| 15271 | return ki; |
| 15272 | } |
| 15273 | //---------------------------------------------------------------------------------------------------- |
| 15274 | cryptonote::blobdata wallet2::export_multisig() |
| 15275 | { |
| 15276 | std::vector<tools::wallet2::multisig_info> info; |
| 15277 | |
| 15278 | const crypto::public_key signer = get_multisig_signer_public_key(); |
| 15279 | |
| 15280 | // For each transfer (output owned by the multisig wallet): |
| 15281 | // 1) Record the output's partial key image (from the local signer), so other signers can assemble the output's full key image. |
| 15282 | // 2) Prepare enough signing nonces for one signing attempt with each possible combination of 'threshold' signers |
| 15283 | // from the multisig group (only groups that include the local signer). |
| 15284 | // - Calling this function will reset any nonces recorded by the previous call to this function. Doing so will |
| 15285 | // invalidate any in-progress signing attempts that rely on the previous output of this function. |
| 15286 | info.resize(m_transfers.size()); |
| 15287 | for (size_t n = 0; n < m_transfers.size(); ++n) |
| 15288 | { |
| 15289 | transfer_details &td = m_transfers[n]; |
| 15290 | crypto::key_image ki; |
| 15291 | if (td.m_multisig_k.size()) |
| 15292 | { |
| 15293 | memwipe(td.m_multisig_k.data(), td.m_multisig_k.size() * sizeof(td.m_multisig_k[0])); |
| 15294 | td.m_multisig_k.clear(); |
| 15295 | } |
| 15296 | info[n].m_LR.clear(); |
| 15297 | info[n].m_partial_key_images.clear(); |
| 15298 | |
| 15299 | // record the partial key images |
| 15300 | for (size_t m = 0; m < get_account().get_multisig_keys().size(); ++m) |
| 15301 | { |
| 15302 | // we want to export the partial key image, not the full one, so we can't use td.m_key_image |
| 15303 | bool r = multisig::generate_multisig_key_image(get_account().get_keys(), m, td.get_public_key(), ki); |
| 15304 | CHECK_AND_ASSERT_THROW_MES(r, "Failed to generate key image"); |
| 15305 | info[n].m_partial_key_images.push_back(ki); |
| 15306 | } |
| 15307 | |
| 15308 | // Wallet tries to create as many transactions as many signers combinations. We calculate the maximum number here as follows: |
| 15309 | // if we have 2/4 wallet with signers: A, B, C, D and A is a transaction creator it will need to pick up 1 signer from 3 wallets left. |
| 15310 | // That means counting combinations for excluding 2-of-3 wallets (k = total signers count - threshold, n = total signers count - 1). |
| 15311 | size_t nlr = tools::combinations_count(m_multisig_signers.size() - m_multisig_threshold, m_multisig_signers.size() - 1); |
| 15312 | |
| 15313 | // 'td.m_multisig_k' is an expansion of [{alpha_0, alpha_1, ...}, {alpha_0, alpha_1, ...}, {alpha_0, alpha_1, ...}], |
| 15314 | // - A '{alpha_0, alpha_1, ...}' tuple contains a set of 'kAlphaComponents' nonces, which can be used for one |
| 15315 | // signing attempt. Each output will gain 'nlr' tuples, so that every signing group can make one signing attempt. |
| 15316 | // - All tuples are always cleared after 1+ of them is used to sign a tx attempt (in sign_multisig_tx()), so |
| 15317 | // in practice, a call to this function only allows _one_ multisig signing cycle for each output (which can |
| 15318 | // include signing attempts for multiple signer groups). |
| 15319 | nlr *= multisig::signing::kAlphaComponents; |
| 15320 | |
| 15321 | for (size_t m = 0; m < nlr; ++m) |
| 15322 | { |
| 15323 | td.m_multisig_k.push_back(rct::skGen()); |
| 15324 | const rct::multisig_kLRki kLRki = get_multisig_kLRki(n, td.m_multisig_k.back()); |
| 15325 | info[n].m_LR.push_back({kLRki.L, kLRki.R}); |
| 15326 | } |
| 15327 | |
| 15328 | info[n].m_signer = signer; |
| 15329 | } |
| 15330 | |
| 15331 | std::stringstream oss; |
| 15332 | binary_archive<true> ar(oss); |
| 15333 | CHECK_AND_ASSERT_THROW_MES(::serialization::serialize(ar, info), "Failed to serialize multisig data"); |
| 15334 | |
| 15335 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 15336 | std::string header; |
| 15337 | header += std::string((const char *)&keys.m_spend_public_key, sizeof(crypto::public_key)); |
| 15338 | header += std::string((const char *)&keys.m_view_public_key, sizeof(crypto::public_key)); |
| 15339 | header += std::string((const char *)&signer, sizeof(crypto::public_key)); |
| 15340 | std::string ciphertext = encrypt_with_view_secret_key(header + oss.str()); |
| 15341 | |
| 15342 | return MULTISIG_EXPORT_FILE_MAGIC + ciphertext; |
| 15343 | } |
| 15344 | //---------------------------------------------------------------------------------------------------- |
| 15345 | void wallet2::update_multisig_rescan_info(const std::vector<std::vector<rct::key>> &multisig_k, const std::vector<std::vector<tools::wallet2::multisig_info>> &info, size_t n) |
| 15346 | { |
| 15347 | CHECK_AND_ASSERT_THROW_MES(n < m_transfers.size(), "Bad index in update_multisig_info"); |
| 15348 | CHECK_AND_ASSERT_THROW_MES(multisig_k.size() >= m_transfers.size(), "Mismatched sizes of multisig_k and info"); |
| 15349 | |
| 15350 | MDEBUG("update_multisig_rescan_info: updating index " << n); |
| 15351 | transfer_details &td = m_transfers[n]; |
| 15352 | td.m_multisig_info.clear(); |
| 15353 | for (const auto &pi: info) |
| 15354 | { |
| 15355 | CHECK_AND_ASSERT_THROW_MES(n < pi.size(), "Bad pi size"); |
| 15356 | td.m_multisig_info.push_back(pi[n]); |
| 15357 | } |
| 15358 | m_key_images.erase(td.m_key_image); |
| 15359 | td.m_key_image = get_multisig_composite_key_image(n); |
| 15360 | td.m_key_image_known = true; |
| 15361 | td.m_key_image_request = false; |
| 15362 | td.m_key_image_partial = false; |
| 15363 | td.m_multisig_k = multisig_k[n]; |
| 15364 | m_key_images[td.m_key_image] = n; |
| 15365 | } |
| 15366 | //---------------------------------------------------------------------------------------------------- |
| 15367 | size_t wallet2::import_multisig(std::vector<cryptonote::blobdata> blobs, bool refresh_after_import) |
| 15368 | { |
| 15369 | CHECK_AND_ASSERT_THROW_MES(m_multisig, "Wallet is not multisig"); |
| 15370 | |
| 15371 | if (!m_multisig_rescan_k.empty() && !m_multisig_rescan_info.empty()) |
| 15372 | refresh(false); |
| 15373 | |
| 15374 | std::unordered_set<crypto::public_key> seen; |
| 15375 | for (cryptonote::blobdata &data: blobs) |
| 15376 | { |
| 15377 | const size_t magiclen = strlen(MULTISIG_EXPORT_FILE_MAGIC); |
| 15378 | THROW_WALLET_EXCEPTION_IF(data.size() < magiclen || memcmp(data.data(), MULTISIG_EXPORT_FILE_MAGIC, magiclen), |
| 15379 | error::wallet_internal_error, "Bad multisig info file magic in "); |
| 15380 | |
| 15381 | data = decrypt_with_view_secret_key(std::string(data, magiclen)); |
| 15382 | |
| 15383 | const size_t headerlen = 3 * sizeof(crypto::public_key); |
| 15384 | THROW_WALLET_EXCEPTION_IF(data.size() < headerlen, error::wallet_internal_error, "Bad data size"); |
| 15385 | |
| 15386 | const crypto::public_key &public_spend_key = *(const crypto::public_key*)&data[0]; |
| 15387 | const crypto::public_key &public_view_key = *(const crypto::public_key*)&data[sizeof(crypto::public_key)]; |
| 15388 | const crypto::public_key &signer = *(const crypto::public_key*)&data[2*sizeof(crypto::public_key)]; |
| 15389 | const cryptonote::account_public_address &keys = get_account().get_keys().m_account_address; |
| 15390 | THROW_WALLET_EXCEPTION_IF(public_spend_key != keys.m_spend_public_key || public_view_key != keys.m_view_public_key, |
| 15391 | error::wallet_internal_error, "Multisig info is for a different account"); |
| 15392 | if (get_multisig_signer_public_key() == signer) |
| 15393 | { |
| 15394 | MINFO("Multisig info from this wallet ignored"); |
| 15395 | continue; |
| 15396 | } |
| 15397 | if (seen.find(signer) != seen.end()) |
| 15398 | { |
| 15399 | MINFO("Duplicate multisig info ignored"); |
| 15400 | continue; |
| 15401 | } |
| 15402 | seen.insert(signer); |
| 15403 | |
| 15404 | std::string body(data, headerlen); |
| 15405 | std::vector<tools::wallet2::multisig_info> i; |
| 15406 | |
| 15407 | bool loaded = false; |
| 15408 | try |
| 15409 | { |
| 15410 | binary_archive<false> ar{epee::strspan<std::uint8_t>(body)}; |
| 15411 | if (::serialization::serialize(ar, i)) |
| 15412 | if (::serialization::check_stream_state(ar)) |
| 15413 | loaded = true; |
| 15414 | } |
| 15415 | catch(...) {} |
| 15416 | if (!loaded && m_load_deprecated_formats) |
| 15417 | { |
| 15418 | std::istringstream iss(body); |
| 15419 | boost::archive::portable_binary_iarchive ar(iss); |
| 15420 | ar >> i; |
| 15421 | loaded = true; |
| 15422 | } |
| 15423 | CHECK_AND_ASSERT_THROW_MES(loaded, "Failed to load output data"); |
| 15424 | |
| 15425 | for (const auto &e: i) |
| 15426 | { |
| 15427 | for (const auto &lr: e.m_LR) |
| 15428 | { |
| 15429 | CHECK_AND_ASSERT_THROW_MES(rct::isInMainSubgroup(lr.m_L), "Multisig value is not in the main subgroup"); |
| 15430 | CHECK_AND_ASSERT_THROW_MES(rct::isInMainSubgroup(lr.m_R), "Multisig value is not in the main subgroup"); |
| 15431 | } |
| 15432 | for (const auto &ki: e.m_partial_key_images) |
| 15433 | { |
| 15434 | CHECK_AND_ASSERT_THROW_MES(rct::isInMainSubgroup(rct::ki2rct(ki)), "Multisig partial key image is not in the main subgroup"); |
| 15435 | } |
| 15436 | } |
| 15437 | |
| 15438 | MINFO(boost::format("%u outputs found") % boost::lexical_cast<std::string>(i.size())); |
| 15439 | m_multisig_rescan_info.push_back(std::move(i)); |
| 15440 | } |
| 15441 | |
| 15442 | CHECK_AND_ASSERT_THROW_MES(m_multisig_rescan_info.size() + 1 <= m_multisig_signers.size() && m_multisig_rescan_info.size() + 1 >= m_multisig_threshold, "Wrong number of multisig sources"); |
| 15443 | |
| 15444 | m_multisig_rescan_k.reserve(m_transfers.size()); |
| 15445 | for (const auto &td: m_transfers) |
| 15446 | m_multisig_rescan_k.push_back(td.m_multisig_k); |
| 15447 | |
| 15448 | // how many outputs we're going to update |
| 15449 | size_t n_outputs = m_transfers.size(); |
| 15450 | for (const auto &pi: m_multisig_rescan_info) |
| 15451 | if (pi.size() < n_outputs) |
| 15452 | n_outputs = pi.size(); |
| 15453 | |
| 15454 | if (n_outputs == 0) |
| 15455 | return 0; |
| 15456 | |
| 15457 | // check signers are consistent |
| 15458 | for (const auto &pi: m_multisig_rescan_info) |
| 15459 | { |
| 15460 | CHECK_AND_ASSERT_THROW_MES(std::find(m_multisig_signers.begin(), m_multisig_signers.end(), pi[0].m_signer) != m_multisig_signers.end(), |
| 15461 | "Signer is not a member of this multisig wallet"); |
| 15462 | for (size_t n = 1; n < n_outputs; ++n) |
| 15463 | CHECK_AND_ASSERT_THROW_MES(pi[n].m_signer == pi[0].m_signer, "Mismatched signers in imported multisig info"); |
| 15464 | } |
| 15465 | |
| 15466 | // trim data we don't have info for from all participants |
| 15467 | for (auto &pi: m_multisig_rescan_info) |
| 15468 | pi.resize(n_outputs); |
| 15469 | |
| 15470 | // sort by signer |
| 15471 | if (!m_multisig_rescan_info.empty() && !m_multisig_rescan_info.front().empty()) |
| 15472 | { |
| 15473 | std::sort(m_multisig_rescan_info.begin(), m_multisig_rescan_info.end(), [](const std::vector<tools::wallet2::multisig_info> &i0, const std::vector<tools::wallet2::multisig_info> &i1){ return memcmp(&i0[0].m_signer, &i1[0].m_signer, sizeof(i0[0].m_signer)) < 0; }); |
| 15474 | } |
| 15475 | |
| 15476 | // first pass to determine where to detach the blockchain |
| 15477 | for (size_t n = 0; n < n_outputs; ++n) |
| 15478 | { |
| 15479 | const transfer_details &td = m_transfers[n]; |
| 15480 | if (!td.m_key_image_partial) |
| 15481 | continue; |
| 15482 | MINFO("Multisig info importing from block height " << td.m_block_height); |
| 15483 | handle_reorg(td.m_block_height); |
| 15484 | break; |
| 15485 | } |
| 15486 | |
| 15487 | for (size_t n = 0; n < n_outputs && n < m_transfers.size(); ++n) |
| 15488 | { |
| 15489 | update_multisig_rescan_info(m_multisig_rescan_k, m_multisig_rescan_info, n); |
| 15490 | } |
| 15491 | |
| 15492 | if (refresh_after_import) |
| 15493 | refresh(false); |
| 15494 | |
| 15495 | return n_outputs; |
| 15496 | } |
| 15497 | //---------------------------------------------------------------------------------------------------- |
| 15498 | std::string wallet2::encrypt(const char *plaintext, size_t len, const crypto::secret_key &skey, bool authenticated) const |
| 15499 | { |
| 15500 | crypto::chacha_key key; |
| 15501 | crypto::generate_chacha_key(&skey, sizeof(skey), key, m_kdf_rounds); |
| 15502 | std::string ciphertext; |
| 15503 | crypto::chacha_iv iv = crypto::rand<crypto::chacha_iv>(); |
| 15504 | ciphertext.resize(len + sizeof(iv) + (authenticated ? sizeof(crypto::signature) : 0)); |
| 15505 | crypto::chacha20(plaintext, len, key, iv, &ciphertext[sizeof(iv)]); |
| 15506 | memcpy(&ciphertext[0], &iv, sizeof(iv)); |
| 15507 | if (authenticated) |
| 15508 | { |
| 15509 | crypto::hash hash; |
| 15510 | crypto::cn_fast_hash(ciphertext.data(), ciphertext.size() - sizeof(signature), hash); |
| 15511 | crypto::public_key pkey; |
| 15512 | crypto::secret_key_to_public_key(skey, pkey); |
| 15513 | crypto::signature &signature = *(crypto::signature*)&ciphertext[ciphertext.size() - sizeof(crypto::signature)]; |
| 15514 | crypto::generate_signature(hash, pkey, skey, signature); |
| 15515 | } |
| 15516 | return ciphertext; |
| 15517 | } |
| 15518 | //---------------------------------------------------------------------------------------------------- |
| 15519 | std::string wallet2::encrypt(const epee::span<char> &plaintext, const crypto::secret_key &skey, bool authenticated) const |
| 15520 | { |
| 15521 | return encrypt(plaintext.data(), plaintext.size(), skey, authenticated); |
| 15522 | } |
| 15523 | //---------------------------------------------------------------------------------------------------- |
| 15524 | std::string wallet2::encrypt(const std::string &plaintext, const crypto::secret_key &skey, bool authenticated) const |
| 15525 | { |
| 15526 | return encrypt(plaintext.data(), plaintext.size(), skey, authenticated); |
| 15527 | } |
| 15528 | //---------------------------------------------------------------------------------------------------- |
| 15529 | std::string wallet2::encrypt(const epee::wipeable_string &plaintext, const crypto::secret_key &skey, bool authenticated) const |
| 15530 | { |
| 15531 | return encrypt(plaintext.data(), plaintext.size(), skey, authenticated); |
| 15532 | } |
| 15533 | //---------------------------------------------------------------------------------------------------- |
| 15534 | std::string wallet2::encrypt_with_view_secret_key(const std::string &plaintext, bool authenticated) const |
| 15535 | { |
| 15536 | return encrypt(plaintext, get_account().get_keys().m_view_secret_key, authenticated); |
| 15537 | } |
| 15538 | //---------------------------------------------------------------------------------------------------- |
| 15539 | template<typename T> |
| 15540 | T wallet2::decrypt(const std::string &ciphertext, const crypto::secret_key &skey, bool authenticated) const |
| 15541 | { |
| 15542 | const size_t prefix_size = sizeof(chacha_iv) + (authenticated ? sizeof(crypto::signature) : 0); |
| 15543 | THROW_WALLET_EXCEPTION_IF(ciphertext.size() < prefix_size, |
| 15544 | error::wallet_internal_error, "Unexpected ciphertext size"); |
| 15545 | |
| 15546 | crypto::chacha_key key; |
| 15547 | crypto::generate_chacha_key(&skey, sizeof(skey), key, m_kdf_rounds); |
| 15548 | const crypto::chacha_iv &iv = *(const crypto::chacha_iv*)&ciphertext[0]; |
| 15549 | if (authenticated) |
| 15550 | { |
| 15551 | crypto::hash hash; |
| 15552 | crypto::cn_fast_hash(ciphertext.data(), ciphertext.size() - sizeof(signature), hash); |
| 15553 | crypto::public_key pkey; |
| 15554 | crypto::secret_key_to_public_key(skey, pkey); |
| 15555 | const crypto::signature &signature = *(const crypto::signature*)&ciphertext[ciphertext.size() - sizeof(crypto::signature)]; |
| 15556 | THROW_WALLET_EXCEPTION_IF(!crypto::check_signature(hash, pkey, signature), |
| 15557 | error::wallet_internal_error, "Failed to authenticate ciphertext"); |
| 15558 | } |
| 15559 | std::unique_ptr<char[]> buffer{new char[ciphertext.size() - prefix_size]}; |
| 15560 | auto wiper = epee::misc_utils::create_scope_leave_handler([&]() { memwipe(buffer.get(), ciphertext.size() - prefix_size); }); |
| 15561 | crypto::chacha20(ciphertext.data() + sizeof(iv), ciphertext.size() - prefix_size, key, iv, buffer.get()); |
| 15562 | return T(buffer.get(), ciphertext.size() - prefix_size); |
| 15563 | } |
| 15564 | //---------------------------------------------------------------------------------------------------- |
| 15565 | template epee::wipeable_string wallet2::decrypt(const std::string &ciphertext, const crypto::secret_key &skey, bool authenticated) const; |
| 15566 | //---------------------------------------------------------------------------------------------------- |
| 15567 | std::string wallet2::decrypt_with_view_secret_key(const std::string &ciphertext, bool authenticated) const |
| 15568 | { |
| 15569 | return decrypt(ciphertext, get_account().get_keys().m_view_secret_key, authenticated); |
| 15570 | } |
| 15571 | //---------------------------------------------------------------------------------------------------- |
| 15572 | std::string wallet2::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) const |
| 15573 | { |
| 15574 | cryptonote::address_parse_info info; |
| 15575 | if(!get_account_address_from_str(info, nettype(), address)) |
| 15576 | { |
| 15577 | error = std::string("wrong address: ") + address; |
| 15578 | return std::string(); |
| 15579 | } |
| 15580 | |
| 15581 | // we want only one payment id |
| 15582 | if (info.has_payment_id && !payment_id.empty()) |
| 15583 | { |
| 15584 | error = "A single payment id is allowed"; |
| 15585 | return std::string(); |
| 15586 | } |
| 15587 | |
| 15588 | if (!payment_id.empty()) |
| 15589 | { |
| 15590 | error = "Standalone payment id deprecated, use integrated address instead"; |
| 15591 | return std::string(); |
| 15592 | } |
| 15593 | |
| 15594 | std::string uri = "monero:" + address; |
| 15595 | unsigned int n_fields = 0; |
| 15596 | |
| 15597 | if (!payment_id.empty()) |
| 15598 | { |
| 15599 | uri += (n_fields++ ? "&" : "?") + std::string("tx_payment_id=") + payment_id; |
| 15600 | } |
| 15601 | |
| 15602 | if (amount > 0) |
| 15603 | { |
| 15604 | // URI encoded amount is in decimal units, not atomic units |
| 15605 | uri += (n_fields++ ? "&" : "?") + std::string("tx_amount=") + cryptonote::print_money(amount); |
| 15606 | } |
| 15607 | |
| 15608 | if (!recipient_name.empty()) |
| 15609 | { |
| 15610 | uri += (n_fields++ ? "&" : "?") + std::string("recipient_name=") + epee::net_utils::conver_to_url_format(recipient_name); |
| 15611 | } |
| 15612 | |
| 15613 | if (!tx_description.empty()) |
| 15614 | { |
| 15615 | uri += (n_fields++ ? "&" : "?") + std::string("tx_description=") + epee::net_utils::conver_to_url_format(tx_description); |
| 15616 | } |
| 15617 | |
| 15618 | return uri; |
| 15619 | } |
| 15620 | //---------------------------------------------------------------------------------------------------- |
| 15621 | bool wallet2::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) |
| 15622 | { |
| 15623 | if (uri.substr(0, 7) != "monero:") |
| 15624 | { |
| 15625 | error = std::string("URI has wrong scheme (expected \"monero:\"): ") + uri; |
| 15626 | return false; |
| 15627 | } |
| 15628 | |
| 15629 | std::string remainder = uri.substr(7); |
| 15630 | const char *ptr = strchr(remainder.c_str(), '?'); |
| 15631 | address = ptr ? remainder.substr(0, ptr-remainder.c_str()) : remainder; |
| 15632 | |
| 15633 | cryptonote::address_parse_info info; |
| 15634 | if(!get_account_address_from_str(info, nettype(), address)) |
| 15635 | { |
| 15636 | error = std::string("URI has wrong address: ") + address; |
| 15637 | return false; |
| 15638 | } |
| 15639 | if (!strchr(remainder.c_str(), '?')) |
| 15640 | return true; |
| 15641 | |
| 15642 | std::vector<std::string> arguments; |
| 15643 | std::string body = remainder.substr(address.size() + 1); |
| 15644 | if (body.empty()) |
| 15645 | return true; |
| 15646 | boost::split(arguments, body, boost::is_any_of("&")); |
| 15647 | std::set<std::string> have_arg; |
| 15648 | for (const auto &arg: arguments) |
| 15649 | { |
| 15650 | std::vector<std::string> kv; |
| 15651 | boost::split(kv, arg, boost::is_any_of("=")); |
| 15652 | if (kv.size() != 2) |
| 15653 | { |
| 15654 | error = std::string("URI has wrong parameter: ") + arg; |
| 15655 | return false; |
| 15656 | } |
| 15657 | if (have_arg.find(kv[0]) != have_arg.end()) |
| 15658 | { |
| 15659 | error = std::string("URI has more than one instance of " + kv[0]); |
| 15660 | return false; |
| 15661 | } |
| 15662 | have_arg.insert(kv[0]); |
| 15663 | |
| 15664 | if (kv[0] == "tx_amount") |
| 15665 | { |
| 15666 | amount = 0; |
| 15667 | if (!cryptonote::parse_amount(amount, kv[1])) |
| 15668 | { |
| 15669 | error = std::string("URI has invalid amount: ") + kv[1]; |
| 15670 | return false; |
| 15671 | } |
| 15672 | } |
| 15673 | else if (kv[0] == "tx_payment_id") |
| 15674 | { |
| 15675 | if (info.has_payment_id) |
| 15676 | { |
| 15677 | error = "Separate payment id given with an integrated address"; |
| 15678 | return false; |
| 15679 | } |
| 15680 | crypto::hash hash; |
| 15681 | if (!wallet2::parse_long_payment_id(kv[1], hash)) |
| 15682 | { |
| 15683 | error = "Invalid payment id: " + kv[1]; |
| 15684 | return false; |
| 15685 | } |
| 15686 | payment_id = kv[1]; |
| 15687 | } |
| 15688 | else if (kv[0] == "recipient_name") |
| 15689 | { |
| 15690 | recipient_name = epee::net_utils::convert_from_url_format(kv[1]); |
| 15691 | } |
| 15692 | else if (kv[0] == "tx_description") |
| 15693 | { |
| 15694 | tx_description = epee::net_utils::convert_from_url_format(kv[1]); |
| 15695 | } |
| 15696 | else |
| 15697 | { |
| 15698 | unknown_parameters.push_back(arg); |
| 15699 | } |
| 15700 | } |
| 15701 | return true; |
| 15702 | } |
| 15703 | //---------------------------------------------------------------------------------------------------- |
| 15704 | uint64_t wallet2::get_blockchain_height_by_date(uint16_t year, uint8_t month, uint8_t day) |
| 15705 | { |
| 15706 | uint32_t version; |
| 15707 | if (!check_connection(&version)) |
| 15708 | { |
| 15709 | throw std::runtime_error("failed to connect to daemon: " + get_daemon_address()); |
| 15710 | } |
| 15711 | if (version < MAKE_CORE_RPC_VERSION(1, 6)) |
| 15712 | { |
| 15713 | throw std::runtime_error("this function requires RPC version 1.6 or higher"); |
| 15714 | } |
| 15715 | std::tm date = { 0, 0, 0, 0, 0, 0, 0, 0 }; |
| 15716 | date.tm_year = year - 1900; |
| 15717 | date.tm_mon = month - 1; |
| 15718 | date.tm_mday = day; |
| 15719 | if (date.tm_mon < 0 || 11 < date.tm_mon || date.tm_mday < 1 || 31 < date.tm_mday) |
| 15720 | { |
| 15721 | throw std::runtime_error("month or day out of range"); |
| 15722 | } |
| 15723 | uint64_t timestamp_target = std::mktime(&date); |
| 15724 | std::string err; |
| 15725 | uint64_t height_min = 0; |
| 15726 | uint64_t height_max = get_daemon_blockchain_height(err) - 1; |
| 15727 | if (!err.empty()) |
| 15728 | { |
| 15729 | throw std::runtime_error("failed to get blockchain height"); |
| 15730 | } |
| 15731 | while (true) |
| 15732 | { |
| 15733 | COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::request req; |
| 15734 | COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::response res; |
| 15735 | uint64_t height_mid = (height_min + height_max) / 2; |
| 15736 | req.heights = |
| 15737 | { |
| 15738 | height_min, |
| 15739 | height_mid, |
| 15740 | height_max |
| 15741 | }; |
| 15742 | |
| 15743 | bool r; |
| 15744 | { |
| 15745 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 15746 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 15747 | req.client = get_client_signature(); |
| 15748 | r = net_utils::invoke_http_bin("/getblocks_by_height.bin", req, res, *m_http_client, rpc_timeout); |
| 15749 | if (r && res.status == CORE_RPC_STATUS_OK) |
| 15750 | check_rpc_cost("/getblocks_by_height.bin", res.credits, pre_call_credits, 3 * COST_PER_BLOCK); |
| 15751 | } |
| 15752 | |
| 15753 | if (!r || res.status != CORE_RPC_STATUS_OK) |
| 15754 | { |
| 15755 | std::ostringstream oss; |
| 15756 | oss << "failed to get blocks by heights: "; |
| 15757 | for (auto height : req.heights) |
| 15758 | oss << height << ' '; |
| 15759 | oss << endl << "reason: "; |
| 15760 | if (!r) |
| 15761 | oss << "possibly lost connection to daemon"; |
| 15762 | else if (res.status == CORE_RPC_STATUS_BUSY) |
| 15763 | oss << "daemon is busy"; |
| 15764 | else |
| 15765 | oss << get_rpc_status(res.status); |
| 15766 | throw std::runtime_error(oss.str()); |
| 15767 | } |
| 15768 | cryptonote::block blk_min, blk_mid, blk_max; |
| 15769 | if (res.blocks.size() < 3) throw std::runtime_error("Not enough blocks returned from daemon"); |
| 15770 | if (!parse_and_validate_block_from_blob(res.blocks[0].block, blk_min)) throw std::runtime_error("failed to parse blob at height " + std::to_string(height_min)); |
| 15771 | if (!parse_and_validate_block_from_blob(res.blocks[1].block, blk_mid)) throw std::runtime_error("failed to parse blob at height " + std::to_string(height_mid)); |
| 15772 | if (!parse_and_validate_block_from_blob(res.blocks[2].block, blk_max)) throw std::runtime_error("failed to parse blob at height " + std::to_string(height_max)); |
| 15773 | uint64_t timestamp_min = blk_min.timestamp; |
| 15774 | uint64_t timestamp_mid = blk_mid.timestamp; |
| 15775 | uint64_t timestamp_max = blk_max.timestamp; |
| 15776 | if (!(timestamp_min <= timestamp_mid && timestamp_mid <= timestamp_max)) |
| 15777 | { |
| 15778 | // the timestamps are not in the chronological order. |
| 15779 | // assuming they're sufficiently close to each other, simply return the smallest height |
| 15780 | return std::min({height_min, height_mid, height_max}); |
| 15781 | } |
| 15782 | if (timestamp_target > timestamp_max) |
| 15783 | { |
| 15784 | throw std::runtime_error("specified date is in the future"); |
| 15785 | } |
| 15786 | if (timestamp_target <= timestamp_min + 2 * 24 * 60 * 60) // two days of "buffer" period |
| 15787 | { |
| 15788 | return height_min; |
| 15789 | } |
| 15790 | if (timestamp_target <= timestamp_mid) |
| 15791 | height_max = height_mid; |
| 15792 | else |
| 15793 | height_min = height_mid; |
| 15794 | if (height_max - height_min <= 2 * 24 * 30) // don't divide the height range finer than two days |
| 15795 | { |
| 15796 | return height_min; |
| 15797 | } |
| 15798 | } |
| 15799 | } |
| 15800 | //---------------------------------------------------------------------------------------------------- |
| 15801 | bool wallet2::is_synced() |
| 15802 | { |
| 15803 | uint64_t height; |
| 15804 | boost::optional<std::string> result = m_node_rpc_proxy.get_height(height); |
| 15805 | if (result && *result != CORE_RPC_STATUS_OK) |
| 15806 | return false; |
| 15807 | return get_blockchain_current_height() >= height; |
| 15808 | } |
| 15809 | //---------------------------------------------------------------------------------------------------- |
| 15810 | std::vector<std::pair<uint64_t, uint64_t>> wallet2::estimate_backlog(const std::vector<std::pair<double, double>> &fee_levels) |
| 15811 | { |
| 15812 | for (const auto &fee_level: fee_levels) |
| 15813 | { |
| 15814 | THROW_WALLET_EXCEPTION_IF(fee_level.first == 0.0, error::wallet_internal_error, "Invalid 0 fee"); |
| 15815 | THROW_WALLET_EXCEPTION_IF(fee_level.second == 0.0, error::wallet_internal_error, "Invalid 0 fee"); |
| 15816 | THROW_WALLET_EXCEPTION_IF(fee_level.second < fee_level.first, error::wallet_internal_error, "Minimum fee cannot be less than maximum fee"); |
| 15817 | } |
| 15818 | |
| 15819 | // get txpool backlog |
| 15820 | cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_BACKLOG::request req = AUTO_VAL_INIT(req); |
| 15821 | cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_BACKLOG::response res = AUTO_VAL_INIT(res); |
| 15822 | |
| 15823 | { |
| 15824 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 15825 | uint64_t pre_call_credits = m_rpc_payment_state.credits; |
| 15826 | req.client = get_client_signature(); |
| 15827 | bool r = net_utils::invoke_http_json_rpc("/json_rpc", "get_txpool_backlog", req, res, *m_http_client, rpc_timeout); |
| 15828 | THROW_ON_RPC_RESPONSE_ERROR(r, {}, res, "get_txpool_backlog", error::get_tx_pool_error); |
| 15829 | check_rpc_cost("get_txpool_backlog", res.credits, pre_call_credits, COST_PER_TX_POOL_STATS * res.backlog.size()); |
| 15830 | } |
| 15831 | |
| 15832 | uint64_t block_weight_limit = 0; |
| 15833 | const auto result = m_node_rpc_proxy.get_block_weight_limit(block_weight_limit); |
| 15834 | THROW_WALLET_EXCEPTION_IF(result, error::wallet_internal_error, "Invalid block weight limit from daemon"); |
| 15835 | uint64_t full_reward_zone = block_weight_limit / 2; |
| 15836 | THROW_WALLET_EXCEPTION_IF(full_reward_zone == 0, error::wallet_internal_error, "Invalid block weight limit from daemon"); |
| 15837 | |
| 15838 | std::vector<std::pair<uint64_t, uint64_t>> blocks; |
| 15839 | for (const auto& [our_fee_byte_min, our_fee_byte_max] : fee_levels) |
| 15840 | { |
| 15841 | uint64_t minfee_weight = 0, maxfee_weight = 0; |
| 15842 | for (const auto &i: res.backlog) |
| 15843 | { |
| 15844 | if (i.weight == 0) |
| 15845 | { |
| 15846 | MWARNING("Got 0 weight tx from txpool, ignored"); |
| 15847 | continue; |
| 15848 | } |
| 15849 | double this_fee_byte = i.fee / (double)i.weight; |
| 15850 | if (this_fee_byte >= our_fee_byte_min) |
| 15851 | minfee_weight += i.weight; |
| 15852 | if (this_fee_byte >= our_fee_byte_max) |
| 15853 | maxfee_weight += i.weight; |
| 15854 | } |
| 15855 | |
| 15856 | uint64_t nblocks_max = minfee_weight / full_reward_zone; |
| 15857 | uint64_t nblocks_min = maxfee_weight / full_reward_zone; |
| 15858 | MDEBUG("estimate_backlog: given a block weight of " << full_reward_zone << " you will need to wait " |
| 15859 | << nblocks_min << " when paying " << our_fee_byte_max << " piconero per byte and " << nblocks_max |
| 15860 | << " when paying " << our_fee_byte_min << " piconeros per byte."); |
| 15861 | blocks.push_back(std::make_pair(nblocks_min, nblocks_max)); |
| 15862 | } |
| 15863 | return blocks; |
| 15864 | } |
| 15865 | //---------------------------------------------------------------------------------------------------- |
| 15866 | std::vector<std::pair<uint64_t, uint64_t>> wallet2::estimate_backlog(uint64_t min_tx_weight, uint64_t max_tx_weight, const std::vector<uint64_t> &fees) |
| 15867 | { |
| 15868 | THROW_WALLET_EXCEPTION_IF(min_tx_weight == 0, error::wallet_internal_error, "Invalid 0 fee"); |
| 15869 | THROW_WALLET_EXCEPTION_IF(max_tx_weight == 0, error::wallet_internal_error, "Invalid 0 fee"); |
| 15870 | for (uint64_t fee: fees) |
| 15871 | { |
| 15872 | THROW_WALLET_EXCEPTION_IF(fee == 0, error::wallet_internal_error, "Invalid 0 fee"); |
| 15873 | } |
| 15874 | std::vector<std::pair<double, double>> fee_levels; |
| 15875 | for (uint64_t fee: fees) |
| 15876 | { |
| 15877 | double our_fee_byte_min = fee / (double)min_tx_weight, our_fee_byte_max = fee / (double)max_tx_weight; |
| 15878 | fee_levels.emplace_back(our_fee_byte_min, our_fee_byte_max); |
| 15879 | } |
| 15880 | return estimate_backlog(fee_levels); |
| 15881 | } |
| 15882 | //---------------------------------------------------------------------------------------------------- |
| 15883 | uint64_t wallet2::get_segregation_fork_height() const |
| 15884 | { |
| 15885 | if (m_nettype == TESTNET) |
| 15886 | return TESTNET_SEGREGATION_FORK_HEIGHT; |
| 15887 | if (m_nettype == STAGENET) |
| 15888 | return STAGENET_SEGREGATION_FORK_HEIGHT; |
| 15889 | THROW_WALLET_EXCEPTION_IF(m_nettype != MAINNET, tools::error::wallet_internal_error, "Invalid network type"); |
| 15890 | |
| 15891 | if (m_segregation_height > 0) |
| 15892 | return m_segregation_height; |
| 15893 | |
| 15894 | return SEGREGATION_FORK_HEIGHT; |
| 15895 | } |
| 15896 | //---------------------------------------------------------------------------------------------------- |
| 15897 | void wallet2::generate_genesis(cryptonote::block& b) const { |
| 15898 | cryptonote::generate_genesis_block(b, get_config(m_nettype).GENESIS_TX, get_config(m_nettype).GENESIS_NONCE); |
| 15899 | } |
| 15900 | //---------------------------------------------------------------------------------------------------- |
| 15901 | mms::multisig_wallet_state wallet2::get_multisig_wallet_state() const |
| 15902 | { |
| 15903 | mms::multisig_wallet_state state; |
| 15904 | state.nettype = m_nettype; |
| 15905 | state.multisig = multisig(&state.multisig_is_ready); |
| 15906 | state.has_multisig_partial_key_images = has_multisig_partial_key_images(); |
| 15907 | state.multisig_rounds_passed = m_multisig_rounds_passed; |
| 15908 | state.num_transfer_details = m_transfers.size(); |
| 15909 | if (state.multisig) |
| 15910 | { |
| 15911 | THROW_WALLET_EXCEPTION_IF(!m_original_keys_available, error::wallet_internal_error, "MMS use not possible because own original Monero address not available"); |
| 15912 | state.address = m_original_address; |
| 15913 | state.view_secret_key = m_original_view_secret_key; |
| 15914 | } |
| 15915 | else |
| 15916 | { |
| 15917 | state.address = m_account.get_keys().m_account_address; |
| 15918 | state.view_secret_key = m_account.get_keys().m_view_secret_key; |
| 15919 | } |
| 15920 | state.mms_file=m_mms_file; |
| 15921 | return state; |
| 15922 | } |
| 15923 | //---------------------------------------------------------------------------------------------------- |
| 15924 | wallet_device_callback * wallet2::get_device_callback() |
| 15925 | { |
| 15926 | if (!m_device_callback){ |
| 15927 | m_device_callback.reset(new wallet_device_callback(this)); |
| 15928 | } |
| 15929 | return m_device_callback.get(); |
| 15930 | }//---------------------------------------------------------------------------------------------------- |
| 15931 | void wallet2::on_device_button_request(uint64_t code) |
| 15932 | { |
| 15933 | if (nullptr != m_callback) |
| 15934 | m_callback->on_device_button_request(code); |
| 15935 | } |
| 15936 | //---------------------------------------------------------------------------------------------------- |
| 15937 | void wallet2::on_device_button_pressed() |
| 15938 | { |
| 15939 | if (nullptr != m_callback) |
| 15940 | m_callback->on_device_button_pressed(); |
| 15941 | } |
| 15942 | //---------------------------------------------------------------------------------------------------- |
| 15943 | boost::optional<epee::wipeable_string> wallet2::on_device_pin_request() |
| 15944 | { |
| 15945 | if (nullptr != m_callback) |
| 15946 | return m_callback->on_device_pin_request(); |
| 15947 | return boost::none; |
| 15948 | } |
| 15949 | //---------------------------------------------------------------------------------------------------- |
| 15950 | boost::optional<epee::wipeable_string> wallet2::on_device_passphrase_request(bool & on_device) |
| 15951 | { |
| 15952 | if (nullptr != m_callback) |
| 15953 | return m_callback->on_device_passphrase_request(on_device); |
| 15954 | else |
| 15955 | on_device = true; |
| 15956 | return boost::none; |
| 15957 | } |
| 15958 | //---------------------------------------------------------------------------------------------------- |
| 15959 | void wallet2::on_device_progress(const hw::device_progress& event) |
| 15960 | { |
| 15961 | if (nullptr != m_callback) |
| 15962 | m_callback->on_device_progress(event); |
| 15963 | } |
| 15964 | //---------------------------------------------------------------------------------------------------- |
| 15965 | std::string wallet2::get_rpc_status(const std::string &s) const |
| 15966 | { |
| 15967 | if (m_trusted_daemon) |
| 15968 | return s; |
| 15969 | if (s == CORE_RPC_STATUS_OK) |
| 15970 | return s; |
| 15971 | if (s == CORE_RPC_STATUS_BUSY || s == CORE_RPC_STATUS_PAYMENT_REQUIRED) |
| 15972 | return s; |
| 15973 | return "<error>"; |
| 15974 | } |
| 15975 | //---------------------------------------------------------------------------------------------------- |
| 15976 | void wallet2::throw_on_rpc_response_error(bool r, const epee::json_rpc::error &error, const std::string &status, const char *method) const |
| 15977 | { |
| 15978 | THROW_WALLET_EXCEPTION_IF(error.code, tools::error::wallet_coded_rpc_error, method, error.code, get_rpc_server_error_message(error.code)); |
| 15979 | THROW_WALLET_EXCEPTION_IF(!r, tools::error::no_connection_to_daemon, method); |
| 15980 | // empty string -> not connection |
| 15981 | THROW_WALLET_EXCEPTION_IF(status.empty(), tools::error::no_connection_to_daemon, method); |
| 15982 | |
| 15983 | THROW_WALLET_EXCEPTION_IF(status == CORE_RPC_STATUS_BUSY, tools::error::daemon_busy, method); |
| 15984 | THROW_WALLET_EXCEPTION_IF(status == CORE_RPC_STATUS_PAYMENT_REQUIRED, tools::error::payment_required, method); |
| 15985 | } |
| 15986 | //---------------------------------------------------------------------------------------------------- |
| 15987 | |
| 15988 | bool wallet2::save_to_file(const std::string& path_to_file, const std::string& raw, bool is_printable) const |
| 15989 | { |
| 15990 | if (is_printable || m_export_format == ExportFormat::Binary) |
| 15991 | { |
| 15992 | return epee::file_io_utils::save_string_to_file(path_to_file, raw); |
| 15993 | } |
| 15994 | |
| 15995 | FILE *fp = fopen(path_to_file.c_str(), "w+"); |
| 15996 | if (!fp) |
| 15997 | { |
| 15998 | MERROR("Failed to open wallet file for writing: " << path_to_file << ": " << strerror(errno)); |
| 15999 | return false; |
| 16000 | } |
| 16001 | |
| 16002 | // Save the result b/c we need to close the fp before returning success/failure. |
| 16003 | int write_result = PEM_write(fp, ASCII_OUTPUT_MAGIC.c_str(), "", (const unsigned char *) raw.c_str(), raw.length()); |
| 16004 | fclose(fp); |
| 16005 | |
| 16006 | if (write_result == 0) |
| 16007 | { |
| 16008 | return false; |
| 16009 | } |
| 16010 | else |
| 16011 | { |
| 16012 | return true; |
| 16013 | } |
| 16014 | } |
| 16015 | //---------------------------------------------------------------------------------------------------- |
| 16016 | |
| 16017 | bool wallet2::load_from_file(const std::string& path_to_file, std::string& target_str, |
| 16018 | size_t max_size) |
| 16019 | { |
| 16020 | std::string data; |
| 16021 | bool r = epee::file_io_utils::load_file_to_string(path_to_file, data, max_size); |
| 16022 | if (!r) |
| 16023 | { |
| 16024 | return false; |
| 16025 | } |
| 16026 | |
| 16027 | if (!boost::algorithm::contains(boost::make_iterator_range(data.begin(), data.end()), ASCII_OUTPUT_MAGIC)) |
| 16028 | { |
| 16029 | // It's NOT our ascii dump. |
| 16030 | target_str = std::move(data); |
| 16031 | return true; |
| 16032 | } |
| 16033 | |
| 16034 | // Creating a BIO and calling PEM_read_bio instead of simpler PEM_read |
| 16035 | // to avoid reading the file from disk twice. |
| 16036 | BIO* b = BIO_new_mem_buf((const void*) data.data(), data.length()); |
| 16037 | |
| 16038 | char *name = NULL; |
| 16039 | char *header = NULL; |
| 16040 | unsigned char *openssl_data = NULL; |
| 16041 | long len = 0; |
| 16042 | |
| 16043 | // Save the result b/c we need to free the data before returning success/failure. |
| 16044 | int success = PEM_read_bio(b, &name, &header, &openssl_data, &len); |
| 16045 | |
| 16046 | try |
| 16047 | { |
| 16048 | target_str = std::string((const char*) openssl_data, len); |
| 16049 | } |
| 16050 | catch (...) |
| 16051 | { |
| 16052 | success = 0; |
| 16053 | } |
| 16054 | |
| 16055 | OPENSSL_free((void *) name); |
| 16056 | OPENSSL_free((void *) header); |
| 16057 | OPENSSL_free((void *) openssl_data); |
| 16058 | BIO_free(b); |
| 16059 | |
| 16060 | if (success == 0) |
| 16061 | { |
| 16062 | return false; |
| 16063 | } |
| 16064 | else |
| 16065 | { |
| 16066 | return true; |
| 16067 | } |
| 16068 | } |
| 16069 | //---------------------------------------------------------------------------------------------------- |
| 16070 | void wallet2::hash_m_transfer(const transfer_details & transfer, crypto::hash &hash) const |
| 16071 | { |
| 16072 | KECCAK_CTX state; |
| 16073 | keccak_init(&state); |
| 16074 | keccak_update(&state, (const uint8_t *) transfer.m_txid.data, sizeof(transfer.m_txid.data)); |
| 16075 | keccak_update(&state, (const uint8_t *) &transfer.m_internal_output_index, sizeof(transfer.m_internal_output_index)); |
| 16076 | keccak_update(&state, (const uint8_t *) &transfer.m_global_output_index, sizeof(transfer.m_global_output_index)); |
| 16077 | keccak_update(&state, (const uint8_t *) &transfer.m_amount, sizeof(transfer.m_amount)); |
| 16078 | keccak_finish(&state, (uint8_t *) hash.data); |
| 16079 | } |
| 16080 | //---------------------------------------------------------------------------------------------------- |
| 16081 | uint64_t wallet2::hash_m_transfers(boost::optional<uint64_t> transfer_height, crypto::hash &hash) const |
| 16082 | { |
| 16083 | CHECK_AND_ASSERT_THROW_MES(!transfer_height || *transfer_height <= m_transfers.size(), "Hash height is greater than number of transfers"); |
| 16084 | |
| 16085 | KECCAK_CTX state; |
| 16086 | crypto::hash tmp_hash{}; |
| 16087 | uint64_t current_height = 0; |
| 16088 | |
| 16089 | keccak_init(&state); |
| 16090 | for(const transfer_details & transfer : m_transfers){ |
| 16091 | if (transfer_height && current_height >= *transfer_height){ |
| 16092 | break; |
| 16093 | } |
| 16094 | |
| 16095 | hash_m_transfer(transfer, tmp_hash); |
| 16096 | keccak_update(&state, (const uint8_t *) &transfer.m_block_height, sizeof(transfer.m_block_height)); |
| 16097 | keccak_update(&state, (const uint8_t *) tmp_hash.data, sizeof(tmp_hash.data)); |
| 16098 | current_height += 1; |
| 16099 | } |
| 16100 | |
| 16101 | keccak_finish(&state, (uint8_t *) hash.data); |
| 16102 | return current_height; |
| 16103 | } |
| 16104 | //---------------------------------------------------------------------------------------------------- |
| 16105 | void wallet2::finish_rescan_bc_keep_key_images(uint64_t transfer_height, const crypto::hash &hash) |
| 16106 | { |
| 16107 | // Compute hash of m_transfers, if differs there had to be BC reorg. |
| 16108 | if (transfer_height <= m_transfers.size()) { |
| 16109 | crypto::hash new_transfers_hash{}; |
| 16110 | hash_m_transfers(transfer_height, new_transfers_hash); |
| 16111 | |
| 16112 | if (new_transfers_hash == hash) { |
| 16113 | // Restore key images in m_transfers from m_key_images |
| 16114 | for(auto it = m_key_images.begin(); it != m_key_images.end(); it++) |
| 16115 | { |
| 16116 | THROW_WALLET_EXCEPTION_IF(it->second >= m_transfers.size(), |
| 16117 | error::wallet_internal_error, |
| 16118 | "Key images cache contains illegal transfer offset"); |
| 16119 | m_transfers[it->second].m_key_image = it->first; |
| 16120 | m_transfers[it->second].m_key_image_known = true; |
| 16121 | } |
| 16122 | |
| 16123 | return; |
| 16124 | } |
| 16125 | } |
| 16126 | |
| 16127 | // Soft-Reset to avoid inconsistency in case of BC reorg. |
| 16128 | clear_soft(false); // keep_key_images works only with soft reset. |
| 16129 | THROW_WALLET_EXCEPTION_IF(true, error::wallet_internal_error, "Transfers changed during rescan, soft or hard rescan is needed"); |
| 16130 | } |
| 16131 | //---------------------------------------------------------------------------------------------------- |
| 16132 | uint64_t wallet2::get_bytes_sent() const |
| 16133 | { |
| 16134 | return m_http_client->get_bytes_sent(); |
| 16135 | } |
| 16136 | //---------------------------------------------------------------------------------------------------- |
| 16137 | uint64_t wallet2::get_bytes_received() const |
| 16138 | { |
| 16139 | return m_http_client->get_bytes_received(); |
| 16140 | } |
| 16141 | //---------------------------------------------------------------------------------------------------- |
| 16142 | std::vector<cryptonote::public_node> wallet2::get_public_nodes(bool white_only) |
| 16143 | { |
| 16144 | cryptonote::COMMAND_RPC_GET_PUBLIC_NODES::request req = AUTO_VAL_INIT(req); |
| 16145 | cryptonote::COMMAND_RPC_GET_PUBLIC_NODES::response res = AUTO_VAL_INIT(res); |
| 16146 | |
| 16147 | req.white = true; |
| 16148 | req.gray = !white_only; |
| 16149 | req.include_blocked = false; |
| 16150 | |
| 16151 | { |
| 16152 | const boost::lock_guard<boost::recursive_mutex> lock{m_daemon_rpc_mutex}; |
| 16153 | bool r = epee::net_utils::invoke_http_json("/get_public_nodes", req, res, *m_http_client, rpc_timeout); |
| 16154 | THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "/get_public_nodes"); |
| 16155 | } |
| 16156 | |
| 16157 | std::vector<cryptonote::public_node> nodes; |
| 16158 | nodes = res.white; |
| 16159 | nodes.reserve(nodes.size() + res.gray.size()); |
| 16160 | std::copy(res.gray.begin(), res.gray.end(), std::back_inserter(nodes)); |
| 16161 | return nodes; |
| 16162 | } |
| 16163 | //---------------------------------------------------------------------------------------------------- |
| 16164 | std::pair<size_t, uint64_t> wallet2::estimate_tx_size_and_weight(bool use_rct, int n_inputs, int ring_size, int n_outputs, size_t extra_size) |
| 16165 | { |
| 16166 | THROW_WALLET_EXCEPTION_IF(n_inputs <= 0, tools::error::wallet_internal_error, "Invalid n_inputs"); |
| 16167 | THROW_WALLET_EXCEPTION_IF(n_outputs < 0, tools::error::wallet_internal_error, "Invalid n_outputs"); |
| 16168 | THROW_WALLET_EXCEPTION_IF(ring_size < 0, tools::error::wallet_internal_error, "Invalid ring size"); |
| 16169 | |
| 16170 | if (ring_size == 0) |
| 16171 | ring_size = get_min_ring_size(); |
| 16172 | if (n_outputs == 1) |
| 16173 | n_outputs = 2; // extra dummy output |
| 16174 | |
| 16175 | const bool bulletproof = use_fork_rules(get_bulletproof_fork(), 0); |
| 16176 | const bool bulletproof_plus = use_fork_rules(get_bulletproof_plus_fork(), 0); |
| 16177 | const bool clsag = use_fork_rules(get_clsag_fork(), 0); |
| 16178 | const bool use_view_tags = use_fork_rules(get_view_tag_fork(), 0); |
| 16179 | size_t size = estimate_tx_size(use_rct, n_inputs, ring_size - 1, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 16180 | uint64_t weight = estimate_tx_weight(use_rct, n_inputs, ring_size - 1, n_outputs, extra_size, bulletproof, clsag, bulletproof_plus, use_view_tags); |
| 16181 | return std::make_pair(size, weight); |
| 16182 | } |
| 16183 | //---------------------------------------------------------------------------------------------------- |
| 16184 | } |