Debian Codegraph @

monero/src/simplewallet/simplewallet.cpp

raw symbols SCIP
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 /*!
32 * \file simplewallet.cpp
33 *
34 * \brief Source file that defines simple_wallet class.
35 */
36
37 // use boost bind placeholders for now
38 #define BOOST_BIND_GLOBAL_PLACEHOLDERS 1
39 #include <boost/bind.hpp>
40
41 #include <locale.h>
42 #include <thread>
43 #include <iostream>
44 #include <sstream>
45 #include <fstream>
46 #include <ctype.h>
47 #include <boost/lexical_cast.hpp>
48 #include <boost/program_options.hpp>
49 #include <boost/algorithm/string.hpp>
50 #include <boost/format.hpp>
51 #include <boost/regex.hpp>
52 #include <boost/range/adaptor/transformed.hpp>
53 #include <boost/filesystem.hpp>
54 #include "include_base_utils.h"
55 #include "console_handler.h"
56 #include "common/i18n.h"
57 #include "common/command_line.h"
58 #include "common/util.h"
59 #include "common/dns_utils.h"
60 #include "common/base58.h"
61 #include "common/scoped_message_writer.h"
62 #include "cryptonote_protocol/cryptonote_protocol_handler.h"
63 #include "simplewallet.h"
64 #include "cryptonote_basic/cryptonote_format_utils.h"
65 #include "storages/http_abstract_invoke.h"
66 #include "rpc/core_rpc_server_commands_defs.h"
67 #include "rpc/rpc_payment_signature.h"
68 #include "crypto/crypto.h" // for crypto::secret_key definition
69 #include "mnemonics/electrum-words.h"
70 #include "rapidjson/document.h"
71 #include "common/json_util.h"
72 #include "ringct/rctSigs.h"
73 #include "multisig/multisig.h"
74 #include "wallet/wallet_args.h"
75 #include "version.h"
76 #include <stdexcept>
77 #include "wallet/message_store.h"
78 #include "QrCode.hpp"
79
80 #ifdef WIN32
81 #include <boost/locale.hpp>
82 #include <boost/filesystem.hpp>
83 #include <fcntl.h>
84 #endif
85
86 #ifdef HAVE_READLINE
87 #include "readline_buffer.h"
88 #endif
89
90 using namespace std;
91 using namespace epee;
92 using namespace cryptonote;
93 using boost::lexical_cast;
94 namespace po = boost::program_options;
95 typedef cryptonote::simple_wallet sw;
96
97 #undef MONERO_DEFAULT_LOG_CATEGORY
98 #define MONERO_DEFAULT_LOG_CATEGORY "wallet.simplewallet"
99
100 #define EXTENDED_LOGS_FILE "wallet_details.log"
101
102 #define OLD_AGE_WARN_THRESHOLD (30 * 86400 / DIFFICULTY_TARGET_V2) // 30 days
103
104 #define LOCK_IDLE_SCOPE() \
105 bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \
106 m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \
107 /* stop any background refresh and other processes, and take over */ \
108 m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); \
109 m_wallet->stop(); \
110 boost::unique_lock<boost::mutex> lock(m_idle_mutex); \
111 m_idle_cond.notify_all(); \
112 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \
113 /* m_idle_mutex is still locked here */ \
114 m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \
115 m_suspend_rpc_payment_mining.store(false, std::memory_order_relaxed); \
116 m_rpc_payment_checker.trigger(); \
117 m_idle_cond.notify_one(); \
118 })
119
120 #define SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(code) \
121 LOCK_IDLE_SCOPE(); \
122 boost::optional<tools::password_container> pwd_container = boost::none; \
123 if (m_wallet->ask_password() && !(pwd_container = get_and_verify_password())) { code; } \
124 tools::wallet_keys_unlocker unlocker(*m_wallet, pwd_container);
125
126 #define SCOPED_WALLET_UNLOCK() SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return true;)
127
128 #define PRINT_USAGE(usage_help) fail_msg_writer() << boost::format(tr("usage: %s")) % usage_help;
129
130 #define LONG_PAYMENT_ID_SUPPORT_CHECK() \
131 do { \
132 fail_msg_writer() << tr("Error: Long payment IDs are obsolete."); \
133 fail_msg_writer() << tr("Long payment IDs were not encrypted on the blockchain and would harm your privacy."); \
134 fail_msg_writer() << tr("If the party you're sending to still requires a long payment ID, please notify them."); \
135 return true; \
136 } while(0)
137
138 #define REFRESH_PERIOD 90 // seconds
139
140 #define CREDITS_TARGET 50000
141 #define MAX_PAYMENT_DIFF 10000
142 #define MIN_PAYMENT_RATE 0.01f // per hash
143 #define MAX_MNEW_ADDRESSES 1000
144
145 #define CHECK_MULTISIG_ENABLED() \
146 do \
147 { \
148 if (!m_wallet->is_multisig_enabled()) \
149 { \
150 fail_msg_writer() << tr("Multisig is disabled."); \
151 fail_msg_writer() << tr("Multisig is an experimental feature and may have bugs. Things that could go wrong include: funds sent to a multisig wallet can't be spent at all, can only be spent with the participation of a malicious group member, or can be stolen by a malicious group member."); \
152 fail_msg_writer() << tr("You can enable it with:"); \
153 fail_msg_writer() << tr(" set enable-multisig-experimental 1"); \
154 return false; \
155 } \
156 } while(0)
157
158 #define CHECK_IF_BACKGROUND_SYNCING(msg) \
159 do \
160 { \
161 if (m_wallet->is_background_wallet() || m_wallet->is_background_syncing()) \
162 { \
163 std::string type = m_wallet->is_background_wallet() ? "background wallet" : "background syncing wallet"; \
164 fail_msg_writer() << boost::format(tr("%s %s")) % type % msg; \
165 return false; \
166 } \
167 } while (0)
168
169 static std::string get_human_readable_timespan(std::chrono::seconds seconds);
170 static std::string get_human_readable_timespan(uint64_t seconds);
171
172 namespace
173 {
174 const std::array<const char* const, 5> allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}};
175 const auto arg_wallet_file = wallet_args::arg_wallet_file();
176 const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key();
177 const command_line::arg_descriptor<std::string> arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to <arg>"), ""};
178 const command_line::arg_descriptor<std::string> arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to <arg>"), ""};
179 const command_line::arg_descriptor<std::string> arg_generate_from_view_key = {"generate-from-view-key", sw::tr("Generate incoming-only wallet from view key"), ""};
180 const command_line::arg_descriptor<std::string> arg_generate_from_spend_key = {"generate-from-spend-key", sw::tr("Generate deterministic wallet from spend key"), ""};
181 const command_line::arg_descriptor<std::string> arg_generate_from_keys = {"generate-from-keys", sw::tr("Generate wallet from private keys"), ""};
182 const command_line::arg_descriptor<std::string> arg_generate_from_multisig_keys = {"generate-from-multisig-keys", sw::tr("Generate a master wallet from multisig wallet keys"), ""};
183 const auto arg_generate_from_json = wallet_args::arg_generate_from_json();
184 const command_line::arg_descriptor<std::string> arg_mnemonic_language = {"mnemonic-language", sw::tr("Language for mnemonic"), ""};
185 const command_line::arg_descriptor<std::string> arg_electrum_seed = {"electrum-seed", sw::tr("Specify Electrum seed for wallet recovery/creation"), ""};
186 const command_line::arg_descriptor<bool> arg_restore_deterministic_wallet = {"restore-deterministic-wallet", sw::tr("Recover wallet using Electrum-style mnemonic seed"), false};
187 const command_line::arg_descriptor<bool> arg_restore_from_seed = {"restore-from-seed", sw::tr("alias for --restore-deterministic-wallet"), false};
188 const command_line::arg_descriptor<bool> arg_restore_multisig_wallet = {"restore-multisig-wallet", sw::tr("Recover multisig wallet using Electrum-style mnemonic seed"), false};
189 const command_line::arg_descriptor<bool> arg_non_deterministic = {"non-deterministic", sw::tr("Generate non-deterministic view and spend keys"), false};
190 const command_line::arg_descriptor<bool> arg_allow_mismatched_daemon_version = {"allow-mismatched-daemon-version", sw::tr("Allow communicating with a daemon that uses a different RPC version"), false};
191 const command_line::arg_descriptor<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0};
192 const command_line::arg_descriptor<std::string> arg_restore_date = {"restore-date", sw::tr("Restore from estimated blockchain height on specified date"), ""};
193 const command_line::arg_descriptor<bool> arg_do_not_relay = {"do-not-relay", sw::tr("The newly created transaction will not be relayed to the monero network"), false};
194 const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false};
195 const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""};
196 const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false};
197
198 const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""};
199
200 const char* USAGE_START_MINING("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]");
201 const char* USAGE_SET_DAEMON("set_daemon <host>[:<port>] [trusted|untrusted|this-is-probably-a-spy-node]");
202 const char* USAGE_SHOW_BALANCE("balance [detail]");
203 const char* USAGE_INCOMING_TRANSFERS("incoming_transfers [available|unavailable] [verbose] [uses] [index=<N1>[,<N2>[,...]]]");
204 const char* USAGE_PAYMENTS("payments <PID_1> [<PID_2> ... <PID_N>]");
205 const char* USAGE_PAYMENT_ID("payment_id");
206 const char* USAGE_TRANSFER("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [subtractfeefrom=<D0>[,<D1>,all,...]] [<payment_id>]");
207 const char* USAGE_SWEEP_ALL("sweep_all [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
208 const char* USAGE_SWEEP_ACCOUNT("sweep_account <account> [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
209 const char* USAGE_SWEEP_BELOW("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id (obsolete)>]");
210 const char* USAGE_SWEEP_SINGLE("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id (obsolete)>]");
211 const char* USAGE_DONATE("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id (obsolete)>]");
212 const char* USAGE_SIGN_TRANSFER("sign_transfer [export_raw] [<filename>]");
213 const char* USAGE_SET_LOG("set_log <level>|{+,-,}<categories>");
214 const char* USAGE_ACCOUNT("account\n"
215 " account new <label text with white spaces allowed>\n"
216 " account switch <index> \n"
217 " account label <index> <label text with white spaces allowed>\n"
218 " account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
219 " account untag <account_index_1> [<account_index_2> ...]\n"
220 " account tag_description <tag_name> <description>");
221 const char* USAGE_ADDRESS("address [ new <label text with white spaces allowed> | mnew <amount of new addresses> | all | <index_min> [<index_max>] | label <index> <label text with white spaces allowed> | device [<index>] | one-off <account> <subaddress>]");
222 const char* USAGE_INTEGRATED_ADDRESS("integrated_address [device] [<payment_id> | <address>]");
223 const char* USAGE_ADDRESS_BOOK("address_book [(add (<address>|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]");
224 const char* USAGE_SET_VARIABLE("set <option> [<value>]");
225 const char* USAGE_GET_TX_KEY("get_tx_key <txid>");
226 const char* USAGE_SET_TX_KEY("set_tx_key <txid> <tx_key> [<subaddress>]");
227 const char* USAGE_CHECK_TX_KEY("check_tx_key <txid> <txkey> <address>");
228 const char* USAGE_GET_TX_PROOF("get_tx_proof <txid> <address> [<message>]");
229 const char* USAGE_CHECK_TX_PROOF("check_tx_proof <txid> <address> <signature_file> [<message>]");
230 const char* USAGE_GET_SPEND_PROOF("get_spend_proof <txid> [<message>]");
231 const char* USAGE_CHECK_SPEND_PROOF("check_spend_proof <txid> <signature_file> [<message>]");
232 const char* USAGE_GET_RESERVE_PROOF("get_reserve_proof (all|<amount>) [<message>]");
233 const char* USAGE_CHECK_RESERVE_PROOF("check_reserve_proof <address> <signature_file> [<message>]");
234 const char* USAGE_SHOW_TRANSFERS("show_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
235 const char* USAGE_UNSPENT_OUTPUTS("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]");
236 const char* USAGE_RESCAN_BC("rescan_bc [hard|soft|keep_ki] [start_height=0]");
237 const char* USAGE_SET_TX_NOTE("set_tx_note <txid> [free text note]");
238 const char* USAGE_GET_TX_NOTE("get_tx_note <txid>");
239 const char* USAGE_GET_DESCRIPTION("get_description");
240 const char* USAGE_SET_DESCRIPTION("set_description [free text note]");
241 const char* USAGE_SIGN("sign [<account_index>,<address_index>] [--spend|--view] <filename>");
242 const char* USAGE_VERIFY("verify <filename> <address> <signature>");
243 const char* USAGE_EXPORT_KEY_IMAGES("export_key_images [all] <filename>");
244 const char* USAGE_IMPORT_KEY_IMAGES("import_key_images <filename>");
245 const char* USAGE_HW_KEY_IMAGES_SYNC("hw_key_images_sync");
246 const char* USAGE_HW_RECONNECT("hw_reconnect");
247 const char* USAGE_EXPORT_OUTPUTS("export_outputs [all] <filename>");
248 const char* USAGE_IMPORT_OUTPUTS("import_outputs <filename>");
249 const char* USAGE_SHOW_TRANSFER("show_transfer <txid>");
250 const char* USAGE_MAKE_MULTISIG("make_multisig <threshold> <string1> [<string>...]");
251 const char* USAGE_EXCHANGE_MULTISIG_KEYS("exchange_multisig_keys [force-update-use-with-caution] <string> [<string>...]");
252 const char* USAGE_EXPORT_MULTISIG_INFO("export_multisig_info <filename>");
253 const char* USAGE_IMPORT_MULTISIG_INFO("import_multisig_info <filename> [<filename>...]");
254 const char* USAGE_SIGN_MULTISIG("sign_multisig <filename>");
255 const char* USAGE_SUBMIT_MULTISIG("submit_multisig <filename>");
256 const char* USAGE_EXPORT_RAW_MULTISIG_TX("export_raw_multisig_tx <filename>");
257 const char* USAGE_MMS("mms [<subcommand> [<subcommand_parameters>]]");
258 const char* USAGE_MMS_INIT("mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
259 const char* USAGE_MMS_INFO("mms info");
260 const char* USAGE_MMS_SIGNER("mms signer [<number> <label> [<transport_address> [<monero_address>]]]");
261 const char* USAGE_MMS_LIST("mms list");
262 const char* USAGE_MMS_NEXT("mms next [sync]");
263 const char* USAGE_MMS_SYNC("mms sync");
264 const char* USAGE_MMS_TRANSFER("mms transfer <transfer_command_arguments>");
265 const char* USAGE_MMS_DELETE("mms delete (<message_id> | all)");
266 const char* USAGE_MMS_SEND("mms send [<message_id>]");
267 const char* USAGE_MMS_RECEIVE("mms receive");
268 const char* USAGE_MMS_EXPORT("mms export <message_id>");
269 const char* USAGE_MMS_NOTE("mms note [<label> <text>]");
270 const char* USAGE_MMS_SHOW("mms show <message_id>");
271 const char* USAGE_MMS_SET("mms set <option_name> [<option_value>]");
272 const char* USAGE_MMS_SEND_SIGNER_CONFIG("mms send_signer_config");
273 const char* USAGE_MMS_START_AUTO_CONFIG("mms start_auto_config [<label> <label> ...]");
274 const char* USAGE_MMS_CONFIG_CHECKSUM("mms config_checksum");
275 const char* USAGE_MMS_STOP_AUTO_CONFIG("mms stop_auto_config");
276 const char* USAGE_MMS_AUTO_CONFIG("mms auto_config <auto_config_token>");
277 const char* USAGE_PRINT_RING("print_ring <key_image> | <txid>");
278 const char* USAGE_SET_RING("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )");
279 const char* USAGE_UNSET_RING("unset_ring <txid> | ( <key_image> [<key_image>...] )");
280 const char* USAGE_SAVE_KNOWN_RINGS("save_known_rings");
281 const char* USAGE_MARK_OUTPUT_SPENT("mark_output_spent <amount>/<offset> | <filename> [add]");
282 const char* USAGE_MARK_OUTPUT_UNSPENT("mark_output_unspent <amount>/<offset>");
283 const char* USAGE_IS_OUTPUT_SPENT("is_output_spent <amount>/<offset>");
284 const char* USAGE_FREEZE("freeze <key_image>");
285 const char* USAGE_THAW("thaw <key_image>");
286 const char* USAGE_FROZEN("frozen <key_image>");
287 const char* USAGE_LOCK("lock");
288 const char* USAGE_NET_STATS("net_stats");
289 const char* USAGE_PUBLIC_NODES("public_nodes");
290 const char* USAGE_WELCOME("welcome");
291 const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info");
292 const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc [<number_of_threads>]");
293 const char* USAGE_STOP_MINING_FOR_RPC("stop_mining_for_rpc");
294 const char* USAGE_SHOW_QR_CODE("show_qr_code [<subaddress_index>]");
295 const char* USAGE_VERSION("version");
296 const char* USAGE_HELP("help [<command> | all]");
297 const char* USAGE_APROPOS("apropos <keyword> [<keyword> ...]");
298 const char* USAGE_SCAN_TX("scan_tx <txid> [<txid> ...]");
299
300 std::string input_line(const std::string& prompt, bool yesno = false)
301 {
302 PAUSE_READLINE();
303 std::cout << prompt;
304 if (yesno)
305 std::cout << " (Y/Yes/N/No)";
306 std::cout << ": " << std::flush;
307
308 std::string buf;
309 #ifdef _WIN32
310 buf = tools::input_line_win();
311 #else
312 std::getline(std::cin, buf);
313 #endif
314
315 return epee::string_tools::trim(buf);
316 }
317
318 epee::wipeable_string input_secure_line(const char *prompt)
319 {
320 PAUSE_READLINE();
321 auto pwd_container = tools::password_container::prompt(false, prompt, false);
322 if (!pwd_container)
323 {
324 MERROR("Failed to read secure line");
325 return "";
326 }
327
328 epee::wipeable_string buf = pwd_container->password();
329
330 buf.trim();
331 return buf;
332 }
333
334 boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
335 {
336 PAUSE_READLINE();
337 auto pwd_container = tools::password_container::prompt(verify, prompt);
338 if (!pwd_container)
339 {
340 tools::fail_msg_writer() << sw::tr("failed to read password");
341 }
342 return pwd_container;
343 }
344
345 boost::optional<tools::password_container> default_password_prompter(bool verify)
346 {
347 return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify);
348 }
349
350 boost::optional<tools::password_container> background_sync_cache_password_prompter(bool verify)
351 {
352 return password_prompter(verify ? sw::tr("Enter a custom password for the background sync cache") : sw::tr("Background sync cache password"), verify);
353 }
354
355 inline std::string interpret_rpc_response(bool ok, const std::string& status)
356 {
357 std::string err;
358 if (ok)
359 {
360 if (status == CORE_RPC_STATUS_BUSY)
361 {
362 err = sw::tr("daemon is busy. Please try again later.");
363 }
364 else if (status != CORE_RPC_STATUS_OK)
365 {
366 err = status;
367 }
368 }
369 else
370 {
371 err = sw::tr("possibly lost connection to daemon");
372 }
373 return err;
374 }
375
376 tools::scoped_message_writer success_msg_writer(bool color = false)
377 {
378 return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info);
379 }
380
381 tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false)
382 {
383 return tools::scoped_message_writer(color, bright);
384 }
385
386 tools::scoped_message_writer fail_msg_writer()
387 {
388 return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error);
389 }
390
391 bool parse_bool(const std::string& s, bool& result)
392 {
393 if (s == "1" || command_line::is_yes(s))
394 {
395 result = true;
396 return true;
397 }
398 if (s == "0" || command_line::is_no(s))
399 {
400 result = false;
401 return true;
402 }
403
404 boost::algorithm::is_iequal ignore_case{};
405 if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case))
406 {
407 result = true;
408 return true;
409 }
410 if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case))
411 {
412 result = false;
413 return true;
414 }
415
416 return false;
417 }
418
419 template <typename F>
420 bool parse_bool_and_use(const std::string& s, F func)
421 {
422 bool r;
423 if (parse_bool(s, r))
424 {
425 func(r);
426 return true;
427 }
428 else
429 {
430 fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no");
431 return false;
432 }
433 }
434
435 const struct
436 {
437 const char *name;
438 tools::wallet2::RefreshType refresh_type;
439 } refresh_type_names[] =
440 {
441 { "full", tools::wallet2::RefreshFull },
442 { "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
443 { "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
444 { "no-coinbase", tools::wallet2::RefreshNoCoinbase },
445 { "default", tools::wallet2::RefreshDefault },
446 };
447
448 bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type)
449 {
450 for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
451 {
452 if (s == refresh_type_names[n].name)
453 {
454 refresh_type = refresh_type_names[n].refresh_type;
455 return true;
456 }
457 }
458 fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type");
459 return false;
460 }
461
462 std::string get_refresh_type_name(tools::wallet2::RefreshType type)
463 {
464 for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
465 {
466 if (type == refresh_type_names[n].refresh_type)
467 return refresh_type_names[n].name;
468 }
469 return "invalid";
470 }
471
472 const struct
473 {
474 const char *name;
475 tools::wallet2::BackgroundSyncType background_sync_type;
476 } background_sync_type_names[] =
477 {
478 { "off", tools::wallet2::BackgroundSyncOff },
479 { "reuse-wallet-password", tools::wallet2::BackgroundSyncReusePassword },
480 { "custom-background-password", tools::wallet2::BackgroundSyncCustomPassword },
481 };
482
483 bool parse_background_sync_type(const std::string &s, tools::wallet2::BackgroundSyncType &background_sync_type)
484 {
485 for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
486 {
487 if (s == background_sync_type_names[n].name)
488 {
489 background_sync_type = background_sync_type_names[n].background_sync_type;
490 return true;
491 }
492 }
493 fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse background sync type");
494 return false;
495 }
496
497 std::string get_background_sync_type_name(tools::wallet2::BackgroundSyncType type)
498 {
499 for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
500 {
501 if (type == background_sync_type_names[n].background_sync_type)
502 return background_sync_type_names[n].name;
503 }
504 return "invalid";
505 }
506
507 std::string get_version_string(uint32_t version)
508 {
509 return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff);
510 }
511
512 std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)
513 {
514 if (addresses.empty())
515 return {};
516 // prompt user for confirmation.
517 // inform user of DNSSEC validation status as well.
518 std::string dnssec_str;
519 if (dnssec_valid)
520 {
521 dnssec_str = sw::tr("DNSSEC validation passed");
522 }
523 else
524 {
525 dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!");
526 }
527 std::stringstream prompt;
528 prompt << sw::tr("For URL: ") << url
529 << ", " << dnssec_str << std::endl
530 << sw::tr(" Monero Address = ") << addresses[0]
531 << std::endl
532 << sw::tr("Is this OK?")
533 ;
534 // prompt the user for confirmation given the dns query and dnssec status
535 std::string confirm_dns_ok = input_line(prompt.str(), true);
536 if (std::cin.eof())
537 {
538 return {};
539 }
540 if (!command_line::is_yes(confirm_dns_ok))
541 {
542 std::cout << sw::tr("you have cancelled the transfer request") << std::endl;
543 return {};
544 }
545 return addresses[0];
546 }
547
548 bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices)
549 {
550 subaddr_indices.clear();
551
552 if (arg.substr(0, 6) != "index=")
553 return false;
554 std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6);
555 std::vector<std::string> subaddr_indices_str;
556 boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(","));
557
558 for (const auto& subaddr_index_str : subaddr_indices_str)
559 {
560 uint32_t subaddr_index;
561 if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str))
562 {
563 fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str;
564 subaddr_indices.clear();
565 return false;
566 }
567 subaddr_indices.insert(subaddr_index);
568 }
569 return true;
570 }
571
572 boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str)
573 {
574 auto r = tools::parse_subaddress_lookahead(str);
575 if (!r)
576 fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>");
577 return r;
578 }
579
580 static constexpr const char* SFFD_ARG_NAME{"subtractfeefrom="};
581
582 bool parse_subtract_fee_from_outputs
583 (
584 const std::string& arg,
585 tools::wallet2::unique_index_container& subtract_fee_from_outputs,
586 bool& subtract_fee_from_all,
587 bool& matches
588 )
589 {
590 matches = false;
591 if (!boost::string_ref{arg}.starts_with(SFFD_ARG_NAME)) // if arg doesn't match
592 return true;
593 matches = true;
594
595 const char* arg_end = arg.c_str() + arg.size();
596 for (const char* p = arg.c_str() + strlen(SFFD_ARG_NAME); p < arg_end;)
597 {
598 const char* new_p = nullptr;
599 const unsigned long dest_index = strtoul(p, const_cast<char**>(&new_p), 10);
600 if (dest_index == 0 && new_p == p) // numerical conversion failed
601 {
602 if (0 != strncmp(p, "all", 3))
603 {
604 fail_msg_writer() << tr("Failed to parse subtractfeefrom list");
605 return false;
606 }
607 subtract_fee_from_all = true;
608 break;
609 }
610 else if (dest_index > std::numeric_limits<uint32_t>::max())
611 {
612 fail_msg_writer() << tr("Destination index is too large") << ": " << dest_index;
613 return false;
614 }
615 else
616 {
617 subtract_fee_from_outputs.insert(dest_index);
618 p = new_p + 1; // skip the comma
619 }
620 }
621
622 return true;
623 }
624 } // anonymous namespace
625
626 void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon)
627 {
628 bool warn_of_possible_attack = !trusted_daemon;
629 try
630 {
631 std::rethrow_exception(e);
632 }
633 catch (const tools::error::payment_required&)
634 {
635 fail_msg_writer() << tr("Payment required, see the 'rpc_payment_info' command");
636 m_need_payment = true;
637 }
638 catch (const tools::error::no_connection_to_daemon&)
639 {
640 fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running.");
641 }
642 catch (const tools::error::daemon_busy&)
643 {
644 fail_msg_writer() << tr("daemon is busy. Please try again later.");
645 }
646 catch (const tools::error::wallet_rpc_error& e)
647 {
648 LOG_ERROR("RPC error: " << e.to_string());
649 fail_msg_writer() << sw::tr("RPC error: ") << e.what();
650 }
651 catch (const tools::error::get_outs_error &e)
652 {
653 fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what();
654 }
655 catch (const tools::error::not_enough_unlocked_money& e)
656 {
657 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
658 print_money(e.available()) %
659 print_money(e.tx_amount()));
660 fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
661 warn_of_possible_attack = false;
662 }
663 catch (const tools::error::not_enough_money& e)
664 {
665 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
666 print_money(e.available()) %
667 print_money(e.tx_amount()));
668 fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
669 warn_of_possible_attack = false;
670 }
671 catch (const tools::error::tx_not_possible& e)
672 {
673 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") %
674 print_money(e.available()) %
675 print_money(e.tx_amount() + e.fee()) %
676 print_money(e.tx_amount()) %
677 print_money(e.fee()));
678 fail_msg_writer() << sw::tr("Failed to find a way to create transactions. This is usually due to dust which is so small it cannot pay for itself in fees, or trying to send more money than the unlocked balance, or not leaving enough for fees");
679 warn_of_possible_attack = false;
680 }
681 catch (const tools::error::not_enough_outs_to_mix& e)
682 {
683 auto writer = fail_msg_writer();
684 writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":";
685 for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs())
686 {
687 writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second;
688 }
689 writer << sw::tr("Please use sweep_unmixable.");
690 }
691 catch (const tools::error::tx_not_constructed&)
692 {
693 fail_msg_writer() << sw::tr("transaction was not constructed");
694 warn_of_possible_attack = false;
695 }
696 catch (const tools::error::tx_rejected& e)
697 {
698 fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx()));
699 std::string reason = e.reason();
700 if (!reason.empty())
701 fail_msg_writer() << sw::tr("Reason: ") << reason;
702 }
703 catch (const tools::error::tx_sum_overflow& e)
704 {
705 fail_msg_writer() << e.what();
706 warn_of_possible_attack = false;
707 }
708 catch (const tools::error::zero_amount&)
709 {
710 fail_msg_writer() << sw::tr("destination amount is zero");
711 warn_of_possible_attack = false;
712 }
713 catch (const tools::error::zero_destination&)
714 {
715 fail_msg_writer() << sw::tr("transaction has no destination");
716 warn_of_possible_attack = false;
717 }
718 catch (const tools::error::tx_too_big& e)
719 {
720 fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions");
721 warn_of_possible_attack = false;
722 }
723 catch (const tools::error::transfer_error& e)
724 {
725 LOG_ERROR("unknown transfer error: " << e.to_string());
726 fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what();
727 }
728 catch (const tools::error::multisig_export_needed& e)
729 {
730 LOG_ERROR("Multisig error: " << e.to_string());
731 fail_msg_writer() << sw::tr("Multisig error: ") << e.what();
732 warn_of_possible_attack = false;
733 }
734 catch (const tools::error::wallet_internal_error& e)
735 {
736 LOG_ERROR("internal error: " << e.to_string());
737 fail_msg_writer() << sw::tr("internal error: ") << e.what();
738 }
739 catch (const std::exception& e)
740 {
741 LOG_ERROR("unexpected error: " << e.what());
742 fail_msg_writer() << sw::tr("unexpected error: ") << e.what();
743 }
744
745 if (warn_of_possible_attack)
746 fail_msg_writer() << sw::tr("There was an error, which could mean the node may be trying to get you to retry creating a transaction, and zero in on which outputs you own. Or it could be a bona fide error. It may be prudent to disconnect from this node, and not try to send a transaction immediately. Alternatively, connect to another node so the original node cannot correlate information.");
747 }
748
749 namespace
750 {
751 bool check_file_overwrite(const std::string &filename)
752 {
753 boost::system::error_code errcode;
754 if (boost::filesystem::exists(filename, errcode))
755 {
756 if (boost::ends_with(filename, ".keys"))
757 {
758 fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename;
759 return false;
760 }
761 return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it?")) % filename).str(), true));
762 }
763 return true;
764 }
765
766 void print_secret_key(const crypto::secret_key &k)
767 {
768 static constexpr const char hex[] = u8"0123456789abcdef";
769 const uint8_t *ptr = (const uint8_t*)k.data;
770 for (size_t i = 0, sz = sizeof(k); i < sz; ++i)
771 {
772 putchar(hex[*ptr >> 4]);
773 putchar(hex[*ptr & 15]);
774 ++ptr;
775 }
776 }
777 }
778
779 bool parse_priority(const std::string& arg, uint32_t& priority)
780 {
781 auto priority_pos = std::find(
782 allowed_priority_strings.begin(),
783 allowed_priority_strings.end(),
784 arg);
785 if(priority_pos != allowed_priority_strings.end()) {
786 priority = std::distance(allowed_priority_strings.begin(), priority_pos);
787 return true;
788 }
789 return false;
790 }
791
792 std::string join_priority_strings(const char *delimiter)
793 {
794 std::string s;
795 for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
796 {
797 if (!s.empty())
798 s += delimiter;
799 s += allowed_priority_strings[n];
800 }
801 return s;
802 }
803
804 std::string simple_wallet::get_commands_str()
805 {
806 std::stringstream ss;
807 ss << tr("Commands: ") << ENDL;
808 std::string usage = m_cmd_binder.get_usage();
809 boost::replace_all(usage, "\n", "\n ");
810 usage.insert(0, " ");
811 ss << usage << ENDL;
812 return ss.str();
813 }
814
815 std::string simple_wallet::get_command_usage(const std::vector<std::string> &args)
816 {
817 std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args);
818 std::stringstream ss;
819 if(documentation.first.empty())
820 {
821 ss << tr("Unknown command: ") << args.front();
822 }
823 else
824 {
825 std::string usage = documentation.second.empty() ? args.front() : documentation.first;
826 std::string description = documentation.second.empty() ? documentation.first : documentation.second;
827 usage.insert(0, " ");
828 ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL;
829 boost::replace_all(description, "\n", "\n ");
830 description.insert(0, " ");
831 ss << tr("Command description: ") << ENDL << description << ENDL;
832 }
833 return ss.str();
834 }
835
836 bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
837 {
838 // don't log
839 PAUSE_READLINE();
840 if (m_wallet->key_on_device()) {
841 std::cout << "secret: On device. Not available" << std::endl;
842 } else {
843 SCOPED_WALLET_UNLOCK();
844 printf("secret: ");
845 print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
846 putchar('\n');
847 }
848 std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl;
849
850 return true;
851 }
852
853 bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
854 {
855 if (m_wallet->watch_only())
856 {
857 fail_msg_writer() << tr("wallet is watch-only and has no spend key");
858 return true;
859 }
860 CHECK_IF_BACKGROUND_SYNCING("has no spend key");
861 // don't log
862 PAUSE_READLINE();
863 if (m_wallet->key_on_device()) {
864 std::cout << "secret: On device. Not available" << std::endl;
865 } else {
866 SCOPED_WALLET_UNLOCK();
867 printf("secret: ");
868 print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key);
869 putchar('\n');
870 }
871 std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl;
872
873 return true;
874 }
875
876 bool simple_wallet::print_seed(bool encrypted)
877 {
878 bool success = false;
879 epee::wipeable_string seed;
880 bool ready, multisig;
881
882 if (m_wallet->key_on_device())
883 {
884 fail_msg_writer() << tr("command not supported by HW wallet");
885 return true;
886 }
887 if (m_wallet->watch_only())
888 {
889 fail_msg_writer() << tr("wallet is watch-only and has no seed");
890 return true;
891 }
892 CHECK_IF_BACKGROUND_SYNCING("has no seed");
893
894 multisig = m_wallet->multisig(&ready);
895 if (multisig)
896 {
897 if (!ready)
898 {
899 fail_msg_writer() << tr("wallet is multisig but not yet finalized");
900 return true;
901 }
902 }
903
904 SCOPED_WALLET_UNLOCK();
905
906 if (!multisig && !m_wallet->is_deterministic())
907 {
908 fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
909 return true;
910 }
911
912 epee::wipeable_string seed_pass;
913 if (encrypted)
914 {
915 auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true);
916 if (std::cin.eof() || !pwd_container)
917 return true;
918 seed_pass = pwd_container->password();
919 }
920
921 if (multisig)
922 success = m_wallet->get_multisig_seed(seed, seed_pass);
923 else if (m_wallet->is_deterministic())
924 success = m_wallet->get_seed(seed, seed_pass);
925
926 if (success)
927 {
928 print_seed(seed);
929 }
930 else
931 {
932 fail_msg_writer() << tr("Failed to retrieve seed");
933 }
934 return true;
935 }
936
937 bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
938 {
939 return print_seed(false);
940 }
941
942 bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
943 {
944 return print_seed(true);
945 }
946
947 bool simple_wallet::restore_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
948 {
949 success_msg_writer() << m_wallet->get_refresh_from_block_height();
950 return true;
951 }
952
953 bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
954 {
955 if (m_wallet->key_on_device())
956 {
957 fail_msg_writer() << tr("command not supported by HW wallet");
958 return true;
959 }
960 if (m_wallet->multisig())
961 {
962 fail_msg_writer() << tr("wallet is multisig and has no seed");
963 return true;
964 }
965 if (m_wallet->watch_only())
966 {
967 fail_msg_writer() << tr("wallet is watch-only and has no seed");
968 return true;
969 }
970 CHECK_IF_BACKGROUND_SYNCING("has no seed");
971
972 epee::wipeable_string password;
973 {
974 SCOPED_WALLET_UNLOCK();
975
976 if (!m_wallet->is_deterministic())
977 {
978 fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
979 return true;
980 }
981
982 // we need the password, even if ask-password is unset
983 if (!pwd_container)
984 {
985 pwd_container = get_and_verify_password();
986 if (pwd_container == boost::none)
987 {
988 fail_msg_writer() << tr("Incorrect password");
989 return true;
990 }
991 }
992 password = pwd_container->password();
993 }
994
995 std::string mnemonic_language = get_mnemonic_language();
996 if (mnemonic_language.empty())
997 return true;
998
999 m_wallet->set_seed_language(std::move(mnemonic_language));
1000 m_wallet->rewrite(m_wallet_file, password);
1001 return true;
1002 }
1003
1004 bool simple_wallet::change_password(const std::vector<std::string> &args)
1005 {
1006 const auto orig_pwd_container = get_and_verify_password();
1007
1008 if(orig_pwd_container == boost::none)
1009 {
1010 fail_msg_writer() << tr("Your original password was incorrect.");
1011 return true;
1012 }
1013
1014 // prompts for a new password, pass true to verify the password
1015 const auto pwd_container = default_password_prompter(true);
1016 if(!pwd_container)
1017 return true;
1018
1019 try
1020 {
1021 m_wallet->change_password(m_wallet_file, orig_pwd_container->password(), pwd_container->password());
1022 }
1023 catch (const tools::error::wallet_logic_error& e)
1024 {
1025 fail_msg_writer() << tr("Error with wallet rewrite: ") << e.what();
1026 return true;
1027 }
1028
1029 return true;
1030 }
1031
1032 bool simple_wallet::payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
1033 {
1034 LONG_PAYMENT_ID_SUPPORT_CHECK();
1035 }
1036
1037 bool simple_wallet::print_fee_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
1038 {
1039 if (!try_connect_to_daemon())
1040 return true;
1041 const bool per_byte = m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE);
1042 const uint64_t base_fee = m_wallet->get_base_fee();
1043 const char *base = per_byte ? "byte" : "kB";
1044 const uint64_t typical_size = per_byte ? 2500 : 13;
1045 const uint64_t size_granularity = per_byte ? 1 : 1024;
1046 message_writer() << (boost::format(tr("Current fee is %s %s per %s")) % print_money(base_fee) % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % base).str();
1047
1048 std::vector<uint64_t> fees;
1049 for (uint32_t priority = 1; priority <= 4; ++priority)
1050 {
1051 uint64_t mult = m_wallet->get_fee_multiplier(priority);
1052 fees.push_back(base_fee * typical_size * mult);
1053 }
1054 std::vector<std::pair<uint64_t, uint64_t>> blocks;
1055 try
1056 {
1057 uint64_t base_size = typical_size * size_granularity;
1058 blocks = m_wallet->estimate_backlog(base_size, base_size + size_granularity - 1, fees);
1059 }
1060 catch (const std::exception &e)
1061 {
1062 fail_msg_writer() << tr("Error: failed to estimate backlog array size: ") << e.what();
1063 return true;
1064 }
1065 if (blocks.size() != 4)
1066 {
1067 fail_msg_writer() << tr("Error: bad estimated backlog array size");
1068 return true;
1069 }
1070
1071 for (uint32_t priority = 1; priority <= 4; ++priority)
1072 {
1073 uint64_t nblocks_low = blocks[priority - 1].first;
1074 uint64_t nblocks_high = blocks[priority - 1].second;
1075 if (nblocks_low > 0)
1076 {
1077 std::string msg;
1078 if (priority == m_wallet->get_default_priority() || (m_wallet->get_default_priority() == 0 && priority == 2))
1079 msg = tr(" (current)");
1080 uint64_t minutes_low = nblocks_low * DIFFICULTY_TARGET_V2 / 60, minutes_high = nblocks_high * DIFFICULTY_TARGET_V2 / 60;
1081 if (nblocks_high == nblocks_low)
1082 message_writer() << (boost::format(tr("%u block (%u minutes) backlog at priority %u%s")) % nblocks_low % minutes_low % priority % msg).str();
1083 else
1084 message_writer() << (boost::format(tr("%u to %u block (%u to %u minutes) backlog at priority %u")) % nblocks_low % nblocks_high % minutes_low % minutes_high % priority).str();
1085 }
1086 else
1087 message_writer() << tr("No backlog at priority ") << priority;
1088 }
1089 return true;
1090 }
1091
1092 bool simple_wallet::prepare_multisig(const std::vector<std::string> &args)
1093 {
1094 CHECK_MULTISIG_ENABLED();
1095 prepare_multisig_main(args, false);
1096 return true;
1097 }
1098
1099 bool simple_wallet::prepare_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1100 {
1101 CHECK_MULTISIG_ENABLED();
1102 if (m_wallet->key_on_device())
1103 {
1104 fail_msg_writer() << tr("command not supported by HW wallet");
1105 return false;
1106 }
1107 if (m_wallet->multisig())
1108 {
1109 fail_msg_writer() << tr("This wallet is already multisig");
1110 return false;
1111 }
1112 if (m_wallet->watch_only())
1113 {
1114 fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
1115 return false;
1116 }
1117 CHECK_IF_BACKGROUND_SYNCING("cannot be made multisig");
1118
1119 if(m_wallet->get_num_transfer_details())
1120 {
1121 fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
1122 return false;
1123 }
1124
1125 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1126
1127 std::string multisig_info = m_wallet->get_multisig_first_kex_msg();
1128 success_msg_writer() << multisig_info;
1129 success_msg_writer() << tr("Send this multisig info to all other participants, then use make_multisig <threshold> <info1> [<info2>...] with others' multisig info");
1130 success_msg_writer() << tr("This includes the PRIVATE view key, so needs to be disclosed only to that multisig wallet's participants ");
1131
1132 if (called_by_mms)
1133 {
1134 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::key_set, multisig_info);
1135 }
1136
1137 return true;
1138 }
1139
1140 bool simple_wallet::make_multisig(const std::vector<std::string> &args)
1141 {
1142 CHECK_MULTISIG_ENABLED();
1143 make_multisig_main(args, false);
1144 return true;
1145 }
1146
1147 bool simple_wallet::make_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1148 {
1149 CHECK_MULTISIG_ENABLED();
1150 if (m_wallet->key_on_device())
1151 {
1152 fail_msg_writer() << tr("command not supported by HW wallet");
1153 return false;
1154 }
1155 if (m_wallet->multisig())
1156 {
1157 fail_msg_writer() << tr("This wallet is already multisig");
1158 return false;
1159 }
1160 if (m_wallet->watch_only())
1161 {
1162 fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
1163 return false;
1164 }
1165
1166 if(m_wallet->get_num_transfer_details())
1167 {
1168 fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
1169 return false;
1170 }
1171
1172 if (args.size() < 2)
1173 {
1174 PRINT_USAGE(USAGE_MAKE_MULTISIG);
1175 return false;
1176 }
1177
1178 // parse threshold
1179 uint32_t threshold;
1180 if (!string_tools::get_xtype_from_string(threshold, args[0]))
1181 {
1182 fail_msg_writer() << tr("Invalid threshold");
1183 return false;
1184 }
1185
1186 const auto orig_pwd_container = get_and_verify_password();
1187 if(orig_pwd_container == boost::none)
1188 {
1189 fail_msg_writer() << tr("Your original password was incorrect.");
1190 return false;
1191 }
1192
1193 LOCK_IDLE_SCOPE();
1194
1195 try
1196 {
1197 auto local_args = args;
1198 local_args.erase(local_args.begin());
1199 std::string multisig_extra_info = m_wallet->make_multisig(orig_pwd_container->password(), local_args, threshold);
1200 bool ready;
1201 m_wallet->multisig(&ready);
1202 if (!ready)
1203 {
1204 success_msg_writer() << tr("Another step is needed");
1205 success_msg_writer() << multisig_extra_info;
1206 success_msg_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
1207 if (called_by_mms)
1208 {
1209 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
1210 }
1211 return true;
1212 }
1213 }
1214 catch (const std::exception &e)
1215 {
1216 fail_msg_writer() << tr("Error creating multisig: ") << e.what();
1217 return false;
1218 }
1219
1220 uint32_t total;
1221 if (!m_wallet->multisig(NULL, &threshold, &total))
1222 {
1223 fail_msg_writer() << tr("Error creating multisig: new wallet is not multisig");
1224 return false;
1225 }
1226 success_msg_writer() << std::to_string(threshold) << "/" << total << tr(" multisig address: ")
1227 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
1228
1229 return true;
1230 }
1231
1232 bool simple_wallet::exchange_multisig_keys(const std::vector<std::string> &args)
1233 {
1234 CHECK_MULTISIG_ENABLED();
1235 bool force_update_use_with_caution = false;
1236
1237 auto local_args = args;
1238 if (args.size() >= 1 && local_args[0] == "force-update-use-with-caution")
1239 {
1240 force_update_use_with_caution = true;
1241 local_args.erase(local_args.begin());
1242 }
1243
1244 exchange_multisig_keys_main(local_args, force_update_use_with_caution, false);
1245 return true;
1246 }
1247
1248 bool simple_wallet::exchange_multisig_keys_main(const std::vector<std::string> &args,
1249 const bool force_update_use_with_caution,
1250 const bool called_by_mms) {
1251 CHECK_MULTISIG_ENABLED();
1252 bool ready;
1253 if (m_wallet->key_on_device())
1254 {
1255 fail_msg_writer() << tr("command not supported by HW wallet");
1256 return false;
1257 }
1258 if (!m_wallet->multisig(&ready))
1259 {
1260 fail_msg_writer() << tr("This wallet is not multisig");
1261 return false;
1262 }
1263 if (ready)
1264 {
1265 fail_msg_writer() << tr("This wallet is already finalized");
1266 return false;
1267 }
1268
1269 const auto orig_pwd_container = get_and_verify_password();
1270 if(orig_pwd_container == boost::none)
1271 {
1272 fail_msg_writer() << tr("Your original password was incorrect.");
1273 return false;
1274 }
1275
1276 try
1277 {
1278 std::string multisig_extra_info = m_wallet->exchange_multisig_keys(orig_pwd_container->password(), args, force_update_use_with_caution);
1279 bool ready;
1280 m_wallet->multisig(&ready);
1281 if (!ready)
1282 {
1283 message_writer() << tr("Another step is needed");
1284 message_writer() << multisig_extra_info;
1285 message_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
1286 if (called_by_mms)
1287 {
1288 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
1289 }
1290 return true;
1291 } else {
1292 uint32_t threshold, total;
1293 m_wallet->multisig(NULL, &threshold, &total);
1294 success_msg_writer() << tr("Multisig wallet has been successfully created. Current wallet type: ") << threshold << "/" << total;
1295 success_msg_writer() << tr("Multisig address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
1296 }
1297 }
1298 catch (const std::exception &e)
1299 {
1300 fail_msg_writer() << tr("Failed to perform multisig keys exchange: ") << e.what();
1301 return false;
1302 }
1303
1304 return true;
1305 }
1306
1307 bool simple_wallet::export_multisig(const std::vector<std::string> &args)
1308 {
1309 CHECK_MULTISIG_ENABLED();
1310 export_multisig_main(args, false);
1311 return true;
1312 }
1313
1314 bool simple_wallet::export_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1315 {
1316 CHECK_MULTISIG_ENABLED();
1317 bool ready;
1318 if (m_wallet->key_on_device())
1319 {
1320 fail_msg_writer() << tr("command not supported by HW wallet");
1321 return false;
1322 }
1323 if (!m_wallet->multisig(&ready))
1324 {
1325 fail_msg_writer() << tr("This wallet is not multisig");
1326 return false;
1327 }
1328 if (!ready)
1329 {
1330 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1331 return false;
1332 }
1333 if (args.size() != 1)
1334 {
1335 PRINT_USAGE(USAGE_EXPORT_MULTISIG_INFO);
1336 return false;
1337 }
1338
1339 const std::string filename = args[0];
1340 if (!called_by_mms && m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
1341 return true;
1342
1343 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1344
1345 try
1346 {
1347 cryptonote::blobdata ciphertext = m_wallet->export_multisig();
1348
1349 if (called_by_mms)
1350 {
1351 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::multisig_sync_data, ciphertext);
1352 }
1353 else
1354 {
1355 bool r = m_wallet->save_to_file(filename, ciphertext);
1356 if (!r)
1357 {
1358 fail_msg_writer() << tr("failed to save file ") << filename;
1359 return false;
1360 }
1361 }
1362 }
1363 catch (const std::exception &e)
1364 {
1365 LOG_ERROR("Error exporting multisig info: " << e.what());
1366 fail_msg_writer() << tr("Error exporting multisig info: ") << e.what();
1367 return false;
1368 }
1369
1370 success_msg_writer() << tr("Multisig info exported to ") << filename;
1371 return true;
1372 }
1373
1374 bool simple_wallet::import_multisig(const std::vector<std::string> &args)
1375 {
1376 CHECK_MULTISIG_ENABLED();
1377 import_multisig_main(args, false);
1378 return true;
1379 }
1380
1381 bool simple_wallet::import_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1382 {
1383 CHECK_MULTISIG_ENABLED();
1384 bool ready;
1385 uint32_t threshold, total;
1386 if (m_wallet->key_on_device())
1387 {
1388 fail_msg_writer() << tr("command not supported by HW wallet");
1389 return false;
1390 }
1391 if (!m_wallet->multisig(&ready, &threshold, &total))
1392 {
1393 fail_msg_writer() << tr("This wallet is not multisig");
1394 return false;
1395 }
1396 if (!ready)
1397 {
1398 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1399 return false;
1400 }
1401 if (args.size() < threshold - 1)
1402 {
1403 PRINT_USAGE(USAGE_IMPORT_MULTISIG_INFO);
1404 return false;
1405 }
1406
1407 std::vector<cryptonote::blobdata> info;
1408 for (size_t n = 0; n < args.size(); ++n)
1409 {
1410 if (called_by_mms)
1411 {
1412 info.push_back(args[n]);
1413 }
1414 else
1415 {
1416 const std::string &filename = args[n];
1417 std::string data;
1418 bool r = m_wallet->load_from_file(filename, data);
1419 if (!r)
1420 {
1421 fail_msg_writer() << tr("failed to read file ") << filename;
1422 return false;
1423 }
1424 info.push_back(std::move(data));
1425 }
1426 }
1427
1428 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1429
1430 // all read and parsed, actually import
1431 try
1432 {
1433 m_in_manual_refresh.store(true, std::memory_order_relaxed);
1434 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
1435 size_t n_outputs = m_wallet->import_multisig(info);
1436 // Clear line "Height xxx of xxx"
1437 std::cout << "\r \r";
1438 success_msg_writer() << tr("Multisig info imported. Number of outputs updated: ") << n_outputs;
1439 }
1440 catch (const std::exception &e)
1441 {
1442 fail_msg_writer() << tr("Failed to import multisig info: ") << e.what();
1443 return false;
1444 }
1445 if (m_wallet->is_trusted_daemon())
1446 {
1447 try
1448 {
1449 m_wallet->rescan_spent();
1450 }
1451 catch (const std::exception &e)
1452 {
1453 message_writer() << tr("Failed to update spent status after importing multisig info: ") << e.what();
1454 return false;
1455 }
1456 }
1457 else
1458 {
1459 message_writer() << tr("Untrusted daemon, spent status may be incorrect. Use a trusted daemon and run \"rescan_spent\"");
1460 return false;
1461 }
1462 return true;
1463 }
1464
1465 bool simple_wallet::accept_loaded_tx(const tools::wallet2::multisig_tx_set &txs)
1466 {
1467 std::string extra_message;
1468 return accept_loaded_tx([&txs](){return txs.m_ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.m_ptx[n].construction_data;}, extra_message);
1469 }
1470
1471 bool simple_wallet::sign_multisig(const std::vector<std::string> &args)
1472 {
1473 CHECK_MULTISIG_ENABLED();
1474 sign_multisig_main(args, false);
1475 return true;
1476 }
1477
1478 bool simple_wallet::sign_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1479 {
1480 CHECK_MULTISIG_ENABLED();
1481 bool ready;
1482 if (m_wallet->key_on_device())
1483 {
1484 fail_msg_writer() << tr("command not supported by HW wallet");
1485 return false;
1486 }
1487 if(!m_wallet->multisig(&ready))
1488 {
1489 fail_msg_writer() << tr("This is not a multisig wallet");
1490 return false;
1491 }
1492 if (!ready)
1493 {
1494 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1495 return false;
1496 }
1497 if (args.size() != 1)
1498 {
1499 PRINT_USAGE(USAGE_SIGN_MULTISIG);
1500 return false;
1501 }
1502
1503 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1504
1505 std::string filename = args[0];
1506 std::vector<crypto::hash> txids;
1507 uint32_t signers = 0;
1508 try
1509 {
1510 if (called_by_mms)
1511 {
1512 tools::wallet2::multisig_tx_set exported_txs;
1513 std::string ciphertext;
1514 bool r = m_wallet->load_multisig_tx(args[0], exported_txs, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); });
1515 if (r)
1516 {
1517 r = m_wallet->sign_multisig_tx(exported_txs, txids);
1518 }
1519 if (r)
1520 {
1521 ciphertext = m_wallet->save_multisig_tx(exported_txs);
1522 if (ciphertext.empty())
1523 {
1524 r = false;
1525 }
1526 }
1527 if (r)
1528 {
1529 mms::message_type message_type = mms::message_type::fully_signed_tx;
1530 if (txids.empty())
1531 {
1532 message_type = mms::message_type::partially_signed_tx;
1533 }
1534 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), message_type, ciphertext);
1535 filename = "MMS"; // for the messages below
1536 }
1537 else
1538 {
1539 fail_msg_writer() << tr("Failed to sign multisig transaction");
1540 return false;
1541 }
1542 }
1543 else
1544 {
1545 bool r = m_wallet->sign_multisig_tx_from_file(filename, txids, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); });
1546 if (!r)
1547 {
1548 fail_msg_writer() << tr("Failed to sign multisig transaction");
1549 return false;
1550 }
1551 }
1552 }
1553 catch (const tools::error::multisig_export_needed& e)
1554 {
1555 fail_msg_writer() << tr("Multisig error: ") << e.what();
1556 return false;
1557 }
1558 catch (const std::exception &e)
1559 {
1560 fail_msg_writer() << tr("Failed to sign multisig transaction: ") << e.what();
1561 return false;
1562 }
1563
1564 if (txids.empty())
1565 {
1566 uint32_t threshold;
1567 m_wallet->multisig(NULL, &threshold);
1568 uint32_t signers_needed = threshold - signers - 1;
1569 success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", "
1570 << signers_needed << " more signer(s) needed";
1571 return true;
1572 }
1573 else
1574 {
1575 std::string txids_as_text;
1576 for (const auto &txid: txids)
1577 {
1578 if (!txids_as_text.empty())
1579 txids_as_text += (", ");
1580 txids_as_text += epee::string_tools::pod_to_hex(txid);
1581 }
1582 success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", txid " << txids_as_text;
1583 success_msg_writer(true) << tr("It may be relayed to the network with submit_multisig");
1584 }
1585 return true;
1586 }
1587
1588 bool simple_wallet::submit_multisig(const std::vector<std::string> &args)
1589 {
1590 CHECK_MULTISIG_ENABLED();
1591 submit_multisig_main(args, false);
1592 return true;
1593 }
1594
1595 bool simple_wallet::submit_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1596 {
1597 CHECK_MULTISIG_ENABLED();
1598 bool ready;
1599 uint32_t threshold;
1600 if (m_wallet->key_on_device())
1601 {
1602 fail_msg_writer() << tr("command not supported by HW wallet");
1603 return false;
1604 }
1605 if (!m_wallet->multisig(&ready, &threshold))
1606 {
1607 fail_msg_writer() << tr("This is not a multisig wallet");
1608 return false;
1609 }
1610 if (!ready)
1611 {
1612 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1613 return false;
1614 }
1615 if (args.size() != 1)
1616 {
1617 PRINT_USAGE(USAGE_SUBMIT_MULTISIG);
1618 return false;
1619 }
1620
1621 if (!try_connect_to_daemon())
1622 return false;
1623
1624 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1625
1626 std::string filename = args[0];
1627 try
1628 {
1629 tools::wallet2::multisig_tx_set txs;
1630 if (called_by_mms)
1631 {
1632 bool r = m_wallet->load_multisig_tx(args[0], txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1633 if (!r)
1634 {
1635 fail_msg_writer() << tr("Failed to load multisig transaction from MMS");
1636 return false;
1637 }
1638 }
1639 else
1640 {
1641 bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1642 if (!r)
1643 {
1644 fail_msg_writer() << tr("Failed to load multisig transaction from file");
1645 return false;
1646 }
1647 }
1648 if (txs.m_signers.size() < threshold)
1649 {
1650 fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
1651 % txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
1652 return false;
1653 }
1654
1655 // actually commit the transactions
1656 for (auto &ptx: txs.m_ptx)
1657 {
1658 m_wallet->commit_tx(ptx);
1659 success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << get_transaction_hash(ptx.tx) << ENDL
1660 << tr("You can check its status by using the `show_transfers` command.");
1661 }
1662 }
1663 catch (const std::exception &e)
1664 {
1665 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
1666 }
1667 catch (...)
1668 {
1669 LOG_ERROR("unknown error");
1670 fail_msg_writer() << tr("unknown error");
1671 return false;
1672 }
1673
1674 return true;
1675 }
1676
1677 bool simple_wallet::export_raw_multisig(const std::vector<std::string> &args)
1678 {
1679 CHECK_MULTISIG_ENABLED();
1680 bool ready;
1681 uint32_t threshold;
1682 if (m_wallet->key_on_device())
1683 {
1684 fail_msg_writer() << tr("command not supported by HW wallet");
1685 return true;
1686 }
1687 if (!m_wallet->multisig(&ready, &threshold))
1688 {
1689 fail_msg_writer() << tr("This is not a multisig wallet");
1690 return true;
1691 }
1692 if (!ready)
1693 {
1694 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1695 return true;
1696 }
1697 if (args.size() != 1)
1698 {
1699 PRINT_USAGE(USAGE_EXPORT_RAW_MULTISIG_TX);
1700 return true;
1701 }
1702
1703 std::string filename = args[0];
1704 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
1705 return true;
1706
1707 SCOPED_WALLET_UNLOCK();
1708
1709 try
1710 {
1711 tools::wallet2::multisig_tx_set txs;
1712 bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1713 if (!r)
1714 {
1715 fail_msg_writer() << tr("Failed to load multisig transaction from file");
1716 return true;
1717 }
1718 if (txs.m_signers.size() < threshold)
1719 {
1720 fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
1721 % txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
1722 return true;
1723 }
1724
1725 // save the transactions
1726 std::string filenames;
1727 for (auto &ptx: txs.m_ptx)
1728 {
1729 const crypto::hash txid = cryptonote::get_transaction_hash(ptx.tx);
1730 const std::string filename = std::string("raw_multisig_monero_tx_") + epee::string_tools::pod_to_hex(txid);
1731 if (!filenames.empty())
1732 filenames += ", ";
1733 filenames += filename;
1734 if (!m_wallet->save_to_file(filename, cryptonote::tx_to_blob(ptx.tx)))
1735 {
1736 fail_msg_writer() << tr("Failed to export multisig transaction to file ") << filename;
1737 return true;
1738 }
1739 }
1740 success_msg_writer() << tr("Saved exported multisig transaction file(s): ") << filenames;
1741 }
1742 catch (const std::exception& e)
1743 {
1744 LOG_ERROR("unexpected error: " << e.what());
1745 fail_msg_writer() << tr("unexpected error: ") << e.what();
1746 }
1747 catch (...)
1748 {
1749 LOG_ERROR("Unknown error");
1750 fail_msg_writer() << tr("unknown error");
1751 }
1752
1753 return true;
1754 }
1755
1756 bool simple_wallet::print_ring(const std::vector<std::string> &args)
1757 {
1758 crypto::key_image key_image;
1759 crypto::hash txid;
1760 if (args.size() != 1)
1761 {
1762 PRINT_USAGE(USAGE_PRINT_RING);
1763 return true;
1764 }
1765
1766 if (!epee::string_tools::hex_to_pod(args[0], key_image))
1767 {
1768 fail_msg_writer() << tr("Invalid key image");
1769 return true;
1770 }
1771 // this one will always work, they're all 32 byte hex
1772 if (!epee::string_tools::hex_to_pod(args[0], txid))
1773 {
1774 fail_msg_writer() << tr("Invalid txid");
1775 return true;
1776 }
1777
1778 std::vector<uint64_t> ring;
1779 std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings;
1780 try
1781 {
1782 if (m_wallet->get_ring(key_image, ring))
1783 rings.push_back({key_image, ring});
1784 else if (!m_wallet->get_rings(txid, rings))
1785 {
1786 fail_msg_writer() << tr("Key image either not spent, or spent with ring size 1");
1787 return true;
1788 }
1789
1790 for (const auto &ring: rings)
1791 {
1792 std::stringstream str;
1793 for (const auto &x: ring.second)
1794 str << x<< " ";
1795 // do NOT translate this "absolute" below, the lin can be used as input to set_ring
1796 success_msg_writer() << epee::string_tools::pod_to_hex(ring.first) << " absolute " << str.str();
1797 }
1798 }
1799 catch (const std::exception &e)
1800 {
1801 fail_msg_writer() << tr("Failed to get key image ring: ") << e.what();
1802 }
1803
1804 return true;
1805 }
1806
1807 bool simple_wallet::set_ring(const std::vector<std::string> &args)
1808 {
1809 crypto::key_image key_image;
1810
1811 // try filename first
1812 if (args.size() == 1)
1813 {
1814 if (!epee::file_io_utils::is_file_exist(args[0]))
1815 {
1816 fail_msg_writer() << tr("File doesn't exist");
1817 return true;
1818 }
1819
1820 char str[4096];
1821 std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
1822 if (f)
1823 {
1824 while (!feof(f.get()))
1825 {
1826 if (!fgets(str, sizeof(str), f.get()))
1827 break;
1828 const size_t len = strlen(str);
1829 if (len > 0 && str[len - 1] == '\n')
1830 str[len - 1] = 0;
1831 if (!str[0])
1832 continue;
1833 char key_image_str[65], type_str[9];
1834 int read_after_key_image = 0, read = 0;
1835 int fields = sscanf(str, "%64[abcdefABCDEF0123456789] %n%8s %n", key_image_str, &read_after_key_image, type_str, &read);
1836 if (fields != 2)
1837 {
1838 fail_msg_writer() << tr("Invalid ring specification: ") << str;
1839 continue;
1840 }
1841 key_image_str[64] = 0;
1842 type_str[8] = 0;
1843 crypto::key_image key_image;
1844 if (read_after_key_image == 0 || !epee::string_tools::hex_to_pod(key_image_str, key_image))
1845 {
1846 fail_msg_writer() << tr("Invalid key image: ") << str;
1847 continue;
1848 }
1849 if (read == read_after_key_image+8 || (strcmp(type_str, "absolute") && strcmp(type_str, "relative")))
1850 {
1851 fail_msg_writer() << tr("Invalid ring type, expected relative or abosolute: ") << str;
1852 continue;
1853 }
1854 bool relative = !strcmp(type_str, "relative");
1855 if (read < 0 || (size_t)read > strlen(str))
1856 {
1857 fail_msg_writer() << tr("Error reading line: ") << str;
1858 continue;
1859 }
1860 bool valid = true;
1861 std::vector<uint64_t> ring;
1862 const char *ptr = str + read;
1863 while (*ptr)
1864 {
1865 unsigned long offset;
1866 int elements = sscanf(ptr, "%lu %n", &offset, &read);
1867 if (elements == 0 || read <= 0 || (size_t)read > strlen(str))
1868 {
1869 fail_msg_writer() << tr("Error reading line: ") << str;
1870 valid = false;
1871 break;
1872 }
1873 ring.push_back(offset);
1874 ptr += read;
1875 }
1876 if (!valid)
1877 continue;
1878 if (ring.empty())
1879 {
1880 fail_msg_writer() << tr("Invalid ring: ") << str;
1881 continue;
1882 }
1883 if (relative)
1884 {
1885 for (size_t n = 1; n < ring.size(); ++n)
1886 {
1887 if (ring[n] <= 0)
1888 {
1889 fail_msg_writer() << tr("Invalid relative ring: ") << str;
1890 valid = false;
1891 break;
1892 }
1893 }
1894 }
1895 else
1896 {
1897 for (size_t n = 1; n < ring.size(); ++n)
1898 {
1899 if (ring[n] <= ring[n-1])
1900 {
1901 fail_msg_writer() << tr("Invalid absolute ring: ") << str;
1902 valid = false;
1903 break;
1904 }
1905 }
1906 }
1907 if (!valid)
1908 continue;
1909 if (!m_wallet->set_ring(key_image, ring, relative))
1910 fail_msg_writer() << tr("Failed to set ring for key image: ") << key_image << ". " << tr("Continuing.");
1911 }
1912 f.reset();
1913 }
1914 return true;
1915 }
1916
1917 if (args.size() < 3)
1918 {
1919 PRINT_USAGE(USAGE_SET_RING);
1920 return true;
1921 }
1922
1923 if (!epee::string_tools::hex_to_pod(args[0], key_image))
1924 {
1925 fail_msg_writer() << tr("Invalid key image");
1926 return true;
1927 }
1928
1929 bool relative;
1930 if (args[1] == "absolute")
1931 {
1932 relative = false;
1933 }
1934 else if (args[1] == "relative")
1935 {
1936 relative = true;
1937 }
1938 else
1939 {
1940 fail_msg_writer() << tr("Missing absolute or relative keyword");
1941 return true;
1942 }
1943
1944 std::vector<uint64_t> ring;
1945 for (size_t n = 2; n < args.size(); ++n)
1946 {
1947 ring.resize(ring.size() + 1);
1948 if (!string_tools::get_xtype_from_string(ring.back(), args[n]))
1949 {
1950 fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
1951 return true;
1952 }
1953 if (relative)
1954 {
1955 if (ring.size() > 1 && !ring.back())
1956 {
1957 fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
1958 return true;
1959 }
1960 uint64_t sum = 0;
1961 for (uint64_t out: ring)
1962 {
1963 if (out > std::numeric_limits<uint64_t>::max() - sum)
1964 {
1965 fail_msg_writer() << tr("invalid index: indices wrap");
1966 return true;
1967 }
1968 sum += out;
1969 }
1970 }
1971 else
1972 {
1973 if (ring.size() > 1 && ring[ring.size() - 2] >= ring[ring.size() - 1])
1974 {
1975 fail_msg_writer() << tr("invalid index: indices should be in strictly ascending order");
1976 return true;
1977 }
1978 }
1979 }
1980 if (!m_wallet->set_ring(key_image, ring, relative))
1981 {
1982 fail_msg_writer() << tr("failed to set ring");
1983 return true;
1984 }
1985
1986 return true;
1987 }
1988
1989 bool simple_wallet::unset_ring(const std::vector<std::string> &args)
1990 {
1991 crypto::hash txid;
1992 std::vector<crypto::key_image> key_images;
1993
1994 if (args.size() < 1)
1995 {
1996 PRINT_USAGE(USAGE_UNSET_RING);
1997 return true;
1998 }
1999
2000 key_images.resize(args.size());
2001 for (size_t i = 0; i < args.size(); ++i)
2002 {
2003 if (!epee::string_tools::hex_to_pod(args[i], key_images[i]))
2004 {
2005 fail_msg_writer() << tr("Invalid key image or txid");
2006 return true;
2007 }
2008 }
2009 static_assert(sizeof(crypto::hash) == sizeof(crypto::key_image), "hash and key_image must have the same size");
2010 memcpy(&txid, &key_images[0], sizeof(txid));
2011
2012 if (!m_wallet->unset_ring(key_images) && !m_wallet->unset_ring(txid))
2013 {
2014 fail_msg_writer() << tr("failed to unset ring");
2015 return true;
2016 }
2017
2018 return true;
2019 }
2020
2021 bool simple_wallet::rpc_payment_info(const std::vector<std::string> &args)
2022 {
2023 if (!try_connect_to_daemon())
2024 return true;
2025
2026 LOCK_IDLE_SCOPE();
2027
2028 try
2029 {
2030 bool payment_required;
2031 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
2032 uint32_t cookie;
2033 std::string hashing_blob;
2034 crypto::hash seed_hash, next_seed_hash;
2035 crypto::public_key pkey;
2036 crypto::secret_key_to_public_key(m_wallet->get_rpc_client_secret_key(), pkey);
2037 message_writer() << tr("RPC client ID: ") << pkey;
2038 message_writer() << tr("RPC client secret key: ") << crypto::secret_key_explicit_print_ref{m_wallet->get_rpc_client_secret_key()};
2039 if (!m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie))
2040 {
2041 fail_msg_writer() << tr("Failed to query daemon");
2042 return true;
2043 }
2044 if (payment_required)
2045 {
2046 uint64_t target = m_wallet->credits_target();
2047 if (target == 0)
2048 target = CREDITS_TARGET;
2049 message_writer() << tr("Using daemon: ") << m_wallet->get_daemon_address();
2050 message_writer() << tr("Payments required for node use, current credits: ") << credits;
2051 message_writer() << tr("Credits target: ") << target;
2052 uint64_t expected, discrepancy;
2053 m_wallet->credit_report(expected, discrepancy);
2054 message_writer() << tr("Credits spent this session: ") << expected;
2055 if (expected)
2056 message_writer() << tr("Credit discrepancy this session: ") << discrepancy << " (" << 100.0f * discrepancy / expected << "%)";
2057 float cph = credits_per_hash_found / (float)diff;
2058 message_writer() << tr("Difficulty: ") << diff << ", " << credits_per_hash_found << " " << tr("credits per hash found, ") << cph << " " << tr("credits/hash");
2059 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
2060 bool mining = (now - m_last_rpc_payment_mining_time).total_microseconds() < 1000000;
2061 if (mining)
2062 {
2063 float hash_rate = m_rpc_payment_hash_rate;
2064 if (hash_rate > 0)
2065 {
2066 message_writer() << (boost::format(tr("Mining for payment at %.1f H/s")) % hash_rate).str();
2067 if (credits < target)
2068 {
2069 std::chrono::seconds seconds((unsigned)((target - credits) / cph / hash_rate));
2070 std::string target_string = get_human_readable_timespan(seconds);
2071 message_writer() << (boost::format(tr("Estimated time till %u credits target mined: %s")) % target % target_string).str();
2072 }
2073 }
2074 else
2075 message_writer() << tr("Mining for payment");
2076 }
2077 else
2078 message_writer() << tr("Not mining");
2079 }
2080 else
2081 message_writer() << tr("No payment needed for node use");
2082 }
2083 catch (const std::exception& e)
2084 {
2085 LOG_ERROR("unexpected error: " << e.what());
2086 fail_msg_writer() << tr("unexpected error: ") << e.what();
2087 }
2088
2089 return true;
2090 }
2091
2092 bool simple_wallet::blackball(const std::vector<std::string> &args)
2093 {
2094 uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets;
2095 if (args.size() == 0)
2096 {
2097 PRINT_USAGE(USAGE_MARK_OUTPUT_SPENT);
2098 return true;
2099 }
2100
2101 try
2102 {
2103 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &amount, &offset) == 2)
2104 {
2105 m_wallet->blackball_output(std::make_pair(amount, offset));
2106 }
2107 else if (epee::file_io_utils::is_file_exist(args[0]))
2108 {
2109 std::vector<std::pair<uint64_t, uint64_t>> outputs;
2110 char str[256];
2111
2112 std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
2113 if (f)
2114 {
2115 while (!feof(f.get()))
2116 {
2117 if (!fgets(str, sizeof(str), f.get()))
2118 break;
2119 const size_t len = strlen(str);
2120 if (len > 0 && str[len - 1] == '\n')
2121 str[len - 1] = 0;
2122 if (!str[0])
2123 continue;
2124 if (sscanf(str, "@%" PRIu64, &amount) == 1)
2125 {
2126 continue;
2127 }
2128 if (amount == std::numeric_limits<uint64_t>::max())
2129 {
2130 fail_msg_writer() << tr("First line is not an amount");
2131 return true;
2132 }
2133 if (sscanf(str, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset)
2134 {
2135 while (num_offsets--)
2136 outputs.push_back(std::make_pair(amount, offset++));
2137 }
2138 else if (sscanf(str, "%" PRIu64, &offset) == 1)
2139 {
2140 outputs.push_back(std::make_pair(amount, offset));
2141 }
2142 else
2143 {
2144 fail_msg_writer() << tr("Invalid output: ") << str;
2145 return true;
2146 }
2147 }
2148 f.reset();
2149 bool add = false;
2150 if (args.size() > 1)
2151 {
2152 if (args[1] != "add")
2153 {
2154 fail_msg_writer() << tr("Bad argument: ") + args[1] + ": " + tr("should be \"add\"");
2155 return true;
2156 }
2157 add = true;
2158 }
2159 m_wallet->set_blackballed_outputs(outputs, add);
2160 }
2161 else
2162 {
2163 fail_msg_writer() << tr("Failed to open file");
2164 return true;
2165 }
2166 }
2167 else
2168 {
2169 fail_msg_writer() << tr("Invalid output key, and file doesn't exist");
2170 return true;
2171 }
2172 }
2173 catch (const std::exception &e)
2174 {
2175 fail_msg_writer() << tr("Failed to mark output spent: ") << e.what();
2176 }
2177
2178 return true;
2179 }
2180
2181 bool simple_wallet::unblackball(const std::vector<std::string> &args)
2182 {
2183 std::pair<uint64_t, uint64_t> output;
2184 if (args.size() != 1)
2185 {
2186 PRINT_USAGE(USAGE_MARK_OUTPUT_UNSPENT);
2187 return true;
2188 }
2189
2190 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
2191 {
2192 fail_msg_writer() << tr("Invalid output");
2193 return true;
2194 }
2195
2196 try
2197 {
2198 m_wallet->unblackball_output(output);
2199 }
2200 catch (const std::exception &e)
2201 {
2202 fail_msg_writer() << tr("Failed to mark output unspent: ") << e.what();
2203 }
2204
2205 return true;
2206 }
2207
2208 bool simple_wallet::blackballed(const std::vector<std::string> &args)
2209 {
2210 std::pair<uint64_t, uint64_t> output;
2211 if (args.size() != 1)
2212 {
2213 PRINT_USAGE(USAGE_IS_OUTPUT_SPENT);
2214 return true;
2215 }
2216
2217 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
2218 {
2219 fail_msg_writer() << tr("Invalid output");
2220 return true;
2221 }
2222
2223 try
2224 {
2225 if (m_wallet->is_output_blackballed(output))
2226 message_writer() << tr("Spent: ") << output.first << "/" << output.second;
2227 else
2228 message_writer() << tr("Not spent: ") << output.first << "/" << output.second;
2229 }
2230 catch (const std::exception &e)
2231 {
2232 fail_msg_writer() << tr("Failed to check whether output is spent: ") << e.what();
2233 }
2234
2235 return true;
2236 }
2237
2238 bool simple_wallet::save_known_rings(const std::vector<std::string> &args)
2239 {
2240 try
2241 {
2242 LOCK_IDLE_SCOPE();
2243 m_wallet->find_and_save_rings();
2244 }
2245 catch (const std::exception &e)
2246 {
2247 fail_msg_writer() << tr("Failed to save known rings: ") << e.what();
2248 }
2249 return true;
2250 }
2251
2252 bool simple_wallet::freeze_thaw(const std::vector<std::string> &args, bool freeze)
2253 {
2254 CHECK_IF_BACKGROUND_SYNCING("cannot freeze/thaw");
2255 if (args.empty())
2256 {
2257 fail_msg_writer() << boost::format(tr("usage: %s <key_image>|<pubkey>")) % (freeze ? "freeze" : "thaw");
2258 return true;
2259 }
2260 crypto::key_image ki;
2261 if (!epee::string_tools::hex_to_pod(args[0], ki))
2262 {
2263 fail_msg_writer() << tr("failed to parse key image");
2264 return true;
2265 }
2266 try
2267 {
2268 if (freeze)
2269 m_wallet->freeze(ki);
2270 else
2271 m_wallet->thaw(ki);
2272 }
2273 catch (const std::exception &e)
2274 {
2275 fail_msg_writer() << e.what();
2276 return true;
2277 }
2278
2279 return true;
2280 }
2281
2282 bool simple_wallet::freeze(const std::vector<std::string> &args)
2283 {
2284 return freeze_thaw(args, true);
2285 }
2286
2287 bool simple_wallet::thaw(const std::vector<std::string> &args)
2288 {
2289 return freeze_thaw(args, false);
2290 }
2291
2292 bool simple_wallet::frozen(const std::vector<std::string> &args)
2293 {
2294 CHECK_IF_BACKGROUND_SYNCING("cannot see frozen key images");
2295 if (args.empty())
2296 {
2297 size_t ntd = m_wallet->get_num_transfer_details();
2298 for (size_t i = 0; i < ntd; ++i)
2299 {
2300 if (!m_wallet->frozen(i))
2301 continue;
2302 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
2303 message_writer() << tr("Frozen: ") << td.m_key_image << " " << cryptonote::print_money(td.amount());
2304 }
2305 }
2306 else
2307 {
2308 crypto::key_image ki;
2309 if (!epee::string_tools::hex_to_pod(args[0], ki))
2310 {
2311 fail_msg_writer() << tr("failed to parse key image");
2312 return true;
2313 }
2314 if (m_wallet->frozen(ki))
2315 message_writer() << tr("Frozen: ") << ki;
2316 else
2317 message_writer() << tr("Not frozen: ") << ki;
2318 }
2319 return true;
2320 }
2321
2322 bool simple_wallet::lock(const std::vector<std::string> &args)
2323 {
2324 m_locked = true;
2325 check_for_inactivity_lock(true);
2326 return true;
2327 }
2328
2329 bool simple_wallet::net_stats(const std::vector<std::string> &args)
2330 {
2331 message_writer() << std::to_string(m_wallet->get_bytes_sent()) + tr(" bytes sent");
2332 message_writer() << std::to_string(m_wallet->get_bytes_received()) + tr(" bytes received");
2333 return true;
2334 }
2335
2336 bool simple_wallet::public_nodes(const std::vector<std::string> &args)
2337 {
2338 try
2339 {
2340 auto nodes = m_wallet->get_public_nodes(false);
2341 m_claimed_cph.clear();
2342 if (nodes.empty())
2343 {
2344 fail_msg_writer() << tr("No known public nodes");
2345 return true;
2346 }
2347 std::sort(nodes.begin(), nodes.end(), [](const public_node &node0, const public_node &node1) {
2348 if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash == 0)
2349 return true;
2350 if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash)
2351 return node0.rpc_credits_per_hash < node1.rpc_credits_per_hash;
2352 return false;
2353 });
2354
2355 const uint64_t now = time(NULL);
2356 message_writer() << boost::format("%32s %12s %16s") % tr("address") % tr("credits/hash") % tr("last_seen");
2357 for (const auto &node: nodes)
2358 {
2359 const float cph = node.rpc_credits_per_hash / RPC_CREDITS_PER_HASH_SCALE;
2360 char cphs[9];
2361 snprintf(cphs, sizeof(cphs), "%.3f", cph);
2362 const std::string last_seen = node.last_seen == 0 ? tr("never") : get_human_readable_timespan(std::chrono::seconds(now - node.last_seen));
2363 std::string host = node.host + ":" + std::to_string(node.rpc_port);
2364 message_writer() << boost::format("%32s %12s %16s") % host % cphs % last_seen;
2365 m_claimed_cph[host] = node.rpc_credits_per_hash;
2366 }
2367 }
2368 catch (const std::exception &e)
2369 {
2370 fail_msg_writer() << tr("Error retrieving public node list: ") << e.what();
2371 }
2372 message_writer(console_color_red, true) << tr("Most of these nodes are probably spies. You should not use them unless connecting via Tor or I2P");
2373 return true;
2374 }
2375
2376 bool simple_wallet::welcome(const std::vector<std::string> &args)
2377 {
2378 message_writer() << tr("Welcome to Monero, the private cryptocurrency.");
2379 message_writer() << "";
2380 message_writer() << tr("Monero, like Bitcoin, is a cryptocurrency. That is, it is digital money.");
2381 message_writer() << tr("Unlike Bitcoin, your Monero transactions and balance stay private and are not visible to the world by default.");
2382 message_writer() << tr("However, you have the option of making those available to select parties if you choose to.");
2383 message_writer() << "";
2384 message_writer() << tr("Monero protects your privacy on the blockchain, and while Monero strives to improve all the time,");
2385 message_writer() << tr("no privacy technology can be 100% perfect, Monero included.");
2386 message_writer() << tr("Monero cannot protect you from malware, and it may not be as effective as we hope against powerful adversaries.");
2387 message_writer() << tr("Flaws in Monero may be discovered in the future, and attacks may be developed to peek under some");
2388 message_writer() << tr("of the layers of privacy Monero provides. Be safe and practice defense in depth.");
2389 message_writer() << "";
2390 message_writer() << tr("Welcome to Monero and financial privacy. For more information see https://GetMonero.org");
2391 return true;
2392 }
2393
2394 bool simple_wallet::version(const std::vector<std::string> &args)
2395 {
2396 message_writer() << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")";
2397 return true;
2398 }
2399
2400 bool simple_wallet::on_unknown_command(const std::vector<std::string> &args)
2401 {
2402 if (args[0] == "exit" || args[0] == "q") // backward compat
2403 return false;
2404 fail_msg_writer() << boost::format(tr("Unknown command '%s', try 'help'")) % args.front();
2405 return true;
2406 }
2407
2408 bool simple_wallet::on_empty_command()
2409 {
2410 return true;
2411 }
2412
2413 bool simple_wallet::on_cancelled_command()
2414 {
2415 check_for_inactivity_lock(false);
2416 return true;
2417 }
2418
2419 bool simple_wallet::cold_sign_tx(const std::vector<tools::wallet2::pending_tx>& ptx_vector, tools::wallet2::signed_tx_set &exported_txs, std::vector<cryptonote::address_parse_info> &dsts_info, std::function<bool(const tools::wallet2::signed_tx_set &)> accept_func)
2420 {
2421 std::vector<std::string> tx_aux;
2422
2423 message_writer(console_color_white, false) << tr("Please confirm the transaction on the device");
2424
2425 m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux);
2426
2427 if (accept_func && !accept_func(exported_txs))
2428 {
2429 MERROR("Transactions rejected by callback");
2430 return false;
2431 }
2432
2433 // aux info
2434 m_wallet->cold_tx_aux_import(exported_txs.ptx, tx_aux);
2435
2436 // import key images
2437 return m_wallet->import_key_images(exported_txs, 0, true);
2438 }
2439
2440 bool simple_wallet::start_mining_for_rpc(const std::vector<std::string> &args)
2441 {
2442 if (!try_connect_to_daemon())
2443 return true;
2444
2445 bool ok = true;
2446 if(args.size() >= 1)
2447 {
2448 uint16_t num = 0;
2449 ok = string_tools::get_xtype_from_string(num, args[0]);
2450 m_rpc_payment_threads = num;
2451 }
2452 else
2453 {
2454 m_rpc_payment_threads = 0;
2455 }
2456
2457 if (!ok)
2458 {
2459 PRINT_USAGE(USAGE_START_MINING_FOR_RPC);
2460 return true;
2461 }
2462
2463 LOCK_IDLE_SCOPE();
2464
2465 bool payment_required;
2466 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
2467 uint32_t cookie;
2468 std::string hashing_blob;
2469 crypto::hash seed_hash, next_seed_hash;
2470 if (!m_wallet->get_rpc_payment_info(true, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie))
2471 {
2472 fail_msg_writer() << tr("Failed to query daemon");
2473 return true;
2474 }
2475 if (!payment_required)
2476 {
2477 fail_msg_writer() << tr("Daemon does not require payment for RPC access");
2478 return true;
2479 }
2480
2481 m_rpc_payment_mining_requested = true;
2482 m_rpc_payment_checker.trigger();
2483 const float cph = credits_per_hash_found / (float)diff;
2484 bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
2485 success_msg_writer() << (boost::format(tr("Starting mining for RPC access: diff %llu, %f credits/hash%s")) % diff % cph % (low ? " - this is low" : "")).str();
2486 success_msg_writer() << tr("Run stop_mining_for_rpc to stop");
2487 return true;
2488 }
2489
2490 bool simple_wallet::stop_mining_for_rpc(const std::vector<std::string> &args)
2491 {
2492 if (!try_connect_to_daemon())
2493 return true;
2494
2495 LOCK_IDLE_SCOPE();
2496 m_rpc_payment_mining_requested = false;
2497 m_last_rpc_payment_mining_time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1));
2498 m_rpc_payment_hash_rate = -1.0f;
2499 return true;
2500 }
2501
2502 bool simple_wallet::show_qr_code(const std::vector<std::string> &args)
2503 {
2504 uint32_t subaddress_index = 0;
2505 if (args.size() >= 1)
2506 {
2507 if (!string_tools::get_xtype_from_string(subaddress_index, args[0]))
2508 {
2509 fail_msg_writer() << tr("invalid index: must be an unsigned integer");
2510 return true;
2511 }
2512 if (subaddress_index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
2513 {
2514 fail_msg_writer() << tr("<subaddress_index> is out of bounds");
2515 return true;
2516 }
2517 }
2518
2519 #ifdef _WIN32
2520 #define PRINT_UTF8(pre, x) std::wcout << pre ## x
2521 #define WTEXTON() _setmode(_fileno(stdout), _O_WTEXT)
2522 #define WTEXTOFF() _setmode(_fileno(stdout), _O_TEXT)
2523 #else
2524 #define PRINT_UTF8(pre, x) std::cout << x
2525 #define WTEXTON()
2526 #define WTEXTOFF()
2527 #endif
2528
2529 WTEXTON();
2530 try
2531 {
2532 const std::string address = "monero:" + m_wallet->get_subaddress_as_str({m_current_subaddress_account, subaddress_index});
2533 const qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText(address.c_str(), qrcodegen::QrCode::Ecc::LOW);
2534 for (int y = -2; y < qr.getSize() + 2; y+=2)
2535 {
2536 for (int x = -2; x < qr.getSize() + 2; x++)
2537 {
2538 if (qr.getModule(x, y) && qr.getModule(x, y + 1))
2539 PRINT_UTF8(L, "\u2588");
2540 else if (qr.getModule(x, y) && !qr.getModule(x, y + 1))
2541 PRINT_UTF8(L, "\u2580");
2542 else if (!qr.getModule(x, y) && qr.getModule(x, y + 1))
2543 PRINT_UTF8(L, "\u2584");
2544 else
2545 PRINT_UTF8(L, " ");
2546 }
2547 PRINT_UTF8(, std::endl);
2548 }
2549 }
2550 catch (const std::length_error&)
2551 {
2552 fail_msg_writer() << tr("Failed to generate QR code, input too large");
2553 }
2554 WTEXTOFF();
2555 return true;
2556 }
2557
2558 bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2559 {
2560 const auto pwd_container = get_and_verify_password();
2561 if (pwd_container)
2562 {
2563 parse_bool_and_use(args[1], [&](bool r) {
2564 m_wallet->always_confirm_transfers(r);
2565 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2566 });
2567 }
2568 return true;
2569 }
2570
2571 bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2572 {
2573 const auto pwd_container = get_and_verify_password();
2574 if (pwd_container)
2575 {
2576 parse_bool_and_use(args[1], [&](bool r) {
2577 m_wallet->print_ring_members(r);
2578 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2579 });
2580 }
2581 return true;
2582 }
2583
2584 bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2585 {
2586 if (m_wallet->watch_only())
2587 {
2588 fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
2589 return true;
2590 }
2591
2592 const auto pwd_container = get_and_verify_password();
2593 if (pwd_container)
2594 {
2595 parse_bool_and_use(args[1], [&](bool r) {
2596 m_wallet->store_tx_info(r);
2597 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2598 });
2599 }
2600 return true;
2601 }
2602
2603 bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2604 {
2605 uint32_t priority = 0;
2606 try
2607 {
2608 if (strchr(args[1].c_str(), '-'))
2609 {
2610 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2611 return true;
2612 }
2613 if (args[1] == "0")
2614 {
2615 priority = 0;
2616 }
2617 else
2618 {
2619 bool found = false;
2620 for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
2621 {
2622 if (allowed_priority_strings[n] == args[1])
2623 {
2624 found = true;
2625 priority = n;
2626 }
2627 }
2628 if (!found)
2629 {
2630 priority = boost::lexical_cast<int>(args[1]);
2631 if (priority < 1 || priority > 4)
2632 {
2633 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2634 return true;
2635 }
2636 }
2637 }
2638
2639 const auto pwd_container = get_and_verify_password();
2640 if (pwd_container)
2641 {
2642 m_wallet->set_default_priority(priority);
2643 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2644 }
2645 return true;
2646 }
2647 catch(const boost::bad_lexical_cast &)
2648 {
2649 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2650 return true;
2651 }
2652 catch(...)
2653 {
2654 fail_msg_writer() << tr("could not change default priority");
2655 return true;
2656 }
2657 }
2658
2659 bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2660 {
2661 const auto pwd_container = get_and_verify_password();
2662 if (pwd_container)
2663 {
2664 parse_bool_and_use(args[1], [&](bool auto_refresh) {
2665 m_auto_refresh_enabled.store(false, std::memory_order_relaxed);
2666 m_wallet->auto_refresh(auto_refresh);
2667 m_idle_mutex.lock();
2668 m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed);
2669 m_idle_cond.notify_one();
2670 m_idle_mutex.unlock();
2671
2672 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2673 });
2674 }
2675 return true;
2676 }
2677
2678 bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2679 {
2680 tools::wallet2::RefreshType refresh_type;
2681 if (!parse_refresh_type(args[1], refresh_type))
2682 {
2683 return true;
2684 }
2685
2686 const auto pwd_container = get_and_verify_password();
2687 if (pwd_container)
2688 {
2689 m_wallet->set_refresh_type(refresh_type);
2690 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2691 }
2692 return true;
2693 }
2694
2695 bool simple_wallet::set_ask_password(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2696 {
2697 const auto pwd_container = get_and_verify_password();
2698 if (pwd_container)
2699 {
2700 tools::wallet2::AskPasswordType ask = tools::wallet2::AskPasswordToDecrypt;
2701 if (args[1] == "never" || args[1] == "0")
2702 ask = tools::wallet2::AskPasswordNever;
2703 else if (args[1] == "action" || args[1] == "1")
2704 ask = tools::wallet2::AskPasswordOnAction;
2705 else if (args[1] == "encrypt" || args[1] == "decrypt" || args[1] == "2")
2706 ask = tools::wallet2::AskPasswordToDecrypt;
2707 else
2708 {
2709 fail_msg_writer() << tr("invalid argument: must be either 0/never, 1/action, or 2/encrypt/decrypt");
2710 return true;
2711 }
2712
2713 const tools::wallet2::AskPasswordType cur_ask = m_wallet->ask_password();
2714 if (!m_wallet->watch_only())
2715 {
2716 if (cur_ask == tools::wallet2::AskPasswordToDecrypt && ask != tools::wallet2::AskPasswordToDecrypt)
2717 m_wallet->decrypt_keys(pwd_container->password());
2718 else if (cur_ask != tools::wallet2::AskPasswordToDecrypt && ask == tools::wallet2::AskPasswordToDecrypt)
2719 m_wallet->encrypt_keys(pwd_container->password());
2720 }
2721 m_wallet->ask_password(ask);
2722 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2723 }
2724 return true;
2725 }
2726
2727 bool simple_wallet::set_unit(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2728 {
2729 const std::string &unit = args[1];
2730 unsigned int decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
2731
2732 if (unit == "monero")
2733 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
2734 else if (unit == "millinero")
2735 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 3;
2736 else if (unit == "micronero")
2737 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 6;
2738 else if (unit == "nanonero")
2739 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 9;
2740 else if (unit == "piconero")
2741 decimal_point = 0;
2742 else
2743 {
2744 fail_msg_writer() << tr("invalid unit");
2745 return true;
2746 }
2747
2748 const auto pwd_container = get_and_verify_password();
2749 if (pwd_container)
2750 {
2751 cryptonote::set_default_decimal_point(decimal_point);
2752 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2753 }
2754 return true;
2755 }
2756
2757 bool simple_wallet::set_max_reorg_depth(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2758 {
2759 uint64_t depth;
2760 if (!epee::string_tools::get_xtype_from_string(depth, args[1]))
2761 {
2762 fail_msg_writer() << tr("invalid value");
2763 return true;
2764 }
2765
2766 const auto pwd_container = get_and_verify_password();
2767 if (pwd_container)
2768 {
2769 m_wallet->max_reorg_depth(depth);
2770 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2771 }
2772 return true;
2773 }
2774
2775 bool simple_wallet::set_min_output_count(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2776 {
2777 uint32_t count;
2778 if (!string_tools::get_xtype_from_string(count, args[1]))
2779 {
2780 fail_msg_writer() << tr("invalid count: must be an unsigned integer");
2781 return true;
2782 }
2783
2784 const auto pwd_container = get_and_verify_password();
2785 if (pwd_container)
2786 {
2787 m_wallet->set_min_output_count(count);
2788 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2789 }
2790 return true;
2791 }
2792
2793 bool simple_wallet::set_min_output_value(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2794 {
2795 uint64_t value;
2796 if (!cryptonote::parse_amount(value, args[1]))
2797 {
2798 fail_msg_writer() << tr("invalid value");
2799 return true;
2800 }
2801
2802 const auto pwd_container = get_and_verify_password();
2803 if (pwd_container)
2804 {
2805 m_wallet->set_min_output_value(value);
2806 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2807 }
2808 return true;
2809 }
2810
2811 bool simple_wallet::set_merge_destinations(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2812 {
2813 const auto pwd_container = get_and_verify_password();
2814 if (pwd_container)
2815 {
2816 parse_bool_and_use(args[1], [&](bool r) {
2817 m_wallet->merge_destinations(r);
2818 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2819 });
2820 }
2821 return true;
2822 }
2823
2824 bool simple_wallet::set_confirm_backlog(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2825 {
2826 const auto pwd_container = get_and_verify_password();
2827 if (pwd_container)
2828 {
2829 parse_bool_and_use(args[1], [&](bool r) {
2830 m_wallet->confirm_backlog(r);
2831 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2832 });
2833 }
2834 return true;
2835 }
2836
2837 bool simple_wallet::set_confirm_backlog_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2838 {
2839 uint32_t threshold;
2840 if (!string_tools::get_xtype_from_string(threshold, args[1]))
2841 {
2842 fail_msg_writer() << tr("invalid count: must be an unsigned integer");
2843 return true;
2844 }
2845
2846 const auto pwd_container = get_and_verify_password();
2847 if (pwd_container)
2848 {
2849 m_wallet->set_confirm_backlog_threshold(threshold);
2850 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2851 }
2852 return true;
2853 }
2854
2855 bool simple_wallet::set_confirm_export_overwrite(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2856 {
2857 const auto pwd_container = get_and_verify_password();
2858 if (pwd_container)
2859 {
2860 parse_bool_and_use(args[1], [&](bool r) {
2861 m_wallet->confirm_export_overwrite(r);
2862 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2863 });
2864 }
2865 return true;
2866 }
2867
2868 bool simple_wallet::set_refresh_from_block_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2869 {
2870 const auto pwd_container = get_and_verify_password();
2871 if (pwd_container)
2872 {
2873 uint64_t height;
2874 if (!epee::string_tools::get_xtype_from_string(height, args[1]))
2875 {
2876 fail_msg_writer() << tr("Invalid height");
2877 return true;
2878 }
2879 m_wallet->set_refresh_from_block_height(height);
2880 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2881 }
2882 return true;
2883 }
2884
2885 bool simple_wallet::set_auto_low_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2886 {
2887 const auto pwd_container = get_and_verify_password();
2888 if (pwd_container)
2889 {
2890 parse_bool_and_use(args[1], [&](bool r) {
2891 m_wallet->auto_low_priority(r);
2892 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2893 });
2894 }
2895 return true;
2896 }
2897
2898 bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2899 {
2900 const auto pwd_container = get_and_verify_password();
2901 if (pwd_container)
2902 {
2903 parse_bool_and_use(args[1], [&](bool r) {
2904 m_wallet->segregate_pre_fork_outputs(r);
2905 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2906 });
2907 }
2908 return true;
2909 }
2910
2911 bool simple_wallet::set_persistent_rpc_client_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2912 {
2913 const auto pwd_container = get_and_verify_password();
2914 if (pwd_container)
2915 {
2916 parse_bool_and_use(args[1], [&](bool r) {
2917 m_wallet->persistent_rpc_client_id(r);
2918 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2919 });
2920 }
2921 return true;
2922 }
2923
2924 bool simple_wallet::set_auto_mine_for_rpc_payment_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2925 {
2926 const auto pwd_container = get_and_verify_password();
2927 if (pwd_container)
2928 {
2929 float threshold;
2930 if (!epee::string_tools::get_xtype_from_string(threshold, args[1]) || threshold < 0.0f)
2931 {
2932 fail_msg_writer() << tr("Invalid threshold");
2933 return true;
2934 }
2935 m_wallet->auto_mine_for_rpc_payment_threshold(threshold);
2936 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2937 }
2938 return true;
2939 }
2940
2941 bool simple_wallet::set_credits_target(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2942 {
2943 const auto pwd_container = get_and_verify_password();
2944 if (pwd_container)
2945 {
2946 uint64_t target;
2947 if (!epee::string_tools::get_xtype_from_string(target, args[1]))
2948 {
2949 fail_msg_writer() << tr("Invalid target");
2950 return true;
2951 }
2952 m_wallet->credits_target(target);
2953 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2954 }
2955 return true;
2956 }
2957
2958 bool simple_wallet::set_key_reuse_mitigation2(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2959 {
2960 const auto pwd_container = get_and_verify_password();
2961 if (pwd_container)
2962 {
2963 parse_bool_and_use(args[1], [&](bool r) {
2964 m_wallet->key_reuse_mitigation2(r);
2965 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2966 });
2967 }
2968 return true;
2969 }
2970
2971 bool simple_wallet::set_subaddress_lookahead(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2972 {
2973 const auto pwd_container = get_and_verify_password();
2974 if (pwd_container)
2975 {
2976 auto lookahead = parse_subaddress_lookahead(args[1]);
2977 if (lookahead)
2978 {
2979 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
2980 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2981 }
2982 }
2983 return true;
2984 }
2985
2986 bool simple_wallet::set_segregation_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2987 {
2988 const auto pwd_container = get_and_verify_password();
2989 if (pwd_container)
2990 {
2991 uint64_t height;
2992 if (!epee::string_tools::get_xtype_from_string(height, args[1]))
2993 {
2994 fail_msg_writer() << tr("Invalid height");
2995 return true;
2996 }
2997 m_wallet->segregation_height(height);
2998 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2999 }
3000 return true;
3001 }
3002
3003 bool simple_wallet::set_ignore_fractional_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3004 {
3005 const auto pwd_container = get_and_verify_password();
3006 if (pwd_container)
3007 {
3008 parse_bool_and_use(args[1], [&](bool r) {
3009 m_wallet->ignore_fractional_outputs(r);
3010 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3011 });
3012 }
3013 return true;
3014 }
3015
3016
3017 bool simple_wallet::set_ignore_outputs_above(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3018 {
3019 const auto pwd_container = get_and_verify_password();
3020 if (pwd_container)
3021 {
3022 uint64_t amount;
3023 if (!cryptonote::parse_amount(amount, args[1]))
3024 {
3025 fail_msg_writer() << tr("Invalid amount");
3026 return true;
3027 }
3028 if (amount == 0)
3029 amount = MONEY_SUPPLY;
3030 m_wallet->ignore_outputs_above(amount);
3031 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3032 }
3033 return true;
3034 }
3035
3036 bool simple_wallet::set_ignore_outputs_below(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3037 {
3038 const auto pwd_container = get_and_verify_password();
3039 if (pwd_container)
3040 {
3041 uint64_t amount;
3042 if (!cryptonote::parse_amount(amount, args[1]))
3043 {
3044 fail_msg_writer() << tr("Invalid amount");
3045 return true;
3046 }
3047 m_wallet->ignore_outputs_below(amount);
3048 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3049 }
3050 return true;
3051 }
3052
3053 bool simple_wallet::set_track_uses(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3054 {
3055 const auto pwd_container = get_and_verify_password();
3056 if (pwd_container)
3057 {
3058 parse_bool_and_use(args[1], [&](bool r) {
3059 m_wallet->track_uses(r);
3060 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3061 });
3062 }
3063 return true;
3064 }
3065
3066 bool simple_wallet::setup_background_sync(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3067 {
3068 if (m_wallet->multisig())
3069 {
3070 fail_msg_writer() << tr("background sync not implemented for multisig wallet");
3071 return true;
3072 }
3073 if (m_wallet->watch_only())
3074 {
3075 fail_msg_writer() << tr("background sync not implemented for watch only wallet");
3076 return true;
3077 }
3078 if (m_wallet->key_on_device())
3079 {
3080 fail_msg_writer() << tr("command not supported by HW wallet");
3081 return true;
3082 }
3083
3084 tools::wallet2::BackgroundSyncType background_sync_type;
3085 if (!parse_background_sync_type(args[1], background_sync_type))
3086 {
3087 fail_msg_writer() << tr("invalid option");
3088 return true;
3089 }
3090
3091 const auto pwd_container = get_and_verify_password();
3092 if (!pwd_container)
3093 return true;
3094
3095 try
3096 {
3097 boost::optional<epee::wipeable_string> background_cache_password = boost::none;
3098 if (background_sync_type == tools::wallet2::BackgroundSyncCustomPassword)
3099 {
3100 const auto background_pwd_container = background_sync_cache_password_prompter(true);
3101 if (!background_pwd_container)
3102 return true;
3103 background_cache_password = background_pwd_container->password();
3104 }
3105
3106 LOCK_IDLE_SCOPE();
3107 m_wallet->setup_background_sync(background_sync_type, pwd_container->password(), background_cache_password);
3108 }
3109 catch (const std::exception &e)
3110 {
3111 fail_msg_writer() << tr("Error setting background sync type: ") << e.what();
3112 }
3113
3114 return true;
3115 }
3116
3117 bool simple_wallet::set_show_wallet_name_when_locked(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3118 {
3119 const auto pwd_container = get_and_verify_password();
3120 if (pwd_container)
3121 {
3122 parse_bool_and_use(args[1], [&](bool r) {
3123 m_wallet->show_wallet_name_when_locked(r);
3124 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3125 });
3126 }
3127 return true;
3128 }
3129
3130 bool simple_wallet::set_inactivity_lock_timeout(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3131 {
3132 #ifdef _WIN32
3133 tools::fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows");
3134 return true;
3135 #endif
3136 const auto pwd_container = get_and_verify_password();
3137 if (pwd_container)
3138 {
3139 uint32_t r;
3140 if (epee::string_tools::get_xtype_from_string(r, args[1]))
3141 {
3142 m_wallet->inactivity_lock_timeout(r);
3143 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3144 }
3145 else
3146 {
3147 tools::fail_msg_writer() << tr("Invalid number of seconds");
3148 }
3149 }
3150 return true;
3151 }
3152
3153 bool simple_wallet::set_setup_background_mining(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3154 {
3155 const auto pwd_container = get_and_verify_password();
3156 if (pwd_container)
3157 {
3158 tools::wallet2::BackgroundMiningSetupType setup = tools::wallet2::BackgroundMiningMaybe;
3159 if (args[1] == "yes" || args[1] == "1")
3160 setup = tools::wallet2::BackgroundMiningYes;
3161 else if (args[1] == "no" || args[1] == "0")
3162 setup = tools::wallet2::BackgroundMiningNo;
3163 else
3164 {
3165 fail_msg_writer() << tr("invalid argument: must be either 1/yes or 0/no");
3166 return true;
3167 }
3168 m_wallet->setup_background_mining(setup);
3169 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3170 if (setup == tools::wallet2::BackgroundMiningYes)
3171 start_background_mining();
3172 else
3173 stop_background_mining();
3174 }
3175 return true;
3176 }
3177
3178 bool simple_wallet::set_device_name(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3179 {
3180 const auto pwd_container = get_and_verify_password();
3181 if (pwd_container)
3182 {
3183 if (args.size() == 0){
3184 fail_msg_writer() << tr("Device name not specified");
3185 return true;
3186 }
3187
3188 m_wallet->device_name(args[1]);
3189 bool r = false;
3190 try {
3191 r = m_wallet->reconnect_device();
3192 if (!r){
3193 fail_msg_writer() << tr("Device reconnect failed");
3194 }
3195
3196 } catch(const std::exception & e){
3197 MWARNING("Device reconnect failed: " << e.what());
3198 fail_msg_writer() << tr("Device reconnect failed: ") << e.what();
3199 }
3200
3201 }
3202 return true;
3203 }
3204
3205 bool simple_wallet::set_export_format(const std::vector<std::string> &args/* = std::vector<std::string()*/)
3206 {
3207 if (args.size() < 2)
3208 {
3209 fail_msg_writer() << tr("Export format not specified");
3210 return true;
3211 }
3212
3213 if (boost::algorithm::iequals(args[1], "ascii"))
3214 {
3215 m_wallet->set_export_format(tools::wallet2::ExportFormat::Ascii);
3216 }
3217 else if (boost::algorithm::iequals(args[1], "binary"))
3218 {
3219 m_wallet->set_export_format(tools::wallet2::ExportFormat::Binary);
3220 }
3221 else
3222 {
3223 fail_msg_writer() << tr("Export format not recognized.");
3224 return true;
3225 }
3226 const auto pwd_container = get_and_verify_password();
3227 if (pwd_container)
3228 {
3229 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3230 }
3231 return true;
3232 }
3233
3234 bool simple_wallet::set_load_deprecated_formats(const std::vector<std::string> &args/* = std::vector<std::string()*/)
3235 {
3236 if (args.size() < 2)
3237 {
3238 fail_msg_writer() << tr("Value not specified");
3239 return true;
3240 }
3241
3242 const auto pwd_container = get_and_verify_password();
3243 if (pwd_container)
3244 {
3245 parse_bool_and_use(args[1], [&](bool r) {
3246 m_wallet->load_deprecated_formats(r);
3247 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3248
3249 if (r)
3250 message_writer() << tr("Warning: deprecated formats use boost serialization, which has buffer overflows and crashers. Only load deprecated formats from sources you trust.");
3251 });
3252 }
3253 return true;
3254 }
3255
3256 bool simple_wallet::set_enable_multisig(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3257 {
3258 if (args.size() < 2)
3259 {
3260 fail_msg_writer() << tr("Value not specified");
3261 return true;
3262 }
3263
3264 const auto pwd_container = get_and_verify_password();
3265 if (pwd_container)
3266 {
3267 parse_bool_and_use(args[1], [&](bool r) {
3268 m_wallet->enable_multisig(r);
3269 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3270 });
3271 }
3272 return true;
3273 }
3274
3275 bool simple_wallet::help(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3276 {
3277 if(args.empty())
3278 {
3279 message_writer() << "";
3280 message_writer() << tr("Important commands:");
3281 message_writer() << "";
3282 message_writer() << tr("\"welcome\" - Show welcome message.");
3283 message_writer() << tr("\"help all\" - Show the list of all available commands.");
3284 message_writer() << tr("\"help <command>\" - Show a command's documentation.");
3285 message_writer() << tr("\"apropos <keyword>\" - Show commands related to a keyword.");
3286 message_writer() << "";
3287 message_writer() << tr("\"wallet_info\" - Show wallet main address and other info.");
3288 message_writer() << tr("\"balance\" - Show balance.");
3289 message_writer() << tr("\"address all\" - Show all addresses.");
3290 message_writer() << tr("\"address new\" - Create new subaddress.");
3291 message_writer() << tr("\"transfer <address> <amount>\" - Send XMR to an address.");
3292 message_writer() << tr("\"show_transfers [in|out|pending|failed|pool]\" - Show transactions.");
3293 message_writer() << tr("\"sweep_all <address>\" - Send whole balance to another wallet.");
3294 message_writer() << tr("\"seed\" - Show secret 25 words that can be used to recover this wallet.");
3295 message_writer() << tr("\"refresh\" - Synchronize wallet with the Monero network.");
3296 message_writer() << tr("\"status\" - Check current status of wallet.");
3297 message_writer() << tr("\"version\" - Check software version.");
3298 message_writer() << tr("\"exit\" - Exit wallet.");
3299 message_writer() << "";
3300 message_writer() << tr("\"donate <amount>\" - Donate XMR to the development team.");
3301 message_writer() << "";
3302 }
3303 else if ((args.size() == 1) && (args.front() == "all"))
3304 {
3305 success_msg_writer() << get_commands_str();
3306 }
3307 else if ((args.size() == 2) && (args.front() == "mms"))
3308 {
3309 // Little hack to be able to do "help mms <subcommand>"
3310 std::vector<std::string> mms_args(1, args.front() + " " + args.back());
3311 success_msg_writer() << get_command_usage(mms_args);
3312 }
3313 else
3314 {
3315 success_msg_writer() << get_command_usage(args);
3316 }
3317 return true;
3318 }
3319
3320 bool simple_wallet::apropos(const std::vector<std::string> &args)
3321 {
3322 if (args.empty())
3323 {
3324 PRINT_USAGE(USAGE_APROPOS);
3325 return true;
3326 }
3327 const std::vector<std::string>& command_list = m_cmd_binder.get_command_list(args);
3328 if (command_list.empty())
3329 {
3330 fail_msg_writer() << tr("No commands found mentioning keyword(s)");
3331 return true;
3332 }
3333
3334 success_msg_writer() << "";
3335 for(auto const& command:command_list)
3336 {
3337 std::vector<std::string> cmd;
3338 cmd.push_back(command);
3339 std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(cmd);
3340 success_msg_writer() << " " << documentation.first;
3341 }
3342 success_msg_writer() << "";
3343
3344 return true;
3345 }
3346
3347 bool simple_wallet::scan_tx(const std::vector<std::string> &args)
3348 {
3349 CHECK_IF_BACKGROUND_SYNCING("cannot scan tx");
3350 if (args.empty())
3351 {
3352 PRINT_USAGE(USAGE_SCAN_TX);
3353 return true;
3354 }
3355
3356 // Parse and dedup args
3357 std::unordered_set<crypto::hash> txids;
3358 for (const auto &s : args) {
3359 crypto::hash txid;
3360 if (!epee::string_tools::hex_to_pod(s, txid)) {
3361 fail_msg_writer() << tr("Invalid txid specified: ") << s;
3362 return true;
3363 }
3364 txids.insert(txid);
3365 }
3366
3367 if (!m_wallet->is_trusted_daemon()) {
3368 message_writer(console_color_red, true) << tr("WARNING: this operation may reveal the txids to the remote node and affect your privacy");
3369 if (!command_line::is_yes(input_line("Do you want to continue?", true))) {
3370 message_writer() << tr("You have canceled the operation");
3371 return true;
3372 }
3373 }
3374
3375 LOCK_IDLE_SCOPE();
3376 m_in_manual_refresh.store(true);
3377 try {
3378 m_wallet->scan_tx(txids);
3379 } catch (const tools::error::wont_reprocess_recent_txs_via_untrusted_daemon &e) {
3380 fail_msg_writer() << e.what() << ". Either connect to a trusted daemon by passing --trusted-daemon when starting the wallet, or use rescan_bc to rescan the chain.";
3381 } catch (const std::exception &e) {
3382 fail_msg_writer() << e.what();
3383 }
3384 m_in_manual_refresh.store(false);
3385 return true;
3386 }
3387
3388 simple_wallet::simple_wallet()
3389 : m_allow_mismatched_daemon_version(false)
3390 , m_refresh_progress_reporter(*this)
3391 , m_idle_run(true)
3392 , m_auto_refresh_enabled(false)
3393 , m_auto_refresh_refreshing(false)
3394 , m_in_manual_refresh(false)
3395 , m_current_subaddress_account(0)
3396 , m_last_activity_time(time(NULL))
3397 , m_locked(false)
3398 , m_in_command(false)
3399 , m_need_payment(false)
3400 , m_rpc_payment_mining_requested(false)
3401 , m_last_rpc_payment_mining_time(boost::gregorian::date(1970, 1, 1))
3402 , m_daemon_rpc_payment_message_displayed(false)
3403 , m_rpc_payment_hash_rate(-1.0f)
3404 , m_suspend_rpc_payment_mining(false)
3405 {
3406 m_cmd_binder.set_handler("start_mining",
3407 boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining, _1),
3408 tr(USAGE_START_MINING),
3409 tr("Start mining in the daemon (bg_mining and ignore_battery are optional booleans)."));
3410 m_cmd_binder.set_handler("stop_mining",
3411 boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining, _1),
3412 tr("Stop mining in the daemon."));
3413 m_cmd_binder.set_handler("set_daemon",
3414 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_daemon, _1),
3415 tr(USAGE_SET_DAEMON),
3416 tr("Set another daemon to connect to. If it's not yours, it'll probably spy on you."));
3417 m_cmd_binder.set_handler("save_bc",
3418 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_bc, _1),
3419 tr("Save the current blockchain data."));
3420 m_cmd_binder.set_handler("refresh",
3421 boost::bind(&simple_wallet::on_command, this, &simple_wallet::refresh, _1),
3422 tr("Synchronize the transactions and balance."));
3423 m_cmd_binder.set_handler("balance",
3424 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_balance, _1),
3425 tr(USAGE_SHOW_BALANCE),
3426 tr("Show the wallet's balance of the currently selected account."));
3427 m_cmd_binder.set_handler("incoming_transfers",
3428 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_incoming_transfers,_1),
3429 tr(USAGE_INCOMING_TRANSFERS),
3430 tr("Show the incoming transfers, all or filtered by availability and address index.\n\n"
3431 "Output format:\n"
3432 "Amount, Spent(\"T\"|\"F\"), \"frozen\"|\"locked\"|\"unlocked\", RingCT, Global Index, Transaction Hash, Address Index, [Public Key, Key Image] "));
3433 m_cmd_binder.set_handler("payments",
3434 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_payments,_1),
3435 tr(USAGE_PAYMENTS),
3436 tr("Show the payments for the given payment IDs."));
3437 m_cmd_binder.set_handler("bc_height",
3438 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_blockchain_height, _1),
3439 tr("Show the blockchain height."));
3440 m_cmd_binder.set_handler("transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::transfer, _1),
3441 tr(USAGE_TRANSFER),
3442 tr("Transfer <amount> to <address>. If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included). The \"subtractfeefrom=\" list allows you to choose which destinations to fund the tx fee from instead of the change output. The fee will be split across the chosen destinations proportionally equally. For example, to make 3 transfers where the fee is taken from the first and third destinations, one could do: \"transfer <addr1> 3 <addr2> 0.5 <addr3> 1 subtractfeefrom=0,2\". Let's say the tx fee is 0.1. The balance would drop by exactly 4.5 XMR including fees, and addr1 & addr3 would receive 2.925 & 0.975 XMR, respectively. Use \"subtractfeefrom=all\" to spread the fee across all destinations."));
3443 m_cmd_binder.set_handler("sweep_unmixable",
3444 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_unmixable, _1),
3445 tr("Send all unmixable outputs to yourself with ring_size 1"));
3446 m_cmd_binder.set_handler("sweep_all", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_all, _1),
3447 tr(USAGE_SWEEP_ALL),
3448 tr("Send all unlocked balance to an address. If the parameter \"index=<N1>[,<N2>,...]\" or \"index=all\" is specified, the wallet sweeps outputs received by those or all address indices, respectively. If omitted, the wallet randomly chooses an address index to be used. If the parameter \"outputs=<N>\" is specified and N > 0, wallet splits the transaction into N even outputs."));
3449 m_cmd_binder.set_handler("sweep_account", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_account, _1),
3450 tr(USAGE_SWEEP_ACCOUNT),
3451 tr("Send all unlocked balance from a given account to an address. If the parameter \"index=<N1>[,<N2>,...]\" or \"index=all\" is specified, the wallet sweeps outputs received by those or all address indices, respectively. If omitted, the wallet randomly chooses an address index to be used. If the parameter \"outputs=<N>\" is specified and N > 0, wallet splits the transaction into N even outputs."));
3452 m_cmd_binder.set_handler("sweep_below",
3453 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_below, _1),
3454 tr(USAGE_SWEEP_BELOW),
3455 tr("Send all unlocked outputs below the threshold to an address."));
3456 m_cmd_binder.set_handler("sweep_single",
3457 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_single, _1),
3458 tr(USAGE_SWEEP_SINGLE),
3459 tr("Send a single output of the given key image to an address without change."));
3460 m_cmd_binder.set_handler("donate",
3461 boost::bind(&simple_wallet::on_command, this, &simple_wallet::donate, _1),
3462 tr(USAGE_DONATE),
3463 tr("Donate <amount> to the development team (donate.getmonero.org)."));
3464 m_cmd_binder.set_handler("sign_transfer",
3465 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_transfer, _1),
3466 tr(USAGE_SIGN_TRANSFER),
3467 tr("Sign a transaction from a file. If the parameter \"export_raw\" is specified, transaction raw hex data suitable for the daemon RPC /sendrawtransaction is exported.\n"
3468 "Use the parameter <filename> to specify the file to read from. If not specified, the default \"unsigned_monero_tx\" will be used."));
3469 m_cmd_binder.set_handler("submit_transfer",
3470 boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_transfer, _1),
3471 tr("Submit a signed transaction from a file."));
3472 m_cmd_binder.set_handler("set_log",
3473 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_log, _1),
3474 tr(USAGE_SET_LOG),
3475 tr("Change the current log detail (level must be <0-4>)."));
3476 m_cmd_binder.set_handler("account",
3477 boost::bind(&simple_wallet::on_command, this, &simple_wallet::account, _1),
3478 tr(USAGE_ACCOUNT),
3479 tr("If no arguments are specified, the wallet shows all the existing accounts along with their balances.\n"
3480 "If the \"new\" argument is specified, the wallet creates a new account with its label initialized by the provided label text (which can be empty).\n"
3481 "If the \"switch\" argument is specified, the wallet switches to the account specified by <index>.\n"
3482 "If the \"label\" argument is specified, the wallet sets the label of the account specified by <index> to the provided label text.\n"
3483 "If the \"tag\" argument is specified, a tag <tag_name> is assigned to the specified accounts <account_index_1>, <account_index_2>, ....\n"
3484 "If the \"untag\" argument is specified, the tags assigned to the specified accounts <account_index_1>, <account_index_2> ..., are removed.\n"
3485 "If the \"tag_description\" argument is specified, the tag <tag_name> is assigned an arbitrary text <description>."));
3486 m_cmd_binder.set_handler("address",
3487 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_address, _1),
3488 tr(USAGE_ADDRESS),
3489 tr("If no arguments are specified or <index> is specified, the wallet shows the default or specified address. If \"all\" is specified, the wallet shows all the existing addresses in the currently selected account. If \"new \" is specified, the wallet creates a new address with the provided label text (which can be empty). If \"mnew\" is specified, the wallet creates as many new addresses as specified by the argument; the default label is set for the new addresses. If \"label\" is specified, the wallet sets the label of the address specified by <index> to the provided label text. If \"one-off\" is specified, the address for the specified index is generated and displayed, and remembered by the wallet"));
3490 m_cmd_binder.set_handler("integrated_address",
3491 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_integrated_address, _1),
3492 tr(USAGE_INTEGRATED_ADDRESS),
3493 tr("Encode a payment ID into an integrated address for the current wallet public address (no argument uses a random payment ID), or decode an integrated address to standard address and payment ID"));
3494 m_cmd_binder.set_handler("address_book",
3495 boost::bind(&simple_wallet::on_command, this, &simple_wallet::address_book,_1),
3496 tr(USAGE_ADDRESS_BOOK),
3497 tr("Print all entries in the address book, optionally adding/deleting an entry to/from it."));
3498 m_cmd_binder.set_handler("save",
3499 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save, _1),
3500 tr("Save the wallet data."));
3501 m_cmd_binder.set_handler("save_watch_only",
3502 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_watch_only, _1),
3503 tr("Save a watch-only keys file."));
3504 m_cmd_binder.set_handler("viewkey",
3505 boost::bind(&simple_wallet::on_command, this, &simple_wallet::viewkey, _1),
3506 tr("Display the private view key."));
3507 m_cmd_binder.set_handler("spendkey",
3508 boost::bind(&simple_wallet::on_command, this, &simple_wallet::spendkey, _1),
3509 tr("Display the private spend key."));
3510 m_cmd_binder.set_handler("seed",
3511 boost::bind(&simple_wallet::on_command, this, &simple_wallet::seed, _1),
3512 tr("Display the Electrum-style mnemonic seed"));
3513 m_cmd_binder.set_handler("restore_height",
3514 boost::bind(&simple_wallet::on_command, this, &simple_wallet::restore_height, _1),
3515 tr("Display the restore height"));
3516 m_cmd_binder.set_handler("set",
3517 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_variable, _1),
3518 tr(USAGE_SET_VARIABLE),
3519 tr("Available options:\n "
3520 "seed language\n "
3521 " Set the wallet's seed language.\n "
3522 "always-confirm-transfers <1|0>\n "
3523 " Whether to confirm unsplit txes.\n "
3524 "print-ring-members <1|0>\n "
3525 " Whether to print detailed information about ring members during confirmation.\n "
3526 "store-tx-info <1|0>\n "
3527 " Whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference.\n "
3528 "auto-refresh <1|0>\n "
3529 " Whether to automatically synchronize new blocks from the daemon.\n "
3530 "refresh-type <full|optimize-coinbase|no-coinbase|default>\n "
3531 " Set the wallet's refresh behaviour.\n "
3532 "priority [0|1|2|3|4]\n "
3533 " Set the fee to default/unimportant/normal/elevated/priority.\n "
3534 "confirm-missing-payment-id <1|0> (obsolete)\n "
3535 "ask-password <0|1|2 (or never|action|decrypt)>\n "
3536 " action: ask the password before many actions such as transfer, etc\n "
3537 " decrypt: same as action, but keeps the spend key encrypted in memory when not needed\n "
3538 "unit <monero|millinero|micronero|nanonero|piconero>\n "
3539 " Set the default monero (sub-)unit.\n "
3540 "min-outputs-count [n]\n "
3541 " Try to keep at least that many outputs of value at least min-outputs-value.\n "
3542 "min-outputs-value [n]\n "
3543 " Try to keep at least min-outputs-count outputs of at least that value.\n "
3544 "merge-destinations <1|0>\n "
3545 " Whether to merge multiple payments to the same destination address.\n "
3546 "confirm-backlog <1|0>\n "
3547 " Whether to warn if there is transaction backlog.\n "
3548 "confirm-backlog-threshold [n]\n "
3549 " Set a threshold for confirm-backlog to only warn if the transaction backlog is greater than n blocks.\n "
3550 "confirm-export-overwrite <1|0>\n "
3551 " Whether to warn if the file to be exported already exists.\n "
3552 "refresh-from-block-height [n]\n "
3553 " Set the height before which to ignore blocks.\n "
3554 "auto-low-priority <1|0>\n "
3555 " Whether to automatically use the low priority fee level when it's safe to do so.\n "
3556 "segregate-pre-fork-outputs <1|0>\n "
3557 " Set this if you intend to spend outputs on both Monero AND a key reusing fork.\n "
3558 "key-reuse-mitigation2 <1|0>\n "
3559 " Set this if you are not sure whether you will spend on a key reusing Monero fork later.\n "
3560 "subaddress-lookahead <major>:<minor>\n "
3561 " Set the lookahead sizes for the subaddress hash table.\n "
3562 "segregation-height <n>\n "
3563 " Set to the height of a key reusing fork you want to use, 0 to use default.\n "
3564 "ignore-fractional-outputs <1|0>\n "
3565 " Whether to ignore fractional outputs that result in net loss when spending due to fee.\n "
3566 "ignore-outputs-above <amount>\n "
3567 " Ignore outputs of amount above this threshold when spending. Value 0 is translated to the maximum value (18 million) which disables this filter.\n "
3568 "ignore-outputs-below <amount>\n "
3569 " Ignore outputs of amount below this threshold when spending.\n "
3570 "track-uses <1|0>\n "
3571 " Whether to keep track of owned outputs uses.\n "
3572 "background-sync <off|reuse-wallet-password|custom-background-password>\n "
3573 " Set this to enable scanning in the background with just the view key while the wallet is locked.\n "
3574 "setup-background-mining <1|0>\n "
3575 " Whether to enable background mining. Set this to support the network and to get a chance to receive new monero.\n "
3576 "device-name <device_name[:device_spec]>\n "
3577 " Device name for hardware wallet.\n "
3578 "export-format <\"binary\"|\"ascii\">\n "
3579 " Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n "
3580 "persistent-rpc-client-id <1|0>\n "
3581 " Whether to keep using the same client id for RPC payment over wallet restarts.\n"
3582 "auto-mine-for-rpc-payment-threshold <float>\n "
3583 " Whether to automatically start mining for RPC payment if the daemon requires it.\n"
3584 "credits-target <unsigned int>\n"
3585 " The RPC payment credits balance to target (0 for default).\n "
3586 "show-wallet-name-when-locked <1|0>\n "
3587 " Set this if you would like to display the wallet name when locked.\n "
3588 "enable-multisig-experimental <1|0>\n "
3589 " Set this to allow multisig commands. Multisig may currently be exploitable if parties do not trust each other.\n "
3590 "inactivity-lock-timeout <unsigned int>\n "
3591 " How many seconds to wait before locking the wallet (0 to disable)."));
3592 m_cmd_binder.set_handler("encrypted_seed",
3593 boost::bind(&simple_wallet::on_command, this, &simple_wallet::encrypted_seed, _1),
3594 tr("Display the encrypted Electrum-style mnemonic seed."));
3595 m_cmd_binder.set_handler("rescan_spent",
3596 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_spent, _1),
3597 tr("Rescan the blockchain for spent outputs."));
3598 m_cmd_binder.set_handler("get_tx_key",
3599 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_key, _1),
3600 tr(USAGE_GET_TX_KEY),
3601 tr("Get the transaction key (r) for a given <txid>."));
3602 m_cmd_binder.set_handler("set_tx_key",
3603 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_key, _1),
3604 tr(USAGE_SET_TX_KEY),
3605 tr("Set the transaction key (r) for a given <txid> in case the tx was made by some other device or 3rd party wallet."));
3606 m_cmd_binder.set_handler("check_tx_key",
3607 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_key, _1),
3608 tr(USAGE_CHECK_TX_KEY),
3609 tr("Check the amount going to <address> in <txid>."));
3610 m_cmd_binder.set_handler("get_tx_proof",
3611 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_proof, _1),
3612 tr(USAGE_GET_TX_PROOF),
3613 tr("Generate a signature proving funds sent to <address> in <txid>, optionally with a challenge string <message>, using either the transaction secret key (when <address> is not your wallet's address) or the view secret key (otherwise), which does not disclose the secret key."));
3614 m_cmd_binder.set_handler("check_tx_proof",
3615 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_proof, _1),
3616 tr(USAGE_CHECK_TX_PROOF),
3617 tr("Check the proof for funds going to <address> in <txid> with the challenge string <message> if any."));
3618 m_cmd_binder.set_handler("get_spend_proof",
3619 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_spend_proof, _1),
3620 tr(USAGE_GET_SPEND_PROOF),
3621 tr("Generate a signature proving that you generated <txid> using the spend secret key, optionally with a challenge string <message>."));
3622 m_cmd_binder.set_handler("check_spend_proof",
3623 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_spend_proof, _1),
3624 tr(USAGE_CHECK_SPEND_PROOF),
3625 tr("Check a signature proving that the signer generated <txid>, optionally with a challenge string <message>."));
3626 m_cmd_binder.set_handler("get_reserve_proof",
3627 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_reserve_proof, _1),
3628 tr(USAGE_GET_RESERVE_PROOF),
3629 tr("Generate a signature proving that you own at least this much, optionally with a challenge string <message>.\n"
3630 "If 'all' is specified, you prove the entire sum of all of your existing accounts' balances.\n"
3631 "Otherwise, you prove the reserve of the smallest possible amount above <amount> available in your current account."));
3632 m_cmd_binder.set_handler("check_reserve_proof",
3633 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_reserve_proof, _1),
3634 tr(USAGE_CHECK_RESERVE_PROOF),
3635 tr("Check a signature proving that the owner of <address> holds at least this much, optionally with a challenge string <message>."));
3636 m_cmd_binder.set_handler("show_transfers",
3637 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfers, _1),
3638 tr(USAGE_SHOW_TRANSFERS),
3639 // Seemingly broken formatting to compensate for the backslash before the quotes.
3640 tr("Show the incoming/outgoing transfers within an optional height range.\n\n"
3641 "Output format:\n"
3642 "In or Coinbase: Block Number, \"block\"|\"in\", Time, Amount, Transaction Hash, Payment ID, Subaddress Index, \"-\", Note\n"
3643 "Out: Block Number, \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Destinations, Input addresses**, \"-\", Note\n"
3644 "Pool: \"pool\", \"in\", Time, Amount, Transaction Hash, Payment Id, Subaddress Index, \"-\", Note, Double Spend Note\n"
3645 "Pending or Failed: \"failed\"|\"pending\", \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Input addresses**, \"-\", Note\n\n"
3646 "* Excluding change and fee.\n"
3647 "** Set of address indices used as inputs in this transfer."));
3648 m_cmd_binder.set_handler("export_transfers",
3649 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_transfers, _1),
3650 tr("export_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<filepath>] [option=<with_keys>]"),
3651 tr("Export to CSV the incoming/outgoing transfers within an optional height range."));
3652 m_cmd_binder.set_handler("unspent_outputs",
3653 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unspent_outputs, _1),
3654 tr(USAGE_UNSPENT_OUTPUTS),
3655 tr("Show the unspent outputs of a specified address within an optional amount range."));
3656 m_cmd_binder.set_handler("rescan_bc",
3657 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_blockchain, _1),
3658 tr(USAGE_RESCAN_BC),
3659 tr("Rescan the blockchain from scratch. If \"hard\" is specified, you will lose any information which can not be recovered from the blockchain itself."));
3660 m_cmd_binder.set_handler("set_tx_note",
3661 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_note, _1),
3662 tr(USAGE_SET_TX_NOTE),
3663 tr("Set an arbitrary string note for a <txid>."));
3664 m_cmd_binder.set_handler("get_tx_note",
3665 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_note, _1),
3666 tr(USAGE_GET_TX_NOTE),
3667 tr("Get a string note for a txid."));
3668 m_cmd_binder.set_handler("set_description",
3669 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_description, _1),
3670 tr(USAGE_SET_DESCRIPTION),
3671 tr("Set an arbitrary description for the wallet."));
3672 m_cmd_binder.set_handler("get_description",
3673 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_description, _1),
3674 tr(USAGE_GET_DESCRIPTION),
3675 tr("Get the description of the wallet."));
3676 m_cmd_binder.set_handler("status",
3677 boost::bind(&simple_wallet::on_command, this, &simple_wallet::status, _1),
3678 tr("Show the wallet's status."));
3679 m_cmd_binder.set_handler("wallet_info",
3680 boost::bind(&simple_wallet::on_command, this, &simple_wallet::wallet_info, _1),
3681 tr("Show the wallet's information."));
3682 m_cmd_binder.set_handler("sign",
3683 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign, _1),
3684 tr(USAGE_SIGN),
3685 tr("Sign the contents of a file with the given subaddress (or the main address if not specified)"));
3686 m_cmd_binder.set_handler("verify",
3687 boost::bind(&simple_wallet::on_command, this, &simple_wallet::verify, _1),
3688 tr(USAGE_VERIFY),
3689 tr("Verify a signature on the contents of a file."));
3690 m_cmd_binder.set_handler("export_key_images",
3691 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_key_images, _1),
3692 tr(USAGE_EXPORT_KEY_IMAGES),
3693 tr("Export a signed set of key images to a <filename>."));
3694 m_cmd_binder.set_handler("import_key_images",
3695 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_key_images, _1),
3696 tr(USAGE_IMPORT_KEY_IMAGES),
3697 tr("Import a signed key images list and verify their spent status."));
3698 m_cmd_binder.set_handler("hw_key_images_sync",
3699 boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_key_images_sync, _1),
3700 tr(USAGE_HW_KEY_IMAGES_SYNC),
3701 tr("Synchronizes key images with the hw wallet."));
3702 m_cmd_binder.set_handler("hw_reconnect",
3703 boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_reconnect, _1),
3704 tr(USAGE_HW_RECONNECT),
3705 tr("Attempts to reconnect HW wallet."));
3706 m_cmd_binder.set_handler("export_outputs",
3707 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_outputs, _1),
3708 tr(USAGE_EXPORT_OUTPUTS),
3709 tr("Export a set of outputs owned by this wallet."));
3710 m_cmd_binder.set_handler("import_outputs",
3711 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_outputs, _1),
3712 tr(USAGE_IMPORT_OUTPUTS),
3713 tr("Import a set of outputs owned by this wallet."));
3714 m_cmd_binder.set_handler("show_transfer",
3715 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfer, _1),
3716 tr(USAGE_SHOW_TRANSFER),
3717 tr("Show information about a transfer to/from this address."));
3718 m_cmd_binder.set_handler("password",
3719 boost::bind(&simple_wallet::on_command, this, &simple_wallet::change_password, _1),
3720 tr("Change the wallet's password."));
3721 m_cmd_binder.set_handler("payment_id",
3722 boost::bind(&simple_wallet::on_command, this, &simple_wallet::payment_id, _1),
3723 tr(USAGE_PAYMENT_ID),
3724 tr("Generate a new random full size payment id (obsolete). These will be unencrypted on the blockchain, see integrated_address for encrypted short payment ids."));
3725 m_cmd_binder.set_handler("fee",
3726 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_fee_info, _1),
3727 tr("Print the information about the current fee and transaction backlog."));
3728 m_cmd_binder.set_handler("prepare_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::prepare_multisig, _1),
3729 tr("Export data needed to create a multisig wallet"));
3730 m_cmd_binder.set_handler("make_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::make_multisig, _1),
3731 tr(USAGE_MAKE_MULTISIG),
3732 tr("Turn this wallet into a multisig wallet"));
3733 m_cmd_binder.set_handler("exchange_multisig_keys",
3734 boost::bind(&simple_wallet::on_command, this, &simple_wallet::exchange_multisig_keys, _1),
3735 tr(USAGE_EXCHANGE_MULTISIG_KEYS),
3736 tr("Performs extra multisig keys exchange rounds. Needed for arbitrary M/N multisig wallets"));
3737 m_cmd_binder.set_handler("export_multisig_info",
3738 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_multisig, _1),
3739 tr(USAGE_EXPORT_MULTISIG_INFO),
3740 tr("Export multisig info for other participants"));
3741 m_cmd_binder.set_handler("import_multisig_info",
3742 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_multisig, _1),
3743 tr(USAGE_IMPORT_MULTISIG_INFO),
3744 tr("Import multisig info from other participants"));
3745 m_cmd_binder.set_handler("sign_multisig",
3746 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_multisig, _1),
3747 tr(USAGE_SIGN_MULTISIG),
3748 tr("Sign a multisig transaction from a file"));
3749 m_cmd_binder.set_handler("submit_multisig",
3750 boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_multisig, _1),
3751 tr(USAGE_SUBMIT_MULTISIG),
3752 tr("Submit a signed multisig transaction from a file"));
3753 m_cmd_binder.set_handler("export_raw_multisig_tx",
3754 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_raw_multisig, _1),
3755 tr(USAGE_EXPORT_RAW_MULTISIG_TX),
3756 tr("Export a signed multisig transaction to a file"));
3757 m_cmd_binder.set_handler("mms",
3758 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3759 tr(USAGE_MMS),
3760 tr("Interface with the MMS (Multisig Messaging System)\n"
3761 "<subcommand> is one of:\n"
3762 " init, info, signer, list, next, sync, transfer, delete, send, receive, export, note, show, set, help\n"
3763 " send_signer_config, start_auto_config, stop_auto_config, auto_config, config_checksum\n"
3764 "Get help about a subcommand with: help mms <subcommand>, or help mms <subcommand>"));
3765 m_cmd_binder.set_handler("mms init",
3766 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3767 tr(USAGE_MMS_INIT),
3768 tr("Initialize and configure the MMS for M/N = number of required signers/number of authorized signers multisig"));
3769 m_cmd_binder.set_handler("mms info",
3770 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3771 tr(USAGE_MMS_INFO),
3772 tr("Display current MMS configuration"));
3773 m_cmd_binder.set_handler("mms signer",
3774 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3775 tr(USAGE_MMS_SIGNER),
3776 tr("Set or modify authorized signer info (single-word label, transport address, Monero address), or list all signers"));
3777 m_cmd_binder.set_handler("mms list",
3778 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3779 tr(USAGE_MMS_LIST),
3780 tr("List all messages"));
3781 m_cmd_binder.set_handler("mms next",
3782 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3783 tr(USAGE_MMS_NEXT),
3784 tr("Evaluate the next possible multisig-related action(s) according to wallet state, and execute or offer for choice\n"
3785 "By using 'sync' processing of waiting messages with multisig sync info can be forced regardless of wallet state"));
3786 m_cmd_binder.set_handler("mms sync",
3787 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3788 tr(USAGE_MMS_SYNC),
3789 tr("Force generation of multisig sync info regardless of wallet state, to recover from special situations like \"stale data\" errors"));
3790 m_cmd_binder.set_handler("mms transfer",
3791 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3792 tr(USAGE_MMS_TRANSFER),
3793 tr("Initiate transfer with MMS support; arguments identical to normal 'transfer' command arguments, for info see there"));
3794 m_cmd_binder.set_handler("mms delete",
3795 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3796 tr(USAGE_MMS_DELETE),
3797 tr("Delete a single message by giving its id, or delete all messages by using 'all'"));
3798 m_cmd_binder.set_handler("mms send",
3799 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3800 tr(USAGE_MMS_SEND),
3801 tr("Send a single message by giving its id, or send all waiting messages"));
3802 m_cmd_binder.set_handler("mms receive",
3803 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3804 tr(USAGE_MMS_RECEIVE),
3805 tr("Check right away for new messages to receive"));
3806 m_cmd_binder.set_handler("mms export",
3807 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3808 tr(USAGE_MMS_EXPORT),
3809 tr("Write the content of a message to a file \"mms_message_content\""));
3810 m_cmd_binder.set_handler("mms note",
3811 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3812 tr(USAGE_MMS_NOTE),
3813 tr("Send a one-line message to an authorized signer, identified by its label, or show any waiting unread notes"));
3814 m_cmd_binder.set_handler("mms show",
3815 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3816 tr(USAGE_MMS_SHOW),
3817 tr("Show detailed info about a single message"));
3818 m_cmd_binder.set_handler("mms set",
3819 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3820 tr(USAGE_MMS_SET),
3821 tr("Available options:\n "
3822 "auto-send <1|0>\n "
3823 " Whether to automatically send newly generated messages right away.\n "));
3824 m_cmd_binder.set_handler("mms send_signer_config",
3825 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3826 tr(USAGE_MMS_SEND_SIGNER_CONFIG),
3827 tr("Send completed signer config to all other authorized signers"));
3828 m_cmd_binder.set_handler("mms start_auto_config",
3829 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3830 tr(USAGE_MMS_START_AUTO_CONFIG),
3831 tr("Start auto-config at the auto-config manager's wallet by issuing auto-config tokens and optionally set others' labels"));
3832 m_cmd_binder.set_handler("mms config_checksum",
3833 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3834 tr(USAGE_MMS_CONFIG_CHECKSUM),
3835 tr("Get a checksum that allows signers to easily check for identical MMS configuration"));
3836 m_cmd_binder.set_handler("mms stop_auto_config",
3837 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3838 tr(USAGE_MMS_STOP_AUTO_CONFIG),
3839 tr("Delete any auto-config tokens and abort a auto-config process"));
3840 m_cmd_binder.set_handler("mms auto_config",
3841 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3842 tr(USAGE_MMS_AUTO_CONFIG),
3843 tr("Start auto-config by using the token received from the auto-config manager"));
3844 m_cmd_binder.set_handler("print_ring",
3845 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_ring, _1),
3846 tr(USAGE_PRINT_RING),
3847 tr("Print the ring(s) used to spend a given key image or transaction (if the ring size is > 1)\n\n"
3848 "Output format:\n"
3849 "Key Image, \"absolute\", list of rings"));
3850 m_cmd_binder.set_handler("set_ring",
3851 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_ring, _1),
3852 tr(USAGE_SET_RING),
3853 tr("Set the ring used for a given key image, so it can be reused in a fork"));
3854 m_cmd_binder.set_handler("unset_ring",
3855 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unset_ring, _1),
3856 tr(USAGE_UNSET_RING),
3857 tr("Unsets the ring used for a given key image or transaction"));
3858 m_cmd_binder.set_handler("save_known_rings",
3859 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_known_rings, _1),
3860 tr(USAGE_SAVE_KNOWN_RINGS),
3861 tr("Save known rings to the shared rings database"));
3862 m_cmd_binder.set_handler("mark_output_spent",
3863 boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackball, _1),
3864 tr(USAGE_MARK_OUTPUT_SPENT),
3865 tr("Mark output(s) as spent so they never get selected as fake outputs in a ring"));
3866 m_cmd_binder.set_handler("mark_output_unspent",
3867 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unblackball, _1),
3868 tr(USAGE_MARK_OUTPUT_UNSPENT),
3869 tr("Marks an output as unspent so it may get selected as a fake output in a ring"));
3870 m_cmd_binder.set_handler("is_output_spent",
3871 boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackballed, _1),
3872 tr(USAGE_IS_OUTPUT_SPENT),
3873 tr("Checks whether an output is marked as spent"));
3874 m_cmd_binder.set_handler("freeze",
3875 boost::bind(&simple_wallet::on_command, this, &simple_wallet::freeze, _1),
3876 tr(USAGE_FREEZE),
3877 tr("Freeze a single output by key image so it will not be used"));
3878 m_cmd_binder.set_handler("thaw",
3879 boost::bind(&simple_wallet::on_command, this, &simple_wallet::thaw, _1),
3880 tr(USAGE_THAW),
3881 tr("Thaw a single output by key image so it may be used again"));
3882 m_cmd_binder.set_handler("frozen",
3883 boost::bind(&simple_wallet::on_command, this, &simple_wallet::frozen, _1),
3884 tr(USAGE_FROZEN),
3885 tr("Checks whether a given output is currently frozen by key image"));
3886 m_cmd_binder.set_handler("lock",
3887 boost::bind(&simple_wallet::on_command, this, &simple_wallet::lock, _1),
3888 tr(USAGE_LOCK),
3889 tr("Lock the wallet console, requiring the wallet password to continue"));
3890 m_cmd_binder.set_handler("net_stats",
3891 boost::bind(&simple_wallet::on_command, this, &simple_wallet::net_stats, _1),
3892 tr(USAGE_NET_STATS),
3893 tr("Prints simple network stats"));
3894 m_cmd_binder.set_handler("public_nodes",
3895 boost::bind(&simple_wallet::on_command, this, &simple_wallet::public_nodes, _1),
3896 tr(USAGE_PUBLIC_NODES),
3897 tr("Lists known public nodes"));
3898 m_cmd_binder.set_handler("welcome",
3899 boost::bind(&simple_wallet::on_command, this, &simple_wallet::welcome, _1),
3900 tr(USAGE_WELCOME),
3901 tr("Prints basic info about Monero for first time users"));
3902 m_cmd_binder.set_handler("version",
3903 boost::bind(&simple_wallet::on_command, this, &simple_wallet::version, _1),
3904 tr(USAGE_VERSION),
3905 tr("Returns version information"));
3906 m_cmd_binder.set_handler("rpc_payment_info",
3907 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rpc_payment_info, _1),
3908 tr(USAGE_RPC_PAYMENT_INFO),
3909 tr("Get info about RPC payments to current node"));
3910 m_cmd_binder.set_handler("start_mining_for_rpc",
3911 boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining_for_rpc, _1),
3912 tr(USAGE_START_MINING_FOR_RPC),
3913 tr("Start mining to pay for RPC access"));
3914 m_cmd_binder.set_handler("stop_mining_for_rpc",
3915 boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining_for_rpc, _1),
3916 tr(USAGE_STOP_MINING_FOR_RPC),
3917 tr("Stop mining to pay for RPC access"));
3918 m_cmd_binder.set_handler("show_qr_code",
3919 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_qr_code, _1),
3920 tr(USAGE_SHOW_QR_CODE),
3921 tr("Show address as QR code"));
3922 m_cmd_binder.set_handler("help",
3923 boost::bind(&simple_wallet::on_command, this, &simple_wallet::help, _1),
3924 tr(USAGE_HELP),
3925 tr("Show the help section or the documentation about a <command>."));
3926 m_cmd_binder.set_handler("apropos",
3927 boost::bind(&simple_wallet::on_command, this, &simple_wallet::apropos, _1),
3928 tr(USAGE_APROPOS),
3929 tr("Search all command descriptions for keyword(s)"));
3930 m_cmd_binder.set_handler("scan_tx",
3931 boost::bind(&simple_wallet::on_command, this, &simple_wallet::scan_tx, _1),
3932 tr(USAGE_SCAN_TX),
3933 tr("Scan the transactions given by <txid>(s), processing them and looking for outputs"));
3934 m_cmd_binder.set_unknown_command_handler(boost::bind(&simple_wallet::on_command, this, &simple_wallet::on_unknown_command, _1));
3935 m_cmd_binder.set_empty_command_handler(boost::bind(&simple_wallet::on_empty_command, this));
3936 m_cmd_binder.set_cancel_handler(boost::bind(&simple_wallet::on_cancelled_command, this));
3937 }
3938 //----------------------------------------------------------------------------------------------------
3939 bool simple_wallet::set_variable(const std::vector<std::string> &args)
3940 {
3941 if (args.empty())
3942 {
3943 std::string seed_language = m_wallet->get_seed_language();
3944 if (m_use_english_language_names)
3945 seed_language = crypto::ElectrumWords::get_english_name_for(seed_language);
3946 std::string priority_string = "invalid";
3947 uint32_t priority = m_wallet->get_default_priority();
3948 if (priority < allowed_priority_strings.size())
3949 priority_string = allowed_priority_strings[priority];
3950 std::string ask_password_string = "invalid";
3951 switch (m_wallet->ask_password())
3952 {
3953 case tools::wallet2::AskPasswordNever: ask_password_string = "never"; break;
3954 case tools::wallet2::AskPasswordOnAction: ask_password_string = "action"; break;
3955 case tools::wallet2::AskPasswordToDecrypt: ask_password_string = "decrypt"; break;
3956 }
3957 std::string setup_background_mining_string = "invalid";
3958 switch (m_wallet->setup_background_mining())
3959 {
3960 case tools::wallet2::BackgroundMiningMaybe: setup_background_mining_string = "maybe"; break;
3961 case tools::wallet2::BackgroundMiningYes: setup_background_mining_string = "yes"; break;
3962 case tools::wallet2::BackgroundMiningNo: setup_background_mining_string = "no"; break;
3963 }
3964 success_msg_writer() << "seed = " << seed_language;
3965 success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers();
3966 success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members();
3967 success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info();
3968 success_msg_writer() << "default-ring-size = " << (m_wallet->default_mixin() ? m_wallet->default_mixin() + 1 : 0);
3969 success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh();
3970 success_msg_writer() << "refresh-type = " << get_refresh_type_name(m_wallet->get_refresh_type());
3971 success_msg_writer() << "priority = " << priority<< " (" << priority_string << ")";
3972 success_msg_writer() << "ask-password = " << m_wallet->ask_password() << " (" << ask_password_string << ")";
3973 success_msg_writer() << "unit = " << cryptonote::get_unit(cryptonote::get_default_decimal_point());
3974 success_msg_writer() << "max-reorg-depth = " << m_wallet->max_reorg_depth();
3975 success_msg_writer() << "min-outputs-count = " << m_wallet->get_min_output_count();
3976 success_msg_writer() << "min-outputs-value = " << cryptonote::print_money(m_wallet->get_min_output_value());
3977 success_msg_writer() << "merge-destinations = " << m_wallet->merge_destinations();
3978 success_msg_writer() << "confirm-backlog = " << m_wallet->confirm_backlog();
3979 success_msg_writer() << "confirm-backlog-threshold = " << m_wallet->get_confirm_backlog_threshold();
3980 success_msg_writer() << "confirm-export-overwrite = " << m_wallet->confirm_export_overwrite();
3981 success_msg_writer() << "refresh-from-block-height = " << m_wallet->get_refresh_from_block_height();
3982 success_msg_writer() << "auto-low-priority = " << m_wallet->auto_low_priority();
3983 success_msg_writer() << "segregate-pre-fork-outputs = " << m_wallet->segregate_pre_fork_outputs();
3984 success_msg_writer() << "key-reuse-mitigation2 = " << m_wallet->key_reuse_mitigation2();
3985 const std::pair<size_t, size_t> lookahead = m_wallet->get_subaddress_lookahead();
3986 success_msg_writer() << "subaddress-lookahead = " << lookahead.first << ":" << lookahead.second;
3987 success_msg_writer() << "segregation-height = " << m_wallet->segregation_height();
3988 success_msg_writer() << "ignore-fractional-outputs = " << m_wallet->ignore_fractional_outputs();
3989 success_msg_writer() << "ignore-outputs-above = " << cryptonote::print_money(m_wallet->ignore_outputs_above());
3990 success_msg_writer() << "ignore-outputs-below = " << cryptonote::print_money(m_wallet->ignore_outputs_below());
3991 success_msg_writer() << "track-uses = " << m_wallet->track_uses();
3992 success_msg_writer() << "background-sync = " << get_background_sync_type_name(m_wallet->background_sync_type());
3993 success_msg_writer() << "setup-background-mining = " << setup_background_mining_string;
3994 success_msg_writer() << "device-name = " << m_wallet->device_name();
3995 success_msg_writer() << "export-format = " << (m_wallet->export_format() == tools::wallet2::ExportFormat::Ascii ? "ascii" : "binary");
3996 success_msg_writer() << "show-wallet-name-when-locked = " << m_wallet->show_wallet_name_when_locked();
3997 success_msg_writer() << "inactivity-lock-timeout = " << m_wallet->inactivity_lock_timeout()
3998 #ifdef _WIN32
3999 << " (disabled on Windows)"
4000 #endif
4001 ;
4002 success_msg_writer() << "persistent-rpc-client-id = " << m_wallet->persistent_rpc_client_id();
4003 success_msg_writer() << "auto-mine-for-rpc-payment-threshold = " << m_wallet->auto_mine_for_rpc_payment_threshold();
4004 success_msg_writer() << "credits-target = " << m_wallet->credits_target();
4005 success_msg_writer() << "load-deprecated-formats = " << m_wallet->load_deprecated_formats();
4006 success_msg_writer() << "enable-multisig-experimental = " << m_wallet->is_multisig_enabled();
4007 return true;
4008 }
4009 else
4010 {
4011 CHECK_IF_BACKGROUND_SYNCING("cannot change wallet settings");
4012
4013 #define CHECK_SIMPLE_VARIABLE(name, f, help) do \
4014 if (args[0] == name) { \
4015 if (args.size() <= 1) \
4016 { \
4017 fail_msg_writer() << "set " << #name << ": " << tr("needs an argument") << " (" << help << ")"; \
4018 return true; \
4019 } \
4020 else \
4021 { \
4022 f(args); \
4023 return true; \
4024 } \
4025 } while(0)
4026
4027 if (args[0] == "seed")
4028 {
4029 if (args.size() == 1)
4030 {
4031 fail_msg_writer() << tr("set seed: needs an argument. available options: language");
4032 return true;
4033 }
4034 else if (args[1] == "language")
4035 {
4036 seed_set_language(args);
4037 return true;
4038 }
4039 }
4040 CHECK_SIMPLE_VARIABLE("always-confirm-transfers", set_always_confirm_transfers, tr("0 or 1"));
4041 CHECK_SIMPLE_VARIABLE("print-ring-members", set_print_ring_members, tr("0 or 1"));
4042 CHECK_SIMPLE_VARIABLE("store-tx-info", set_store_tx_info, tr("0 or 1"));
4043 CHECK_SIMPLE_VARIABLE("auto-refresh", set_auto_refresh, tr("0 or 1"));
4044 CHECK_SIMPLE_VARIABLE("refresh-type", set_refresh_type, tr("full (slowest, no assumptions); optimize-coinbase (fast, assumes the whole coinbase is paid to a single address); no-coinbase (fastest, assumes we receive no coinbase transaction), default (same as optimize-coinbase)"));
4045 CHECK_SIMPLE_VARIABLE("priority", set_default_priority, tr("0, 1, 2, 3, or 4, or one of ") << join_priority_strings(", "));
4046 CHECK_SIMPLE_VARIABLE("ask-password", set_ask_password, tr("0|1|2 (or never|action|decrypt)"));
4047 CHECK_SIMPLE_VARIABLE("unit", set_unit, tr("monero, millinero, micronero, nanonero, piconero"));
4048 CHECK_SIMPLE_VARIABLE("max-reorg-depth", set_max_reorg_depth, tr("unsigned integer"));
4049 CHECK_SIMPLE_VARIABLE("min-outputs-count", set_min_output_count, tr("unsigned integer"));
4050 CHECK_SIMPLE_VARIABLE("min-outputs-value", set_min_output_value, tr("amount"));
4051 CHECK_SIMPLE_VARIABLE("merge-destinations", set_merge_destinations, tr("0 or 1"));
4052 CHECK_SIMPLE_VARIABLE("confirm-backlog", set_confirm_backlog, tr("0 or 1"));
4053 CHECK_SIMPLE_VARIABLE("confirm-backlog-threshold", set_confirm_backlog_threshold, tr("unsigned integer"));
4054 CHECK_SIMPLE_VARIABLE("confirm-export-overwrite", set_confirm_export_overwrite, tr("0 or 1"));
4055 CHECK_SIMPLE_VARIABLE("refresh-from-block-height", set_refresh_from_block_height, tr("block height"));
4056 CHECK_SIMPLE_VARIABLE("auto-low-priority", set_auto_low_priority, tr("0 or 1"));
4057 CHECK_SIMPLE_VARIABLE("segregate-pre-fork-outputs", set_segregate_pre_fork_outputs, tr("0 or 1"));
4058 CHECK_SIMPLE_VARIABLE("key-reuse-mitigation2", set_key_reuse_mitigation2, tr("0 or 1"));
4059 CHECK_SIMPLE_VARIABLE("subaddress-lookahead", set_subaddress_lookahead, tr("<major>:<minor>"));
4060 CHECK_SIMPLE_VARIABLE("segregation-height", set_segregation_height, tr("unsigned integer"));
4061 CHECK_SIMPLE_VARIABLE("ignore-fractional-outputs", set_ignore_fractional_outputs, tr("0 or 1"));
4062 CHECK_SIMPLE_VARIABLE("ignore-outputs-above", set_ignore_outputs_above, tr("amount"));
4063 CHECK_SIMPLE_VARIABLE("ignore-outputs-below", set_ignore_outputs_below, tr("amount"));
4064 CHECK_SIMPLE_VARIABLE("track-uses", set_track_uses, tr("0 or 1"));
4065 CHECK_SIMPLE_VARIABLE("background-sync", setup_background_sync, tr("off (default); reuse-wallet-password (reuse the wallet password to encrypt the background cache); custom-background-password (use a custom background password to encrypt the background cache)"));
4066 CHECK_SIMPLE_VARIABLE("show-wallet-name-when-locked", set_show_wallet_name_when_locked, tr("1 or 0"));
4067 CHECK_SIMPLE_VARIABLE("inactivity-lock-timeout", set_inactivity_lock_timeout, tr("unsigned integer (seconds, 0 to disable)"));
4068 CHECK_SIMPLE_VARIABLE("setup-background-mining", set_setup_background_mining, tr("1/yes or 0/no"));
4069 CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("<device_name[:device_spec]>"));
4070 CHECK_SIMPLE_VARIABLE("export-format", set_export_format, tr("\"binary\" or \"ascii\""));
4071 CHECK_SIMPLE_VARIABLE("load-deprecated-formats", set_load_deprecated_formats, tr("0 or 1"));
4072 CHECK_SIMPLE_VARIABLE("persistent-rpc-client-id", set_persistent_rpc_client_id, tr("0 or 1"));
4073 CHECK_SIMPLE_VARIABLE("auto-mine-for-rpc-payment-threshold", set_auto_mine_for_rpc_payment_threshold, tr("floating point >= 0"));
4074 CHECK_SIMPLE_VARIABLE("credits-target", set_credits_target, tr("unsigned integer"));
4075 CHECK_SIMPLE_VARIABLE("enable-multisig-experimental", set_enable_multisig, tr("0 or 1"));
4076 }
4077 fail_msg_writer() << tr("set: unrecognized argument(s)");
4078 return true;
4079 }
4080
4081 //----------------------------------------------------------------------------------------------------
4082 bool simple_wallet::set_log(const std::vector<std::string> &args)
4083 {
4084 if(args.size() > 1)
4085 {
4086 PRINT_USAGE(USAGE_SET_LOG);
4087 return true;
4088 }
4089 if(!args.empty())
4090 {
4091 uint16_t level = 0;
4092 if(epee::string_tools::get_xtype_from_string(level, args[0]))
4093 {
4094 if(4 < level)
4095 {
4096 fail_msg_writer() << boost::format(tr("wrong number range, use: %s")) % USAGE_SET_LOG;
4097 return true;
4098 }
4099 mlog_set_log_level(level);
4100 }
4101 else
4102 {
4103 mlog_set_log(args[0].c_str());
4104 }
4105 }
4106
4107 success_msg_writer() << "New log categories: " << mlog_get_categories();
4108 return true;
4109 }
4110 //----------------------------------------------------------------------------------------------------
4111 bool simple_wallet::ask_wallet_create_if_needed()
4112 {
4113 LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started");
4114 std::string wallet_path;
4115 std::string confirm_creation;
4116 bool wallet_name_valid = false;
4117 bool keys_file_exists;
4118 bool wallet_file_exists;
4119
4120 do{
4121 LOG_PRINT_L3("User asked to specify wallet file name.");
4122 wallet_path = input_line(
4123 tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n"
4124 "Wallet file name (or Ctrl-C to quit)" :
4125 "Specify wallet file name (e.g., MyWallet). If the wallet doesn't exist, it will be created.\n"
4126 "Wallet file name (or Ctrl-C to quit)")
4127 );
4128 if(std::cin.eof())
4129 {
4130 LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
4131 return false;
4132 }
4133 if(!tools::wallet2::wallet_valid_path_format(wallet_path))
4134 {
4135 fail_msg_writer() << tr("Wallet name not valid. Please try again or use Ctrl-C to quit.");
4136 wallet_name_valid = false;
4137 }
4138 else
4139 {
4140 tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists);
4141 LOG_PRINT_L3("wallet_path: " << wallet_path << "");
4142 LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
4143 << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
4144
4145 if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring))
4146 {
4147 fail_msg_writer() << tr("Attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting.");
4148 return false;
4149 }
4150 if(wallet_file_exists && keys_file_exists) //Yes wallet, yes keys
4151 {
4152 success_msg_writer() << tr("Wallet and key files found, loading...");
4153 m_wallet_file = wallet_path;
4154 return true;
4155 }
4156 else if(!wallet_file_exists && keys_file_exists) //No wallet, yes keys
4157 {
4158 success_msg_writer() << tr("Key file found but not wallet file. Regenerating...");
4159 m_wallet_file = wallet_path;
4160 return true;
4161 }
4162 else if(wallet_file_exists && !keys_file_exists) //Yes wallet, no keys
4163 {
4164 fail_msg_writer() << tr("Key file not found. Failed to open wallet: ") << "\"" << wallet_path << "\". Exiting.";
4165 return false;
4166 }
4167 else if(!wallet_file_exists && !keys_file_exists) //No wallet, no keys
4168 {
4169 bool ok = true;
4170 if (!m_restoring)
4171 {
4172 message_writer() << tr("No wallet found with that name. Confirm creation of new wallet named: ") << wallet_path;
4173 confirm_creation = input_line("", true);
4174 if(std::cin.eof())
4175 {
4176 LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
4177 return false;
4178 }
4179 ok = command_line::is_yes(confirm_creation);
4180 }
4181 if (ok)
4182 {
4183 success_msg_writer() << tr("Generating new wallet...");
4184 m_generate_new = wallet_path;
4185 return true;
4186 }
4187 }
4188 }
4189 } while(!wallet_name_valid);
4190
4191 LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()");
4192 return false;
4193 }
4194
4195 /*!
4196 * \brief Prints the seed with a nice message
4197 * \param seed seed to print
4198 */
4199 void simple_wallet::print_seed(const epee::wipeable_string &seed)
4200 {
4201 success_msg_writer(true) << "\n" << boost::format(tr("NOTE: the following %s can be used to recover access to your wallet. "
4202 "Write them down and store them somewhere safe and secure. Please do not store them in "
4203 "your email or on file storage services outside of your immediate control.\n")) % (m_wallet->multisig() ? tr("string") : tr("25 words"));
4204 // don't log
4205 int space_index = 0;
4206 size_t len = seed.size();
4207 for (const char *ptr = seed.data(); len--; ++ptr)
4208 {
4209 if (*ptr == ' ')
4210 {
4211 if (space_index == 15 || space_index == 7)
4212 putchar('\n');
4213 else
4214 putchar(*ptr);
4215 ++space_index;
4216 }
4217 else
4218 putchar(*ptr);
4219 }
4220 putchar('\n');
4221 fflush(stdout);
4222 }
4223 //----------------------------------------------------------------------------------------------------
4224 static bool might_be_partial_seed(const epee::wipeable_string &words)
4225 {
4226 std::vector<epee::wipeable_string> seed;
4227
4228 words.split(seed);
4229 return seed.size() < 24;
4230 }
4231 //----------------------------------------------------------------------------------------------------
4232 static bool datestr_to_int(const std::string &heightstr, uint16_t &year, uint8_t &month, uint8_t &day)
4233 {
4234 if (heightstr.size() != 10 || heightstr[4] != '-' || heightstr[7] != '-')
4235 {
4236 fail_msg_writer() << tr("date format must be YYYY-MM-DD");
4237 return false;
4238 }
4239 try
4240 {
4241 year = boost::lexical_cast<uint16_t>(heightstr.substr(0,4));
4242 // lexical_cast<uint8_t> won't work because uint8_t is treated as character type
4243 month = boost::lexical_cast<uint16_t>(heightstr.substr(5,2));
4244 day = boost::lexical_cast<uint16_t>(heightstr.substr(8,2));
4245 }
4246 catch (const boost::bad_lexical_cast &)
4247 {
4248 fail_msg_writer() << tr("bad height parameter: ") << heightstr;
4249 return false;
4250 }
4251 return true;
4252 }
4253 //----------------------------------------------------------------------------------------------------
4254 bool simple_wallet::init(const boost::program_options::variables_map& vm)
4255 {
4256 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
4257 m_electrum_seed.wipe();
4258 });
4259
4260 const bool testnet = tools::wallet2::has_testnet_option(vm);
4261 const bool stagenet = tools::wallet2::has_stagenet_option(vm);
4262 if (testnet && stagenet)
4263 {
4264 fail_msg_writer() << tr("Can't specify more than one of --testnet and --stagenet");
4265 return false;
4266 }
4267 const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET;
4268
4269 epee::wipeable_string multisig_keys;
4270 epee::wipeable_string password;
4271 epee::wipeable_string seed_pass;
4272
4273 if (!handle_command_line(vm))
4274 return false;
4275
4276 bool welcome = false;
4277
4278 if((!m_generate_new.empty()) + (!m_wallet_file.empty()) + (!m_generate_from_device.empty()) + (!m_generate_from_view_key.empty()) + (!m_generate_from_spend_key.empty()) + (!m_generate_from_keys.empty()) + (!m_generate_from_multisig_keys.empty()) + (!m_generate_from_json.empty()) > 1)
4279 {
4280 fail_msg_writer() << tr("can't specify more than one of --generate-new-wallet=\"wallet_name\", --wallet-file=\"wallet_name\", --generate-from-view-key=\"wallet_name\", --generate-from-spend-key=\"wallet_name\", --generate-from-keys=\"wallet_name\", --generate-from-multisig-keys=\"wallet_name\", --generate-from-json=\"jsonfilename\" and --generate-from-device=\"wallet_name\"");
4281 return false;
4282 }
4283 else if (m_generate_new.empty() && m_wallet_file.empty() && m_generate_from_device.empty() && m_generate_from_view_key.empty() && m_generate_from_spend_key.empty() && m_generate_from_keys.empty() && m_generate_from_multisig_keys.empty() && m_generate_from_json.empty())
4284 {
4285 if(!ask_wallet_create_if_needed()) return false;
4286 }
4287
4288 bool enable_multisig = false;
4289 if (m_restore_multisig_wallet) {
4290 fail_msg_writer() << tr("Multisig is disabled.");
4291 fail_msg_writer() << tr("Multisig is an experimental feature and may have bugs. Things that could go wrong include: funds sent to a multisig wallet can't be spent at all, can only be spent with the participation of a malicious group member, or can be stolen by a malicious group member.");
4292 if (!command_line::is_yes(input_line("Do you want to continue restoring a multisig wallet?", true))) {
4293 message_writer() << tr("You have canceled restoring a multisig wallet.");
4294 return false;
4295 }
4296 enable_multisig = true;
4297 }
4298
4299 if (!m_generate_new.empty() || m_restoring)
4300 {
4301 if (!m_subaddress_lookahead.empty() && !parse_subaddress_lookahead(m_subaddress_lookahead))
4302 return false;
4303
4304 std::string old_language;
4305 // check for recover flag. if present, require electrum word list (only recovery option for now).
4306 if (m_restore_deterministic_wallet || m_restore_multisig_wallet)
4307 {
4308 if (m_non_deterministic)
4309 {
4310 fail_msg_writer() << tr("can't specify both --restore-deterministic-wallet or --restore-multisig-wallet and --non-deterministic");
4311 return false;
4312 }
4313 if (!m_wallet_file.empty())
4314 {
4315 if (m_restore_multisig_wallet)
4316 fail_msg_writer() << tr("--restore-multisig-wallet uses --generate-new-wallet, not --wallet-file");
4317 else
4318 fail_msg_writer() << tr("--restore-deterministic-wallet uses --generate-new-wallet, not --wallet-file");
4319 return false;
4320 }
4321
4322 if (m_electrum_seed.empty())
4323 {
4324 if (m_restore_multisig_wallet)
4325 {
4326 const char *prompt = "Specify multisig seed";
4327 m_electrum_seed = input_secure_line(prompt);
4328 if (std::cin.eof())
4329 return false;
4330 if (m_electrum_seed.empty())
4331 {
4332 fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"multisig seed here\"");
4333 return false;
4334 }
4335 }
4336 else
4337 {
4338 m_electrum_seed = "";
4339 do
4340 {
4341 const char *prompt = m_electrum_seed.empty() ? "Specify Electrum seed" : "Electrum seed continued";
4342 epee::wipeable_string electrum_seed = input_secure_line(prompt);
4343 if (std::cin.eof())
4344 return false;
4345 if (electrum_seed.empty())
4346 {
4347 fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"words list here\"");
4348 return false;
4349 }
4350 m_electrum_seed += electrum_seed;
4351 m_electrum_seed += ' ';
4352 } while (might_be_partial_seed(m_electrum_seed));
4353 }
4354 }
4355
4356 if (m_restore_multisig_wallet)
4357 {
4358 const boost::optional<epee::wipeable_string> parsed = m_electrum_seed.parse_hexstr();
4359 if (!parsed)
4360 {
4361 fail_msg_writer() << tr("Multisig seed failed verification");
4362 return false;
4363 }
4364 multisig_keys = *parsed;
4365 }
4366 else
4367 {
4368 if (!crypto::ElectrumWords::words_to_bytes(m_electrum_seed, m_recovery_key, old_language))
4369 {
4370 fail_msg_writer() << tr("Electrum-style word list failed verification");
4371 return false;
4372 }
4373 }
4374
4375 auto pwd_container = password_prompter(tr("Enter seed offset passphrase, empty if none"), false);
4376 if (std::cin.eof() || !pwd_container)
4377 return false;
4378 seed_pass = pwd_container->password();
4379 if (!seed_pass.empty() && !m_restore_multisig_wallet)
4380 m_recovery_key = cryptonote::decrypt_key(m_recovery_key, seed_pass);
4381 }
4382 if (!m_generate_from_view_key.empty())
4383 {
4384 m_wallet_file = m_generate_from_view_key;
4385 // parse address
4386 std::string address_string = input_line("Standard address");
4387 if (std::cin.eof())
4388 return false;
4389 if (address_string.empty()) {
4390 fail_msg_writer() << tr("No data supplied, cancelled");
4391 return false;
4392 }
4393 cryptonote::address_parse_info info;
4394 if(!get_account_address_from_str(info, nettype, address_string))
4395 {
4396 fail_msg_writer() << tr("failed to parse address");
4397 return false;
4398 }
4399 if (info.is_subaddress)
4400 {
4401 fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
4402 return false;
4403 }
4404
4405 // parse view secret key
4406 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4407 if (std::cin.eof())
4408 return false;
4409 if (viewkey_string.empty()) {
4410 fail_msg_writer() << tr("No data supplied, cancelled");
4411 return false;
4412 }
4413 crypto::secret_key viewkey;
4414 if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4415 {
4416 fail_msg_writer() << tr("failed to parse view key secret key");
4417 return false;
4418 }
4419
4420 m_wallet_file=m_generate_from_view_key;
4421
4422 // check the view key matches the given address
4423 crypto::public_key pkey;
4424 if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
4425 fail_msg_writer() << tr("failed to verify view key secret key");
4426 return false;
4427 }
4428 if (info.address.m_view_public_key != pkey) {
4429 fail_msg_writer() << tr("view key does not match standard address");
4430 return false;
4431 }
4432
4433 auto r = new_wallet(vm, info.address, boost::none, viewkey);
4434 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4435 password = *r;
4436 welcome = true;
4437 }
4438 else if (!m_generate_from_spend_key.empty())
4439 {
4440 m_wallet_file = m_generate_from_spend_key;
4441 // parse spend secret key
4442 epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
4443 if (std::cin.eof())
4444 return false;
4445 if (spendkey_string.empty()) {
4446 fail_msg_writer() << tr("No data supplied, cancelled");
4447 return false;
4448 }
4449 if (!spendkey_string.hex_to_pod(unwrap(unwrap(m_recovery_key))))
4450 {
4451 fail_msg_writer() << tr("failed to parse spend key secret key");
4452 return false;
4453 }
4454 auto r = new_wallet(vm, m_recovery_key, true, false, "");
4455 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4456 password = *r;
4457 welcome = true;
4458 }
4459 else if (!m_generate_from_keys.empty())
4460 {
4461 m_wallet_file = m_generate_from_keys;
4462 // parse address
4463 std::string address_string = input_line("Standard address");
4464 if (std::cin.eof())
4465 return false;
4466 if (address_string.empty()) {
4467 fail_msg_writer() << tr("No data supplied, cancelled");
4468 return false;
4469 }
4470 cryptonote::address_parse_info info;
4471 if(!get_account_address_from_str(info, nettype, address_string))
4472 {
4473 fail_msg_writer() << tr("failed to parse address");
4474 return false;
4475 }
4476 if (info.is_subaddress)
4477 {
4478 fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
4479 return false;
4480 }
4481
4482 // parse spend secret key
4483 epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
4484 if (std::cin.eof())
4485 return false;
4486 if (spendkey_string.empty()) {
4487 fail_msg_writer() << tr("No data supplied, cancelled");
4488 return false;
4489 }
4490 crypto::secret_key spendkey;
4491 if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey))))
4492 {
4493 fail_msg_writer() << tr("failed to parse spend key secret key");
4494 return false;
4495 }
4496
4497 // parse view secret key
4498 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4499 if (std::cin.eof())
4500 return false;
4501 if (viewkey_string.empty()) {
4502 fail_msg_writer() << tr("No data supplied, cancelled");
4503 return false;
4504 }
4505 crypto::secret_key viewkey;
4506 if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4507 {
4508 fail_msg_writer() << tr("failed to parse view key secret key");
4509 return false;
4510 }
4511
4512 m_wallet_file=m_generate_from_keys;
4513
4514 // check the spend and view keys match the given address
4515 crypto::public_key pkey;
4516 if (!crypto::secret_key_to_public_key(spendkey, pkey)) {
4517 fail_msg_writer() << tr("failed to verify spend key secret key");
4518 return false;
4519 }
4520 if (info.address.m_spend_public_key != pkey) {
4521 fail_msg_writer() << tr("spend key does not match standard address");
4522 return false;
4523 }
4524 if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
4525 fail_msg_writer() << tr("failed to verify view key secret key");
4526 return false;
4527 }
4528 if (info.address.m_view_public_key != pkey) {
4529 fail_msg_writer() << tr("view key does not match standard address");
4530 return false;
4531 }
4532 auto r = new_wallet(vm, info.address, spendkey, viewkey);
4533 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4534 password = *r;
4535 welcome = true;
4536 }
4537
4538 // Asks user for all the data required to merge secret keys from multisig wallets into one master wallet, which then gets full control of the multisig wallet. The resulting wallet will be the same as any other regular wallet.
4539 else if (!m_generate_from_multisig_keys.empty())
4540 {
4541 m_wallet_file = m_generate_from_multisig_keys;
4542 unsigned int multisig_m;
4543 unsigned int multisig_n;
4544
4545 // parse multisig type
4546 std::string multisig_type_string = input_line("Multisig type (input as M/N with M <= N and M > 1)");
4547 if (std::cin.eof())
4548 return false;
4549 if (multisig_type_string.empty())
4550 {
4551 fail_msg_writer() << tr("No data supplied, cancelled");
4552 return false;
4553 }
4554 if (sscanf(multisig_type_string.c_str(), "%u/%u", &multisig_m, &multisig_n) != 2)
4555 {
4556 fail_msg_writer() << tr("Error: expected M/N, but got: ") << multisig_type_string;
4557 return false;
4558 }
4559 if (multisig_m <= 1 || multisig_m > multisig_n)
4560 {
4561 fail_msg_writer() << tr("Error: expected N > 1 and N <= M, but got: ") << multisig_type_string;
4562 return false;
4563 }
4564 if (multisig_m != multisig_n)
4565 {
4566 fail_msg_writer() << tr("Error: M/N is currently unsupported. ");
4567 return false;
4568 }
4569 message_writer() << boost::format(tr("Generating master wallet from %u of %u multisig wallet keys")) % multisig_m % multisig_n;
4570
4571 // parse multisig address
4572 std::string address_string = input_line("Multisig wallet address");
4573 if (std::cin.eof())
4574 return false;
4575 if (address_string.empty()) {
4576 fail_msg_writer() << tr("No data supplied, cancelled");
4577 return false;
4578 }
4579 cryptonote::address_parse_info info;
4580 if(!get_account_address_from_str(info, nettype, address_string))
4581 {
4582 fail_msg_writer() << tr("failed to parse address");
4583 return false;
4584 }
4585
4586 // parse secret view key
4587 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4588 if (std::cin.eof())
4589 return false;
4590 if (viewkey_string.empty())
4591 {
4592 fail_msg_writer() << tr("No data supplied, cancelled");
4593 return false;
4594 }
4595 crypto::secret_key viewkey;
4596 if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4597 {
4598 fail_msg_writer() << tr("failed to parse secret view key");
4599 return false;
4600 }
4601
4602 // check that the view key matches the given address
4603 crypto::public_key pkey;
4604 if (!crypto::secret_key_to_public_key(viewkey, pkey))
4605 {
4606 fail_msg_writer() << tr("failed to verify secret view key");
4607 return false;
4608 }
4609 if (info.address.m_view_public_key != pkey)
4610 {
4611 fail_msg_writer() << tr("view key does not match standard address");
4612 return false;
4613 }
4614
4615 // parse multisig spend keys
4616 crypto::secret_key spendkey;
4617 // parsing N/N
4618 if(multisig_m == multisig_n)
4619 {
4620 std::vector<crypto::secret_key> multisig_secret_spendkeys(multisig_n);
4621 epee::wipeable_string spendkey_string;
4622 cryptonote::blobdata spendkey_data;
4623 // get N secret spend keys from user
4624 for(unsigned int i=0; i<multisig_n; ++i)
4625 {
4626 spendkey_string = input_secure_line(tr((boost::format(tr("Secret spend key (%u of %u)")) % (i+1) % multisig_m).str().c_str()));
4627 if (std::cin.eof())
4628 return false;
4629 if (spendkey_string.empty())
4630 {
4631 fail_msg_writer() << tr("No data supplied, cancelled");
4632 return false;
4633 }
4634 if(!spendkey_string.hex_to_pod(unwrap(unwrap(multisig_secret_spendkeys[i]))))
4635 {
4636 fail_msg_writer() << tr("failed to parse spend key secret key");
4637 return false;
4638 }
4639 }
4640
4641 // sum the spend keys together to get the master spend key
4642 spendkey = multisig_secret_spendkeys[0];
4643 for(unsigned int i=1; i<multisig_n; ++i)
4644 sc_add(reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&multisig_secret_spendkeys[i]));
4645 }
4646 // parsing M/N
4647 else
4648 {
4649 fail_msg_writer() << tr("Error: M/N is currently unsupported");
4650 return false;
4651 }
4652
4653 // check that the spend key matches the given address
4654 if (!crypto::secret_key_to_public_key(spendkey, pkey))
4655 {
4656 fail_msg_writer() << tr("failed to verify spend key secret key");
4657 return false;
4658 }
4659 if (info.address.m_spend_public_key != pkey)
4660 {
4661 fail_msg_writer() << tr("spend key does not match standard address");
4662 return false;
4663 }
4664
4665 // create wallet
4666 auto r = new_wallet(vm, info.address, spendkey, viewkey);
4667 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4668 password = *r;
4669 welcome = true;
4670 }
4671
4672 else if (!m_generate_from_json.empty())
4673 {
4674 try
4675 {
4676 auto rc = tools::wallet2::make_from_json(vm, false, m_generate_from_json, password_prompter);
4677 m_wallet = std::move(rc.first);
4678 password = rc.second.password();
4679 m_wallet_file = m_wallet->path();
4680 }
4681 catch (const std::exception &e)
4682 {
4683 fail_msg_writer() << e.what();
4684 return false;
4685 }
4686 if (!m_wallet)
4687 return false;
4688 }
4689 else if (!m_generate_from_device.empty())
4690 {
4691 m_wallet_file = m_generate_from_device;
4692 // create wallet
4693 auto r = new_wallet(vm);
4694 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4695 password = *r;
4696 welcome = true;
4697 // if no block_height is specified, assume its a new account and start it "now"
4698 if (command_line::is_arg_defaulted(vm, arg_restore_height)) {
4699 {
4700 tools::scoped_message_writer wrt = tools::msg_writer();
4701 wrt << tr("No restore height is specified.") << " ";
4702 wrt << tr("Assumed you are creating a new account, restore will be done from current estimated blockchain height.") << " ";
4703 wrt << tr("Use --restore-height or --restore-date if you want to restore an already setup account from a specific height.");
4704 }
4705 std::string confirm = input_line(tr("Is this okay?"), true);
4706 if (std::cin.eof() || !command_line::is_yes(confirm))
4707 CHECK_AND_ASSERT_MES(false, false, tr("account creation aborted"));
4708
4709 m_wallet->set_refresh_from_block_height(m_wallet->estimate_blockchain_height() > 0 ? m_wallet->estimate_blockchain_height() - 1 : 0);
4710 m_wallet->explicit_refresh_from_block_height(true);
4711 m_restore_height = m_wallet->get_refresh_from_block_height();
4712 }
4713 }
4714 else
4715 {
4716 if (m_generate_new.empty()) {
4717 fail_msg_writer() << tr("specify a wallet path with --generate-new-wallet (not --wallet-file)");
4718 return false;
4719 }
4720 m_wallet_file = m_generate_new;
4721 boost::optional<epee::wipeable_string> r;
4722 if (m_restore_multisig_wallet)
4723 r = new_wallet(vm, multisig_keys, seed_pass, old_language);
4724 else
4725 r = new_wallet(vm, m_recovery_key, m_restore_deterministic_wallet, m_non_deterministic, old_language);
4726 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4727 password = *r;
4728 welcome = true;
4729 }
4730
4731 if (m_restoring && m_generate_from_json.empty() && m_generate_from_device.empty())
4732 {
4733 m_wallet->explicit_refresh_from_block_height(!(command_line::is_arg_defaulted(vm, arg_restore_height) &&
4734 command_line::is_arg_defaulted(vm, arg_restore_date)));
4735 if (command_line::is_arg_defaulted(vm, arg_restore_height) && !command_line::is_arg_defaulted(vm, arg_restore_date))
4736 {
4737 uint16_t year;
4738 uint8_t month;
4739 uint8_t day;
4740 if (!datestr_to_int(m_restore_date, year, month, day))
4741 return false;
4742 try
4743 {
4744 m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
4745 success_msg_writer() << tr("Restore height is: ") << m_restore_height;
4746 }
4747 catch (const std::runtime_error& e)
4748 {
4749 fail_msg_writer() << e.what();
4750 return false;
4751 }
4752 }
4753 }
4754 if (!m_wallet->explicit_refresh_from_block_height() && m_restoring)
4755 {
4756 uint32_t version;
4757 bool connected = try_connect_to_daemon(false, &version);
4758 while (true)
4759 {
4760 std::string heightstr;
4761 if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
4762 heightstr = input_line("Restore from specific blockchain height (optional, default 0)");
4763 else
4764 heightstr = input_line("Restore from specific blockchain height (optional, default 0),\nor alternatively from specific date (YYYY-MM-DD)");
4765 if (std::cin.eof())
4766 return false;
4767 if (heightstr.empty())
4768 {
4769 m_restore_height = 0;
4770 break;
4771 }
4772 try
4773 {
4774 m_restore_height = boost::lexical_cast<uint64_t>(heightstr);
4775 break;
4776 }
4777 catch (const boost::bad_lexical_cast &)
4778 {
4779 if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
4780 {
4781 fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
4782 continue;
4783 }
4784 uint16_t year;
4785 uint8_t month; // 1, 2, ..., 12
4786 uint8_t day; // 1, 2, ..., 31
4787 try
4788 {
4789 if (!datestr_to_int(heightstr, year, month, day))
4790 return false;
4791 m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
4792 success_msg_writer() << tr("Restore height is: ") << m_restore_height;
4793 std::string confirm = input_line(tr("Is this okay?"), true);
4794 if (std::cin.eof())
4795 return false;
4796 if(command_line::is_yes(confirm))
4797 break;
4798 }
4799 catch (const boost::bad_lexical_cast &)
4800 {
4801 fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
4802 }
4803 catch (const std::runtime_error& e)
4804 {
4805 fail_msg_writer() << e.what();
4806 }
4807 }
4808 }
4809 }
4810 if (m_restoring)
4811 {
4812 uint64_t estimate_height = m_wallet->estimate_blockchain_height();
4813 if (m_restore_height >= estimate_height)
4814 {
4815 success_msg_writer() << tr("Restore height ") << m_restore_height << (" is not yet reached. The current estimated height is ") << estimate_height;
4816 std::string confirm = input_line(tr("Still apply restore height?"), true);
4817 if (std::cin.eof() || command_line::is_no(confirm))
4818 m_restore_height = 0;
4819 }
4820 m_wallet->set_refresh_from_block_height(m_restore_height);
4821 }
4822 if (enable_multisig)
4823 m_wallet->enable_multisig(true);
4824 m_wallet->rewrite(m_wallet_file, password);
4825 }
4826 else
4827 {
4828 assert(!m_wallet_file.empty());
4829 if (!m_subaddress_lookahead.empty())
4830 {
4831 fail_msg_writer() << tr("can't specify --subaddress-lookahead and --wallet-file at the same time");
4832 return false;
4833 }
4834 auto r = open_wallet(vm);
4835 CHECK_AND_ASSERT_MES(r, false, tr("failed to open account"));
4836 password = *r;
4837 }
4838 if (!m_wallet)
4839 {
4840 fail_msg_writer() << tr("wallet is null");
4841 return false;
4842 }
4843
4844 if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key))
4845 {
4846 crypto::secret_key rpc_client_secret_key;
4847 if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), rpc_client_secret_key))
4848 {
4849 fail_msg_writer() << tr("RPC client secret key should be 32 byte in hex format");
4850 return false;
4851 }
4852 m_wallet->set_rpc_client_secret_key(rpc_client_secret_key);
4853 }
4854
4855 if (!m_wallet->is_trusted_daemon())
4856 {
4857 message_writer(console_color_red, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str();
4858 message_writer(console_color_red, true) << boost::format(tr("Using a third party daemon can be detrimental to your security and privacy"));
4859 bool ssl = false;
4860 if (m_wallet->check_connection(NULL, &ssl) && !ssl)
4861 message_writer(console_color_red, true) << boost::format(tr("Using your own without SSL exposes your RPC traffic to monitoring"));
4862 message_writer(console_color_red, true) << boost::format(tr("You are strongly encouraged to connect to the Monero network using your own daemon"));
4863 message_writer(console_color_red, true) << boost::format(tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon"));
4864
4865 COMMAND_RPC_GET_INFO::request req;
4866 COMMAND_RPC_GET_INFO::response res;
4867 bool r = m_wallet->invoke_http_json("/get_info", req, res);
4868 std::string err = interpret_rpc_response(r, res.status);
4869 if (r && err.empty() && (res.was_bootstrap_ever_used || !res.bootstrap_daemon_address.empty()))
4870 message_writer(console_color_red, true) << boost::format(tr("Moreover, a daemon is also less secure when running in bootstrap mode"));
4871 }
4872
4873 if (m_wallet->get_ring_database().empty())
4874 fail_msg_writer() << tr("Failed to initialize ring database: privacy enhancing features will be inactive");
4875
4876 m_wallet->callback(this);
4877
4878 bool skip_check_backround_mining = !command_line::get_arg(vm, arg_command).empty();
4879 if (!skip_check_backround_mining)
4880 check_background_mining(password);
4881
4882 if (welcome)
4883 message_writer(console_color_yellow, true) << tr("If you are new to Monero, type \"welcome\" for a brief overview.");
4884
4885 m_last_activity_time = time(NULL);
4886 return true;
4887 }
4888 //----------------------------------------------------------------------------------------------------
4889 bool simple_wallet::deinit()
4890 {
4891 if (!m_wallet.get())
4892 return true;
4893
4894 return close_wallet();
4895 }
4896 //----------------------------------------------------------------------------------------------------
4897 bool simple_wallet::handle_command_line(const boost::program_options::variables_map& vm)
4898 {
4899 m_wallet_file = command_line::get_arg(vm, arg_wallet_file);
4900 m_generate_new = command_line::get_arg(vm, arg_generate_new_wallet);
4901 m_generate_from_device = command_line::get_arg(vm, arg_generate_from_device);
4902 m_generate_from_view_key = command_line::get_arg(vm, arg_generate_from_view_key);
4903 m_generate_from_spend_key = command_line::get_arg(vm, arg_generate_from_spend_key);
4904 m_generate_from_keys = command_line::get_arg(vm, arg_generate_from_keys);
4905 m_generate_from_multisig_keys = command_line::get_arg(vm, arg_generate_from_multisig_keys);
4906 m_generate_from_json = command_line::get_arg(vm, arg_generate_from_json);
4907 m_mnemonic_language = command_line::get_arg(vm, arg_mnemonic_language);
4908 m_electrum_seed = command_line::get_arg(vm, arg_electrum_seed);
4909 m_restore_deterministic_wallet = command_line::get_arg(vm, arg_restore_deterministic_wallet) || command_line::get_arg(vm, arg_restore_from_seed);
4910 m_restore_multisig_wallet = command_line::get_arg(vm, arg_restore_multisig_wallet);
4911 m_non_deterministic = command_line::get_arg(vm, arg_non_deterministic);
4912 m_allow_mismatched_daemon_version = command_line::get_arg(vm, arg_allow_mismatched_daemon_version);
4913 m_restore_height = command_line::get_arg(vm, arg_restore_height);
4914 m_restore_date = command_line::get_arg(vm, arg_restore_date);
4915 m_do_not_relay = command_line::get_arg(vm, arg_do_not_relay);
4916 m_subaddress_lookahead = command_line::get_arg(vm, arg_subaddress_lookahead);
4917 m_use_english_language_names = command_line::get_arg(vm, arg_use_english_language_names);
4918 m_restoring = !m_generate_from_view_key.empty() ||
4919 !m_generate_from_spend_key.empty() ||
4920 !m_generate_from_keys.empty() ||
4921 !m_generate_from_multisig_keys.empty() ||
4922 !m_generate_from_json.empty() ||
4923 !m_generate_from_device.empty() ||
4924 m_restore_deterministic_wallet ||
4925 m_restore_multisig_wallet;
4926
4927 if (!command_line::is_arg_defaulted(vm, arg_restore_date))
4928 {
4929 uint16_t year;
4930 uint8_t month, day;
4931 if (!datestr_to_int(m_restore_date, year, month, day))
4932 return false;
4933 }
4934
4935 return true;
4936 }
4937 //----------------------------------------------------------------------------------------------------
4938 bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version)
4939 {
4940 uint32_t version_ = 0;
4941 if (!version)
4942 version = &version_;
4943 if (!m_wallet->check_connection(version))
4944 {
4945 if (!silent)
4946 {
4947 if (m_wallet->is_offline())
4948 fail_msg_writer() << tr("wallet failed to connect to daemon, because it is set to offline mode");
4949 else
4950 fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " <<
4951 tr("Daemon either is not started or wrong port was passed. "
4952 "Please make sure daemon is running or change the daemon address using the 'set_daemon' command.");
4953 }
4954 return false;
4955 }
4956 if (!m_allow_mismatched_daemon_version && ((*version >> 16) != CORE_RPC_VERSION_MAJOR))
4957 {
4958 if (!silent)
4959 fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (*version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address();
4960 return false;
4961 }
4962 return true;
4963 }
4964
4965 /*!
4966 * \brief Gets the word seed language from the user.
4967 *
4968 * User is asked to choose from a list of supported languages.
4969 *
4970 * \return The chosen language.
4971 */
4972 std::string simple_wallet::get_mnemonic_language()
4973 {
4974 std::vector<std::string> language_list_self, language_list_english;
4975 const std::vector<std::string> &language_list = m_use_english_language_names ? language_list_english : language_list_self;
4976 std::string language_choice;
4977 int language_number = -1;
4978 crypto::ElectrumWords::get_language_list(language_list_self, false);
4979 crypto::ElectrumWords::get_language_list(language_list_english, true);
4980 std::cout << tr("List of available languages for your wallet's seed:") << std::endl;
4981 std::cout << tr("If your display freezes, exit blind with ^C, then run again with --use-english-language-names") << std::endl;
4982 int ii;
4983 std::vector<std::string>::const_iterator it;
4984 for (it = language_list.begin(), ii = 0; it != language_list.end(); it++, ii++)
4985 {
4986 std::cout << ii << " : " << *it << std::endl;
4987 }
4988 while (language_number < 0)
4989 {
4990 language_choice = input_line(tr("Enter the number corresponding to the language of your choice"));
4991 if (std::cin.eof())
4992 return std::string();
4993 try
4994 {
4995 language_number = std::stoi(language_choice);
4996 if (!((language_number >= 0) && (static_cast<unsigned int>(language_number) < language_list.size())))
4997 {
4998 language_number = -1;
4999 fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
5000 }
5001 }
5002 catch (const std::exception &e)
5003 {
5004 fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
5005 }
5006 }
5007 return language_list_self[language_number];
5008 }
5009 //----------------------------------------------------------------------------------------------------
5010 boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const
5011 {
5012 const bool verify = m_wallet_file.empty();
5013 auto pwd_container = (m_wallet->is_background_wallet() && m_wallet->background_sync_type() == tools::wallet2::BackgroundSyncCustomPassword)
5014 ? background_sync_cache_password_prompter(verify)
5015 : default_password_prompter(verify);
5016 if (!pwd_container)
5017 return boost::none;
5018
5019 if (!m_wallet->verify_password(pwd_container->password()))
5020 {
5021 fail_msg_writer() << tr("invalid password");
5022 return boost::none;
5023 }
5024 return pwd_container;
5025 }
5026 //----------------------------------------------------------------------------------------------------
5027 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5028 const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language)
5029 {
5030 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5031 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5032 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5033 m_wallet = std::move(rc.first);
5034 if (!m_wallet)
5035 {
5036 return {};
5037 }
5038 epee::wipeable_string password = rc.second.password();
5039
5040 if (!m_subaddress_lookahead.empty())
5041 {
5042 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5043 assert(lookahead);
5044 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5045 }
5046
5047 bool was_deprecated_wallet = m_restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) ||
5048 crypto::ElectrumWords::get_is_old_style_seed(m_electrum_seed));
5049
5050 std::string mnemonic_language = old_language;
5051
5052 std::vector<std::string> language_list;
5053 crypto::ElectrumWords::get_language_list(language_list);
5054 if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
5055 {
5056 mnemonic_language = m_mnemonic_language;
5057 }
5058
5059 // Ask for seed language if:
5060 // it's a deterministic wallet AND
5061 // a seed language is not already specified AND
5062 // (it is not a wallet restore OR if it was a deprecated wallet
5063 // that was earlier used before this restore)
5064 if ((!two_random) && (mnemonic_language.empty() || mnemonic_language == crypto::ElectrumWords::old_language_name) && (!m_restore_deterministic_wallet || was_deprecated_wallet))
5065 {
5066 if (was_deprecated_wallet)
5067 {
5068 // The user had used an older version of the wallet with old style mnemonics.
5069 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5070 "a deprecated version of the wallet. Please use the new seed that we provide.\n");
5071 }
5072 mnemonic_language = get_mnemonic_language();
5073 if (mnemonic_language.empty())
5074 return {};
5075 }
5076
5077 m_wallet->set_seed_language(mnemonic_language);
5078
5079 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5080
5081 crypto::secret_key recovery_val;
5082 try
5083 {
5084 recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file);
5085 message_writer(console_color_white, true) << tr("Generated new wallet: ")
5086 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5087 PAUSE_READLINE();
5088 std::cout << tr("View key: ");
5089 print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
5090 putchar('\n');
5091 }
5092 catch (const std::exception& e)
5093 {
5094 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5095 return {};
5096 }
5097
5098 // convert rng value to electrum-style word list
5099 epee::wipeable_string electrum_words;
5100
5101 crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language);
5102
5103 success_msg_writer() <<
5104 "**********************************************************************\n" <<
5105 tr("Your wallet has been generated!\n"
5106 "To start synchronizing with the daemon, use the \"refresh\" command.\n"
5107 "Use the \"help\" command to see a simplified list of available commands.\n"
5108 "Use \"help all\" command to see the list of all available commands.\n"
5109 "Use \"help <command>\" to see a command's documentation.\n"
5110 "Always use the \"exit\" command when closing monero-wallet-cli to save \n"
5111 "your current session's state. Otherwise, you might need to synchronize \n"
5112 "your wallet again (your wallet keys are NOT at risk in any case).\n")
5113 ;
5114
5115 if (!two_random)
5116 {
5117 print_seed(electrum_words);
5118 }
5119 success_msg_writer() << "**********************************************************************";
5120
5121 return password;
5122 }
5123 //----------------------------------------------------------------------------------------------------
5124 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5125 const cryptonote::account_public_address& address, const boost::optional<crypto::secret_key>& spendkey,
5126 const crypto::secret_key& viewkey)
5127 {
5128 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5129 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5130 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5131 m_wallet = std::move(rc.first);
5132 if (!m_wallet)
5133 {
5134 return {};
5135 }
5136 epee::wipeable_string password = rc.second.password();
5137
5138 if (!m_subaddress_lookahead.empty())
5139 {
5140 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5141 assert(lookahead);
5142 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5143 }
5144
5145 if (m_restore_height)
5146 m_wallet->set_refresh_from_block_height(m_restore_height);
5147
5148 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5149
5150 try
5151 {
5152 if (spendkey)
5153 {
5154 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, *spendkey, viewkey, create_address_file);
5155 }
5156 else
5157 {
5158 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file);
5159 }
5160 message_writer(console_color_white, true) << tr("Generated new wallet: ")
5161 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5162 }
5163 catch (const std::exception& e)
5164 {
5165 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5166 return {};
5167 }
5168
5169
5170 return password;
5171 }
5172
5173 //----------------------------------------------------------------------------------------------------
5174 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm)
5175 {
5176 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5177 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5178 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5179 m_wallet = std::move(rc.first);
5180 m_wallet->callback(this);
5181 if (!m_wallet)
5182 {
5183 return {};
5184 }
5185 epee::wipeable_string password = rc.second.password();
5186
5187 if (!m_subaddress_lookahead.empty())
5188 {
5189 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5190 assert(lookahead);
5191 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5192 }
5193
5194 if (m_restore_height)
5195 m_wallet->set_refresh_from_block_height(m_restore_height);
5196
5197 auto device_desc = tools::wallet2::device_name_option(vm);
5198 auto device_derivation_path = tools::wallet2::device_derivation_path_option(vm);
5199 try
5200 {
5201 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5202 m_wallet->device_derivation_path(device_derivation_path);
5203 m_wallet->restore(m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file);
5204 message_writer(console_color_white, true) << tr("Generated new wallet on hw device: ")
5205 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5206 }
5207 catch (const std::exception& e)
5208 {
5209 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5210 return {};
5211 }
5212
5213 return password;
5214 }
5215 //----------------------------------------------------------------------------------------------------
5216 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5217 const epee::wipeable_string &multisig_keys, const epee::wipeable_string &seed_pass, const std::string &old_language)
5218 {
5219 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5220 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5221 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5222 m_wallet = std::move(rc.first);
5223 if (!m_wallet)
5224 {
5225 return {};
5226 }
5227 epee::wipeable_string password = rc.second.password();
5228
5229 if (!m_subaddress_lookahead.empty())
5230 {
5231 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5232 assert(lookahead);
5233 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5234 }
5235
5236 std::string mnemonic_language = old_language;
5237
5238 std::vector<std::string> language_list;
5239 crypto::ElectrumWords::get_language_list(language_list);
5240 if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
5241 {
5242 mnemonic_language = m_mnemonic_language;
5243 }
5244
5245 m_wallet->set_seed_language(mnemonic_language);
5246
5247 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5248
5249 try
5250 {
5251 if (seed_pass.empty())
5252 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), multisig_keys, create_address_file);
5253 else
5254 {
5255 crypto::secret_key key;
5256 crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key);
5257 sc_reduce32((unsigned char*)key.data);
5258 const epee::wipeable_string &msig_keys = m_wallet->decrypt<epee::wipeable_string>(std::string(multisig_keys.data(), multisig_keys.size()), key, true);
5259 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), msig_keys, create_address_file);
5260 }
5261 bool ready;
5262 uint32_t threshold, total;
5263 if (!m_wallet->multisig(&ready, &threshold, &total) || !ready)
5264 {
5265 fail_msg_writer() << tr("failed to generate new mutlisig wallet");
5266 return {};
5267 }
5268 message_writer(console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total
5269 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5270 }
5271 catch (const std::exception& e)
5272 {
5273 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5274 return {};
5275 }
5276
5277 return password;
5278 }
5279 //----------------------------------------------------------------------------------------------------
5280 boost::optional<epee::wipeable_string> simple_wallet::open_wallet(const boost::program_options::variables_map& vm)
5281 {
5282 if (!tools::wallet2::wallet_valid_path_format(m_wallet_file))
5283 {
5284 fail_msg_writer() << tr("wallet file path not valid: ") << m_wallet_file;
5285 return {};
5286 }
5287
5288 bool keys_file_exists;
5289 bool wallet_file_exists;
5290
5291 tools::wallet2::wallet_exists(m_wallet_file, keys_file_exists, wallet_file_exists);
5292 if(!keys_file_exists)
5293 {
5294 fail_msg_writer() << tr("Key file not found. Failed to open wallet");
5295 return {};
5296 }
5297
5298 epee::wipeable_string password;
5299 try
5300 {
5301 auto rc = tools::wallet2::make_from_file(vm, false, "", password_prompter);
5302 m_wallet = std::move(rc.first);
5303 password = std::move(std::move(rc.second).password());
5304 if (!m_wallet)
5305 {
5306 return {};
5307 }
5308
5309 m_wallet->callback(this);
5310 m_wallet->load(m_wallet_file, password);
5311 std::string prefix;
5312 bool ready;
5313 uint32_t threshold, total;
5314 if (m_wallet->watch_only())
5315 prefix = tr("Opened watch-only wallet");
5316 else if (m_wallet->multisig(&ready, &threshold, &total))
5317 prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
5318 else if (m_wallet->is_background_wallet())
5319 prefix = tr("Opened background wallet");
5320 else
5321 prefix = tr("Opened wallet");
5322 message_writer(console_color_white, true) <<
5323 prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5324 if (m_wallet->get_account().get_device()) {
5325 message_writer(console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name();
5326 }
5327 // If the wallet file is deprecated, we should ask for mnemonic language again and store
5328 // everything in the new format.
5329 // NOTE: this is_deprecated() refers to the wallet file format before becoming JSON. It does not refer to the "old english" seed words form of "deprecated" used elsewhere.
5330 if (m_wallet->is_deprecated())
5331 {
5332 bool is_deterministic;
5333 {
5334 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return {};);
5335 is_deterministic = m_wallet->is_deterministic();
5336 }
5337 if (is_deterministic)
5338 {
5339 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5340 "a deprecated version of the wallet. Please proceed to upgrade your wallet.\n");
5341 std::string mnemonic_language = get_mnemonic_language();
5342 if (mnemonic_language.empty())
5343 return {};
5344 m_wallet->set_seed_language(mnemonic_language);
5345 m_wallet->rewrite(m_wallet_file, password);
5346
5347 // Display the seed
5348 epee::wipeable_string seed;
5349 m_wallet->get_seed(seed);
5350 print_seed(seed);
5351 }
5352 else
5353 {
5354 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5355 "a deprecated version of the wallet. Your wallet file format is being upgraded now.\n");
5356 m_wallet->rewrite(m_wallet_file, password);
5357 }
5358 }
5359 }
5360 catch (const std::exception& e)
5361 {
5362 fail_msg_writer() << tr("failed to load wallet: ") << e.what();
5363 if (m_wallet)
5364 {
5365 // only suggest removing cache if the password was actually correct
5366 bool password_is_correct = false;
5367 try
5368 {
5369 password_is_correct = m_wallet->verify_password(password);
5370 }
5371 catch (...) { } // guard against I/O errors
5372 if (password_is_correct)
5373 fail_msg_writer() << boost::format(tr("You may want to remove the file \"%s\" and try again")) % m_wallet_file;
5374 }
5375 return {};
5376 }
5377 success_msg_writer() <<
5378 "**********************************************************************\n" <<
5379 tr("Use the \"help\" command to see a simplified list of available commands.\n") <<
5380 tr("Use \"help all\" to see the list of all available commands.\n") <<
5381 tr("Use \"help <command>\" to see a command's documentation.\n") <<
5382 "**********************************************************************";
5383 return password;
5384 }
5385 //----------------------------------------------------------------------------------------------------
5386 bool simple_wallet::close_wallet()
5387 {
5388 if (m_idle_run.load(std::memory_order_relaxed))
5389 {
5390 m_idle_run.store(false, std::memory_order_relaxed);
5391 m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed);
5392 m_wallet->stop();
5393 {
5394 boost::unique_lock<boost::mutex> lock(m_idle_mutex);
5395 m_idle_cond.notify_one();
5396 }
5397 m_idle_thread.join();
5398 }
5399
5400 bool r = m_wallet->deinit();
5401 if (!r)
5402 {
5403 fail_msg_writer() << tr("failed to deinitialize wallet");
5404 return false;
5405 }
5406
5407 try
5408 {
5409 m_wallet->store();
5410 }
5411 catch (const std::exception& e)
5412 {
5413 fail_msg_writer() << e.what();
5414 return false;
5415 }
5416
5417 return true;
5418 }
5419 //----------------------------------------------------------------------------------------------------
5420 bool simple_wallet::save(const std::vector<std::string> &args)
5421 {
5422 try
5423 {
5424 LOCK_IDLE_SCOPE();
5425 m_wallet->store();
5426 success_msg_writer() << tr("Wallet data saved");
5427 }
5428 catch (const std::exception& e)
5429 {
5430 fail_msg_writer() << e.what();
5431 }
5432
5433 return true;
5434 }
5435 //----------------------------------------------------------------------------------------------------
5436 bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
5437 {
5438 if (m_wallet->multisig())
5439 {
5440 fail_msg_writer() << tr("wallet is multisig and cannot save a watch-only version");
5441 return true;
5442 }
5443
5444 const auto pwd_container = password_prompter(tr("Password for new watch-only wallet"), true);
5445
5446 if (!pwd_container)
5447 {
5448 fail_msg_writer() << tr("failed to read wallet password");
5449 return true;
5450 }
5451
5452 try
5453 {
5454 std::string new_keys_filename;
5455 m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password(), new_keys_filename);
5456 success_msg_writer() << tr("Watch only wallet saved as: ") << new_keys_filename;
5457 }
5458 catch (const std::exception &e)
5459 {
5460 fail_msg_writer() << tr("Failed to save watch only wallet: ") << e.what();
5461 return true;
5462 }
5463 return true;
5464 }
5465 //----------------------------------------------------------------------------------------------------
5466 void simple_wallet::start_background_mining()
5467 {
5468 COMMAND_RPC_MINING_STATUS::request reqq;
5469 COMMAND_RPC_MINING_STATUS::response resq;
5470 bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
5471 std::string err = interpret_rpc_response(r, resq.status);
5472 if (!r)
5473 return;
5474 if (!err.empty())
5475 {
5476 fail_msg_writer() << tr("Failed to query mining status: ") << err;
5477 return;
5478 }
5479 if (!resq.is_background_mining_enabled)
5480 {
5481 COMMAND_RPC_START_MINING::request req;
5482 COMMAND_RPC_START_MINING::response res;
5483 req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5484 req.threads_count = 1;
5485 req.do_background_mining = true;
5486 req.ignore_battery = false;
5487 bool r = m_wallet->invoke_http_json("/start_mining", req, res);
5488 std::string err = interpret_rpc_response(r, res.status);
5489 if (!err.empty())
5490 {
5491 fail_msg_writer() << tr("Failed to setup background mining: ") << err;
5492 return;
5493 }
5494 }
5495 success_msg_writer() << tr("Background mining enabled. Thank you for supporting the Monero network.");
5496 }
5497 //----------------------------------------------------------------------------------------------------
5498 void simple_wallet::stop_background_mining()
5499 {
5500 COMMAND_RPC_MINING_STATUS::request reqq;
5501 COMMAND_RPC_MINING_STATUS::response resq;
5502 bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
5503 if (!r)
5504 return;
5505 std::string err = interpret_rpc_response(r, resq.status);
5506 if (!err.empty())
5507 {
5508 fail_msg_writer() << tr("Failed to query mining status: ") << err;
5509 return;
5510 }
5511 if (resq.is_background_mining_enabled)
5512 {
5513 COMMAND_RPC_STOP_MINING::request req;
5514 COMMAND_RPC_STOP_MINING::response res;
5515 bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
5516 std::string err = interpret_rpc_response(r, res.status);
5517 if (!err.empty())
5518 {
5519 fail_msg_writer() << tr("Failed to setup background mining: ") << err;
5520 return;
5521 }
5522 }
5523 message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
5524 }
5525 //----------------------------------------------------------------------------------------------------
5526 void simple_wallet::check_background_mining(const epee::wipeable_string &password)
5527 {
5528 // Background mining can be toggled from the main wallet
5529 if (m_wallet->is_background_wallet() || m_wallet->is_background_syncing())
5530 return;
5531
5532 tools::wallet2::BackgroundMiningSetupType setup = m_wallet->setup_background_mining();
5533 if (setup == tools::wallet2::BackgroundMiningNo)
5534 {
5535 message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
5536 return;
5537 }
5538
5539 if (!m_wallet->is_trusted_daemon())
5540 {
5541 message_writer() << tr("Using an untrusted daemon, skipping background mining check");
5542 return;
5543 }
5544
5545 COMMAND_RPC_MINING_STATUS::request req;
5546 COMMAND_RPC_MINING_STATUS::response res;
5547 bool r = m_wallet->invoke_http_json("/mining_status", req, res);
5548 std::string err = interpret_rpc_response(r, res.status);
5549 bool is_background_mining_enabled = false;
5550 if (err.empty())
5551 is_background_mining_enabled = res.is_background_mining_enabled;
5552
5553 if (is_background_mining_enabled)
5554 {
5555 // already active, nice
5556 if (setup == tools::wallet2::BackgroundMiningMaybe)
5557 {
5558 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
5559 m_wallet->rewrite(m_wallet_file, password);
5560 }
5561 start_background_mining();
5562 return;
5563 }
5564 if (res.active)
5565 return;
5566
5567 if (setup == tools::wallet2::BackgroundMiningMaybe)
5568 {
5569 message_writer() << tr("The daemon is not set up to background mine.");
5570 message_writer() << tr("With background mining enabled, the daemon will mine when idle and not on battery.");
5571 message_writer() << tr("Enabling this supports the network you are using, and makes you eligible for receiving new monero");
5572 std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
5573 if (std::cin.eof() || !command_line::is_yes(accepted)) {
5574 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningNo);
5575 m_wallet->rewrite(m_wallet_file, password);
5576 message_writer(console_color_red, false) << tr("Background mining not enabled. Set setup-background-mining to 1 to change.");
5577 return;
5578 }
5579 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
5580 m_wallet->rewrite(m_wallet_file, password);
5581 start_background_mining();
5582 }
5583 else
5584 {
5585 // the setting is already enabled, and the daemon is not mining yet, so start it
5586 start_background_mining();
5587 }
5588 }
5589 //----------------------------------------------------------------------------------------------------
5590 bool simple_wallet::start_mining(const std::vector<std::string>& args)
5591 {
5592 if (!m_wallet->is_trusted_daemon())
5593 {
5594 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
5595 return true;
5596 }
5597
5598 if (!try_connect_to_daemon())
5599 return true;
5600
5601 if (!m_wallet)
5602 {
5603 fail_msg_writer() << tr("wallet is null");
5604 return true;
5605 }
5606 COMMAND_RPC_START_MINING::request req = AUTO_VAL_INIT(req);
5607 req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5608
5609 bool ok = true;
5610 size_t arg_size = args.size();
5611 if(arg_size >= 3)
5612 {
5613 if (!parse_bool_and_use(args[2], [&](bool r) { req.ignore_battery = r; }))
5614 return true;
5615 }
5616 if(arg_size >= 2)
5617 {
5618 if (!parse_bool_and_use(args[1], [&](bool r) { req.do_background_mining = r; }))
5619 return true;
5620 }
5621 if(arg_size >= 1)
5622 {
5623 uint16_t num = 1;
5624 ok = string_tools::get_xtype_from_string(num, args[0]);
5625 ok = ok && 1 <= num;
5626 req.threads_count = num;
5627 }
5628 else
5629 {
5630 req.threads_count = 1;
5631 }
5632
5633 if (!ok)
5634 {
5635 PRINT_USAGE(USAGE_START_MINING);
5636 return true;
5637 }
5638
5639 COMMAND_RPC_START_MINING::response res;
5640 bool r = m_wallet->invoke_http_json("/start_mining", req, res);
5641 std::string err = interpret_rpc_response(r, res.status);
5642 if (err.empty())
5643 success_msg_writer() << tr("Mining started in daemon");
5644 else
5645 fail_msg_writer() << tr("mining has NOT been started: ") << err;
5646 return true;
5647 }
5648 //----------------------------------------------------------------------------------------------------
5649 bool simple_wallet::stop_mining(const std::vector<std::string>& args)
5650 {
5651 if (!try_connect_to_daemon())
5652 return true;
5653
5654 if (!m_wallet)
5655 {
5656 fail_msg_writer() << tr("wallet is null");
5657 return true;
5658 }
5659
5660 COMMAND_RPC_STOP_MINING::request req;
5661 COMMAND_RPC_STOP_MINING::response res;
5662 bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
5663 std::string err = interpret_rpc_response(r, res.status);
5664 if (err.empty())
5665 success_msg_writer() << tr("Mining stopped in daemon");
5666 else
5667 fail_msg_writer() << tr("mining has NOT been stopped: ") << err;
5668 return true;
5669 }
5670 //----------------------------------------------------------------------------------------------------
5671 bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph)
5672 {
5673 try
5674 {
5675 auto i = m_claimed_cph.find(daemon_url);
5676 if (i == m_claimed_cph.end())
5677 return false;
5678
5679 claimed_cph = m_claimed_cph[daemon_url];
5680 bool payment_required;
5681 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
5682 uint32_t cookie;
5683 cryptonote::blobdata hashing_blob;
5684 crypto::hash seed_hash, next_seed_hash;
5685 if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie) && payment_required)
5686 {
5687 actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff);
5688 return true;
5689 }
5690 else
5691 {
5692 fail_msg_writer() << tr("Error checking daemon RPC access prices");
5693 }
5694 }
5695 catch (const std::exception &e)
5696 {
5697 // can't check
5698 fail_msg_writer() << tr("Error checking daemon RPC access prices: ") << e.what();
5699 return false;
5700 }
5701 // no record found for this daemon
5702 return false;
5703 }
5704 //----------------------------------------------------------------------------------------------------
5705 bool simple_wallet::set_daemon(const std::vector<std::string>& args)
5706 {
5707 std::string daemon_url;
5708
5709 if (args.size() < 1)
5710 {
5711 PRINT_USAGE(USAGE_SET_DAEMON);
5712 return true;
5713 }
5714
5715 boost::regex rgx("^(.*://)?([A-Za-z0-9\\-\\.]+)(:[0-9]+)?");
5716 boost::cmatch match;
5717 // If user input matches URL regex
5718 if (boost::regex_match(args[0].c_str(), match, rgx))
5719 {
5720 if (match.length() < 4)
5721 {
5722 fail_msg_writer() << tr("Unexpected array length - Exited simple_wallet::set_daemon()");
5723 return true;
5724 }
5725 // If no port has been provided, use the default from config
5726 if (!match[3].length())
5727 {
5728 uint16_t daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT;
5729 daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port);
5730 } else {
5731 daemon_url = args[0];
5732 }
5733
5734 epee::net_utils::http::url_content parsed{};
5735 const bool r = epee::net_utils::parse_url(daemon_url, parsed);
5736 if (!r)
5737 {
5738 fail_msg_writer() << tr("Failed to parse address");
5739 return true;
5740 }
5741
5742 std::string trusted;
5743 if (args.size() == 2)
5744 {
5745 if (args[1] == "trusted")
5746 trusted = "trusted";
5747 else if (args[1] == "untrusted")
5748 trusted = "untrusted";
5749 else if (args[1] == "this-is-probably-a-spy-node")
5750 trusted = "this-is-probably-a-spy-node";
5751 else
5752 {
5753 fail_msg_writer() << tr("Expected trusted, untrusted or this-is-probably-a-spy-node got ") << args[1];
5754 return true;
5755 }
5756 }
5757
5758 if (!tools::is_privacy_preserving_network(parsed.host) && !tools::is_local_address(parsed.host))
5759 {
5760 if (trusted == "untrusted" || trusted == "")
5761 {
5762 fail_msg_writer() << tr("This is not Tor/I2P address, and is not a trusted daemon.");
5763 fail_msg_writer() << tr("Either use your own trusted node, connect via Tor or I2P, or pass this-is-probably-a-spy-node and be spied on.");
5764 return true;
5765 }
5766
5767 if (parsed.schema != "https")
5768 message_writer(console_color_red) << tr("Warning: connecting to a non-local daemon without SSL, passive adversaries will be able to spy on you.");
5769 }
5770
5771 LOCK_IDLE_SCOPE();
5772 m_wallet->init(daemon_url);
5773
5774 if (!trusted.empty())
5775 {
5776 m_wallet->set_trusted_daemon(trusted == "trusted");
5777 }
5778 else
5779 {
5780 m_wallet->set_trusted_daemon(false);
5781 try
5782 {
5783 if (tools::is_local_address(m_wallet->get_daemon_address()))
5784 {
5785 MINFO(tr("Daemon is local, assuming trusted"));
5786 m_wallet->set_trusted_daemon(true);
5787 }
5788 }
5789 catch (const std::exception &e) { }
5790 }
5791
5792 if (!try_connect_to_daemon())
5793 {
5794 fail_msg_writer() << tr("Failed to connect to daemon");
5795 return true;
5796 }
5797
5798 success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted"));
5799
5800 // check whether the daemon's prices match the claim, and disconnect if not, to disincentivize daemons lying
5801 uint32_t actual_cph, claimed_cph;
5802 if (check_daemon_rpc_prices(daemon_url, actual_cph, claimed_cph))
5803 {
5804 if (actual_cph < claimed_cph)
5805 {
5806 fail_msg_writer() << tr("Daemon RPC credits/hash is less than was claimed. Either this daemon is cheating, or it changed its setup recently.");
5807 fail_msg_writer() << tr("Claimed: ") << claimed_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
5808 fail_msg_writer() << tr("Actual: ") << actual_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
5809 }
5810 }
5811
5812 m_daemon_rpc_payment_message_displayed = false;
5813 } else {
5814 fail_msg_writer() << tr("This does not seem to be a valid daemon URL.");
5815 }
5816 return true;
5817 }
5818 //----------------------------------------------------------------------------------------------------
5819 bool simple_wallet::save_bc(const std::vector<std::string>& args)
5820 {
5821 if (!try_connect_to_daemon())
5822 return true;
5823
5824 if (!m_wallet)
5825 {
5826 fail_msg_writer() << tr("wallet is null");
5827 return true;
5828 }
5829 COMMAND_RPC_SAVE_BC::request req;
5830 COMMAND_RPC_SAVE_BC::response res;
5831 bool r = m_wallet->invoke_http_json("/save_bc", req, res);
5832 std::string err = interpret_rpc_response(r, res.status);
5833 if (err.empty())
5834 success_msg_writer() << tr("Blockchain saved");
5835 else
5836 fail_msg_writer() << tr("blockchain can't be saved: ") << err;
5837 return true;
5838 }
5839 //----------------------------------------------------------------------------------------------------
5840 void simple_wallet::on_new_block(uint64_t height, const cryptonote::block& block)
5841 {
5842 if (m_locked)
5843 return;
5844 if (!m_auto_refresh_refreshing)
5845 m_refresh_progress_reporter.update(height, false);
5846 }
5847 //----------------------------------------------------------------------------------------------------
5848 void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, uint64_t burnt, const cryptonote::subaddress_index& subaddr_index, bool is_change, uint64_t unlock_time)
5849 {
5850 if (m_locked)
5851 return;
5852 std::stringstream burn;
5853 if (burnt != 0) {
5854 burn << " (" << print_money(amount) << " yet " << print_money(burnt) << " was burnt)";
5855 }
5856 message_writer(console_color_green, false) << "\r" <<
5857 tr("Height ") << height << ", " <<
5858 tr("txid ") << txid << ", " <<
5859 print_money(amount - burnt) << burn.str() << ", " <<
5860 tr("idx ") << subaddr_index;
5861
5862 const uint64_t warn_height = m_wallet->nettype() == TESTNET ? 1000000 : m_wallet->nettype() == STAGENET ? 50000 : 1650000;
5863 if (height >= warn_height && !is_change)
5864 {
5865 std::vector<tx_extra_field> tx_extra_fields;
5866 parse_tx_extra(tx.extra, tx_extra_fields); // failure ok
5867 tx_extra_nonce extra_nonce;
5868 tx_extra_pub_key extra_pub_key;
5869 crypto::hash8 payment_id8 = crypto::null_hash8;
5870 if (find_tx_extra_field_by_type(tx_extra_fields, extra_pub_key))
5871 {
5872 const crypto::public_key &tx_pub_key = extra_pub_key.pub_key;
5873 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
5874 {
5875 if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
5876 {
5877 m_wallet->get_account().get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_wallet->get_account().get_keys().m_view_secret_key);
5878 }
5879 }
5880 }
5881
5882 if (payment_id8 != crypto::null_hash8)
5883 message_writer() <<
5884 tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead");
5885
5886 crypto::hash payment_id = crypto::null_hash;
5887 if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
5888 message_writer(console_color_red, false) <<
5889 tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead.");
5890 }
5891 if (unlock_time && !cryptonote::is_coinbase(tx))
5892 message_writer() << tr("NOTE: This transaction is locked, see details with: show_transfer ") + epee::string_tools::pod_to_hex(txid);
5893 if (m_auto_refresh_refreshing)
5894 m_cmd_binder.print_prompt();
5895 else
5896 m_refresh_progress_reporter.update(height, true);
5897 }
5898 //----------------------------------------------------------------------------------------------------
5899 void simple_wallet::on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index)
5900 {
5901 if (m_locked)
5902 return;
5903 // Not implemented in CLI wallet
5904 }
5905 //----------------------------------------------------------------------------------------------------
5906 void simple_wallet::on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx, uint64_t amount, const cryptonote::transaction& spend_tx, const cryptonote::subaddress_index& subaddr_index)
5907 {
5908 if (m_locked)
5909 return;
5910 message_writer(console_color_magenta, false) << "\r" <<
5911 tr("Height ") << height << ", " <<
5912 tr("txid ") << txid << ", " <<
5913 tr("spent ") << print_money(amount) << ", " <<
5914 tr("idx ") << subaddr_index;
5915 if (m_auto_refresh_refreshing)
5916 m_cmd_binder.print_prompt();
5917 else
5918 m_refresh_progress_reporter.update(height, true);
5919 }
5920 //----------------------------------------------------------------------------------------------------
5921 void simple_wallet::on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx)
5922 {
5923 if (m_locked)
5924 return;
5925 }
5926 //----------------------------------------------------------------------------------------------------
5927 boost::optional<epee::wipeable_string> simple_wallet::on_get_password(const char *reason)
5928 {
5929 if (m_locked)
5930 return boost::none;
5931 // can't ask for password from a background thread
5932 if (!m_in_manual_refresh.load(std::memory_order_relaxed))
5933 {
5934 message_writer(console_color_red, false) << boost::format(tr("Password needed (%s) - use the refresh command")) % reason;
5935 m_cmd_binder.print_prompt();
5936 return boost::none;
5937 }
5938
5939 PAUSE_READLINE();
5940 std::string msg = tr("Enter password");
5941 if (reason && *reason)
5942 msg += std::string(" (") + reason + ")";
5943 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5944 if (!pwd_container)
5945 {
5946 MERROR("Failed to read password");
5947 return boost::none;
5948 }
5949
5950 return pwd_container->password();
5951 }
5952 //----------------------------------------------------------------------------------------------------
5953 void simple_wallet::on_device_button_request(uint64_t code)
5954 {
5955 message_writer(console_color_white, false) << tr("Device requires attention");
5956 }
5957 //----------------------------------------------------------------------------------------------------
5958 boost::optional<epee::wipeable_string> simple_wallet::on_device_pin_request()
5959 {
5960 PAUSE_READLINE();
5961 std::string msg = tr("Enter device PIN");
5962 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5963 THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device PIN"));
5964 return pwd_container->password();
5965 }
5966 //----------------------------------------------------------------------------------------------------
5967 boost::optional<epee::wipeable_string> simple_wallet::on_device_passphrase_request(bool & on_device)
5968 {
5969 if (on_device) {
5970 std::string accepted = input_line(tr(
5971 "Device asks for passphrase. Do you want to enter the passphrase on device (Y) (or on the host (N))?"));
5972 if (std::cin.eof() || command_line::is_yes(accepted)) {
5973 message_writer(console_color_white, true) << tr("Please enter the device passphrase on the device");
5974 return boost::none;
5975 }
5976 }
5977
5978 PAUSE_READLINE();
5979 on_device = false;
5980 std::string msg = tr("Enter device passphrase");
5981 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5982 THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device passphrase"));
5983 return pwd_container->password();
5984 }
5985 //----------------------------------------------------------------------------------------------------
5986 void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_blocks, bool is_init, bool received_money)
5987 {
5988 const uint64_t rfbh = m_wallet->get_refresh_from_block_height();
5989 std::string err;
5990 const uint64_t dh = m_wallet->get_daemon_blockchain_height(err);
5991 if (err.empty() && rfbh > dh)
5992 {
5993 message_writer(console_color_yellow, false) << tr("The wallet's refresh-from-block-height setting is higher than the daemon's height: this may mean your wallet will skip over transactions");
5994 }
5995
5996 // Key image sync after the first refresh
5997 if (!m_wallet->get_account().get_device().has_tx_cold_sign() || m_wallet->get_account().get_device().has_ki_live_refresh()) {
5998 return;
5999 }
6000
6001 if (!received_money || m_wallet->get_device_last_key_image_sync() != 0) {
6002 return;
6003 }
6004
6005 // Finished first refresh for HW device and money received -> KI sync
6006 message_writer() << "\n" << tr("The first refresh has finished for the HW-based wallet with received money. hw_key_images_sync is needed. ");
6007
6008 std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
6009 if (std::cin.eof() || !command_line::is_yes(accepted)) {
6010 message_writer(console_color_red, false) << tr("hw_key_images_sync skipped. Run command manually before a transfer.");
6011 return;
6012 }
6013
6014 key_images_sync_intern();
6015 }
6016 //----------------------------------------------------------------------------------------------------
6017 bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bool is_init)
6018 {
6019 if (!try_connect_to_daemon(is_init))
6020 return true;
6021
6022 LOCK_IDLE_SCOPE();
6023
6024 crypto::hash transfer_hash_pre{};
6025 uint64_t height_pre = 0, height_post;
6026 if (reset != ResetNone)
6027 {
6028 if (reset == ResetSoftKeepKI)
6029 height_pre = m_wallet->hash_m_transfers(boost::none, transfer_hash_pre);
6030
6031 m_wallet->rescan_blockchain(reset == ResetHard, false, reset == ResetSoftKeepKI);
6032 }
6033
6034 PAUSE_READLINE();
6035
6036 message_writer() << tr("Starting refresh...");
6037
6038 uint64_t fetched_blocks = 0;
6039 bool received_money = false;
6040 bool ok = false;
6041 std::ostringstream ss;
6042 try
6043 {
6044 m_in_manual_refresh.store(true, std::memory_order_relaxed);
6045 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
6046 // For manual refresh don't allow incremental checking of the pool: Because we did not process the txs
6047 // for us in the pool during automatic refresh we could miss some of them if we checked the pool
6048 // incrementally here
6049 m_wallet->refresh(m_wallet->is_trusted_daemon(), start_height, fetched_blocks, received_money, true, false);
6050
6051 if (reset == ResetSoftKeepKI)
6052 {
6053 m_wallet->finish_rescan_bc_keep_key_images(height_pre, transfer_hash_pre);
6054
6055 height_post = m_wallet->get_num_transfer_details();
6056 if (height_pre != height_post)
6057 {
6058 message_writer() << tr("New transfer received since rescan was started. Key images are incomplete.");
6059 }
6060 }
6061
6062 ok = true;
6063 // Clear line "Height xxx of xxx"
6064 std::cout << "\r \r";
6065 success_msg_writer(true) << tr("Refresh done, blocks received: ") << fetched_blocks;
6066 if (is_init)
6067 print_accounts();
6068 show_balance_unlocked();
6069 on_refresh_finished(start_height, fetched_blocks, is_init, received_money);
6070 }
6071 catch (const tools::error::daemon_busy&)
6072 {
6073 ss << tr("daemon is busy. Please try again later.");
6074 }
6075 catch (const tools::error::no_connection_to_daemon&)
6076 {
6077 ss << tr("no connection to daemon. Please make sure daemon is running.");
6078 }
6079 catch (const tools::error::payment_required&)
6080 {
6081 ss << tr("payment required.");
6082 m_need_payment = true;
6083 }
6084 catch (const tools::error::wallet_rpc_error& e)
6085 {
6086 LOG_ERROR("RPC error: " << e.to_string());
6087 ss << tr("RPC error: ") << e.what();
6088 }
6089 catch (const tools::error::refresh_error& e)
6090 {
6091 LOG_ERROR("refresh error: " << e.to_string());
6092 ss << tr("refresh error: ") << e.what();
6093 }
6094 catch (const tools::error::wallet_internal_error& e)
6095 {
6096 LOG_ERROR("internal error: " << e.to_string());
6097 ss << tr("internal error: ") << e.what();
6098 }
6099 catch (const std::exception& e)
6100 {
6101 LOG_ERROR("unexpected error: " << e.what());
6102 ss << tr("unexpected error: ") << e.what();
6103 }
6104 catch (...)
6105 {
6106 LOG_ERROR("unknown error");
6107 ss << tr("unknown error");
6108 }
6109
6110 if (!ok)
6111 {
6112 fail_msg_writer() << tr("refresh failed: ") << ss.str() << ". " << tr("Blocks received: ") << fetched_blocks;
6113 }
6114
6115 // prevent it from triggering the idle screen due to waiting for a foreground refresh
6116 m_last_activity_time = time(NULL);
6117
6118 return true;
6119 }
6120 //----------------------------------------------------------------------------------------------------
6121 bool simple_wallet::refresh(const std::vector<std::string>& args)
6122 {
6123 uint64_t start_height = 0;
6124 if(!args.empty()){
6125 try
6126 {
6127 start_height = boost::lexical_cast<uint64_t>( args[0] );
6128 }
6129 catch(const boost::bad_lexical_cast &)
6130 {
6131 start_height = 0;
6132 }
6133 }
6134 return refresh_main(start_height, ResetNone);
6135 }
6136 //----------------------------------------------------------------------------------------------------
6137 bool simple_wallet::show_balance_unlocked(bool detailed)
6138 {
6139 std::string extra;
6140 if (m_wallet->has_multisig_partial_key_images())
6141 extra = tr(" (Some owned outputs have partial key images - import_multisig_info needed)");
6142 else if (m_wallet->has_unknown_key_images())
6143 extra += tr(" (Some owned outputs have missing key images - export_outputs, import_outputs, export_key_images, and import_key_images needed)");
6144 success_msg_writer() << tr("Currently selected account: [") << m_current_subaddress_account << tr("] ") << m_wallet->get_subaddress_label({m_current_subaddress_account, 0});
6145 const std::string tag = m_wallet->get_account_tags().second[m_current_subaddress_account];
6146 success_msg_writer() << tr("Tag: ") << (tag.empty() ? std::string{tr("(No tag assigned)")} : tag);
6147 uint64_t blocks_to_unlock, time_to_unlock;
6148 uint64_t unlocked_balance = m_wallet->unlocked_balance(m_current_subaddress_account, false, &blocks_to_unlock, &time_to_unlock);
6149 std::string unlock_time_message;
6150 if (blocks_to_unlock > 0 && time_to_unlock > 0)
6151 unlock_time_message = (boost::format(" (%lu block(s) and %s to unlock)") % blocks_to_unlock % get_human_readable_timespan(time_to_unlock)).str();
6152 else if (blocks_to_unlock > 0)
6153 unlock_time_message = (boost::format(" (%lu block(s) to unlock)") % blocks_to_unlock).str();
6154 else if (time_to_unlock > 0)
6155 unlock_time_message = (boost::format(" (%s to unlock)") % get_human_readable_timespan(time_to_unlock)).str();
6156 success_msg_writer() << tr("Balance: ") << print_money(m_wallet->balance(m_current_subaddress_account, false)) << ", "
6157 << tr("unlocked balance: ") << print_money(unlocked_balance) << unlock_time_message << extra;
6158 std::map<uint32_t, uint64_t> balance_per_subaddress = m_wallet->balance_per_subaddress(m_current_subaddress_account, false);
6159 std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> unlocked_balance_per_subaddress = m_wallet->unlocked_balance_per_subaddress(m_current_subaddress_account, false);
6160 if (!detailed || balance_per_subaddress.empty())
6161 return true;
6162 success_msg_writer() << tr("Balance per address:");
6163 success_msg_writer() << boost::format("%15s %21s %21s %7s %21s") % tr("Address") % tr("Balance") % tr("Unlocked balance") % tr("Outputs") % tr("Label");
6164 std::vector<tools::wallet2::transfer_details> transfers;
6165 m_wallet->get_transfers(transfers);
6166 for (const auto& i : balance_per_subaddress)
6167 {
6168 cryptonote::subaddress_index subaddr_index = {m_current_subaddress_account, i.first};
6169 std::string address_str = m_wallet->get_subaddress_as_str(subaddr_index).substr(0, 6);
6170 uint64_t num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&subaddr_index](const tools::wallet2::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == subaddr_index; });
6171 success_msg_writer() << boost::format(tr("%8u %6s %21s %21s %7u %21s")) % i.first % address_str % print_money(i.second) % print_money(unlocked_balance_per_subaddress[i.first].first) % num_unspent_outputs % m_wallet->get_subaddress_label(subaddr_index);
6172 }
6173 return true;
6174 }
6175 //----------------------------------------------------------------------------------------------------
6176 bool simple_wallet::show_balance(const std::vector<std::string>& args/* = std::vector<std::string>()*/)
6177 {
6178 if (args.size() > 1 || (args.size() == 1 && args[0] != "detail"))
6179 {
6180 PRINT_USAGE(USAGE_SHOW_BALANCE);
6181 return true;
6182 }
6183 LOCK_IDLE_SCOPE();
6184 show_balance_unlocked(args.size() == 1);
6185 return true;
6186 }
6187 //----------------------------------------------------------------------------------------------------
6188 bool simple_wallet::show_incoming_transfers(const std::vector<std::string>& args)
6189 {
6190 if (args.size() > 3)
6191 {
6192 PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
6193 return true;
6194 }
6195 auto local_args = args;
6196 LOCK_IDLE_SCOPE();
6197
6198 std::set<uint32_t> subaddr_indices;
6199 bool filter = false;
6200 bool available = false;
6201 bool verbose = false;
6202 bool uses = false;
6203 if (local_args.size() > 0)
6204 {
6205 if (local_args[0] == "available")
6206 {
6207 filter = true;
6208 available = true;
6209 local_args.erase(local_args.begin());
6210 }
6211 else if (local_args[0] == "unavailable")
6212 {
6213 filter = true;
6214 available = false;
6215 local_args.erase(local_args.begin());
6216 }
6217 }
6218 while (local_args.size() > 0)
6219 {
6220 if (local_args[0] == "verbose")
6221 verbose = true;
6222 else if (local_args[0] == "uses")
6223 uses = true;
6224 else if (local_args[0].substr(0, 6) == "index=")
6225 {
6226 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
6227 return true;
6228 }
6229 else
6230 {
6231 fail_msg_writer() << tr("Invalid keyword: ") << local_args.front();
6232 break;
6233 }
6234 local_args.erase(local_args.begin());
6235 }
6236
6237 const uint64_t blockchain_height = m_wallet->get_blockchain_current_height();
6238
6239 PAUSE_READLINE();
6240
6241 if (local_args.size() > 0)
6242 {
6243 PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
6244 return true;
6245 }
6246
6247 tools::wallet2::transfer_container transfers;
6248 m_wallet->get_transfers(transfers);
6249
6250 size_t transfers_found = 0;
6251 for (const auto& td : transfers)
6252 {
6253 if (!filter || available != td.m_spent)
6254 {
6255 if (m_current_subaddress_account != td.m_subaddr_index.major || (!subaddr_indices.empty() && subaddr_indices.count(td.m_subaddr_index.minor) == 0))
6256 continue;
6257 if (!transfers_found)
6258 {
6259 std::string verbose_string;
6260 if (verbose)
6261 verbose_string = (boost::format("%68s%68s") % tr("pubkey") % tr("key image")).str();
6262 message_writer() << boost::format("%21s%8s%12s%8s%16s%68s%16s%s") % tr("amount") % tr("spent") % tr("unlocked") % tr("ringct") % tr("global index") % tr("tx id") % tr("addr index") % verbose_string;
6263 }
6264 std::string extra_string;
6265 if (verbose)
6266 extra_string += (boost::format("%68s%68s") % td.get_public_key() % (td.m_key_image_known ? epee::string_tools::pod_to_hex(td.m_key_image) : td.m_key_image_partial ? (epee::string_tools::pod_to_hex(td.m_key_image) + "/p") : std::string(64, '?'))).str();
6267 if (uses)
6268 {
6269 std::vector<uint64_t> heights;
6270 uint64_t idx = 0;
6271 for (const auto &e: td.m_uses)
6272 {
6273 heights.push_back(e.first);
6274 if (e.first < td.m_spent_height)
6275 ++idx;
6276 }
6277 const std::pair<std::string, std::string> line = show_outputs_line(heights, blockchain_height, idx);
6278 extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second;
6279 }
6280 message_writer(td.m_spent ? console_color_magenta : console_color_green, false) <<
6281 boost::format("%21s%8s%12s%8s%16u%68s%16u%s") %
6282 print_money(td.amount()) %
6283 (td.m_spent ? tr("T") : tr("F")) %
6284 (m_wallet->frozen(td) ? tr("[frozen]") : m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) %
6285 (td.is_rct() ? tr("RingCT") : tr("-")) %
6286 td.m_global_output_index %
6287 td.m_txid %
6288 td.m_subaddr_index.minor %
6289 extra_string;
6290 ++transfers_found;
6291 }
6292 }
6293
6294 if (!transfers_found)
6295 {
6296 if (!filter)
6297 {
6298 success_msg_writer() << tr("No incoming transfers");
6299 }
6300 else if (available)
6301 {
6302 success_msg_writer() << tr("No incoming available transfers");
6303 }
6304 else
6305 {
6306 success_msg_writer() << tr("No incoming unavailable transfers");
6307 }
6308 }
6309 else
6310 {
6311 success_msg_writer() << boost::format("Found %u/%u transfers") % transfers_found % transfers.size();
6312 }
6313
6314 return true;
6315 }
6316 //----------------------------------------------------------------------------------------------------
6317 bool simple_wallet::show_payments(const std::vector<std::string> &args)
6318 {
6319 if(args.empty())
6320 {
6321 PRINT_USAGE(USAGE_PAYMENTS);
6322 return true;
6323 }
6324
6325 LOCK_IDLE_SCOPE();
6326
6327 PAUSE_READLINE();
6328
6329 message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") %
6330 tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index");
6331
6332 bool payments_found = false;
6333 for(std::string arg : args)
6334 {
6335 crypto::hash payment_id;
6336 if(tools::wallet2::parse_payment_id(arg, payment_id))
6337 {
6338 std::list<tools::wallet2::payment_details> payments;
6339 m_wallet->get_payments(payment_id, payments);
6340 if(payments.empty())
6341 {
6342 success_msg_writer() << tr("No payments with id ") << payment_id;
6343 continue;
6344 }
6345
6346 for (const tools::wallet2::payment_details& pd : payments)
6347 {
6348 if(!payments_found)
6349 {
6350 payments_found = true;
6351 }
6352 success_msg_writer(true) <<
6353 boost::format("%68s%68s%12s%21s%16s%16s") %
6354 payment_id %
6355 pd.m_tx_hash %
6356 pd.m_block_height %
6357 print_money(pd.m_amount) %
6358 pd.m_unlock_time %
6359 pd.m_subaddr_index.minor;
6360 }
6361 }
6362 else
6363 {
6364 fail_msg_writer() << tr("payment ID has invalid format, expected 16 or 64 character hex string: ") << arg;
6365 }
6366 }
6367
6368 return true;
6369 }
6370 //----------------------------------------------------------------------------------------------------
6371 uint64_t simple_wallet::get_daemon_blockchain_height(std::string& err)
6372 {
6373 if (!m_wallet)
6374 {
6375 throw std::runtime_error("simple_wallet null wallet");
6376 }
6377 return m_wallet->get_daemon_blockchain_height(err);
6378 }
6379 //----------------------------------------------------------------------------------------------------
6380 bool simple_wallet::show_blockchain_height(const std::vector<std::string>& args)
6381 {
6382 if (!try_connect_to_daemon())
6383 return true;
6384
6385 std::string err;
6386 uint64_t bc_height = get_daemon_blockchain_height(err);
6387 if (err.empty())
6388 success_msg_writer() << bc_height;
6389 else
6390 fail_msg_writer() << tr("failed to get blockchain height: ") << err;
6391 return true;
6392 }
6393 //----------------------------------------------------------------------------------------------------
6394 bool simple_wallet::rescan_spent(const std::vector<std::string> &args)
6395 {
6396 CHECK_IF_BACKGROUND_SYNCING("cannot rescan spent");
6397 if (!m_wallet->is_trusted_daemon())
6398 {
6399 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
6400 return true;
6401 }
6402
6403 if (!try_connect_to_daemon())
6404 return true;
6405
6406 try
6407 {
6408 LOCK_IDLE_SCOPE();
6409 m_wallet->rescan_spent();
6410 }
6411 catch (const tools::error::daemon_busy&)
6412 {
6413 fail_msg_writer() << tr("daemon is busy. Please try again later.");
6414 }
6415 catch (const tools::error::no_connection_to_daemon&)
6416 {
6417 fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running.");
6418 }
6419 catch (const tools::error::payment_required&)
6420 {
6421 fail_msg_writer() << tr("payment required.");
6422 m_need_payment = true;
6423 }
6424 catch (const tools::error::is_key_image_spent_error&)
6425 {
6426 fail_msg_writer() << tr("failed to get spent status");
6427 }
6428 catch (const tools::error::wallet_rpc_error& e)
6429 {
6430 LOG_ERROR("RPC error: " << e.to_string());
6431 fail_msg_writer() << tr("RPC error: ") << e.what();
6432 }
6433 catch (const std::exception& e)
6434 {
6435 LOG_ERROR("unexpected error: " << e.what());
6436 fail_msg_writer() << tr("unexpected error: ") << e.what();
6437 }
6438 catch (...)
6439 {
6440 LOG_ERROR("unknown error");
6441 fail_msg_writer() << tr("unknown error");
6442 }
6443
6444 return true;
6445 }
6446 //----------------------------------------------------------------------------------------------------
6447 std::pair<std::string, std::string> simple_wallet::show_outputs_line(const std::vector<uint64_t> &heights, uint64_t blockchain_height, uint64_t highlight_idx) const
6448 {
6449 std::stringstream ostr;
6450
6451 for (uint64_t h: heights)
6452 blockchain_height = std::max(blockchain_height, h);
6453
6454 for (size_t j = 0; j < heights.size(); ++j)
6455 ostr << (j == highlight_idx ? " *" : " ") << heights[j];
6456
6457 // visualize the distribution, using the code by moneroexamples onion-monero-viewer
6458 const uint64_t resolution = 79;
6459 std::string ring_str(resolution, '_');
6460 for (size_t j = 0; j < heights.size(); ++j)
6461 {
6462 uint64_t pos = (heights[j] * resolution) / blockchain_height;
6463 ring_str[pos] = 'o';
6464 }
6465 if (highlight_idx < heights.size() && heights[highlight_idx] < blockchain_height)
6466 {
6467 uint64_t pos = (heights[highlight_idx] * resolution) / blockchain_height;
6468 ring_str[pos] = '*';
6469 }
6470
6471 return std::make_pair(ostr.str(), ring_str);
6472 }
6473 //----------------------------------------------------------------------------------------------------
6474 bool simple_wallet::process_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr, bool verbose)
6475 {
6476 uint32_t version;
6477 if (!try_connect_to_daemon(false, &version))
6478 {
6479 fail_msg_writer() << tr("failed to connect to daemon");
6480 return false;
6481 }
6482 // available for RPC version 1.4 or higher
6483 if (version < MAKE_CORE_RPC_VERSION(1, 4))
6484 return true;
6485 std::string err;
6486 uint64_t blockchain_height = get_daemon_blockchain_height(err);
6487 if (!err.empty())
6488 {
6489 fail_msg_writer() << tr("failed to get blockchain height: ") << err;
6490 return false;
6491 }
6492 // for each transaction
6493 for (size_t n = 0; n < ptx_vector.size(); ++n)
6494 {
6495 const cryptonote::transaction& tx = ptx_vector[n].tx;
6496 const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data;
6497 if (verbose)
6498 ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx);
6499 // for each input
6500 std::vector<uint64_t> spent_key_height(tx.vin.size());
6501 std::vector<crypto::hash> spent_key_txid (tx.vin.size());
6502 for (size_t i = 0; i < tx.vin.size(); ++i)
6503 {
6504 if (tx.vin[i].type() != typeid(cryptonote::txin_to_key))
6505 continue;
6506 const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]);
6507 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(construction_data.selected_transfers[i]);
6508 const cryptonote::tx_source_entry *sptr = NULL;
6509 for (const auto &src: construction_data.sources)
6510 if (src.outputs[src.real_output].second.dest == td.get_public_key())
6511 sptr = &src;
6512 if (!sptr)
6513 {
6514 fail_msg_writer() << tr("failed to find construction data for tx input");
6515 return false;
6516 }
6517 const cryptonote::tx_source_entry& source = *sptr;
6518
6519 if (verbose)
6520 ostr << boost::format(tr("\nInput %llu/%llu (%s): amount=%s")) % (i + 1) % tx.vin.size() % epee::string_tools::pod_to_hex(in_key.k_image) % print_money(source.amount);
6521 // convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount
6522 std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets);
6523 // get block heights from which those ring member keys originated
6524 COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req);
6525 req.outputs.resize(absolute_offsets.size());
6526 for (size_t j = 0; j < absolute_offsets.size(); ++j)
6527 {
6528 req.outputs[j].amount = in_key.amount;
6529 req.outputs[j].index = absolute_offsets[j];
6530 }
6531 COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res);
6532 req.get_txid = true;
6533 req.client = cryptonote::make_rpc_payment_signature(m_wallet->get_rpc_client_secret_key());
6534 bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res);
6535 err = interpret_rpc_response(r, res.status);
6536 if (!err.empty())
6537 {
6538 fail_msg_writer() << tr("failed to get output: ") << err;
6539 return false;
6540 }
6541 // make sure that returned block heights are less than blockchain height
6542 for (auto& res_out : res.outs)
6543 {
6544 if (res_out.height >= blockchain_height)
6545 {
6546 fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height");
6547 return false;
6548 }
6549 }
6550 if (verbose)
6551 ostr << tr("\nOriginating block heights: ");
6552 spent_key_height[i] = res.outs[source.real_output].height;
6553 spent_key_txid [i] = res.outs[source.real_output].txid;
6554 std::vector<uint64_t> heights(absolute_offsets.size(), 0);
6555 for (size_t j = 0; j < absolute_offsets.size(); ++j)
6556 {
6557 heights[j] = res.outs[j].height;
6558 }
6559 std::pair<std::string, std::string> ring_str = show_outputs_line(heights, blockchain_height, source.real_output);
6560 if (verbose)
6561 ostr << ring_str.first << tr("\n|") << ring_str.second << tr("|\n");
6562 }
6563 // warn if rings contain keys originating from the same tx or temporally very close block heights
6564 bool are_keys_from_same_tx = false;
6565 bool are_keys_from_close_height = false;
6566 for (size_t i = 0; i < tx.vin.size(); ++i) {
6567 for (size_t j = i + 1; j < tx.vin.size(); ++j)
6568 {
6569 if (spent_key_txid[i] == spent_key_txid[j])
6570 are_keys_from_same_tx = true;
6571 if (std::abs((int64_t)(spent_key_height[i] - spent_key_height[j])) < (int64_t)5)
6572 are_keys_from_close_height = true;
6573 }
6574 }
6575 if (are_keys_from_same_tx || are_keys_from_close_height)
6576 {
6577 ostr
6578 << tr("\nWarning: Some input keys being spent are from ")
6579 << (are_keys_from_same_tx ? tr("the same transaction") : tr("blocks that are temporally very close"))
6580 << tr(", which can break the anonymity of ring signatures. Make sure this is intentional!");
6581 }
6582 ostr << ENDL;
6583 }
6584 return true;
6585 }
6586 //----------------------------------------------------------------------------------------------------
6587 bool simple_wallet::prompt_if_old(const std::vector<tools::wallet2::pending_tx> &ptx_vector)
6588 {
6589 // count the number of old outputs
6590 std::string err;
6591 uint64_t bc_height = get_daemon_blockchain_height(err);
6592 if (!err.empty())
6593 return true;
6594
6595 int max_n_old = 0;
6596 for (const auto &ptx: ptx_vector)
6597 {
6598 int n_old = 0;
6599 for (const auto i: ptx.selected_transfers)
6600 {
6601 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
6602 uint64_t age = bc_height - td.m_block_height;
6603 if (age > OLD_AGE_WARN_THRESHOLD)
6604 ++n_old;
6605 }
6606 max_n_old = std::max(max_n_old, n_old);
6607 }
6608 if (max_n_old > 1)
6609 {
6610 std::stringstream prompt;
6611 prompt << tr("Transaction spends more than one very old output. Privacy would be better if they were sent separately.");
6612 prompt << ENDL << tr("Spend them now anyway?");
6613 std::string accepted = input_line(prompt.str(), true);
6614 if (std::cin.eof())
6615 return false;
6616 if (!command_line::is_yes(accepted))
6617 {
6618 return false;
6619 }
6620 }
6621 return true;
6622 }
6623 //----------------------------------------------------------------------------------------------------
6624 void simple_wallet::check_for_inactivity_lock(bool user)
6625 {
6626 if (m_locked)
6627 {
6628 #ifdef HAVE_READLINE
6629 PAUSE_READLINE();
6630 rdln::clear_screen();
6631 #endif
6632 tools::clear_screen();
6633 m_in_command = true;
6634 if (!user)
6635 {
6636 const std::string speech = tr("I locked your Monero wallet to protect you while you were away\nsee \"help set\" to configure/disable");
6637 std::vector<std::pair<std::string, size_t>> lines = tools::split_string_by_width(speech, 45);
6638
6639 size_t max_len = 0;
6640 for (const auto &i: lines)
6641 max_len = std::max(max_len, i.second);
6642 const size_t n_u = max_len + 2;
6643 tools::msg_writer() << " " << std::string(n_u, '_');
6644 for (size_t i = 0; i < lines.size(); ++i)
6645 tools::msg_writer() << (i == 0 ? "/" : i == lines.size() - 1 ? "\\" : "|") << " " << lines[i].first << std::string(max_len - lines[i].second, ' ') << " " << (i == 0 ? "\\" : i == lines.size() - 1 ? "/" : "|");
6646 tools::msg_writer() << " " << std::string(n_u, '-') << std::endl <<
6647 " \\ (__)" << std::endl <<
6648 " \\ (oo)\\_______" << std::endl <<
6649 " (__)\\ )\\/\\" << std::endl <<
6650 " ||----w |" << std::endl <<
6651 " || ||" << std::endl <<
6652 "" << std::endl;
6653 }
6654
6655 bool started_background_sync = false;
6656 if (!m_wallet->is_background_wallet() &&
6657 m_wallet->background_sync_type() != tools::wallet2::BackgroundSyncOff)
6658 {
6659 LOCK_IDLE_SCOPE();
6660 m_wallet->start_background_sync();
6661 started_background_sync = true;
6662 }
6663
6664 while (1)
6665 {
6666 const char *inactivity_msg = user ? "" : tr("Locked due to inactivity.");
6667 tools::msg_writer() << inactivity_msg << (inactivity_msg[0] ? " " : "") << (
6668 (m_wallet->is_background_wallet() && m_wallet->background_sync_type() == tools::wallet2::BackgroundSyncCustomPassword)
6669 ? tr("The background password is required to unlock the console.")
6670 : tr("The wallet password is required to unlock the console.")
6671 );
6672
6673 if (m_wallet->is_background_syncing())
6674 tools::msg_writer() << tr("\nSyncing in the background while locked...") << std::endl;
6675
6676 const bool show_wallet_name = m_wallet->show_wallet_name_when_locked();
6677 if (show_wallet_name)
6678 {
6679 tools::msg_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
6680 tools::msg_writer() << tr("Network type: ") << (
6681 m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
6682 m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet")
6683 );
6684 }
6685 try
6686 {
6687 const auto pwd_container = get_and_verify_password();
6688 if (pwd_container)
6689 {
6690 if (started_background_sync)
6691 {
6692 LOCK_IDLE_SCOPE();
6693 m_wallet->stop_background_sync(pwd_container->password());
6694 }
6695 break;
6696 }
6697 }
6698 catch (...) { /* do nothing, just let the loop loop */ }
6699 }
6700 m_last_activity_time = time(NULL);
6701 m_in_command = false;
6702 m_locked = false;
6703 }
6704 }
6705 //----------------------------------------------------------------------------------------------------
6706 bool simple_wallet::on_command(bool (simple_wallet::*cmd)(const std::vector<std::string>&), const std::vector<std::string> &args)
6707 {
6708 m_last_activity_time = time(NULL);
6709
6710 m_in_command = true;
6711 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
6712 m_last_activity_time = time(NULL);
6713 m_in_command = false;
6714 });
6715
6716 check_for_inactivity_lock(false);
6717 return (this->*cmd)(args);
6718 }
6719 //----------------------------------------------------------------------------------------------------
6720 bool simple_wallet::transfer_main(const std::vector<std::string> &args_, bool called_by_mms)
6721 {
6722 // "transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <amount> [<payment_id>]"
6723 CHECK_IF_BACKGROUND_SYNCING("cannot transfer");
6724 if (!try_connect_to_daemon())
6725 return false;
6726
6727 std::vector<std::string> local_args = args_;
6728
6729 std::set<uint32_t> subaddr_indices;
6730 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
6731 {
6732 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
6733 return false;
6734 local_args.erase(local_args.begin());
6735 }
6736
6737 uint32_t priority = m_wallet->get_default_priority();
6738 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
6739 local_args.erase(local_args.begin());
6740
6741 priority = m_wallet->adjust_priority(priority);
6742
6743 const size_t min_ring_size = m_wallet->get_min_ring_size();
6744 size_t fake_outs_count = min_ring_size - 1;
6745 if(local_args.size() > 0) {
6746 size_t ring_size;
6747 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
6748 {
6749 }
6750 else if (ring_size == 0)
6751 {
6752 fail_msg_writer() << tr("Ring size must not be 0");
6753 return false;
6754 }
6755 else
6756 {
6757 fake_outs_count = ring_size - 1;
6758 local_args.erase(local_args.begin());
6759 }
6760 }
6761 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
6762 if (adjusted_fake_outs_count > fake_outs_count)
6763 {
6764 fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
6765 return false;
6766 }
6767 if (adjusted_fake_outs_count < fake_outs_count)
6768 {
6769 fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
6770 return false;
6771 }
6772
6773 const size_t min_args = 1;
6774 if(local_args.size() < min_args)
6775 {
6776 fail_msg_writer() << tr("wrong number of arguments");
6777 return false;
6778 }
6779
6780 std::vector<uint8_t> extra;
6781 bool payment_id_seen = false;
6782 if (!local_args.empty())
6783 {
6784 std::string payment_id_str = local_args.back();
6785 crypto::hash payment_id;
6786 bool r = true;
6787 if (tools::wallet2::parse_long_payment_id(payment_id_str, payment_id))
6788 {
6789 LONG_PAYMENT_ID_SUPPORT_CHECK();
6790 }
6791 if(!r)
6792 {
6793 fail_msg_writer() << tr("payment id failed to encode");
6794 return false;
6795 }
6796 }
6797
6798 // Parse subtractfeefrom destination list
6799 tools::wallet2::unique_index_container subtract_fee_from_outputs;
6800 bool subtract_fee_from_all = false;
6801 for (auto it = local_args.begin(); it < local_args.end();)
6802 {
6803 bool matches = false;
6804 if (!parse_subtract_fee_from_outputs(*it, subtract_fee_from_outputs, subtract_fee_from_all, matches))
6805 {
6806 return false;
6807 }
6808 else if (matches)
6809 {
6810 it = local_args.erase(it);
6811 break;
6812 }
6813 else
6814 {
6815 ++it;
6816 }
6817 }
6818
6819 vector<cryptonote::address_parse_info> dsts_info;
6820 vector<cryptonote::tx_destination_entry> dsts;
6821 for (size_t i = 0; i < local_args.size(); )
6822 {
6823 dsts_info.emplace_back();
6824 cryptonote::address_parse_info & info = dsts_info.back();
6825 cryptonote::tx_destination_entry de;
6826 bool r = true;
6827
6828 // check for a URI
6829 std::string address_uri, payment_id_uri, tx_description, recipient_name, error;
6830 std::vector<std::string> unknown_parameters;
6831 uint64_t amount = 0;
6832 bool has_uri = m_wallet->parse_uri(local_args[i], address_uri, payment_id_uri, amount, tx_description, recipient_name, unknown_parameters, error);
6833 if (has_uri)
6834 {
6835 r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_uri, oa_prompter);
6836 if (payment_id_uri.size() == 16)
6837 {
6838 if (!tools::wallet2::parse_short_payment_id(payment_id_uri, info.payment_id))
6839 {
6840 fail_msg_writer() << tr("failed to parse short payment ID from URI");
6841 return false;
6842 }
6843 info.has_payment_id = true;
6844 }
6845 de.amount = amount;
6846 de.original = local_args[i];
6847 ++i;
6848 }
6849 else if (i + 1 < local_args.size())
6850 {
6851 r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[i], oa_prompter);
6852 bool ok = cryptonote::parse_amount(de.amount, local_args[i + 1]);
6853 if(!ok || 0 == de.amount)
6854 {
6855 fail_msg_writer() << tr("amount is wrong: ") << local_args[i] << ' ' << local_args[i + 1] <<
6856 ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
6857 return false;
6858 }
6859 de.original = local_args[i];
6860 i += 2;
6861 }
6862 else
6863 {
6864 if (boost::starts_with(local_args[i], "monero:"))
6865 fail_msg_writer() << tr("Invalid last argument: ") << local_args.back() << ": " << error;
6866 else
6867 fail_msg_writer() << tr("Invalid last argument: ") << local_args.back();
6868 return false;
6869 }
6870
6871 if (!r)
6872 {
6873 fail_msg_writer() << tr("failed to parse address");
6874 return false;
6875 }
6876 de.addr = info.address;
6877 de.is_subaddress = info.is_subaddress;
6878 de.is_integrated = info.has_payment_id;
6879
6880 if (info.has_payment_id || !payment_id_uri.empty())
6881 {
6882 if (payment_id_seen)
6883 {
6884 fail_msg_writer() << tr("a single transaction cannot use more than one payment id");
6885 return false;
6886 }
6887
6888 crypto::hash payment_id;
6889 std::string extra_nonce;
6890 if (info.has_payment_id)
6891 {
6892 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
6893 }
6894 else if (tools::wallet2::parse_payment_id(payment_id_uri, payment_id))
6895 {
6896 LONG_PAYMENT_ID_SUPPORT_CHECK();
6897 }
6898 else
6899 {
6900 fail_msg_writer() << tr("failed to parse payment id, though it was detected");
6901 return false;
6902 }
6903 bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
6904 if(!r)
6905 {
6906 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
6907 return false;
6908 }
6909 payment_id_seen = true;
6910 }
6911
6912 dsts.push_back(de);
6913 }
6914
6915 if (subtract_fee_from_all)
6916 {
6917 subtract_fee_from_outputs.clear();
6918 for (decltype(subtract_fee_from_outputs)::value_type i = 0; i < dsts.size(); ++i)
6919 subtract_fee_from_outputs.insert(i);
6920 }
6921
6922 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
6923
6924 try
6925 {
6926 // figure out what tx will be necessary
6927 auto ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, priority, extra,
6928 m_current_subaddress_account, subaddr_indices, subtract_fee_from_outputs);
6929
6930 if (ptx_vector.empty())
6931 {
6932 fail_msg_writer() << tr("No outputs found, or daemon is not ready");
6933 return false;
6934 }
6935
6936 // if we need to check for backlog, check the worst case tx
6937 if (m_wallet->confirm_backlog())
6938 {
6939 std::stringstream prompt;
6940 double worst_fee_per_byte = std::numeric_limits<double>::max();
6941 for (size_t n = 0; n < ptx_vector.size(); ++n)
6942 {
6943 const uint64_t blob_size = cryptonote::tx_to_blob(ptx_vector[n].tx).size();
6944 const double fee_per_byte = ptx_vector[n].fee / (double)blob_size;
6945 if (fee_per_byte < worst_fee_per_byte)
6946 {
6947 worst_fee_per_byte = fee_per_byte;
6948 }
6949 }
6950 try
6951 {
6952 std::vector<std::pair<uint64_t, uint64_t>> nblocks = m_wallet->estimate_backlog({std::make_pair(worst_fee_per_byte, worst_fee_per_byte)});
6953 if (nblocks.size() != 1)
6954 {
6955 prompt << "Internal error checking for backlog. " << tr("Is this okay anyway?");
6956 }
6957 else
6958 {
6959 if (nblocks[0].first > m_wallet->get_confirm_backlog_threshold())
6960 prompt << (boost::format(tr("There is currently a %u block backlog at that fee level. Is this okay?")) % nblocks[0].first).str();
6961 }
6962 }
6963 catch (const std::exception &e)
6964 {
6965 prompt << tr("Failed to check for backlog: ") << e.what() << ENDL << tr("Is this okay anyway?");
6966 }
6967
6968 std::string prompt_str = prompt.str();
6969 if (!prompt_str.empty())
6970 {
6971 std::string accepted = input_line(prompt_str, true);
6972 if (std::cin.eof())
6973 return false;
6974 if (!command_line::is_yes(accepted))
6975 {
6976 fail_msg_writer() << tr("transaction cancelled.");
6977
6978 return false;
6979 }
6980 }
6981 }
6982
6983 if (!prompt_if_old(ptx_vector))
6984 {
6985 fail_msg_writer() << tr("transaction cancelled.");
6986 return false;
6987 }
6988
6989 // if more than one tx necessary, prompt user to confirm
6990 if (m_wallet->always_confirm_transfers() || ptx_vector.size() > 1)
6991 {
6992 uint64_t total_sent = 0;
6993 uint64_t total_fee = 0;
6994 uint64_t dust_not_in_fee = 0;
6995 uint64_t dust_in_fee = 0;
6996 uint64_t change = 0;
6997 for (size_t n = 0; n < ptx_vector.size(); ++n)
6998 {
6999 total_fee += ptx_vector[n].fee;
7000 for (auto i: ptx_vector[n].selected_transfers)
7001 total_sent += m_wallet->get_transfer_details(i).amount();
7002 total_sent -= ptx_vector[n].change_dts.amount + ptx_vector[n].fee;
7003 change += ptx_vector[n].change_dts.amount;
7004
7005 if (ptx_vector[n].dust_added_to_fee)
7006 dust_in_fee += ptx_vector[n].dust;
7007 else
7008 dust_not_in_fee += ptx_vector[n].dust;
7009 }
7010
7011 std::stringstream prompt;
7012 for (size_t n = 0; n < ptx_vector.size(); ++n)
7013 {
7014 prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
7015 subaddr_indices.clear();
7016 for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
7017 subaddr_indices.insert(i);
7018 for (uint32_t i : subaddr_indices)
7019 prompt << boost::format(tr("Spending from address index %d\n")) % i;
7020 if (subaddr_indices.size() > 1)
7021 prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
7022 }
7023 prompt << boost::format(tr("Sending %s. ")) % print_money(total_sent);
7024 if (ptx_vector.size() > 1)
7025 {
7026 prompt << boost::format(tr("Your transaction needs to be split into %llu transactions. "
7027 "This will result in a transaction fee being applied to each transaction, for a total fee of %s")) %
7028 ((unsigned long long)ptx_vector.size()) % print_money(total_fee);
7029 }
7030 else
7031 {
7032 prompt << boost::format(tr("The transaction fee is %s")) %
7033 print_money(total_fee);
7034 }
7035 if (dust_in_fee != 0) prompt << boost::format(tr(", of which %s is dust from change")) % print_money(dust_in_fee);
7036 if (dust_not_in_fee != 0) prompt << tr(".") << ENDL << boost::format(tr("A total of %s from dust change will be sent to dust address"))
7037 % print_money(dust_not_in_fee);
7038 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7039 return false;
7040 bool default_ring_size = true;
7041 for (const auto &ptx: ptx_vector)
7042 {
7043 for (const auto &vin: ptx.tx.vin)
7044 {
7045 if (vin.type() == typeid(txin_to_key))
7046 {
7047 const txin_to_key& in_to_key = boost::get<txin_to_key>(vin);
7048 if (in_to_key.key_offsets.size() != min_ring_size)
7049 default_ring_size = false;
7050 }
7051 }
7052 }
7053 if (m_wallet->confirm_non_default_ring_size() && !default_ring_size)
7054 {
7055 prompt << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
7056 }
7057 prompt << ENDL << tr("Is this okay?");
7058
7059 std::string accepted = input_line(prompt.str(), true);
7060 if (std::cin.eof())
7061 return false;
7062 if (!command_line::is_yes(accepted))
7063 {
7064 fail_msg_writer() << tr("transaction cancelled.");
7065
7066 return false;
7067 }
7068 }
7069
7070 // actually commit the transactions
7071 if (m_wallet->multisig() && called_by_mms)
7072 {
7073 std::string ciphertext = m_wallet->save_multisig_tx(ptx_vector);
7074 if (!ciphertext.empty())
7075 {
7076 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::partially_signed_tx, ciphertext);
7077 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to MMS");
7078 }
7079 }
7080 else if (m_wallet->multisig())
7081 {
7082 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7083 if (!r)
7084 {
7085 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7086 return false;
7087 }
7088 else
7089 {
7090 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7091 }
7092 }
7093 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7094 {
7095 try
7096 {
7097 tools::wallet2::signed_tx_set signed_tx;
7098 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7099 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7100 return false;
7101 }
7102
7103 commit_or_save(signed_tx.ptx, m_do_not_relay);
7104 }
7105 catch (const std::exception& e)
7106 {
7107 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7108 return false;
7109 }
7110 catch (...)
7111 {
7112 LOG_ERROR("Unknown error");
7113 fail_msg_writer() << tr("unknown error");
7114 return false;
7115 }
7116 }
7117 else if (m_wallet->watch_only())
7118 {
7119 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7120 if (!r)
7121 {
7122 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7123 return false;
7124 }
7125 else
7126 {
7127 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7128 }
7129 }
7130 else
7131 {
7132 commit_or_save(ptx_vector, m_do_not_relay);
7133 }
7134 }
7135 catch (const std::exception &e)
7136 {
7137 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7138 return false;
7139 }
7140 catch (...)
7141 {
7142 LOG_ERROR("unknown error");
7143 fail_msg_writer() << tr("unknown error");
7144 return false;
7145 }
7146
7147 return true;
7148 }
7149 //----------------------------------------------------------------------------------------------------
7150 bool simple_wallet::transfer(const std::vector<std::string> &args_)
7151 {
7152 CHECK_IF_BACKGROUND_SYNCING("cannot transfer");
7153 if (args_.size() < 1)
7154 {
7155 PRINT_USAGE(USAGE_TRANSFER);
7156 return true;
7157 }
7158 transfer_main(args_, false);
7159 return true;
7160 }
7161 //----------------------------------------------------------------------------------------------------
7162
7163 bool simple_wallet::sweep_unmixable(const std::vector<std::string> &args_)
7164 {
7165 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7166 if (!try_connect_to_daemon())
7167 return true;
7168
7169 SCOPED_WALLET_UNLOCK();
7170
7171 try
7172 {
7173 // figure out what tx will be necessary
7174 auto ptx_vector = m_wallet->create_unmixable_sweep_transactions();
7175
7176 if (ptx_vector.empty())
7177 {
7178 fail_msg_writer() << tr("No unmixable outputs found");
7179 return true;
7180 }
7181
7182 // give user total and fee, and prompt to confirm
7183 uint64_t total_fee = 0, total_unmixable = 0;
7184 for (size_t n = 0; n < ptx_vector.size(); ++n)
7185 {
7186 total_fee += ptx_vector[n].fee;
7187 for (auto i: ptx_vector[n].selected_transfers)
7188 total_unmixable += m_wallet->get_transfer_details(i).amount();
7189 }
7190
7191 std::string prompt_str = tr("Sweeping ") + print_money(total_unmixable);
7192 if (ptx_vector.size() > 1) {
7193 prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
7194 print_money(total_unmixable) %
7195 ((unsigned long long)ptx_vector.size()) %
7196 print_money(total_fee)).str();
7197 }
7198 else {
7199 prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7200 print_money(total_unmixable) %
7201 print_money(total_fee)).str();
7202 }
7203 std::string accepted = input_line(prompt_str, true);
7204 if (std::cin.eof())
7205 return true;
7206 if (!command_line::is_yes(accepted))
7207 {
7208 fail_msg_writer() << tr("transaction cancelled.");
7209
7210 return true;
7211 }
7212
7213 // actually commit the transactions
7214 if (m_wallet->multisig())
7215 {
7216 CHECK_MULTISIG_ENABLED();
7217 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7218 if (!r)
7219 {
7220 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7221 }
7222 else
7223 {
7224 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7225 }
7226 }
7227 else if (m_wallet->watch_only())
7228 {
7229 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7230 if (!r)
7231 {
7232 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7233 }
7234 else
7235 {
7236 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7237 }
7238 }
7239 else
7240 {
7241 commit_or_save(ptx_vector, m_do_not_relay);
7242 }
7243 }
7244 catch (const tools::error::not_enough_unlocked_money& e)
7245 {
7246 fail_msg_writer() << tr("Not enough money in unlocked balance");
7247 std::string accepted = input_line((boost::format(tr("Discarding %s of unmixable outputs that cannot be spent, which can be undone by \"rescan_spent\". Is this okay?")) % print_money(e.available())).str(), true);
7248 if (std::cin.eof())
7249 return true;
7250 if (command_line::is_yes(accepted))
7251 {
7252 try
7253 {
7254 m_wallet->discard_unmixable_outputs();
7255 } catch (...) {}
7256 }
7257 }
7258 catch (const std::exception &e)
7259 {
7260 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7261 }
7262 catch (...)
7263 {
7264 LOG_ERROR("unknown error");
7265 fail_msg_writer() << tr("unknown error");
7266 }
7267
7268 return true;
7269 }
7270 //----------------------------------------------------------------------------------------------------
7271 bool simple_wallet::sweep_main(uint32_t account, uint64_t below, const std::vector<std::string> &args_)
7272 {
7273 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7274 auto print_usage = [this, account, below]()
7275 {
7276 if (below)
7277 {
7278 PRINT_USAGE(USAGE_SWEEP_BELOW);
7279 }
7280 else if (account == m_current_subaddress_account)
7281 {
7282 PRINT_USAGE(USAGE_SWEEP_ALL);
7283 }
7284 else
7285 {
7286 PRINT_USAGE(USAGE_SWEEP_ACCOUNT);
7287 }
7288 };
7289 if (args_.size() == 0)
7290 {
7291 fail_msg_writer() << tr("No address given");
7292 print_usage();
7293 return true;
7294 }
7295
7296 if (!try_connect_to_daemon())
7297 return true;
7298
7299 std::vector<std::string> local_args = args_;
7300
7301 std::set<uint32_t> subaddr_indices;
7302 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
7303 {
7304 if (local_args[0] == "index=all")
7305 {
7306 for (uint32_t i = 0; i < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++i)
7307 subaddr_indices.insert(i);
7308 }
7309 else if (!parse_subaddress_indices(local_args[0], subaddr_indices))
7310 {
7311 print_usage();
7312 return true;
7313 }
7314 local_args.erase(local_args.begin());
7315 }
7316
7317 uint32_t priority = 0;
7318 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
7319 local_args.erase(local_args.begin());
7320
7321 priority = m_wallet->adjust_priority(priority);
7322
7323 size_t fake_outs_count = m_wallet->get_min_ring_size() - 1;
7324 if(local_args.size() > 0) {
7325 size_t ring_size;
7326 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
7327 {
7328 }
7329 else if (ring_size == 0)
7330 {
7331 fail_msg_writer() << tr("Ring size must not be 0");
7332 return true;
7333 }
7334 else
7335 {
7336 fake_outs_count = ring_size - 1;
7337 local_args.erase(local_args.begin());
7338 }
7339 }
7340 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
7341 if (adjusted_fake_outs_count > fake_outs_count)
7342 {
7343 fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
7344 return true;
7345 }
7346 if (adjusted_fake_outs_count < fake_outs_count)
7347 {
7348 fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
7349 return true;
7350 }
7351
7352 size_t outputs = 1;
7353 if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
7354 {
7355 if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
7356 {
7357 fail_msg_writer() << tr("Failed to parse number of outputs");
7358 return true;
7359 }
7360 else if (outputs < 1)
7361 {
7362 fail_msg_writer() << tr("Amount of outputs should be greater than 0");
7363 return true;
7364 }
7365 else
7366 {
7367 local_args.erase(local_args.begin());
7368 }
7369 }
7370
7371 std::vector<uint8_t> extra;
7372 bool payment_id_seen = false;
7373 if (local_args.size() >= 2)
7374 {
7375 std::string payment_id_str = local_args.back();
7376
7377 crypto::hash payment_id;
7378 bool r = tools::wallet2::parse_long_payment_id(payment_id_str, payment_id);
7379 if(r)
7380 {
7381 LONG_PAYMENT_ID_SUPPORT_CHECK();
7382 }
7383
7384 if(!r && local_args.size() == 3)
7385 {
7386 fail_msg_writer() << tr("payment id has invalid format, expected 16 or 64 character hex string: ") << payment_id_str;
7387 print_usage();
7388 return true;
7389 }
7390 if (payment_id_seen)
7391 local_args.pop_back();
7392 }
7393
7394 cryptonote::address_parse_info info;
7395 if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[0], oa_prompter))
7396 {
7397 fail_msg_writer() << tr("failed to parse address");
7398 print_usage();
7399 return true;
7400 }
7401
7402 if (info.has_payment_id)
7403 {
7404 if (payment_id_seen)
7405 {
7406 fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
7407 return true;
7408 }
7409
7410 std::string extra_nonce;
7411 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
7412 bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
7413 if(!r)
7414 {
7415 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7416 return true;
7417 }
7418 payment_id_seen = true;
7419 }
7420
7421 SCOPED_WALLET_UNLOCK();
7422
7423 try
7424 {
7425 // figure out what tx will be necessary
7426 auto ptx_vector = m_wallet->create_transactions_all(below, info.address, info.is_subaddress, outputs, fake_outs_count, priority, extra, account, subaddr_indices);
7427
7428 if (ptx_vector.empty())
7429 {
7430 fail_msg_writer() << tr("No outputs found, or daemon is not ready");
7431 return true;
7432 }
7433
7434 if (!prompt_if_old(ptx_vector))
7435 {
7436 fail_msg_writer() << tr("transaction cancelled.");
7437 return false;
7438 }
7439
7440 // give user total and fee, and prompt to confirm
7441 uint64_t total_fee = 0, total_sent = 0;
7442 for (size_t n = 0; n < ptx_vector.size(); ++n)
7443 {
7444 total_fee += ptx_vector[n].fee;
7445 for (auto i: ptx_vector[n].selected_transfers)
7446 total_sent += m_wallet->get_transfer_details(i).amount();
7447 }
7448
7449 std::ostringstream prompt;
7450 for (size_t n = 0; n < ptx_vector.size(); ++n)
7451 {
7452 prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
7453 subaddr_indices.clear();
7454 for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
7455 subaddr_indices.insert(i);
7456 for (uint32_t i : subaddr_indices)
7457 prompt << boost::format(tr("Spending from address index %d\n")) % i;
7458 if (subaddr_indices.size() > 1)
7459 prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
7460 }
7461 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7462 return true;
7463 if (ptx_vector.size() > 1) {
7464 prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
7465 print_money(total_sent) %
7466 ((unsigned long long)ptx_vector.size()) %
7467 print_money(total_fee);
7468 }
7469 else {
7470 prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7471 print_money(total_sent) %
7472 print_money(total_fee);
7473 }
7474 std::string accepted = input_line(prompt.str(), true);
7475 if (std::cin.eof())
7476 return true;
7477 if (!command_line::is_yes(accepted))
7478 {
7479 fail_msg_writer() << tr("transaction cancelled.");
7480
7481 return true;
7482 }
7483
7484 // actually commit the transactions
7485 if (m_wallet->multisig())
7486 {
7487 CHECK_MULTISIG_ENABLED();
7488 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7489 if (!r)
7490 {
7491 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7492 }
7493 else
7494 {
7495 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7496 }
7497 }
7498 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7499 {
7500 try
7501 {
7502 tools::wallet2::signed_tx_set signed_tx;
7503 std::vector<cryptonote::address_parse_info> dsts_info;
7504 dsts_info.push_back(info);
7505
7506 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7507 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7508 return true;
7509 }
7510
7511 commit_or_save(signed_tx.ptx, m_do_not_relay);
7512 }
7513 catch (const std::exception& e)
7514 {
7515 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7516 }
7517 catch (...)
7518 {
7519 LOG_ERROR("Unknown error");
7520 fail_msg_writer() << tr("unknown error");
7521 }
7522 }
7523 else if (m_wallet->watch_only())
7524 {
7525 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7526 if (!r)
7527 {
7528 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7529 }
7530 else
7531 {
7532 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7533 }
7534 }
7535 else
7536 {
7537 commit_or_save(ptx_vector, m_do_not_relay);
7538 }
7539 }
7540 catch (const std::exception& e)
7541 {
7542 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7543 }
7544 catch (...)
7545 {
7546 LOG_ERROR("unknown error");
7547 fail_msg_writer() << tr("unknown error");
7548 }
7549
7550 return true;
7551 }
7552 //----------------------------------------------------------------------------------------------------
7553 bool simple_wallet::sweep_single(const std::vector<std::string> &args_)
7554 {
7555 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7556 if (!try_connect_to_daemon())
7557 return true;
7558
7559 std::vector<std::string> local_args = args_;
7560
7561 uint32_t priority = 0;
7562 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
7563 local_args.erase(local_args.begin());
7564
7565 priority = m_wallet->adjust_priority(priority);
7566
7567 size_t fake_outs_count = m_wallet->get_min_ring_size() - 1;
7568 if(local_args.size() > 0) {
7569 size_t ring_size;
7570 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
7571 {
7572 }
7573 else if (ring_size == 0)
7574 {
7575 fail_msg_writer() << tr("Ring size must not be 0");
7576 return true;
7577 }
7578 else
7579 {
7580 fake_outs_count = ring_size - 1;
7581 local_args.erase(local_args.begin());
7582 }
7583 }
7584 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
7585 if (adjusted_fake_outs_count > fake_outs_count)
7586 {
7587 fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
7588 return true;
7589 }
7590 if (adjusted_fake_outs_count < fake_outs_count)
7591 {
7592 fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
7593 return true;
7594 }
7595
7596 size_t outputs = 1;
7597 if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
7598 {
7599 if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
7600 {
7601 fail_msg_writer() << tr("Failed to parse number of outputs");
7602 return true;
7603 }
7604 else if (outputs < 1)
7605 {
7606 fail_msg_writer() << tr("Amount of outputs should be greater than 0");
7607 return true;
7608 }
7609 else
7610 {
7611 local_args.erase(local_args.begin());
7612 }
7613 }
7614
7615 std::vector<uint8_t> extra;
7616 bool payment_id_seen = false;
7617 if (local_args.size() == 3)
7618 {
7619 crypto::hash payment_id;
7620 std::string extra_nonce;
7621 if (tools::wallet2::parse_long_payment_id(local_args.back(), payment_id))
7622 {
7623 LONG_PAYMENT_ID_SUPPORT_CHECK();
7624 }
7625 else
7626 {
7627 fail_msg_writer() << tr("failed to parse Payment ID");
7628 return true;
7629 }
7630
7631 if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
7632 {
7633 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7634 return true;
7635 }
7636
7637 local_args.pop_back();
7638 payment_id_seen = true;
7639 }
7640
7641 if (local_args.size() != 2)
7642 {
7643 PRINT_USAGE(USAGE_SWEEP_SINGLE);
7644 return true;
7645 }
7646
7647 crypto::key_image ki;
7648 if (!epee::string_tools::hex_to_pod(local_args[0], ki))
7649 {
7650 fail_msg_writer() << tr("failed to parse key image");
7651 return true;
7652 }
7653
7654 cryptonote::address_parse_info info;
7655 if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[1], oa_prompter))
7656 {
7657 fail_msg_writer() << tr("failed to parse address");
7658 return true;
7659 }
7660
7661 if (info.has_payment_id)
7662 {
7663 if (payment_id_seen)
7664 {
7665 fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
7666 return true;
7667 }
7668
7669 std::string extra_nonce;
7670 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
7671 if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
7672 {
7673 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7674 return true;
7675 }
7676 payment_id_seen = true;
7677 }
7678
7679 SCOPED_WALLET_UNLOCK();
7680
7681 try
7682 {
7683 // figure out what tx will be necessary
7684 auto ptx_vector = m_wallet->create_transactions_single(ki, info.address, info.is_subaddress, outputs, fake_outs_count, priority, extra);
7685
7686 if (ptx_vector.empty())
7687 {
7688 fail_msg_writer() << tr("No outputs found");
7689 return true;
7690 }
7691 if (ptx_vector.size() > 1)
7692 {
7693 fail_msg_writer() << tr("Multiple transactions are created, which is not supposed to happen");
7694 return true;
7695 }
7696 if (ptx_vector[0].selected_transfers.size() != 1)
7697 {
7698 fail_msg_writer() << tr("The transaction uses multiple or no inputs, which is not supposed to happen");
7699 return true;
7700 }
7701
7702 // give user total and fee, and prompt to confirm
7703 uint64_t total_fee = ptx_vector[0].fee;
7704 uint64_t total_sent = m_wallet->get_transfer_details(ptx_vector[0].selected_transfers.front()).amount();
7705 std::ostringstream prompt;
7706 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7707 return true;
7708 prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7709 print_money(total_sent) %
7710 print_money(total_fee);
7711 std::string accepted = input_line(prompt.str(), true);
7712 if (std::cin.eof())
7713 return true;
7714 if (!command_line::is_yes(accepted))
7715 {
7716 fail_msg_writer() << tr("transaction cancelled.");
7717 return true;
7718 }
7719
7720 // actually commit the transactions
7721 if (m_wallet->multisig())
7722 {
7723 CHECK_MULTISIG_ENABLED();
7724 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7725 if (!r)
7726 {
7727 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7728 }
7729 else
7730 {
7731 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7732 }
7733 }
7734 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7735 {
7736 try
7737 {
7738 tools::wallet2::signed_tx_set signed_tx;
7739 std::vector<cryptonote::address_parse_info> dsts_info;
7740 dsts_info.push_back(info);
7741
7742 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7743 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7744 return true;
7745 }
7746
7747 commit_or_save(signed_tx.ptx, m_do_not_relay);
7748 success_msg_writer(true) << tr("Money successfully sent, transaction: ") << get_transaction_hash(ptx_vector[0].tx);
7749 }
7750 catch (const std::exception& e)
7751 {
7752 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7753 }
7754 catch (...)
7755 {
7756 LOG_ERROR("Unknown error");
7757 fail_msg_writer() << tr("unknown error");
7758 }
7759 }
7760 else if (m_wallet->watch_only())
7761 {
7762 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7763 if (!r)
7764 {
7765 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7766 }
7767 else
7768 {
7769 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7770 }
7771 }
7772 else
7773 {
7774 m_wallet->commit_tx(ptx_vector[0]);
7775 success_msg_writer(true) << tr("Money successfully sent, transaction: ") << get_transaction_hash(ptx_vector[0].tx);
7776 }
7777
7778 }
7779 catch (const std::exception& e)
7780 {
7781 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7782 }
7783 catch (...)
7784 {
7785 LOG_ERROR("unknown error");
7786 fail_msg_writer() << tr("unknown error");
7787 }
7788
7789 return true;
7790 }
7791 //----------------------------------------------------------------------------------------------------
7792 bool simple_wallet::sweep_all(const std::vector<std::string> &args_)
7793 {
7794 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7795 sweep_main(m_current_subaddress_account, 0, args_);
7796 return true;
7797 }
7798 //----------------------------------------------------------------------------------------------------
7799 bool simple_wallet::sweep_account(const std::vector<std::string> &args_)
7800 {
7801 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7802 auto local_args = args_;
7803 if (local_args.empty())
7804 {
7805 PRINT_USAGE(USAGE_SWEEP_ACCOUNT);
7806 return true;
7807 }
7808 uint32_t account = 0;
7809 if (!epee::string_tools::get_xtype_from_string(account, local_args[0]))
7810 {
7811 fail_msg_writer() << tr("Invalid account");
7812 return true;
7813 }
7814 local_args.erase(local_args.begin());
7815
7816 sweep_main(account, 0, local_args);
7817 return true;
7818 }
7819 //----------------------------------------------------------------------------------------------------
7820 bool simple_wallet::sweep_below(const std::vector<std::string> &args_)
7821 {
7822 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7823 uint64_t below = 0;
7824 if (args_.size() < 1)
7825 {
7826 fail_msg_writer() << tr("missing threshold amount");
7827 PRINT_USAGE(USAGE_SWEEP_BELOW);
7828 return true;
7829 }
7830 if (!cryptonote::parse_amount(below, args_[0]))
7831 {
7832 fail_msg_writer() << tr("invalid amount threshold");
7833 return true;
7834 }
7835 sweep_main(m_current_subaddress_account, below, std::vector<std::string>(++args_.begin(), args_.end()));
7836 return true;
7837 }
7838 //----------------------------------------------------------------------------------------------------
7839 bool simple_wallet::donate(const std::vector<std::string> &args_)
7840 {
7841 CHECK_IF_BACKGROUND_SYNCING("cannot donate");
7842 std::vector<std::string> local_args = args_;
7843 if(local_args.empty() || local_args.size() > 5)
7844 {
7845 PRINT_USAGE(USAGE_DONATE);
7846 return true;
7847 }
7848 std::string amount_str;
7849 std::string payment_id_str;
7850 // get payment id and pop
7851 crypto::hash payment_id;
7852 crypto::hash8 payment_id8;
7853 if (tools::wallet2::parse_long_payment_id (local_args.back(), payment_id ) ||
7854 tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8))
7855 {
7856 payment_id_str = local_args.back();
7857 local_args.pop_back();
7858 }
7859 // get amount and pop
7860 uint64_t amount;
7861 bool ok = cryptonote::parse_amount(amount, local_args.back());
7862 if (ok && amount != 0)
7863 {
7864 amount_str = local_args.back();
7865 local_args.pop_back();
7866 }
7867 else
7868 {
7869 fail_msg_writer() << tr("amount is wrong: ") << local_args.back() << ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
7870 return true;
7871 }
7872 // push back address, amount, payment id
7873 std::string address_str;
7874 if (m_wallet->nettype() != cryptonote::MAINNET)
7875 {
7876 // if not mainnet, convert donation address string to the relevant network type
7877 address_parse_info info;
7878 if (!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, MONERO_DONATION_ADDR))
7879 {
7880 fail_msg_writer() << tr("Failed to parse donation address: ") << MONERO_DONATION_ADDR;
7881 return true;
7882 }
7883 address_str = cryptonote::get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
7884 }
7885 else
7886 {
7887 address_str = MONERO_DONATION_ADDR;
7888 }
7889 local_args.push_back(address_str);
7890 local_args.push_back(amount_str);
7891 if (!payment_id_str.empty())
7892 local_args.push_back(payment_id_str);
7893 if (m_wallet->nettype() == cryptonote::MAINNET)
7894 message_writer() << (boost::format(tr("Donating %s %s to The Monero Project (donate.getmonero.org or %s).")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % MONERO_DONATION_ADDR).str();
7895 else
7896 message_writer() << (boost::format(tr("Donating %s %s to %s.")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % address_str).str();
7897 transfer(local_args);
7898 return true;
7899 }
7900 //----------------------------------------------------------------------------------------------------
7901 bool simple_wallet::accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message)
7902 {
7903 CHECK_IF_BACKGROUND_SYNCING("cannot load tx");
7904 // gather info to ask the user
7905 uint64_t amount = 0, amount_to_dests = 0, change = 0;
7906 size_t min_ring_size = ~0;
7907 std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> dests;
7908 int first_known_non_zero_change_index = -1;
7909 std::string payment_id_string = "";
7910 for (size_t n = 0; n < get_num_txes(); ++n)
7911 {
7912 const tools::wallet2::tx_construction_data &cd = get_tx(n);
7913
7914 std::vector<tx_extra_field> tx_extra_fields;
7915 bool has_encrypted_payment_id = false;
7916 crypto::hash8 payment_id8 = crypto::null_hash8;
7917 if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields))
7918 {
7919 tx_extra_nonce extra_nonce;
7920 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
7921 {
7922 crypto::hash payment_id;
7923 if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
7924 {
7925 if (!payment_id_string.empty())
7926 payment_id_string += ", ";
7927
7928 // if none of the addresses are integrated addresses, it's a dummy one
7929 bool is_dummy = true;
7930 for (const auto &e: cd.dests)
7931 if (e.is_integrated)
7932 is_dummy = false;
7933
7934 if (is_dummy)
7935 {
7936 payment_id_string += std::string("dummy encrypted payment ID");
7937 }
7938 else
7939 {
7940 payment_id_string += std::string("encrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id8);
7941 has_encrypted_payment_id = true;
7942 }
7943 }
7944 else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
7945 {
7946 if (!payment_id_string.empty())
7947 payment_id_string += ", ";
7948 payment_id_string += std::string("unencrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id);
7949 payment_id_string += " (OBSOLETE)";
7950 }
7951 }
7952 }
7953
7954 for (size_t s = 0; s < cd.sources.size(); ++s)
7955 {
7956 amount += cd.sources[s].amount;
7957 size_t ring_size = cd.sources[s].outputs.size();
7958 if (ring_size < min_ring_size)
7959 min_ring_size = ring_size;
7960 }
7961 for (size_t d = 0; d < cd.splitted_dsts.size(); ++d)
7962 {
7963 const tx_destination_entry &entry = cd.splitted_dsts[d];
7964 std::string address, standard_address = get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr);
7965 if (has_encrypted_payment_id && !entry.is_subaddress && standard_address != entry.original)
7966 {
7967 address = get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8);
7968 address += std::string(" (" + standard_address + " with encrypted payment id " + epee::string_tools::pod_to_hex(payment_id8) + ")");
7969 }
7970 else
7971 address = standard_address;
7972 auto i = dests.find(entry.addr);
7973 if (i == dests.end())
7974 dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount)));
7975 else
7976 i->second.second += entry.amount;
7977 amount_to_dests += entry.amount;
7978 }
7979 if (cd.change_dts.amount > 0)
7980 {
7981 auto it = dests.find(cd.change_dts.addr);
7982 if (it == dests.end())
7983 {
7984 fail_msg_writer() << tr("Claimed change does not go to a paid address");
7985 return false;
7986 }
7987 if (it->second.second < cd.change_dts.amount)
7988 {
7989 fail_msg_writer() << tr("Claimed change is larger than payment to the change address");
7990 return false;
7991 }
7992 if (cd.change_dts.amount > 0)
7993 {
7994 if (first_known_non_zero_change_index == -1)
7995 first_known_non_zero_change_index = n;
7996 if (memcmp(&cd.change_dts.addr, &get_tx(first_known_non_zero_change_index).change_dts.addr, sizeof(cd.change_dts.addr)))
7997 {
7998 fail_msg_writer() << tr("Change goes to more than one address");
7999 return false;
8000 }
8001 }
8002 change += cd.change_dts.amount;
8003 it->second.second -= cd.change_dts.amount;
8004 if (it->second.second == 0)
8005 dests.erase(cd.change_dts.addr);
8006 }
8007 }
8008
8009 if (payment_id_string.empty())
8010 payment_id_string = "no payment ID";
8011
8012 std::string dest_string;
8013 size_t n_dummy_outputs = 0;
8014 for (auto i = dests.begin(); i != dests.end(); )
8015 {
8016 if (i->second.second > 0)
8017 {
8018 if (!dest_string.empty())
8019 dest_string += ", ";
8020 dest_string += (boost::format(tr("sending %s to %s")) % print_money(i->second.second) % i->second.first).str();
8021 }
8022 else
8023 ++n_dummy_outputs;
8024 ++i;
8025 }
8026 if (n_dummy_outputs > 0)
8027 {
8028 if (!dest_string.empty())
8029 dest_string += ", ";
8030 dest_string += std::to_string(n_dummy_outputs) + tr(" dummy output(s)");
8031 }
8032 if (dest_string.empty())
8033 dest_string = tr("with no destinations");
8034
8035 std::string change_string;
8036 if (change > 0)
8037 {
8038 std::string address = get_account_address_as_str(m_wallet->nettype(), get_tx(0).subaddr_account > 0, get_tx(0).change_dts.addr);
8039 change_string += (boost::format(tr("%s change to %s")) % print_money(change) % address).str();
8040 }
8041 else
8042 change_string += tr("no change");
8043
8044 uint64_t fee = amount - amount_to_dests;
8045 std::string prompt_str = (boost::format(tr("Loaded %lu transactions, for %s, fee %s, %s, %s, with min ring size %lu, %s. %sIs this okay?")) % (unsigned long)get_num_txes() % print_money(amount) % print_money(fee) % dest_string % change_string % (unsigned long)min_ring_size % payment_id_string % extra_message).str();
8046 return command_line::is_yes(input_line(prompt_str, true));
8047 }
8048 //----------------------------------------------------------------------------------------------------
8049 bool simple_wallet::accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs)
8050 {
8051 std::string extra_message;
8052 if (!std::get<2>(txs.new_transfers).empty())
8053 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(txs.new_transfers).size()).str();
8054 else if (!std::get<2>(txs.transfers).empty())
8055 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(txs.transfers).size()).str();
8056 return accept_loaded_tx([&txs](){return txs.txes.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.txes[n];}, extra_message);
8057 }
8058 //----------------------------------------------------------------------------------------------------
8059 bool simple_wallet::accept_loaded_tx(const tools::wallet2::signed_tx_set &txs)
8060 {
8061 std::string extra_message;
8062 if (!txs.key_images.empty())
8063 extra_message = (boost::format("%u key images to import. ") % (unsigned)txs.key_images.size()).str();
8064 return accept_loaded_tx([&txs](){return txs.ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.ptx[n].construction_data;}, extra_message);
8065 }
8066 //----------------------------------------------------------------------------------------------------
8067 bool simple_wallet::sign_transfer(const std::vector<std::string> &args_)
8068 {
8069 if (m_wallet->key_on_device())
8070 {
8071 fail_msg_writer() << tr("command not supported by HW wallet");
8072 return true;
8073 }
8074 if(m_wallet->multisig())
8075 {
8076 fail_msg_writer() << tr("This is a multisig wallet, it can only sign with sign_multisig");
8077 return true;
8078 }
8079 if(m_wallet->watch_only())
8080 {
8081 fail_msg_writer() << tr("This is a watch only wallet");
8082 return true;
8083 }
8084 CHECK_IF_BACKGROUND_SYNCING("cannot sign transfer");
8085
8086 bool export_raw = false;
8087 std::string unsigned_filename = "unsigned_monero_tx";
8088 if (args_.size() > 2 || (args_.size() == 2 && args_[0] != "export_raw"))
8089 {
8090 PRINT_USAGE(USAGE_SIGN_TRANSFER);
8091 return true;
8092 }
8093 else if (args_.size() == 2)
8094 {
8095 export_raw = true;
8096 unsigned_filename = args_[1];
8097 }
8098 else if (args_.size() == 1)
8099 {
8100 if (args_[0] == "export_raw")
8101 export_raw = true;
8102 else
8103 unsigned_filename = args_[0];
8104 }
8105
8106 SCOPED_WALLET_UNLOCK();
8107
8108 std::vector<tools::wallet2::pending_tx> ptx;
8109 try
8110 {
8111 bool r = m_wallet->sign_tx(unsigned_filename, "signed_monero_tx", ptx, [&](const tools::wallet2::unsigned_tx_set &tx){ return accept_loaded_tx(tx); }, export_raw);
8112 if (!r)
8113 {
8114 fail_msg_writer() << tr("Failed to sign transaction");
8115 return true;
8116 }
8117 }
8118 catch (const std::exception &e)
8119 {
8120 fail_msg_writer() << tr("Failed to sign transaction: ") << e.what();
8121 return true;
8122 }
8123
8124 std::string txids_as_text;
8125 for (const auto &t: ptx)
8126 {
8127 if (!txids_as_text.empty())
8128 txids_as_text += (", ");
8129 txids_as_text += epee::string_tools::pod_to_hex(get_transaction_hash(t.tx));
8130 }
8131 success_msg_writer(true) << tr("Transaction successfully signed to file ") << "signed_monero_tx" << ", txid " << txids_as_text;
8132 if (export_raw)
8133 {
8134 std::string rawfiles_as_text;
8135 for (size_t i = 0; i < ptx.size(); ++i)
8136 {
8137 if (i > 0)
8138 rawfiles_as_text += ", ";
8139 rawfiles_as_text += "signed_monero_tx_raw" + (ptx.size() == 1 ? "" : ("_" + std::to_string(i)));
8140 }
8141 success_msg_writer(true) << tr("Transaction raw hex data exported to ") << rawfiles_as_text;
8142 }
8143 return true;
8144 }
8145 //----------------------------------------------------------------------------------------------------
8146 bool simple_wallet::submit_transfer(const std::vector<std::string> &args_)
8147 {
8148 if (m_wallet->key_on_device())
8149 {
8150 fail_msg_writer() << tr("command not supported by HW wallet");
8151 return true;
8152 }
8153 if (!try_connect_to_daemon())
8154 return true;
8155
8156 try
8157 {
8158 std::vector<tools::wallet2::pending_tx> ptx_vector;
8159 bool r = m_wallet->load_tx("signed_monero_tx", ptx_vector, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); });
8160 if (!r)
8161 {
8162 fail_msg_writer() << tr("Failed to load transaction from file");
8163 return true;
8164 }
8165
8166 commit_or_save(ptx_vector, false);
8167 }
8168 catch (const std::exception& e)
8169 {
8170 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
8171 }
8172 catch (...)
8173 {
8174 LOG_ERROR("Unknown error");
8175 fail_msg_writer() << tr("unknown error");
8176 }
8177
8178 return true;
8179 }
8180 //----------------------------------------------------------------------------------------------------
8181 std::string get_tx_key_stream(crypto::secret_key tx_key, std::vector<crypto::secret_key> additional_tx_keys)
8182 {
8183 ostringstream oss;
8184 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(tx_key)));
8185 for (size_t i = 0; i < additional_tx_keys.size(); ++i)
8186 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(additional_tx_keys[i])));
8187 return oss.str();
8188 }
8189
8190 bool simple_wallet::get_tx_key(const std::vector<std::string> &args_)
8191 {
8192 CHECK_IF_BACKGROUND_SYNCING("cannot get tx key");
8193
8194 std::vector<std::string> local_args = args_;
8195
8196 if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR)
8197 {
8198 fail_msg_writer() << tr("command not supported by HW wallet");
8199 return true;
8200 }
8201 if(local_args.size() != 1) {
8202 PRINT_USAGE(USAGE_GET_TX_KEY);
8203 return true;
8204 }
8205
8206 crypto::hash txid;
8207 if (!epee::string_tools::hex_to_pod(local_args[0], txid))
8208 {
8209 fail_msg_writer() << tr("failed to parse txid");
8210 return true;
8211 }
8212
8213 SCOPED_WALLET_UNLOCK();
8214
8215 crypto::secret_key tx_key;
8216 std::vector<crypto::secret_key> additional_tx_keys;
8217
8218 bool found_tx_key = m_wallet->get_tx_key(txid, tx_key, additional_tx_keys);
8219 if (found_tx_key)
8220 {
8221 std::string stream = get_tx_key_stream(tx_key, additional_tx_keys);
8222 success_msg_writer() << tr("Tx key: ") << stream;
8223 return true;
8224 }
8225 else
8226 {
8227 fail_msg_writer() << tr("no tx keys found for this txid");
8228 return true;
8229 }
8230 }
8231 //----------------------------------------------------------------------------------------------------
8232 bool simple_wallet::set_tx_key(const std::vector<std::string> &args_)
8233 {
8234 CHECK_IF_BACKGROUND_SYNCING("cannot set tx key");
8235
8236 std::vector<std::string> local_args = args_;
8237
8238 if(local_args.size() != 2 && local_args.size() != 3) {
8239 PRINT_USAGE(USAGE_SET_TX_KEY);
8240 return true;
8241 }
8242
8243 boost::optional<cryptonote::account_public_address> single_destination_subaddress;
8244 if (local_args.size() > 1)
8245 {
8246 cryptonote::address_parse_info info;
8247 if (cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args.back(), oa_prompter))
8248 {
8249 if (!info.is_subaddress)
8250 {
8251 fail_msg_writer() << tr("Last argument is an address, but not a subaddress");
8252 return true;
8253 }
8254 single_destination_subaddress = info.address;
8255 local_args.pop_back();
8256 }
8257 }
8258
8259 crypto::hash txid;
8260 if (!epee::string_tools::hex_to_pod(local_args[0], txid))
8261 {
8262 fail_msg_writer() << tr("failed to parse txid");
8263 return true;
8264 }
8265
8266 crypto::secret_key tx_key;
8267 std::vector<crypto::secret_key> additional_tx_keys;
8268 try
8269 {
8270 if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
8271 {
8272 fail_msg_writer() << tr("failed to parse tx_key");
8273 return true;
8274 }
8275 while(true)
8276 {
8277 local_args[1] = local_args[1].substr(64);
8278 if (local_args[1].empty())
8279 break;
8280 additional_tx_keys.resize(additional_tx_keys.size() + 1);
8281 if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
8282 {
8283 fail_msg_writer() << tr("failed to parse tx_key");
8284 return true;
8285 }
8286 }
8287 }
8288 catch (const std::out_of_range &e)
8289 {
8290 fail_msg_writer() << tr("failed to parse tx_key");
8291 return true;
8292 }
8293
8294 LOCK_IDLE_SCOPE();
8295
8296 try
8297 {
8298 m_wallet->set_tx_key(txid, tx_key, additional_tx_keys, single_destination_subaddress);
8299 success_msg_writer() << tr("Tx key successfully stored.");
8300 }
8301 catch (const std::exception &e)
8302 {
8303 fail_msg_writer() << tr("Failed to store tx key: ") << e.what();
8304 if (!single_destination_subaddress)
8305 fail_msg_writer() << tr("It could be because the transfer was to a subaddress. If this is the case, pass the subaddress last");
8306 }
8307 return true;
8308 }
8309 //----------------------------------------------------------------------------------------------------
8310 bool simple_wallet::get_tx_proof(const std::vector<std::string> &args)
8311 {
8312 CHECK_IF_BACKGROUND_SYNCING("cannot get tx proof");
8313
8314 if (args.size() != 2 && args.size() != 3)
8315 {
8316 PRINT_USAGE(USAGE_GET_TX_PROOF);
8317 return true;
8318 }
8319
8320 crypto::hash txid;
8321 if(!epee::string_tools::hex_to_pod(args[0], txid))
8322 {
8323 fail_msg_writer() << tr("failed to parse txid");
8324 return true;
8325 }
8326
8327 cryptonote::address_parse_info info;
8328 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
8329 {
8330 fail_msg_writer() << tr("failed to parse address");
8331 return true;
8332 }
8333
8334 SCOPED_WALLET_UNLOCK();
8335
8336 try
8337 {
8338 std::string sig_str = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, args.size() == 3 ? args[2] : "");
8339 const std::string filename = "monero_tx_proof";
8340 if (m_wallet->save_to_file(filename, sig_str, true))
8341 success_msg_writer() << tr("signature file saved to: ") << filename;
8342 else
8343 fail_msg_writer() << tr("failed to save signature file");
8344 }
8345 catch (const std::exception &e)
8346 {
8347 fail_msg_writer() << tr("error: ") << e.what();
8348 }
8349 return true;
8350 }
8351 //----------------------------------------------------------------------------------------------------
8352 bool simple_wallet::check_tx_key(const std::vector<std::string> &args_)
8353 {
8354 std::vector<std::string> local_args = args_;
8355
8356 if(local_args.size() != 3) {
8357 PRINT_USAGE(USAGE_CHECK_TX_KEY);
8358 return true;
8359 }
8360
8361 if (!try_connect_to_daemon())
8362 return true;
8363
8364 if (!m_wallet)
8365 {
8366 fail_msg_writer() << tr("wallet is null");
8367 return true;
8368 }
8369 crypto::hash txid;
8370 if(!epee::string_tools::hex_to_pod(local_args[0], txid))
8371 {
8372 fail_msg_writer() << tr("failed to parse txid");
8373 return true;
8374 }
8375
8376 crypto::secret_key tx_key;
8377 std::vector<crypto::secret_key> additional_tx_keys;
8378 if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
8379 {
8380 fail_msg_writer() << tr("failed to parse tx key");
8381 return true;
8382 }
8383 local_args[1] = local_args[1].substr(64);
8384 while (!local_args[1].empty())
8385 {
8386 additional_tx_keys.resize(additional_tx_keys.size() + 1);
8387 if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
8388 {
8389 fail_msg_writer() << tr("failed to parse tx key");
8390 return true;
8391 }
8392 local_args[1] = local_args[1].substr(64);
8393 }
8394
8395 cryptonote::address_parse_info info;
8396 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[2], oa_prompter))
8397 {
8398 fail_msg_writer() << tr("failed to parse address");
8399 return true;
8400 }
8401
8402 try
8403 {
8404 uint64_t received;
8405 bool in_pool;
8406 uint64_t confirmations;
8407 m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations);
8408
8409 if (received > 0)
8410 {
8411 success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
8412 if (in_pool)
8413 {
8414 success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
8415 }
8416 else
8417 {
8418 if (confirmations != (uint64_t)-1)
8419 {
8420 success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
8421 }
8422 else
8423 {
8424 success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
8425 }
8426 }
8427 }
8428 else
8429 {
8430 fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
8431 }
8432 }
8433 catch (const std::exception &e)
8434 {
8435 fail_msg_writer() << tr("error: ") << e.what();
8436 }
8437 return true;
8438 }
8439 //----------------------------------------------------------------------------------------------------
8440 bool simple_wallet::check_tx_proof(const std::vector<std::string> &args)
8441 {
8442 if(args.size() != 3 && args.size() != 4) {
8443 PRINT_USAGE(USAGE_CHECK_TX_PROOF);
8444 return true;
8445 }
8446
8447 if (!try_connect_to_daemon())
8448 return true;
8449
8450 // parse txid
8451 crypto::hash txid;
8452 if(!epee::string_tools::hex_to_pod(args[0], txid))
8453 {
8454 fail_msg_writer() << tr("failed to parse txid");
8455 return true;
8456 }
8457
8458 // parse address
8459 cryptonote::address_parse_info info;
8460 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
8461 {
8462 fail_msg_writer() << tr("failed to parse address");
8463 return true;
8464 }
8465
8466 // read signature file
8467 std::string sig_str;
8468 if (!m_wallet->load_from_file(args[2], sig_str))
8469 {
8470 fail_msg_writer() << tr("failed to load signature file");
8471 return true;
8472 }
8473
8474 try
8475 {
8476 uint64_t received;
8477 bool in_pool;
8478 uint64_t confirmations;
8479 if (m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, args.size() == 4 ? args[3] : "", sig_str, received, in_pool, confirmations))
8480 {
8481 success_msg_writer() << tr("Good signature");
8482 if (received > 0)
8483 {
8484 success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
8485 if (in_pool)
8486 {
8487 success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
8488 }
8489 else
8490 {
8491 if (confirmations != (uint64_t)-1)
8492 {
8493 success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
8494 }
8495 else
8496 {
8497 success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
8498 }
8499 }
8500 }
8501 else
8502 {
8503 fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
8504 }
8505 }
8506 else
8507 {
8508 fail_msg_writer() << tr("Bad signature");
8509 }
8510 }
8511 catch (const std::exception &e)
8512 {
8513 fail_msg_writer() << tr("error: ") << e.what();
8514 }
8515 return true;
8516 }
8517 //----------------------------------------------------------------------------------------------------
8518 bool simple_wallet::get_spend_proof(const std::vector<std::string> &args)
8519 {
8520 CHECK_IF_BACKGROUND_SYNCING("cannot get spend proof");
8521 if (m_wallet->key_on_device())
8522 {
8523 fail_msg_writer() << tr("command not supported by HW wallet");
8524 return true;
8525 }
8526 if(args.size() != 1 && args.size() != 2) {
8527 PRINT_USAGE(USAGE_GET_SPEND_PROOF);
8528 return true;
8529 }
8530
8531 if (m_wallet->watch_only())
8532 {
8533 fail_msg_writer() << tr("wallet is watch-only and cannot generate the proof");
8534 return true;
8535 }
8536
8537 crypto::hash txid;
8538 if (!epee::string_tools::hex_to_pod(args[0], txid))
8539 {
8540 fail_msg_writer() << tr("failed to parse txid");
8541 return true;
8542 }
8543
8544 if (!try_connect_to_daemon())
8545 return true;
8546
8547 SCOPED_WALLET_UNLOCK();
8548
8549 try
8550 {
8551 const std::string sig_str = m_wallet->get_spend_proof(txid, args.size() == 2 ? args[1] : "");
8552 const std::string filename = "monero_spend_proof";
8553 if (m_wallet->save_to_file(filename, sig_str, true))
8554 success_msg_writer() << tr("signature file saved to: ") << filename;
8555 else
8556 fail_msg_writer() << tr("failed to save signature file");
8557 }
8558 catch (const std::exception &e)
8559 {
8560 fail_msg_writer() << e.what();
8561 }
8562 return true;
8563 }
8564 //----------------------------------------------------------------------------------------------------
8565 bool simple_wallet::check_spend_proof(const std::vector<std::string> &args)
8566 {
8567 if(args.size() != 2 && args.size() != 3) {
8568 PRINT_USAGE(USAGE_CHECK_SPEND_PROOF);
8569 return true;
8570 }
8571
8572 crypto::hash txid;
8573 if (!epee::string_tools::hex_to_pod(args[0], txid))
8574 {
8575 fail_msg_writer() << tr("failed to parse txid");
8576 return true;
8577 }
8578
8579 if (!try_connect_to_daemon())
8580 return true;
8581
8582 std::string sig_str;
8583 if (!m_wallet->load_from_file(args[1], sig_str))
8584 {
8585 fail_msg_writer() << tr("failed to load signature file");
8586 return true;
8587 }
8588
8589 try
8590 {
8591 if (m_wallet->check_spend_proof(txid, args.size() == 3 ? args[2] : "", sig_str))
8592 success_msg_writer() << tr("Good signature");
8593 else
8594 fail_msg_writer() << tr("Bad signature");
8595 }
8596 catch (const std::exception& e)
8597 {
8598 fail_msg_writer() << e.what();
8599 }
8600 return true;
8601 }
8602 //----------------------------------------------------------------------------------------------------
8603 bool simple_wallet::get_reserve_proof(const std::vector<std::string> &args)
8604 {
8605 CHECK_IF_BACKGROUND_SYNCING("cannot get reserve proof");
8606 if (m_wallet->key_on_device())
8607 {
8608 fail_msg_writer() << tr("command not supported by HW wallet");
8609 return true;
8610 }
8611 if(args.size() != 1 && args.size() != 2) {
8612 PRINT_USAGE(USAGE_GET_RESERVE_PROOF);
8613 return true;
8614 }
8615
8616 if (m_wallet->watch_only() || m_wallet->multisig())
8617 {
8618 fail_msg_writer() << tr("The reserve proof can be generated only by a full wallet");
8619 return true;
8620 }
8621
8622 boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
8623 if (args[0] != "all")
8624 {
8625 account_minreserve = std::pair<uint32_t, uint64_t>();
8626 account_minreserve->first = m_current_subaddress_account;
8627 if (!cryptonote::parse_amount(account_minreserve->second, args[0]))
8628 {
8629 fail_msg_writer() << tr("amount is wrong: ") << args[0];
8630 return true;
8631 }
8632 }
8633
8634 if (!try_connect_to_daemon())
8635 return true;
8636
8637 SCOPED_WALLET_UNLOCK();
8638
8639 try
8640 {
8641 const std::string sig_str = m_wallet->get_reserve_proof(account_minreserve, args.size() == 2 ? args[1] : "");
8642 const std::string filename = "monero_reserve_proof";
8643 if (m_wallet->save_to_file(filename, sig_str, true))
8644 success_msg_writer() << tr("signature file saved to: ") << filename;
8645 else
8646 fail_msg_writer() << tr("failed to save signature file");
8647 }
8648 catch (const std::exception &e)
8649 {
8650 fail_msg_writer() << e.what();
8651 }
8652 return true;
8653 }
8654 //----------------------------------------------------------------------------------------------------
8655 bool simple_wallet::check_reserve_proof(const std::vector<std::string> &args)
8656 {
8657 if(args.size() != 2 && args.size() != 3) {
8658 PRINT_USAGE(USAGE_CHECK_RESERVE_PROOF);
8659 return true;
8660 }
8661
8662 if (!try_connect_to_daemon())
8663 return true;
8664
8665 cryptonote::address_parse_info info;
8666 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[0], oa_prompter))
8667 {
8668 fail_msg_writer() << tr("failed to parse address");
8669 return true;
8670 }
8671 if (info.is_subaddress)
8672 {
8673 fail_msg_writer() << tr("Address must not be a subaddress");
8674 return true;
8675 }
8676
8677 std::string sig_str;
8678 if (!m_wallet->load_from_file(args[1], sig_str))
8679 {
8680 fail_msg_writer() << tr("failed to load signature file");
8681 return true;
8682 }
8683
8684 LOCK_IDLE_SCOPE();
8685
8686 try
8687 {
8688 uint64_t total, spent;
8689 if (m_wallet->check_reserve_proof(info.address, args.size() == 3 ? args[2] : "", sig_str, total, spent))
8690 {
8691 success_msg_writer() << boost::format(tr("Good signature -- total: %s, spent: %s, unspent: %s")) % print_money(total) % print_money(spent) % print_money(total - spent);
8692 }
8693 else
8694 {
8695 fail_msg_writer() << tr("Bad signature");
8696 }
8697 }
8698 catch (const std::exception& e)
8699 {
8700 fail_msg_writer() << e.what();
8701 }
8702 return true;
8703 }
8704 //----------------------------------------------------------------------------------------------------
8705 static std::string get_human_readable_timespan(std::chrono::seconds seconds)
8706 {
8707 uint64_t ts = seconds.count();
8708 if (ts < 60)
8709 return std::to_string(ts) + sw::tr(" seconds");
8710 if (ts < 3600)
8711 return std::to_string((uint64_t)(ts / 60)) + sw::tr(" minutes");
8712 if (ts < 3600 * 24)
8713 return std::to_string((uint64_t)(ts / 3600)) + sw::tr(" hours");
8714 if (ts < 3600 * 24 * 30.5)
8715 return std::to_string((uint64_t)(ts / (3600 * 24))) + sw::tr(" days");
8716 if (ts < 3600 * 24 * 365.25)
8717 return std::to_string((uint64_t)(ts / (3600 * 24 * 30.5))) + sw::tr(" months");
8718 return sw::tr("a long time");
8719 }
8720 //----------------------------------------------------------------------------------------------------
8721 static std::string get_human_readable_timespan(uint64_t seconds)
8722 {
8723 return get_human_readable_timespan(std::chrono::seconds(seconds));
8724 }
8725 //----------------------------------------------------------------------------------------------------
8726 // mutates local_args as it parses and consumes arguments
8727 bool simple_wallet::get_transfers(std::vector<std::string>& local_args, std::vector<transfer_view>& transfers)
8728 {
8729 bool in = true;
8730 bool out = true;
8731 bool pending = true;
8732 bool failed = true;
8733 bool pool = true;
8734 bool coinbase = true;
8735 uint64_t min_height = 0;
8736 uint64_t max_height = (uint64_t)-1;
8737
8738 // optional in/out selector
8739 if (local_args.size() > 0) {
8740 if (local_args[0] == "in" || local_args[0] == "incoming") {
8741 out = pending = failed = false;
8742 local_args.erase(local_args.begin());
8743 }
8744 else if (local_args[0] == "out" || local_args[0] == "outgoing") {
8745 in = pool = coinbase = false;
8746 local_args.erase(local_args.begin());
8747 }
8748 else if (local_args[0] == "pending") {
8749 in = out = failed = coinbase = false;
8750 local_args.erase(local_args.begin());
8751 }
8752 else if (local_args[0] == "failed") {
8753 in = out = pending = pool = coinbase = false;
8754 local_args.erase(local_args.begin());
8755 }
8756 else if (local_args[0] == "pool") {
8757 in = out = pending = failed = coinbase = false;
8758 local_args.erase(local_args.begin());
8759 }
8760 else if (local_args[0] == "coinbase") {
8761 in = out = pending = failed = pool = false;
8762 coinbase = true;
8763 local_args.erase(local_args.begin());
8764 }
8765 else if (local_args[0] == "all" || local_args[0] == "both") {
8766 local_args.erase(local_args.begin());
8767 }
8768 }
8769
8770 // subaddr_index
8771 std::set<uint32_t> subaddr_indices;
8772 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
8773 {
8774 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
8775 return false;
8776 local_args.erase(local_args.begin());
8777 }
8778
8779 // min height
8780 if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
8781 try {
8782 min_height = boost::lexical_cast<uint64_t>(local_args[0]);
8783 }
8784 catch (const boost::bad_lexical_cast &) {
8785 fail_msg_writer() << tr("bad min_height parameter:") << " " << local_args[0];
8786 return false;
8787 }
8788 local_args.erase(local_args.begin());
8789 }
8790
8791 // max height
8792 if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
8793 try {
8794 max_height = boost::lexical_cast<uint64_t>(local_args[0]);
8795 }
8796 catch (const boost::bad_lexical_cast &) {
8797 fail_msg_writer() << tr("bad max_height parameter:") << " " << local_args[0];
8798 return false;
8799 }
8800 local_args.erase(local_args.begin());
8801 }
8802
8803 const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
8804
8805 if (in || coinbase) {
8806 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
8807 m_wallet->get_payments(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
8808 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8809 const tools::wallet2::payment_details &pd = i->second;
8810 if (!pd.m_coinbase && !in)
8811 continue;
8812 std::string payment_id = string_tools::pod_to_hex(i->first);
8813 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8814 payment_id = payment_id.substr(0,16);
8815 std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
8816 std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
8817 const std::string type = pd.m_coinbase ? tr("block") : tr("in");
8818 const bool unlocked = m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height);
8819 std::string locked_msg = "unlocked";
8820 if (!unlocked)
8821 {
8822 locked_msg = "locked";
8823 if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
8824 {
8825 uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
8826 if (bh >= last_block_height)
8827 locked_msg = std::to_string(bh - last_block_height) + " blks";
8828 }
8829 else
8830 {
8831 const uint64_t adjusted_time = m_wallet->get_daemon_adjusted_time();
8832 uint64_t threshold = adjusted_time + (m_wallet->use_fork_rules(2, 0) ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1);
8833 if (threshold < pd.m_unlock_time)
8834 locked_msg = get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
8835 }
8836 }
8837 transfers.push_back({
8838 type,
8839 pd.m_block_height,
8840 pd.m_timestamp,
8841 type,
8842 true,
8843 pd.m_amount,
8844 pd.m_tx_hash,
8845 payment_id,
8846 0,
8847 {{destination, pd.m_amount}},
8848 {pd.m_subaddr_index.minor},
8849 note,
8850 locked_msg
8851 });
8852 }
8853 }
8854
8855 if (out) {
8856 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments;
8857 m_wallet->get_payments_out(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
8858 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8859 const tools::wallet2::confirmed_transfer_details &pd = i->second;
8860 uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
8861 uint64_t fee = pd.m_amount_in - pd.m_amount_out;
8862 std::vector<std::pair<std::string, uint64_t>> destinations;
8863 for (const auto &d: pd.m_dests) {
8864 destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
8865 }
8866 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
8867 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8868 payment_id = payment_id.substr(0,16);
8869 std::string note = m_wallet->get_tx_note(i->first);
8870 transfers.push_back({
8871 "out",
8872 pd.m_block_height,
8873 pd.m_timestamp,
8874 "out",
8875 true,
8876 pd.m_amount_in - change - fee,
8877 i->first,
8878 payment_id,
8879 fee,
8880 destinations,
8881 pd.m_subaddr_indices,
8882 note,
8883 "-"
8884 });
8885 }
8886 }
8887
8888 if (pool) {
8889 try
8890 {
8891 m_in_manual_refresh.store(true, std::memory_order_relaxed);
8892 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
8893
8894 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
8895 m_wallet->update_pool_state(process_txs);
8896 if (!process_txs.empty())
8897 m_wallet->process_pool_state(process_txs);
8898
8899 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments;
8900 m_wallet->get_unconfirmed_payments(payments, m_current_subaddress_account, subaddr_indices);
8901 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8902 const tools::wallet2::payment_details &pd = i->second.m_pd;
8903 std::string payment_id = string_tools::pod_to_hex(i->first);
8904 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8905 payment_id = payment_id.substr(0,16);
8906 std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
8907 std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
8908 std::string double_spend_note;
8909 if (i->second.m_double_spend_seen)
8910 double_spend_note = tr("[Double spend seen on the network: this transaction may or may not end up being mined] ");
8911 transfers.push_back({
8912 "pool",
8913 "pool",
8914 pd.m_timestamp,
8915 "in",
8916 false,
8917 pd.m_amount,
8918 pd.m_tx_hash,
8919 payment_id,
8920 0,
8921 {{destination, pd.m_amount}},
8922 {pd.m_subaddr_index.minor},
8923 note + double_spend_note,
8924 "locked"
8925 });
8926 }
8927 }
8928 catch (const std::exception& e)
8929 {
8930 fail_msg_writer() << "Failed to get pool state:" << e.what();
8931 }
8932 }
8933
8934 // print unconfirmed last
8935 if (pending || failed) {
8936 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
8937 m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account, subaddr_indices);
8938 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
8939 const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
8940 uint64_t amount = pd.m_amount_in;
8941 uint64_t fee = amount - pd.m_amount_out;
8942 std::vector<std::pair<std::string, uint64_t>> destinations;
8943 for (const auto &d: pd.m_dests) {
8944 destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
8945 }
8946 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
8947 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8948 payment_id = payment_id.substr(0,16);
8949 std::string note = m_wallet->get_tx_note(i->first);
8950 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
8951 if ((failed && is_failed) || (!is_failed && pending)) {
8952 transfers.push_back({
8953 (is_failed ? "failed" : "pending"),
8954 (is_failed ? "failed" : "pending"),
8955 pd.m_timestamp,
8956 "out",
8957 false,
8958 amount - pd.m_change - fee,
8959 i->first,
8960 payment_id,
8961 fee,
8962 destinations,
8963 pd.m_subaddr_indices,
8964 note,
8965 "-"
8966 });
8967 }
8968 }
8969 }
8970 // sort by block, then by timestamp (unconfirmed last)
8971 std::sort(transfers.begin(), transfers.end(), [](const transfer_view& a, const transfer_view& b) -> bool {
8972 if (a.confirmed && !b.confirmed)
8973 return true;
8974 if (a.block == b.block)
8975 return a.timestamp < b.timestamp;
8976 return a.block < b.block;
8977 });
8978
8979 return true;
8980 }
8981 //----------------------------------------------------------------------------------------------------
8982 bool simple_wallet::show_transfers(const std::vector<std::string> &args_)
8983 {
8984 std::vector<std::string> local_args = args_;
8985
8986 if(local_args.size() > 4) {
8987 fail_msg_writer() << tr("usage: show_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
8988 return true;
8989 }
8990
8991 LOCK_IDLE_SCOPE();
8992
8993 std::vector<transfer_view> all_transfers;
8994
8995 if (!get_transfers(local_args, all_transfers))
8996 return true;
8997
8998 PAUSE_READLINE();
8999
9000 for (const auto& transfer : all_transfers)
9001 {
9002 const auto color = transfer.type == "failed" ? console_color_red : transfer.confirmed ? ((transfer.direction == "in" || transfer.direction == "block") ? console_color_green : console_color_magenta) : console_color_default;
9003
9004 std::string destinations = "-";
9005 if (!transfer.outputs.empty())
9006 {
9007 destinations = "";
9008 for (const auto& output : transfer.outputs)
9009 {
9010 if (!destinations.empty())
9011 destinations += ", ";
9012 destinations += (transfer.direction == "in" ? output.first.substr(0, 6) : output.first) + ":" + print_money(output.second);
9013 }
9014 }
9015
9016 auto formatter = boost::format("%8.8llu %6.6s %8.8s %25.25s %20.20s %s %s %14.14s %s %s - %s");
9017
9018 message_writer(color, false) << formatter
9019 % transfer.block
9020 % transfer.direction
9021 % transfer.unlocked
9022 % tools::get_human_readable_timestamp(transfer.timestamp)
9023 % print_money(transfer.amount)
9024 % string_tools::pod_to_hex(transfer.hash)
9025 % transfer.payment_id
9026 % print_money(transfer.fee)
9027 % destinations
9028 % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
9029 % transfer.note;
9030 }
9031
9032 return true;
9033 }
9034 //----------------------------------------------------------------------------------------------------
9035 bool simple_wallet::export_transfers(const std::vector<std::string>& args_)
9036 {
9037 std::vector<std::string> local_args = args_;
9038
9039 if(local_args.size() > 6) {
9040 fail_msg_writer() << tr("usage: export_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<path>] [option=<with_keys>]");
9041 return true;
9042 }
9043
9044 std::vector<transfer_view> all_transfers;
9045
9046 // might consumes arguments in local_args
9047 if (!get_transfers(local_args, all_transfers))
9048 return true;
9049
9050 // output filename
9051 std::string filename = (boost::format("output%u.csv") % m_current_subaddress_account).str();
9052 if (local_args.size() > 0 && local_args[0].substr(0, 7) == "output=")
9053 {
9054 filename = local_args[0].substr(7, -1);
9055 local_args.erase(local_args.begin());
9056 }
9057 // check for export with tx keys
9058 bool export_keys = false;
9059 if (local_args.size() > 0 && local_args[0].substr(0, 7) == "option=")
9060 {
9061 export_keys = local_args[0].substr(7, -1) == "with_keys";
9062 local_args.erase(local_args.begin());
9063 }
9064 if (export_keys)
9065 {
9066 if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR)
9067 {
9068 fail_msg_writer() << tr("command not supported by HW wallet");
9069 return true;
9070 }
9071 SCOPED_WALLET_UNLOCK();
9072 } else
9073 {
9074 LOCK_IDLE_SCOPE();
9075 }
9076
9077 std::ofstream file(filename);
9078
9079 // header
9080 file <<
9081 boost::format("%8.8s,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%106.106s,%20.20s,%s,%s,%s") %
9082 tr("block") % tr("direction") % tr("unlocked") % tr("timestamp") % tr("amount") % tr("running balance") % tr("hash") % tr("payment ID") % tr("fee") % tr("destination") % tr("amount") % tr("index") % tr("note") % tr("tx key")
9083 << std::endl;
9084
9085 uint64_t running_balance = 0;
9086 auto formatter = boost::format("%8.8llu,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%106.106s,%20.20s,\"%s\",%s,%s");
9087
9088 for (const auto& transfer : all_transfers)
9089 {
9090 // ignore unconfirmed transfers in running balance
9091 if (transfer.confirmed)
9092 {
9093 if (transfer.direction == "in" || transfer.direction == "block")
9094 running_balance += transfer.amount;
9095 else
9096 running_balance -= transfer.amount + transfer.fee;
9097 }
9098
9099 crypto::secret_key tx_key;
9100 std::vector<crypto::secret_key> additional_tx_keys;
9101 bool found_tx_key = m_wallet->get_tx_key(transfer.hash, tx_key, additional_tx_keys);
9102 std::string key_string;
9103 if (export_keys && found_tx_key)
9104 {
9105 key_string = get_tx_key_stream(tx_key, additional_tx_keys);
9106 }
9107
9108 file << formatter
9109 % transfer.block
9110 % transfer.direction
9111 % transfer.unlocked
9112 % tools::get_human_readable_timestamp(transfer.timestamp)
9113 % print_money(transfer.amount)
9114 % print_money(running_balance)
9115 % string_tools::pod_to_hex(transfer.hash)
9116 % transfer.payment_id
9117 % print_money(transfer.fee)
9118 % (transfer.outputs.size() ? transfer.outputs[0].first : "-")
9119 % (transfer.outputs.size() ? print_money(transfer.outputs[0].second) : "")
9120 % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
9121 % transfer.note
9122 % key_string
9123 << std::endl;
9124
9125 for (size_t i = 1; i < transfer.outputs.size(); ++i)
9126 {
9127 file << formatter
9128 % ""
9129 % ""
9130 % ""
9131 % ""
9132 % ""
9133 % ""
9134 % ""
9135 % ""
9136 % ""
9137 % transfer.outputs[i].first
9138 % print_money(transfer.outputs[i].second)
9139 % ""
9140 % ""
9141 % ""
9142 << std::endl;
9143 }
9144 }
9145 file.close();
9146
9147 success_msg_writer() << tr("CSV exported to ") << filename;
9148
9149 return true;
9150 }
9151 //----------------------------------------------------------------------------------------------------
9152 bool simple_wallet::unspent_outputs(const std::vector<std::string> &args_)
9153 {
9154 if(args_.size() > 3)
9155 {
9156 PRINT_USAGE(USAGE_UNSPENT_OUTPUTS);
9157 return true;
9158 }
9159 auto local_args = args_;
9160
9161 std::set<uint32_t> subaddr_indices;
9162 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
9163 {
9164 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
9165 return true;
9166 local_args.erase(local_args.begin());
9167 }
9168
9169 uint64_t min_amount = 0;
9170 uint64_t max_amount = std::numeric_limits<uint64_t>::max();
9171 if (local_args.size() > 0)
9172 {
9173 if (!cryptonote::parse_amount(min_amount, local_args[0]))
9174 {
9175 fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
9176 return true;
9177 }
9178 local_args.erase(local_args.begin());
9179 if (local_args.size() > 0)
9180 {
9181 if (!cryptonote::parse_amount(max_amount, local_args[0]))
9182 {
9183 fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
9184 return true;
9185 }
9186 local_args.erase(local_args.begin());
9187 }
9188 if (min_amount > max_amount)
9189 {
9190 fail_msg_writer() << tr("<min_amount> should be smaller than <max_amount>");
9191 return true;
9192 }
9193 }
9194 tools::wallet2::transfer_container transfers;
9195 m_wallet->get_transfers(transfers);
9196 std::map<uint64_t, tools::wallet2::transfer_container> amount_to_tds;
9197 uint64_t min_height = std::numeric_limits<uint64_t>::max();
9198 uint64_t max_height = 0;
9199 uint64_t found_min_amount = std::numeric_limits<uint64_t>::max();
9200 uint64_t found_max_amount = 0;
9201 uint64_t count = 0;
9202 for (const auto& td : transfers)
9203 {
9204 uint64_t amount = td.amount();
9205 if (td.m_spent || amount < min_amount || amount > max_amount || td.m_subaddr_index.major != m_current_subaddress_account || (subaddr_indices.count(td.m_subaddr_index.minor) == 0 && !subaddr_indices.empty()))
9206 continue;
9207 amount_to_tds[amount].push_back(td);
9208 if (min_height > td.m_block_height) min_height = td.m_block_height;
9209 if (max_height < td.m_block_height) max_height = td.m_block_height;
9210 if (found_min_amount > amount) found_min_amount = amount;
9211 if (found_max_amount < amount) found_max_amount = amount;
9212 ++count;
9213 }
9214 if (amount_to_tds.empty())
9215 {
9216 success_msg_writer() << tr("There is no unspent output in the specified address");
9217 return true;
9218 }
9219 for (const auto& amount_tds : amount_to_tds)
9220 {
9221 auto& tds = amount_tds.second;
9222 success_msg_writer() << tr("\nAmount: ") << print_money(amount_tds.first) << tr(", number of keys: ") << tds.size();
9223 for (size_t i = 0; i < tds.size(); )
9224 {
9225 std::ostringstream oss;
9226 for (size_t j = 0; j < 8 && i < tds.size(); ++i, ++j)
9227 oss << tds[i].m_block_height << tr(" ");
9228 success_msg_writer() << oss.str();
9229 }
9230 }
9231 success_msg_writer()
9232 << tr("\nMin block height: ") << min_height
9233 << tr("\nMax block height: ") << max_height
9234 << tr("\nMin amount found: ") << print_money(found_min_amount)
9235 << tr("\nMax amount found: ") << print_money(found_max_amount)
9236 << tr("\nTotal count: ") << count;
9237 const size_t histogram_height = 10;
9238 const size_t histogram_width = 50;
9239 double bin_size = (max_height - min_height + 1.0) / histogram_width;
9240 size_t max_bin_count = 0;
9241 std::vector<size_t> histogram(histogram_width, 0);
9242 for (const auto& amount_tds : amount_to_tds)
9243 {
9244 for (auto& td : amount_tds.second)
9245 {
9246 uint64_t bin_index = (td.m_block_height - min_height + 1) / bin_size;
9247 if (bin_index >= histogram_width)
9248 bin_index = histogram_width - 1;
9249 histogram[bin_index]++;
9250 if (max_bin_count < histogram[bin_index])
9251 max_bin_count = histogram[bin_index];
9252 }
9253 }
9254 for (size_t x = 0; x < histogram_width; ++x)
9255 {
9256 double bin_count = histogram[x];
9257 if (max_bin_count > histogram_height)
9258 bin_count *= histogram_height / (double)max_bin_count;
9259 if (histogram[x] > 0 && bin_count < 1.0)
9260 bin_count = 1.0;
9261 histogram[x] = bin_count;
9262 }
9263 std::vector<std::string> histogram_line(histogram_height, std::string(histogram_width, ' '));
9264 for (size_t y = 0; y < histogram_height; ++y)
9265 {
9266 for (size_t x = 0; x < histogram_width; ++x)
9267 {
9268 if (y < histogram[x])
9269 histogram_line[y][x] = '*';
9270 }
9271 }
9272 double count_per_star = max_bin_count / (double)histogram_height;
9273 if (count_per_star < 1)
9274 count_per_star = 1;
9275 success_msg_writer()
9276 << tr("\nBin size: ") << bin_size
9277 << tr("\nOutputs per *: ") << count_per_star;
9278 ostringstream histogram_str;
9279 histogram_str << tr("count\n ^\n");
9280 for (size_t y = histogram_height; y > 0; --y)
9281 histogram_str << tr(" |") << histogram_line[y - 1] << tr("|\n");
9282 histogram_str
9283 << tr(" +") << std::string(histogram_width, '-') << tr("+--> block height\n")
9284 << tr(" ^") << std::string(histogram_width - 2, ' ') << tr("^\n")
9285 << tr(" ") << min_height << std::string(histogram_width - 8, ' ') << max_height;
9286 success_msg_writer() << histogram_str.str();
9287 return true;
9288 }
9289 //----------------------------------------------------------------------------------------------------
9290 bool simple_wallet::rescan_blockchain(const std::vector<std::string> &args_)
9291 {
9292 CHECK_IF_BACKGROUND_SYNCING("cannot rescan");
9293
9294 uint64_t start_height = 0;
9295 ResetType reset_type = ResetSoft;
9296
9297 if (!args_.empty())
9298 {
9299 if (args_[0] == "hard")
9300 {
9301 reset_type = ResetHard;
9302 }
9303 else if (args_[0] == "soft")
9304 {
9305 reset_type = ResetSoft;
9306 }
9307 else if (args_[0] == "keep_ki")
9308 {
9309 reset_type = ResetSoftKeepKI;
9310 }
9311 else
9312 {
9313 PRINT_USAGE(USAGE_RESCAN_BC);
9314 return true;
9315 }
9316
9317 if (args_.size() > 1)
9318 {
9319 try
9320 {
9321 start_height = boost::lexical_cast<uint64_t>( args_[1] );
9322 }
9323 catch(const boost::bad_lexical_cast &)
9324 {
9325 start_height = 0;
9326 }
9327 }
9328 }
9329
9330 if (reset_type == ResetHard)
9331 {
9332 message_writer() << tr("Warning: this will lose any information which can not be recovered from the blockchain.");
9333 message_writer() << tr("This includes destination addresses, tx secret keys, tx notes, etc");
9334 std::string confirm = input_line(tr("Rescan anyway?"), true);
9335 if(!std::cin.eof())
9336 {
9337 if (!command_line::is_yes(confirm))
9338 return true;
9339 }
9340 }
9341
9342 const uint64_t wallet_from_height = m_wallet->get_refresh_from_block_height();
9343 if (start_height > wallet_from_height)
9344 {
9345 message_writer() << tr("Warning: your restore height is higher than wallet restore height: ") << wallet_from_height;
9346 std::string confirm = input_line(tr("Rescan anyway ? (Y/Yes/N/No): "));
9347 if(!std::cin.eof())
9348 {
9349 if (!command_line::is_yes(confirm))
9350 return true;
9351 }
9352 }
9353
9354 m_in_manual_refresh.store(true, std::memory_order_relaxed);
9355 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
9356 return refresh_main(start_height, reset_type, true);
9357 }
9358 //----------------------------------------------------------------------------------------------------
9359 void simple_wallet::check_for_messages()
9360 {
9361 try
9362 {
9363 std::vector<mms::message> new_messages;
9364 bool new_message = get_message_store().check_for_messages(get_multisig_wallet_state(), new_messages);
9365 if (new_message)
9366 {
9367 message_writer(console_color_magenta, true) << tr("MMS received new message");
9368 list_mms_messages(new_messages);
9369 m_cmd_binder.print_prompt();
9370 }
9371 }
9372 catch(...) {}
9373 }
9374 //----------------------------------------------------------------------------------------------------
9375 void simple_wallet::wallet_idle_thread()
9376 {
9377 const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
9378 while (true)
9379 {
9380 boost::unique_lock<boost::mutex> lock(m_idle_mutex);
9381 if (!m_idle_run.load(std::memory_order_relaxed))
9382 break;
9383
9384 // if another thread was busy (ie, a foreground refresh thread), we'll end up here at
9385 // some random time that's not what we slept for, so we should not call refresh now
9386 // or we'll be leaking that fact through timing
9387 const boost::posix_time::ptime now0 = boost::posix_time::microsec_clock::universal_time();
9388 const uint64_t dt_actual = (now0 - start_time).total_microseconds() % 1000000;
9389 #ifdef _WIN32
9390 static const uint64_t threshold = 10000;
9391 #else
9392 static const uint64_t threshold = 2000;
9393 #endif
9394 if (dt_actual < threshold) // if less than a threshold... would a very slow machine always miss it ?
9395 {
9396 #ifndef _WIN32
9397 m_inactivity_checker.do_call(boost::bind(&simple_wallet::check_inactivity, this));
9398 #endif
9399 m_refresh_checker.do_call(boost::bind(&simple_wallet::check_refresh, this));
9400 m_mms_checker.do_call(boost::bind(&simple_wallet::check_mms, this));
9401 m_rpc_payment_checker.do_call(boost::bind(&simple_wallet::check_rpc_payment, this));
9402
9403 if (!m_idle_run.load(std::memory_order_relaxed))
9404 break;
9405 }
9406
9407 // aim for the next multiple of 1 second
9408 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
9409 const auto dt = (now - start_time).total_microseconds();
9410 const auto wait = 1000000 - dt % 1000000;
9411 m_idle_cond.wait_for(lock, boost::chrono::microseconds(wait));
9412 }
9413 }
9414 //----------------------------------------------------------------------------------------------------
9415 bool simple_wallet::check_inactivity()
9416 {
9417 // inactivity lock
9418 if (!m_locked && !m_in_command)
9419 {
9420 const uint32_t seconds = m_wallet->inactivity_lock_timeout();
9421 if (seconds > 0 && time(NULL) - m_last_activity_time > seconds)
9422 {
9423 m_locked = true;
9424 m_cmd_binder.cancel_input();
9425 }
9426 }
9427 return true;
9428 }
9429 //----------------------------------------------------------------------------------------------------
9430 bool simple_wallet::check_refresh()
9431 {
9432 // auto refresh
9433 if (m_auto_refresh_enabled)
9434 {
9435 m_auto_refresh_refreshing = true;
9436 try
9437 {
9438 uint64_t fetched_blocks;
9439 bool received_money;
9440 if (try_connect_to_daemon(true))
9441 m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, fetched_blocks, received_money, false); // don't check the pool in background mode
9442 }
9443 catch(...) {}
9444 m_auto_refresh_refreshing = false;
9445 }
9446 return true;
9447 }
9448 //----------------------------------------------------------------------------------------------------
9449 bool simple_wallet::check_mms()
9450 {
9451 // Check for new MMS messages;
9452 // For simplicity auto message check is ALSO controlled by "m_auto_refresh_enabled" and has no
9453 // separate thread either; thread syncing is tricky enough with only this one idle thread here
9454 if (m_auto_refresh_enabled && get_message_store().get_active())
9455 {
9456 check_for_messages();
9457 }
9458 return true;
9459 }
9460 //----------------------------------------------------------------------------------------------------
9461 bool simple_wallet::check_rpc_payment()
9462 {
9463 if (!m_rpc_payment_mining_requested && m_wallet->auto_mine_for_rpc_payment_threshold() == 0.0f)
9464 return true;
9465
9466 uint64_t target = m_wallet->credits_target();
9467 if (target == 0)
9468 target = CREDITS_TARGET;
9469 if (m_rpc_payment_mining_requested)
9470 target = std::numeric_limits<uint64_t>::max();
9471 bool need_payment = m_need_payment || m_rpc_payment_mining_requested || (m_wallet->credits() < target && m_wallet->daemon_requires_payment());
9472 if (need_payment)
9473 {
9474 const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
9475 auto startfunc = [this](uint64_t diff, uint64_t credits_per_hash_found)
9476 {
9477 const float cph = credits_per_hash_found / (float)diff;
9478 bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
9479 if (credits_per_hash_found > 0 && cph >= m_wallet->auto_mine_for_rpc_payment_threshold())
9480 {
9481 MINFO(std::to_string(cph) << " credits per hash is >= our threshold (" << m_wallet->auto_mine_for_rpc_payment_threshold() << "), starting mining");
9482 return true;
9483 }
9484 else if (m_rpc_payment_mining_requested)
9485 {
9486 MINFO("Mining for RPC payment was requested, starting mining");
9487 return true;
9488 }
9489 else
9490 {
9491 if (!m_daemon_rpc_payment_message_displayed)
9492 {
9493 success_msg_writer() << boost::format(tr("Daemon requests payment at diff %llu, with %f credits/hash%s. Run start_mining_for_rpc to start mining to pay for RPC access, or use another daemon")) %
9494 diff % cph % (low ? " - this is low" : "");
9495 m_cmd_binder.print_prompt();
9496 m_daemon_rpc_payment_message_displayed = true;
9497 }
9498 return false;
9499 }
9500 };
9501 auto contfunc = [&,this](unsigned n_hashes)
9502 {
9503 if (m_suspend_rpc_payment_mining.load(std::memory_order_relaxed))
9504 return false;
9505 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
9506 m_last_rpc_payment_mining_time = now;
9507 if ((now - start_time).total_microseconds() >= 2 * 1000000)
9508 m_rpc_payment_hash_rate = n_hashes / (float)((now - start_time).total_seconds());
9509 if ((now - start_time).total_microseconds() >= REFRESH_PERIOD * 1000000)
9510 return false;
9511 return true;
9512 };
9513 auto foundfunc = [this, target](uint64_t credits)
9514 {
9515 m_need_payment = false;
9516 return credits < target;
9517 };
9518 auto errorfunc = [this](const std::string &error)
9519 {
9520 fail_msg_writer() << tr("Error mining to daemon: ") << error;
9521 m_cmd_binder.print_prompt();
9522 };
9523 bool ret = m_wallet->search_for_rpc_payment(target, m_rpc_payment_threads, startfunc, contfunc, foundfunc, errorfunc);
9524 if (!ret)
9525 {
9526 fail_msg_writer() << tr("Failed to start mining for RPC payment");
9527 m_cmd_binder.print_prompt();
9528 }
9529 }
9530 return true;
9531 }
9532 //----------------------------------------------------------------------------------------------------
9533 std::string simple_wallet::get_prompt() const
9534 {
9535 if (m_locked)
9536 return std::string("[") + tr("locked due to inactivity") + "]";
9537 std::string addr_start = m_wallet->get_subaddress_as_str({m_current_subaddress_account, 0}).substr(0, 6);
9538 std::string prompt = std::string("[") + tr("wallet") + " " + addr_start;
9539 if (!m_wallet->check_connection(NULL))
9540 prompt += tr(" (no daemon)");
9541 else if (!m_wallet->is_synced())
9542 prompt += tr(" (out of sync)");
9543 prompt += "]: ";
9544 return prompt;
9545 }
9546 //----------------------------------------------------------------------------------------------------
9547 bool simple_wallet::run()
9548 {
9549 // check and display warning, but go on anyway
9550 try_connect_to_daemon();
9551
9552 refresh_main(0, ResetNone, true);
9553
9554 m_auto_refresh_enabled = !m_wallet->is_offline() && m_wallet->auto_refresh();
9555 m_idle_thread = boost::thread([&]{wallet_idle_thread();});
9556
9557 message_writer(console_color_green, false) << "Background refresh thread started";
9558 return m_cmd_binder.run_handling([this](){return get_prompt();}, "");
9559 }
9560 //----------------------------------------------------------------------------------------------------
9561 void simple_wallet::stop()
9562 {
9563 m_cmd_binder.stop_handling();
9564 }
9565 //----------------------------------------------------------------------------------------------------
9566 bool simple_wallet::account(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9567 {
9568 // Usage:
9569 // account
9570 // account new <label text with white spaces allowed>
9571 // account switch <index>
9572 // account label <index> <label text with white spaces allowed>
9573 // account tag <tag_name> <account_index_1> [<account_index_2> ...]
9574 // account untag <account_index_1> [<account_index_2> ...]
9575 // account tag_description <tag_name> <description>
9576
9577 if (args.empty())
9578 {
9579 // print all the existing accounts
9580 LOCK_IDLE_SCOPE();
9581 print_accounts();
9582 return true;
9583 }
9584
9585 std::vector<std::string> local_args = args;
9586 std::string command = local_args[0];
9587 local_args.erase(local_args.begin());
9588 if (command == "new")
9589 {
9590 // create a new account and switch to it
9591 CHECK_IF_BACKGROUND_SYNCING("cannot create new account");
9592 std::string label = boost::join(local_args, " ");
9593 if (label.empty())
9594 label = tr("(Untitled account)");
9595 m_wallet->add_subaddress_account(label);
9596 m_current_subaddress_account = m_wallet->get_num_subaddress_accounts() - 1;
9597 // update_prompt();
9598 LOCK_IDLE_SCOPE();
9599 print_accounts();
9600 }
9601 else if (command == "switch" && local_args.size() == 1)
9602 {
9603 // switch to the specified account
9604 uint32_t index_major;
9605 if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
9606 {
9607 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9608 return true;
9609 }
9610 if (index_major >= m_wallet->get_num_subaddress_accounts())
9611 {
9612 fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddress_accounts() - 1);
9613 return true;
9614 }
9615 m_current_subaddress_account = index_major;
9616 // update_prompt();
9617 show_balance();
9618 }
9619 else if (command == "label" && local_args.size() >= 1)
9620 {
9621 // set label of the specified account
9622 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9623 uint32_t index_major;
9624 if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
9625 {
9626 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9627 return true;
9628 }
9629 local_args.erase(local_args.begin());
9630 std::string label = boost::join(local_args, " ");
9631 try
9632 {
9633 m_wallet->set_subaddress_label({index_major, 0}, label);
9634 LOCK_IDLE_SCOPE();
9635 print_accounts();
9636 }
9637 catch (const std::exception& e)
9638 {
9639 fail_msg_writer() << e.what();
9640 }
9641 }
9642 else if (command == "tag" && local_args.size() >= 2)
9643 {
9644 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9645 const std::string tag = local_args[0];
9646 std::set<uint32_t> account_indices;
9647 for (size_t i = 1; i < local_args.size(); ++i)
9648 {
9649 uint32_t account_index;
9650 if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
9651 {
9652 fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
9653 return true;
9654 }
9655 account_indices.insert(account_index);
9656 }
9657 try
9658 {
9659 m_wallet->set_account_tag(account_indices, tag);
9660 print_accounts(tag);
9661 }
9662 catch (const std::exception& e)
9663 {
9664 fail_msg_writer() << e.what();
9665 }
9666 }
9667 else if (command == "untag" && local_args.size() >= 1)
9668 {
9669 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9670 std::set<uint32_t> account_indices;
9671 for (size_t i = 0; i < local_args.size(); ++i)
9672 {
9673 uint32_t account_index;
9674 if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
9675 {
9676 fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
9677 return true;
9678 }
9679 account_indices.insert(account_index);
9680 }
9681 try
9682 {
9683 m_wallet->set_account_tag(account_indices, "");
9684 print_accounts();
9685 }
9686 catch (const std::exception& e)
9687 {
9688 fail_msg_writer() << e.what();
9689 }
9690 }
9691 else if (command == "tag_description" && local_args.size() >= 1)
9692 {
9693 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9694 const std::string tag = local_args[0];
9695 std::string description;
9696 if (local_args.size() > 1)
9697 {
9698 local_args.erase(local_args.begin());
9699 description = boost::join(local_args, " ");
9700 }
9701 try
9702 {
9703 m_wallet->set_account_tag_description(tag, description);
9704 print_accounts(tag);
9705 }
9706 catch (const std::exception& e)
9707 {
9708 fail_msg_writer() << e.what();
9709 }
9710 }
9711 else
9712 {
9713 PRINT_USAGE(USAGE_ACCOUNT);
9714 }
9715 return true;
9716 }
9717 //----------------------------------------------------------------------------------------------------
9718 void simple_wallet::print_accounts()
9719 {
9720 const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
9721 size_t num_untagged_accounts = m_wallet->get_num_subaddress_accounts();
9722 for (const std::pair<const std::string, std::string>& p : account_tags.first)
9723 {
9724 const std::string& tag = p.first;
9725 print_accounts(tag);
9726 num_untagged_accounts -= std::count(account_tags.second.begin(), account_tags.second.end(), tag);
9727 success_msg_writer() << "";
9728 }
9729
9730 if (num_untagged_accounts > 0)
9731 print_accounts("");
9732
9733 if (num_untagged_accounts < m_wallet->get_num_subaddress_accounts())
9734 success_msg_writer() << tr("\nGrand total:\n Balance: ") << print_money(m_wallet->balance_all(false)) << tr(", unlocked balance: ") << print_money(m_wallet->unlocked_balance_all(false));
9735 }
9736 //----------------------------------------------------------------------------------------------------
9737 void simple_wallet::print_accounts(const std::string& tag)
9738 {
9739 const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
9740 if (tag.empty())
9741 {
9742 success_msg_writer() << tr("Untagged accounts:");
9743 }
9744 else
9745 {
9746 if (account_tags.first.count(tag) == 0)
9747 {
9748 fail_msg_writer() << boost::format(tr("Tag %s is unregistered.")) % tag;
9749 return;
9750 }
9751 success_msg_writer() << tr("Accounts with tag: ") << tag;
9752 success_msg_writer() << tr("Tag's description: ") << account_tags.first.find(tag)->second;
9753 }
9754 success_msg_writer() << boost::format(" %15s %21s %21s %21s") % tr("Account") % tr("Balance") % tr("Unlocked balance") % tr("Label");
9755 uint64_t total_balance = 0, total_unlocked_balance = 0;
9756 for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
9757 {
9758 if (account_tags.second[account_index] != tag)
9759 continue;
9760 success_msg_writer() << boost::format(tr(" %c%8u %6s %21s %21s %21s"))
9761 % (m_current_subaddress_account == account_index ? '*' : ' ')
9762 % account_index
9763 % m_wallet->get_subaddress_as_str({account_index, 0}).substr(0, 6)
9764 % print_money(m_wallet->balance(account_index, false))
9765 % print_money(m_wallet->unlocked_balance(account_index, false))
9766 % m_wallet->get_subaddress_label({account_index, 0});
9767 total_balance += m_wallet->balance(account_index, false);
9768 total_unlocked_balance += m_wallet->unlocked_balance(account_index, false);
9769 }
9770 success_msg_writer() << tr("------------------------------------------------------------------------------------");
9771 success_msg_writer() << boost::format(tr("%15s %21s %21s")) % "Total" % print_money(total_balance) % print_money(total_unlocked_balance);
9772 }
9773 //----------------------------------------------------------------------------------------------------
9774 bool simple_wallet::print_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9775 {
9776 // Usage:
9777 // address
9778 // address new <label text with white spaces allowed>
9779 // address all
9780 // address <index_min> [<index_max>]
9781 // address label <index> <label text with white spaces allowed>
9782 // address device [<index>]
9783
9784 std::vector<std::string> local_args = args;
9785 tools::wallet2::transfer_container transfers;
9786 m_wallet->get_transfers(transfers);
9787
9788 auto print_address_sub = [this, &transfers](uint32_t index)
9789 {
9790 bool used = std::find_if(
9791 transfers.begin(), transfers.end(),
9792 [this, &index](const tools::wallet2::transfer_details& td) {
9793 return td.m_subaddr_index == cryptonote::subaddress_index{ m_current_subaddress_account, index };
9794 }) != transfers.end();
9795 success_msg_writer() << index << " " << m_wallet->get_subaddress_as_str({m_current_subaddress_account, index}) << " " << (index == 0 ? tr("Primary address") : m_wallet->get_subaddress_label({m_current_subaddress_account, index})) << " " << (used ? tr("(used)") : "");
9796 };
9797
9798 uint32_t index = 0;
9799 if (local_args.empty())
9800 {
9801 print_address_sub(index);
9802 }
9803 else if (local_args.size() == 1 && local_args[0] == "all")
9804 {
9805 local_args.erase(local_args.begin());
9806 for (; index < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++index)
9807 print_address_sub(index);
9808 }
9809 else if (local_args[0] == "new")
9810 {
9811 CHECK_IF_BACKGROUND_SYNCING("cannot add address");
9812 local_args.erase(local_args.begin());
9813 std::string label;
9814 if (local_args.size() > 0)
9815 label = boost::join(local_args, " ");
9816 if (label.empty())
9817 label = tr("(Untitled address)");
9818 m_wallet->add_subaddress(m_current_subaddress_account, label);
9819 print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9820 m_wallet->device_show_address(m_current_subaddress_account, m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1, boost::none);
9821 }
9822 else if (local_args[0] == "mnew")
9823 {
9824 CHECK_IF_BACKGROUND_SYNCING("cannot add addresses");
9825 local_args.erase(local_args.begin());
9826 if (local_args.size() != 1)
9827 {
9828 fail_msg_writer() << tr("Expected exactly one argument for the amount of new addresses");
9829 return true;
9830 }
9831 uint32_t n;
9832 if (!epee::string_tools::get_xtype_from_string(n, local_args[0]))
9833 {
9834 fail_msg_writer() << tr("failed to parse the amount of new addresses: ") << local_args[0];
9835 return true;
9836 }
9837 if (n > MAX_MNEW_ADDRESSES)
9838 {
9839 fail_msg_writer() << tr("the amount of new addresses must be lower or equal to ") << MAX_MNEW_ADDRESSES;
9840 return true;
9841 }
9842 for (uint32_t i = 0; i < n; ++i)
9843 {
9844 m_wallet->add_subaddress(m_current_subaddress_account, tr("(Untitled address)"));
9845 print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9846 }
9847 }
9848 else if (local_args[0] == "one-off")
9849 {
9850 CHECK_IF_BACKGROUND_SYNCING("cannot add address");
9851 local_args.erase(local_args.begin());
9852 std::string label;
9853 if (local_args.size() != 2)
9854 {
9855 fail_msg_writer() << tr("Expected exactly two arguments for index");
9856 return true;
9857 }
9858 uint32_t major, minor;
9859 if (!epee::string_tools::get_xtype_from_string(major, local_args[0]) || !epee::string_tools::get_xtype_from_string(minor, local_args[1]))
9860 {
9861 fail_msg_writer() << tr("failed to parse index: ") << local_args[0] << " " << local_args[1];
9862 return true;
9863 }
9864 m_wallet->create_one_off_subaddress({major, minor});
9865 success_msg_writer() << boost::format(tr("Address at %u %u: %s")) % major % minor % m_wallet->get_subaddress_as_str({major, minor});
9866 }
9867 else if (local_args.size() >= 2 && local_args[0] == "label")
9868 {
9869 CHECK_IF_BACKGROUND_SYNCING("cannot modify address");
9870 if (!epee::string_tools::get_xtype_from_string(index, local_args[1]))
9871 {
9872 fail_msg_writer() << tr("failed to parse index: ") << local_args[1];
9873 return true;
9874 }
9875 if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9876 {
9877 fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9878 return true;
9879 }
9880 local_args.erase(local_args.begin());
9881 local_args.erase(local_args.begin());
9882 std::string label = boost::join(local_args, " ");
9883 m_wallet->set_subaddress_label({m_current_subaddress_account, index}, label);
9884 print_address_sub(index);
9885 }
9886 else if (local_args.size() <= 2 && epee::string_tools::get_xtype_from_string(index, local_args[0]))
9887 {
9888 local_args.erase(local_args.begin());
9889 uint32_t index_min = index;
9890 uint32_t index_max = index_min;
9891 if (local_args.size() > 0)
9892 {
9893 if (!epee::string_tools::get_xtype_from_string(index_max, local_args[0]))
9894 {
9895 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9896 return true;
9897 }
9898 local_args.erase(local_args.begin());
9899 }
9900 if (index_max < index_min)
9901 std::swap(index_min, index_max);
9902 if (index_min >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9903 {
9904 fail_msg_writer() << tr("<index_min> is already out of bound");
9905 return true;
9906 }
9907 if (index_max >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9908 {
9909 message_writer() << tr("<index_max> exceeds the bound");
9910 index_max = m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1;
9911 }
9912 for (index = index_min; index <= index_max; ++index)
9913 print_address_sub(index);
9914 }
9915 else if (local_args[0] == "device")
9916 {
9917 index = 0;
9918 local_args.erase(local_args.begin());
9919 if (local_args.size() > 0)
9920 {
9921 if (!epee::string_tools::get_xtype_from_string(index, local_args[0]))
9922 {
9923 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9924 return true;
9925 }
9926 if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9927 {
9928 fail_msg_writer() << tr("<index> is out of bounds");
9929 return true;
9930 }
9931 }
9932
9933 print_address_sub(index);
9934 m_wallet->device_show_address(m_current_subaddress_account, index, boost::none);
9935 }
9936 else
9937 {
9938 PRINT_USAGE(USAGE_ADDRESS);
9939 }
9940
9941 return true;
9942 }
9943 //----------------------------------------------------------------------------------------------------
9944 bool simple_wallet::print_integrated_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9945 {
9946 crypto::hash8 payment_id;
9947 bool display_on_device = false;
9948 std::vector<std::string> local_args = args;
9949
9950 if (local_args.size() > 0 && local_args[0] == "device")
9951 {
9952 local_args.erase(local_args.begin());
9953 display_on_device = true;
9954 }
9955
9956 auto device_show_integrated = [this, display_on_device](crypto::hash8 payment_id)
9957 {
9958 if (display_on_device)
9959 {
9960 m_wallet->device_show_address(m_current_subaddress_account, 0, payment_id);
9961 }
9962 };
9963
9964 if (local_args.size() > 1)
9965 {
9966 PRINT_USAGE(USAGE_INTEGRATED_ADDRESS);
9967 return true;
9968 }
9969 if (local_args.size() == 0)
9970 {
9971 if (m_current_subaddress_account != 0)
9972 {
9973 fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
9974 return true;
9975 }
9976 payment_id = crypto::rand<crypto::hash8>();
9977 success_msg_writer() << tr("Random payment ID: ") << payment_id;
9978 success_msg_writer() << tr("Matching integrated address: ") << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
9979 device_show_integrated(payment_id);
9980 return true;
9981 }
9982 if(tools::wallet2::parse_short_payment_id(local_args.back(), payment_id))
9983 {
9984 if (m_current_subaddress_account != 0)
9985 {
9986 fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
9987 return true;
9988 }
9989 success_msg_writer() << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
9990 device_show_integrated(payment_id);
9991 return true;
9992 }
9993 else {
9994 address_parse_info info;
9995 if(get_account_address_from_str(info, m_wallet->nettype(), local_args.back()))
9996 {
9997 if (info.has_payment_id)
9998 {
9999 success_msg_writer() << boost::format(tr("Standard address: %s, payment ID: %s")) %
10000 get_account_address_as_str(m_wallet->nettype(), false, info.address) % epee::string_tools::pod_to_hex(info.payment_id);
10001 device_show_integrated(info.payment_id);
10002 }
10003 else
10004 {
10005 success_msg_writer() << (info.is_subaddress ? tr("Subaddress: ") : tr("Standard address: ")) << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
10006 }
10007 return true;
10008 }
10009 }
10010 fail_msg_writer() << tr("failed to parse payment ID or address");
10011 return true;
10012 }
10013 //----------------------------------------------------------------------------------------------------
10014 bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
10015 {
10016 CHECK_IF_BACKGROUND_SYNCING("cannot get address book");
10017
10018 if (args.size() == 0)
10019 {
10020 }
10021 else if (args.size() == 1 || (args[0] != "add" && args[0] != "delete"))
10022 {
10023 PRINT_USAGE(USAGE_ADDRESS_BOOK);
10024 return true;
10025 }
10026 else if (args[0] == "add")
10027 {
10028 cryptonote::address_parse_info info;
10029 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
10030 {
10031 fail_msg_writer() << tr("failed to parse address");
10032 return true;
10033 }
10034 size_t description_start = 2;
10035 std::string description;
10036 for (size_t i = description_start; i < args.size(); ++i)
10037 {
10038 if (i > description_start)
10039 description += " ";
10040 description += args[i];
10041 }
10042 m_wallet->add_address_book_row(info.address, info.has_payment_id ? &info.payment_id : NULL, description, info.is_subaddress);
10043 }
10044 else
10045 {
10046 size_t row_id;
10047 if(!epee::string_tools::get_xtype_from_string(row_id, args[1]))
10048 {
10049 fail_msg_writer() << tr("failed to parse index");
10050 return true;
10051 }
10052 m_wallet->delete_address_book_row(row_id);
10053 }
10054 auto address_book = m_wallet->get_address_book();
10055 if (address_book.empty())
10056 {
10057 success_msg_writer() << tr("Address book is empty.");
10058 }
10059 else
10060 {
10061 for (size_t i = 0; i < address_book.size(); ++i) {
10062 auto& row = address_book[i];
10063 success_msg_writer() << tr("Index: ") << i;
10064 std::string address;
10065 if (row.m_has_payment_id)
10066 address = cryptonote::get_account_integrated_address_as_str(m_wallet->nettype(), row.m_address, row.m_payment_id);
10067 else
10068 address = get_account_address_as_str(m_wallet->nettype(), row.m_is_subaddress, row.m_address);
10069 success_msg_writer() << tr("Address: ") << address;
10070 success_msg_writer() << tr("Description: ") << row.m_description << "\n";
10071 }
10072 }
10073 return true;
10074 }
10075 //----------------------------------------------------------------------------------------------------
10076 bool simple_wallet::set_tx_note(const std::vector<std::string> &args)
10077 {
10078 CHECK_IF_BACKGROUND_SYNCING("cannot set tx note");
10079
10080 if (args.size() == 0)
10081 {
10082 PRINT_USAGE(USAGE_SET_TX_NOTE);
10083 return true;
10084 }
10085
10086 cryptonote::blobdata txid_data;
10087 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10088 {
10089 fail_msg_writer() << tr("failed to parse txid");
10090 return true;
10091 }
10092 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10093
10094 std::string note = "";
10095 for (size_t n = 1; n < args.size(); ++n)
10096 {
10097 if (n > 1)
10098 note += " ";
10099 note += args[n];
10100 }
10101 m_wallet->set_tx_note(txid, note);
10102
10103 return true;
10104 }
10105 //----------------------------------------------------------------------------------------------------
10106 bool simple_wallet::get_tx_note(const std::vector<std::string> &args)
10107 {
10108 CHECK_IF_BACKGROUND_SYNCING("cannot get tx note");
10109
10110 if (args.size() != 1)
10111 {
10112 PRINT_USAGE(USAGE_GET_TX_NOTE);
10113 return true;
10114 }
10115
10116 cryptonote::blobdata txid_data;
10117 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10118 {
10119 fail_msg_writer() << tr("failed to parse txid");
10120 return true;
10121 }
10122 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10123
10124 std::string note = m_wallet->get_tx_note(txid);
10125 if (note.empty())
10126 success_msg_writer() << "no note found";
10127 else
10128 success_msg_writer() << "note found: " << note;
10129
10130 return true;
10131 }
10132 //----------------------------------------------------------------------------------------------------
10133 bool simple_wallet::set_description(const std::vector<std::string> &args)
10134 {
10135 CHECK_IF_BACKGROUND_SYNCING("cannot set description");
10136
10137 // 0 arguments allowed, for setting the description to empty string
10138
10139 std::string description = "";
10140 for (size_t n = 0; n < args.size(); ++n)
10141 {
10142 if (n > 0)
10143 description += " ";
10144 description += args[n];
10145 }
10146 m_wallet->set_description(description);
10147
10148 return true;
10149 }
10150 //----------------------------------------------------------------------------------------------------
10151 bool simple_wallet::get_description(const std::vector<std::string> &args)
10152 {
10153 CHECK_IF_BACKGROUND_SYNCING("cannot get description");
10154
10155 if (args.size() != 0)
10156 {
10157 PRINT_USAGE(USAGE_GET_DESCRIPTION);
10158 return true;
10159 }
10160
10161 std::string description = m_wallet->get_description();
10162 if (description.empty())
10163 success_msg_writer() << tr("no description found");
10164 else
10165 success_msg_writer() << tr("description found: ") << description;
10166
10167 return true;
10168 }
10169 //----------------------------------------------------------------------------------------------------
10170 bool simple_wallet::status(const std::vector<std::string> &args)
10171 {
10172 uint64_t local_height = m_wallet->get_blockchain_current_height();
10173 uint32_t version = 0;
10174 bool ssl = false;
10175 if (!m_wallet->check_connection(&version, &ssl))
10176 {
10177 success_msg_writer() << "Refreshed " << local_height << "/?, no daemon connected";
10178 return true;
10179 }
10180
10181 std::string err;
10182 uint64_t bc_height = get_daemon_blockchain_height(err);
10183 if (err.empty())
10184 {
10185 bool synced = local_height == bc_height;
10186 success_msg_writer() << "Refreshed " << local_height << "/" << bc_height << ", " << (synced ? "synced" : "syncing")
10187 << ", daemon RPC v" << get_version_string(version) << ", " << (ssl ? "SSL" : "no SSL");
10188 }
10189 else
10190 {
10191 fail_msg_writer() << "Refreshed " << local_height << "/?, daemon connection error";
10192 }
10193 return true;
10194 }
10195 //----------------------------------------------------------------------------------------------------
10196 bool simple_wallet::wallet_info(const std::vector<std::string> &args)
10197 {
10198 bool ready;
10199 uint32_t threshold, total;
10200 std::string description = m_wallet->get_description();
10201 if (description.empty())
10202 {
10203 description = "<Not set>";
10204 }
10205 message_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
10206 message_writer() << tr("Description: ") << description;
10207 message_writer() << tr("Address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
10208 std::string type;
10209 if (m_wallet->watch_only())
10210 type = tr("Watch only");
10211 else if (m_wallet->multisig(&ready, &threshold, &total))
10212 type = (boost::format(tr("%u/%u multisig%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
10213 else if (m_wallet->is_background_wallet())
10214 type = tr("Background wallet");
10215 else
10216 type = tr("Normal");
10217 message_writer() << tr("Type: ") << type;
10218 message_writer() << tr("Network type: ") << (
10219 m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
10220 m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet"));
10221 return true;
10222 }
10223 //----------------------------------------------------------------------------------------------------
10224 bool simple_wallet::sign(const std::vector<std::string> &args)
10225 {
10226 CHECK_IF_BACKGROUND_SYNCING("cannot sign");
10227 if (m_wallet->key_on_device())
10228 {
10229 fail_msg_writer() << tr("command not supported by HW wallet");
10230 return true;
10231 }
10232 if (args.size() != 1 && args.size() != 2 && args.size() != 3)
10233 {
10234 PRINT_USAGE(USAGE_SIGN);
10235 return true;
10236 }
10237 if (m_wallet->watch_only())
10238 {
10239 fail_msg_writer() << tr("wallet is watch-only and cannot sign");
10240 return true;
10241 }
10242 if (m_wallet->multisig())
10243 {
10244 fail_msg_writer() << tr("This wallet is multisig and cannot sign");
10245 return true;
10246 }
10247
10248 tools::wallet2::message_signature_type_t message_signature_type = tools::wallet2::sign_with_spend_key;
10249 subaddress_index index{0, 0};
10250 for (unsigned int idx = 0; idx + 1 < args.size(); ++idx)
10251 {
10252 unsigned int a, b;
10253 if (sscanf(args[idx].c_str(), "%u,%u", &a, &b) == 2)
10254 {
10255 index.major = a;
10256 index.minor = b;
10257 }
10258 else if (args[idx] == "--spend")
10259 {
10260 message_signature_type = tools::wallet2::sign_with_spend_key;
10261 }
10262 else if (args[idx] == "--view")
10263 {
10264 message_signature_type = tools::wallet2::sign_with_view_key;
10265 }
10266 else
10267 {
10268 fail_msg_writer() << tr("Invalid subaddress index format, and not a signature type: ") << args[idx];
10269 return true;
10270 }
10271 }
10272
10273 const std::string &filename = args.back();
10274 std::string data;
10275 bool r = m_wallet->load_from_file(filename, data);
10276 if (!r)
10277 {
10278 fail_msg_writer() << tr("failed to read file ") << filename;
10279 return true;
10280 }
10281
10282 SCOPED_WALLET_UNLOCK();
10283
10284 std::string signature = m_wallet->sign(data, message_signature_type, index);
10285 success_msg_writer() << signature;
10286 return true;
10287 }
10288 //----------------------------------------------------------------------------------------------------
10289 bool simple_wallet::verify(const std::vector<std::string> &args)
10290 {
10291 if (args.size() != 3)
10292 {
10293 PRINT_USAGE(USAGE_VERIFY);
10294 return true;
10295 }
10296 std::string filename = args[0];
10297 std::string address_string = args[1];
10298 std::string signature= args[2];
10299
10300 std::string data;
10301 bool r = m_wallet->load_from_file(filename, data);
10302 if (!r)
10303 {
10304 fail_msg_writer() << tr("failed to read file ") << filename;
10305 return true;
10306 }
10307
10308 cryptonote::address_parse_info info;
10309 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_string, oa_prompter))
10310 {
10311 fail_msg_writer() << tr("failed to parse address");
10312 return true;
10313 }
10314
10315 tools::wallet2::message_signature_result_t result = m_wallet->verify(data, info.address, signature);
10316 if (!result.valid)
10317 {
10318 fail_msg_writer() << tr("Bad signature from ") << address_string;
10319 }
10320 else
10321 {
10322 success_msg_writer() << tr("Good signature from ") << address_string << (result.old ? " (using old signature algorithm)" : "") << " with " << (result.type == tools::wallet2::sign_with_spend_key ? "spend key" : result.type == tools::wallet2::sign_with_view_key ? "view key" : "unknown key combination (suspicious)");
10323 }
10324 return true;
10325 }
10326 //----------------------------------------------------------------------------------------------------
10327 bool simple_wallet::export_key_images(const std::vector<std::string> &args_)
10328 {
10329 if (m_wallet->key_on_device())
10330 {
10331 fail_msg_writer() << tr("command not supported by HW wallet");
10332 return true;
10333 }
10334 CHECK_IF_BACKGROUND_SYNCING("cannot export key images");
10335 auto args = args_;
10336
10337 if (m_wallet->watch_only())
10338 {
10339 fail_msg_writer() << tr("wallet is watch-only and cannot export key images");
10340 return true;
10341 }
10342
10343 bool all = false;
10344 if (args.size() >= 2 && args[0] == "all")
10345 {
10346 all = true;
10347 args.erase(args.begin());
10348 }
10349
10350 if (args.size() != 1)
10351 {
10352 PRINT_USAGE(USAGE_EXPORT_KEY_IMAGES);
10353 return true;
10354 }
10355
10356 std::string filename = args[0];
10357 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
10358 return true;
10359
10360 SCOPED_WALLET_UNLOCK();
10361
10362 try
10363 {
10364 if (!m_wallet->export_key_images(filename, all))
10365 {
10366 fail_msg_writer() << tr("failed to save file ") << filename;
10367 return true;
10368 }
10369 }
10370 catch (const std::exception &e)
10371 {
10372 LOG_ERROR("Error exporting key images: " << e.what());
10373 fail_msg_writer() << "Error exporting key images: " << e.what();
10374 return true;
10375 }
10376
10377 success_msg_writer() << tr("Signed key images exported to ") << filename;
10378 return true;
10379 }
10380 //----------------------------------------------------------------------------------------------------
10381 bool simple_wallet::import_key_images(const std::vector<std::string> &args)
10382 {
10383 if (m_wallet->key_on_device())
10384 {
10385 fail_msg_writer() << tr("command not supported by HW wallet");
10386 return true;
10387 }
10388 CHECK_IF_BACKGROUND_SYNCING("cannot import key images");
10389 if (!m_wallet->is_trusted_daemon())
10390 {
10391 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
10392 return true;
10393 }
10394
10395 if (args.size() != 1)
10396 {
10397 PRINT_USAGE(USAGE_IMPORT_KEY_IMAGES);
10398 return true;
10399 }
10400 std::string filename = args[0];
10401
10402 LOCK_IDLE_SCOPE();
10403 try
10404 {
10405 uint64_t spent = 0, unspent = 0;
10406 uint64_t height = m_wallet->import_key_images(filename, spent, unspent);
10407 success_msg_writer() << "Signed key images imported to height " << height << ", "
10408 << print_money(spent) << " spent, " << print_money(unspent) << " unspent";
10409 }
10410 catch (const std::exception &e)
10411 {
10412 fail_msg_writer() << "Failed to import key images: " << e.what();
10413 return true;
10414 }
10415
10416 return true;
10417 }
10418 //----------------------------------------------------------------------------------------------------
10419 bool simple_wallet::hw_key_images_sync(const std::vector<std::string> &args)
10420 {
10421 if (!m_wallet->key_on_device())
10422 {
10423 fail_msg_writer() << tr("command only supported by HW wallet");
10424 return true;
10425 }
10426 if (!m_wallet->get_account().get_device().has_ki_cold_sync())
10427 {
10428 fail_msg_writer() << tr("hw wallet does not support cold KI sync");
10429 return true;
10430 }
10431
10432 LOCK_IDLE_SCOPE();
10433 key_images_sync_intern();
10434 return true;
10435 }
10436 //----------------------------------------------------------------------------------------------------
10437 void simple_wallet::key_images_sync_intern(){
10438 try
10439 {
10440 message_writer(console_color_white, false) << tr("Please confirm the key image sync on the device");
10441
10442 uint64_t spent = 0, unspent = 0;
10443 uint64_t height = m_wallet->cold_key_image_sync(spent, unspent);
10444 if (height > 0)
10445 {
10446 success_msg_writer() << tr("Key images synchronized to height ") << height;
10447 if (!m_wallet->is_trusted_daemon())
10448 {
10449 message_writer() << tr("Running untrusted daemon, cannot determine which transaction output is spent. Use a trusted daemon with --trusted-daemon and run rescan_spent");
10450 } else
10451 {
10452 success_msg_writer() << print_money(spent) << tr(" spent, ") << print_money(unspent) << tr(" unspent");
10453 }
10454 }
10455 else {
10456 fail_msg_writer() << tr("Failed to import key images");
10457 }
10458 }
10459 catch (const std::exception &e)
10460 {
10461 fail_msg_writer() << tr("Failed to import key images: ") << e.what();
10462 }
10463 }
10464 //----------------------------------------------------------------------------------------------------
10465 bool simple_wallet::hw_reconnect(const std::vector<std::string> &args)
10466 {
10467 if (!m_wallet->key_on_device())
10468 {
10469 fail_msg_writer() << tr("command only supported by HW wallet");
10470 return true;
10471 }
10472
10473 LOCK_IDLE_SCOPE();
10474 try
10475 {
10476 bool r = m_wallet->reconnect_device();
10477 if (!r){
10478 fail_msg_writer() << tr("Failed to reconnect device");
10479 }
10480 }
10481 catch (const std::exception &e)
10482 {
10483 fail_msg_writer() << tr("Failed to reconnect device: ") << tr(e.what());
10484 return true;
10485 }
10486
10487 return true;
10488 }
10489 //----------------------------------------------------------------------------------------------------
10490 bool simple_wallet::export_outputs(const std::vector<std::string> &args_)
10491 {
10492 if (m_wallet->key_on_device())
10493 {
10494 fail_msg_writer() << tr("command not supported by HW wallet");
10495 return true;
10496 }
10497 CHECK_IF_BACKGROUND_SYNCING("cannot export outputs");
10498 auto args = args_;
10499
10500 bool all = false;
10501 if (args.size() >= 2 && args[0] == "all")
10502 {
10503 all = true;
10504 args.erase(args.begin());
10505 }
10506
10507 if (args.size() != 1)
10508 {
10509 PRINT_USAGE(USAGE_EXPORT_OUTPUTS);
10510 return true;
10511 }
10512
10513 std::string filename = args[0];
10514 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
10515 return true;
10516
10517 SCOPED_WALLET_UNLOCK();
10518
10519 try
10520 {
10521 std::string data = m_wallet->export_outputs_to_str(all);
10522 bool r = m_wallet->save_to_file(filename, data);
10523 if (!r)
10524 {
10525 fail_msg_writer() << tr("failed to save file ") << filename;
10526 return true;
10527 }
10528 }
10529 catch (const std::exception &e)
10530 {
10531 LOG_ERROR("Error exporting outputs: " << e.what());
10532 fail_msg_writer() << "Error exporting outputs: " << e.what();
10533 return true;
10534 }
10535
10536 success_msg_writer() << tr("Outputs exported to ") << filename;
10537 return true;
10538 }
10539 //----------------------------------------------------------------------------------------------------
10540 bool simple_wallet::import_outputs(const std::vector<std::string> &args)
10541 {
10542 if (m_wallet->key_on_device())
10543 {
10544 fail_msg_writer() << tr("command not supported by HW wallet");
10545 return true;
10546 }
10547 CHECK_IF_BACKGROUND_SYNCING("cannot import outputs");
10548 if (args.size() != 1)
10549 {
10550 PRINT_USAGE(USAGE_IMPORT_OUTPUTS);
10551 return true;
10552 }
10553 std::string filename = args[0];
10554
10555 std::string data;
10556 bool r = m_wallet->load_from_file(filename, data);
10557 if (!r)
10558 {
10559 fail_msg_writer() << tr("failed to read file ") << filename;
10560 return true;
10561 }
10562
10563 try
10564 {
10565 SCOPED_WALLET_UNLOCK();
10566 size_t n_outputs = m_wallet->import_outputs_from_str(data);
10567 success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported";
10568 }
10569 catch (const std::exception &e)
10570 {
10571 fail_msg_writer() << "Failed to import outputs " << filename << ": " << e.what();
10572 return true;
10573 }
10574
10575 return true;
10576 }
10577 //----------------------------------------------------------------------------------------------------
10578 bool simple_wallet::show_transfer(const std::vector<std::string> &args)
10579 {
10580 if (args.size() != 1)
10581 {
10582 PRINT_USAGE(USAGE_SHOW_TRANSFER);
10583 return true;
10584 }
10585
10586 cryptonote::blobdata txid_data;
10587 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10588 {
10589 fail_msg_writer() << tr("failed to parse txid");
10590 return true;
10591 }
10592 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10593
10594 const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
10595
10596 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
10597 m_wallet->get_payments(payments, 0, (uint64_t)-1, m_current_subaddress_account);
10598 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
10599 const tools::wallet2::payment_details &pd = i->second;
10600 if (pd.m_tx_hash == txid) {
10601 std::string payment_id = string_tools::pod_to_hex(i->first);
10602 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10603 payment_id = payment_id.substr(0,16);
10604 success_msg_writer() << "Incoming transaction found";
10605 success_msg_writer() << "txid: " << txid;
10606 success_msg_writer() << "Height: " << pd.m_block_height;
10607 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10608 success_msg_writer() << "Amount: " << print_money(pd.m_amount);
10609 success_msg_writer() << "Payment ID: " << payment_id;
10610 if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
10611 {
10612 uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
10613 uint64_t last_block_reward = m_wallet->get_last_block_reward();
10614 uint64_t suggested_threshold = last_block_reward ? (pd.m_amount + last_block_reward - 1) / last_block_reward : 0;
10615 if (bh >= last_block_height)
10616 success_msg_writer() << "Locked: " << (bh - last_block_height) << " blocks to unlock";
10617 else if (suggested_threshold > 0)
10618 success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations (" << suggested_threshold << " suggested threshold)";
10619 else
10620 success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations";
10621 }
10622 else
10623 {
10624 const uint64_t adjusted_time = m_wallet->get_daemon_adjusted_time();
10625 uint64_t threshold = adjusted_time + (m_wallet->use_fork_rules(2, 0) ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1);
10626 if (threshold >= pd.m_unlock_time)
10627 success_msg_writer() << "unlocked for " << get_human_readable_timespan(std::chrono::seconds(threshold - pd.m_unlock_time));
10628 else
10629 success_msg_writer() << "locked for " << get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
10630 }
10631 success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
10632 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10633 return true;
10634 }
10635 }
10636
10637 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out;
10638 m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, m_current_subaddress_account);
10639 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) {
10640 if (i->first == txid)
10641 {
10642 const tools::wallet2::confirmed_transfer_details &pd = i->second;
10643 uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
10644 uint64_t fee = pd.m_amount_in - pd.m_amount_out;
10645 std::string dests;
10646 for (const auto &d: pd.m_dests) {
10647 if (!dests.empty())
10648 dests += ", ";
10649 dests += d.address(m_wallet->nettype(), pd.m_payment_id) + ": " + print_money(d.amount);
10650 }
10651 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
10652 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10653 payment_id = payment_id.substr(0,16);
10654 success_msg_writer() << "Outgoing transaction found";
10655 success_msg_writer() << "txid: " << txid;
10656 success_msg_writer() << "Height: " << pd.m_block_height;
10657 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10658 success_msg_writer() << "Amount: " << print_money(pd.m_amount_in - change - fee);
10659 success_msg_writer() << "Payment ID: " << payment_id;
10660 success_msg_writer() << "Change: " << print_money(change);
10661 success_msg_writer() << "Fee: " << print_money(fee);
10662 success_msg_writer() << "Destinations: " << dests;
10663 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10664 return true;
10665 }
10666 }
10667
10668 try
10669 {
10670 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
10671 m_wallet->update_pool_state(process_txs);
10672 if (!process_txs.empty())
10673 m_wallet->process_pool_state(process_txs);
10674
10675 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments;
10676 m_wallet->get_unconfirmed_payments(pool_payments, m_current_subaddress_account);
10677 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) {
10678 const tools::wallet2::payment_details &pd = i->second.m_pd;
10679 if (pd.m_tx_hash == txid)
10680 {
10681 std::string payment_id = string_tools::pod_to_hex(i->first);
10682 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10683 payment_id = payment_id.substr(0,16);
10684 success_msg_writer() << "Unconfirmed incoming transaction found in the txpool";
10685 success_msg_writer() << "txid: " << txid;
10686 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10687 success_msg_writer() << "Amount: " << print_money(pd.m_amount);
10688 success_msg_writer() << "Payment ID: " << payment_id;
10689 success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
10690 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10691 if (i->second.m_double_spend_seen)
10692 success_msg_writer() << tr("Double spend seen on the network: this transaction may or may not end up being mined");
10693 return true;
10694 }
10695 }
10696 }
10697 catch (...)
10698 {
10699 fail_msg_writer() << "Failed to get pool state";
10700 }
10701
10702 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
10703 m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account);
10704 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
10705 if (i->first == txid)
10706 {
10707 const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
10708 uint64_t amount = pd.m_amount_in;
10709 uint64_t fee = amount - pd.m_amount_out;
10710 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
10711 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10712 payment_id = payment_id.substr(0,16);
10713 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
10714
10715 success_msg_writer() << (is_failed ? "Failed" : "Pending") << " outgoing transaction found";
10716 success_msg_writer() << "txid: " << txid;
10717 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10718 success_msg_writer() << "Amount: " << print_money(amount - pd.m_change - fee);
10719 success_msg_writer() << "Payment ID: " << payment_id;
10720 success_msg_writer() << "Change: " << print_money(pd.m_change);
10721 success_msg_writer() << "Fee: " << print_money(fee);
10722 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10723 return true;
10724 }
10725 }
10726
10727 fail_msg_writer() << tr("Transaction ID not found");
10728 return true;
10729 }
10730 //----------------------------------------------------------------------------------------------------
10731 bool simple_wallet::process_command(const std::vector<std::string> &args)
10732 {
10733 return m_cmd_binder.process_command_vec(args);
10734 }
10735 //----------------------------------------------------------------------------------------------------
10736 void simple_wallet::interrupt()
10737 {
10738 if (m_in_manual_refresh.load(std::memory_order_relaxed))
10739 {
10740 m_wallet->stop();
10741 }
10742 else
10743 {
10744 stop();
10745 }
10746 }
10747 //----------------------------------------------------------------------------------------------------
10748 void simple_wallet::commit_or_save(std::vector<tools::wallet2::pending_tx>& ptx_vector, bool do_not_relay)
10749 {
10750 size_t i = 0;
10751 while (!ptx_vector.empty())
10752 {
10753 auto & ptx = ptx_vector.back();
10754 const crypto::hash txid = get_transaction_hash(ptx.tx);
10755 if (do_not_relay)
10756 {
10757 cryptonote::blobdata blob;
10758 tx_to_blob(ptx.tx, blob);
10759 const std::string blob_hex = epee::string_tools::buff_to_hex_nodelimer(blob);
10760 const std::string filename = "raw_monero_tx" + (ptx_vector.size() == 1 ? "" : ("_" + std::to_string(i++)));
10761 if (m_wallet->save_to_file(filename, blob_hex, true))
10762 success_msg_writer(true) << tr("Transaction successfully saved to ") << filename << tr(", txid ") << txid;
10763 else
10764 fail_msg_writer() << tr("Failed to save transaction to ") << filename << tr(", txid ") << txid;
10765 }
10766 else
10767 {
10768 m_wallet->commit_tx(ptx);
10769 success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << txid << ENDL
10770 << tr("You can check its status by using the `show_transfers` command.");
10771 }
10772 // if no exception, remove element from vector
10773 ptx_vector.pop_back();
10774 }
10775 }
10776 //----------------------------------------------------------------------------------------------------
10777 int main(int argc, char* argv[])
10778 {
10779 TRY_ENTRY();
10780
10781 #ifdef WIN32
10782 // Activate UTF-8 support for Boost filesystem classes on Windows
10783 std::locale::global(boost::locale::generator().generate(""));
10784 boost::filesystem::path::imbue(std::locale());
10785 #endif
10786 setlocale(LC_CTYPE, "");
10787
10788 po::options_description desc_params(wallet_args::tr("Wallet options"));
10789 tools::wallet2::init_options(desc_params);
10790 command_line::add_arg(desc_params, arg_wallet_file);
10791 command_line::add_arg(desc_params, arg_generate_new_wallet);
10792 command_line::add_arg(desc_params, arg_generate_from_device);
10793 command_line::add_arg(desc_params, arg_generate_from_view_key);
10794 command_line::add_arg(desc_params, arg_generate_from_spend_key);
10795 command_line::add_arg(desc_params, arg_generate_from_keys);
10796 command_line::add_arg(desc_params, arg_generate_from_multisig_keys);
10797 command_line::add_arg(desc_params, arg_generate_from_json);
10798 command_line::add_arg(desc_params, arg_mnemonic_language);
10799 command_line::add_arg(desc_params, arg_command);
10800
10801 command_line::add_arg(desc_params, arg_restore_deterministic_wallet );
10802 command_line::add_arg(desc_params, arg_restore_from_seed );
10803 command_line::add_arg(desc_params, arg_restore_multisig_wallet );
10804 command_line::add_arg(desc_params, arg_non_deterministic );
10805 command_line::add_arg(desc_params, arg_electrum_seed );
10806 command_line::add_arg(desc_params, arg_allow_mismatched_daemon_version);
10807 command_line::add_arg(desc_params, arg_restore_height);
10808 command_line::add_arg(desc_params, arg_restore_date);
10809 command_line::add_arg(desc_params, arg_do_not_relay);
10810 command_line::add_arg(desc_params, arg_create_address_file);
10811 command_line::add_arg(desc_params, arg_subaddress_lookahead);
10812 command_line::add_arg(desc_params, arg_use_english_language_names);
10813 command_line::add_arg(desc_params, arg_rpc_client_secret_key);
10814
10815 po::positional_options_description positional_options;
10816 positional_options.add(arg_command.name, -1);
10817
10818 boost::optional<po::variables_map> vm;
10819 bool should_terminate = false;
10820 std::tie(vm, should_terminate) = wallet_args::main(
10821 argc, argv,
10822 "monero-wallet-cli [--wallet-file=<filename>|--generate-new-wallet=<filename>] [<COMMAND>]",
10823 sw::tr("This is the command line monero wallet. It needs to connect to a monero\ndaemon to work correctly.\nWARNING: Do not reuse your Monero keys on another fork, UNLESS this fork has key reuse mitigations built in. Doing so will harm your privacy."),
10824 desc_params,
10825 positional_options,
10826 [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; },
10827 "monero-wallet-cli.log"
10828 );
10829
10830 if (!vm)
10831 {
10832 return 1;
10833 }
10834
10835 if (should_terminate)
10836 {
10837 return 0;
10838 }
10839
10840 cryptonote::simple_wallet w;
10841 const bool r = w.init(*vm);
10842 CHECK_AND_ASSERT_MES(r, 1, sw::tr("Failed to initialize wallet"));
10843
10844 std::vector<std::string> command = command_line::get_arg(*vm, arg_command);
10845 if (!command.empty())
10846 {
10847 if (!w.process_command(command))
10848 fail_msg_writer() << sw::tr("Unknown command: ") << command.front();
10849 w.stop();
10850 w.deinit();
10851 }
10852 else
10853 {
10854 tools::signal_handler::install([&w](int type) {
10855 if (tools::password_container::is_prompting.load())
10856 {
10857 // must be prompting for password so return and let the signal stop prompt
10858 return;
10859 }
10860 #ifdef WIN32
10861 if (type == CTRL_C_EVENT)
10862 #else
10863 if (type == SIGINT)
10864 #endif
10865 {
10866 // if we're pressing ^C when refreshing, just stop refreshing
10867 w.interrupt();
10868 }
10869 else
10870 {
10871 w.stop();
10872 }
10873 });
10874 w.run();
10875
10876 w.deinit();
10877 }
10878 return 0;
10879 CATCH_ENTRY_L0("main", 1);
10880 }
10881
10882 // MMS ---------------------------------------------------------------------------------------------------
10883
10884 // Access to the message store, or more exactly to the list of the messages that can be changed
10885 // by the idle thread, is guarded by the same mutex-based mechanism as access to the wallet
10886 // as a whole and thus e.g. uses the "LOCK_IDLE_SCOPE" macro. This is a little over-cautious, but
10887 // simple and safe. Care has to be taken however where MMS methods call other simplewallet methods
10888 // that use "LOCK_IDLE_SCOPE" as this cannot be nested!
10889
10890 // Methods for commands like "export_multisig_info" usually read data from file(s) or write data
10891 // to files. The MMS calls now those methods as well, to produce data for messages and to process data
10892 // from messages. As it would be quite inconvenient for the MMS to write data for such methods to files
10893 // first or get data out of result files after the call, those methods detect a call from the MMS and
10894 // expect data as arguments instead of files and give back data by calling 'process_wallet_created_data'.
10895
10896 bool simple_wallet::user_confirms(const std::string &question)
10897 {
10898 std::string answer = input_line(question + tr(" (Y/Yes/N/No): "));
10899 return !std::cin.eof() && command_line::is_yes(answer);
10900 }
10901
10902 bool simple_wallet::user_confirms_auto_config()
10903 {
10904 message_writer(console_color_red, true) << tr("WARNING: Using MMS auto-config mechanisms is not trustless");
10905 message_writer() << tr("A malicious auto-config manager could send you info about own wallets instead of other signers' info");
10906 message_writer() << tr("If in doubt do not use auto-config or at least compare configs using the \"mms config_checksum\" command");
10907 return user_confirms("Accept the risks and continue?");
10908 }
10909
10910 bool simple_wallet::get_number_from_arg(const std::string &arg, uint32_t &number, const uint32_t lower_bound, const uint32_t upper_bound)
10911 {
10912 bool valid = false;
10913 try
10914 {
10915 number = boost::lexical_cast<uint32_t>(arg);
10916 valid = (number >= lower_bound) && (number <= upper_bound);
10917 }
10918 catch(const boost::bad_lexical_cast &)
10919 {
10920 }
10921 return valid;
10922 }
10923
10924 bool simple_wallet::choose_mms_processing(const std::vector<mms::processing_data> &data_list, uint32_t &choice)
10925 {
10926 size_t choices = data_list.size();
10927 if (choices == 1)
10928 {
10929 choice = 0;
10930 return true;
10931 }
10932 mms::message_store& ms = m_wallet->get_message_store();
10933 message_writer() << tr("Choose processing:");
10934 std::string text;
10935 for (size_t i = 0; i < choices; ++i)
10936 {
10937 const mms::processing_data &data = data_list[i];
10938 text = std::to_string(i+1) + ": ";
10939 switch (data.processing)
10940 {
10941 case mms::message_processing::sign_tx:
10942 text += tr("Sign tx");
10943 break;
10944 case mms::message_processing::send_tx:
10945 {
10946 mms::message m;
10947 ms.get_message_by_id(data.message_ids[0], m);
10948 if (m.type == mms::message_type::fully_signed_tx)
10949 {
10950 text += tr("Send the tx for submission to ");
10951 }
10952 else
10953 {
10954 text += tr("Send the tx for signing to ");
10955 }
10956 mms::authorized_signer signer = ms.get_signer(data.receiving_signer_index);
10957 text += ms.signer_to_string(signer, 50);
10958 break;
10959 }
10960 case mms::message_processing::submit_tx:
10961 text += tr("Submit tx");
10962 break;
10963 default:
10964 text += tr("unknown");
10965 break;
10966 }
10967 message_writer() << text;
10968 }
10969
10970 std::string line = input_line(tr("Choice: "));
10971 if (std::cin.eof() || line.empty())
10972 {
10973 return false;
10974 }
10975 bool choice_ok = get_number_from_arg(line, choice, 1, choices);
10976 if (choice_ok)
10977 {
10978 choice--;
10979 }
10980 else
10981 {
10982 fail_msg_writer() << tr("Wrong choice");
10983 }
10984 return choice_ok;
10985 }
10986
10987 void simple_wallet::list_mms_messages(const std::vector<mms::message> &messages)
10988 {
10989 message_writer() << boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") % tr("Id") % tr("I/O") % tr("Authorized Signer")
10990 % tr("Message Type") % tr("Height") % tr("R") % tr("Message State") % tr("Since");
10991 mms::message_store& ms = m_wallet->get_message_store();
10992 uint64_t now = (uint64_t)time(NULL);
10993 for (size_t i = 0; i < messages.size(); ++i)
10994 {
10995 const mms::message &m = messages[i];
10996 const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
10997 bool highlight = (m.state == mms::message_state::ready_to_send) || (m.state == mms::message_state::waiting);
10998 message_writer(m.direction == mms::message_direction::out ? console_color_green : console_color_magenta, highlight) <<
10999 boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") %
11000 m.id %
11001 ms.message_direction_to_string(m.direction) %
11002 ms.signer_to_string(signer, 30) %
11003 ms.message_type_to_string(m.type) %
11004 m.wallet_height %
11005 m.round %
11006 ms.message_state_to_string(m.state) %
11007 (tools::get_human_readable_timestamp(m.modified) + ", " + get_human_readable_timespan(std::chrono::seconds(now - m.modified)) + tr(" ago"));
11008 }
11009 }
11010
11011 void simple_wallet::list_signers(const std::vector<mms::authorized_signer> &signers)
11012 {
11013 message_writer() << boost::format("%2s %-20s %-s") % tr("#") % tr("Label") % tr("Transport Address");
11014 message_writer() << boost::format("%2s %-20s %-s") % "" % tr("Auto-Config Token") % tr("Monero Address");
11015 for (size_t i = 0; i < signers.size(); ++i)
11016 {
11017 const mms::authorized_signer &signer = signers[i];
11018 std::string label = signer.label.empty() ? tr("<not set>") : signer.label;
11019 std::string monero_address;
11020 if (signer.monero_address_known)
11021 {
11022 monero_address = get_account_address_as_str(m_wallet->nettype(), false, signer.monero_address);
11023 }
11024 else
11025 {
11026 monero_address = tr("<not set>");
11027 }
11028 std::string transport_address = signer.transport_address.empty() ? tr("<not set>") : signer.transport_address;
11029 message_writer() << boost::format("%2s %-20s %-s") % (i + 1) % label % transport_address;
11030 message_writer() << boost::format("%2s %-20s %-s") % "" % signer.auto_config_token % monero_address;
11031 message_writer() << "";
11032 }
11033 }
11034
11035 void simple_wallet::add_signer_config_messages()
11036 {
11037 mms::message_store& ms = m_wallet->get_message_store();
11038 std::string signer_config;
11039 ms.get_signer_config(signer_config);
11040
11041 const std::vector<mms::authorized_signer> signers = ms.get_all_signers();
11042 mms::multisig_wallet_state state = get_multisig_wallet_state();
11043 uint32_t num_authorized_signers = ms.get_num_authorized_signers();
11044 for (uint32_t i = 1 /* without me */; i < num_authorized_signers; ++i)
11045 {
11046 ms.add_message(state, i, mms::message_type::signer_config, mms::message_direction::out, signer_config);
11047 }
11048 }
11049
11050 void simple_wallet::show_message(const mms::message &m)
11051 {
11052 mms::message_store& ms = m_wallet->get_message_store();
11053 const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
11054 bool display_content;
11055 std::string sanitized_text;
11056 switch (m.type)
11057 {
11058 case mms::message_type::key_set:
11059 case mms::message_type::additional_key_set:
11060 case mms::message_type::note:
11061 display_content = true;
11062 sanitized_text = mms::message_store::get_sanitized_text(m.content, 1000);
11063 break;
11064 default:
11065 display_content = false;
11066 }
11067 uint64_t now = (uint64_t)time(NULL);
11068 message_writer() << "";
11069 message_writer() << tr("Message ") << m.id;
11070 message_writer() << tr("In/out: ") << ms.message_direction_to_string(m.direction);
11071 message_writer() << tr("Type: ") << ms.message_type_to_string(m.type);
11072 message_writer() << tr("State: ") << boost::format(tr("%s since %s, %s ago")) %
11073 ms.message_state_to_string(m.state) % tools::get_human_readable_timestamp(m.modified) % get_human_readable_timespan(std::chrono::seconds(now - m.modified));
11074 if (m.sent == 0)
11075 {
11076 message_writer() << tr("Sent: Never");
11077 }
11078 else
11079 {
11080 message_writer() << boost::format(tr("Sent: %s, %s ago")) %
11081 tools::get_human_readable_timestamp(m.sent) % get_human_readable_timespan(std::chrono::seconds(now - m.sent));
11082 }
11083 message_writer() << tr("Authorized signer: ") << ms.signer_to_string(signer, 100);
11084 message_writer() << tr("Content size: ") << m.content.length() << tr(" bytes");
11085 message_writer() << tr("Content: ") << (display_content ? sanitized_text : tr("(binary data)"));
11086
11087 if (m.type == mms::message_type::note)
11088 {
11089 // Showing a note and read its text is "processing" it: Set the state accordingly
11090 // which will also delete it from Bitmessage as a side effect
11091 // (Without this little "twist" it would never change the state, and never get deleted)
11092 ms.set_message_processed_or_sent(m.id);
11093 }
11094 }
11095
11096 void simple_wallet::ask_send_all_ready_messages()
11097 {
11098 mms::message_store& ms = m_wallet->get_message_store();
11099 std::vector<mms::message> ready_messages;
11100 const std::vector<mms::message> &messages = ms.get_all_messages();
11101 for (size_t i = 0; i < messages.size(); ++i)
11102 {
11103 const mms::message &m = messages[i];
11104 if (m.state == mms::message_state::ready_to_send)
11105 {
11106 ready_messages.push_back(m);
11107 }
11108 }
11109 if (ready_messages.size() != 0)
11110 {
11111 list_mms_messages(ready_messages);
11112 bool send = ms.get_auto_send();
11113 if (!send)
11114 {
11115 send = user_confirms(tr("Send these messages now?"));
11116 }
11117 if (send)
11118 {
11119 mms::multisig_wallet_state state = get_multisig_wallet_state();
11120 for (size_t i = 0; i < ready_messages.size(); ++i)
11121 {
11122 ms.send_message(state, ready_messages[i].id);
11123 ms.set_message_processed_or_sent(ready_messages[i].id);
11124 }
11125 success_msg_writer() << tr("Queued for sending.");
11126 }
11127 }
11128 }
11129
11130 bool simple_wallet::get_message_from_arg(const std::string &arg, mms::message &m)
11131 {
11132 mms::message_store& ms = m_wallet->get_message_store();
11133 bool valid_id = false;
11134 uint32_t id;
11135 try
11136 {
11137 id = (uint32_t)boost::lexical_cast<uint32_t>(arg);
11138 valid_id = ms.get_message_by_id(id, m);
11139 }
11140 catch (const boost::bad_lexical_cast &)
11141 {
11142 }
11143 if (!valid_id)
11144 {
11145 fail_msg_writer() << tr("Invalid message id");
11146 }
11147 return valid_id;
11148 }
11149
11150 void simple_wallet::mms_init(const std::vector<std::string> &args)
11151 {
11152 if (args.size() != 3)
11153 {
11154 fail_msg_writer() << tr("usage: mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
11155 return;
11156 }
11157 mms::message_store& ms = m_wallet->get_message_store();
11158 if (ms.get_active())
11159 {
11160 if (!user_confirms(tr("The MMS is already initialized. Re-initialize by deleting all signer info and messages?")))
11161 {
11162 return;
11163 }
11164 }
11165 uint32_t num_required_signers;
11166 uint32_t num_authorized_signers;
11167 const std::string &mn = args[0];
11168 std::vector<std::string> numbers;
11169 boost::split(numbers, mn, boost::is_any_of("/"));
11170 bool mn_ok = (numbers.size() == 2)
11171 && get_number_from_arg(numbers[1], num_authorized_signers, 2, config::MULTISIG_MAX_SIGNERS)
11172 && get_number_from_arg(numbers[0], num_required_signers, 1, num_authorized_signers);
11173 if (!mn_ok)
11174 {
11175 fail_msg_writer() << tr("Error in the number of required signers and/or authorized signers");
11176 return;
11177 }
11178 LOCK_IDLE_SCOPE();
11179 ms.init(get_multisig_wallet_state(), args[1], args[2], num_authorized_signers, num_required_signers);
11180 }
11181
11182 void simple_wallet::mms_info(const std::vector<std::string> &args)
11183 {
11184 mms::message_store& ms = m_wallet->get_message_store();
11185 if (ms.get_active())
11186 {
11187 message_writer() << boost::format("The MMS is active for %s/%s multisig.")
11188 % ms.get_num_required_signers() % ms.get_num_authorized_signers();
11189 }
11190 else
11191 {
11192 message_writer() << tr("The MMS is not active.");
11193 }
11194 }
11195
11196 void simple_wallet::mms_signer(const std::vector<std::string> &args)
11197 {
11198 mms::message_store& ms = m_wallet->get_message_store();
11199 const std::vector<mms::authorized_signer> &signers = ms.get_all_signers();
11200 if (args.size() == 0)
11201 {
11202 // Without further parameters list all defined signers
11203 list_signers(signers);
11204 return;
11205 }
11206
11207 uint32_t index;
11208 bool index_valid = get_number_from_arg(args[0], index, 1, ms.get_num_authorized_signers());
11209 if (index_valid)
11210 {
11211 index--;
11212 }
11213 else
11214 {
11215 fail_msg_writer() << tr("Invalid signer number ") + args[0];
11216 return;
11217 }
11218 if ((args.size() < 2) || (args.size() > 4))
11219 {
11220 fail_msg_writer() << tr("mms signer [<number> <label> [<transport_address> [<monero_address>]]]");
11221 return;
11222 }
11223
11224 boost::optional<string> label = args[1];
11225 boost::optional<string> transport_address;
11226 if (args.size() >= 3)
11227 {
11228 transport_address = args[2];
11229 }
11230 boost::optional<cryptonote::account_public_address> monero_address;
11231 LOCK_IDLE_SCOPE();
11232 mms::multisig_wallet_state state = get_multisig_wallet_state();
11233 if (args.size() == 4)
11234 {
11235 cryptonote::address_parse_info info;
11236 bool ok = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[3], oa_prompter);
11237 if (!ok)
11238 {
11239 fail_msg_writer() << tr("Invalid Monero address");
11240 return;
11241 }
11242 monero_address = info.address;
11243 const std::vector<mms::message> &messages = ms.get_all_messages();
11244 if ((messages.size() > 0) || state.multisig)
11245 {
11246 fail_msg_writer() << tr("Wallet state does not allow changing Monero addresses anymore");
11247 return;
11248 }
11249 }
11250 ms.set_signer(state, index, label, transport_address, monero_address);
11251 }
11252
11253 void simple_wallet::mms_list(const std::vector<std::string> &args)
11254 {
11255 mms::message_store& ms = m_wallet->get_message_store();
11256 if (args.size() != 0)
11257 {
11258 fail_msg_writer() << tr("Usage: mms list");
11259 return;
11260 }
11261 LOCK_IDLE_SCOPE();
11262 const std::vector<mms::message> &messages = ms.get_all_messages();
11263 list_mms_messages(messages);
11264 }
11265
11266 void simple_wallet::mms_next(const std::vector<std::string> &args)
11267 {
11268 mms::message_store& ms = m_wallet->get_message_store();
11269 if ((args.size() > 1) || ((args.size() == 1) && (args[0] != "sync")))
11270 {
11271 fail_msg_writer() << tr("Usage: mms next [sync]");
11272 return;
11273 }
11274 bool avail = false;
11275 std::vector<mms::processing_data> data_list;
11276 bool force_sync = false;
11277 uint32_t choice = 0;
11278 {
11279 LOCK_IDLE_SCOPE();
11280 if ((args.size() == 1) && (args[0] == "sync"))
11281 {
11282 // Force the MMS to process any waiting sync info although on its own it would just ignore
11283 // those messages because no need to process them can be seen
11284 force_sync = true;
11285 }
11286 string wait_reason;
11287 {
11288 avail = ms.get_processable_messages(get_multisig_wallet_state(), force_sync, data_list, wait_reason);
11289 }
11290 if (avail)
11291 {
11292 avail = choose_mms_processing(data_list, choice);
11293 }
11294 else if (!wait_reason.empty())
11295 {
11296 message_writer() << tr("No next step: ") << wait_reason;
11297 }
11298 }
11299 if (avail)
11300 {
11301 mms::processing_data data = data_list[choice];
11302 bool command_successful = false;
11303 switch(data.processing)
11304 {
11305 case mms::message_processing::prepare_multisig:
11306 message_writer() << tr("prepare_multisig");
11307 command_successful = prepare_multisig_main(std::vector<std::string>(), true);
11308 break;
11309
11310 case mms::message_processing::make_multisig:
11311 {
11312 message_writer() << tr("make_multisig");
11313 size_t number_of_key_sets = data.message_ids.size();
11314 std::vector<std::string> sig_args(number_of_key_sets + 1);
11315 sig_args[0] = std::to_string(ms.get_num_required_signers());
11316 for (size_t i = 0; i < number_of_key_sets; ++i)
11317 {
11318 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11319 sig_args[i+1] = m.content;
11320 }
11321 command_successful = make_multisig_main(sig_args, true);
11322 break;
11323 }
11324
11325 case mms::message_processing::exchange_multisig_keys:
11326 {
11327 message_writer() << tr("exchange_multisig_keys");
11328 size_t number_of_key_sets = data.message_ids.size();
11329 // Other than "make_multisig" only the key sets as parameters, no num_required_signers
11330 std::vector<std::string> sig_args(number_of_key_sets);
11331 for (size_t i = 0; i < number_of_key_sets; ++i)
11332 {
11333 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11334 sig_args[i] = m.content;
11335 }
11336 // todo: update mms to enable 'key exchange force updating'
11337 command_successful = exchange_multisig_keys_main(sig_args, false, true);
11338 break;
11339 }
11340
11341 case mms::message_processing::create_sync_data:
11342 {
11343 message_writer() << tr("export_multisig_info");
11344 std::vector<std::string> export_args;
11345 export_args.push_back("MMS"); // dummy filename
11346 command_successful = export_multisig_main(export_args, true);
11347 break;
11348 }
11349
11350 case mms::message_processing::process_sync_data:
11351 {
11352 message_writer() << tr("import_multisig_info");
11353 std::vector<std::string> import_args;
11354 for (size_t i = 0; i < data.message_ids.size(); ++i)
11355 {
11356 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11357 import_args.push_back(m.content);
11358 }
11359 command_successful = import_multisig_main(import_args, true);
11360 break;
11361 }
11362
11363 case mms::message_processing::sign_tx:
11364 {
11365 message_writer() << tr("sign_multisig");
11366 std::vector<std::string> sign_args;
11367 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11368 sign_args.push_back(m.content);
11369 command_successful = sign_multisig_main(sign_args, true);
11370 break;
11371 }
11372
11373 case mms::message_processing::submit_tx:
11374 {
11375 message_writer() << tr("submit_multisig");
11376 std::vector<std::string> submit_args;
11377 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11378 submit_args.push_back(m.content);
11379 command_successful = submit_multisig_main(submit_args, true);
11380 break;
11381 }
11382
11383 case mms::message_processing::send_tx:
11384 {
11385 message_writer() << tr("Send tx");
11386 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11387 LOCK_IDLE_SCOPE();
11388 ms.add_message(get_multisig_wallet_state(), data.receiving_signer_index, m.type, mms::message_direction::out,
11389 m.content);
11390 command_successful = true;
11391 break;
11392 }
11393
11394 case mms::message_processing::process_signer_config:
11395 {
11396 message_writer() << tr("Process signer config");
11397 LOCK_IDLE_SCOPE();
11398 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11399 mms::authorized_signer me = ms.get_signer(0);
11400 mms::multisig_wallet_state state = get_multisig_wallet_state();
11401 if (!me.auto_config_running)
11402 {
11403 // If no auto-config is running, the config sent may be unsolicited or problematic
11404 // so show what arrived and ask for confirmation before taking it in
11405 std::vector<mms::authorized_signer> signers;
11406 ms.unpack_signer_config(state, m.content, signers);
11407 list_signers(signers);
11408 if (!user_confirms(tr("Replace current signer config with the one displayed above?")))
11409 {
11410 break;
11411 }
11412 if (!user_confirms_auto_config())
11413 {
11414 message_writer() << tr("You can use the \"mms delete\" command to delete any unwanted message");
11415 break;
11416 }
11417 }
11418 ms.process_signer_config(state, m.content);
11419 ms.stop_auto_config();
11420 list_signers(ms.get_all_signers());
11421 command_successful = true;
11422 break;
11423 }
11424
11425 case mms::message_processing::process_auto_config_data:
11426 {
11427 message_writer() << tr("Process auto config data");
11428 LOCK_IDLE_SCOPE();
11429 for (size_t i = 0; i < data.message_ids.size(); ++i)
11430 {
11431 ms.process_auto_config_data_message(data.message_ids[i]);
11432 }
11433 ms.stop_auto_config();
11434 list_signers(ms.get_all_signers());
11435 add_signer_config_messages();
11436 command_successful = true;
11437 break;
11438 }
11439
11440 default:
11441 message_writer() << tr("Nothing ready to process");
11442 break;
11443 }
11444
11445 if (command_successful)
11446 {
11447 {
11448 LOCK_IDLE_SCOPE();
11449 ms.set_messages_processed(data);
11450 ask_send_all_ready_messages();
11451 }
11452 }
11453 }
11454 }
11455
11456 void simple_wallet::mms_sync(const std::vector<std::string> &args)
11457 {
11458 if (args.size() != 0)
11459 {
11460 fail_msg_writer() << tr("Usage: mms sync");
11461 return;
11462 }
11463 // Force the start of a new sync round, for exceptional cases where something went wrong
11464 // Can e.g. solve the problem "This signature was made with stale data" after trying to
11465 // create 2 transactions in a row somehow
11466 // Code is identical to the code for 'message_processing::create_sync_data'
11467 message_writer() << tr("export_multisig_info");
11468 std::vector<std::string> export_args;
11469 export_args.push_back("MMS"); // dummy filename
11470 export_multisig_main(export_args, true);
11471 ask_send_all_ready_messages();
11472 }
11473
11474 void simple_wallet::mms_transfer(const std::vector<std::string> &args)
11475 {
11476 // It's too complicated to check any arguments here, just let 'transfer_main' do the whole job
11477 transfer_main(args, true);
11478 }
11479
11480 void simple_wallet::mms_delete(const std::vector<std::string> &args)
11481 {
11482 if (args.size() != 1)
11483 {
11484 fail_msg_writer() << tr("Usage: mms delete (<message_id> | all)");
11485 return;
11486 }
11487 LOCK_IDLE_SCOPE();
11488 mms::message_store& ms = m_wallet->get_message_store();
11489 if (args[0] == "all")
11490 {
11491 if (user_confirms(tr("Delete all messages?")))
11492 {
11493 ms.delete_all_messages();
11494 }
11495 }
11496 else
11497 {
11498 mms::message m;
11499 bool valid_id = get_message_from_arg(args[0], m);
11500 if (valid_id)
11501 {
11502 // If only a single message and not all delete even if unsent / unprocessed
11503 ms.delete_message(m.id);
11504 }
11505 }
11506 }
11507
11508 void simple_wallet::mms_send(const std::vector<std::string> &args)
11509 {
11510 if (args.size() == 0)
11511 {
11512 ask_send_all_ready_messages();
11513 return;
11514 }
11515 else if (args.size() != 1)
11516 {
11517 fail_msg_writer() << tr("Usage: mms send [<message_id>]");
11518 return;
11519 }
11520 LOCK_IDLE_SCOPE();
11521 mms::message_store& ms = m_wallet->get_message_store();
11522 mms::message m;
11523 bool valid_id = get_message_from_arg(args[0], m);
11524 if (valid_id)
11525 {
11526 ms.send_message(get_multisig_wallet_state(), m.id);
11527 }
11528 }
11529
11530 void simple_wallet::mms_receive(const std::vector<std::string> &args)
11531 {
11532 if (args.size() != 0)
11533 {
11534 fail_msg_writer() << tr("Usage: mms receive");
11535 return;
11536 }
11537 std::vector<mms::message> new_messages;
11538 LOCK_IDLE_SCOPE();
11539 mms::message_store& ms = m_wallet->get_message_store();
11540 bool avail = ms.check_for_messages(get_multisig_wallet_state(), new_messages);
11541 if (avail)
11542 {
11543 list_mms_messages(new_messages);
11544 }
11545 }
11546
11547 void simple_wallet::mms_export(const std::vector<std::string> &args)
11548 {
11549 if (args.size() != 1)
11550 {
11551 fail_msg_writer() << tr("Usage: mms export <message_id>");
11552 return;
11553 }
11554 LOCK_IDLE_SCOPE();
11555 mms::message m;
11556 bool valid_id = get_message_from_arg(args[0], m);
11557 if (valid_id)
11558 {
11559 const std::string filename = "mms_message_content";
11560 if (m_wallet->save_to_file(filename, m.content))
11561 {
11562 success_msg_writer() << tr("Message content saved to: ") << filename;
11563 }
11564 else
11565 {
11566 fail_msg_writer() << tr("Failed to to save message content");
11567 }
11568 }
11569 }
11570
11571 void simple_wallet::mms_note(const std::vector<std::string> &args)
11572 {
11573 mms::message_store& ms = m_wallet->get_message_store();
11574 if (args.size() == 0)
11575 {
11576 LOCK_IDLE_SCOPE();
11577 const std::vector<mms::message> &messages = ms.get_all_messages();
11578 for (size_t i = 0; i < messages.size(); ++i)
11579 {
11580 const mms::message &m = messages[i];
11581 if ((m.type == mms::message_type::note) && (m.state == mms::message_state::waiting))
11582 {
11583 show_message(m);
11584 }
11585 }
11586 return;
11587 }
11588 if (args.size() < 2)
11589 {
11590 fail_msg_writer() << tr("Usage: mms note [<label> <text>]");
11591 return;
11592 }
11593 uint32_t signer_index;
11594 bool found = ms.get_signer_index_by_label(args[0], signer_index);
11595 if (!found)
11596 {
11597 fail_msg_writer() << tr("No signer found with label ") << args[0];
11598 return;
11599 }
11600 std::string note = "";
11601 for (size_t n = 1; n < args.size(); ++n)
11602 {
11603 if (n > 1)
11604 {
11605 note += " ";
11606 }
11607 note += args[n];
11608 }
11609 LOCK_IDLE_SCOPE();
11610 ms.add_message(get_multisig_wallet_state(), signer_index, mms::message_type::note,
11611 mms::message_direction::out, note);
11612 ask_send_all_ready_messages();
11613 }
11614
11615 void simple_wallet::mms_show(const std::vector<std::string> &args)
11616 {
11617 if (args.size() != 1)
11618 {
11619 fail_msg_writer() << tr("Usage: mms show <message_id>");
11620 return;
11621 }
11622 LOCK_IDLE_SCOPE();
11623 mms::message m;
11624 bool valid_id = get_message_from_arg(args[0], m);
11625 if (valid_id)
11626 {
11627 show_message(m);
11628 }
11629 }
11630
11631 void simple_wallet::mms_set(const std::vector<std::string> &args)
11632 {
11633 bool set = args.size() == 2;
11634 bool query = args.size() == 1;
11635 if (!set && !query)
11636 {
11637 fail_msg_writer() << tr("Usage: mms set <option_name> [<option_value>]");
11638 return;
11639 }
11640 mms::message_store& ms = m_wallet->get_message_store();
11641 LOCK_IDLE_SCOPE();
11642 if (args[0] == "auto-send")
11643 {
11644 if (set)
11645 {
11646 bool result;
11647 bool ok = parse_bool(args[1], result);
11648 if (ok)
11649 {
11650 ms.set_auto_send(result);
11651 }
11652 else
11653 {
11654 fail_msg_writer() << tr("Wrong option value");
11655 }
11656 }
11657 else
11658 {
11659 message_writer() << (ms.get_auto_send() ? tr("Auto-send is on") : tr("Auto-send is off"));
11660 }
11661 }
11662 else
11663 {
11664 fail_msg_writer() << tr("Unknown option");
11665 }
11666 }
11667
11668 void simple_wallet::mms_help(const std::vector<std::string> &args)
11669 {
11670 if (args.size() > 1)
11671 {
11672 fail_msg_writer() << tr("Usage: help mms [<subcommand>]");
11673 return;
11674 }
11675 std::vector<std::string> help_args;
11676 help_args.push_back("mms");
11677 if (args.size() == 1)
11678 {
11679 help_args.push_back(args[0]);
11680 }
11681 help(help_args);
11682 }
11683
11684 void simple_wallet::mms_send_signer_config(const std::vector<std::string> &args)
11685 {
11686 if (args.size() != 0)
11687 {
11688 fail_msg_writer() << tr("Usage: mms send_signer_config");
11689 return;
11690 }
11691 mms::message_store& ms = m_wallet->get_message_store();
11692 if (!ms.signer_config_complete())
11693 {
11694 fail_msg_writer() << tr("Signer config not yet complete");
11695 return;
11696 }
11697 LOCK_IDLE_SCOPE();
11698 add_signer_config_messages();
11699 ask_send_all_ready_messages();
11700 }
11701
11702 void simple_wallet::mms_start_auto_config(const std::vector<std::string> &args)
11703 {
11704 mms::message_store& ms = m_wallet->get_message_store();
11705 uint32_t other_signers = ms.get_num_authorized_signers() - 1;
11706 size_t args_size = args.size();
11707 if ((args_size != 0) && (args_size != other_signers))
11708 {
11709 fail_msg_writer() << tr("Usage: mms start_auto_config [<label> <label> ...]");
11710 return;
11711 }
11712 if ((args_size == 0) && !ms.signer_labels_complete())
11713 {
11714 fail_msg_writer() << tr("There are signers without a label set. Complete labels before auto-config or specify them as parameters here.");
11715 return;
11716 }
11717 mms::authorized_signer me = ms.get_signer(0);
11718 if (me.auto_config_running)
11719 {
11720 if (!user_confirms(tr("Auto-config is already running. Cancel and restart?")))
11721 {
11722 return;
11723 }
11724 }
11725 LOCK_IDLE_SCOPE();
11726 mms::multisig_wallet_state state = get_multisig_wallet_state();
11727 if (args_size != 0)
11728 {
11729 // Set (or overwrite) all the labels except "me" from the arguments
11730 for (uint32_t i = 1; i < (other_signers + 1); ++i)
11731 {
11732 ms.set_signer(state, i, args[i - 1], boost::none, boost::none);
11733 }
11734 }
11735 ms.start_auto_config(state);
11736 // List the signers to show the generated auto-config tokens
11737 list_signers(ms.get_all_signers());
11738 }
11739
11740 void simple_wallet::mms_config_checksum(const std::vector<std::string> &args)
11741 {
11742 if (args.size() != 0)
11743 {
11744 fail_msg_writer() << tr("Usage: mms config_checksum");
11745 return;
11746 }
11747 mms::message_store& ms = m_wallet->get_message_store();
11748 LOCK_IDLE_SCOPE();
11749 message_writer() << ms.get_config_checksum();
11750 }
11751
11752 void simple_wallet::mms_stop_auto_config(const std::vector<std::string> &args)
11753 {
11754 if (args.size() != 0)
11755 {
11756 fail_msg_writer() << tr("Usage: mms stop_auto_config");
11757 return;
11758 }
11759 if (!user_confirms(tr("Delete any auto-config tokens and stop auto-config?")))
11760 {
11761 return;
11762 }
11763 mms::message_store& ms = m_wallet->get_message_store();
11764 LOCK_IDLE_SCOPE();
11765 ms.stop_auto_config();
11766 }
11767
11768 void simple_wallet::mms_auto_config(const std::vector<std::string> &args)
11769 {
11770 if (args.size() != 1)
11771 {
11772 fail_msg_writer() << tr("Usage: mms auto_config <auto_config_token>");
11773 return;
11774 }
11775 mms::message_store& ms = m_wallet->get_message_store();
11776 std::string adjusted_token;
11777 if (!ms.check_auto_config_token(args[0], adjusted_token))
11778 {
11779 fail_msg_writer() << tr("Invalid auto-config token");
11780 return;
11781 }
11782 if (!user_confirms_auto_config())
11783 {
11784 return;
11785 }
11786 mms::authorized_signer me = ms.get_signer(0);
11787 if (me.auto_config_running)
11788 {
11789 if (!user_confirms(tr("Auto-config already running. Cancel and restart?")))
11790 {
11791 return;
11792 }
11793 }
11794 LOCK_IDLE_SCOPE();
11795 ms.add_auto_config_data_message(get_multisig_wallet_state(), adjusted_token);
11796 ask_send_all_ready_messages();
11797 }
11798
11799 bool simple_wallet::mms(const std::vector<std::string> &args)
11800 {
11801 CHECK_MULTISIG_ENABLED();
11802 try
11803 {
11804 m_wallet->get_multisig_wallet_state();
11805 }
11806 catch(const std::exception &e)
11807 {
11808 fail_msg_writer() << tr("MMS not available in this wallet");
11809 return true;
11810 }
11811
11812 try
11813 {
11814 mms::message_store& ms = m_wallet->get_message_store();
11815 if (args.size() == 0)
11816 {
11817 mms_info(args);
11818 return true;
11819 }
11820
11821 const std::string &sub_command = args[0];
11822 std::vector<std::string> mms_args = args;
11823 mms_args.erase(mms_args.begin());
11824
11825 if (sub_command == "init")
11826 {
11827 mms_init(mms_args);
11828 return true;
11829 }
11830 if (!ms.get_active())
11831 {
11832 fail_msg_writer() << tr("The MMS is not active. Activate using the \"mms init\" command");
11833 return true;
11834 }
11835 else if (sub_command == "info")
11836 {
11837 mms_info(mms_args);
11838 }
11839 else if (sub_command == "signer")
11840 {
11841 mms_signer(mms_args);
11842 }
11843 else if (sub_command == "list")
11844 {
11845 mms_list(mms_args);
11846 }
11847 else if (sub_command == "next")
11848 {
11849 mms_next(mms_args);
11850 }
11851 else if (sub_command == "sync")
11852 {
11853 mms_sync(mms_args);
11854 }
11855 else if (sub_command == "transfer")
11856 {
11857 mms_transfer(mms_args);
11858 }
11859 else if (sub_command == "delete")
11860 {
11861 mms_delete(mms_args);
11862 }
11863 else if (sub_command == "send")
11864 {
11865 mms_send(mms_args);
11866 }
11867 else if (sub_command == "receive")
11868 {
11869 mms_receive(mms_args);
11870 }
11871 else if (sub_command == "export")
11872 {
11873 mms_export(mms_args);
11874 }
11875 else if (sub_command == "note")
11876 {
11877 mms_note(mms_args);
11878 }
11879 else if (sub_command == "show")
11880 {
11881 mms_show(mms_args);
11882 }
11883 else if (sub_command == "set")
11884 {
11885 mms_set(mms_args);
11886 }
11887 else if (sub_command == "help")
11888 {
11889 mms_help(mms_args);
11890 }
11891 else if (sub_command == "send_signer_config")
11892 {
11893 mms_send_signer_config(mms_args);
11894 }
11895 else if (sub_command == "start_auto_config")
11896 {
11897 mms_start_auto_config(mms_args);
11898 }
11899 else if (sub_command == "config_checksum")
11900 {
11901 mms_config_checksum(mms_args);
11902 }
11903 else if (sub_command == "stop_auto_config")
11904 {
11905 mms_stop_auto_config(mms_args);
11906 }
11907 else if (sub_command == "auto_config")
11908 {
11909 mms_auto_config(mms_args);
11910 }
11911 else
11912 {
11913 fail_msg_writer() << tr("Invalid MMS subcommand");
11914 }
11915 }
11916 catch (const tools::error::no_connection_to_daemon &e)
11917 {
11918 fail_msg_writer() << tr("Error in MMS command: ") << e.what() << " " << e.request();
11919 }
11920 catch (const std::exception &e)
11921 {
11922 fail_msg_writer() << tr("Error in MMS command: ") << e.what();
11923 PRINT_USAGE(USAGE_MMS);
11924 return true;
11925 }
11926 return true;
11927 }
11928 // End MMS ------------------------------------------------------------------------------------------------