Debian Codegraph @

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 65536
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<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0};
191 const command_line::arg_descriptor<std::string> arg_restore_date = {"restore-date", sw::tr("Restore from estimated blockchain height on specified date"), ""};
192 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};
193 const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false};
194 const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""};
195 const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false};
196
197 const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""};
198
199 const char* USAGE_START_MINING("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]");
200 const char* USAGE_SET_DAEMON("set_daemon <host>[:<port>] [trusted|untrusted|this-is-probably-a-spy-node]");
201 const char* USAGE_SHOW_BALANCE("balance [detail]");
202 const char* USAGE_INCOMING_TRANSFERS("incoming_transfers [available|unavailable] [verbose] [uses] [index=<N1>[,<N2>[,...]]]");
203 const char* USAGE_PAYMENTS("payments <PID_1> [<PID_2> ... <PID_N>]");
204 const char* USAGE_PAYMENT_ID("payment_id");
205 const char* USAGE_TRANSFER("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [subtractfeefrom=<D0>[,<D1>,all,...]] [<payment_id>]");
206 const char* USAGE_SWEEP_ALL("sweep_all [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
207 const char* USAGE_SWEEP_ACCOUNT("sweep_account <account> [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
208 const char* USAGE_SWEEP_BELOW("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id (obsolete)>]");
209 const char* USAGE_SWEEP_SINGLE("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id (obsolete)>]");
210 const char* USAGE_DONATE("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id (obsolete)>]");
211 const char* USAGE_SIGN_TRANSFER("sign_transfer [export_raw] [<filename>]");
212 const char* USAGE_SET_LOG("set_log <level>|{+,-,}<categories>");
213 const char* USAGE_ACCOUNT("account\n"
214 " account new <label text with white spaces allowed>\n"
215 " account switch <index> \n"
216 " account label <index> <label text with white spaces allowed>\n"
217 " account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
218 " account untag <account_index_1> [<account_index_2> ...]\n"
219 " account tag_description <tag_name> <description>");
220 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>]");
221 const char* USAGE_INTEGRATED_ADDRESS("integrated_address [device] [<payment_id> | <address>]");
222 const char* USAGE_ADDRESS_BOOK("address_book [(add (<address>|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]");
223 const char* USAGE_SET_VARIABLE("set <option> [<value>]");
224 const char* USAGE_GET_TX_KEY("get_tx_key <txid>");
225 const char* USAGE_SET_TX_KEY("set_tx_key <txid> <tx_key> [<subaddress>]");
226 const char* USAGE_CHECK_TX_KEY("check_tx_key <txid> <txkey> <address>");
227 const char* USAGE_GET_TX_PROOF("get_tx_proof <txid> <address> [<message>]");
228 const char* USAGE_CHECK_TX_PROOF("check_tx_proof <txid> <address> <signature_file> [<message>]");
229 const char* USAGE_GET_SPEND_PROOF("get_spend_proof <txid> [<message>]");
230 const char* USAGE_CHECK_SPEND_PROOF("check_spend_proof <txid> <signature_file> [<message>]");
231 const char* USAGE_GET_RESERVE_PROOF("get_reserve_proof (all|<amount>) [<message>]");
232 const char* USAGE_CHECK_RESERVE_PROOF("check_reserve_proof <address> <signature_file> [<message>]");
233 const char* USAGE_SHOW_TRANSFERS("show_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
234 const char* USAGE_UNSPENT_OUTPUTS("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]");
235 const char* USAGE_RESCAN_BC("rescan_bc [hard|soft|keep_ki] [start_height=0]");
236 const char* USAGE_SET_TX_NOTE("set_tx_note <txid> [free text note]");
237 const char* USAGE_GET_TX_NOTE("get_tx_note <txid>");
238 const char* USAGE_GET_DESCRIPTION("get_description");
239 const char* USAGE_SET_DESCRIPTION("set_description [free text note]");
240 const char* USAGE_SIGN("sign [<account_index>,<address_index>] [--spend|--view] <filename>");
241 const char* USAGE_VERIFY("verify <filename> <address> <signature>");
242 const char* USAGE_EXPORT_KEY_IMAGES("export_key_images [all] <filename>");
243 const char* USAGE_IMPORT_KEY_IMAGES("import_key_images <filename>");
244 const char* USAGE_HW_KEY_IMAGES_SYNC("hw_key_images_sync");
245 const char* USAGE_HW_RECONNECT("hw_reconnect");
246 const char* USAGE_EXPORT_OUTPUTS("export_outputs [all] <filename>");
247 const char* USAGE_IMPORT_OUTPUTS("import_outputs <filename>");
248 const char* USAGE_SHOW_TRANSFER("show_transfer <txid>");
249 const char* USAGE_MAKE_MULTISIG("make_multisig <threshold> <string1> [<string>...]");
250 const char* USAGE_EXCHANGE_MULTISIG_KEYS("exchange_multisig_keys [force-update-use-with-caution] <string> [<string>...]");
251 const char* USAGE_EXPORT_MULTISIG_INFO("export_multisig_info <filename>");
252 const char* USAGE_IMPORT_MULTISIG_INFO("import_multisig_info <filename> [<filename>...]");
253 const char* USAGE_SIGN_MULTISIG("sign_multisig <filename>");
254 const char* USAGE_SUBMIT_MULTISIG("submit_multisig <filename>");
255 const char* USAGE_EXPORT_RAW_MULTISIG_TX("export_raw_multisig_tx <filename>");
256 const char* USAGE_MMS("mms [<subcommand> [<subcommand_parameters>]]");
257 const char* USAGE_MMS_INIT("mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
258 const char* USAGE_MMS_INFO("mms info");
259 const char* USAGE_MMS_SIGNER("mms signer [<number> <label> [<transport_address> [<monero_address>]]]");
260 const char* USAGE_MMS_LIST("mms list");
261 const char* USAGE_MMS_NEXT("mms next [sync]");
262 const char* USAGE_MMS_SYNC("mms sync");
263 const char* USAGE_MMS_TRANSFER("mms transfer <transfer_command_arguments>");
264 const char* USAGE_MMS_DELETE("mms delete (<message_id> | all)");
265 const char* USAGE_MMS_SEND("mms send [<message_id>]");
266 const char* USAGE_MMS_RECEIVE("mms receive");
267 const char* USAGE_MMS_EXPORT("mms export <message_id>");
268 const char* USAGE_MMS_NOTE("mms note [<label> <text>]");
269 const char* USAGE_MMS_SHOW("mms show <message_id>");
270 const char* USAGE_MMS_SET("mms set <option_name> [<option_value>]");
271 const char* USAGE_MMS_SEND_SIGNER_CONFIG("mms send_signer_config");
272 const char* USAGE_MMS_START_AUTO_CONFIG("mms start_auto_config [<label> <label> ...]");
273 const char* USAGE_MMS_CONFIG_CHECKSUM("mms config_checksum");
274 const char* USAGE_MMS_STOP_AUTO_CONFIG("mms stop_auto_config");
275 const char* USAGE_MMS_AUTO_CONFIG("mms auto_config <auto_config_token>");
276 const char* USAGE_PRINT_RING("print_ring <key_image> | <txid>");
277 const char* USAGE_SET_RING("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )");
278 const char* USAGE_UNSET_RING("unset_ring <txid> | ( <key_image> [<key_image>...] )");
279 const char* USAGE_SAVE_KNOWN_RINGS("save_known_rings");
280 const char* USAGE_MARK_OUTPUT_SPENT("mark_output_spent <amount>/<offset> | <filename> [add]");
281 const char* USAGE_MARK_OUTPUT_UNSPENT("mark_output_unspent <amount>/<offset>");
282 const char* USAGE_IS_OUTPUT_SPENT("is_output_spent <amount>/<offset>");
283 const char* USAGE_FREEZE("freeze <key_image>");
284 const char* USAGE_THAW("thaw <key_image>");
285 const char* USAGE_FROZEN("frozen <key_image>");
286 const char* USAGE_LOCK("lock");
287 const char* USAGE_NET_STATS("net_stats");
288 const char* USAGE_PUBLIC_NODES("public_nodes");
289 const char* USAGE_WELCOME("welcome");
290 const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info");
291 const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc [<number_of_threads>]");
292 const char* USAGE_STOP_MINING_FOR_RPC("stop_mining_for_rpc");
293 const char* USAGE_SHOW_QR_CODE("show_qr_code [<subaddress_index>]");
294 const char* USAGE_VERSION("version");
295 const char* USAGE_HELP("help [<command> | all]");
296 const char* USAGE_APROPOS("apropos <keyword> [<keyword> ...]");
297 const char* USAGE_SCAN_TX("scan_tx <txid> [<txid> ...]");
298
299 std::string input_line(const std::string& prompt, bool yesno = false)
300 {
301 PAUSE_READLINE();
302 std::cout << prompt;
303 if (yesno)
304 std::cout << " (Y/Yes/N/No)";
305 std::cout << ": " << std::flush;
306
307 std::string buf;
308 #ifdef _WIN32
309 buf = tools::input_line_win();
310 #else
311 std::getline(std::cin, buf);
312 #endif
313
314 return epee::string_tools::trim(buf);
315 }
316
317 epee::wipeable_string input_secure_line(const char *prompt)
318 {
319 PAUSE_READLINE();
320 auto pwd_container = tools::password_container::prompt(false, prompt, false);
321 if (!pwd_container)
322 {
323 MERROR("Failed to read secure line");
324 return "";
325 }
326
327 epee::wipeable_string buf = pwd_container->password();
328
329 buf.trim();
330 return buf;
331 }
332
333 boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
334 {
335 PAUSE_READLINE();
336 auto pwd_container = tools::password_container::prompt(verify, prompt);
337 if (!pwd_container)
338 {
339 tools::fail_msg_writer() << sw::tr("failed to read password");
340 }
341 return pwd_container;
342 }
343
344 boost::optional<tools::password_container> default_password_prompter(bool verify)
345 {
346 return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify);
347 }
348
349 boost::optional<tools::password_container> background_sync_cache_password_prompter(bool verify)
350 {
351 return password_prompter(verify ? sw::tr("Enter a custom password for the background sync cache") : sw::tr("Background sync cache password"), verify);
352 }
353
354 inline std::string interpret_rpc_response(bool ok, const std::string& status)
355 {
356 std::string err;
357 if (ok)
358 {
359 if (status == CORE_RPC_STATUS_BUSY)
360 {
361 err = sw::tr("daemon is busy. Please try again later.");
362 }
363 else if (status != CORE_RPC_STATUS_OK)
364 {
365 err = status;
366 }
367 }
368 else
369 {
370 err = sw::tr("possibly lost connection to daemon");
371 }
372 return err;
373 }
374
375 tools::scoped_message_writer success_msg_writer(bool color = false)
376 {
377 return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info);
378 }
379
380 tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false)
381 {
382 return tools::scoped_message_writer(color, bright);
383 }
384
385 tools::scoped_message_writer fail_msg_writer()
386 {
387 return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error);
388 }
389
390 bool parse_bool(const std::string& s, bool& result)
391 {
392 if (s == "1" || command_line::is_yes(s))
393 {
394 result = true;
395 return true;
396 }
397 if (s == "0" || command_line::is_no(s))
398 {
399 result = false;
400 return true;
401 }
402
403 boost::algorithm::is_iequal ignore_case{};
404 if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case))
405 {
406 result = true;
407 return true;
408 }
409 if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case))
410 {
411 result = false;
412 return true;
413 }
414
415 return false;
416 }
417
418 template <typename F>
419 bool parse_bool_and_use(const std::string& s, F func)
420 {
421 bool r;
422 if (parse_bool(s, r))
423 {
424 func(r);
425 return true;
426 }
427 else
428 {
429 fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no");
430 return false;
431 }
432 }
433
434 const struct
435 {
436 const char *name;
437 tools::wallet2::RefreshType refresh_type;
438 } refresh_type_names[] =
439 {
440 { "full", tools::wallet2::RefreshFull },
441 { "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
442 { "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
443 { "no-coinbase", tools::wallet2::RefreshNoCoinbase },
444 { "default", tools::wallet2::RefreshDefault },
445 };
446
447 bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type)
448 {
449 for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
450 {
451 if (s == refresh_type_names[n].name)
452 {
453 refresh_type = refresh_type_names[n].refresh_type;
454 return true;
455 }
456 }
457 fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type");
458 return false;
459 }
460
461 std::string get_refresh_type_name(tools::wallet2::RefreshType type)
462 {
463 for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
464 {
465 if (type == refresh_type_names[n].refresh_type)
466 return refresh_type_names[n].name;
467 }
468 return "invalid";
469 }
470
471 const struct
472 {
473 const char *name;
474 tools::wallet2::BackgroundSyncType background_sync_type;
475 } background_sync_type_names[] =
476 {
477 { "off", tools::wallet2::BackgroundSyncOff },
478 { "reuse-wallet-password", tools::wallet2::BackgroundSyncReusePassword },
479 { "custom-background-password", tools::wallet2::BackgroundSyncCustomPassword },
480 };
481
482 bool parse_background_sync_type(const std::string &s, tools::wallet2::BackgroundSyncType &background_sync_type)
483 {
484 for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
485 {
486 if (s == background_sync_type_names[n].name)
487 {
488 background_sync_type = background_sync_type_names[n].background_sync_type;
489 return true;
490 }
491 }
492 fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse background sync type");
493 return false;
494 }
495
496 std::string get_background_sync_type_name(tools::wallet2::BackgroundSyncType type)
497 {
498 for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
499 {
500 if (type == background_sync_type_names[n].background_sync_type)
501 return background_sync_type_names[n].name;
502 }
503 return "invalid";
504 }
505
506 std::string get_version_string(uint32_t version)
507 {
508 return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff);
509 }
510
511 std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)
512 {
513 if (addresses.empty())
514 return {};
515 // prompt user for confirmation.
516 // inform user of DNSSEC validation status as well.
517 std::string dnssec_str;
518 if (dnssec_valid)
519 {
520 dnssec_str = sw::tr("DNSSEC validation passed");
521 }
522 else
523 {
524 dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!");
525 }
526 std::stringstream prompt;
527 prompt << sw::tr("For URL: ") << url
528 << ", " << dnssec_str << std::endl
529 << sw::tr(" Monero Address = ") << addresses[0]
530 << std::endl
531 << sw::tr("Is this OK?")
532 ;
533 // prompt the user for confirmation given the dns query and dnssec status
534 std::string confirm_dns_ok = input_line(prompt.str(), true);
535 if (std::cin.eof())
536 {
537 return {};
538 }
539 if (!command_line::is_yes(confirm_dns_ok))
540 {
541 std::cout << sw::tr("you have cancelled the transfer request") << std::endl;
542 return {};
543 }
544 return addresses[0];
545 }
546
547 bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices)
548 {
549 subaddr_indices.clear();
550
551 if (arg.substr(0, 6) != "index=")
552 return false;
553 std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6);
554 std::vector<std::string> subaddr_indices_str;
555 boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(","));
556
557 for (const auto& subaddr_index_str : subaddr_indices_str)
558 {
559 uint32_t subaddr_index;
560 if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str))
561 {
562 fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str;
563 subaddr_indices.clear();
564 return false;
565 }
566 subaddr_indices.insert(subaddr_index);
567 }
568 return true;
569 }
570
571 boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str)
572 {
573 auto r = tools::parse_subaddress_lookahead(str);
574 if (!r)
575 fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>");
576 return r;
577 }
578
579 static constexpr const char* SFFD_ARG_NAME{"subtractfeefrom="};
580
581 bool parse_subtract_fee_from_outputs
582 (
583 const std::string& arg,
584 tools::wallet2::unique_index_container& subtract_fee_from_outputs,
585 bool& subtract_fee_from_all,
586 bool& matches
587 )
588 {
589 matches = false;
590 if (!boost::string_ref{arg}.starts_with(SFFD_ARG_NAME)) // if arg doesn't match
591 return true;
592 matches = true;
593
594 const char* arg_end = arg.c_str() + arg.size();
595 for (const char* p = arg.c_str() + strlen(SFFD_ARG_NAME); p < arg_end;)
596 {
597 const char* new_p = nullptr;
598 const unsigned long dest_index = strtoul(p, const_cast<char**>(&new_p), 10);
599 if (dest_index == 0 && new_p == p) // numerical conversion failed
600 {
601 if (0 != strncmp(p, "all", 3))
602 {
603 fail_msg_writer() << tr("Failed to parse subtractfeefrom list");
604 return false;
605 }
606 subtract_fee_from_all = true;
607 break;
608 }
609 else if (dest_index > std::numeric_limits<uint32_t>::max())
610 {
611 fail_msg_writer() << tr("Destination index is too large") << ": " << dest_index;
612 return false;
613 }
614 else
615 {
616 subtract_fee_from_outputs.insert(dest_index);
617 p = new_p + 1; // skip the comma
618 }
619 }
620
621 return true;
622 }
623 } // anonymous namespace
624
625 void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon)
626 {
627 bool warn_of_possible_attack = !trusted_daemon;
628 try
629 {
630 std::rethrow_exception(e);
631 }
632 catch (const tools::error::payment_required&)
633 {
634 fail_msg_writer() << tr("Payment required, see the 'rpc_payment_info' command");
635 m_need_payment = true;
636 }
637 catch (const tools::error::no_connection_to_daemon&)
638 {
639 fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running.");
640 }
641 catch (const tools::error::daemon_busy&)
642 {
643 fail_msg_writer() << tr("daemon is busy. Please try again later.");
644 }
645 catch (const tools::error::wallet_rpc_error& e)
646 {
647 LOG_ERROR("RPC error: " << e.to_string());
648 fail_msg_writer() << sw::tr("RPC error: ") << e.what();
649 }
650 catch (const tools::error::get_outs_error &e)
651 {
652 fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what();
653 }
654 catch (const tools::error::not_enough_unlocked_money& e)
655 {
656 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
657 print_money(e.available()) %
658 print_money(e.tx_amount()));
659 fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
660 warn_of_possible_attack = false;
661 }
662 catch (const tools::error::not_enough_money& e)
663 {
664 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
665 print_money(e.available()) %
666 print_money(e.tx_amount()));
667 fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
668 warn_of_possible_attack = false;
669 }
670 catch (const tools::error::tx_not_possible& e)
671 {
672 LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") %
673 print_money(e.available()) %
674 print_money(e.tx_amount() + e.fee()) %
675 print_money(e.tx_amount()) %
676 print_money(e.fee()));
677 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");
678 warn_of_possible_attack = false;
679 }
680 catch (const tools::error::not_enough_outs_to_mix& e)
681 {
682 auto writer = fail_msg_writer();
683 writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":";
684 for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs())
685 {
686 writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second;
687 }
688 writer << sw::tr("Please use sweep_unmixable.");
689 }
690 catch (const tools::error::tx_not_constructed&)
691 {
692 fail_msg_writer() << sw::tr("transaction was not constructed");
693 warn_of_possible_attack = false;
694 }
695 catch (const tools::error::tx_rejected& e)
696 {
697 fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx()));
698 std::string reason = e.reason();
699 if (!reason.empty())
700 fail_msg_writer() << sw::tr("Reason: ") << reason;
701 }
702 catch (const tools::error::tx_sum_overflow& e)
703 {
704 fail_msg_writer() << e.what();
705 warn_of_possible_attack = false;
706 }
707 catch (const tools::error::zero_amount&)
708 {
709 fail_msg_writer() << sw::tr("destination amount is zero");
710 warn_of_possible_attack = false;
711 }
712 catch (const tools::error::zero_destination&)
713 {
714 fail_msg_writer() << sw::tr("transaction has no destination");
715 warn_of_possible_attack = false;
716 }
717 catch (const tools::error::tx_too_big& e)
718 {
719 fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions");
720 warn_of_possible_attack = false;
721 }
722 catch (const tools::error::transfer_error& e)
723 {
724 LOG_ERROR("unknown transfer error: " << e.to_string());
725 fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what();
726 }
727 catch (const tools::error::multisig_export_needed& e)
728 {
729 LOG_ERROR("Multisig error: " << e.to_string());
730 fail_msg_writer() << sw::tr("Multisig error: ") << e.what();
731 warn_of_possible_attack = false;
732 }
733 catch (const tools::error::wallet_internal_error& e)
734 {
735 LOG_ERROR("internal error: " << e.to_string());
736 fail_msg_writer() << sw::tr("internal error: ") << e.what();
737 }
738 catch (const std::exception& e)
739 {
740 LOG_ERROR("unexpected error: " << e.what());
741 fail_msg_writer() << sw::tr("unexpected error: ") << e.what();
742 }
743
744 if (warn_of_possible_attack)
745 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.");
746 }
747
748 namespace
749 {
750 bool check_file_overwrite(const std::string &filename)
751 {
752 boost::system::error_code errcode;
753 if (boost::filesystem::exists(filename, errcode))
754 {
755 if (boost::ends_with(filename, ".keys"))
756 {
757 fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename;
758 return false;
759 }
760 return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it?")) % filename).str(), true));
761 }
762 return true;
763 }
764
765 void print_secret_key(const crypto::secret_key &k)
766 {
767 static constexpr const char hex[] = u8"0123456789abcdef";
768 const uint8_t *ptr = (const uint8_t*)k.data;
769 for (size_t i = 0, sz = sizeof(k); i < sz; ++i)
770 {
771 putchar(hex[*ptr >> 4]);
772 putchar(hex[*ptr & 15]);
773 ++ptr;
774 }
775 }
776 }
777
778 bool parse_priority(const std::string& arg, uint32_t& priority)
779 {
780 auto priority_pos = std::find(
781 allowed_priority_strings.begin(),
782 allowed_priority_strings.end(),
783 arg);
784 if(priority_pos != allowed_priority_strings.end()) {
785 priority = std::distance(allowed_priority_strings.begin(), priority_pos);
786 return true;
787 }
788 return false;
789 }
790
791 std::string join_priority_strings(const char *delimiter)
792 {
793 std::string s;
794 for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
795 {
796 if (!s.empty())
797 s += delimiter;
798 s += allowed_priority_strings[n];
799 }
800 return s;
801 }
802
803 std::string simple_wallet::get_commands_str()
804 {
805 std::stringstream ss;
806 ss << tr("Commands: ") << ENDL;
807 std::string usage = m_cmd_binder.get_usage();
808 boost::replace_all(usage, "\n", "\n ");
809 usage.insert(0, " ");
810 ss << usage << ENDL;
811 return ss.str();
812 }
813
814 std::string simple_wallet::get_command_usage(const std::vector<std::string> &args)
815 {
816 std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args);
817 std::stringstream ss;
818 if(documentation.first.empty())
819 {
820 ss << tr("Unknown command: ") << args.front();
821 }
822 else
823 {
824 std::string usage = documentation.second.empty() ? args.front() : documentation.first;
825 std::string description = documentation.second.empty() ? documentation.first : documentation.second;
826 usage.insert(0, " ");
827 ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL;
828 boost::replace_all(description, "\n", "\n ");
829 description.insert(0, " ");
830 ss << tr("Command description: ") << ENDL << description << ENDL;
831 }
832 return ss.str();
833 }
834
835 bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
836 {
837 // don't log
838 PAUSE_READLINE();
839 if (m_wallet->key_on_device()) {
840 std::cout << "secret: On device. Not available" << std::endl;
841 } else {
842 SCOPED_WALLET_UNLOCK();
843 printf("secret: ");
844 print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
845 putchar('\n');
846 }
847 std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl;
848
849 return true;
850 }
851
852 bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
853 {
854 if (m_wallet->watch_only())
855 {
856 fail_msg_writer() << tr("wallet is watch-only and has no spend key");
857 return true;
858 }
859 CHECK_IF_BACKGROUND_SYNCING("has no spend key");
860 // don't log
861 PAUSE_READLINE();
862 if (m_wallet->key_on_device()) {
863 std::cout << "secret: On device. Not available" << std::endl;
864 } else {
865 SCOPED_WALLET_UNLOCK();
866 printf("secret: ");
867 print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key);
868 putchar('\n');
869 }
870 std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl;
871
872 return true;
873 }
874
875 bool simple_wallet::print_seed(bool encrypted)
876 {
877 bool success = false;
878 epee::wipeable_string seed;
879 bool ready, multisig;
880
881 if (m_wallet->key_on_device())
882 {
883 fail_msg_writer() << tr("command not supported by HW wallet");
884 return true;
885 }
886 if (m_wallet->watch_only())
887 {
888 fail_msg_writer() << tr("wallet is watch-only and has no seed");
889 return true;
890 }
891 CHECK_IF_BACKGROUND_SYNCING("has no seed");
892
893 multisig = m_wallet->multisig(&ready);
894 if (multisig)
895 {
896 if (!ready)
897 {
898 fail_msg_writer() << tr("wallet is multisig but not yet finalized");
899 return true;
900 }
901 }
902
903 SCOPED_WALLET_UNLOCK();
904
905 if (!multisig && !m_wallet->is_deterministic())
906 {
907 fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
908 return true;
909 }
910
911 epee::wipeable_string seed_pass;
912 if (encrypted)
913 {
914 auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true);
915 if (std::cin.eof() || !pwd_container)
916 return true;
917 seed_pass = pwd_container->password();
918 }
919
920 if (multisig)
921 success = m_wallet->get_multisig_seed(seed, seed_pass);
922 else if (m_wallet->is_deterministic())
923 success = m_wallet->get_seed(seed, seed_pass);
924
925 if (success)
926 {
927 print_seed(seed);
928 }
929 else
930 {
931 fail_msg_writer() << tr("Failed to retrieve seed");
932 }
933 return true;
934 }
935
936 bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
937 {
938 return print_seed(false);
939 }
940
941 bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
942 {
943 return print_seed(true);
944 }
945
946 bool simple_wallet::restore_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
947 {
948 success_msg_writer() << m_wallet->get_refresh_from_block_height();
949 return true;
950 }
951
952 bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
953 {
954 if (m_wallet->key_on_device())
955 {
956 fail_msg_writer() << tr("command not supported by HW wallet");
957 return true;
958 }
959 if (m_wallet->multisig())
960 {
961 fail_msg_writer() << tr("wallet is multisig and has no seed");
962 return true;
963 }
964 if (m_wallet->watch_only())
965 {
966 fail_msg_writer() << tr("wallet is watch-only and has no seed");
967 return true;
968 }
969 CHECK_IF_BACKGROUND_SYNCING("has no seed");
970
971 epee::wipeable_string password;
972 {
973 SCOPED_WALLET_UNLOCK();
974
975 if (!m_wallet->is_deterministic())
976 {
977 fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
978 return true;
979 }
980
981 // we need the password, even if ask-password is unset
982 if (!pwd_container)
983 {
984 pwd_container = get_and_verify_password();
985 if (pwd_container == boost::none)
986 {
987 fail_msg_writer() << tr("Incorrect password");
988 return true;
989 }
990 }
991 password = pwd_container->password();
992 }
993
994 std::string mnemonic_language = get_mnemonic_language();
995 if (mnemonic_language.empty())
996 return true;
997
998 m_wallet->set_seed_language(std::move(mnemonic_language));
999 m_wallet->rewrite(m_wallet_file, password);
1000 return true;
1001 }
1002
1003 bool simple_wallet::change_password(const std::vector<std::string> &args)
1004 {
1005 const auto orig_pwd_container = get_and_verify_password();
1006
1007 if(orig_pwd_container == boost::none)
1008 {
1009 fail_msg_writer() << tr("Your original password was incorrect.");
1010 return true;
1011 }
1012
1013 // prompts for a new password, pass true to verify the password
1014 const auto pwd_container = default_password_prompter(true);
1015 if(!pwd_container)
1016 return true;
1017
1018 try
1019 {
1020 m_wallet->change_password(m_wallet->get_wallet_file(), orig_pwd_container->password(), pwd_container->password());
1021 }
1022 catch (const tools::error::wallet_logic_error& e)
1023 {
1024 fail_msg_writer() << tr("Error with wallet rewrite: ") << e.what();
1025 return true;
1026 }
1027
1028 return true;
1029 }
1030
1031 bool simple_wallet::payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
1032 {
1033 LONG_PAYMENT_ID_SUPPORT_CHECK();
1034 }
1035
1036 bool simple_wallet::print_fee_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
1037 {
1038 if (!try_connect_to_daemon())
1039 return true;
1040 const bool per_byte = m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE);
1041 const uint64_t base_fee = m_wallet->get_base_fee();
1042 const char *base = per_byte ? "byte" : "kB";
1043 const uint64_t typical_size = per_byte ? 2500 : 13;
1044 const uint64_t size_granularity = per_byte ? 1 : 1024;
1045 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();
1046
1047 std::vector<uint64_t> fees;
1048 for (uint32_t priority = 1; priority <= 4; ++priority)
1049 {
1050 uint64_t mult = m_wallet->get_fee_multiplier(priority);
1051 fees.push_back(base_fee * typical_size * mult);
1052 }
1053 std::vector<std::pair<uint64_t, uint64_t>> blocks;
1054 try
1055 {
1056 uint64_t base_size = typical_size * size_granularity;
1057 blocks = m_wallet->estimate_backlog(base_size, base_size + size_granularity - 1, fees);
1058 }
1059 catch (const std::exception &e)
1060 {
1061 fail_msg_writer() << tr("Error: failed to estimate backlog array size: ") << e.what();
1062 return true;
1063 }
1064 if (blocks.size() != 4)
1065 {
1066 fail_msg_writer() << tr("Error: bad estimated backlog array size");
1067 return true;
1068 }
1069
1070 for (uint32_t priority = 1; priority <= 4; ++priority)
1071 {
1072 uint64_t nblocks_low = blocks[priority - 1].first;
1073 uint64_t nblocks_high = blocks[priority - 1].second;
1074 if (nblocks_low > 0)
1075 {
1076 std::string msg;
1077 if (priority == m_wallet->get_default_priority() || (m_wallet->get_default_priority() == 0 && priority == 2))
1078 msg = tr(" (current)");
1079 uint64_t minutes_low = nblocks_low * DIFFICULTY_TARGET_V2 / 60, minutes_high = nblocks_high * DIFFICULTY_TARGET_V2 / 60;
1080 if (nblocks_high == nblocks_low)
1081 message_writer() << (boost::format(tr("%u block (%u minutes) backlog at priority %u%s")) % nblocks_low % minutes_low % priority % msg).str();
1082 else
1083 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();
1084 }
1085 else
1086 message_writer() << tr("No backlog at priority ") << priority;
1087 }
1088 return true;
1089 }
1090
1091 bool simple_wallet::prepare_multisig(const std::vector<std::string> &args)
1092 {
1093 CHECK_MULTISIG_ENABLED();
1094 prepare_multisig_main(args, false);
1095 return true;
1096 }
1097
1098 bool simple_wallet::prepare_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1099 {
1100 CHECK_MULTISIG_ENABLED();
1101 if (m_wallet->key_on_device())
1102 {
1103 fail_msg_writer() << tr("command not supported by HW wallet");
1104 return false;
1105 }
1106 if (m_wallet->multisig())
1107 {
1108 fail_msg_writer() << tr("This wallet is already multisig");
1109 return false;
1110 }
1111 if (m_wallet->watch_only())
1112 {
1113 fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
1114 return false;
1115 }
1116 CHECK_IF_BACKGROUND_SYNCING("cannot be made multisig");
1117
1118 if(m_wallet->get_num_transfer_details())
1119 {
1120 fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
1121 return false;
1122 }
1123
1124 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1125
1126 std::string multisig_info = m_wallet->get_multisig_first_kex_msg();
1127 success_msg_writer() << multisig_info;
1128 success_msg_writer() << tr("Send this multisig info to all other participants, then use make_multisig <threshold> <info1> [<info2>...] with others' multisig info");
1129 success_msg_writer() << tr("This includes the PRIVATE view key, so needs to be disclosed only to that multisig wallet's participants ");
1130
1131 if (called_by_mms)
1132 {
1133 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::key_set, multisig_info);
1134 }
1135
1136 return true;
1137 }
1138
1139 bool simple_wallet::make_multisig(const std::vector<std::string> &args)
1140 {
1141 CHECK_MULTISIG_ENABLED();
1142 make_multisig_main(args, false);
1143 return true;
1144 }
1145
1146 bool simple_wallet::make_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1147 {
1148 CHECK_MULTISIG_ENABLED();
1149 if (m_wallet->key_on_device())
1150 {
1151 fail_msg_writer() << tr("command not supported by HW wallet");
1152 return false;
1153 }
1154 if (m_wallet->multisig())
1155 {
1156 fail_msg_writer() << tr("This wallet is already multisig");
1157 return false;
1158 }
1159 if (m_wallet->watch_only())
1160 {
1161 fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
1162 return false;
1163 }
1164
1165 if(m_wallet->get_num_transfer_details())
1166 {
1167 fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
1168 return false;
1169 }
1170
1171 if (args.size() < 2)
1172 {
1173 PRINT_USAGE(USAGE_MAKE_MULTISIG);
1174 return false;
1175 }
1176
1177 // parse threshold
1178 uint32_t threshold;
1179 if (!string_tools::get_xtype_from_string(threshold, args[0]))
1180 {
1181 fail_msg_writer() << tr("Invalid threshold");
1182 return false;
1183 }
1184
1185 const auto orig_pwd_container = get_and_verify_password();
1186 if(orig_pwd_container == boost::none)
1187 {
1188 fail_msg_writer() << tr("Your original password was incorrect.");
1189 return false;
1190 }
1191
1192 LOCK_IDLE_SCOPE();
1193
1194 try
1195 {
1196 auto local_args = args;
1197 local_args.erase(local_args.begin());
1198 std::string multisig_extra_info = m_wallet->make_multisig(orig_pwd_container->password(), local_args, threshold);
1199 bool ready;
1200 m_wallet->multisig(&ready);
1201 if (!ready)
1202 {
1203 success_msg_writer() << tr("Another step is needed");
1204 success_msg_writer() << multisig_extra_info;
1205 success_msg_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
1206 if (called_by_mms)
1207 {
1208 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
1209 }
1210 return true;
1211 }
1212 }
1213 catch (const std::exception &e)
1214 {
1215 fail_msg_writer() << tr("Error creating multisig: ") << e.what();
1216 return false;
1217 }
1218
1219 uint32_t total;
1220 if (!m_wallet->multisig(NULL, &threshold, &total))
1221 {
1222 fail_msg_writer() << tr("Error creating multisig: new wallet is not multisig");
1223 return false;
1224 }
1225 success_msg_writer() << std::to_string(threshold) << "/" << total << tr(" multisig address: ")
1226 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
1227
1228 return true;
1229 }
1230
1231 bool simple_wallet::exchange_multisig_keys(const std::vector<std::string> &args)
1232 {
1233 CHECK_MULTISIG_ENABLED();
1234 bool force_update_use_with_caution = false;
1235
1236 auto local_args = args;
1237 if (args.size() >= 1 && local_args[0] == "force-update-use-with-caution")
1238 {
1239 force_update_use_with_caution = true;
1240 local_args.erase(local_args.begin());
1241 }
1242
1243 exchange_multisig_keys_main(local_args, force_update_use_with_caution, false);
1244 return true;
1245 }
1246
1247 bool simple_wallet::exchange_multisig_keys_main(const std::vector<std::string> &args,
1248 const bool force_update_use_with_caution,
1249 const bool called_by_mms) {
1250 CHECK_MULTISIG_ENABLED();
1251 bool ready;
1252 if (m_wallet->key_on_device())
1253 {
1254 fail_msg_writer() << tr("command not supported by HW wallet");
1255 return false;
1256 }
1257 if (!m_wallet->multisig(&ready))
1258 {
1259 fail_msg_writer() << tr("This wallet is not multisig");
1260 return false;
1261 }
1262 if (ready)
1263 {
1264 fail_msg_writer() << tr("This wallet is already finalized");
1265 return false;
1266 }
1267
1268 const auto orig_pwd_container = get_and_verify_password();
1269 if(orig_pwd_container == boost::none)
1270 {
1271 fail_msg_writer() << tr("Your original password was incorrect.");
1272 return false;
1273 }
1274
1275 try
1276 {
1277 std::string multisig_extra_info = m_wallet->exchange_multisig_keys(orig_pwd_container->password(), args, force_update_use_with_caution);
1278 bool ready;
1279 m_wallet->multisig(&ready);
1280 if (!ready)
1281 {
1282 message_writer() << tr("Another step is needed");
1283 message_writer() << multisig_extra_info;
1284 message_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
1285 if (called_by_mms)
1286 {
1287 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::additional_key_set, multisig_extra_info);
1288 }
1289 return true;
1290 } else {
1291 uint32_t threshold, total;
1292 m_wallet->multisig(NULL, &threshold, &total);
1293 success_msg_writer() << tr("Multisig wallet has been successfully created. Current wallet type: ") << threshold << "/" << total;
1294 success_msg_writer() << tr("Multisig address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
1295 }
1296 }
1297 catch (const std::exception &e)
1298 {
1299 fail_msg_writer() << tr("Failed to perform multisig keys exchange: ") << e.what();
1300 return false;
1301 }
1302
1303 return true;
1304 }
1305
1306 bool simple_wallet::export_multisig(const std::vector<std::string> &args)
1307 {
1308 CHECK_MULTISIG_ENABLED();
1309 export_multisig_main(args, false);
1310 return true;
1311 }
1312
1313 bool simple_wallet::export_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1314 {
1315 CHECK_MULTISIG_ENABLED();
1316 bool ready;
1317 if (m_wallet->key_on_device())
1318 {
1319 fail_msg_writer() << tr("command not supported by HW wallet");
1320 return false;
1321 }
1322 if (!m_wallet->multisig(&ready))
1323 {
1324 fail_msg_writer() << tr("This wallet is not multisig");
1325 return false;
1326 }
1327 if (!ready)
1328 {
1329 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1330 return false;
1331 }
1332 if (args.size() != 1)
1333 {
1334 PRINT_USAGE(USAGE_EXPORT_MULTISIG_INFO);
1335 return false;
1336 }
1337
1338 const std::string filename = args[0];
1339 if (!called_by_mms && m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
1340 return true;
1341
1342 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1343
1344 try
1345 {
1346 cryptonote::blobdata ciphertext = m_wallet->export_multisig();
1347
1348 if (called_by_mms)
1349 {
1350 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::multisig_sync_data, ciphertext);
1351 }
1352 else
1353 {
1354 bool r = m_wallet->save_to_file(filename, ciphertext);
1355 if (!r)
1356 {
1357 fail_msg_writer() << tr("failed to save file ") << filename;
1358 return false;
1359 }
1360 }
1361 }
1362 catch (const std::exception &e)
1363 {
1364 LOG_ERROR("Error exporting multisig info: " << e.what());
1365 fail_msg_writer() << tr("Error exporting multisig info: ") << e.what();
1366 return false;
1367 }
1368
1369 success_msg_writer() << tr("Multisig info exported to ") << filename;
1370 return true;
1371 }
1372
1373 bool simple_wallet::import_multisig(const std::vector<std::string> &args)
1374 {
1375 CHECK_MULTISIG_ENABLED();
1376 import_multisig_main(args, false);
1377 return true;
1378 }
1379
1380 bool simple_wallet::import_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1381 {
1382 CHECK_MULTISIG_ENABLED();
1383 bool ready;
1384 uint32_t threshold, total;
1385 if (m_wallet->key_on_device())
1386 {
1387 fail_msg_writer() << tr("command not supported by HW wallet");
1388 return false;
1389 }
1390 if (!m_wallet->multisig(&ready, &threshold, &total))
1391 {
1392 fail_msg_writer() << tr("This wallet is not multisig");
1393 return false;
1394 }
1395 if (!ready)
1396 {
1397 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1398 return false;
1399 }
1400 if (args.size() < threshold - 1)
1401 {
1402 PRINT_USAGE(USAGE_IMPORT_MULTISIG_INFO);
1403 return false;
1404 }
1405
1406 std::vector<cryptonote::blobdata> info;
1407 for (size_t n = 0; n < args.size(); ++n)
1408 {
1409 if (called_by_mms)
1410 {
1411 info.push_back(args[n]);
1412 }
1413 else
1414 {
1415 const std::string &filename = args[n];
1416 std::string data;
1417 bool r = m_wallet->load_from_file(filename, data);
1418 if (!r)
1419 {
1420 fail_msg_writer() << tr("failed to read file ") << filename;
1421 return false;
1422 }
1423 info.push_back(std::move(data));
1424 }
1425 }
1426
1427 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1428
1429 // all read and parsed, actually import
1430 try
1431 {
1432 m_in_manual_refresh.store(true, std::memory_order_relaxed);
1433 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);});
1434 size_t n_outputs = m_wallet->import_multisig(info);
1435 // Clear line "Height xxx of xxx"
1436 std::cout << "\r \r";
1437 success_msg_writer() << tr("Multisig info imported. Number of outputs updated: ") << n_outputs;
1438 }
1439 catch (const std::exception &e)
1440 {
1441 fail_msg_writer() << tr("Failed to import multisig info: ") << e.what();
1442 return false;
1443 }
1444 if (m_wallet->is_trusted_daemon())
1445 {
1446 try
1447 {
1448 m_wallet->rescan_spent();
1449 }
1450 catch (const std::exception &e)
1451 {
1452 message_writer() << tr("Failed to update spent status after importing multisig info: ") << e.what();
1453 return false;
1454 }
1455 }
1456 else
1457 {
1458 message_writer() << tr("Untrusted daemon, spent status may be incorrect. Use a trusted daemon and run \"rescan_spent\"");
1459 return false;
1460 }
1461 return true;
1462 }
1463
1464 bool simple_wallet::accept_loaded_tx(const tools::wallet2::multisig_tx_set &txs)
1465 {
1466 std::string extra_message;
1467 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);
1468 }
1469
1470 bool simple_wallet::sign_multisig(const std::vector<std::string> &args)
1471 {
1472 CHECK_MULTISIG_ENABLED();
1473 sign_multisig_main(args, false);
1474 return true;
1475 }
1476
1477 bool simple_wallet::sign_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1478 {
1479 CHECK_MULTISIG_ENABLED();
1480 bool ready;
1481 if (m_wallet->key_on_device())
1482 {
1483 fail_msg_writer() << tr("command not supported by HW wallet");
1484 return false;
1485 }
1486 if(!m_wallet->multisig(&ready))
1487 {
1488 fail_msg_writer() << tr("This is not a multisig wallet");
1489 return false;
1490 }
1491 if (!ready)
1492 {
1493 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1494 return false;
1495 }
1496 if (args.size() != 1)
1497 {
1498 PRINT_USAGE(USAGE_SIGN_MULTISIG);
1499 return false;
1500 }
1501
1502 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1503
1504 std::string filename = args[0];
1505 std::vector<crypto::hash> txids;
1506 uint32_t signers = 0;
1507 try
1508 {
1509 if (called_by_mms)
1510 {
1511 tools::wallet2::multisig_tx_set exported_txs;
1512 std::string ciphertext;
1513 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); });
1514 if (r)
1515 {
1516 r = m_wallet->sign_multisig_tx(exported_txs, txids);
1517 }
1518 if (r)
1519 {
1520 ciphertext = m_wallet->save_multisig_tx(exported_txs);
1521 if (ciphertext.empty())
1522 {
1523 r = false;
1524 }
1525 }
1526 if (r)
1527 {
1528 mms::message_type message_type = mms::message_type::fully_signed_tx;
1529 if (txids.empty())
1530 {
1531 message_type = mms::message_type::partially_signed_tx;
1532 }
1533 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), message_type, ciphertext);
1534 filename = "MMS"; // for the messages below
1535 }
1536 else
1537 {
1538 fail_msg_writer() << tr("Failed to sign multisig transaction");
1539 return false;
1540 }
1541 }
1542 else
1543 {
1544 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); });
1545 if (!r)
1546 {
1547 fail_msg_writer() << tr("Failed to sign multisig transaction");
1548 return false;
1549 }
1550 }
1551 }
1552 catch (const tools::error::multisig_export_needed& e)
1553 {
1554 fail_msg_writer() << tr("Multisig error: ") << e.what();
1555 return false;
1556 }
1557 catch (const std::exception &e)
1558 {
1559 fail_msg_writer() << tr("Failed to sign multisig transaction: ") << e.what();
1560 return false;
1561 }
1562
1563 if (txids.empty())
1564 {
1565 uint32_t threshold;
1566 m_wallet->multisig(NULL, &threshold);
1567 uint32_t signers_needed = threshold - signers - 1;
1568 success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", "
1569 << signers_needed << " more signer(s) needed";
1570 return true;
1571 }
1572 else
1573 {
1574 std::string txids_as_text;
1575 for (const auto &txid: txids)
1576 {
1577 if (!txids_as_text.empty())
1578 txids_as_text += (", ");
1579 txids_as_text += epee::string_tools::pod_to_hex(txid);
1580 }
1581 success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", txid " << txids_as_text;
1582 success_msg_writer(true) << tr("It may be relayed to the network with submit_multisig");
1583 }
1584 return true;
1585 }
1586
1587 bool simple_wallet::submit_multisig(const std::vector<std::string> &args)
1588 {
1589 CHECK_MULTISIG_ENABLED();
1590 submit_multisig_main(args, false);
1591 return true;
1592 }
1593
1594 bool simple_wallet::submit_multisig_main(const std::vector<std::string> &args, bool called_by_mms)
1595 {
1596 CHECK_MULTISIG_ENABLED();
1597 bool ready;
1598 uint32_t threshold;
1599 if (m_wallet->key_on_device())
1600 {
1601 fail_msg_writer() << tr("command not supported by HW wallet");
1602 return false;
1603 }
1604 if (!m_wallet->multisig(&ready, &threshold))
1605 {
1606 fail_msg_writer() << tr("This is not a multisig wallet");
1607 return false;
1608 }
1609 if (!ready)
1610 {
1611 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1612 return false;
1613 }
1614 if (args.size() != 1)
1615 {
1616 PRINT_USAGE(USAGE_SUBMIT_MULTISIG);
1617 return false;
1618 }
1619
1620 if (!try_connect_to_daemon())
1621 return false;
1622
1623 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
1624
1625 std::string filename = args[0];
1626 try
1627 {
1628 tools::wallet2::multisig_tx_set txs;
1629 if (called_by_mms)
1630 {
1631 bool r = m_wallet->load_multisig_tx(args[0], txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1632 if (!r)
1633 {
1634 fail_msg_writer() << tr("Failed to load multisig transaction from MMS");
1635 return false;
1636 }
1637 }
1638 else
1639 {
1640 bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1641 if (!r)
1642 {
1643 fail_msg_writer() << tr("Failed to load multisig transaction from file");
1644 return false;
1645 }
1646 }
1647 if (txs.m_signers.size() < threshold)
1648 {
1649 fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
1650 % txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
1651 return false;
1652 }
1653
1654 // actually commit the transactions
1655 commit_or_save(txs.m_ptx, /* do_not_relay */ false);
1656 }
1657 catch (const std::exception &e)
1658 {
1659 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
1660 }
1661 catch (...)
1662 {
1663 LOG_ERROR("unknown error");
1664 fail_msg_writer() << tr("unknown error");
1665 return false;
1666 }
1667
1668 return true;
1669 }
1670
1671 bool simple_wallet::export_raw_multisig(const std::vector<std::string> &args)
1672 {
1673 CHECK_MULTISIG_ENABLED();
1674 bool ready;
1675 uint32_t threshold;
1676 if (m_wallet->key_on_device())
1677 {
1678 fail_msg_writer() << tr("command not supported by HW wallet");
1679 return true;
1680 }
1681 if (!m_wallet->multisig(&ready, &threshold))
1682 {
1683 fail_msg_writer() << tr("This is not a multisig wallet");
1684 return true;
1685 }
1686 if (!ready)
1687 {
1688 fail_msg_writer() << tr("This multisig wallet is not yet finalized");
1689 return true;
1690 }
1691 if (args.size() != 1)
1692 {
1693 PRINT_USAGE(USAGE_EXPORT_RAW_MULTISIG_TX);
1694 return true;
1695 }
1696
1697 std::string filename = args[0];
1698 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
1699 return true;
1700
1701 SCOPED_WALLET_UNLOCK();
1702
1703 try
1704 {
1705 tools::wallet2::multisig_tx_set txs;
1706 bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
1707 if (!r)
1708 {
1709 fail_msg_writer() << tr("Failed to load multisig transaction from file");
1710 return true;
1711 }
1712 if (txs.m_signers.size() < threshold)
1713 {
1714 fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
1715 % txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
1716 return true;
1717 }
1718
1719 // save the transactions
1720 std::string filenames;
1721 for (auto &ptx: txs.m_ptx)
1722 {
1723 const crypto::hash txid = cryptonote::get_transaction_hash(ptx.tx);
1724 const std::string filename = std::string("raw_multisig_monero_tx_") + epee::string_tools::pod_to_hex(txid);
1725 if (!filenames.empty())
1726 filenames += ", ";
1727 filenames += filename;
1728 if (!m_wallet->save_to_file(filename, cryptonote::tx_to_blob(ptx.tx)))
1729 {
1730 fail_msg_writer() << tr("Failed to export multisig transaction to file ") << filename;
1731 return true;
1732 }
1733 }
1734 success_msg_writer() << tr("Saved exported multisig transaction file(s): ") << filenames;
1735 }
1736 catch (const std::exception& e)
1737 {
1738 LOG_ERROR("unexpected error: " << e.what());
1739 fail_msg_writer() << tr("unexpected error: ") << e.what();
1740 }
1741 catch (...)
1742 {
1743 LOG_ERROR("Unknown error");
1744 fail_msg_writer() << tr("unknown error");
1745 }
1746
1747 return true;
1748 }
1749
1750 bool simple_wallet::print_ring(const std::vector<std::string> &args)
1751 {
1752 crypto::key_image key_image;
1753 crypto::hash txid;
1754 if (args.size() != 1)
1755 {
1756 PRINT_USAGE(USAGE_PRINT_RING);
1757 return true;
1758 }
1759
1760 if (!epee::string_tools::hex_to_pod(args[0], key_image))
1761 {
1762 fail_msg_writer() << tr("Invalid key image");
1763 return true;
1764 }
1765 // this one will always work, they're all 32 byte hex
1766 if (!epee::string_tools::hex_to_pod(args[0], txid))
1767 {
1768 fail_msg_writer() << tr("Invalid txid");
1769 return true;
1770 }
1771
1772 std::vector<uint64_t> ring;
1773 std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings;
1774 try
1775 {
1776 if (m_wallet->get_ring(key_image, ring))
1777 rings.push_back({key_image, ring});
1778 else if (!m_wallet->get_rings(txid, rings))
1779 {
1780 fail_msg_writer() << tr("Key image either not spent, or spent with ring size 1");
1781 return true;
1782 }
1783
1784 for (const auto &ring: rings)
1785 {
1786 std::stringstream str;
1787 for (const auto &x: ring.second)
1788 str << x<< " ";
1789 // do NOT translate this "absolute" below, the lin can be used as input to set_ring
1790 success_msg_writer() << epee::string_tools::pod_to_hex(ring.first) << " absolute " << str.str();
1791 }
1792 }
1793 catch (const std::exception &e)
1794 {
1795 fail_msg_writer() << tr("Failed to get key image ring: ") << e.what();
1796 }
1797
1798 return true;
1799 }
1800
1801 bool simple_wallet::set_ring(const std::vector<std::string> &args)
1802 {
1803 crypto::key_image key_image;
1804
1805 // try filename first
1806 if (args.size() == 1)
1807 {
1808 if (!epee::file_io_utils::is_file_exist(args[0]))
1809 {
1810 fail_msg_writer() << tr("File doesn't exist");
1811 return true;
1812 }
1813
1814 char str[4096];
1815 std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
1816 if (f)
1817 {
1818 while (!feof(f.get()))
1819 {
1820 if (!fgets(str, sizeof(str), f.get()))
1821 break;
1822 const size_t len = strlen(str);
1823 if (len > 0 && str[len - 1] == '\n')
1824 str[len - 1] = 0;
1825 if (!str[0])
1826 continue;
1827 char key_image_str[65], type_str[9];
1828 int read_after_key_image = 0, read = 0;
1829 int fields = sscanf(str, "%64[abcdefABCDEF0123456789] %n%8s %n", key_image_str, &read_after_key_image, type_str, &read);
1830 if (fields != 2)
1831 {
1832 fail_msg_writer() << tr("Invalid ring specification: ") << str;
1833 continue;
1834 }
1835 key_image_str[64] = 0;
1836 type_str[8] = 0;
1837 crypto::key_image key_image;
1838 if (read_after_key_image == 0 || !epee::string_tools::hex_to_pod(key_image_str, key_image))
1839 {
1840 fail_msg_writer() << tr("Invalid key image: ") << str;
1841 continue;
1842 }
1843 if (read == read_after_key_image+8 || (strcmp(type_str, "absolute") && strcmp(type_str, "relative")))
1844 {
1845 fail_msg_writer() << tr("Invalid ring type, expected relative or abosolute: ") << str;
1846 continue;
1847 }
1848 bool relative = !strcmp(type_str, "relative");
1849 if (read < 0 || (size_t)read > strlen(str))
1850 {
1851 fail_msg_writer() << tr("Error reading line: ") << str;
1852 continue;
1853 }
1854 bool valid = true;
1855 std::vector<uint64_t> ring;
1856 const char *ptr = str + read;
1857 while (*ptr)
1858 {
1859 unsigned long offset;
1860 int elements = sscanf(ptr, "%lu %n", &offset, &read);
1861 if (elements == 0 || read <= 0 || (size_t)read > strlen(str))
1862 {
1863 fail_msg_writer() << tr("Error reading line: ") << str;
1864 valid = false;
1865 break;
1866 }
1867 ring.push_back(offset);
1868 ptr += read;
1869 }
1870 if (!valid)
1871 continue;
1872 if (ring.empty())
1873 {
1874 fail_msg_writer() << tr("Invalid ring: ") << str;
1875 continue;
1876 }
1877 if (relative)
1878 {
1879 for (size_t n = 1; n < ring.size(); ++n)
1880 {
1881 if (ring[n] <= 0)
1882 {
1883 fail_msg_writer() << tr("Invalid relative ring: ") << str;
1884 valid = false;
1885 break;
1886 }
1887 }
1888 }
1889 else
1890 {
1891 for (size_t n = 1; n < ring.size(); ++n)
1892 {
1893 if (ring[n] <= ring[n-1])
1894 {
1895 fail_msg_writer() << tr("Invalid absolute ring: ") << str;
1896 valid = false;
1897 break;
1898 }
1899 }
1900 }
1901 if (!valid)
1902 continue;
1903 if (!m_wallet->set_ring(key_image, ring, relative))
1904 fail_msg_writer() << tr("Failed to set ring for key image: ") << key_image << ". " << tr("Continuing.");
1905 }
1906 f.reset();
1907 }
1908 return true;
1909 }
1910
1911 if (args.size() < 3)
1912 {
1913 PRINT_USAGE(USAGE_SET_RING);
1914 return true;
1915 }
1916
1917 if (!epee::string_tools::hex_to_pod(args[0], key_image))
1918 {
1919 fail_msg_writer() << tr("Invalid key image");
1920 return true;
1921 }
1922
1923 bool relative;
1924 if (args[1] == "absolute")
1925 {
1926 relative = false;
1927 }
1928 else if (args[1] == "relative")
1929 {
1930 relative = true;
1931 }
1932 else
1933 {
1934 fail_msg_writer() << tr("Missing absolute or relative keyword");
1935 return true;
1936 }
1937
1938 std::vector<uint64_t> ring;
1939 for (size_t n = 2; n < args.size(); ++n)
1940 {
1941 ring.resize(ring.size() + 1);
1942 if (!string_tools::get_xtype_from_string(ring.back(), args[n]))
1943 {
1944 fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
1945 return true;
1946 }
1947 if (relative)
1948 {
1949 if (ring.size() > 1 && !ring.back())
1950 {
1951 fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
1952 return true;
1953 }
1954 uint64_t sum = 0;
1955 for (uint64_t out: ring)
1956 {
1957 if (out > std::numeric_limits<uint64_t>::max() - sum)
1958 {
1959 fail_msg_writer() << tr("invalid index: indices wrap");
1960 return true;
1961 }
1962 sum += out;
1963 }
1964 }
1965 else
1966 {
1967 if (ring.size() > 1 && ring[ring.size() - 2] >= ring[ring.size() - 1])
1968 {
1969 fail_msg_writer() << tr("invalid index: indices should be in strictly ascending order");
1970 return true;
1971 }
1972 }
1973 }
1974 if (!m_wallet->set_ring(key_image, ring, relative))
1975 {
1976 fail_msg_writer() << tr("failed to set ring");
1977 return true;
1978 }
1979
1980 return true;
1981 }
1982
1983 bool simple_wallet::unset_ring(const std::vector<std::string> &args)
1984 {
1985 crypto::hash txid;
1986 std::vector<crypto::key_image> key_images;
1987
1988 if (args.size() < 1)
1989 {
1990 PRINT_USAGE(USAGE_UNSET_RING);
1991 return true;
1992 }
1993
1994 key_images.resize(args.size());
1995 for (size_t i = 0; i < args.size(); ++i)
1996 {
1997 if (!epee::string_tools::hex_to_pod(args[i], key_images[i]))
1998 {
1999 fail_msg_writer() << tr("Invalid key image or txid");
2000 return true;
2001 }
2002 }
2003 static_assert(sizeof(crypto::hash) == sizeof(crypto::key_image), "hash and key_image must have the same size");
2004 memcpy(&txid, &key_images[0], sizeof(txid));
2005
2006 if (!m_wallet->unset_ring(key_images) && !m_wallet->unset_ring(txid))
2007 {
2008 fail_msg_writer() << tr("failed to unset ring");
2009 return true;
2010 }
2011
2012 return true;
2013 }
2014
2015 bool simple_wallet::rpc_payment_info(const std::vector<std::string> &args)
2016 {
2017 if (!try_connect_to_daemon())
2018 return true;
2019
2020 LOCK_IDLE_SCOPE();
2021
2022 try
2023 {
2024 bool payment_required;
2025 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
2026 uint32_t cookie;
2027 std::string hashing_blob;
2028 crypto::hash seed_hash, next_seed_hash;
2029 crypto::public_key pkey;
2030 crypto::secret_key_to_public_key(m_wallet->get_rpc_client_secret_key(), pkey);
2031 message_writer() << tr("RPC client ID: ") << pkey;
2032 message_writer() << tr("RPC client secret key: ") << crypto::secret_key_explicit_print_ref{m_wallet->get_rpc_client_secret_key()};
2033 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))
2034 {
2035 fail_msg_writer() << tr("Failed to query daemon");
2036 return true;
2037 }
2038 if (payment_required)
2039 {
2040 uint64_t target = m_wallet->credits_target();
2041 if (target == 0)
2042 target = CREDITS_TARGET;
2043 message_writer() << tr("Using daemon: ") << m_wallet->get_daemon_address();
2044 message_writer() << tr("Payments required for node use, current credits: ") << credits;
2045 message_writer() << tr("Credits target: ") << target;
2046 uint64_t expected, discrepancy;
2047 m_wallet->credit_report(expected, discrepancy);
2048 message_writer() << tr("Credits spent this session: ") << expected;
2049 if (expected)
2050 message_writer() << tr("Credit discrepancy this session: ") << discrepancy << " (" << 100.0f * discrepancy / expected << "%)";
2051 float cph = credits_per_hash_found / (float)diff;
2052 message_writer() << tr("Difficulty: ") << diff << ", " << credits_per_hash_found << " " << tr("credits per hash found, ") << cph << " " << tr("credits/hash");
2053 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
2054 bool mining = (now - m_last_rpc_payment_mining_time).total_microseconds() < 1000000;
2055 if (mining)
2056 {
2057 float hash_rate = m_rpc_payment_hash_rate;
2058 if (hash_rate > 0)
2059 {
2060 message_writer() << (boost::format(tr("Mining for payment at %.1f H/s")) % hash_rate).str();
2061 if (credits < target)
2062 {
2063 std::chrono::seconds seconds((unsigned)((target - credits) / cph / hash_rate));
2064 std::string target_string = get_human_readable_timespan(seconds);
2065 message_writer() << (boost::format(tr("Estimated time till %u credits target mined: %s")) % target % target_string).str();
2066 }
2067 }
2068 else
2069 message_writer() << tr("Mining for payment");
2070 }
2071 else
2072 message_writer() << tr("Not mining");
2073 }
2074 else
2075 message_writer() << tr("No payment needed for node use");
2076 }
2077 catch (const std::exception& e)
2078 {
2079 LOG_ERROR("unexpected error: " << e.what());
2080 fail_msg_writer() << tr("unexpected error: ") << e.what();
2081 }
2082
2083 return true;
2084 }
2085
2086 bool simple_wallet::blackball(const std::vector<std::string> &args)
2087 {
2088 uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets;
2089 if (args.size() == 0)
2090 {
2091 PRINT_USAGE(USAGE_MARK_OUTPUT_SPENT);
2092 return true;
2093 }
2094
2095 try
2096 {
2097 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &amount, &offset) == 2)
2098 {
2099 m_wallet->blackball_output(std::make_pair(amount, offset));
2100 }
2101 else if (epee::file_io_utils::is_file_exist(args[0]))
2102 {
2103 std::vector<std::pair<uint64_t, uint64_t>> outputs;
2104 char str[256];
2105
2106 std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
2107 if (f)
2108 {
2109 while (!feof(f.get()))
2110 {
2111 if (!fgets(str, sizeof(str), f.get()))
2112 break;
2113 const size_t len = strlen(str);
2114 if (len > 0 && str[len - 1] == '\n')
2115 str[len - 1] = 0;
2116 if (!str[0])
2117 continue;
2118 if (sscanf(str, "@%" PRIu64, &amount) == 1)
2119 {
2120 continue;
2121 }
2122 if (amount == std::numeric_limits<uint64_t>::max())
2123 {
2124 fail_msg_writer() << tr("First line is not an amount");
2125 return true;
2126 }
2127 if (sscanf(str, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset)
2128 {
2129 while (num_offsets--)
2130 outputs.push_back(std::make_pair(amount, offset++));
2131 }
2132 else if (sscanf(str, "%" PRIu64, &offset) == 1)
2133 {
2134 outputs.push_back(std::make_pair(amount, offset));
2135 }
2136 else
2137 {
2138 fail_msg_writer() << tr("Invalid output: ") << str;
2139 return true;
2140 }
2141 }
2142 f.reset();
2143 bool add = false;
2144 if (args.size() > 1)
2145 {
2146 if (args[1] != "add")
2147 {
2148 fail_msg_writer() << tr("Bad argument: ") + args[1] + ": " + tr("should be \"add\"");
2149 return true;
2150 }
2151 add = true;
2152 }
2153 m_wallet->set_blackballed_outputs(outputs, add);
2154 }
2155 else
2156 {
2157 fail_msg_writer() << tr("Failed to open file");
2158 return true;
2159 }
2160 }
2161 else
2162 {
2163 fail_msg_writer() << tr("Invalid output key, and file doesn't exist");
2164 return true;
2165 }
2166 }
2167 catch (const std::exception &e)
2168 {
2169 fail_msg_writer() << tr("Failed to mark output spent: ") << e.what();
2170 }
2171
2172 return true;
2173 }
2174
2175 bool simple_wallet::unblackball(const std::vector<std::string> &args)
2176 {
2177 std::pair<uint64_t, uint64_t> output;
2178 if (args.size() != 1)
2179 {
2180 PRINT_USAGE(USAGE_MARK_OUTPUT_UNSPENT);
2181 return true;
2182 }
2183
2184 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
2185 {
2186 fail_msg_writer() << tr("Invalid output");
2187 return true;
2188 }
2189
2190 try
2191 {
2192 m_wallet->unblackball_output(output);
2193 }
2194 catch (const std::exception &e)
2195 {
2196 fail_msg_writer() << tr("Failed to mark output unspent: ") << e.what();
2197 }
2198
2199 return true;
2200 }
2201
2202 bool simple_wallet::blackballed(const std::vector<std::string> &args)
2203 {
2204 std::pair<uint64_t, uint64_t> output;
2205 if (args.size() != 1)
2206 {
2207 PRINT_USAGE(USAGE_IS_OUTPUT_SPENT);
2208 return true;
2209 }
2210
2211 if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
2212 {
2213 fail_msg_writer() << tr("Invalid output");
2214 return true;
2215 }
2216
2217 try
2218 {
2219 if (m_wallet->is_output_blackballed(output))
2220 message_writer() << tr("Spent: ") << output.first << "/" << output.second;
2221 else
2222 message_writer() << tr("Not spent: ") << output.first << "/" << output.second;
2223 }
2224 catch (const std::exception &e)
2225 {
2226 fail_msg_writer() << tr("Failed to check whether output is spent: ") << e.what();
2227 }
2228
2229 return true;
2230 }
2231
2232 bool simple_wallet::save_known_rings(const std::vector<std::string> &args)
2233 {
2234 fail_msg_writer() << tr("save_known_rings is deprecated");
2235 return true;
2236 }
2237
2238 bool simple_wallet::freeze_thaw(const std::vector<std::string> &args, bool freeze)
2239 {
2240 CHECK_IF_BACKGROUND_SYNCING("cannot freeze/thaw");
2241 if (args.empty())
2242 {
2243 fail_msg_writer() << boost::format(tr("usage: %s <key_image>|<pubkey>")) % (freeze ? "freeze" : "thaw");
2244 return true;
2245 }
2246 crypto::key_image ki;
2247 if (!epee::string_tools::hex_to_pod(args[0], ki))
2248 {
2249 fail_msg_writer() << tr("failed to parse key image");
2250 return true;
2251 }
2252 try
2253 {
2254 if (freeze)
2255 m_wallet->freeze(ki);
2256 else
2257 m_wallet->thaw(ki);
2258 }
2259 catch (const std::exception &e)
2260 {
2261 fail_msg_writer() << e.what();
2262 return true;
2263 }
2264
2265 return true;
2266 }
2267
2268 bool simple_wallet::freeze(const std::vector<std::string> &args)
2269 {
2270 return freeze_thaw(args, true);
2271 }
2272
2273 bool simple_wallet::thaw(const std::vector<std::string> &args)
2274 {
2275 return freeze_thaw(args, false);
2276 }
2277
2278 bool simple_wallet::frozen(const std::vector<std::string> &args)
2279 {
2280 CHECK_IF_BACKGROUND_SYNCING("cannot see frozen key images");
2281 if (args.empty())
2282 {
2283 size_t ntd = m_wallet->get_num_transfer_details();
2284 for (size_t i = 0; i < ntd; ++i)
2285 {
2286 if (!m_wallet->frozen(i))
2287 continue;
2288 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
2289 message_writer() << tr("Frozen: ") << td.m_key_image << " " << cryptonote::print_money(td.amount());
2290 }
2291 }
2292 else
2293 {
2294 crypto::key_image ki;
2295 if (!epee::string_tools::hex_to_pod(args[0], ki))
2296 {
2297 fail_msg_writer() << tr("failed to parse key image");
2298 return true;
2299 }
2300 if (m_wallet->frozen(ki))
2301 message_writer() << tr("Frozen: ") << ki;
2302 else
2303 message_writer() << tr("Not frozen: ") << ki;
2304 }
2305 return true;
2306 }
2307
2308 bool simple_wallet::lock(const std::vector<std::string> &args)
2309 {
2310 m_locked = true;
2311 check_for_inactivity_lock(true);
2312 return true;
2313 }
2314
2315 bool simple_wallet::net_stats(const std::vector<std::string> &args)
2316 {
2317 message_writer() << std::to_string(m_wallet->get_bytes_sent()) + tr(" bytes sent");
2318 message_writer() << std::to_string(m_wallet->get_bytes_received()) + tr(" bytes received");
2319 return true;
2320 }
2321
2322 bool simple_wallet::public_nodes(const std::vector<std::string> &args)
2323 {
2324 try
2325 {
2326 auto nodes = m_wallet->get_public_nodes(false);
2327 m_claimed_cph.clear();
2328 if (nodes.empty())
2329 {
2330 fail_msg_writer() << tr("No known public nodes");
2331 return true;
2332 }
2333 std::sort(nodes.begin(), nodes.end(), [](const public_node &node0, const public_node &node1) {
2334 if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash == 0)
2335 return true;
2336 if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash)
2337 return node0.rpc_credits_per_hash < node1.rpc_credits_per_hash;
2338 return false;
2339 });
2340
2341 const uint64_t now = time(NULL);
2342 message_writer() << boost::format("%32s %12s %16s") % tr("address") % tr("credits/hash") % tr("last_seen");
2343 for (const auto &node: nodes)
2344 {
2345 const float cph = node.rpc_credits_per_hash / RPC_CREDITS_PER_HASH_SCALE;
2346 char cphs[9];
2347 snprintf(cphs, sizeof(cphs), "%.3f", cph);
2348 const std::string last_seen = node.last_seen == 0 ? tr("never") : get_human_readable_timespan(std::chrono::seconds(now - node.last_seen));
2349 std::string host = node.host + ":" + std::to_string(node.rpc_port);
2350 message_writer() << boost::format("%32s %12s %16s") % host % cphs % last_seen;
2351 m_claimed_cph[host] = node.rpc_credits_per_hash;
2352 }
2353 }
2354 catch (const std::exception &e)
2355 {
2356 fail_msg_writer() << tr("Error retrieving public node list: ") << e.what();
2357 }
2358 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");
2359 return true;
2360 }
2361
2362 bool simple_wallet::welcome(const std::vector<std::string> &args)
2363 {
2364 message_writer() << tr("Welcome to Monero, the private cryptocurrency.");
2365 message_writer() << "";
2366 message_writer() << tr("Monero, like Bitcoin, is a cryptocurrency. That is, it is digital money.");
2367 message_writer() << tr("Unlike Bitcoin, your Monero transactions and balance stay private and are not visible to the world by default.");
2368 message_writer() << tr("However, you have the option of making those available to select parties if you choose to.");
2369 message_writer() << "";
2370 message_writer() << tr("Monero protects your privacy on the blockchain, and while Monero strives to improve all the time,");
2371 message_writer() << tr("no privacy technology can be 100% perfect, Monero included.");
2372 message_writer() << tr("Monero cannot protect you from malware, and it may not be as effective as we hope against powerful adversaries.");
2373 message_writer() << tr("Flaws in Monero may be discovered in the future, and attacks may be developed to peek under some");
2374 message_writer() << tr("of the layers of privacy Monero provides. Be safe and practice defense in depth.");
2375 message_writer() << "";
2376 message_writer() << tr("Welcome to Monero and financial privacy. For more information see https://GetMonero.org");
2377 return true;
2378 }
2379
2380 bool simple_wallet::version(const std::vector<std::string> &args)
2381 {
2382 message_writer() << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")";
2383 return true;
2384 }
2385
2386 bool simple_wallet::on_unknown_command(const std::vector<std::string> &args)
2387 {
2388 if (args[0] == "exit" || args[0] == "q") // backward compat
2389 return false;
2390 fail_msg_writer() << boost::format(tr("Unknown command '%s', try 'help'")) % args.front();
2391 return true;
2392 }
2393
2394 bool simple_wallet::on_empty_command()
2395 {
2396 return true;
2397 }
2398
2399 bool simple_wallet::on_cancelled_command()
2400 {
2401 check_for_inactivity_lock(false);
2402 return true;
2403 }
2404
2405 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)
2406 {
2407 std::vector<std::string> tx_aux;
2408
2409 message_writer(console_color_white, false) << tr("Please confirm the transaction on the device");
2410
2411 m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux);
2412
2413 if (accept_func && !accept_func(exported_txs))
2414 {
2415 MERROR("Transactions rejected by callback");
2416 return false;
2417 }
2418
2419 // aux info
2420 m_wallet->cold_tx_aux_import(exported_txs.ptx, tx_aux);
2421
2422 // import key images
2423 return m_wallet->import_key_images(exported_txs, 0, true);
2424 }
2425
2426 bool simple_wallet::start_mining_for_rpc(const std::vector<std::string> &args)
2427 {
2428 if (!try_connect_to_daemon())
2429 return true;
2430
2431 bool ok = true;
2432 if(args.size() >= 1)
2433 {
2434 uint16_t num = 0;
2435 ok = string_tools::get_xtype_from_string(num, args[0]);
2436 m_rpc_payment_threads = num;
2437 }
2438 else
2439 {
2440 m_rpc_payment_threads = 0;
2441 }
2442
2443 if (!ok)
2444 {
2445 PRINT_USAGE(USAGE_START_MINING_FOR_RPC);
2446 return true;
2447 }
2448
2449 LOCK_IDLE_SCOPE();
2450
2451 bool payment_required;
2452 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
2453 uint32_t cookie;
2454 std::string hashing_blob;
2455 crypto::hash seed_hash, next_seed_hash;
2456 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))
2457 {
2458 fail_msg_writer() << tr("Failed to query daemon");
2459 return true;
2460 }
2461 if (!payment_required)
2462 {
2463 fail_msg_writer() << tr("Daemon does not require payment for RPC access");
2464 return true;
2465 }
2466
2467 m_rpc_payment_mining_requested = true;
2468 m_rpc_payment_checker.trigger();
2469 const float cph = credits_per_hash_found / (float)diff;
2470 bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
2471 success_msg_writer() << (boost::format(tr("Starting mining for RPC access: diff %llu, %f credits/hash%s")) % diff % cph % (low ? " - this is low" : "")).str();
2472 success_msg_writer() << tr("Run stop_mining_for_rpc to stop");
2473 return true;
2474 }
2475
2476 bool simple_wallet::stop_mining_for_rpc(const std::vector<std::string> &args)
2477 {
2478 if (!try_connect_to_daemon())
2479 return true;
2480
2481 LOCK_IDLE_SCOPE();
2482 m_rpc_payment_mining_requested = false;
2483 m_last_rpc_payment_mining_time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1));
2484 m_rpc_payment_hash_rate = -1.0f;
2485 return true;
2486 }
2487
2488 bool simple_wallet::show_qr_code(const std::vector<std::string> &args)
2489 {
2490 uint32_t subaddress_index = 0;
2491 if (args.size() >= 1)
2492 {
2493 if (!string_tools::get_xtype_from_string(subaddress_index, args[0]))
2494 {
2495 fail_msg_writer() << tr("invalid index: must be an unsigned integer");
2496 return true;
2497 }
2498 if (subaddress_index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
2499 {
2500 fail_msg_writer() << tr("<subaddress_index> is out of bounds");
2501 return true;
2502 }
2503 }
2504
2505 #ifdef _WIN32
2506 #define PRINT_UTF8(pre, x) std::wcout << pre ## x
2507 #define WTEXTON() _setmode(_fileno(stdout), _O_WTEXT)
2508 #define WTEXTOFF() _setmode(_fileno(stdout), _O_TEXT)
2509 #else
2510 #define PRINT_UTF8(pre, x) std::cout << x
2511 #define WTEXTON()
2512 #define WTEXTOFF()
2513 #endif
2514
2515 WTEXTON();
2516 try
2517 {
2518 const std::string address = "monero:" + m_wallet->get_subaddress_as_str({m_current_subaddress_account, subaddress_index});
2519 const qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText(address.c_str(), qrcodegen::QrCode::Ecc::LOW);
2520 for (int y = -2; y < qr.getSize() + 2; y+=2)
2521 {
2522 for (int x = -2; x < qr.getSize() + 2; x++)
2523 {
2524 if (qr.getModule(x, y) && qr.getModule(x, y + 1))
2525 PRINT_UTF8(L, "\u2588");
2526 else if (qr.getModule(x, y) && !qr.getModule(x, y + 1))
2527 PRINT_UTF8(L, "\u2580");
2528 else if (!qr.getModule(x, y) && qr.getModule(x, y + 1))
2529 PRINT_UTF8(L, "\u2584");
2530 else
2531 PRINT_UTF8(L, " ");
2532 }
2533 PRINT_UTF8(, std::endl);
2534 }
2535 }
2536 catch (const std::length_error&)
2537 {
2538 fail_msg_writer() << tr("Failed to generate QR code, input too large");
2539 }
2540 WTEXTOFF();
2541 return true;
2542 }
2543
2544 bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2545 {
2546 const auto pwd_container = get_and_verify_password();
2547 if (pwd_container)
2548 {
2549 parse_bool_and_use(args[1], [&](bool r) {
2550 m_wallet->always_confirm_transfers(r);
2551 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2552 });
2553 }
2554 return true;
2555 }
2556
2557 bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2558 {
2559 const auto pwd_container = get_and_verify_password();
2560 if (pwd_container)
2561 {
2562 parse_bool_and_use(args[1], [&](bool r) {
2563 m_wallet->print_ring_members(r);
2564 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2565 });
2566 }
2567 return true;
2568 }
2569
2570 bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2571 {
2572 if (m_wallet->watch_only())
2573 {
2574 fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
2575 return true;
2576 }
2577
2578 const auto pwd_container = get_and_verify_password();
2579 if (pwd_container)
2580 {
2581 parse_bool_and_use(args[1], [&](bool r) {
2582 m_wallet->store_tx_info(r);
2583 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2584 });
2585 }
2586 return true;
2587 }
2588
2589 bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2590 {
2591 uint32_t priority = 0;
2592 try
2593 {
2594 if (strchr(args[1].c_str(), '-'))
2595 {
2596 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2597 return true;
2598 }
2599 if (args[1] == "0")
2600 {
2601 priority = 0;
2602 }
2603 else
2604 {
2605 bool found = false;
2606 for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
2607 {
2608 if (allowed_priority_strings[n] == args[1])
2609 {
2610 found = true;
2611 priority = n;
2612 }
2613 }
2614 if (!found)
2615 {
2616 priority = boost::lexical_cast<int>(args[1]);
2617 if (priority < 1 || priority > 4)
2618 {
2619 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2620 return true;
2621 }
2622 }
2623 }
2624
2625 const auto pwd_container = get_and_verify_password();
2626 if (pwd_container)
2627 {
2628 m_wallet->set_default_priority(priority);
2629 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2630 }
2631 return true;
2632 }
2633 catch(const boost::bad_lexical_cast &)
2634 {
2635 fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
2636 return true;
2637 }
2638 catch(...)
2639 {
2640 fail_msg_writer() << tr("could not change default priority");
2641 return true;
2642 }
2643 }
2644
2645 bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2646 {
2647 const auto pwd_container = get_and_verify_password();
2648 if (pwd_container)
2649 {
2650 parse_bool_and_use(args[1], [&](bool auto_refresh) {
2651 m_auto_refresh_enabled.store(false, std::memory_order_relaxed);
2652 m_wallet->auto_refresh(auto_refresh);
2653 m_idle_mutex.lock();
2654 m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed);
2655 m_idle_cond.notify_one();
2656 m_idle_mutex.unlock();
2657
2658 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2659 });
2660 }
2661 return true;
2662 }
2663
2664 bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2665 {
2666 tools::wallet2::RefreshType refresh_type;
2667 if (!parse_refresh_type(args[1], refresh_type))
2668 {
2669 return true;
2670 }
2671
2672 const auto pwd_container = get_and_verify_password();
2673 if (pwd_container)
2674 {
2675 m_wallet->set_refresh_type(refresh_type);
2676 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2677 }
2678 return true;
2679 }
2680
2681 bool simple_wallet::set_ask_password(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2682 {
2683 const auto pwd_container = get_and_verify_password();
2684 if (pwd_container)
2685 {
2686 tools::wallet2::AskPasswordType ask = tools::wallet2::AskPasswordToDecrypt;
2687 if (args[1] == "never" || args[1] == "0")
2688 ask = tools::wallet2::AskPasswordNever;
2689 else if (args[1] == "action" || args[1] == "1")
2690 ask = tools::wallet2::AskPasswordOnAction;
2691 else if (args[1] == "encrypt" || args[1] == "decrypt" || args[1] == "2")
2692 ask = tools::wallet2::AskPasswordToDecrypt;
2693 else
2694 {
2695 fail_msg_writer() << tr("invalid argument: must be either 0/never, 1/action, or 2/encrypt/decrypt");
2696 return true;
2697 }
2698
2699 const tools::wallet2::AskPasswordType cur_ask = m_wallet->ask_password();
2700 if (!m_wallet->watch_only())
2701 {
2702 if (cur_ask == tools::wallet2::AskPasswordToDecrypt && ask != tools::wallet2::AskPasswordToDecrypt)
2703 m_wallet->decrypt_keys(pwd_container->password());
2704 else if (cur_ask != tools::wallet2::AskPasswordToDecrypt && ask == tools::wallet2::AskPasswordToDecrypt)
2705 m_wallet->encrypt_keys(pwd_container->password());
2706 }
2707 m_wallet->ask_password(ask);
2708 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2709 }
2710 return true;
2711 }
2712
2713 bool simple_wallet::set_unit(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2714 {
2715 const std::string &unit = args[1];
2716 unsigned int decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
2717
2718 if (unit == "monero")
2719 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
2720 else if (unit == "millinero")
2721 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 3;
2722 else if (unit == "micronero")
2723 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 6;
2724 else if (unit == "nanonero")
2725 decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 9;
2726 else if (unit == "piconero")
2727 decimal_point = 0;
2728 else
2729 {
2730 fail_msg_writer() << tr("invalid unit");
2731 return true;
2732 }
2733
2734 const auto pwd_container = get_and_verify_password();
2735 if (pwd_container)
2736 {
2737 cryptonote::set_default_decimal_point(decimal_point);
2738 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2739 }
2740 return true;
2741 }
2742
2743 bool simple_wallet::set_max_reorg_depth(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2744 {
2745 uint64_t depth;
2746 if (!epee::string_tools::get_xtype_from_string(depth, args[1]))
2747 {
2748 fail_msg_writer() << tr("invalid value");
2749 return true;
2750 }
2751
2752 const auto pwd_container = get_and_verify_password();
2753 if (pwd_container)
2754 {
2755 m_wallet->max_reorg_depth(depth);
2756 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2757 }
2758 return true;
2759 }
2760
2761 bool simple_wallet::set_min_output_count(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2762 {
2763 uint32_t count;
2764 if (!string_tools::get_xtype_from_string(count, args[1]))
2765 {
2766 fail_msg_writer() << tr("invalid count: must be an unsigned integer");
2767 return true;
2768 }
2769
2770 const auto pwd_container = get_and_verify_password();
2771 if (pwd_container)
2772 {
2773 m_wallet->set_min_output_count(count);
2774 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2775 }
2776 return true;
2777 }
2778
2779 bool simple_wallet::set_min_output_value(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2780 {
2781 uint64_t value;
2782 if (!cryptonote::parse_amount(value, args[1]))
2783 {
2784 fail_msg_writer() << tr("invalid value");
2785 return true;
2786 }
2787
2788 const auto pwd_container = get_and_verify_password();
2789 if (pwd_container)
2790 {
2791 m_wallet->set_min_output_value(value);
2792 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2793 }
2794 return true;
2795 }
2796
2797 bool simple_wallet::set_merge_destinations(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2798 {
2799 const auto pwd_container = get_and_verify_password();
2800 if (pwd_container)
2801 {
2802 parse_bool_and_use(args[1], [&](bool r) {
2803 m_wallet->merge_destinations(r);
2804 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2805 });
2806 }
2807 return true;
2808 }
2809
2810 bool simple_wallet::set_confirm_backlog(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2811 {
2812 const auto pwd_container = get_and_verify_password();
2813 if (pwd_container)
2814 {
2815 parse_bool_and_use(args[1], [&](bool r) {
2816 m_wallet->confirm_backlog(r);
2817 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2818 });
2819 }
2820 return true;
2821 }
2822
2823 bool simple_wallet::set_confirm_backlog_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2824 {
2825 uint32_t threshold;
2826 if (!string_tools::get_xtype_from_string(threshold, args[1]))
2827 {
2828 fail_msg_writer() << tr("invalid count: must be an unsigned integer");
2829 return true;
2830 }
2831
2832 const auto pwd_container = get_and_verify_password();
2833 if (pwd_container)
2834 {
2835 m_wallet->set_confirm_backlog_threshold(threshold);
2836 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2837 }
2838 return true;
2839 }
2840
2841 bool simple_wallet::set_confirm_export_overwrite(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2842 {
2843 const auto pwd_container = get_and_verify_password();
2844 if (pwd_container)
2845 {
2846 parse_bool_and_use(args[1], [&](bool r) {
2847 m_wallet->confirm_export_overwrite(r);
2848 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2849 });
2850 }
2851 return true;
2852 }
2853
2854 bool simple_wallet::set_refresh_from_block_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2855 {
2856 const auto pwd_container = get_and_verify_password();
2857 if (pwd_container)
2858 {
2859 uint64_t height;
2860 if (!epee::string_tools::get_xtype_from_string(height, args[1]))
2861 {
2862 fail_msg_writer() << tr("Invalid height");
2863 return true;
2864 }
2865 m_wallet->set_refresh_from_block_height(height);
2866 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2867 }
2868 return true;
2869 }
2870
2871 bool simple_wallet::set_auto_low_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2872 {
2873 const auto pwd_container = get_and_verify_password();
2874 if (pwd_container)
2875 {
2876 parse_bool_and_use(args[1], [&](bool r) {
2877 m_wallet->auto_low_priority(r);
2878 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2879 });
2880 }
2881 return true;
2882 }
2883
2884 bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2885 {
2886 const auto pwd_container = get_and_verify_password();
2887 if (pwd_container)
2888 {
2889 parse_bool_and_use(args[1], [&](bool r) {
2890 m_wallet->segregate_pre_fork_outputs(r);
2891 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2892 });
2893 }
2894 return true;
2895 }
2896
2897 bool simple_wallet::set_persistent_rpc_client_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2898 {
2899 const auto pwd_container = get_and_verify_password();
2900 if (pwd_container)
2901 {
2902 parse_bool_and_use(args[1], [&](bool r) {
2903 m_wallet->persistent_rpc_client_id(r);
2904 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2905 });
2906 }
2907 return true;
2908 }
2909
2910 bool simple_wallet::set_auto_mine_for_rpc_payment_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2911 {
2912 const auto pwd_container = get_and_verify_password();
2913 if (pwd_container)
2914 {
2915 float threshold;
2916 if (!epee::string_tools::get_xtype_from_string(threshold, args[1]) || threshold < 0.0f)
2917 {
2918 fail_msg_writer() << tr("Invalid threshold");
2919 return true;
2920 }
2921 m_wallet->auto_mine_for_rpc_payment_threshold(threshold);
2922 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2923 }
2924 return true;
2925 }
2926
2927 bool simple_wallet::set_credits_target(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2928 {
2929 const auto pwd_container = get_and_verify_password();
2930 if (pwd_container)
2931 {
2932 uint64_t target;
2933 if (!epee::string_tools::get_xtype_from_string(target, args[1]))
2934 {
2935 fail_msg_writer() << tr("Invalid target");
2936 return true;
2937 }
2938 m_wallet->credits_target(target);
2939 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2940 }
2941 return true;
2942 }
2943
2944 bool simple_wallet::set_key_reuse_mitigation2(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2945 {
2946 const auto pwd_container = get_and_verify_password();
2947 if (pwd_container)
2948 {
2949 parse_bool_and_use(args[1], [&](bool r) {
2950 m_wallet->key_reuse_mitigation2(r);
2951 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2952 });
2953 }
2954 return true;
2955 }
2956
2957 bool simple_wallet::set_subaddress_lookahead(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2958 {
2959 const auto pwd_container = get_and_verify_password();
2960 if (pwd_container)
2961 {
2962 auto lookahead = parse_subaddress_lookahead(args[1]);
2963 if (lookahead)
2964 {
2965 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
2966 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2967 }
2968 }
2969 return true;
2970 }
2971
2972 bool simple_wallet::set_segregation_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2973 {
2974 const auto pwd_container = get_and_verify_password();
2975 if (pwd_container)
2976 {
2977 uint64_t height;
2978 if (!epee::string_tools::get_xtype_from_string(height, args[1]))
2979 {
2980 fail_msg_writer() << tr("Invalid height");
2981 return true;
2982 }
2983 m_wallet->segregation_height(height);
2984 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2985 }
2986 return true;
2987 }
2988
2989 bool simple_wallet::set_ignore_fractional_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
2990 {
2991 const auto pwd_container = get_and_verify_password();
2992 if (pwd_container)
2993 {
2994 parse_bool_and_use(args[1], [&](bool r) {
2995 m_wallet->ignore_fractional_outputs(r);
2996 m_wallet->rewrite(m_wallet_file, pwd_container->password());
2997 });
2998 }
2999 return true;
3000 }
3001
3002
3003 bool simple_wallet::set_ignore_outputs_above(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 uint64_t amount;
3009 if (!cryptonote::parse_amount(amount, args[1]))
3010 {
3011 fail_msg_writer() << tr("Invalid amount");
3012 return true;
3013 }
3014 if (amount == 0)
3015 amount = MONEY_SUPPLY;
3016 m_wallet->ignore_outputs_above(amount);
3017 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3018 }
3019 return true;
3020 }
3021
3022 bool simple_wallet::set_ignore_outputs_below(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3023 {
3024 const auto pwd_container = get_and_verify_password();
3025 if (pwd_container)
3026 {
3027 uint64_t amount;
3028 if (!cryptonote::parse_amount(amount, args[1]))
3029 {
3030 fail_msg_writer() << tr("Invalid amount");
3031 return true;
3032 }
3033 m_wallet->ignore_outputs_below(amount);
3034 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3035 }
3036 return true;
3037 }
3038
3039 bool simple_wallet::set_track_uses(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3040 {
3041 const auto pwd_container = get_and_verify_password();
3042 if (pwd_container)
3043 {
3044 parse_bool_and_use(args[1], [&](bool r) {
3045 m_wallet->track_uses(r);
3046 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3047 });
3048 }
3049 return true;
3050 }
3051
3052 bool simple_wallet::setup_background_sync(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3053 {
3054 if (m_wallet->multisig())
3055 {
3056 fail_msg_writer() << tr("background sync not implemented for multisig wallet");
3057 return true;
3058 }
3059 if (m_wallet->watch_only())
3060 {
3061 fail_msg_writer() << tr("background sync not implemented for watch only wallet");
3062 return true;
3063 }
3064 if (m_wallet->key_on_device())
3065 {
3066 fail_msg_writer() << tr("command not supported by HW wallet");
3067 return true;
3068 }
3069
3070 tools::wallet2::BackgroundSyncType background_sync_type;
3071 if (!parse_background_sync_type(args[1], background_sync_type))
3072 {
3073 fail_msg_writer() << tr("invalid option");
3074 return true;
3075 }
3076
3077 const auto pwd_container = get_and_verify_password();
3078 if (!pwd_container)
3079 return true;
3080
3081 try
3082 {
3083 boost::optional<epee::wipeable_string> background_cache_password = boost::none;
3084 if (background_sync_type == tools::wallet2::BackgroundSyncCustomPassword)
3085 {
3086 const auto background_pwd_container = background_sync_cache_password_prompter(true);
3087 if (!background_pwd_container)
3088 return true;
3089 background_cache_password = background_pwd_container->password();
3090 }
3091
3092 LOCK_IDLE_SCOPE();
3093 m_wallet->setup_background_sync(background_sync_type, pwd_container->password(), background_cache_password);
3094 }
3095 catch (const std::exception &e)
3096 {
3097 fail_msg_writer() << tr("Error setting background sync type: ") << e.what();
3098 }
3099
3100 return true;
3101 }
3102
3103 bool simple_wallet::set_show_wallet_name_when_locked(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3104 {
3105 const auto pwd_container = get_and_verify_password();
3106 if (pwd_container)
3107 {
3108 parse_bool_and_use(args[1], [&](bool r) {
3109 m_wallet->show_wallet_name_when_locked(r);
3110 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3111 });
3112 }
3113 return true;
3114 }
3115
3116 bool simple_wallet::set_inactivity_lock_timeout(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3117 {
3118 #ifdef _WIN32
3119 tools::fail_msg_writer() << tr("Inactivity lock timeout disabled on Windows");
3120 return true;
3121 #endif
3122 const auto pwd_container = get_and_verify_password();
3123 if (pwd_container)
3124 {
3125 uint32_t r;
3126 if (epee::string_tools::get_xtype_from_string(r, args[1]))
3127 {
3128 m_wallet->inactivity_lock_timeout(r);
3129 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3130 }
3131 else
3132 {
3133 tools::fail_msg_writer() << tr("Invalid number of seconds");
3134 }
3135 }
3136 return true;
3137 }
3138
3139 bool simple_wallet::set_setup_background_mining(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3140 {
3141 const auto pwd_container = get_and_verify_password();
3142 if (pwd_container)
3143 {
3144 tools::wallet2::BackgroundMiningSetupType setup = tools::wallet2::BackgroundMiningMaybe;
3145 if (args[1] == "yes" || args[1] == "1")
3146 setup = tools::wallet2::BackgroundMiningYes;
3147 else if (args[1] == "no" || args[1] == "0")
3148 setup = tools::wallet2::BackgroundMiningNo;
3149 else
3150 {
3151 fail_msg_writer() << tr("invalid argument: must be either 1/yes or 0/no");
3152 return true;
3153 }
3154 m_wallet->setup_background_mining(setup);
3155 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3156 if (setup == tools::wallet2::BackgroundMiningYes)
3157 start_background_mining();
3158 else
3159 stop_background_mining();
3160 }
3161 return true;
3162 }
3163
3164 bool simple_wallet::set_device_name(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3165 {
3166 const auto pwd_container = get_and_verify_password();
3167 if (pwd_container)
3168 {
3169 if (args.size() == 0){
3170 fail_msg_writer() << tr("Device name not specified");
3171 return true;
3172 }
3173
3174 m_wallet->device_name(args[1]);
3175 bool r = false;
3176 try {
3177 r = m_wallet->reconnect_device();
3178 if (!r){
3179 fail_msg_writer() << tr("Device reconnect failed");
3180 }
3181
3182 } catch(const std::exception & e){
3183 MWARNING("Device reconnect failed: " << e.what());
3184 fail_msg_writer() << tr("Device reconnect failed: ") << e.what();
3185 }
3186
3187 }
3188 return true;
3189 }
3190
3191 bool simple_wallet::set_export_format(const std::vector<std::string> &args/* = std::vector<std::string()*/)
3192 {
3193 if (args.size() < 2)
3194 {
3195 fail_msg_writer() << tr("Export format not specified");
3196 return true;
3197 }
3198
3199 if (boost::algorithm::iequals(args[1], "ascii"))
3200 {
3201 m_wallet->set_export_format(tools::wallet2::ExportFormat::Ascii);
3202 }
3203 else if (boost::algorithm::iequals(args[1], "binary"))
3204 {
3205 m_wallet->set_export_format(tools::wallet2::ExportFormat::Binary);
3206 }
3207 else
3208 {
3209 fail_msg_writer() << tr("Export format not recognized.");
3210 return true;
3211 }
3212 const auto pwd_container = get_and_verify_password();
3213 if (pwd_container)
3214 {
3215 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3216 }
3217 return true;
3218 }
3219
3220 bool simple_wallet::set_load_deprecated_formats(const std::vector<std::string> &args/* = std::vector<std::string()*/)
3221 {
3222 if (args.size() < 2)
3223 {
3224 fail_msg_writer() << tr("Value not specified");
3225 return true;
3226 }
3227
3228 const auto pwd_container = get_and_verify_password();
3229 if (pwd_container)
3230 {
3231 parse_bool_and_use(args[1], [&](bool r) {
3232 m_wallet->load_deprecated_formats(r);
3233 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3234
3235 if (r)
3236 message_writer() << tr("Warning: deprecated formats use boost serialization, which has buffer overflows and crashers. Only load deprecated formats from sources you trust.");
3237 });
3238 }
3239 return true;
3240 }
3241
3242 bool simple_wallet::set_enable_multisig(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3243 {
3244 if (args.size() < 2)
3245 {
3246 fail_msg_writer() << tr("Value not specified");
3247 return true;
3248 }
3249
3250 const auto pwd_container = get_and_verify_password();
3251 if (pwd_container)
3252 {
3253 parse_bool_and_use(args[1], [&](bool r) {
3254 m_wallet->enable_multisig(r);
3255 m_wallet->rewrite(m_wallet_file, pwd_container->password());
3256 });
3257 }
3258 return true;
3259 }
3260
3261 bool simple_wallet::help(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
3262 {
3263 if(args.empty())
3264 {
3265 message_writer() << "";
3266 message_writer() << tr("Important commands:");
3267 message_writer() << "";
3268 message_writer() << tr("\"welcome\" - Show welcome message.");
3269 message_writer() << tr("\"help all\" - Show the list of all available commands.");
3270 message_writer() << tr("\"help <command>\" - Show a command's documentation.");
3271 message_writer() << tr("\"apropos <keyword>\" - Show commands related to a keyword.");
3272 message_writer() << "";
3273 message_writer() << tr("\"wallet_info\" - Show wallet main address and other info.");
3274 message_writer() << tr("\"balance\" - Show balance.");
3275 message_writer() << tr("\"address all\" - Show all addresses.");
3276 message_writer() << tr("\"address new\" - Create new subaddress.");
3277 message_writer() << tr("\"transfer <address> <amount>\" - Send XMR to an address.");
3278 message_writer() << tr("\"show_transfers [in|out|pending|failed|pool]\" - Show transactions.");
3279 message_writer() << tr("\"sweep_all <address>\" - Send whole balance to another wallet.");
3280 message_writer() << tr("\"seed\" - Show secret 25 words that can be used to recover this wallet.");
3281 message_writer() << tr("\"refresh\" - Synchronize wallet with the Monero network.");
3282 message_writer() << tr("\"status\" - Check current status of wallet.");
3283 message_writer() << tr("\"version\" - Check software version.");
3284 message_writer() << tr("\"exit\" - Exit wallet.");
3285 message_writer() << "";
3286 message_writer() << tr("\"donate <amount>\" - Donate XMR to the development team.");
3287 message_writer() << "";
3288 }
3289 else if ((args.size() == 1) && (args.front() == "all"))
3290 {
3291 success_msg_writer() << get_commands_str();
3292 }
3293 else if ((args.size() == 2) && (args.front() == "mms"))
3294 {
3295 // Little hack to be able to do "help mms <subcommand>"
3296 std::vector<std::string> mms_args(1, args.front() + " " + args.back());
3297 success_msg_writer() << get_command_usage(mms_args);
3298 }
3299 else
3300 {
3301 success_msg_writer() << get_command_usage(args);
3302 }
3303 return true;
3304 }
3305
3306 bool simple_wallet::apropos(const std::vector<std::string> &args)
3307 {
3308 if (args.empty())
3309 {
3310 PRINT_USAGE(USAGE_APROPOS);
3311 return true;
3312 }
3313 const std::vector<std::string>& command_list = m_cmd_binder.get_command_list(args);
3314 if (command_list.empty())
3315 {
3316 fail_msg_writer() << tr("No commands found mentioning keyword(s)");
3317 return true;
3318 }
3319
3320 success_msg_writer() << "";
3321 for(auto const& command:command_list)
3322 {
3323 std::vector<std::string> cmd;
3324 cmd.push_back(command);
3325 std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(cmd);
3326 success_msg_writer() << " " << documentation.first;
3327 }
3328 success_msg_writer() << "";
3329
3330 return true;
3331 }
3332
3333 bool simple_wallet::scan_tx(const std::vector<std::string> &args)
3334 {
3335 CHECK_IF_BACKGROUND_SYNCING("cannot scan tx");
3336 if (args.empty())
3337 {
3338 PRINT_USAGE(USAGE_SCAN_TX);
3339 return true;
3340 }
3341
3342 // Parse and dedup args
3343 std::unordered_set<crypto::hash> txids;
3344 for (const auto &s : args) {
3345 crypto::hash txid;
3346 if (!epee::string_tools::hex_to_pod(s, txid)) {
3347 fail_msg_writer() << tr("Invalid txid specified: ") << s;
3348 return true;
3349 }
3350 txids.insert(txid);
3351 }
3352
3353 if (!m_wallet->is_trusted_daemon()) {
3354 message_writer(console_color_red, true) << tr("WARNING: this operation may reveal the txids to the remote node and affect your privacy");
3355 if (!command_line::is_yes(input_line("Do you want to continue?", true))) {
3356 message_writer() << tr("You have canceled the operation");
3357 return true;
3358 }
3359 }
3360
3361 LOCK_IDLE_SCOPE();
3362 m_in_manual_refresh.store(true);
3363 try {
3364 m_wallet->scan_tx(txids);
3365 } catch (const tools::error::wont_reprocess_recent_txs_via_untrusted_daemon &e) {
3366 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.";
3367 } catch (const std::exception &e) {
3368 fail_msg_writer() << e.what();
3369 }
3370 m_in_manual_refresh.store(false);
3371 return true;
3372 }
3373
3374 simple_wallet::simple_wallet()
3375 : m_refresh_progress_reporter(*this)
3376 , m_idle_run(true)
3377 , m_auto_refresh_enabled(false)
3378 , m_auto_refresh_refreshing(false)
3379 , m_in_manual_refresh(false)
3380 , m_current_subaddress_account(0)
3381 , m_last_activity_time(time(NULL))
3382 , m_locked(false)
3383 , m_in_command(false)
3384 , m_need_payment(false)
3385 , m_rpc_payment_mining_requested(false)
3386 , m_last_rpc_payment_mining_time(boost::gregorian::date(1970, 1, 1))
3387 , m_daemon_rpc_payment_message_displayed(false)
3388 , m_rpc_payment_hash_rate(-1.0f)
3389 , m_suspend_rpc_payment_mining(false)
3390 {
3391 m_cmd_binder.set_handler("start_mining",
3392 boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining, _1),
3393 tr(USAGE_START_MINING),
3394 tr("Start mining in the daemon (bg_mining and ignore_battery are optional booleans)."));
3395 m_cmd_binder.set_handler("stop_mining",
3396 boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining, _1),
3397 tr("Stop mining in the daemon."));
3398 m_cmd_binder.set_handler("set_daemon",
3399 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_daemon, _1),
3400 tr(USAGE_SET_DAEMON),
3401 tr("Set another daemon to connect to. If it's not yours, it'll probably spy on you."));
3402 m_cmd_binder.set_handler("save_bc",
3403 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_bc, _1),
3404 tr("Save the current blockchain data."));
3405 m_cmd_binder.set_handler("refresh",
3406 boost::bind(&simple_wallet::on_command, this, &simple_wallet::refresh, _1),
3407 tr("Synchronize the transactions and balance."));
3408 m_cmd_binder.set_handler("balance",
3409 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_balance, _1),
3410 tr(USAGE_SHOW_BALANCE),
3411 tr("Show the wallet's balance of the currently selected account."));
3412 m_cmd_binder.set_handler("incoming_transfers",
3413 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_incoming_transfers,_1),
3414 tr(USAGE_INCOMING_TRANSFERS),
3415 tr("Show the incoming transfers, all or filtered by availability and address index.\n\n"
3416 "Output format:\n"
3417 "Amount, Spent(\"T\"|\"F\"), \"frozen\"|\"locked\"|\"unlocked\", RingCT, Global Index, Transaction Hash, Address Index, [Public Key, Key Image] "));
3418 m_cmd_binder.set_handler("payments",
3419 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_payments,_1),
3420 tr(USAGE_PAYMENTS),
3421 tr("Show the payments for the given payment IDs."));
3422 m_cmd_binder.set_handler("bc_height",
3423 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_blockchain_height, _1),
3424 tr("Show the blockchain height."));
3425 m_cmd_binder.set_handler("transfer", boost::bind(&simple_wallet::on_command, this, &simple_wallet::transfer, _1),
3426 tr(USAGE_TRANSFER),
3427 tr("Transfer <address> <amount>. 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."));
3428 m_cmd_binder.set_handler("sweep_unmixable",
3429 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_unmixable, _1),
3430 tr("Send all unmixable outputs to yourself with ring_size 1"));
3431 m_cmd_binder.set_handler("sweep_all", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_all, _1),
3432 tr(USAGE_SWEEP_ALL),
3433 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."));
3434 m_cmd_binder.set_handler("sweep_account", boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_account, _1),
3435 tr(USAGE_SWEEP_ACCOUNT),
3436 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."));
3437 m_cmd_binder.set_handler("sweep_below",
3438 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_below, _1),
3439 tr(USAGE_SWEEP_BELOW),
3440 tr("Send all unlocked outputs below the threshold to an address."));
3441 m_cmd_binder.set_handler("sweep_single",
3442 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sweep_single, _1),
3443 tr(USAGE_SWEEP_SINGLE),
3444 tr("Send a single output of the given key image to an address without change."));
3445 m_cmd_binder.set_handler("donate",
3446 boost::bind(&simple_wallet::on_command, this, &simple_wallet::donate, _1),
3447 tr(USAGE_DONATE),
3448 tr("Donate <amount> to the development team (donate.getmonero.org)."));
3449 m_cmd_binder.set_handler("sign_transfer",
3450 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_transfer, _1),
3451 tr(USAGE_SIGN_TRANSFER),
3452 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"
3453 "Use the parameter <filename> to specify the file to read from. If not specified, the default \"unsigned_monero_tx\" will be used."));
3454 m_cmd_binder.set_handler("submit_transfer",
3455 boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_transfer, _1),
3456 tr("Submit a signed transaction from a file."));
3457 m_cmd_binder.set_handler("set_log",
3458 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_log, _1),
3459 tr(USAGE_SET_LOG),
3460 tr("Change the current log detail (level must be <0-4>)."));
3461 m_cmd_binder.set_handler("account",
3462 boost::bind(&simple_wallet::on_command, this, &simple_wallet::account, _1),
3463 tr(USAGE_ACCOUNT),
3464 tr("If no arguments are specified, the wallet shows all the existing accounts along with their balances.\n"
3465 "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"
3466 "If the \"switch\" argument is specified, the wallet switches to the account specified by <index>.\n"
3467 "If the \"label\" argument is specified, the wallet sets the label of the account specified by <index> to the provided label text.\n"
3468 "If the \"tag\" argument is specified, a tag <tag_name> is assigned to the specified accounts <account_index_1>, <account_index_2>, ....\n"
3469 "If the \"untag\" argument is specified, the tags assigned to the specified accounts <account_index_1>, <account_index_2> ..., are removed.\n"
3470 "If the \"tag_description\" argument is specified, the tag <tag_name> is assigned an arbitrary text <description>."));
3471 m_cmd_binder.set_handler("address",
3472 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_address, _1),
3473 tr(USAGE_ADDRESS),
3474 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"));
3475 m_cmd_binder.set_handler("integrated_address",
3476 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_integrated_address, _1),
3477 tr(USAGE_INTEGRATED_ADDRESS),
3478 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"));
3479 m_cmd_binder.set_handler("address_book",
3480 boost::bind(&simple_wallet::on_command, this, &simple_wallet::address_book,_1),
3481 tr(USAGE_ADDRESS_BOOK),
3482 tr("Print all entries in the address book, optionally adding/deleting an entry to/from it."));
3483 m_cmd_binder.set_handler("save",
3484 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save, _1),
3485 tr("Save the wallet data."));
3486 m_cmd_binder.set_handler("save_watch_only",
3487 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_watch_only, _1),
3488 tr("Save a watch-only keys file."));
3489 m_cmd_binder.set_handler("viewkey",
3490 boost::bind(&simple_wallet::on_command, this, &simple_wallet::viewkey, _1),
3491 tr("Display the private view key."));
3492 m_cmd_binder.set_handler("spendkey",
3493 boost::bind(&simple_wallet::on_command, this, &simple_wallet::spendkey, _1),
3494 tr("Display the private spend key."));
3495 m_cmd_binder.set_handler("seed",
3496 boost::bind(&simple_wallet::on_command, this, &simple_wallet::seed, _1),
3497 tr("Display the Electrum-style mnemonic seed"));
3498 m_cmd_binder.set_handler("restore_height",
3499 boost::bind(&simple_wallet::on_command, this, &simple_wallet::restore_height, _1),
3500 tr("Display the restore height"));
3501 m_cmd_binder.set_handler("set",
3502 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_variable, _1),
3503 tr(USAGE_SET_VARIABLE),
3504 tr("Available options:\n "
3505 "seed language\n "
3506 " Set the wallet's seed language.\n "
3507 "always-confirm-transfers <1|0>\n "
3508 " Whether to confirm unsplit txes.\n "
3509 "print-ring-members <1|0>\n "
3510 " Whether to print detailed information about ring members during confirmation.\n "
3511 "store-tx-info <1|0>\n "
3512 " Whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference.\n "
3513 "auto-refresh <1|0>\n "
3514 " Whether to automatically synchronize new blocks from the daemon.\n "
3515 "refresh-type <full|optimize-coinbase|no-coinbase|default>\n "
3516 " Set the wallet's refresh behaviour.\n "
3517 "priority [0|1|2|3|4]\n "
3518 " Set the fee to default/unimportant/normal/elevated/priority.\n "
3519 "confirm-missing-payment-id <1|0> (obsolete)\n "
3520 "ask-password <0|1|2 (or never|action|decrypt)>\n "
3521 " action: ask the password before many actions such as transfer, etc\n "
3522 " decrypt: same as action, but keeps the spend key encrypted in memory when not needed\n "
3523 "unit <monero|millinero|micronero|nanonero|piconero>\n "
3524 " Set the default monero (sub-)unit.\n "
3525 "min-outputs-count [n]\n "
3526 " Try to keep at least that many outputs of value at least min-outputs-value.\n "
3527 "min-outputs-value [n]\n "
3528 " Try to keep at least min-outputs-count outputs of at least that value.\n "
3529 "merge-destinations <1|0>\n "
3530 " Whether to merge multiple payments to the same destination address.\n "
3531 "confirm-backlog <1|0>\n "
3532 " Whether to warn if there is transaction backlog.\n "
3533 "confirm-backlog-threshold [n]\n "
3534 " Set a threshold for confirm-backlog to only warn if the transaction backlog is greater than n blocks.\n "
3535 "confirm-export-overwrite <1|0>\n "
3536 " Whether to warn if the file to be exported already exists.\n "
3537 "refresh-from-block-height [n]\n "
3538 " Set the height before which to ignore blocks.\n "
3539 "auto-low-priority <1|0>\n "
3540 " Whether to automatically use the low priority fee level when it's safe to do so.\n "
3541 "segregate-pre-fork-outputs <1|0>\n "
3542 " Set this if you intend to spend outputs on both Monero AND a key reusing fork.\n "
3543 "key-reuse-mitigation2 <1|0>\n "
3544 " Set this if you are not sure whether you will spend on a key reusing Monero fork later.\n "
3545 "subaddress-lookahead <major>:<minor>\n "
3546 " Set the lookahead sizes for the subaddress hash table.\n "
3547 "segregation-height <n>\n "
3548 " Set to the height of a key reusing fork you want to use, 0 to use default.\n "
3549 "ignore-fractional-outputs <1|0>\n "
3550 " Whether to ignore fractional outputs that result in net loss when spending due to fee.\n "
3551 "ignore-outputs-above <amount>\n "
3552 " Ignore outputs of amount above this threshold when spending. Value 0 is translated to the maximum value (18 million) which disables this filter.\n "
3553 "ignore-outputs-below <amount>\n "
3554 " Ignore outputs of amount below this threshold when spending.\n "
3555 "track-uses <1|0>\n "
3556 " Whether to keep track of owned outputs uses.\n "
3557 "background-sync <off|reuse-wallet-password|custom-background-password>\n "
3558 " Set this to enable scanning in the background with just the view key while the wallet is locked.\n "
3559 "setup-background-mining <1|0>\n "
3560 " Whether to enable background mining. Set this to support the network and to get a chance to receive new monero.\n "
3561 "device-name <device_name[:device_spec]>\n "
3562 " Device name for hardware wallet.\n "
3563 "export-format <\"binary\"|\"ascii\">\n "
3564 " Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n "
3565 "persistent-rpc-client-id <1|0>\n "
3566 " Whether to keep using the same client id for RPC payment over wallet restarts.\n"
3567 "auto-mine-for-rpc-payment-threshold <float>\n "
3568 " Whether to automatically start mining for RPC payment if the daemon requires it.\n"
3569 "credits-target <unsigned int>\n"
3570 " The RPC payment credits balance to target (0 for default).\n "
3571 "show-wallet-name-when-locked <1|0>\n "
3572 " Set this if you would like to display the wallet name when locked.\n "
3573 "enable-multisig-experimental <1|0>\n "
3574 " Set this to allow multisig commands. Multisig may currently be exploitable if parties do not trust each other.\n "
3575 "inactivity-lock-timeout <unsigned int>\n "
3576 " How many seconds to wait before locking the wallet (0 to disable)."));
3577 m_cmd_binder.set_handler("encrypted_seed",
3578 boost::bind(&simple_wallet::on_command, this, &simple_wallet::encrypted_seed, _1),
3579 tr("Display the encrypted Electrum-style mnemonic seed."));
3580 m_cmd_binder.set_handler("rescan_spent",
3581 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_spent, _1),
3582 tr("Rescan the blockchain for spent outputs."));
3583 m_cmd_binder.set_handler("get_tx_key",
3584 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_key, _1),
3585 tr(USAGE_GET_TX_KEY),
3586 tr("Get the transaction key (r) for a given <txid>."));
3587 m_cmd_binder.set_handler("set_tx_key",
3588 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_key, _1),
3589 tr(USAGE_SET_TX_KEY),
3590 tr("Set the transaction key (r) for a given <txid> in case the tx was made by some other device or 3rd party wallet."));
3591 m_cmd_binder.set_handler("check_tx_key",
3592 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_key, _1),
3593 tr(USAGE_CHECK_TX_KEY),
3594 tr("Check the amount going to <address> in <txid>."));
3595 m_cmd_binder.set_handler("get_tx_proof",
3596 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_proof, _1),
3597 tr(USAGE_GET_TX_PROOF),
3598 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."));
3599 m_cmd_binder.set_handler("check_tx_proof",
3600 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_tx_proof, _1),
3601 tr(USAGE_CHECK_TX_PROOF),
3602 tr("Check the proof for funds going to <address> in <txid> with the challenge string <message> if any."));
3603 m_cmd_binder.set_handler("get_spend_proof",
3604 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_spend_proof, _1),
3605 tr(USAGE_GET_SPEND_PROOF),
3606 tr("Generate a signature proving that you generated <txid> using the spend secret key, optionally with a challenge string <message>."));
3607 m_cmd_binder.set_handler("check_spend_proof",
3608 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_spend_proof, _1),
3609 tr(USAGE_CHECK_SPEND_PROOF),
3610 tr("Check a signature proving that the signer generated <txid>, optionally with a challenge string <message>."));
3611 m_cmd_binder.set_handler("get_reserve_proof",
3612 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_reserve_proof, _1),
3613 tr(USAGE_GET_RESERVE_PROOF),
3614 tr("Generate a signature proving that you own at least this much, optionally with a challenge string <message>.\n"
3615 "If 'all' is specified, you prove the entire sum of all of your existing accounts' balances.\n"
3616 "Otherwise, you prove the reserve of the smallest possible amount above <amount> available in your current account."));
3617 m_cmd_binder.set_handler("check_reserve_proof",
3618 boost::bind(&simple_wallet::on_command, this, &simple_wallet::check_reserve_proof, _1),
3619 tr(USAGE_CHECK_RESERVE_PROOF),
3620 tr("Check a signature proving that the owner of <address> holds at least this much, optionally with a challenge string <message>."));
3621 m_cmd_binder.set_handler("show_transfers",
3622 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfers, _1),
3623 tr(USAGE_SHOW_TRANSFERS),
3624 // Seemingly broken formatting to compensate for the backslash before the quotes.
3625 tr("Show the incoming/outgoing transfers within an optional height range.\n\n"
3626 "Output format:\n"
3627 "In or Coinbase: Block Number, \"block\"|\"in\", Time, Amount, Transaction Hash, Payment ID, Subaddress Index, \"-\", Note\n"
3628 "Out: Block Number, \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Destinations, Input addresses**, \"-\", Note\n"
3629 "Pool: \"pool\", \"in\", Time, Amount, Transaction Hash, Payment Id, Subaddress Index, \"-\", Note, Double Spend Note\n"
3630 "Pending or Failed: \"failed\"|\"pending\", \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Input addresses**, \"-\", Note\n\n"
3631 "* Excluding change and fee.\n"
3632 "** Set of address indices used as inputs in this transfer."));
3633 m_cmd_binder.set_handler("export_transfers",
3634 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_transfers, _1),
3635 tr("export_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<filepath>] [option=<with_keys>]"),
3636 tr("Export to CSV the incoming/outgoing transfers within an optional height range."));
3637 m_cmd_binder.set_handler("unspent_outputs",
3638 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unspent_outputs, _1),
3639 tr(USAGE_UNSPENT_OUTPUTS),
3640 tr("Show the unspent outputs of a specified address within an optional amount range."));
3641 m_cmd_binder.set_handler("rescan_bc",
3642 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rescan_blockchain, _1),
3643 tr(USAGE_RESCAN_BC),
3644 tr("Rescan the blockchain from scratch. If \"hard\" is specified, you will lose any information which can not be recovered from the blockchain itself."));
3645 m_cmd_binder.set_handler("set_tx_note",
3646 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_tx_note, _1),
3647 tr(USAGE_SET_TX_NOTE),
3648 tr("Set an arbitrary string note for a <txid>."));
3649 m_cmd_binder.set_handler("get_tx_note",
3650 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_tx_note, _1),
3651 tr(USAGE_GET_TX_NOTE),
3652 tr("Get a string note for a txid."));
3653 m_cmd_binder.set_handler("set_description",
3654 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_description, _1),
3655 tr(USAGE_SET_DESCRIPTION),
3656 tr("Set an arbitrary description for the wallet."));
3657 m_cmd_binder.set_handler("get_description",
3658 boost::bind(&simple_wallet::on_command, this, &simple_wallet::get_description, _1),
3659 tr(USAGE_GET_DESCRIPTION),
3660 tr("Get the description of the wallet."));
3661 m_cmd_binder.set_handler("status",
3662 boost::bind(&simple_wallet::on_command, this, &simple_wallet::status, _1),
3663 tr("Show the wallet's status."));
3664 m_cmd_binder.set_handler("wallet_info",
3665 boost::bind(&simple_wallet::on_command, this, &simple_wallet::wallet_info, _1),
3666 tr("Show the wallet's information."));
3667 m_cmd_binder.set_handler("sign",
3668 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign, _1),
3669 tr(USAGE_SIGN),
3670 tr("Sign the contents of a file with the given subaddress (or the main address if not specified)"));
3671 m_cmd_binder.set_handler("verify",
3672 boost::bind(&simple_wallet::on_command, this, &simple_wallet::verify, _1),
3673 tr(USAGE_VERIFY),
3674 tr("Verify a signature on the contents of a file."));
3675 m_cmd_binder.set_handler("export_key_images",
3676 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_key_images, _1),
3677 tr(USAGE_EXPORT_KEY_IMAGES),
3678 tr("Export a signed set of key images to a <filename>."));
3679 m_cmd_binder.set_handler("import_key_images",
3680 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_key_images, _1),
3681 tr(USAGE_IMPORT_KEY_IMAGES),
3682 tr("Import a signed key images list and verify their spent status."));
3683 m_cmd_binder.set_handler("hw_key_images_sync",
3684 boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_key_images_sync, _1),
3685 tr(USAGE_HW_KEY_IMAGES_SYNC),
3686 tr("Synchronizes key images with the hw wallet."));
3687 m_cmd_binder.set_handler("hw_reconnect",
3688 boost::bind(&simple_wallet::on_command, this, &simple_wallet::hw_reconnect, _1),
3689 tr(USAGE_HW_RECONNECT),
3690 tr("Attempts to reconnect HW wallet."));
3691 m_cmd_binder.set_handler("export_outputs",
3692 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_outputs, _1),
3693 tr(USAGE_EXPORT_OUTPUTS),
3694 tr("Export a set of outputs owned by this wallet."));
3695 m_cmd_binder.set_handler("import_outputs",
3696 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_outputs, _1),
3697 tr(USAGE_IMPORT_OUTPUTS),
3698 tr("Import a set of outputs owned by this wallet."));
3699 m_cmd_binder.set_handler("show_transfer",
3700 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_transfer, _1),
3701 tr(USAGE_SHOW_TRANSFER),
3702 tr("Show information about a transfer to/from this address."));
3703 m_cmd_binder.set_handler("password",
3704 boost::bind(&simple_wallet::on_command, this, &simple_wallet::change_password, _1),
3705 tr("Change the wallet's password."));
3706 m_cmd_binder.set_handler("payment_id",
3707 boost::bind(&simple_wallet::on_command, this, &simple_wallet::payment_id, _1),
3708 tr(USAGE_PAYMENT_ID),
3709 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."));
3710 m_cmd_binder.set_handler("fee",
3711 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_fee_info, _1),
3712 tr("Print the information about the current fee and transaction backlog."));
3713 m_cmd_binder.set_handler("prepare_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::prepare_multisig, _1),
3714 tr("Export data needed to create a multisig wallet"));
3715 m_cmd_binder.set_handler("make_multisig", boost::bind(&simple_wallet::on_command, this, &simple_wallet::make_multisig, _1),
3716 tr(USAGE_MAKE_MULTISIG),
3717 tr("Turn this wallet into a multisig wallet"));
3718 m_cmd_binder.set_handler("exchange_multisig_keys",
3719 boost::bind(&simple_wallet::on_command, this, &simple_wallet::exchange_multisig_keys, _1),
3720 tr(USAGE_EXCHANGE_MULTISIG_KEYS),
3721 tr("Performs extra multisig keys exchange rounds. Needed for arbitrary M/N multisig wallets"));
3722 m_cmd_binder.set_handler("export_multisig_info",
3723 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_multisig, _1),
3724 tr(USAGE_EXPORT_MULTISIG_INFO),
3725 tr("Export multisig info for other participants"));
3726 m_cmd_binder.set_handler("import_multisig_info",
3727 boost::bind(&simple_wallet::on_command, this, &simple_wallet::import_multisig, _1),
3728 tr(USAGE_IMPORT_MULTISIG_INFO),
3729 tr("Import multisig info from other participants"));
3730 m_cmd_binder.set_handler("sign_multisig",
3731 boost::bind(&simple_wallet::on_command, this, &simple_wallet::sign_multisig, _1),
3732 tr(USAGE_SIGN_MULTISIG),
3733 tr("Sign a multisig transaction from a file"));
3734 m_cmd_binder.set_handler("submit_multisig",
3735 boost::bind(&simple_wallet::on_command, this, &simple_wallet::submit_multisig, _1),
3736 tr(USAGE_SUBMIT_MULTISIG),
3737 tr("Submit a signed multisig transaction from a file"));
3738 m_cmd_binder.set_handler("export_raw_multisig_tx",
3739 boost::bind(&simple_wallet::on_command, this, &simple_wallet::export_raw_multisig, _1),
3740 tr(USAGE_EXPORT_RAW_MULTISIG_TX),
3741 tr("Export a signed multisig transaction to a file"));
3742 m_cmd_binder.set_handler("mms",
3743 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3744 tr(USAGE_MMS),
3745 tr("Interface with the MMS (Multisig Messaging System)\n"
3746 "<subcommand> is one of:\n"
3747 " init, info, signer, list, next, sync, transfer, delete, send, receive, export, note, show, set, help\n"
3748 " send_signer_config, start_auto_config, stop_auto_config, auto_config, config_checksum\n"
3749 "Get help about a subcommand with: help mms <subcommand>, or help mms <subcommand>"));
3750 m_cmd_binder.set_handler("mms init",
3751 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3752 tr(USAGE_MMS_INIT),
3753 tr("Initialize and configure the MMS for M/N = number of required signers/number of authorized signers multisig"));
3754 m_cmd_binder.set_handler("mms info",
3755 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3756 tr(USAGE_MMS_INFO),
3757 tr("Display current MMS configuration"));
3758 m_cmd_binder.set_handler("mms signer",
3759 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3760 tr(USAGE_MMS_SIGNER),
3761 tr("Set or modify authorized signer info (single-word label, transport address, Monero address), or list all signers"));
3762 m_cmd_binder.set_handler("mms list",
3763 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3764 tr(USAGE_MMS_LIST),
3765 tr("List all messages"));
3766 m_cmd_binder.set_handler("mms next",
3767 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3768 tr(USAGE_MMS_NEXT),
3769 tr("Evaluate the next possible multisig-related action(s) according to wallet state, and execute or offer for choice\n"
3770 "By using 'sync' processing of waiting messages with multisig sync info can be forced regardless of wallet state"));
3771 m_cmd_binder.set_handler("mms sync",
3772 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3773 tr(USAGE_MMS_SYNC),
3774 tr("Force generation of multisig sync info regardless of wallet state, to recover from special situations like \"stale data\" errors"));
3775 m_cmd_binder.set_handler("mms transfer",
3776 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3777 tr(USAGE_MMS_TRANSFER),
3778 tr("Initiate transfer with MMS support; arguments identical to normal 'transfer' command arguments, for info see there"));
3779 m_cmd_binder.set_handler("mms delete",
3780 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3781 tr(USAGE_MMS_DELETE),
3782 tr("Delete a single message by giving its id, or delete all messages by using 'all'"));
3783 m_cmd_binder.set_handler("mms send",
3784 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3785 tr(USAGE_MMS_SEND),
3786 tr("Send a single message by giving its id, or send all waiting messages"));
3787 m_cmd_binder.set_handler("mms receive",
3788 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3789 tr(USAGE_MMS_RECEIVE),
3790 tr("Check right away for new messages to receive"));
3791 m_cmd_binder.set_handler("mms export",
3792 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3793 tr(USAGE_MMS_EXPORT),
3794 tr("Write the content of a message to a file \"mms_message_content\""));
3795 m_cmd_binder.set_handler("mms note",
3796 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3797 tr(USAGE_MMS_NOTE),
3798 tr("Send a one-line message to an authorized signer, identified by its label, or show any waiting unread notes"));
3799 m_cmd_binder.set_handler("mms show",
3800 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3801 tr(USAGE_MMS_SHOW),
3802 tr("Show detailed info about a single message"));
3803 m_cmd_binder.set_handler("mms set",
3804 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3805 tr(USAGE_MMS_SET),
3806 tr("Available options:\n "
3807 "auto-send <1|0>\n "
3808 " Whether to automatically send newly generated messages right away.\n "));
3809 m_cmd_binder.set_handler("mms send_signer_config",
3810 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3811 tr(USAGE_MMS_SEND_SIGNER_CONFIG),
3812 tr("Send completed signer config to all other authorized signers"));
3813 m_cmd_binder.set_handler("mms start_auto_config",
3814 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3815 tr(USAGE_MMS_START_AUTO_CONFIG),
3816 tr("Start auto-config at the auto-config manager's wallet by issuing auto-config tokens and optionally set others' labels"));
3817 m_cmd_binder.set_handler("mms config_checksum",
3818 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3819 tr(USAGE_MMS_CONFIG_CHECKSUM),
3820 tr("Get a checksum that allows signers to easily check for identical MMS configuration"));
3821 m_cmd_binder.set_handler("mms stop_auto_config",
3822 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3823 tr(USAGE_MMS_STOP_AUTO_CONFIG),
3824 tr("Delete any auto-config tokens and abort a auto-config process"));
3825 m_cmd_binder.set_handler("mms auto_config",
3826 boost::bind(&simple_wallet::on_command, this, &simple_wallet::mms, _1),
3827 tr(USAGE_MMS_AUTO_CONFIG),
3828 tr("Start auto-config by using the token received from the auto-config manager"));
3829 m_cmd_binder.set_handler("print_ring",
3830 boost::bind(&simple_wallet::on_command, this, &simple_wallet::print_ring, _1),
3831 tr(USAGE_PRINT_RING),
3832 tr("Print the ring(s) used to spend a given key image or transaction (if the ring size is > 1)\n\n"
3833 "Output format:\n"
3834 "Key Image, \"absolute\", list of rings"));
3835 m_cmd_binder.set_handler("set_ring",
3836 boost::bind(&simple_wallet::on_command, this, &simple_wallet::set_ring, _1),
3837 tr(USAGE_SET_RING),
3838 tr("Set the ring used for a given key image, so it can be reused in a fork"));
3839 m_cmd_binder.set_handler("unset_ring",
3840 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unset_ring, _1),
3841 tr(USAGE_UNSET_RING),
3842 tr("Unsets the ring used for a given key image or transaction"));
3843 m_cmd_binder.set_handler("save_known_rings",
3844 boost::bind(&simple_wallet::on_command, this, &simple_wallet::save_known_rings, _1),
3845 tr(USAGE_SAVE_KNOWN_RINGS),
3846 tr("Save known rings to the shared rings database"));
3847 m_cmd_binder.set_handler("mark_output_spent",
3848 boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackball, _1),
3849 tr(USAGE_MARK_OUTPUT_SPENT),
3850 tr("Mark output(s) as spent so they never get selected as fake outputs in a ring"));
3851 m_cmd_binder.set_handler("mark_output_unspent",
3852 boost::bind(&simple_wallet::on_command, this, &simple_wallet::unblackball, _1),
3853 tr(USAGE_MARK_OUTPUT_UNSPENT),
3854 tr("Marks an output as unspent so it may get selected as a fake output in a ring"));
3855 m_cmd_binder.set_handler("is_output_spent",
3856 boost::bind(&simple_wallet::on_command, this, &simple_wallet::blackballed, _1),
3857 tr(USAGE_IS_OUTPUT_SPENT),
3858 tr("Checks whether an output is marked as spent"));
3859 m_cmd_binder.set_handler("freeze",
3860 boost::bind(&simple_wallet::on_command, this, &simple_wallet::freeze, _1),
3861 tr(USAGE_FREEZE),
3862 tr("Freeze a single output by key image so it will not be used"));
3863 m_cmd_binder.set_handler("thaw",
3864 boost::bind(&simple_wallet::on_command, this, &simple_wallet::thaw, _1),
3865 tr(USAGE_THAW),
3866 tr("Thaw a single output by key image so it may be used again"));
3867 m_cmd_binder.set_handler("frozen",
3868 boost::bind(&simple_wallet::on_command, this, &simple_wallet::frozen, _1),
3869 tr(USAGE_FROZEN),
3870 tr("Checks whether a given output is currently frozen by key image"));
3871 m_cmd_binder.set_handler("lock",
3872 boost::bind(&simple_wallet::on_command, this, &simple_wallet::lock, _1),
3873 tr(USAGE_LOCK),
3874 tr("Lock the wallet console, requiring the wallet password to continue"));
3875 m_cmd_binder.set_handler("net_stats",
3876 boost::bind(&simple_wallet::on_command, this, &simple_wallet::net_stats, _1),
3877 tr(USAGE_NET_STATS),
3878 tr("Prints simple network stats"));
3879 m_cmd_binder.set_handler("public_nodes",
3880 boost::bind(&simple_wallet::on_command, this, &simple_wallet::public_nodes, _1),
3881 tr(USAGE_PUBLIC_NODES),
3882 tr("Lists known public nodes"));
3883 m_cmd_binder.set_handler("welcome",
3884 boost::bind(&simple_wallet::on_command, this, &simple_wallet::welcome, _1),
3885 tr(USAGE_WELCOME),
3886 tr("Prints basic info about Monero for first time users"));
3887 m_cmd_binder.set_handler("version",
3888 boost::bind(&simple_wallet::on_command, this, &simple_wallet::version, _1),
3889 tr(USAGE_VERSION),
3890 tr("Returns version information"));
3891 m_cmd_binder.set_handler("rpc_payment_info",
3892 boost::bind(&simple_wallet::on_command, this, &simple_wallet::rpc_payment_info, _1),
3893 tr(USAGE_RPC_PAYMENT_INFO),
3894 tr("Get info about RPC payments to current node"));
3895 m_cmd_binder.set_handler("start_mining_for_rpc",
3896 boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining_for_rpc, _1),
3897 tr(USAGE_START_MINING_FOR_RPC),
3898 tr("Start mining to pay for RPC access"));
3899 m_cmd_binder.set_handler("stop_mining_for_rpc",
3900 boost::bind(&simple_wallet::on_command, this, &simple_wallet::stop_mining_for_rpc, _1),
3901 tr(USAGE_STOP_MINING_FOR_RPC),
3902 tr("Stop mining to pay for RPC access"));
3903 m_cmd_binder.set_handler("show_qr_code",
3904 boost::bind(&simple_wallet::on_command, this, &simple_wallet::show_qr_code, _1),
3905 tr(USAGE_SHOW_QR_CODE),
3906 tr("Show address as QR code"));
3907 m_cmd_binder.set_handler("help",
3908 boost::bind(&simple_wallet::on_command, this, &simple_wallet::help, _1),
3909 tr(USAGE_HELP),
3910 tr("Show the help section or the documentation about a <command>."));
3911 m_cmd_binder.set_handler("apropos",
3912 boost::bind(&simple_wallet::on_command, this, &simple_wallet::apropos, _1),
3913 tr(USAGE_APROPOS),
3914 tr("Search all command descriptions for keyword(s)"));
3915 m_cmd_binder.set_handler("scan_tx",
3916 boost::bind(&simple_wallet::on_command, this, &simple_wallet::scan_tx, _1),
3917 tr(USAGE_SCAN_TX),
3918 tr("Scan the transactions given by <txid>(s), processing them and looking for outputs"));
3919 m_cmd_binder.set_unknown_command_handler(boost::bind(&simple_wallet::on_command, this, &simple_wallet::on_unknown_command, _1));
3920 m_cmd_binder.set_empty_command_handler(boost::bind(&simple_wallet::on_empty_command, this));
3921 m_cmd_binder.set_cancel_handler(boost::bind(&simple_wallet::on_cancelled_command, this));
3922 }
3923 //----------------------------------------------------------------------------------------------------
3924 bool simple_wallet::set_variable(const std::vector<std::string> &args)
3925 {
3926 if (args.empty())
3927 {
3928 std::string seed_language = m_wallet->get_seed_language();
3929 if (m_use_english_language_names)
3930 seed_language = crypto::ElectrumWords::get_english_name_for(seed_language);
3931 std::string priority_string = "invalid";
3932 uint32_t priority = m_wallet->get_default_priority();
3933 if (priority < allowed_priority_strings.size())
3934 priority_string = allowed_priority_strings[priority];
3935 std::string ask_password_string = "invalid";
3936 switch (m_wallet->ask_password())
3937 {
3938 case tools::wallet2::AskPasswordNever: ask_password_string = "never"; break;
3939 case tools::wallet2::AskPasswordOnAction: ask_password_string = "action"; break;
3940 case tools::wallet2::AskPasswordToDecrypt: ask_password_string = "decrypt"; break;
3941 }
3942 std::string setup_background_mining_string = "invalid";
3943 switch (m_wallet->setup_background_mining())
3944 {
3945 case tools::wallet2::BackgroundMiningMaybe: setup_background_mining_string = "maybe"; break;
3946 case tools::wallet2::BackgroundMiningYes: setup_background_mining_string = "yes"; break;
3947 case tools::wallet2::BackgroundMiningNo: setup_background_mining_string = "no"; break;
3948 }
3949 success_msg_writer() << "seed = " << seed_language;
3950 success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers();
3951 success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members();
3952 success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info();
3953 success_msg_writer() << "default-ring-size = " << (m_wallet->default_mixin() ? m_wallet->default_mixin() + 1 : 0);
3954 success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh();
3955 success_msg_writer() << "refresh-type = " << get_refresh_type_name(m_wallet->get_refresh_type());
3956 success_msg_writer() << "priority = " << priority<< " (" << priority_string << ")";
3957 success_msg_writer() << "ask-password = " << m_wallet->ask_password() << " (" << ask_password_string << ")";
3958 success_msg_writer() << "unit = " << cryptonote::get_unit(cryptonote::get_default_decimal_point());
3959 success_msg_writer() << "max-reorg-depth = " << m_wallet->max_reorg_depth();
3960 success_msg_writer() << "min-outputs-count = " << m_wallet->get_min_output_count();
3961 success_msg_writer() << "min-outputs-value = " << cryptonote::print_money(m_wallet->get_min_output_value());
3962 success_msg_writer() << "merge-destinations = " << m_wallet->merge_destinations();
3963 success_msg_writer() << "confirm-backlog = " << m_wallet->confirm_backlog();
3964 success_msg_writer() << "confirm-backlog-threshold = " << m_wallet->get_confirm_backlog_threshold();
3965 success_msg_writer() << "confirm-export-overwrite = " << m_wallet->confirm_export_overwrite();
3966 success_msg_writer() << "refresh-from-block-height = " << m_wallet->get_refresh_from_block_height();
3967 success_msg_writer() << "auto-low-priority = " << m_wallet->auto_low_priority();
3968 success_msg_writer() << "segregate-pre-fork-outputs = " << m_wallet->segregate_pre_fork_outputs();
3969 success_msg_writer() << "key-reuse-mitigation2 = " << m_wallet->key_reuse_mitigation2();
3970 const std::pair<size_t, size_t> lookahead = m_wallet->get_subaddress_lookahead();
3971 success_msg_writer() << "subaddress-lookahead = " << lookahead.first << ":" << lookahead.second;
3972 success_msg_writer() << "segregation-height = " << m_wallet->segregation_height();
3973 success_msg_writer() << "ignore-fractional-outputs = " << m_wallet->ignore_fractional_outputs();
3974 success_msg_writer() << "ignore-outputs-above = " << cryptonote::print_money(m_wallet->ignore_outputs_above());
3975 success_msg_writer() << "ignore-outputs-below = " << cryptonote::print_money(m_wallet->ignore_outputs_below());
3976 success_msg_writer() << "track-uses = " << m_wallet->track_uses();
3977 success_msg_writer() << "background-sync = " << get_background_sync_type_name(m_wallet->background_sync_type());
3978 success_msg_writer() << "setup-background-mining = " << setup_background_mining_string;
3979 success_msg_writer() << "device-name = " << m_wallet->device_name();
3980 success_msg_writer() << "export-format = " << (m_wallet->export_format() == tools::wallet2::ExportFormat::Ascii ? "ascii" : "binary");
3981 success_msg_writer() << "show-wallet-name-when-locked = " << m_wallet->show_wallet_name_when_locked();
3982 success_msg_writer() << "inactivity-lock-timeout = " << m_wallet->inactivity_lock_timeout()
3983 #ifdef _WIN32
3984 << " (disabled on Windows)"
3985 #endif
3986 ;
3987 success_msg_writer() << "persistent-rpc-client-id = " << m_wallet->persistent_rpc_client_id();
3988 success_msg_writer() << "auto-mine-for-rpc-payment-threshold = " << m_wallet->auto_mine_for_rpc_payment_threshold();
3989 success_msg_writer() << "credits-target = " << m_wallet->credits_target();
3990 success_msg_writer() << "load-deprecated-formats = " << m_wallet->load_deprecated_formats();
3991 success_msg_writer() << "enable-multisig-experimental = " << m_wallet->is_multisig_enabled();
3992 return true;
3993 }
3994 else
3995 {
3996 CHECK_IF_BACKGROUND_SYNCING("cannot change wallet settings");
3997
3998 #define CHECK_SIMPLE_VARIABLE(name, f, help) do \
3999 if (args[0] == name) { \
4000 if (args.size() <= 1) \
4001 { \
4002 fail_msg_writer() << "set " << #name << ": " << tr("needs an argument") << " (" << help << ")"; \
4003 return true; \
4004 } \
4005 else \
4006 { \
4007 f(args); \
4008 return true; \
4009 } \
4010 } while(0)
4011
4012 if (args[0] == "seed")
4013 {
4014 if (args.size() == 1)
4015 {
4016 fail_msg_writer() << tr("set seed: needs an argument. available options: language");
4017 return true;
4018 }
4019 else if (args[1] == "language")
4020 {
4021 seed_set_language(args);
4022 return true;
4023 }
4024 }
4025 CHECK_SIMPLE_VARIABLE("always-confirm-transfers", set_always_confirm_transfers, tr("0 or 1"));
4026 CHECK_SIMPLE_VARIABLE("print-ring-members", set_print_ring_members, tr("0 or 1"));
4027 CHECK_SIMPLE_VARIABLE("store-tx-info", set_store_tx_info, tr("0 or 1"));
4028 CHECK_SIMPLE_VARIABLE("auto-refresh", set_auto_refresh, tr("0 or 1"));
4029 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)"));
4030 CHECK_SIMPLE_VARIABLE("priority", set_default_priority, tr("0, 1, 2, 3, or 4, or one of ") << join_priority_strings(", "));
4031 CHECK_SIMPLE_VARIABLE("ask-password", set_ask_password, tr("0|1|2 (or never|action|decrypt)"));
4032 CHECK_SIMPLE_VARIABLE("unit", set_unit, tr("monero, millinero, micronero, nanonero, piconero"));
4033 CHECK_SIMPLE_VARIABLE("max-reorg-depth", set_max_reorg_depth, tr("unsigned integer"));
4034 CHECK_SIMPLE_VARIABLE("min-outputs-count", set_min_output_count, tr("unsigned integer"));
4035 CHECK_SIMPLE_VARIABLE("min-outputs-value", set_min_output_value, tr("amount"));
4036 CHECK_SIMPLE_VARIABLE("merge-destinations", set_merge_destinations, tr("0 or 1"));
4037 CHECK_SIMPLE_VARIABLE("confirm-backlog", set_confirm_backlog, tr("0 or 1"));
4038 CHECK_SIMPLE_VARIABLE("confirm-backlog-threshold", set_confirm_backlog_threshold, tr("unsigned integer"));
4039 CHECK_SIMPLE_VARIABLE("confirm-export-overwrite", set_confirm_export_overwrite, tr("0 or 1"));
4040 CHECK_SIMPLE_VARIABLE("refresh-from-block-height", set_refresh_from_block_height, tr("block height"));
4041 CHECK_SIMPLE_VARIABLE("auto-low-priority", set_auto_low_priority, tr("0 or 1"));
4042 CHECK_SIMPLE_VARIABLE("segregate-pre-fork-outputs", set_segregate_pre_fork_outputs, tr("0 or 1"));
4043 CHECK_SIMPLE_VARIABLE("key-reuse-mitigation2", set_key_reuse_mitigation2, tr("0 or 1"));
4044 CHECK_SIMPLE_VARIABLE("subaddress-lookahead", set_subaddress_lookahead, tr("<major>:<minor>"));
4045 CHECK_SIMPLE_VARIABLE("segregation-height", set_segregation_height, tr("unsigned integer"));
4046 CHECK_SIMPLE_VARIABLE("ignore-fractional-outputs", set_ignore_fractional_outputs, tr("0 or 1"));
4047 CHECK_SIMPLE_VARIABLE("ignore-outputs-above", set_ignore_outputs_above, tr("amount"));
4048 CHECK_SIMPLE_VARIABLE("ignore-outputs-below", set_ignore_outputs_below, tr("amount"));
4049 CHECK_SIMPLE_VARIABLE("track-uses", set_track_uses, tr("0 or 1"));
4050 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)"));
4051 CHECK_SIMPLE_VARIABLE("show-wallet-name-when-locked", set_show_wallet_name_when_locked, tr("1 or 0"));
4052 CHECK_SIMPLE_VARIABLE("inactivity-lock-timeout", set_inactivity_lock_timeout, tr("unsigned integer (seconds, 0 to disable)"));
4053 CHECK_SIMPLE_VARIABLE("setup-background-mining", set_setup_background_mining, tr("1/yes or 0/no"));
4054 CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("<device_name[:device_spec]>"));
4055 CHECK_SIMPLE_VARIABLE("export-format", set_export_format, tr("\"binary\" or \"ascii\""));
4056 CHECK_SIMPLE_VARIABLE("load-deprecated-formats", set_load_deprecated_formats, tr("0 or 1"));
4057 CHECK_SIMPLE_VARIABLE("persistent-rpc-client-id", set_persistent_rpc_client_id, tr("0 or 1"));
4058 CHECK_SIMPLE_VARIABLE("auto-mine-for-rpc-payment-threshold", set_auto_mine_for_rpc_payment_threshold, tr("floating point >= 0"));
4059 CHECK_SIMPLE_VARIABLE("credits-target", set_credits_target, tr("unsigned integer"));
4060 CHECK_SIMPLE_VARIABLE("enable-multisig-experimental", set_enable_multisig, tr("0 or 1"));
4061 }
4062 fail_msg_writer() << tr("set: unrecognized argument(s)");
4063 return true;
4064 }
4065
4066 //----------------------------------------------------------------------------------------------------
4067 bool simple_wallet::set_log(const std::vector<std::string> &args)
4068 {
4069 if(args.size() > 1)
4070 {
4071 PRINT_USAGE(USAGE_SET_LOG);
4072 return true;
4073 }
4074 if(!args.empty())
4075 {
4076 uint16_t level = 0;
4077 if(epee::string_tools::get_xtype_from_string(level, args[0]))
4078 {
4079 if(4 < level)
4080 {
4081 fail_msg_writer() << boost::format(tr("wrong number range, use: %s")) % USAGE_SET_LOG;
4082 return true;
4083 }
4084 mlog_set_log_level(level);
4085 }
4086 else
4087 {
4088 mlog_set_log(args[0].c_str());
4089 }
4090 }
4091
4092 success_msg_writer() << "New log categories: " << mlog_get_categories();
4093 return true;
4094 }
4095 //----------------------------------------------------------------------------------------------------
4096 bool simple_wallet::ask_wallet_create_if_needed()
4097 {
4098 LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started");
4099 std::string wallet_path;
4100 std::string confirm_creation;
4101 bool wallet_name_valid = false;
4102 bool keys_file_exists;
4103 bool wallet_file_exists;
4104
4105 do{
4106 LOG_PRINT_L3("User asked to specify wallet file name.");
4107 wallet_path = input_line(
4108 tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n"
4109 "Wallet file name (or Ctrl-C to quit)" :
4110 "Specify wallet file name (e.g., MyWallet). If the wallet doesn't exist, it will be created.\n"
4111 "Wallet file name (or Ctrl-C to quit)")
4112 );
4113 if(std::cin.eof())
4114 {
4115 LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
4116 return false;
4117 }
4118 if(!tools::wallet2::wallet_valid_path_format(wallet_path))
4119 {
4120 fail_msg_writer() << tr("Wallet name not valid. Please try again or use Ctrl-C to quit.");
4121 wallet_name_valid = false;
4122 }
4123 else
4124 {
4125 tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists);
4126 LOG_PRINT_L3("wallet_path: " << wallet_path << "");
4127 LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
4128 << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
4129
4130 if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring))
4131 {
4132 fail_msg_writer() << tr("Attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting.");
4133 return false;
4134 }
4135 if(wallet_file_exists && keys_file_exists) //Yes wallet, yes keys
4136 {
4137 success_msg_writer() << tr("Wallet and key files found, loading...");
4138 m_wallet_file = wallet_path;
4139 return true;
4140 }
4141 else if(!wallet_file_exists && keys_file_exists) //No wallet, yes keys
4142 {
4143 success_msg_writer() << tr("Key file found but not wallet file. Regenerating...");
4144 m_wallet_file = wallet_path;
4145 return true;
4146 }
4147 else if(wallet_file_exists && !keys_file_exists) //Yes wallet, no keys
4148 {
4149 fail_msg_writer() << tr("Key file not found. Failed to open wallet: ") << "\"" << wallet_path << "\". Exiting.";
4150 return false;
4151 }
4152 else if(!wallet_file_exists && !keys_file_exists) //No wallet, no keys
4153 {
4154 bool ok = true;
4155 if (!m_restoring)
4156 {
4157 message_writer() << tr("No wallet found with that name. Confirm creation of new wallet named: ") << wallet_path;
4158 confirm_creation = input_line("", true);
4159 if(std::cin.eof())
4160 {
4161 LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
4162 return false;
4163 }
4164 ok = command_line::is_yes(confirm_creation);
4165 }
4166 if (ok)
4167 {
4168 success_msg_writer() << tr("Generating new wallet...");
4169 m_generate_new = wallet_path;
4170 return true;
4171 }
4172 }
4173 }
4174 } while(!wallet_name_valid);
4175
4176 LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()");
4177 return false;
4178 }
4179
4180 /*!
4181 * \brief Prints the seed with a nice message
4182 * \param seed seed to print
4183 */
4184 void simple_wallet::print_seed(const epee::wipeable_string &seed)
4185 {
4186 success_msg_writer(true) << "\n" << boost::format(tr("NOTE: the following %s can be used to recover access to your wallet. "
4187 "Write them down and store them somewhere safe and secure. Please do not store them in "
4188 "your email or on file storage services outside of your immediate control.\n")) % (m_wallet->multisig() ? tr("string") : tr("25 words"));
4189 // don't log
4190 int space_index = 0;
4191 size_t len = seed.size();
4192 for (const char *ptr = seed.data(); len--; ++ptr)
4193 {
4194 if (*ptr == ' ')
4195 {
4196 if (space_index == 15 || space_index == 7)
4197 putchar('\n');
4198 else
4199 putchar(*ptr);
4200 ++space_index;
4201 }
4202 else
4203 putchar(*ptr);
4204 }
4205 putchar('\n');
4206 fflush(stdout);
4207 }
4208 //----------------------------------------------------------------------------------------------------
4209 static bool might_be_partial_seed(const epee::wipeable_string &words)
4210 {
4211 std::vector<epee::wipeable_string> seed;
4212
4213 words.split(seed);
4214 return seed.size() < 24;
4215 }
4216 //----------------------------------------------------------------------------------------------------
4217 static bool datestr_to_int(const std::string &heightstr, uint16_t &year, uint8_t &month, uint8_t &day)
4218 {
4219 if (heightstr.size() != 10 || heightstr[4] != '-' || heightstr[7] != '-')
4220 {
4221 fail_msg_writer() << tr("date format must be YYYY-MM-DD");
4222 return false;
4223 }
4224 try
4225 {
4226 year = boost::lexical_cast<uint16_t>(heightstr.substr(0,4));
4227 // lexical_cast<uint8_t> won't work because uint8_t is treated as character type
4228 month = boost::lexical_cast<uint16_t>(heightstr.substr(5,2));
4229 day = boost::lexical_cast<uint16_t>(heightstr.substr(8,2));
4230 }
4231 catch (const boost::bad_lexical_cast &)
4232 {
4233 fail_msg_writer() << tr("bad height parameter: ") << heightstr;
4234 return false;
4235 }
4236 return true;
4237 }
4238 //----------------------------------------------------------------------------------------------------
4239 bool simple_wallet::init(const boost::program_options::variables_map& vm)
4240 {
4241 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
4242 m_electrum_seed.wipe();
4243 });
4244
4245 const bool testnet = tools::wallet2::has_testnet_option(vm);
4246 const bool stagenet = tools::wallet2::has_stagenet_option(vm);
4247 if (testnet && stagenet)
4248 {
4249 fail_msg_writer() << tr("Can't specify more than one of --testnet and --stagenet");
4250 return false;
4251 }
4252 const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET;
4253
4254 epee::wipeable_string multisig_keys;
4255 epee::wipeable_string password;
4256 epee::wipeable_string seed_pass;
4257
4258 if (!handle_command_line(vm))
4259 return false;
4260
4261 bool welcome = false;
4262
4263 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)
4264 {
4265 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\"");
4266 return false;
4267 }
4268 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())
4269 {
4270 if(!ask_wallet_create_if_needed()) return false;
4271 }
4272
4273 bool enable_multisig = false;
4274 if (m_restore_multisig_wallet) {
4275 fail_msg_writer() << tr("Multisig is disabled.");
4276 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.");
4277 if (!command_line::is_yes(input_line("Do you want to continue restoring a multisig wallet?", true))) {
4278 message_writer() << tr("You have canceled restoring a multisig wallet.");
4279 return false;
4280 }
4281 enable_multisig = true;
4282 }
4283
4284 if (!m_generate_new.empty() || m_restoring)
4285 {
4286 if (!m_subaddress_lookahead.empty() && !parse_subaddress_lookahead(m_subaddress_lookahead))
4287 return false;
4288
4289 std::string old_language;
4290 // check for recover flag. if present, require electrum word list (only recovery option for now).
4291 if (m_restore_deterministic_wallet || m_restore_multisig_wallet)
4292 {
4293 if (m_non_deterministic)
4294 {
4295 fail_msg_writer() << tr("can't specify both --restore-deterministic-wallet or --restore-multisig-wallet and --non-deterministic");
4296 return false;
4297 }
4298 if (!m_wallet_file.empty())
4299 {
4300 if (m_restore_multisig_wallet)
4301 fail_msg_writer() << tr("--restore-multisig-wallet uses --generate-new-wallet, not --wallet-file");
4302 else
4303 fail_msg_writer() << tr("--restore-deterministic-wallet uses --generate-new-wallet, not --wallet-file");
4304 return false;
4305 }
4306
4307 if (m_electrum_seed.empty())
4308 {
4309 if (m_restore_multisig_wallet)
4310 {
4311 const char *prompt = "Specify multisig seed";
4312 m_electrum_seed = input_secure_line(prompt);
4313 if (std::cin.eof())
4314 return false;
4315 if (m_electrum_seed.empty())
4316 {
4317 fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"multisig seed here\"");
4318 return false;
4319 }
4320 }
4321 else
4322 {
4323 m_electrum_seed = "";
4324 do
4325 {
4326 const char *prompt = m_electrum_seed.empty() ? "Specify Electrum seed" : "Electrum seed continued";
4327 epee::wipeable_string electrum_seed = input_secure_line(prompt);
4328 if (std::cin.eof())
4329 return false;
4330 if (electrum_seed.empty())
4331 {
4332 fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"words list here\"");
4333 return false;
4334 }
4335 m_electrum_seed += electrum_seed;
4336 m_electrum_seed += ' ';
4337 } while (might_be_partial_seed(m_electrum_seed));
4338 }
4339 }
4340
4341 if (m_restore_multisig_wallet)
4342 {
4343 const boost::optional<epee::wipeable_string> parsed = m_electrum_seed.parse_hexstr();
4344 if (!parsed)
4345 {
4346 fail_msg_writer() << tr("Multisig seed failed verification");
4347 return false;
4348 }
4349 multisig_keys = *parsed;
4350 }
4351 else
4352 {
4353 if (!crypto::ElectrumWords::words_to_bytes(m_electrum_seed, m_recovery_key, old_language))
4354 {
4355 fail_msg_writer() << tr("Electrum-style word list failed verification");
4356 return false;
4357 }
4358 }
4359
4360 auto pwd_container = password_prompter(tr("Enter seed offset passphrase, empty if none"), false);
4361 if (std::cin.eof() || !pwd_container)
4362 return false;
4363 seed_pass = pwd_container->password();
4364 if (!seed_pass.empty() && !m_restore_multisig_wallet)
4365 m_recovery_key = cryptonote::decrypt_key(m_recovery_key, seed_pass);
4366 }
4367 if (!m_generate_from_view_key.empty())
4368 {
4369 m_wallet_file = m_generate_from_view_key;
4370 // parse address
4371 std::string address_string = input_line("Standard address");
4372 if (std::cin.eof())
4373 return false;
4374 if (address_string.empty()) {
4375 fail_msg_writer() << tr("No data supplied, cancelled");
4376 return false;
4377 }
4378 cryptonote::address_parse_info info;
4379 if(!get_account_address_from_str(info, nettype, address_string))
4380 {
4381 fail_msg_writer() << tr("failed to parse address");
4382 return false;
4383 }
4384 if (info.is_subaddress)
4385 {
4386 fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
4387 return false;
4388 }
4389
4390 // parse view secret key
4391 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4392 if (std::cin.eof())
4393 return false;
4394 if (viewkey_string.empty()) {
4395 fail_msg_writer() << tr("No data supplied, cancelled");
4396 return false;
4397 }
4398 crypto::secret_key viewkey;
4399 if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4400 {
4401 fail_msg_writer() << tr("failed to parse view key secret key");
4402 return false;
4403 }
4404
4405 m_wallet_file=m_generate_from_view_key;
4406
4407 // check the view key matches the given address
4408 crypto::public_key pkey;
4409 if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
4410 fail_msg_writer() << tr("failed to verify view key secret key");
4411 return false;
4412 }
4413 if (info.address.m_view_public_key != pkey) {
4414 fail_msg_writer() << tr("view key does not match standard address");
4415 return false;
4416 }
4417
4418 auto r = new_wallet(vm, info.address, boost::none, viewkey);
4419 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4420 password = *r;
4421 welcome = true;
4422 }
4423 else if (!m_generate_from_spend_key.empty())
4424 {
4425 m_wallet_file = m_generate_from_spend_key;
4426 // parse spend secret key
4427 epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
4428 if (std::cin.eof())
4429 return false;
4430 if (spendkey_string.empty()) {
4431 fail_msg_writer() << tr("No data supplied, cancelled");
4432 return false;
4433 }
4434 if (!spendkey_string.hex_to_pod(unwrap(unwrap(m_recovery_key))))
4435 {
4436 fail_msg_writer() << tr("failed to parse spend key secret key");
4437 return false;
4438 }
4439 auto r = new_wallet(vm, m_recovery_key, true, false, "");
4440 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4441 password = *r;
4442 welcome = true;
4443 }
4444 else if (!m_generate_from_keys.empty())
4445 {
4446 m_wallet_file = m_generate_from_keys;
4447 // parse address
4448 std::string address_string = input_line("Standard address");
4449 if (std::cin.eof())
4450 return false;
4451 if (address_string.empty()) {
4452 fail_msg_writer() << tr("No data supplied, cancelled");
4453 return false;
4454 }
4455 cryptonote::address_parse_info info;
4456 if(!get_account_address_from_str(info, nettype, address_string))
4457 {
4458 fail_msg_writer() << tr("failed to parse address");
4459 return false;
4460 }
4461 if (info.is_subaddress)
4462 {
4463 fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
4464 return false;
4465 }
4466
4467 // parse spend secret key
4468 epee::wipeable_string spendkey_string = input_secure_line("Secret spend key");
4469 if (std::cin.eof())
4470 return false;
4471 if (spendkey_string.empty()) {
4472 fail_msg_writer() << tr("No data supplied, cancelled");
4473 return false;
4474 }
4475 crypto::secret_key spendkey;
4476 if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey))))
4477 {
4478 fail_msg_writer() << tr("failed to parse spend key secret key");
4479 return false;
4480 }
4481
4482 // parse view secret key
4483 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4484 if (std::cin.eof())
4485 return false;
4486 if (viewkey_string.empty()) {
4487 fail_msg_writer() << tr("No data supplied, cancelled");
4488 return false;
4489 }
4490 crypto::secret_key viewkey;
4491 if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4492 {
4493 fail_msg_writer() << tr("failed to parse view key secret key");
4494 return false;
4495 }
4496
4497 m_wallet_file=m_generate_from_keys;
4498
4499 // check the spend and view keys match the given address
4500 crypto::public_key pkey;
4501 if (!crypto::secret_key_to_public_key(spendkey, pkey)) {
4502 fail_msg_writer() << tr("failed to verify spend key secret key");
4503 return false;
4504 }
4505 if (info.address.m_spend_public_key != pkey) {
4506 fail_msg_writer() << tr("spend key does not match standard address");
4507 return false;
4508 }
4509 if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
4510 fail_msg_writer() << tr("failed to verify view key secret key");
4511 return false;
4512 }
4513 if (info.address.m_view_public_key != pkey) {
4514 fail_msg_writer() << tr("view key does not match standard address");
4515 return false;
4516 }
4517 auto r = new_wallet(vm, info.address, spendkey, viewkey);
4518 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4519 password = *r;
4520 welcome = true;
4521 }
4522
4523 // 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.
4524 else if (!m_generate_from_multisig_keys.empty())
4525 {
4526 m_wallet_file = m_generate_from_multisig_keys;
4527 unsigned int multisig_m;
4528 unsigned int multisig_n;
4529
4530 // parse multisig type
4531 std::string multisig_type_string = input_line("Multisig type (input as M/N with M <= N and M > 1)");
4532 if (std::cin.eof())
4533 return false;
4534 if (multisig_type_string.empty())
4535 {
4536 fail_msg_writer() << tr("No data supplied, cancelled");
4537 return false;
4538 }
4539 if (sscanf(multisig_type_string.c_str(), "%u/%u", &multisig_m, &multisig_n) != 2)
4540 {
4541 fail_msg_writer() << tr("Error: expected M/N, but got: ") << multisig_type_string;
4542 return false;
4543 }
4544 if (multisig_m <= 1 || multisig_m > multisig_n)
4545 {
4546 fail_msg_writer() << tr("Error: expected N > 1 and N <= M, but got: ") << multisig_type_string;
4547 return false;
4548 }
4549 if (multisig_m != multisig_n)
4550 {
4551 fail_msg_writer() << tr("Error: M/N is currently unsupported. ");
4552 return false;
4553 }
4554 message_writer() << boost::format(tr("Generating master wallet from %u of %u multisig wallet keys")) % multisig_m % multisig_n;
4555
4556 // parse multisig address
4557 std::string address_string = input_line("Multisig wallet address");
4558 if (std::cin.eof())
4559 return false;
4560 if (address_string.empty()) {
4561 fail_msg_writer() << tr("No data supplied, cancelled");
4562 return false;
4563 }
4564 cryptonote::address_parse_info info;
4565 if(!get_account_address_from_str(info, nettype, address_string))
4566 {
4567 fail_msg_writer() << tr("failed to parse address");
4568 return false;
4569 }
4570
4571 // parse secret view key
4572 epee::wipeable_string viewkey_string = input_secure_line("Secret view key");
4573 if (std::cin.eof())
4574 return false;
4575 if (viewkey_string.empty())
4576 {
4577 fail_msg_writer() << tr("No data supplied, cancelled");
4578 return false;
4579 }
4580 crypto::secret_key viewkey;
4581 if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
4582 {
4583 fail_msg_writer() << tr("failed to parse secret view key");
4584 return false;
4585 }
4586
4587 // check that the view key matches the given address
4588 crypto::public_key pkey;
4589 if (!crypto::secret_key_to_public_key(viewkey, pkey))
4590 {
4591 fail_msg_writer() << tr("failed to verify secret view key");
4592 return false;
4593 }
4594 if (info.address.m_view_public_key != pkey)
4595 {
4596 fail_msg_writer() << tr("view key does not match standard address");
4597 return false;
4598 }
4599
4600 // parse multisig spend keys
4601 crypto::secret_key spendkey;
4602 // parsing N/N
4603 if(multisig_m == multisig_n)
4604 {
4605 std::vector<crypto::secret_key> multisig_secret_spendkeys(multisig_n);
4606 epee::wipeable_string spendkey_string;
4607 cryptonote::blobdata spendkey_data;
4608 // get N secret spend keys from user
4609 for(unsigned int i=0; i<multisig_n; ++i)
4610 {
4611 spendkey_string = input_secure_line(tr((boost::format(tr("Secret spend key (%u of %u)")) % (i+1) % multisig_m).str().c_str()));
4612 if (std::cin.eof())
4613 return false;
4614 if (spendkey_string.empty())
4615 {
4616 fail_msg_writer() << tr("No data supplied, cancelled");
4617 return false;
4618 }
4619 if(!spendkey_string.hex_to_pod(unwrap(unwrap(multisig_secret_spendkeys[i]))))
4620 {
4621 fail_msg_writer() << tr("failed to parse spend key secret key");
4622 return false;
4623 }
4624 }
4625
4626 // sum the spend keys together to get the master spend key
4627 spendkey = multisig_secret_spendkeys[0];
4628 for(unsigned int i=1; i<multisig_n; ++i)
4629 sc_add(reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&multisig_secret_spendkeys[i]));
4630 }
4631 // parsing M/N
4632 else
4633 {
4634 fail_msg_writer() << tr("Error: M/N is currently unsupported");
4635 return false;
4636 }
4637
4638 // check that the spend key matches the given address
4639 if (!crypto::secret_key_to_public_key(spendkey, pkey))
4640 {
4641 fail_msg_writer() << tr("failed to verify spend key secret key");
4642 return false;
4643 }
4644 if (info.address.m_spend_public_key != pkey)
4645 {
4646 fail_msg_writer() << tr("spend key does not match standard address");
4647 return false;
4648 }
4649
4650 // create wallet
4651 auto r = new_wallet(vm, info.address, spendkey, viewkey);
4652 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4653 password = *r;
4654 welcome = true;
4655 }
4656
4657 else if (!m_generate_from_json.empty())
4658 {
4659 try
4660 {
4661 auto rc = tools::wallet2::make_from_json(vm, false, m_generate_from_json, password_prompter);
4662 m_wallet = std::move(rc.first);
4663 password = rc.second.password();
4664 m_wallet_file = m_wallet->path();
4665 }
4666 catch (const std::exception &e)
4667 {
4668 fail_msg_writer() << e.what();
4669 return false;
4670 }
4671 if (!m_wallet)
4672 return false;
4673 }
4674 else if (!m_generate_from_device.empty())
4675 {
4676 m_wallet_file = m_generate_from_device;
4677 // create wallet
4678 auto r = new_wallet(vm);
4679 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4680 password = *r;
4681 welcome = true;
4682 // if no block_height is specified, assume its a new account and start it "now"
4683 if (command_line::is_arg_defaulted(vm, arg_restore_height)) {
4684 {
4685 tools::scoped_message_writer wrt = tools::msg_writer();
4686 wrt << tr("No restore height is specified.") << " ";
4687 wrt << tr("Assumed you are creating a new account, restore will be done from current estimated blockchain height.") << " ";
4688 wrt << tr("Use --restore-height or --restore-date if you want to restore an already setup account from a specific height.");
4689 }
4690 std::string confirm = input_line(tr("Is this okay?"), true);
4691 if (std::cin.eof() || !command_line::is_yes(confirm))
4692 CHECK_AND_ASSERT_MES(false, false, tr("account creation aborted"));
4693
4694 m_wallet->set_refresh_from_block_height(m_wallet->estimate_blockchain_height() > 0 ? m_wallet->estimate_blockchain_height() - 1 : 0);
4695 m_wallet->explicit_refresh_from_block_height(true);
4696 m_restore_height = m_wallet->get_refresh_from_block_height();
4697 }
4698 }
4699 else
4700 {
4701 if (m_generate_new.empty()) {
4702 fail_msg_writer() << tr("specify a wallet path with --generate-new-wallet (not --wallet-file)");
4703 return false;
4704 }
4705 m_wallet_file = m_generate_new;
4706 boost::optional<epee::wipeable_string> r;
4707 if (m_restore_multisig_wallet)
4708 r = new_wallet(vm, multisig_keys, seed_pass, old_language);
4709 else
4710 r = new_wallet(vm, m_recovery_key, m_restore_deterministic_wallet, m_non_deterministic, old_language);
4711 CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
4712 password = *r;
4713 welcome = true;
4714 }
4715
4716 if (m_restoring && m_generate_from_json.empty() && m_generate_from_device.empty())
4717 {
4718 m_wallet->explicit_refresh_from_block_height(!(command_line::is_arg_defaulted(vm, arg_restore_height) &&
4719 command_line::is_arg_defaulted(vm, arg_restore_date)));
4720 if (command_line::is_arg_defaulted(vm, arg_restore_height) && !command_line::is_arg_defaulted(vm, arg_restore_date))
4721 {
4722 uint16_t year;
4723 uint8_t month;
4724 uint8_t day;
4725 if (!datestr_to_int(m_restore_date, year, month, day))
4726 return false;
4727 try
4728 {
4729 m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
4730 success_msg_writer() << tr("Restore height is: ") << m_restore_height;
4731 }
4732 catch (const std::runtime_error& e)
4733 {
4734 fail_msg_writer() << e.what();
4735 return false;
4736 }
4737 }
4738 }
4739 if (!m_wallet->explicit_refresh_from_block_height() && m_restoring)
4740 {
4741 uint32_t version;
4742 bool connected = try_connect_to_daemon(false, &version);
4743 while (true)
4744 {
4745 std::string heightstr;
4746 if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
4747 heightstr = input_line("Restore from specific blockchain height (optional, default 0)");
4748 else
4749 heightstr = input_line("Restore from specific blockchain height (optional, default 0),\nor alternatively from specific date (YYYY-MM-DD)");
4750 if (std::cin.eof())
4751 return false;
4752 if (heightstr.empty())
4753 {
4754 m_restore_height = 0;
4755 break;
4756 }
4757 try
4758 {
4759 m_restore_height = boost::lexical_cast<uint64_t>(heightstr);
4760 break;
4761 }
4762 catch (const boost::bad_lexical_cast &)
4763 {
4764 if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
4765 {
4766 fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
4767 continue;
4768 }
4769 uint16_t year;
4770 uint8_t month; // 1, 2, ..., 12
4771 uint8_t day; // 1, 2, ..., 31
4772 try
4773 {
4774 if (!datestr_to_int(heightstr, year, month, day))
4775 return false;
4776 m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
4777 success_msg_writer() << tr("Restore height is: ") << m_restore_height;
4778 std::string confirm = input_line(tr("Is this okay?"), true);
4779 if (std::cin.eof())
4780 return false;
4781 if(command_line::is_yes(confirm))
4782 break;
4783 }
4784 catch (const boost::bad_lexical_cast &)
4785 {
4786 fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
4787 }
4788 catch (const std::runtime_error& e)
4789 {
4790 fail_msg_writer() << e.what();
4791 }
4792 }
4793 }
4794 }
4795 if (m_restoring)
4796 {
4797 uint64_t estimate_height = m_wallet->estimate_blockchain_height();
4798 if (m_restore_height >= estimate_height)
4799 {
4800 success_msg_writer() << tr("Restore height ") << m_restore_height << (" is not yet reached. The current estimated height is ") << estimate_height;
4801 std::string confirm = input_line(tr("Still apply restore height?"), true);
4802 if (std::cin.eof() || command_line::is_no(confirm))
4803 m_restore_height = 0;
4804 }
4805 m_wallet->set_refresh_from_block_height(m_restore_height);
4806 }
4807 if (enable_multisig)
4808 m_wallet->enable_multisig(true);
4809 m_wallet->rewrite(m_wallet_file, password);
4810 }
4811 else
4812 {
4813 assert(!m_wallet_file.empty());
4814 if (!m_subaddress_lookahead.empty())
4815 {
4816 fail_msg_writer() << tr("can't specify --subaddress-lookahead and --wallet-file at the same time");
4817 return false;
4818 }
4819 auto r = open_wallet(vm);
4820 CHECK_AND_ASSERT_MES(r, false, tr("failed to open account"));
4821 password = *r;
4822 }
4823 if (!m_wallet)
4824 {
4825 fail_msg_writer() << tr("wallet is null");
4826 return false;
4827 }
4828
4829 if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key))
4830 {
4831 crypto::secret_key rpc_client_secret_key;
4832 if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), rpc_client_secret_key))
4833 {
4834 fail_msg_writer() << tr("RPC client secret key should be 32 byte in hex format");
4835 return false;
4836 }
4837 m_wallet->set_rpc_client_secret_key(rpc_client_secret_key);
4838 }
4839
4840 if (!m_wallet->is_trusted_daemon())
4841 {
4842 message_writer(console_color_red, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str();
4843 message_writer(console_color_red, true) << boost::format(tr("Using a third party daemon can be detrimental to your security and privacy"));
4844 bool ssl = false;
4845 if (m_wallet->check_connection(NULL, &ssl) && !ssl)
4846 message_writer(console_color_red, true) << boost::format(tr("Using your own without SSL exposes your RPC traffic to monitoring"));
4847 message_writer(console_color_red, true) << boost::format(tr("You are strongly encouraged to connect to the Monero network using your own daemon"));
4848 message_writer(console_color_red, true) << boost::format(tr("If you or someone you trust are operating this daemon, you can use --trusted-daemon"));
4849
4850 COMMAND_RPC_GET_INFO::request req;
4851 COMMAND_RPC_GET_INFO::response res;
4852 bool r = m_wallet->invoke_http_json("/get_info", req, res);
4853 std::string err = interpret_rpc_response(r, res.status);
4854 if (r && err.empty() && (res.was_bootstrap_ever_used || !res.bootstrap_daemon_address.empty()))
4855 message_writer(console_color_red, true) << boost::format(tr("Moreover, a daemon is also less secure when running in bootstrap mode"));
4856 }
4857
4858 if (m_wallet->get_ring_database().empty())
4859 fail_msg_writer() << tr("Failed to initialize ring database: privacy enhancing features will be inactive");
4860
4861 m_wallet->callback(this);
4862
4863 bool skip_check_backround_mining = !command_line::get_arg(vm, arg_command).empty();
4864 if (!skip_check_backround_mining)
4865 check_background_mining(password);
4866
4867 if (welcome)
4868 message_writer(console_color_yellow, true) << tr("If you are new to Monero, type \"welcome\" for a brief overview.");
4869
4870 m_last_activity_time = time(NULL);
4871 return true;
4872 }
4873 //----------------------------------------------------------------------------------------------------
4874 bool simple_wallet::deinit()
4875 {
4876 if (!m_wallet.get())
4877 return true;
4878
4879 return close_wallet();
4880 }
4881 //----------------------------------------------------------------------------------------------------
4882 bool simple_wallet::handle_command_line(const boost::program_options::variables_map& vm)
4883 {
4884 m_wallet_file = command_line::get_arg(vm, arg_wallet_file);
4885 m_generate_new = command_line::get_arg(vm, arg_generate_new_wallet);
4886 m_generate_from_device = command_line::get_arg(vm, arg_generate_from_device);
4887 m_generate_from_view_key = command_line::get_arg(vm, arg_generate_from_view_key);
4888 m_generate_from_spend_key = command_line::get_arg(vm, arg_generate_from_spend_key);
4889 m_generate_from_keys = command_line::get_arg(vm, arg_generate_from_keys);
4890 m_generate_from_multisig_keys = command_line::get_arg(vm, arg_generate_from_multisig_keys);
4891 m_generate_from_json = command_line::get_arg(vm, arg_generate_from_json);
4892 m_mnemonic_language = command_line::get_arg(vm, arg_mnemonic_language);
4893 m_electrum_seed = command_line::get_arg(vm, arg_electrum_seed);
4894 m_restore_deterministic_wallet = command_line::get_arg(vm, arg_restore_deterministic_wallet) || command_line::get_arg(vm, arg_restore_from_seed);
4895 m_restore_multisig_wallet = command_line::get_arg(vm, arg_restore_multisig_wallet);
4896 m_non_deterministic = command_line::get_arg(vm, arg_non_deterministic);
4897 m_restore_height = command_line::get_arg(vm, arg_restore_height);
4898 m_restore_date = command_line::get_arg(vm, arg_restore_date);
4899 m_do_not_relay = command_line::get_arg(vm, arg_do_not_relay);
4900 m_subaddress_lookahead = command_line::get_arg(vm, arg_subaddress_lookahead);
4901 m_use_english_language_names = command_line::get_arg(vm, arg_use_english_language_names);
4902 m_restoring = !m_generate_from_view_key.empty() ||
4903 !m_generate_from_spend_key.empty() ||
4904 !m_generate_from_keys.empty() ||
4905 !m_generate_from_multisig_keys.empty() ||
4906 !m_generate_from_json.empty() ||
4907 !m_generate_from_device.empty() ||
4908 m_restore_deterministic_wallet ||
4909 m_restore_multisig_wallet;
4910
4911 if (!command_line::is_arg_defaulted(vm, arg_restore_date))
4912 {
4913 uint16_t year;
4914 uint8_t month, day;
4915 if (!datestr_to_int(m_restore_date, year, month, day))
4916 return false;
4917 }
4918
4919 return true;
4920 }
4921 //----------------------------------------------------------------------------------------------------
4922 bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version)
4923 {
4924 uint32_t version_ = 0;
4925 if (!version)
4926 version = &version_;
4927 bool wallet_is_outdated = false, daemon_is_outdated = false;
4928 if (!m_wallet->check_connection(version, NULL, 200000, &wallet_is_outdated, &daemon_is_outdated))
4929 {
4930 if (!silent)
4931 {
4932 if (m_wallet->is_offline())
4933 fail_msg_writer() << tr("wallet failed to connect to daemon, because it is set to offline mode");
4934 else if (wallet_is_outdated)
4935 fail_msg_writer() << tr("wallet failed to connect to daemon, because it is not up to date. ") <<
4936 tr("Please make sure you are running the latest wallet.");
4937 else if (daemon_is_outdated)
4938 fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " <<
4939 tr("Daemon is not up to date. "
4940 "Please make sure the daemon is running the latest version or change the daemon address using the 'set_daemon' command.");
4941 else
4942 fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " <<
4943 tr("Daemon either is not started or wrong port was passed. "
4944 "Please make sure daemon is running or change the daemon address using the 'set_daemon' command.");
4945 }
4946 return false;
4947 }
4948 if (!m_wallet->is_mismatched_daemon_version_allowed() && ((*version >> 16) != CORE_RPC_VERSION_MAJOR))
4949 {
4950 if (!silent)
4951 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();
4952 return false;
4953 }
4954 return true;
4955 }
4956
4957 /*!
4958 * \brief Gets the word seed language from the user.
4959 *
4960 * User is asked to choose from a list of supported languages.
4961 *
4962 * \return The chosen language.
4963 */
4964 std::string simple_wallet::get_mnemonic_language()
4965 {
4966 std::vector<std::string> language_list_self, language_list_english;
4967 const std::vector<std::string> &language_list = m_use_english_language_names ? language_list_english : language_list_self;
4968 std::string language_choice;
4969 int language_number = -1;
4970 crypto::ElectrumWords::get_language_list(language_list_self, false);
4971 crypto::ElectrumWords::get_language_list(language_list_english, true);
4972 std::cout << tr("List of available languages for your wallet's seed:") << std::endl;
4973 std::cout << tr("If your display freezes, exit blind with ^C, then run again with --use-english-language-names") << std::endl;
4974 int ii;
4975 std::vector<std::string>::const_iterator it;
4976 for (it = language_list.begin(), ii = 0; it != language_list.end(); it++, ii++)
4977 {
4978 std::cout << ii << " : " << *it << std::endl;
4979 }
4980 while (language_number < 0)
4981 {
4982 language_choice = input_line(tr("Enter the number corresponding to the language of your choice"));
4983 if (std::cin.eof())
4984 return std::string();
4985 try
4986 {
4987 language_number = std::stoi(language_choice);
4988 if (!((language_number >= 0) && (static_cast<unsigned int>(language_number) < language_list.size())))
4989 {
4990 language_number = -1;
4991 fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
4992 }
4993 }
4994 catch (const std::exception &e)
4995 {
4996 fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
4997 }
4998 }
4999 return language_list_self[language_number];
5000 }
5001 //----------------------------------------------------------------------------------------------------
5002 boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const
5003 {
5004 const bool verify = m_wallet_file.empty();
5005 auto pwd_container = (m_wallet->is_background_wallet() && m_wallet->background_sync_type() == tools::wallet2::BackgroundSyncCustomPassword)
5006 ? background_sync_cache_password_prompter(verify)
5007 : default_password_prompter(verify);
5008 if (!pwd_container)
5009 return boost::none;
5010
5011 if (!m_wallet->verify_password(pwd_container->password()))
5012 {
5013 fail_msg_writer() << tr("invalid password");
5014 return boost::none;
5015 }
5016 return pwd_container;
5017 }
5018 //----------------------------------------------------------------------------------------------------
5019 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5020 const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language)
5021 {
5022 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5023 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5024 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5025 m_wallet = std::move(rc.first);
5026 if (!m_wallet)
5027 {
5028 return {};
5029 }
5030 epee::wipeable_string password = rc.second.password();
5031
5032 if (!m_subaddress_lookahead.empty())
5033 {
5034 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5035 assert(lookahead);
5036 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5037 }
5038
5039 bool was_deprecated_wallet = m_restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) ||
5040 crypto::ElectrumWords::get_is_old_style_seed(m_electrum_seed));
5041
5042 std::string mnemonic_language = old_language;
5043
5044 std::vector<std::string> language_list;
5045 crypto::ElectrumWords::get_language_list(language_list);
5046 if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
5047 {
5048 mnemonic_language = m_mnemonic_language;
5049 }
5050
5051 // Ask for seed language if:
5052 // it's a deterministic wallet AND
5053 // a seed language is not already specified AND
5054 // (it is not a wallet restore OR if it was a deprecated wallet
5055 // that was earlier used before this restore)
5056 if ((!two_random) && (mnemonic_language.empty() || mnemonic_language == crypto::ElectrumWords::old_language_name) && (!m_restore_deterministic_wallet || was_deprecated_wallet))
5057 {
5058 if (was_deprecated_wallet)
5059 {
5060 // The user had used an older version of the wallet with old style mnemonics.
5061 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5062 "a deprecated version of the wallet. Please use the new seed that we provide.\n");
5063 }
5064 mnemonic_language = get_mnemonic_language();
5065 if (mnemonic_language.empty())
5066 return {};
5067 }
5068
5069 m_wallet->set_seed_language(mnemonic_language);
5070
5071 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5072
5073 crypto::secret_key recovery_val;
5074 try
5075 {
5076 recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file);
5077 message_writer(console_color_white, true) << tr("Generated new wallet: ")
5078 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5079 PAUSE_READLINE();
5080 std::cout << tr("View key: ");
5081 print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
5082 putchar('\n');
5083 }
5084 catch (const std::exception& e)
5085 {
5086 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5087 return {};
5088 }
5089
5090 // convert rng value to electrum-style word list
5091 epee::wipeable_string electrum_words;
5092
5093 crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language);
5094
5095 success_msg_writer() <<
5096 "**********************************************************************\n" <<
5097 tr("Your wallet has been generated!\n"
5098 "To start synchronizing with the daemon, use the \"refresh\" command.\n"
5099 "Use the \"help\" command to see a simplified list of available commands.\n"
5100 "Use \"help all\" command to see the list of all available commands.\n"
5101 "Use \"help <command>\" to see a command's documentation.\n"
5102 "Always use the \"exit\" command when closing monero-wallet-cli to save \n"
5103 "your current session's state. Otherwise, you might need to synchronize \n"
5104 "your wallet again (your wallet keys are NOT at risk in any case).\n")
5105 ;
5106
5107 if (!two_random)
5108 {
5109 print_seed(electrum_words);
5110 }
5111 success_msg_writer() << "**********************************************************************";
5112
5113 return password;
5114 }
5115 //----------------------------------------------------------------------------------------------------
5116 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5117 const cryptonote::account_public_address& address, const boost::optional<crypto::secret_key>& spendkey,
5118 const crypto::secret_key& viewkey)
5119 {
5120 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5121 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5122 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5123 m_wallet = std::move(rc.first);
5124 if (!m_wallet)
5125 {
5126 return {};
5127 }
5128 epee::wipeable_string password = rc.second.password();
5129
5130 if (!m_subaddress_lookahead.empty())
5131 {
5132 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5133 assert(lookahead);
5134 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5135 }
5136
5137 if (m_restore_height)
5138 m_wallet->set_refresh_from_block_height(m_restore_height);
5139
5140 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5141
5142 try
5143 {
5144 if (spendkey)
5145 {
5146 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, *spendkey, viewkey, create_address_file);
5147 }
5148 else
5149 {
5150 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file);
5151 }
5152 message_writer(console_color_white, true) << tr("Generated new wallet: ")
5153 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5154 }
5155 catch (const std::exception& e)
5156 {
5157 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5158 return {};
5159 }
5160
5161
5162 return password;
5163 }
5164
5165 //----------------------------------------------------------------------------------------------------
5166 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm)
5167 {
5168 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5169 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5170 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5171 m_wallet = std::move(rc.first);
5172 m_wallet->callback(this);
5173 if (!m_wallet)
5174 {
5175 return {};
5176 }
5177 epee::wipeable_string password = rc.second.password();
5178
5179 if (!m_subaddress_lookahead.empty())
5180 {
5181 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5182 assert(lookahead);
5183 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5184 }
5185
5186 if (m_restore_height)
5187 m_wallet->set_refresh_from_block_height(m_restore_height);
5188
5189 auto device_desc = tools::wallet2::device_name_option(vm);
5190 auto device_derivation_path = tools::wallet2::device_derivation_path_option(vm);
5191 try
5192 {
5193 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5194 m_wallet->device_derivation_path(device_derivation_path);
5195 m_wallet->restore(m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file);
5196 message_writer(console_color_white, true) << tr("Generated new wallet on hw device: ")
5197 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5198 }
5199 catch (const std::exception& e)
5200 {
5201 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5202 return {};
5203 }
5204
5205 return password;
5206 }
5207 //----------------------------------------------------------------------------------------------------
5208 boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
5209 const epee::wipeable_string &multisig_keys, const epee::wipeable_string &seed_pass, const std::string &old_language)
5210 {
5211 std::pair<std::unique_ptr<tools::wallet2>, tools::password_container> rc;
5212 try { rc = tools::wallet2::make_new(vm, false, password_prompter); }
5213 catch(const std::exception &e) { fail_msg_writer() << tr("Error creating wallet: ") << e.what(); return {}; }
5214 m_wallet = std::move(rc.first);
5215 if (!m_wallet)
5216 {
5217 return {};
5218 }
5219 epee::wipeable_string password = rc.second.password();
5220
5221 if (!m_subaddress_lookahead.empty())
5222 {
5223 auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
5224 assert(lookahead);
5225 m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
5226 }
5227
5228 std::string mnemonic_language = old_language;
5229
5230 std::vector<std::string> language_list;
5231 crypto::ElectrumWords::get_language_list(language_list);
5232 if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
5233 {
5234 mnemonic_language = m_mnemonic_language;
5235 }
5236
5237 m_wallet->set_seed_language(mnemonic_language);
5238
5239 bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
5240
5241 try
5242 {
5243 if (seed_pass.empty())
5244 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), multisig_keys, create_address_file);
5245 else
5246 {
5247 crypto::secret_key key;
5248 crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key);
5249 sc_reduce32((unsigned char*)key.data);
5250 const epee::wipeable_string &msig_keys = m_wallet->decrypt<epee::wipeable_string>(std::string(multisig_keys.data(), multisig_keys.size()), key, true);
5251 m_wallet->generate(m_wallet_file, std::move(rc.second).password(), msig_keys, create_address_file);
5252 }
5253 bool ready;
5254 uint32_t threshold, total;
5255 if (!m_wallet->multisig(&ready, &threshold, &total) || !ready)
5256 {
5257 fail_msg_writer() << tr("failed to generate new mutlisig wallet");
5258 return {};
5259 }
5260 message_writer(console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total
5261 << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5262 }
5263 catch (const std::exception& e)
5264 {
5265 fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
5266 return {};
5267 }
5268
5269 return password;
5270 }
5271 //----------------------------------------------------------------------------------------------------
5272 boost::optional<epee::wipeable_string> simple_wallet::open_wallet(const boost::program_options::variables_map& vm)
5273 {
5274 if (!tools::wallet2::wallet_valid_path_format(m_wallet_file))
5275 {
5276 fail_msg_writer() << tr("wallet file path not valid: ") << m_wallet_file;
5277 return {};
5278 }
5279
5280 bool keys_file_exists;
5281 bool wallet_file_exists;
5282
5283 tools::wallet2::wallet_exists(m_wallet_file, keys_file_exists, wallet_file_exists);
5284 if(!keys_file_exists)
5285 {
5286 fail_msg_writer() << tr("Key file not found. Failed to open wallet");
5287 return {};
5288 }
5289
5290 epee::wipeable_string password;
5291 try
5292 {
5293 auto rc = tools::wallet2::make_from_file(vm, false, "", password_prompter);
5294 m_wallet = std::move(rc.first);
5295 password = std::move(std::move(rc.second).password());
5296 if (!m_wallet)
5297 {
5298 return {};
5299 }
5300
5301 m_wallet->callback(this);
5302 m_wallet->load(m_wallet_file, password);
5303 std::string prefix;
5304 bool ready;
5305 uint32_t threshold, total;
5306 if (m_wallet->watch_only())
5307 prefix = tr("Opened watch-only wallet");
5308 else if (m_wallet->multisig(&ready, &threshold, &total))
5309 prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
5310 else if (m_wallet->is_background_wallet())
5311 prefix = tr("Opened background wallet");
5312 else
5313 prefix = tr("Opened wallet");
5314 message_writer(console_color_white, true) <<
5315 prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5316 if (m_wallet->get_account().get_device()) {
5317 message_writer(console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name();
5318 }
5319 // If the wallet file is deprecated, we should ask for mnemonic language again and store
5320 // everything in the new format.
5321 // 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.
5322 if (m_wallet->is_deprecated())
5323 {
5324 bool is_deterministic;
5325 {
5326 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return {};);
5327 is_deterministic = m_wallet->is_deterministic();
5328 }
5329 if (is_deterministic)
5330 {
5331 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5332 "a deprecated version of the wallet. Please proceed to upgrade your wallet.\n");
5333 std::string mnemonic_language = get_mnemonic_language();
5334 if (mnemonic_language.empty())
5335 return {};
5336 m_wallet->set_seed_language(mnemonic_language);
5337 m_wallet->rewrite(m_wallet_file, password);
5338
5339 // Display the seed
5340 epee::wipeable_string seed;
5341 m_wallet->get_seed(seed);
5342 print_seed(seed);
5343 }
5344 else
5345 {
5346 message_writer(console_color_green, false) << "\n" << tr("You had been using "
5347 "a deprecated version of the wallet. Your wallet file format is being upgraded now.\n");
5348 m_wallet->rewrite(m_wallet_file, password);
5349 }
5350 }
5351 }
5352 catch (const std::exception& e)
5353 {
5354 fail_msg_writer() << tr("failed to load wallet: ") << e.what();
5355 if (m_wallet)
5356 {
5357 // only suggest removing cache if the password was actually correct
5358 bool password_is_correct = false;
5359 try
5360 {
5361 password_is_correct = m_wallet->verify_password(password);
5362 }
5363 catch (...) { } // guard against I/O errors
5364 if (password_is_correct)
5365 fail_msg_writer() << boost::format(tr("You may want to remove the file \"%s\" and try again")) % m_wallet_file;
5366 }
5367 return {};
5368 }
5369 success_msg_writer() <<
5370 "**********************************************************************\n" <<
5371 tr("Use the \"help\" command to see a simplified list of available commands.\n") <<
5372 tr("Use \"help all\" to see the list of all available commands.\n") <<
5373 tr("Use \"help <command>\" to see a command's documentation.\n") <<
5374 "**********************************************************************";
5375 return password;
5376 }
5377 //----------------------------------------------------------------------------------------------------
5378 bool simple_wallet::close_wallet()
5379 {
5380 if (m_idle_run.load(std::memory_order_relaxed))
5381 {
5382 m_idle_run.store(false, std::memory_order_relaxed);
5383 m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed);
5384 m_wallet->stop();
5385 {
5386 boost::unique_lock<boost::mutex> lock(m_idle_mutex);
5387 m_idle_cond.notify_one();
5388 }
5389 m_idle_thread.join();
5390 }
5391
5392 bool r = m_wallet->deinit();
5393 if (!r)
5394 {
5395 fail_msg_writer() << tr("failed to deinitialize wallet");
5396 return false;
5397 }
5398
5399 try
5400 {
5401 m_wallet->store();
5402 }
5403 catch (const std::exception& e)
5404 {
5405 fail_msg_writer() << e.what();
5406 return false;
5407 }
5408
5409 return true;
5410 }
5411 //----------------------------------------------------------------------------------------------------
5412 bool simple_wallet::save(const std::vector<std::string> &args)
5413 {
5414 try
5415 {
5416 LOCK_IDLE_SCOPE();
5417 m_wallet->store();
5418 success_msg_writer() << tr("Wallet data saved");
5419 }
5420 catch (const std::exception& e)
5421 {
5422 fail_msg_writer() << e.what();
5423 }
5424
5425 return true;
5426 }
5427 //----------------------------------------------------------------------------------------------------
5428 bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
5429 {
5430 if (m_wallet->multisig())
5431 {
5432 fail_msg_writer() << tr("wallet is multisig and cannot save a watch-only version");
5433 return true;
5434 }
5435
5436 const auto pwd_container = password_prompter(tr("Password for new watch-only wallet"), true);
5437
5438 if (!pwd_container)
5439 {
5440 fail_msg_writer() << tr("failed to read wallet password");
5441 return true;
5442 }
5443
5444 try
5445 {
5446 std::string new_keys_filename;
5447 m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password(), new_keys_filename);
5448 success_msg_writer() << tr("Watch only wallet saved as: ") << new_keys_filename;
5449 }
5450 catch (const std::exception &e)
5451 {
5452 fail_msg_writer() << tr("Failed to save watch only wallet: ") << e.what();
5453 return true;
5454 }
5455 return true;
5456 }
5457 //----------------------------------------------------------------------------------------------------
5458 void simple_wallet::start_background_mining()
5459 {
5460 COMMAND_RPC_MINING_STATUS::request reqq;
5461 COMMAND_RPC_MINING_STATUS::response resq;
5462 bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
5463 std::string err = interpret_rpc_response(r, resq.status);
5464 if (!r)
5465 return;
5466 if (!err.empty())
5467 {
5468 fail_msg_writer() << tr("Failed to query mining status: ") << err;
5469 return;
5470 }
5471 if (!resq.is_background_mining_enabled)
5472 {
5473 COMMAND_RPC_START_MINING::request req;
5474 COMMAND_RPC_START_MINING::response res;
5475 req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5476 req.threads_count = 1;
5477 req.do_background_mining = true;
5478 req.ignore_battery = false;
5479 bool r = m_wallet->invoke_http_json("/start_mining", req, res);
5480 std::string err = interpret_rpc_response(r, res.status);
5481 if (!err.empty())
5482 {
5483 fail_msg_writer() << tr("Failed to setup background mining: ") << err;
5484 return;
5485 }
5486 }
5487 success_msg_writer() << tr("Background mining enabled. Thank you for supporting the Monero network.");
5488 }
5489 //----------------------------------------------------------------------------------------------------
5490 void simple_wallet::stop_background_mining()
5491 {
5492 COMMAND_RPC_MINING_STATUS::request reqq;
5493 COMMAND_RPC_MINING_STATUS::response resq;
5494 bool r = m_wallet->invoke_http_json("/mining_status", reqq, resq);
5495 if (!r)
5496 return;
5497 std::string err = interpret_rpc_response(r, resq.status);
5498 if (!err.empty())
5499 {
5500 fail_msg_writer() << tr("Failed to query mining status: ") << err;
5501 return;
5502 }
5503 if (resq.is_background_mining_enabled)
5504 {
5505 COMMAND_RPC_STOP_MINING::request req;
5506 COMMAND_RPC_STOP_MINING::response res;
5507 bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
5508 std::string err = interpret_rpc_response(r, res.status);
5509 if (!err.empty())
5510 {
5511 fail_msg_writer() << tr("Failed to setup background mining: ") << err;
5512 return;
5513 }
5514 }
5515 message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
5516 }
5517 //----------------------------------------------------------------------------------------------------
5518 void simple_wallet::check_background_mining(const epee::wipeable_string &password)
5519 {
5520 // Background mining can be toggled from the main wallet
5521 if (m_wallet->is_background_wallet() || m_wallet->is_background_syncing())
5522 return;
5523
5524 tools::wallet2::BackgroundMiningSetupType setup = m_wallet->setup_background_mining();
5525 if (setup == tools::wallet2::BackgroundMiningNo)
5526 {
5527 message_writer(console_color_red, false) << tr("Background mining not enabled. Run \"set setup-background-mining 1\" to change.");
5528 return;
5529 }
5530
5531 if (!m_wallet->is_trusted_daemon())
5532 {
5533 message_writer() << tr("Using an untrusted daemon, skipping background mining check");
5534 return;
5535 }
5536
5537 COMMAND_RPC_MINING_STATUS::request req;
5538 COMMAND_RPC_MINING_STATUS::response res;
5539 bool r = m_wallet->invoke_http_json("/mining_status", req, res);
5540 std::string err = interpret_rpc_response(r, res.status);
5541 bool is_background_mining_enabled = false;
5542 if (err.empty())
5543 is_background_mining_enabled = res.is_background_mining_enabled;
5544
5545 if (is_background_mining_enabled)
5546 {
5547 // already active, nice
5548 if (setup == tools::wallet2::BackgroundMiningMaybe)
5549 {
5550 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
5551 m_wallet->rewrite(m_wallet_file, password);
5552 }
5553 start_background_mining();
5554 return;
5555 }
5556 if (res.active)
5557 return;
5558
5559 if (setup == tools::wallet2::BackgroundMiningMaybe)
5560 {
5561 message_writer() << tr("The daemon is not set up to background mine.");
5562 message_writer() << tr("With background mining enabled, the daemon will mine when idle and not on battery.");
5563 message_writer() << tr("Enabling this supports the network you are using, and makes you eligible for receiving new monero");
5564 std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
5565 if (std::cin.eof() || !command_line::is_yes(accepted)) {
5566 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningNo);
5567 m_wallet->rewrite(m_wallet_file, password);
5568 message_writer(console_color_red, false) << tr("Background mining not enabled. Set setup-background-mining to 1 to change.");
5569 return;
5570 }
5571 m_wallet->setup_background_mining(tools::wallet2::BackgroundMiningYes);
5572 m_wallet->rewrite(m_wallet_file, password);
5573 start_background_mining();
5574 }
5575 else
5576 {
5577 // the setting is already enabled, and the daemon is not mining yet, so start it
5578 start_background_mining();
5579 }
5580 }
5581 //----------------------------------------------------------------------------------------------------
5582 bool simple_wallet::start_mining(const std::vector<std::string>& args)
5583 {
5584 if (!m_wallet->is_trusted_daemon())
5585 {
5586 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
5587 return true;
5588 }
5589
5590 if (!try_connect_to_daemon())
5591 return true;
5592
5593 if (!m_wallet)
5594 {
5595 fail_msg_writer() << tr("wallet is null");
5596 return true;
5597 }
5598 COMMAND_RPC_START_MINING::request req = AUTO_VAL_INIT(req);
5599 req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
5600
5601 bool ok = true;
5602 size_t arg_size = args.size();
5603 if(arg_size >= 3)
5604 {
5605 if (!parse_bool_and_use(args[2], [&](bool r) { req.ignore_battery = r; }))
5606 return true;
5607 }
5608 if(arg_size >= 2)
5609 {
5610 if (!parse_bool_and_use(args[1], [&](bool r) { req.do_background_mining = r; }))
5611 return true;
5612 }
5613 if(arg_size >= 1)
5614 {
5615 uint16_t num = 1;
5616 ok = string_tools::get_xtype_from_string(num, args[0]);
5617 ok = ok && 1 <= num;
5618 req.threads_count = num;
5619 }
5620 else
5621 {
5622 req.threads_count = 1;
5623 }
5624
5625 if (!ok)
5626 {
5627 PRINT_USAGE(USAGE_START_MINING);
5628 return true;
5629 }
5630
5631 COMMAND_RPC_START_MINING::response res;
5632 bool r = m_wallet->invoke_http_json("/start_mining", req, res);
5633 std::string err = interpret_rpc_response(r, res.status);
5634 if (err.empty())
5635 success_msg_writer() << tr("Mining started in daemon");
5636 else
5637 fail_msg_writer() << tr("mining has NOT been started: ") << err;
5638 return true;
5639 }
5640 //----------------------------------------------------------------------------------------------------
5641 bool simple_wallet::stop_mining(const std::vector<std::string>& args)
5642 {
5643 if (!try_connect_to_daemon())
5644 return true;
5645
5646 if (!m_wallet)
5647 {
5648 fail_msg_writer() << tr("wallet is null");
5649 return true;
5650 }
5651
5652 COMMAND_RPC_STOP_MINING::request req;
5653 COMMAND_RPC_STOP_MINING::response res;
5654 bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
5655 std::string err = interpret_rpc_response(r, res.status);
5656 if (err.empty())
5657 success_msg_writer() << tr("Mining stopped in daemon");
5658 else
5659 fail_msg_writer() << tr("mining has NOT been stopped: ") << err;
5660 return true;
5661 }
5662 //----------------------------------------------------------------------------------------------------
5663 bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph)
5664 {
5665 try
5666 {
5667 auto i = m_claimed_cph.find(daemon_url);
5668 if (i == m_claimed_cph.end())
5669 return false;
5670
5671 claimed_cph = m_claimed_cph[daemon_url];
5672 bool payment_required;
5673 uint64_t credits, diff, credits_per_hash_found, height, seed_height;
5674 uint32_t cookie;
5675 cryptonote::blobdata hashing_blob;
5676 crypto::hash seed_hash, next_seed_hash;
5677 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)
5678 {
5679 actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff);
5680 return true;
5681 }
5682 else
5683 {
5684 fail_msg_writer() << tr("Error checking daemon RPC access prices");
5685 }
5686 }
5687 catch (const std::exception &e)
5688 {
5689 // can't check
5690 fail_msg_writer() << tr("Error checking daemon RPC access prices: ") << e.what();
5691 return false;
5692 }
5693 // no record found for this daemon
5694 return false;
5695 }
5696 //----------------------------------------------------------------------------------------------------
5697 bool simple_wallet::set_daemon(const std::vector<std::string>& args)
5698 {
5699 std::string daemon_url;
5700
5701 if (args.size() < 1)
5702 {
5703 PRINT_USAGE(USAGE_SET_DAEMON);
5704 return true;
5705 }
5706
5707 boost::regex rgx("^(.*://)?([A-Za-z0-9\\-\\.]+)(:[0-9]+)?");
5708 boost::cmatch match;
5709 // If user input matches URL regex
5710 if (boost::regex_match(args[0].c_str(), match, rgx))
5711 {
5712 if (match.length() < 4)
5713 {
5714 fail_msg_writer() << tr("Unexpected array length - Exited simple_wallet::set_daemon()");
5715 return true;
5716 }
5717 // If no port has been provided, use the default from config
5718 if (!match[3].length())
5719 {
5720 uint16_t daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT;
5721 daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port);
5722 } else {
5723 daemon_url = args[0];
5724 }
5725
5726 epee::net_utils::http::url_content parsed{};
5727 const bool r = epee::net_utils::parse_url(daemon_url, parsed);
5728 if (!r)
5729 {
5730 fail_msg_writer() << tr("Failed to parse address");
5731 return true;
5732 }
5733
5734 std::string trusted;
5735 if (args.size() == 2)
5736 {
5737 if (args[1] == "trusted")
5738 trusted = "trusted";
5739 else if (args[1] == "untrusted")
5740 trusted = "untrusted";
5741 else if (args[1] == "this-is-probably-a-spy-node")
5742 trusted = "this-is-probably-a-spy-node";
5743 else
5744 {
5745 fail_msg_writer() << tr("Expected trusted, untrusted or this-is-probably-a-spy-node got ") << args[1];
5746 return true;
5747 }
5748 }
5749
5750 if (!tools::is_privacy_preserving_network(parsed.host) && !tools::is_local_address(parsed.host))
5751 {
5752 if (trusted == "untrusted" || trusted == "")
5753 {
5754 fail_msg_writer() << tr("This is not Tor/I2P address, and is not a trusted daemon.");
5755 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.");
5756 return true;
5757 }
5758
5759 if (parsed.schema != "https")
5760 message_writer(console_color_red) << tr("Warning: connecting to a non-local daemon without SSL, passive adversaries will be able to spy on you.");
5761 }
5762
5763 LOCK_IDLE_SCOPE();
5764 m_wallet->init(daemon_url);
5765
5766 if (!trusted.empty())
5767 {
5768 m_wallet->set_trusted_daemon(trusted == "trusted");
5769 }
5770 else
5771 {
5772 m_wallet->set_trusted_daemon(false);
5773 try
5774 {
5775 if (tools::is_local_address(m_wallet->get_daemon_address()))
5776 {
5777 MINFO(tr("Daemon is local, assuming trusted"));
5778 m_wallet->set_trusted_daemon(true);
5779 }
5780 }
5781 catch (const std::exception &e) { }
5782 }
5783
5784 if (!try_connect_to_daemon())
5785 {
5786 fail_msg_writer() << tr("Failed to connect to daemon");
5787 return true;
5788 }
5789
5790 success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted"));
5791
5792 // check whether the daemon's prices match the claim, and disconnect if not, to disincentivize daemons lying
5793 uint32_t actual_cph, claimed_cph;
5794 if (check_daemon_rpc_prices(daemon_url, actual_cph, claimed_cph))
5795 {
5796 if (actual_cph < claimed_cph)
5797 {
5798 fail_msg_writer() << tr("Daemon RPC credits/hash is less than was claimed. Either this daemon is cheating, or it changed its setup recently.");
5799 fail_msg_writer() << tr("Claimed: ") << claimed_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
5800 fail_msg_writer() << tr("Actual: ") << actual_cph / (float)RPC_CREDITS_PER_HASH_SCALE;
5801 }
5802 }
5803
5804 m_daemon_rpc_payment_message_displayed = false;
5805 } else {
5806 fail_msg_writer() << tr("This does not seem to be a valid daemon URL.");
5807 }
5808 return true;
5809 }
5810 //----------------------------------------------------------------------------------------------------
5811 bool simple_wallet::save_bc(const std::vector<std::string>& args)
5812 {
5813 if (!try_connect_to_daemon())
5814 return true;
5815
5816 if (!m_wallet)
5817 {
5818 fail_msg_writer() << tr("wallet is null");
5819 return true;
5820 }
5821 COMMAND_RPC_SAVE_BC::request req;
5822 COMMAND_RPC_SAVE_BC::response res;
5823 bool r = m_wallet->invoke_http_json("/save_bc", req, res);
5824 std::string err = interpret_rpc_response(r, res.status);
5825 if (err.empty())
5826 success_msg_writer() << tr("Blockchain saved");
5827 else
5828 fail_msg_writer() << tr("blockchain can't be saved: ") << err;
5829 return true;
5830 }
5831 //----------------------------------------------------------------------------------------------------
5832 void simple_wallet::on_new_block(uint64_t height, const cryptonote::block& block)
5833 {
5834 if (m_locked)
5835 return;
5836 if (!m_auto_refresh_refreshing)
5837 m_refresh_progress_reporter.update(height, false);
5838 }
5839 //----------------------------------------------------------------------------------------------------
5840 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)
5841 {
5842 if (m_locked)
5843 return;
5844 std::stringstream burn;
5845 if (burnt != 0) {
5846 burn << " (" << print_money(amount) << " yet " << print_money(burnt) << " was burnt)";
5847 }
5848 message_writer(console_color_green, false) << "\r" <<
5849 tr("Height ") << height << ", " <<
5850 tr("txid ") << txid << ", " <<
5851 print_money(amount - burnt) << burn.str() << ", " <<
5852 tr("idx ") << subaddr_index;
5853
5854 const uint64_t warn_height = m_wallet->nettype() == TESTNET ? 1000000 : m_wallet->nettype() == STAGENET ? 50000 : 1650000;
5855 if (height >= warn_height && !is_change)
5856 {
5857 std::vector<tx_extra_field> tx_extra_fields;
5858 parse_tx_extra(tx.extra, tx_extra_fields); // failure ok
5859 tx_extra_nonce extra_nonce;
5860 tx_extra_pub_key extra_pub_key;
5861 crypto::hash8 payment_id8 = crypto::null_hash8;
5862 if (find_tx_extra_field_by_type(tx_extra_fields, extra_pub_key))
5863 {
5864 const crypto::public_key &tx_pub_key = extra_pub_key.pub_key;
5865 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
5866 {
5867 if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
5868 {
5869 m_wallet->get_account().get_device().decrypt_payment_id(payment_id8, tx_pub_key, m_wallet->get_account().get_keys().m_view_secret_key);
5870 }
5871 }
5872 }
5873
5874 if (payment_id8 != crypto::null_hash8)
5875 message_writer() <<
5876 tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead");
5877
5878 crypto::hash payment_id = crypto::null_hash;
5879 if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
5880 message_writer(console_color_red, false) <<
5881 tr("WARNING: this transaction uses an unencrypted payment ID: these are obsolete and ignored. Use subaddresses instead.");
5882 }
5883 if (unlock_time && !cryptonote::is_coinbase(tx))
5884 message_writer() << tr("NOTE: This transaction is locked, see details with: show_transfer ") + epee::string_tools::pod_to_hex(txid);
5885 if (m_auto_refresh_refreshing)
5886 m_cmd_binder.print_prompt();
5887 else
5888 m_refresh_progress_reporter.update(height, true);
5889 }
5890 //----------------------------------------------------------------------------------------------------
5891 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)
5892 {
5893 if (m_locked)
5894 return;
5895 // Not implemented in CLI wallet
5896 }
5897 //----------------------------------------------------------------------------------------------------
5898 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)
5899 {
5900 if (m_locked)
5901 return;
5902 message_writer(console_color_magenta, false) << "\r" <<
5903 tr("Height ") << height << ", " <<
5904 tr("txid ") << txid << ", " <<
5905 tr("spent ") << print_money(amount) << ", " <<
5906 tr("idx ") << subaddr_index;
5907 if (m_auto_refresh_refreshing)
5908 m_cmd_binder.print_prompt();
5909 else
5910 m_refresh_progress_reporter.update(height, true);
5911 }
5912 //----------------------------------------------------------------------------------------------------
5913 void simple_wallet::on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx)
5914 {
5915 if (m_locked)
5916 return;
5917 }
5918 //----------------------------------------------------------------------------------------------------
5919 boost::optional<epee::wipeable_string> simple_wallet::on_get_password(const char *reason)
5920 {
5921 if (m_locked)
5922 return boost::none;
5923 // can't ask for password from a background thread
5924 if (!m_in_manual_refresh.load(std::memory_order_relaxed))
5925 {
5926 message_writer(console_color_red, false) << boost::format(tr("Password needed (%s) - use the refresh command")) % reason;
5927 m_cmd_binder.print_prompt();
5928 return boost::none;
5929 }
5930
5931 PAUSE_READLINE();
5932 std::string msg = tr("Enter password");
5933 if (reason && *reason)
5934 msg += std::string(" (") + reason + ")";
5935 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5936 if (!pwd_container)
5937 {
5938 MERROR("Failed to read password");
5939 return boost::none;
5940 }
5941
5942 return pwd_container->password();
5943 }
5944 //----------------------------------------------------------------------------------------------------
5945 void simple_wallet::on_device_button_request(uint64_t code)
5946 {
5947 message_writer(console_color_white, false) << tr("Device requires attention");
5948 }
5949 //----------------------------------------------------------------------------------------------------
5950 boost::optional<epee::wipeable_string> simple_wallet::on_device_pin_request()
5951 {
5952 PAUSE_READLINE();
5953 std::string msg = tr("Enter device PIN");
5954 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5955 THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device PIN"));
5956 return pwd_container->password();
5957 }
5958 //----------------------------------------------------------------------------------------------------
5959 boost::optional<epee::wipeable_string> simple_wallet::on_device_passphrase_request(bool & on_device)
5960 {
5961 if (on_device) {
5962 std::string accepted = input_line(tr(
5963 "Device asks for passphrase. Do you want to enter the passphrase on device (Y) (or on the host (N))?"));
5964 if (std::cin.eof() || command_line::is_yes(accepted)) {
5965 message_writer(console_color_white, true) << tr("Please enter the device passphrase on the device");
5966 return boost::none;
5967 }
5968 }
5969
5970 PAUSE_READLINE();
5971 on_device = false;
5972 std::string msg = tr("Enter device passphrase");
5973 auto pwd_container = tools::password_container::prompt(false, msg.c_str());
5974 THROW_WALLET_EXCEPTION_IF(!pwd_container, tools::error::password_entry_failed, tr("Failed to read device passphrase"));
5975 return pwd_container->password();
5976 }
5977 //----------------------------------------------------------------------------------------------------
5978 void simple_wallet::on_refresh_finished(uint64_t start_height, uint64_t fetched_blocks, bool is_init, bool received_money)
5979 {
5980 const uint64_t rfbh = m_wallet->get_refresh_from_block_height();
5981 std::string err;
5982 const uint64_t dh = m_wallet->get_daemon_blockchain_height(err);
5983 if (err.empty() && rfbh > dh)
5984 {
5985 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");
5986 }
5987
5988 // Key image sync after the first refresh
5989 if (!m_wallet->get_account().get_device().has_tx_cold_sign() || m_wallet->get_account().get_device().has_ki_live_refresh()) {
5990 return;
5991 }
5992
5993 if (!received_money || m_wallet->get_device_last_key_image_sync() != 0) {
5994 return;
5995 }
5996
5997 // Finished first refresh for HW device and money received -> KI sync
5998 message_writer() << "\n" << tr("The first refresh has finished for the HW-based wallet with received money. hw_key_images_sync is needed. ");
5999
6000 std::string accepted = input_line(tr("Do you want to do it now? (Y/Yes/N/No): "));
6001 if (std::cin.eof() || !command_line::is_yes(accepted)) {
6002 message_writer(console_color_red, false) << tr("hw_key_images_sync skipped. Run command manually before a transfer.");
6003 return;
6004 }
6005
6006 key_images_sync_intern();
6007 }
6008 //----------------------------------------------------------------------------------------------------
6009 bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bool is_init)
6010 {
6011 if (!try_connect_to_daemon(is_init))
6012 return true;
6013
6014 LOCK_IDLE_SCOPE();
6015
6016 crypto::hash transfer_hash_pre{};
6017 uint64_t height_pre = 0, height_post;
6018 if (reset != ResetNone)
6019 {
6020 if (reset == ResetSoftKeepKI)
6021 height_pre = m_wallet->hash_m_transfers(boost::none, transfer_hash_pre);
6022
6023 m_wallet->rescan_blockchain(reset == ResetHard, false, reset == ResetSoftKeepKI);
6024 }
6025
6026 PAUSE_READLINE();
6027
6028 message_writer() << tr("Starting refresh...");
6029
6030 uint64_t fetched_blocks = 0;
6031 bool received_money = false;
6032 bool ok = false;
6033 std::ostringstream ss;
6034 try
6035 {
6036 m_in_manual_refresh.store(true, std::memory_order_relaxed);
6037 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);});
6038 // For manual refresh don't allow incremental checking of the pool: Because we did not process the txs
6039 // for us in the pool during automatic refresh we could miss some of them if we checked the pool
6040 // incrementally here
6041 m_wallet->refresh(m_wallet->is_trusted_daemon(), start_height, fetched_blocks, received_money, true, false);
6042
6043 if (reset == ResetSoftKeepKI)
6044 {
6045 m_wallet->finish_rescan_bc_keep_key_images(height_pre, transfer_hash_pre);
6046
6047 height_post = m_wallet->get_num_transfer_details();
6048 if (height_pre != height_post)
6049 {
6050 message_writer() << tr("New transfer received since rescan was started. Key images are incomplete.");
6051 }
6052 }
6053
6054 ok = true;
6055 // Clear line "Height xxx of xxx"
6056 std::cout << "\r \r";
6057 success_msg_writer(true) << tr("Refresh done, blocks received: ") << fetched_blocks;
6058 if (is_init)
6059 print_accounts();
6060 show_balance_unlocked();
6061 on_refresh_finished(start_height, fetched_blocks, is_init, received_money);
6062 }
6063 catch (const tools::error::daemon_busy&)
6064 {
6065 ss << tr("daemon is busy. Please try again later.");
6066 }
6067 catch (const tools::error::no_connection_to_daemon&)
6068 {
6069 ss << tr("no connection to daemon. Please make sure daemon is running.");
6070 }
6071 catch (const tools::error::payment_required&)
6072 {
6073 ss << tr("payment required.");
6074 m_need_payment = true;
6075 }
6076 catch (const tools::error::wallet_rpc_error& e)
6077 {
6078 LOG_ERROR("RPC error: " << e.to_string());
6079 ss << tr("RPC error: ") << e.what();
6080 }
6081 catch (const tools::error::refresh_error& e)
6082 {
6083 LOG_ERROR("refresh error: " << e.to_string());
6084 ss << tr("refresh error: ") << e.what();
6085 }
6086 catch (const tools::error::wallet_internal_error& e)
6087 {
6088 LOG_ERROR("internal error: " << e.to_string());
6089 ss << tr("internal error: ") << e.what();
6090 }
6091 catch (const std::exception& e)
6092 {
6093 LOG_ERROR("unexpected error: " << e.what());
6094 ss << tr("unexpected error: ") << e.what();
6095 }
6096 catch (...)
6097 {
6098 LOG_ERROR("unknown error");
6099 ss << tr("unknown error");
6100 }
6101
6102 if (!ok)
6103 {
6104 fail_msg_writer() << tr("refresh failed: ") << ss.str() << ". " << tr("Blocks received: ") << fetched_blocks;
6105 }
6106
6107 // prevent it from triggering the idle screen due to waiting for a foreground refresh
6108 m_last_activity_time = time(NULL);
6109
6110 return true;
6111 }
6112 //----------------------------------------------------------------------------------------------------
6113 bool simple_wallet::refresh(const std::vector<std::string>& args)
6114 {
6115 uint64_t start_height = 0;
6116 if(!args.empty()){
6117 try
6118 {
6119 start_height = boost::lexical_cast<uint64_t>( args[0] );
6120 }
6121 catch(const boost::bad_lexical_cast &)
6122 {
6123 start_height = 0;
6124 }
6125 }
6126 return refresh_main(start_height, ResetNone);
6127 }
6128 //----------------------------------------------------------------------------------------------------
6129 bool simple_wallet::show_balance_unlocked(bool detailed)
6130 {
6131 std::string extra;
6132 if (m_wallet->has_multisig_partial_key_images())
6133 extra = tr(" (Some owned outputs have partial key images - import_multisig_info needed)");
6134 else if (m_wallet->has_unknown_key_images())
6135 extra += tr(" (Some owned outputs have missing key images - export_outputs, import_outputs, export_key_images, and import_key_images needed)");
6136 success_msg_writer() << tr("Currently selected account: [") << m_current_subaddress_account << tr("] ") << m_wallet->get_subaddress_label({m_current_subaddress_account, 0});
6137 const std::string tag = m_wallet->get_account_tags().second[m_current_subaddress_account];
6138 success_msg_writer() << tr("Tag: ") << (tag.empty() ? std::string{tr("(No tag assigned)")} : tag);
6139 uint64_t blocks_to_unlock, time_to_unlock;
6140 uint64_t unlocked_balance = m_wallet->unlocked_balance(m_current_subaddress_account, false, &blocks_to_unlock, &time_to_unlock);
6141 std::string unlock_time_message;
6142 if (blocks_to_unlock > 0 && time_to_unlock > 0)
6143 unlock_time_message = (boost::format(" (%lu block(s) and %s to unlock)") % blocks_to_unlock % get_human_readable_timespan(time_to_unlock)).str();
6144 else if (blocks_to_unlock > 0)
6145 unlock_time_message = (boost::format(" (%lu block(s) to unlock)") % blocks_to_unlock).str();
6146 else if (time_to_unlock > 0)
6147 unlock_time_message = (boost::format(" (%s to unlock)") % get_human_readable_timespan(time_to_unlock)).str();
6148 success_msg_writer() << tr("Balance: ") << print_money(m_wallet->balance(m_current_subaddress_account, false)) << ", "
6149 << tr("unlocked balance: ") << print_money(unlocked_balance) << unlock_time_message << extra;
6150 std::map<uint32_t, uint64_t> balance_per_subaddress = m_wallet->balance_per_subaddress(m_current_subaddress_account, false);
6151 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);
6152 if (!detailed || balance_per_subaddress.empty())
6153 return true;
6154 success_msg_writer() << tr("Balance per address:");
6155 success_msg_writer() << boost::format("%15s %21s %21s %7s %21s") % tr("Address") % tr("Balance") % tr("Unlocked balance") % tr("Outputs") % tr("Label");
6156 std::vector<tools::wallet2::transfer_details> transfers;
6157 m_wallet->get_transfers(transfers);
6158 for (const auto& i : balance_per_subaddress)
6159 {
6160 cryptonote::subaddress_index subaddr_index = {m_current_subaddress_account, i.first};
6161 std::string address_str = m_wallet->get_subaddress_as_str(subaddr_index).substr(0, 6);
6162 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; });
6163 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);
6164 }
6165 return true;
6166 }
6167 //----------------------------------------------------------------------------------------------------
6168 bool simple_wallet::show_balance(const std::vector<std::string>& args/* = std::vector<std::string>()*/)
6169 {
6170 if (args.size() > 1 || (args.size() == 1 && args[0] != "detail"))
6171 {
6172 PRINT_USAGE(USAGE_SHOW_BALANCE);
6173 return true;
6174 }
6175 LOCK_IDLE_SCOPE();
6176 show_balance_unlocked(args.size() == 1);
6177 return true;
6178 }
6179 //----------------------------------------------------------------------------------------------------
6180 bool simple_wallet::show_incoming_transfers(const std::vector<std::string>& args)
6181 {
6182 if (args.size() > 3)
6183 {
6184 PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
6185 return true;
6186 }
6187 auto local_args = args;
6188 LOCK_IDLE_SCOPE();
6189
6190 std::set<uint32_t> subaddr_indices;
6191 bool filter = false;
6192 bool available = false;
6193 bool verbose = false;
6194 bool uses = false;
6195 if (local_args.size() > 0)
6196 {
6197 if (local_args[0] == "available")
6198 {
6199 filter = true;
6200 available = true;
6201 local_args.erase(local_args.begin());
6202 }
6203 else if (local_args[0] == "unavailable")
6204 {
6205 filter = true;
6206 available = false;
6207 local_args.erase(local_args.begin());
6208 }
6209 }
6210 while (local_args.size() > 0)
6211 {
6212 if (local_args[0] == "verbose")
6213 verbose = true;
6214 else if (local_args[0] == "uses")
6215 uses = true;
6216 else if (local_args[0].substr(0, 6) == "index=")
6217 {
6218 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
6219 return true;
6220 }
6221 else
6222 {
6223 fail_msg_writer() << tr("Invalid keyword: ") << local_args.front();
6224 break;
6225 }
6226 local_args.erase(local_args.begin());
6227 }
6228
6229 const uint64_t blockchain_height = m_wallet->get_blockchain_current_height();
6230
6231 PAUSE_READLINE();
6232
6233 if (local_args.size() > 0)
6234 {
6235 PRINT_USAGE(USAGE_INCOMING_TRANSFERS);
6236 return true;
6237 }
6238
6239 tools::wallet2::transfer_container transfers;
6240 m_wallet->get_transfers(transfers);
6241
6242 size_t transfers_found = 0;
6243 for (const auto& td : transfers)
6244 {
6245 if (!filter || available != td.m_spent)
6246 {
6247 if (m_current_subaddress_account != td.m_subaddr_index.major || (!subaddr_indices.empty() && subaddr_indices.count(td.m_subaddr_index.minor) == 0))
6248 continue;
6249 if (!transfers_found)
6250 {
6251 std::string verbose_string;
6252 if (verbose)
6253 verbose_string = (boost::format("%68s%68s") % tr("pubkey") % tr("key image")).str();
6254 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;
6255 }
6256 std::string extra_string;
6257 if (verbose)
6258 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();
6259 if (uses)
6260 {
6261 std::vector<uint64_t> heights;
6262 uint64_t idx = 0;
6263 for (const auto &e: td.m_uses)
6264 {
6265 heights.push_back(e.first);
6266 if (e.first < td.m_spent_height)
6267 ++idx;
6268 }
6269 const std::pair<std::string, std::string> line = show_outputs_line(heights, blockchain_height, idx);
6270 extra_string += std::string("\n ") + tr("Used at heights: ") + line.first + "\n " + line.second;
6271 }
6272 message_writer(td.m_spent ? console_color_magenta : console_color_green, false) <<
6273 boost::format("%21s%8s%12s%8s%16u%68s%16u%s") %
6274 print_money(td.amount()) %
6275 (td.m_spent ? tr("T") : tr("F")) %
6276 (m_wallet->frozen(td) ? tr("[frozen]") : m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) %
6277 (td.is_rct() ? tr("RingCT") : tr("-")) %
6278 td.m_global_output_index %
6279 td.m_txid %
6280 td.m_subaddr_index.minor %
6281 extra_string;
6282 ++transfers_found;
6283 }
6284 }
6285
6286 if (!transfers_found)
6287 {
6288 if (!filter)
6289 {
6290 success_msg_writer() << tr("No incoming transfers");
6291 }
6292 else if (available)
6293 {
6294 success_msg_writer() << tr("No incoming available transfers");
6295 }
6296 else
6297 {
6298 success_msg_writer() << tr("No incoming unavailable transfers");
6299 }
6300 }
6301 else
6302 {
6303 success_msg_writer() << boost::format("Found %u/%u transfers") % transfers_found % transfers.size();
6304 }
6305
6306 return true;
6307 }
6308 //----------------------------------------------------------------------------------------------------
6309 bool simple_wallet::show_payments(const std::vector<std::string> &args)
6310 {
6311 if(args.empty())
6312 {
6313 PRINT_USAGE(USAGE_PAYMENTS);
6314 return true;
6315 }
6316
6317 LOCK_IDLE_SCOPE();
6318
6319 PAUSE_READLINE();
6320
6321 message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") %
6322 tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index");
6323
6324 bool payments_found = false;
6325 for(std::string arg : args)
6326 {
6327 crypto::hash payment_id;
6328 if(tools::wallet2::parse_payment_id(arg, payment_id))
6329 {
6330 std::list<tools::wallet2::payment_details> payments;
6331 m_wallet->get_payments(payment_id, payments);
6332 if(payments.empty())
6333 {
6334 success_msg_writer() << tr("No payments with id ") << payment_id;
6335 continue;
6336 }
6337
6338 for (const tools::wallet2::payment_details& pd : payments)
6339 {
6340 if(!payments_found)
6341 {
6342 payments_found = true;
6343 }
6344 success_msg_writer(true) <<
6345 boost::format("%68s%68s%12s%21s%16s%16s") %
6346 payment_id %
6347 pd.m_tx_hash %
6348 pd.m_block_height %
6349 print_money(pd.m_amount) %
6350 pd.m_unlock_time %
6351 pd.m_subaddr_index.minor;
6352 }
6353 }
6354 else
6355 {
6356 fail_msg_writer() << tr("payment ID has invalid format, expected 16 or 64 character hex string: ") << arg;
6357 }
6358 }
6359
6360 return true;
6361 }
6362 //----------------------------------------------------------------------------------------------------
6363 uint64_t simple_wallet::get_daemon_blockchain_height(std::string& err)
6364 {
6365 if (!m_wallet)
6366 {
6367 throw std::runtime_error("simple_wallet null wallet");
6368 }
6369 return m_wallet->get_daemon_blockchain_height(err);
6370 }
6371 //----------------------------------------------------------------------------------------------------
6372 bool simple_wallet::show_blockchain_height(const std::vector<std::string>& args)
6373 {
6374 if (!try_connect_to_daemon())
6375 return true;
6376
6377 std::string err;
6378 uint64_t bc_height = get_daemon_blockchain_height(err);
6379 if (err.empty())
6380 success_msg_writer() << bc_height;
6381 else
6382 fail_msg_writer() << tr("failed to get blockchain height: ") << err;
6383 return true;
6384 }
6385 //----------------------------------------------------------------------------------------------------
6386 bool simple_wallet::rescan_spent(const std::vector<std::string> &args)
6387 {
6388 CHECK_IF_BACKGROUND_SYNCING("cannot rescan spent");
6389 if (!m_wallet->is_trusted_daemon())
6390 {
6391 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
6392 return true;
6393 }
6394
6395 if (!try_connect_to_daemon())
6396 return true;
6397
6398 try
6399 {
6400 LOCK_IDLE_SCOPE();
6401 m_wallet->rescan_spent();
6402 }
6403 catch (const tools::error::daemon_busy&)
6404 {
6405 fail_msg_writer() << tr("daemon is busy. Please try again later.");
6406 }
6407 catch (const tools::error::no_connection_to_daemon&)
6408 {
6409 fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running.");
6410 }
6411 catch (const tools::error::payment_required&)
6412 {
6413 fail_msg_writer() << tr("payment required.");
6414 m_need_payment = true;
6415 }
6416 catch (const tools::error::is_key_image_spent_error&)
6417 {
6418 fail_msg_writer() << tr("failed to get spent status");
6419 }
6420 catch (const tools::error::wallet_rpc_error& e)
6421 {
6422 LOG_ERROR("RPC error: " << e.to_string());
6423 fail_msg_writer() << tr("RPC error: ") << e.what();
6424 }
6425 catch (const std::exception& e)
6426 {
6427 LOG_ERROR("unexpected error: " << e.what());
6428 fail_msg_writer() << tr("unexpected error: ") << e.what();
6429 }
6430 catch (...)
6431 {
6432 LOG_ERROR("unknown error");
6433 fail_msg_writer() << tr("unknown error");
6434 }
6435
6436 return true;
6437 }
6438 //----------------------------------------------------------------------------------------------------
6439 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
6440 {
6441 std::stringstream ostr;
6442
6443 for (uint64_t h: heights)
6444 blockchain_height = std::max(blockchain_height, h);
6445
6446 for (size_t j = 0; j < heights.size(); ++j)
6447 ostr << (j == highlight_idx ? " *" : " ") << heights[j];
6448
6449 // visualize the distribution, using the code by moneroexamples onion-monero-viewer
6450 const uint64_t resolution = 79;
6451 std::string ring_str(resolution, '_');
6452 for (size_t j = 0; j < heights.size(); ++j)
6453 {
6454 uint64_t pos = (heights[j] * resolution) / blockchain_height;
6455 ring_str[pos] = 'o';
6456 }
6457 if (highlight_idx < heights.size() && heights[highlight_idx] < blockchain_height)
6458 {
6459 uint64_t pos = (heights[highlight_idx] * resolution) / blockchain_height;
6460 ring_str[pos] = '*';
6461 }
6462
6463 return std::make_pair(ostr.str(), ring_str);
6464 }
6465 //----------------------------------------------------------------------------------------------------
6466 bool simple_wallet::process_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr, bool verbose)
6467 {
6468 uint32_t version;
6469 if (!try_connect_to_daemon(false, &version))
6470 {
6471 fail_msg_writer() << tr("failed to connect to daemon");
6472 return false;
6473 }
6474 // available for RPC version 1.4 or higher
6475 if (version < MAKE_CORE_RPC_VERSION(1, 4))
6476 return true;
6477 std::string err;
6478 uint64_t blockchain_height = get_daemon_blockchain_height(err);
6479 if (!err.empty())
6480 {
6481 fail_msg_writer() << tr("failed to get blockchain height: ") << err;
6482 return false;
6483 }
6484 // for each transaction
6485 for (size_t n = 0; n < ptx_vector.size(); ++n)
6486 {
6487 const cryptonote::transaction& tx = ptx_vector[n].tx;
6488 const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data;
6489 if (verbose)
6490 ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx);
6491 // for each input
6492 std::vector<uint64_t> spent_key_height(tx.vin.size());
6493 std::vector<crypto::hash> spent_key_txid (tx.vin.size());
6494 for (size_t i = 0; i < tx.vin.size(); ++i)
6495 {
6496 if (tx.vin[i].type() != typeid(cryptonote::txin_to_key))
6497 continue;
6498 const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]);
6499 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(construction_data.selected_transfers[i]);
6500 const cryptonote::tx_source_entry *sptr = NULL;
6501 for (const auto &src: construction_data.sources)
6502 if (src.outputs[src.real_output].second.dest == td.get_public_key())
6503 sptr = &src;
6504 if (!sptr)
6505 {
6506 fail_msg_writer() << tr("failed to find construction data for tx input");
6507 return false;
6508 }
6509 const cryptonote::tx_source_entry& source = *sptr;
6510
6511 if (verbose)
6512 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);
6513 // convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount
6514 std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets);
6515 // get block heights from which those ring member keys originated
6516 COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req);
6517 req.outputs.resize(absolute_offsets.size());
6518 for (size_t j = 0; j < absolute_offsets.size(); ++j)
6519 {
6520 req.outputs[j].amount = in_key.amount;
6521 req.outputs[j].index = absolute_offsets[j];
6522 }
6523 COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res);
6524 req.get_txid = true;
6525 req.client = cryptonote::make_rpc_payment_signature(m_wallet->get_rpc_client_secret_key());
6526 bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res);
6527 err = interpret_rpc_response(r, res.status);
6528 if (!err.empty())
6529 {
6530 fail_msg_writer() << tr("failed to get output: ") << err;
6531 return false;
6532 }
6533 // make sure that returned block heights are less than blockchain height
6534 for (auto& res_out : res.outs)
6535 {
6536 if (res_out.height >= blockchain_height)
6537 {
6538 fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height");
6539 return false;
6540 }
6541 }
6542 if (verbose)
6543 ostr << tr("\nOriginating block heights: ");
6544 spent_key_height[i] = res.outs[source.real_output].height;
6545 spent_key_txid [i] = res.outs[source.real_output].txid;
6546 std::vector<uint64_t> heights(absolute_offsets.size(), 0);
6547 for (size_t j = 0; j < absolute_offsets.size(); ++j)
6548 {
6549 heights[j] = res.outs[j].height;
6550 }
6551 std::pair<std::string, std::string> ring_str = show_outputs_line(heights, blockchain_height, source.real_output);
6552 if (verbose)
6553 ostr << ring_str.first << tr("\n|") << ring_str.second << tr("|\n");
6554 }
6555 // warn if rings contain keys originating from the same tx or temporally very close block heights
6556 bool are_keys_from_same_tx = false;
6557 bool are_keys_from_close_height = false;
6558 for (size_t i = 0; i < tx.vin.size(); ++i) {
6559 for (size_t j = i + 1; j < tx.vin.size(); ++j)
6560 {
6561 if (spent_key_txid[i] == spent_key_txid[j])
6562 are_keys_from_same_tx = true;
6563 if (std::abs((int64_t)(spent_key_height[i] - spent_key_height[j])) < (int64_t)5)
6564 are_keys_from_close_height = true;
6565 }
6566 }
6567 if (are_keys_from_same_tx || are_keys_from_close_height)
6568 {
6569 ostr
6570 << tr("\nWarning: Some input keys being spent are from ")
6571 << (are_keys_from_same_tx ? tr("the same transaction") : tr("blocks that are temporally very close"))
6572 << tr(", which can break the anonymity of ring signatures. Make sure this is intentional!");
6573 }
6574 ostr << ENDL;
6575 }
6576 return true;
6577 }
6578 //----------------------------------------------------------------------------------------------------
6579 bool simple_wallet::prompt_if_old(const std::vector<tools::wallet2::pending_tx> &ptx_vector)
6580 {
6581 // count the number of old outputs
6582 std::string err;
6583 uint64_t bc_height = get_daemon_blockchain_height(err);
6584 if (!err.empty())
6585 return true;
6586
6587 int max_n_old = 0;
6588 for (const auto &ptx: ptx_vector)
6589 {
6590 int n_old = 0;
6591 for (const auto i: ptx.selected_transfers)
6592 {
6593 const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(i);
6594 uint64_t age = bc_height - td.m_block_height;
6595 if (age > OLD_AGE_WARN_THRESHOLD)
6596 ++n_old;
6597 }
6598 max_n_old = std::max(max_n_old, n_old);
6599 }
6600 if (max_n_old > 1)
6601 {
6602 std::stringstream prompt;
6603 prompt << tr("Transaction spends more than one very old output. Privacy would be better if they were sent separately.");
6604 prompt << ENDL << tr("Spend them now anyway?");
6605 std::string accepted = input_line(prompt.str(), true);
6606 if (std::cin.eof())
6607 return false;
6608 if (!command_line::is_yes(accepted))
6609 {
6610 return false;
6611 }
6612 }
6613 return true;
6614 }
6615 //----------------------------------------------------------------------------------------------------
6616 void simple_wallet::check_for_inactivity_lock(bool user)
6617 {
6618 if (m_locked)
6619 {
6620 #ifdef HAVE_READLINE
6621 PAUSE_READLINE();
6622 rdln::clear_screen();
6623 #endif
6624 tools::clear_screen();
6625 m_in_command = true;
6626 if (!user)
6627 {
6628 const std::string speech = tr("I locked your Monero wallet to protect you while you were away\nsee \"help set\" to configure/disable");
6629 std::vector<std::pair<std::string, size_t>> lines = tools::split_string_by_width(speech, 45);
6630
6631 size_t max_len = 0;
6632 for (const auto &i: lines)
6633 max_len = std::max(max_len, i.second);
6634 const size_t n_u = max_len + 2;
6635 tools::msg_writer() << " " << std::string(n_u, '_');
6636 for (size_t i = 0; i < lines.size(); ++i)
6637 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 ? "/" : "|");
6638 tools::msg_writer() << " " << std::string(n_u, '-') << std::endl <<
6639 " \\ (__)" << std::endl <<
6640 " \\ (oo)\\_______" << std::endl <<
6641 " (__)\\ )\\/\\" << std::endl <<
6642 " ||----w |" << std::endl <<
6643 " || ||" << std::endl <<
6644 "" << std::endl;
6645 }
6646
6647 bool started_background_sync = false;
6648 if (!m_wallet->is_background_wallet() &&
6649 m_wallet->background_sync_type() != tools::wallet2::BackgroundSyncOff)
6650 {
6651 LOCK_IDLE_SCOPE();
6652 m_wallet->start_background_sync();
6653 started_background_sync = true;
6654 }
6655
6656 while (1)
6657 {
6658 const char *inactivity_msg = user ? "" : tr("Locked due to inactivity.");
6659 tools::msg_writer() << inactivity_msg << (inactivity_msg[0] ? " " : "") << (
6660 (m_wallet->is_background_wallet() && m_wallet->background_sync_type() == tools::wallet2::BackgroundSyncCustomPassword)
6661 ? tr("The background password is required to unlock the console.")
6662 : tr("The wallet password is required to unlock the console.")
6663 );
6664
6665 if (m_wallet->is_background_syncing())
6666 tools::msg_writer() << tr("\nSyncing in the background while locked...") << std::endl;
6667
6668 const bool show_wallet_name = m_wallet->show_wallet_name_when_locked();
6669 if (show_wallet_name)
6670 {
6671 tools::msg_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
6672 tools::msg_writer() << tr("Network type: ") << (
6673 m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
6674 m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet")
6675 );
6676 }
6677 try
6678 {
6679 const auto pwd_container = get_and_verify_password();
6680 if (pwd_container)
6681 {
6682 if (started_background_sync)
6683 {
6684 LOCK_IDLE_SCOPE();
6685 m_wallet->stop_background_sync(pwd_container->password());
6686 }
6687 break;
6688 }
6689 }
6690 catch (...) { /* do nothing, just let the loop loop */ }
6691 }
6692 m_last_activity_time = time(NULL);
6693 m_in_command = false;
6694 m_locked = false;
6695 }
6696 }
6697 //----------------------------------------------------------------------------------------------------
6698 bool simple_wallet::on_command(bool (simple_wallet::*cmd)(const std::vector<std::string>&), const std::vector<std::string> &args)
6699 {
6700 m_last_activity_time = time(NULL);
6701
6702 m_in_command = true;
6703 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
6704 m_last_activity_time = time(NULL);
6705 m_in_command = false;
6706 });
6707
6708 check_for_inactivity_lock(false);
6709 return (this->*cmd)(args);
6710 }
6711 //----------------------------------------------------------------------------------------------------
6712 bool simple_wallet::transfer_main(const std::vector<std::string> &args_, bool called_by_mms)
6713 {
6714 // "transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <amount> [<payment_id>]"
6715 CHECK_IF_BACKGROUND_SYNCING("cannot transfer");
6716 if (!try_connect_to_daemon())
6717 return false;
6718
6719 std::vector<std::string> local_args = args_;
6720
6721 std::set<uint32_t> subaddr_indices;
6722 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
6723 {
6724 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
6725 return false;
6726 local_args.erase(local_args.begin());
6727 }
6728
6729 uint32_t priority = m_wallet->get_default_priority();
6730 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
6731 local_args.erase(local_args.begin());
6732
6733 priority = m_wallet->adjust_priority(priority);
6734
6735 const size_t min_ring_size = m_wallet->get_min_ring_size();
6736 size_t fake_outs_count = min_ring_size - 1;
6737 if(local_args.size() > 0) {
6738 size_t ring_size;
6739 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
6740 {
6741 }
6742 else if (ring_size == 0)
6743 {
6744 fail_msg_writer() << tr("Ring size must not be 0");
6745 return false;
6746 }
6747 else
6748 {
6749 fake_outs_count = ring_size - 1;
6750 local_args.erase(local_args.begin());
6751 }
6752 }
6753 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
6754 if (adjusted_fake_outs_count > fake_outs_count)
6755 {
6756 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();
6757 return false;
6758 }
6759 if (adjusted_fake_outs_count < fake_outs_count)
6760 {
6761 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();
6762 return false;
6763 }
6764
6765 const size_t min_args = 1;
6766 if(local_args.size() < min_args)
6767 {
6768 fail_msg_writer() << tr("wrong number of arguments");
6769 return false;
6770 }
6771
6772 std::vector<uint8_t> extra;
6773 bool payment_id_seen = false;
6774 if (!local_args.empty())
6775 {
6776 std::string payment_id_str = local_args.back();
6777 crypto::hash payment_id;
6778 bool r = true;
6779 if (tools::wallet2::parse_long_payment_id(payment_id_str, payment_id))
6780 {
6781 LONG_PAYMENT_ID_SUPPORT_CHECK();
6782 }
6783 if(!r)
6784 {
6785 fail_msg_writer() << tr("payment id failed to encode");
6786 return false;
6787 }
6788 }
6789
6790 // Parse subtractfeefrom destination list
6791 tools::wallet2::unique_index_container subtract_fee_from_outputs;
6792 bool subtract_fee_from_all = false;
6793 for (auto it = local_args.begin(); it < local_args.end();)
6794 {
6795 bool matches = false;
6796 if (!parse_subtract_fee_from_outputs(*it, subtract_fee_from_outputs, subtract_fee_from_all, matches))
6797 {
6798 return false;
6799 }
6800 else if (matches)
6801 {
6802 it = local_args.erase(it);
6803 break;
6804 }
6805 else
6806 {
6807 ++it;
6808 }
6809 }
6810
6811 vector<cryptonote::address_parse_info> dsts_info;
6812 vector<cryptonote::tx_destination_entry> dsts;
6813 for (size_t i = 0; i < local_args.size(); )
6814 {
6815 dsts_info.emplace_back();
6816 cryptonote::address_parse_info & info = dsts_info.back();
6817 cryptonote::tx_destination_entry de;
6818 bool r = true;
6819
6820 // check for a URI
6821 std::string address_uri, payment_id_uri, tx_description, recipient_name, error;
6822 std::vector<std::string> unknown_parameters;
6823 uint64_t amount = 0;
6824 bool has_uri = m_wallet->parse_uri(local_args[i], address_uri, payment_id_uri, amount, tx_description, recipient_name, unknown_parameters, error);
6825 if (has_uri)
6826 {
6827 r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_uri, oa_prompter);
6828 if (payment_id_uri.size() == 16)
6829 {
6830 if (!tools::wallet2::parse_short_payment_id(payment_id_uri, info.payment_id))
6831 {
6832 fail_msg_writer() << tr("failed to parse short payment ID from URI");
6833 return false;
6834 }
6835 info.has_payment_id = true;
6836 }
6837 de.amount = amount;
6838 de.original = local_args[i];
6839 ++i;
6840 }
6841 else if (i + 1 < local_args.size())
6842 {
6843 r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[i], oa_prompter);
6844 bool ok = cryptonote::parse_amount(de.amount, local_args[i + 1]);
6845 if(!ok || 0 == de.amount)
6846 {
6847 fail_msg_writer() << tr("amount is wrong: ") << local_args[i] << ' ' << local_args[i + 1] <<
6848 ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
6849 return false;
6850 }
6851 de.original = local_args[i];
6852 i += 2;
6853 }
6854 else
6855 {
6856 if (boost::starts_with(local_args[i], "monero:"))
6857 fail_msg_writer() << tr("Invalid last argument: ") << local_args.back() << ": " << error;
6858 else
6859 fail_msg_writer() << tr("Invalid last argument: ") << local_args.back();
6860 return false;
6861 }
6862
6863 if (!r)
6864 {
6865 fail_msg_writer() << tr("failed to parse address");
6866 return false;
6867 }
6868 de.addr = info.address;
6869 de.is_subaddress = info.is_subaddress;
6870 de.is_integrated = info.has_payment_id;
6871
6872 if (info.has_payment_id || !payment_id_uri.empty())
6873 {
6874 if (payment_id_seen)
6875 {
6876 fail_msg_writer() << tr("a single transaction cannot use more than one payment id");
6877 return false;
6878 }
6879
6880 crypto::hash payment_id;
6881 std::string extra_nonce;
6882 if (info.has_payment_id)
6883 {
6884 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
6885 }
6886 else if (tools::wallet2::parse_payment_id(payment_id_uri, payment_id))
6887 {
6888 LONG_PAYMENT_ID_SUPPORT_CHECK();
6889 }
6890 else
6891 {
6892 fail_msg_writer() << tr("failed to parse payment id, though it was detected");
6893 return false;
6894 }
6895 bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
6896 if(!r)
6897 {
6898 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
6899 return false;
6900 }
6901 payment_id_seen = true;
6902 }
6903
6904 dsts.push_back(de);
6905 }
6906
6907 if (subtract_fee_from_all)
6908 {
6909 subtract_fee_from_outputs.clear();
6910 for (decltype(subtract_fee_from_outputs)::value_type i = 0; i < dsts.size(); ++i)
6911 subtract_fee_from_outputs.insert(i);
6912 }
6913
6914 SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return false;);
6915
6916 try
6917 {
6918 // figure out what tx will be necessary
6919 auto ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, priority, extra,
6920 m_current_subaddress_account, subaddr_indices, subtract_fee_from_outputs);
6921
6922 if (ptx_vector.empty())
6923 {
6924 fail_msg_writer() << tr("No outputs found, or daemon is not ready");
6925 return false;
6926 }
6927
6928 // if we need to check for backlog, check the worst case tx
6929 if (m_wallet->confirm_backlog())
6930 {
6931 std::stringstream prompt;
6932 double worst_fee_per_byte = std::numeric_limits<double>::max();
6933 for (size_t n = 0; n < ptx_vector.size(); ++n)
6934 {
6935 const uint64_t blob_size = cryptonote::tx_to_blob(ptx_vector[n].tx).size();
6936 const double fee_per_byte = ptx_vector[n].fee / (double)blob_size;
6937 if (fee_per_byte < worst_fee_per_byte)
6938 {
6939 worst_fee_per_byte = fee_per_byte;
6940 }
6941 }
6942 try
6943 {
6944 std::vector<std::pair<uint64_t, uint64_t>> nblocks = m_wallet->estimate_backlog({std::make_pair(worst_fee_per_byte, worst_fee_per_byte)});
6945 if (nblocks.size() != 1)
6946 {
6947 prompt << "Internal error checking for backlog. " << tr("Is this okay anyway?");
6948 }
6949 else
6950 {
6951 if (nblocks[0].first > m_wallet->get_confirm_backlog_threshold())
6952 prompt << (boost::format(tr("There is currently a %u block backlog at that fee level. Is this okay?")) % nblocks[0].first).str();
6953 }
6954 }
6955 catch (const std::exception &e)
6956 {
6957 prompt << tr("Failed to check for backlog: ") << e.what() << ENDL << tr("Is this okay anyway?");
6958 }
6959
6960 std::string prompt_str = prompt.str();
6961 if (!prompt_str.empty())
6962 {
6963 std::string accepted = input_line(prompt_str, true);
6964 if (std::cin.eof())
6965 return false;
6966 if (!command_line::is_yes(accepted))
6967 {
6968 fail_msg_writer() << tr("transaction cancelled.");
6969
6970 return false;
6971 }
6972 }
6973 }
6974
6975 if (!prompt_if_old(ptx_vector))
6976 {
6977 fail_msg_writer() << tr("transaction cancelled.");
6978 return false;
6979 }
6980
6981 // if more than one tx necessary, prompt user to confirm
6982 if (m_wallet->always_confirm_transfers() || ptx_vector.size() > 1)
6983 {
6984 uint64_t total_sent = 0;
6985 uint64_t total_fee = 0;
6986 uint64_t dust_not_in_fee = 0;
6987 uint64_t dust_in_fee = 0;
6988 uint64_t change = 0;
6989 for (size_t n = 0; n < ptx_vector.size(); ++n)
6990 {
6991 total_fee += ptx_vector[n].fee;
6992 for (auto i: ptx_vector[n].selected_transfers)
6993 total_sent += m_wallet->get_transfer_details(i).amount();
6994 total_sent -= ptx_vector[n].change_dts.amount + ptx_vector[n].fee;
6995 change += ptx_vector[n].change_dts.amount;
6996
6997 if (ptx_vector[n].dust_added_to_fee)
6998 dust_in_fee += ptx_vector[n].dust;
6999 else
7000 dust_not_in_fee += ptx_vector[n].dust;
7001 }
7002
7003 std::stringstream prompt;
7004 for (size_t n = 0; n < ptx_vector.size(); ++n)
7005 {
7006 prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
7007 subaddr_indices.clear();
7008 for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
7009 subaddr_indices.insert(i);
7010 for (uint32_t i : subaddr_indices)
7011 prompt << boost::format(tr("Spending from address index %d\n")) % i;
7012 if (subaddr_indices.size() > 1)
7013 prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
7014 }
7015 prompt << boost::format(tr("Sending %s. ")) % print_money(total_sent);
7016 if (ptx_vector.size() > 1)
7017 {
7018 prompt << boost::format(tr("Your transaction needs to be split into %llu transactions. "
7019 "This will result in a transaction fee being applied to each transaction, for a total fee of %s")) %
7020 ((unsigned long long)ptx_vector.size()) % print_money(total_fee);
7021 }
7022 else
7023 {
7024 prompt << boost::format(tr("The transaction fee is %s")) %
7025 print_money(total_fee);
7026 }
7027 if (dust_in_fee != 0) prompt << boost::format(tr(", of which %s is dust from change")) % print_money(dust_in_fee);
7028 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"))
7029 % print_money(dust_not_in_fee);
7030 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7031 return false;
7032 bool default_ring_size = true;
7033 for (const auto &ptx: ptx_vector)
7034 {
7035 for (const auto &vin: ptx.tx.vin)
7036 {
7037 if (vin.type() == typeid(txin_to_key))
7038 {
7039 const txin_to_key& in_to_key = boost::get<txin_to_key>(vin);
7040 if (in_to_key.key_offsets.size() != min_ring_size)
7041 default_ring_size = false;
7042 }
7043 }
7044 }
7045 if (m_wallet->confirm_non_default_ring_size() && !default_ring_size)
7046 {
7047 prompt << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
7048 }
7049 prompt << ENDL << tr("Is this okay?");
7050
7051 std::string accepted = input_line(prompt.str(), true);
7052 if (std::cin.eof())
7053 return false;
7054 if (!command_line::is_yes(accepted))
7055 {
7056 fail_msg_writer() << tr("transaction cancelled.");
7057
7058 return false;
7059 }
7060 }
7061
7062 // actually commit the transactions
7063 if (m_wallet->multisig() && called_by_mms)
7064 {
7065 std::string ciphertext = m_wallet->save_multisig_tx(ptx_vector);
7066 if (!ciphertext.empty())
7067 {
7068 get_message_store().process_wallet_created_data(get_multisig_wallet_state(), mms::message_type::partially_signed_tx, ciphertext);
7069 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to MMS");
7070 }
7071 }
7072 else if (m_wallet->multisig())
7073 {
7074 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7075 if (!r)
7076 {
7077 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7078 return false;
7079 }
7080 else
7081 {
7082 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7083 }
7084 }
7085 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7086 {
7087 try
7088 {
7089 tools::wallet2::signed_tx_set signed_tx;
7090 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7091 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7092 return false;
7093 }
7094
7095 commit_or_save(signed_tx.ptx, m_do_not_relay);
7096 }
7097 catch (const std::exception& e)
7098 {
7099 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7100 return false;
7101 }
7102 catch (...)
7103 {
7104 LOG_ERROR("Unknown error");
7105 fail_msg_writer() << tr("unknown error");
7106 return false;
7107 }
7108 }
7109 else if (m_wallet->watch_only())
7110 {
7111 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7112 if (!r)
7113 {
7114 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7115 return false;
7116 }
7117 else
7118 {
7119 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7120 }
7121 }
7122 else
7123 {
7124 commit_or_save(ptx_vector, m_do_not_relay);
7125 }
7126 }
7127 catch (const std::exception &e)
7128 {
7129 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7130 return false;
7131 }
7132 catch (...)
7133 {
7134 LOG_ERROR("unknown error");
7135 fail_msg_writer() << tr("unknown error");
7136 return false;
7137 }
7138
7139 return true;
7140 }
7141 //----------------------------------------------------------------------------------------------------
7142 bool simple_wallet::transfer(const std::vector<std::string> &args_)
7143 {
7144 CHECK_IF_BACKGROUND_SYNCING("cannot transfer");
7145 if (args_.size() < 1)
7146 {
7147 PRINT_USAGE(USAGE_TRANSFER);
7148 return true;
7149 }
7150 transfer_main(args_, false);
7151 return true;
7152 }
7153 //----------------------------------------------------------------------------------------------------
7154
7155 bool simple_wallet::sweep_unmixable(const std::vector<std::string> &args_)
7156 {
7157 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7158 if (!try_connect_to_daemon())
7159 return true;
7160
7161 SCOPED_WALLET_UNLOCK();
7162
7163 try
7164 {
7165 // figure out what tx will be necessary
7166 auto ptx_vector = m_wallet->create_unmixable_sweep_transactions();
7167
7168 if (ptx_vector.empty())
7169 {
7170 fail_msg_writer() << tr("No unmixable outputs found");
7171 return true;
7172 }
7173
7174 // give user total and fee, and prompt to confirm
7175 uint64_t total_fee = 0, total_unmixable = 0;
7176 for (size_t n = 0; n < ptx_vector.size(); ++n)
7177 {
7178 total_fee += ptx_vector[n].fee;
7179 for (auto i: ptx_vector[n].selected_transfers)
7180 total_unmixable += m_wallet->get_transfer_details(i).amount();
7181 }
7182
7183 std::string prompt_str = tr("Sweeping ") + print_money(total_unmixable);
7184 if (ptx_vector.size() > 1) {
7185 prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
7186 print_money(total_unmixable) %
7187 ((unsigned long long)ptx_vector.size()) %
7188 print_money(total_fee)).str();
7189 }
7190 else {
7191 prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7192 print_money(total_unmixable) %
7193 print_money(total_fee)).str();
7194 }
7195 std::string accepted = input_line(prompt_str, true);
7196 if (std::cin.eof())
7197 return true;
7198 if (!command_line::is_yes(accepted))
7199 {
7200 fail_msg_writer() << tr("transaction cancelled.");
7201
7202 return true;
7203 }
7204
7205 // actually commit the transactions
7206 if (m_wallet->multisig())
7207 {
7208 CHECK_MULTISIG_ENABLED();
7209 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7210 if (!r)
7211 {
7212 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7213 }
7214 else
7215 {
7216 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7217 }
7218 }
7219 else if (m_wallet->watch_only())
7220 {
7221 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7222 if (!r)
7223 {
7224 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7225 }
7226 else
7227 {
7228 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7229 }
7230 }
7231 else
7232 {
7233 commit_or_save(ptx_vector, m_do_not_relay);
7234 }
7235 }
7236 catch (const tools::error::not_enough_unlocked_money& e)
7237 {
7238 fail_msg_writer() << tr("Not enough money in unlocked balance");
7239 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);
7240 if (std::cin.eof())
7241 return true;
7242 if (command_line::is_yes(accepted))
7243 {
7244 try
7245 {
7246 m_wallet->discard_unmixable_outputs();
7247 } catch (...) {}
7248 }
7249 }
7250 catch (const std::exception &e)
7251 {
7252 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7253 }
7254 catch (...)
7255 {
7256 LOG_ERROR("unknown error");
7257 fail_msg_writer() << tr("unknown error");
7258 }
7259
7260 return true;
7261 }
7262 //----------------------------------------------------------------------------------------------------
7263 bool simple_wallet::sweep_main(uint32_t account, uint64_t below, const std::vector<std::string> &args_)
7264 {
7265 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7266 auto print_usage = [this, account, below]()
7267 {
7268 if (below)
7269 {
7270 PRINT_USAGE(USAGE_SWEEP_BELOW);
7271 }
7272 else if (account == m_current_subaddress_account)
7273 {
7274 PRINT_USAGE(USAGE_SWEEP_ALL);
7275 }
7276 else
7277 {
7278 PRINT_USAGE(USAGE_SWEEP_ACCOUNT);
7279 }
7280 };
7281 if (args_.size() == 0)
7282 {
7283 fail_msg_writer() << tr("No address given");
7284 print_usage();
7285 return true;
7286 }
7287
7288 if (!try_connect_to_daemon())
7289 return true;
7290
7291 std::vector<std::string> local_args = args_;
7292
7293 std::set<uint32_t> subaddr_indices;
7294 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
7295 {
7296 if (local_args[0] == "index=all")
7297 {
7298 for (uint32_t i = 0; i < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++i)
7299 subaddr_indices.insert(i);
7300 }
7301 else if (!parse_subaddress_indices(local_args[0], subaddr_indices))
7302 {
7303 print_usage();
7304 return true;
7305 }
7306 local_args.erase(local_args.begin());
7307 }
7308
7309 uint32_t priority = 0;
7310 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
7311 local_args.erase(local_args.begin());
7312
7313 priority = m_wallet->adjust_priority(priority);
7314
7315 size_t fake_outs_count = m_wallet->get_min_ring_size() - 1;
7316 if(local_args.size() > 0) {
7317 size_t ring_size;
7318 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
7319 {
7320 }
7321 else if (ring_size == 0)
7322 {
7323 fail_msg_writer() << tr("Ring size must not be 0");
7324 return true;
7325 }
7326 else
7327 {
7328 fake_outs_count = ring_size - 1;
7329 local_args.erase(local_args.begin());
7330 }
7331 }
7332 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
7333 if (adjusted_fake_outs_count > fake_outs_count)
7334 {
7335 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();
7336 return true;
7337 }
7338 if (adjusted_fake_outs_count < fake_outs_count)
7339 {
7340 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();
7341 return true;
7342 }
7343
7344 size_t outputs = 1;
7345 if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
7346 {
7347 if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
7348 {
7349 fail_msg_writer() << tr("Failed to parse number of outputs");
7350 return true;
7351 }
7352 else if (outputs < 1)
7353 {
7354 fail_msg_writer() << tr("Amount of outputs should be greater than 0");
7355 return true;
7356 }
7357 else
7358 {
7359 local_args.erase(local_args.begin());
7360 }
7361 }
7362
7363 std::vector<uint8_t> extra;
7364 bool payment_id_seen = false;
7365 if (local_args.size() >= 2)
7366 {
7367 std::string payment_id_str = local_args.back();
7368
7369 crypto::hash payment_id;
7370 bool r = tools::wallet2::parse_long_payment_id(payment_id_str, payment_id);
7371 if(r)
7372 {
7373 LONG_PAYMENT_ID_SUPPORT_CHECK();
7374 }
7375
7376 if(!r && local_args.size() == 3)
7377 {
7378 fail_msg_writer() << tr("payment id has invalid format, expected 16 or 64 character hex string: ") << payment_id_str;
7379 print_usage();
7380 return true;
7381 }
7382 if (payment_id_seen)
7383 local_args.pop_back();
7384 }
7385
7386 cryptonote::address_parse_info info;
7387 if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[0], oa_prompter))
7388 {
7389 fail_msg_writer() << tr("failed to parse address");
7390 print_usage();
7391 return true;
7392 }
7393
7394 if (info.has_payment_id)
7395 {
7396 if (payment_id_seen)
7397 {
7398 fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
7399 return true;
7400 }
7401
7402 std::string extra_nonce;
7403 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
7404 bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
7405 if(!r)
7406 {
7407 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7408 return true;
7409 }
7410 payment_id_seen = true;
7411 }
7412
7413 SCOPED_WALLET_UNLOCK();
7414
7415 try
7416 {
7417 // figure out what tx will be necessary
7418 auto ptx_vector = m_wallet->create_transactions_all(below, info.address, info.is_subaddress, outputs, fake_outs_count, priority, extra, account, subaddr_indices);
7419
7420 if (ptx_vector.empty())
7421 {
7422 fail_msg_writer() << tr("No outputs found, or daemon is not ready");
7423 return true;
7424 }
7425
7426 if (!prompt_if_old(ptx_vector))
7427 {
7428 fail_msg_writer() << tr("transaction cancelled.");
7429 return false;
7430 }
7431
7432 // give user total and fee, and prompt to confirm
7433 uint64_t total_fee = 0, total_sent = 0;
7434 for (size_t n = 0; n < ptx_vector.size(); ++n)
7435 {
7436 total_fee += ptx_vector[n].fee;
7437 for (auto i: ptx_vector[n].selected_transfers)
7438 total_sent += m_wallet->get_transfer_details(i).amount();
7439 }
7440
7441 std::ostringstream prompt;
7442 for (size_t n = 0; n < ptx_vector.size(); ++n)
7443 {
7444 prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
7445 subaddr_indices.clear();
7446 for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
7447 subaddr_indices.insert(i);
7448 for (uint32_t i : subaddr_indices)
7449 prompt << boost::format(tr("Spending from address index %d\n")) % i;
7450 if (subaddr_indices.size() > 1)
7451 prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
7452 }
7453 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7454 return true;
7455 if (ptx_vector.size() > 1) {
7456 prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay?")) %
7457 print_money(total_sent) %
7458 ((unsigned long long)ptx_vector.size()) %
7459 print_money(total_fee);
7460 }
7461 else {
7462 prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7463 print_money(total_sent) %
7464 print_money(total_fee);
7465 }
7466 std::string accepted = input_line(prompt.str(), true);
7467 if (std::cin.eof())
7468 return true;
7469 if (!command_line::is_yes(accepted))
7470 {
7471 fail_msg_writer() << tr("transaction cancelled.");
7472
7473 return true;
7474 }
7475
7476 // actually commit the transactions
7477 if (m_wallet->multisig())
7478 {
7479 CHECK_MULTISIG_ENABLED();
7480 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7481 if (!r)
7482 {
7483 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7484 }
7485 else
7486 {
7487 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7488 }
7489 }
7490 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7491 {
7492 try
7493 {
7494 tools::wallet2::signed_tx_set signed_tx;
7495 std::vector<cryptonote::address_parse_info> dsts_info;
7496 dsts_info.push_back(info);
7497
7498 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7499 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7500 return true;
7501 }
7502
7503 commit_or_save(signed_tx.ptx, m_do_not_relay);
7504 }
7505 catch (const std::exception& e)
7506 {
7507 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7508 }
7509 catch (...)
7510 {
7511 LOG_ERROR("Unknown error");
7512 fail_msg_writer() << tr("unknown error");
7513 }
7514 }
7515 else if (m_wallet->watch_only())
7516 {
7517 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7518 if (!r)
7519 {
7520 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7521 }
7522 else
7523 {
7524 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7525 }
7526 }
7527 else
7528 {
7529 commit_or_save(ptx_vector, m_do_not_relay);
7530 }
7531 }
7532 catch (const std::exception& e)
7533 {
7534 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7535 }
7536 catch (...)
7537 {
7538 LOG_ERROR("unknown error");
7539 fail_msg_writer() << tr("unknown error");
7540 }
7541
7542 return true;
7543 }
7544 //----------------------------------------------------------------------------------------------------
7545 bool simple_wallet::sweep_single(const std::vector<std::string> &args_)
7546 {
7547 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7548 if (!try_connect_to_daemon())
7549 return true;
7550
7551 std::vector<std::string> local_args = args_;
7552
7553 uint32_t priority = 0;
7554 if (local_args.size() > 0 && parse_priority(local_args[0], priority))
7555 local_args.erase(local_args.begin());
7556
7557 priority = m_wallet->adjust_priority(priority);
7558
7559 size_t fake_outs_count = m_wallet->get_min_ring_size() - 1;
7560 if(local_args.size() > 0) {
7561 size_t ring_size;
7562 if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
7563 {
7564 }
7565 else if (ring_size == 0)
7566 {
7567 fail_msg_writer() << tr("Ring size must not be 0");
7568 return true;
7569 }
7570 else
7571 {
7572 fake_outs_count = ring_size - 1;
7573 local_args.erase(local_args.begin());
7574 }
7575 }
7576 uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
7577 if (adjusted_fake_outs_count > fake_outs_count)
7578 {
7579 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();
7580 return true;
7581 }
7582 if (adjusted_fake_outs_count < fake_outs_count)
7583 {
7584 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();
7585 return true;
7586 }
7587
7588 size_t outputs = 1;
7589 if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
7590 {
7591 if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
7592 {
7593 fail_msg_writer() << tr("Failed to parse number of outputs");
7594 return true;
7595 }
7596 else if (outputs < 1)
7597 {
7598 fail_msg_writer() << tr("Amount of outputs should be greater than 0");
7599 return true;
7600 }
7601 else
7602 {
7603 local_args.erase(local_args.begin());
7604 }
7605 }
7606
7607 std::vector<uint8_t> extra;
7608 bool payment_id_seen = false;
7609 if (local_args.size() == 3)
7610 {
7611 crypto::hash payment_id;
7612 std::string extra_nonce;
7613 if (tools::wallet2::parse_long_payment_id(local_args.back(), payment_id))
7614 {
7615 LONG_PAYMENT_ID_SUPPORT_CHECK();
7616 }
7617 else
7618 {
7619 fail_msg_writer() << tr("failed to parse Payment ID");
7620 return true;
7621 }
7622
7623 if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
7624 {
7625 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7626 return true;
7627 }
7628
7629 local_args.pop_back();
7630 payment_id_seen = true;
7631 }
7632
7633 if (local_args.size() != 2)
7634 {
7635 PRINT_USAGE(USAGE_SWEEP_SINGLE);
7636 return true;
7637 }
7638
7639 crypto::key_image ki;
7640 if (!epee::string_tools::hex_to_pod(local_args[0], ki))
7641 {
7642 fail_msg_writer() << tr("failed to parse key image");
7643 return true;
7644 }
7645
7646 cryptonote::address_parse_info info;
7647 if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[1], oa_prompter))
7648 {
7649 fail_msg_writer() << tr("failed to parse address");
7650 return true;
7651 }
7652
7653 if (info.has_payment_id)
7654 {
7655 if (payment_id_seen)
7656 {
7657 fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
7658 return true;
7659 }
7660
7661 std::string extra_nonce;
7662 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
7663 if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
7664 {
7665 fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
7666 return true;
7667 }
7668 payment_id_seen = true;
7669 }
7670
7671 SCOPED_WALLET_UNLOCK();
7672
7673 try
7674 {
7675 // figure out what tx will be necessary
7676 auto ptx_vector = m_wallet->create_transactions_single(ki, info.address, info.is_subaddress, outputs, fake_outs_count, priority, extra);
7677
7678 if (ptx_vector.empty())
7679 {
7680 fail_msg_writer() << tr("No outputs found");
7681 return true;
7682 }
7683 if (ptx_vector.size() > 1)
7684 {
7685 fail_msg_writer() << tr("Multiple transactions are created, which is not supposed to happen");
7686 return true;
7687 }
7688 if (ptx_vector[0].selected_transfers.size() != 1)
7689 {
7690 fail_msg_writer() << tr("The transaction uses multiple or no inputs, which is not supposed to happen");
7691 return true;
7692 }
7693
7694 // give user total and fee, and prompt to confirm
7695 uint64_t total_fee = ptx_vector[0].fee;
7696 uint64_t total_sent = m_wallet->get_transfer_details(ptx_vector[0].selected_transfers.front()).amount();
7697 std::ostringstream prompt;
7698 if (!process_ring_members(ptx_vector, prompt, m_wallet->print_ring_members()))
7699 return true;
7700 prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay?")) %
7701 print_money(total_sent) %
7702 print_money(total_fee);
7703 std::string accepted = input_line(prompt.str(), true);
7704 if (std::cin.eof())
7705 return true;
7706 if (!command_line::is_yes(accepted))
7707 {
7708 fail_msg_writer() << tr("transaction cancelled.");
7709 return true;
7710 }
7711
7712 // actually commit the transactions
7713 if (m_wallet->multisig())
7714 {
7715 CHECK_MULTISIG_ENABLED();
7716 bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_monero_tx");
7717 if (!r)
7718 {
7719 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7720 }
7721 else
7722 {
7723 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_monero_tx";
7724 }
7725 }
7726 else if (m_wallet->get_account().get_device().has_tx_cold_sign())
7727 {
7728 try
7729 {
7730 tools::wallet2::signed_tx_set signed_tx;
7731 std::vector<cryptonote::address_parse_info> dsts_info;
7732 dsts_info.push_back(info);
7733
7734 if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
7735 fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
7736 return true;
7737 }
7738
7739 commit_or_save(signed_tx.ptx, m_do_not_relay);
7740 }
7741 catch (const std::exception& e)
7742 {
7743 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7744 }
7745 catch (...)
7746 {
7747 LOG_ERROR("Unknown error");
7748 fail_msg_writer() << tr("unknown error");
7749 }
7750 }
7751 else if (m_wallet->watch_only())
7752 {
7753 bool r = m_wallet->save_tx(ptx_vector, "unsigned_monero_tx");
7754 if (!r)
7755 {
7756 fail_msg_writer() << tr("Failed to write transaction(s) to file");
7757 }
7758 else
7759 {
7760 success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_monero_tx";
7761 }
7762 }
7763 else
7764 {
7765 commit_or_save(ptx_vector, m_do_not_relay);
7766 }
7767
7768 }
7769 catch (const std::exception& e)
7770 {
7771 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
7772 }
7773 catch (...)
7774 {
7775 LOG_ERROR("unknown error");
7776 fail_msg_writer() << tr("unknown error");
7777 }
7778
7779 return true;
7780 }
7781 //----------------------------------------------------------------------------------------------------
7782 bool simple_wallet::sweep_all(const std::vector<std::string> &args_)
7783 {
7784 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7785 sweep_main(m_current_subaddress_account, 0, args_);
7786 return true;
7787 }
7788 //----------------------------------------------------------------------------------------------------
7789 bool simple_wallet::sweep_account(const std::vector<std::string> &args_)
7790 {
7791 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7792 auto local_args = args_;
7793 if (local_args.empty())
7794 {
7795 PRINT_USAGE(USAGE_SWEEP_ACCOUNT);
7796 return true;
7797 }
7798 uint32_t account = 0;
7799 if (!epee::string_tools::get_xtype_from_string(account, local_args[0]))
7800 {
7801 fail_msg_writer() << tr("Invalid account");
7802 return true;
7803 }
7804 local_args.erase(local_args.begin());
7805
7806 sweep_main(account, 0, local_args);
7807 return true;
7808 }
7809 //----------------------------------------------------------------------------------------------------
7810 bool simple_wallet::sweep_below(const std::vector<std::string> &args_)
7811 {
7812 CHECK_IF_BACKGROUND_SYNCING("cannot sweep");
7813 uint64_t below = 0;
7814 if (args_.size() < 1)
7815 {
7816 fail_msg_writer() << tr("missing threshold amount");
7817 PRINT_USAGE(USAGE_SWEEP_BELOW);
7818 return true;
7819 }
7820 if (!cryptonote::parse_amount(below, args_[0]))
7821 {
7822 fail_msg_writer() << tr("invalid amount threshold");
7823 return true;
7824 }
7825 sweep_main(m_current_subaddress_account, below, std::vector<std::string>(++args_.begin(), args_.end()));
7826 return true;
7827 }
7828 //----------------------------------------------------------------------------------------------------
7829 bool simple_wallet::donate(const std::vector<std::string> &args_)
7830 {
7831 CHECK_IF_BACKGROUND_SYNCING("cannot donate");
7832 std::vector<std::string> local_args = args_;
7833 if(local_args.empty() || local_args.size() > 5)
7834 {
7835 PRINT_USAGE(USAGE_DONATE);
7836 return true;
7837 }
7838 std::string amount_str;
7839 std::string payment_id_str;
7840 // get payment id and pop
7841 crypto::hash payment_id;
7842 crypto::hash8 payment_id8;
7843 if (tools::wallet2::parse_long_payment_id (local_args.back(), payment_id ) ||
7844 tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8))
7845 {
7846 payment_id_str = local_args.back();
7847 local_args.pop_back();
7848 }
7849 // get amount and pop
7850 uint64_t amount;
7851 bool ok = cryptonote::parse_amount(amount, local_args.back());
7852 if (ok && amount != 0)
7853 {
7854 amount_str = local_args.back();
7855 local_args.pop_back();
7856 }
7857 else
7858 {
7859 fail_msg_writer() << tr("amount is wrong: ") << local_args.back() << ", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
7860 return true;
7861 }
7862 // push back address, amount, payment id
7863 std::string address_str;
7864 if (m_wallet->nettype() != cryptonote::MAINNET)
7865 {
7866 // if not mainnet, convert donation address string to the relevant network type
7867 address_parse_info info;
7868 if (!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, MONERO_DONATION_ADDR))
7869 {
7870 fail_msg_writer() << tr("Failed to parse donation address: ") << MONERO_DONATION_ADDR;
7871 return true;
7872 }
7873 address_str = cryptonote::get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
7874 }
7875 else
7876 {
7877 address_str = MONERO_DONATION_ADDR;
7878 }
7879 local_args.push_back(address_str);
7880 local_args.push_back(amount_str);
7881 if (!payment_id_str.empty())
7882 local_args.push_back(payment_id_str);
7883 if (m_wallet->nettype() == cryptonote::MAINNET)
7884 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();
7885 else
7886 message_writer() << (boost::format(tr("Donating %s %s to %s.")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % address_str).str();
7887 transfer(local_args);
7888 return true;
7889 }
7890 //----------------------------------------------------------------------------------------------------
7891 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)
7892 {
7893 CHECK_IF_BACKGROUND_SYNCING("cannot load tx");
7894 // gather info to ask the user
7895 uint64_t amount = 0, amount_to_dests = 0, change = 0;
7896 size_t min_ring_size = ~0;
7897 std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> dests;
7898 int first_known_non_zero_change_index = -1;
7899 std::string payment_id_string = "";
7900 for (size_t n = 0; n < get_num_txes(); ++n)
7901 {
7902 const tools::wallet2::tx_construction_data &cd = get_tx(n);
7903
7904 std::vector<tx_extra_field> tx_extra_fields;
7905 bool has_encrypted_payment_id = false;
7906 crypto::hash8 payment_id8 = crypto::null_hash8;
7907 if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields))
7908 {
7909 tx_extra_nonce extra_nonce;
7910 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
7911 {
7912 crypto::hash payment_id;
7913 if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
7914 {
7915 if (!payment_id_string.empty())
7916 payment_id_string += ", ";
7917
7918 // if none of the addresses are integrated addresses, it's a dummy one
7919 bool is_dummy = true;
7920 for (const auto &e: cd.dests)
7921 if (e.is_integrated)
7922 is_dummy = false;
7923
7924 if (is_dummy)
7925 {
7926 payment_id_string += std::string("dummy encrypted payment ID");
7927 }
7928 else
7929 {
7930 payment_id_string += std::string("encrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id8);
7931 has_encrypted_payment_id = true;
7932 }
7933 }
7934 else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
7935 {
7936 if (!payment_id_string.empty())
7937 payment_id_string += ", ";
7938 payment_id_string += std::string("unencrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id);
7939 payment_id_string += " (OBSOLETE)";
7940 }
7941 }
7942 }
7943
7944 for (size_t s = 0; s < cd.sources.size(); ++s)
7945 {
7946 amount += cd.sources[s].amount;
7947 size_t ring_size = cd.sources[s].outputs.size();
7948 if (ring_size < min_ring_size)
7949 min_ring_size = ring_size;
7950 }
7951 for (size_t d = 0; d < cd.splitted_dsts.size(); ++d)
7952 {
7953 const tx_destination_entry &entry = cd.splitted_dsts[d];
7954 std::string address, standard_address = get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr);
7955 if (has_encrypted_payment_id && !entry.is_subaddress && standard_address != entry.original)
7956 {
7957 address = get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8);
7958 address += std::string(" (" + standard_address + " with encrypted payment id " + epee::string_tools::pod_to_hex(payment_id8) + ")");
7959 }
7960 else
7961 address = standard_address;
7962 auto i = dests.find(entry.addr);
7963 if (i == dests.end())
7964 dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount)));
7965 else
7966 i->second.second += entry.amount;
7967 amount_to_dests += entry.amount;
7968 }
7969 if (cd.change_dts.amount > 0)
7970 {
7971 auto it = dests.find(cd.change_dts.addr);
7972 if (it == dests.end())
7973 {
7974 fail_msg_writer() << tr("Claimed change does not go to a paid address");
7975 return false;
7976 }
7977 if (it->second.second < cd.change_dts.amount)
7978 {
7979 fail_msg_writer() << tr("Claimed change is larger than payment to the change address");
7980 return false;
7981 }
7982 if (cd.change_dts.amount > 0)
7983 {
7984 if (first_known_non_zero_change_index == -1)
7985 first_known_non_zero_change_index = n;
7986 if (memcmp(&cd.change_dts.addr, &get_tx(first_known_non_zero_change_index).change_dts.addr, sizeof(cd.change_dts.addr)))
7987 {
7988 fail_msg_writer() << tr("Change goes to more than one address");
7989 return false;
7990 }
7991 }
7992 change += cd.change_dts.amount;
7993 it->second.second -= cd.change_dts.amount;
7994 if (it->second.second == 0)
7995 dests.erase(cd.change_dts.addr);
7996 }
7997 }
7998
7999 if (payment_id_string.empty())
8000 payment_id_string = "no payment ID";
8001
8002 std::string dest_string;
8003 size_t n_dummy_outputs = 0;
8004 for (auto i = dests.begin(); i != dests.end(); )
8005 {
8006 if (i->second.second > 0)
8007 {
8008 if (!dest_string.empty())
8009 dest_string += ", ";
8010 dest_string += (boost::format(tr("sending %s to %s")) % print_money(i->second.second) % i->second.first).str();
8011 }
8012 else
8013 ++n_dummy_outputs;
8014 ++i;
8015 }
8016 if (n_dummy_outputs > 0)
8017 {
8018 if (!dest_string.empty())
8019 dest_string += ", ";
8020 dest_string += std::to_string(n_dummy_outputs) + tr(" dummy output(s)");
8021 }
8022 if (dest_string.empty())
8023 dest_string = tr("with no destinations");
8024
8025 std::string change_string;
8026 if (change > 0)
8027 {
8028 std::string address = get_account_address_as_str(m_wallet->nettype(), get_tx(0).subaddr_account > 0, get_tx(0).change_dts.addr);
8029 change_string += (boost::format(tr("%s change to %s")) % print_money(change) % address).str();
8030 }
8031 else
8032 change_string += tr("no change");
8033
8034 uint64_t fee = amount - amount_to_dests;
8035 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();
8036 return command_line::is_yes(input_line(prompt_str, true));
8037 }
8038 //----------------------------------------------------------------------------------------------------
8039 bool simple_wallet::accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs)
8040 {
8041 std::string extra_message;
8042 if (!std::get<2>(txs.new_transfers).empty())
8043 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(txs.new_transfers).size()).str();
8044 else if (!std::get<2>(txs.transfers).empty())
8045 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(txs.transfers).size()).str();
8046 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);
8047 }
8048 //----------------------------------------------------------------------------------------------------
8049 bool simple_wallet::accept_loaded_tx(const tools::wallet2::signed_tx_set &txs)
8050 {
8051 std::string extra_message;
8052 if (!txs.key_images.empty())
8053 extra_message = (boost::format("%u key images to import. ") % (unsigned)txs.key_images.size()).str();
8054 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);
8055 }
8056 //----------------------------------------------------------------------------------------------------
8057 bool simple_wallet::sign_transfer(const std::vector<std::string> &args_)
8058 {
8059 if (m_wallet->key_on_device())
8060 {
8061 fail_msg_writer() << tr("command not supported by HW wallet");
8062 return true;
8063 }
8064 if(m_wallet->multisig())
8065 {
8066 fail_msg_writer() << tr("This is a multisig wallet, it can only sign with sign_multisig");
8067 return true;
8068 }
8069 if(m_wallet->watch_only())
8070 {
8071 fail_msg_writer() << tr("This is a watch only wallet");
8072 return true;
8073 }
8074 CHECK_IF_BACKGROUND_SYNCING("cannot sign transfer");
8075
8076 bool export_raw = false;
8077 std::string unsigned_filename = "unsigned_monero_tx";
8078 if (args_.size() > 2 || (args_.size() == 2 && args_[0] != "export_raw"))
8079 {
8080 PRINT_USAGE(USAGE_SIGN_TRANSFER);
8081 return true;
8082 }
8083 else if (args_.size() == 2)
8084 {
8085 export_raw = true;
8086 unsigned_filename = args_[1];
8087 }
8088 else if (args_.size() == 1)
8089 {
8090 if (args_[0] == "export_raw")
8091 export_raw = true;
8092 else
8093 unsigned_filename = args_[0];
8094 }
8095
8096 SCOPED_WALLET_UNLOCK();
8097
8098 std::vector<tools::wallet2::pending_tx> ptx;
8099 try
8100 {
8101 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);
8102 if (!r)
8103 {
8104 fail_msg_writer() << tr("Failed to sign transaction");
8105 return true;
8106 }
8107 }
8108 catch (const std::exception &e)
8109 {
8110 fail_msg_writer() << tr("Failed to sign transaction: ") << e.what();
8111 return true;
8112 }
8113
8114 std::string txids_as_text;
8115 for (const auto &t: ptx)
8116 {
8117 if (!txids_as_text.empty())
8118 txids_as_text += (", ");
8119 txids_as_text += epee::string_tools::pod_to_hex(get_transaction_hash(t.tx));
8120 }
8121 success_msg_writer(true) << tr("Transaction successfully signed to file ") << "signed_monero_tx" << ", txid " << txids_as_text;
8122 if (export_raw)
8123 {
8124 std::string rawfiles_as_text;
8125 for (size_t i = 0; i < ptx.size(); ++i)
8126 {
8127 if (i > 0)
8128 rawfiles_as_text += ", ";
8129 rawfiles_as_text += "signed_monero_tx_raw" + (ptx.size() == 1 ? "" : ("_" + std::to_string(i)));
8130 }
8131 success_msg_writer(true) << tr("Transaction raw hex data exported to ") << rawfiles_as_text;
8132 }
8133 return true;
8134 }
8135 //----------------------------------------------------------------------------------------------------
8136 bool simple_wallet::submit_transfer(const std::vector<std::string> &args_)
8137 {
8138 if (m_wallet->key_on_device())
8139 {
8140 fail_msg_writer() << tr("command not supported by HW wallet");
8141 return true;
8142 }
8143 if (!try_connect_to_daemon())
8144 return true;
8145
8146 try
8147 {
8148 std::vector<tools::wallet2::pending_tx> ptx_vector;
8149 bool r = m_wallet->load_tx("signed_monero_tx", ptx_vector, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); });
8150 if (!r)
8151 {
8152 fail_msg_writer() << tr("Failed to load transaction from file");
8153 return true;
8154 }
8155
8156 commit_or_save(ptx_vector, false);
8157 }
8158 catch (const std::exception& e)
8159 {
8160 handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
8161 }
8162 catch (...)
8163 {
8164 LOG_ERROR("Unknown error");
8165 fail_msg_writer() << tr("unknown error");
8166 }
8167
8168 return true;
8169 }
8170 //----------------------------------------------------------------------------------------------------
8171 std::string get_tx_key_stream(crypto::secret_key tx_key, std::vector<crypto::secret_key> additional_tx_keys)
8172 {
8173 ostringstream oss;
8174 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(tx_key)));
8175 for (size_t i = 0; i < additional_tx_keys.size(); ++i)
8176 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(additional_tx_keys[i])));
8177 return oss.str();
8178 }
8179
8180 bool simple_wallet::get_tx_key(const std::vector<std::string> &args_)
8181 {
8182 CHECK_IF_BACKGROUND_SYNCING("cannot get tx key");
8183
8184 std::vector<std::string> local_args = args_;
8185
8186 if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR)
8187 {
8188 fail_msg_writer() << tr("command not supported by HW wallet");
8189 return true;
8190 }
8191 if(local_args.size() != 1) {
8192 PRINT_USAGE(USAGE_GET_TX_KEY);
8193 return true;
8194 }
8195
8196 crypto::hash txid;
8197 if (!epee::string_tools::hex_to_pod(local_args[0], txid))
8198 {
8199 fail_msg_writer() << tr("failed to parse txid");
8200 return true;
8201 }
8202
8203 SCOPED_WALLET_UNLOCK();
8204
8205 crypto::secret_key tx_key;
8206 std::vector<crypto::secret_key> additional_tx_keys;
8207
8208 bool found_tx_key = m_wallet->get_tx_key(txid, tx_key, additional_tx_keys);
8209 if (found_tx_key)
8210 {
8211 std::string stream = get_tx_key_stream(tx_key, additional_tx_keys);
8212 success_msg_writer() << tr("Tx key: ") << stream;
8213 return true;
8214 }
8215 else
8216 {
8217 fail_msg_writer() << tr("no tx keys found for this txid");
8218 return true;
8219 }
8220 }
8221 //----------------------------------------------------------------------------------------------------
8222 bool simple_wallet::set_tx_key(const std::vector<std::string> &args_)
8223 {
8224 CHECK_IF_BACKGROUND_SYNCING("cannot set tx key");
8225
8226 std::vector<std::string> local_args = args_;
8227
8228 if(local_args.size() != 2 && local_args.size() != 3) {
8229 PRINT_USAGE(USAGE_SET_TX_KEY);
8230 return true;
8231 }
8232
8233 boost::optional<cryptonote::account_public_address> single_destination_subaddress;
8234 if (local_args.size() > 1)
8235 {
8236 cryptonote::address_parse_info info;
8237 if (cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args.back(), oa_prompter))
8238 {
8239 if (!info.is_subaddress)
8240 {
8241 fail_msg_writer() << tr("Last argument is an address, but not a subaddress");
8242 return true;
8243 }
8244 single_destination_subaddress = info.address;
8245 local_args.pop_back();
8246 }
8247 }
8248
8249 crypto::hash txid;
8250 if (!epee::string_tools::hex_to_pod(local_args[0], txid))
8251 {
8252 fail_msg_writer() << tr("failed to parse txid");
8253 return true;
8254 }
8255
8256 crypto::secret_key tx_key;
8257 std::vector<crypto::secret_key> additional_tx_keys;
8258 try
8259 {
8260 if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
8261 {
8262 fail_msg_writer() << tr("failed to parse tx_key");
8263 return true;
8264 }
8265 while(true)
8266 {
8267 local_args[1] = local_args[1].substr(64);
8268 if (local_args[1].empty())
8269 break;
8270 additional_tx_keys.resize(additional_tx_keys.size() + 1);
8271 if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
8272 {
8273 fail_msg_writer() << tr("failed to parse tx_key");
8274 return true;
8275 }
8276 }
8277 }
8278 catch (const std::out_of_range &e)
8279 {
8280 fail_msg_writer() << tr("failed to parse tx_key");
8281 return true;
8282 }
8283
8284 LOCK_IDLE_SCOPE();
8285
8286 try
8287 {
8288 m_wallet->set_tx_key(txid, tx_key, additional_tx_keys, single_destination_subaddress);
8289 success_msg_writer() << tr("Tx key successfully stored.");
8290 }
8291 catch (const std::exception &e)
8292 {
8293 fail_msg_writer() << tr("Failed to store tx key: ") << e.what();
8294 if (!single_destination_subaddress)
8295 fail_msg_writer() << tr("It could be because the transfer was to a subaddress. If this is the case, pass the subaddress last");
8296 }
8297 return true;
8298 }
8299 //----------------------------------------------------------------------------------------------------
8300 bool simple_wallet::get_tx_proof(const std::vector<std::string> &args)
8301 {
8302 CHECK_IF_BACKGROUND_SYNCING("cannot get tx proof");
8303
8304 if (args.size() != 2 && args.size() != 3)
8305 {
8306 PRINT_USAGE(USAGE_GET_TX_PROOF);
8307 return true;
8308 }
8309
8310 crypto::hash txid;
8311 if(!epee::string_tools::hex_to_pod(args[0], txid))
8312 {
8313 fail_msg_writer() << tr("failed to parse txid");
8314 return true;
8315 }
8316
8317 cryptonote::address_parse_info info;
8318 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
8319 {
8320 fail_msg_writer() << tr("failed to parse address");
8321 return true;
8322 }
8323
8324 SCOPED_WALLET_UNLOCK();
8325
8326 try
8327 {
8328 std::string sig_str = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, args.size() == 3 ? args[2] : "");
8329 const std::string filename = "monero_tx_proof";
8330 if (m_wallet->save_to_file(filename, sig_str, true))
8331 success_msg_writer() << tr("signature file saved to: ") << filename;
8332 else
8333 fail_msg_writer() << tr("failed to save signature file");
8334 }
8335 catch (const std::exception &e)
8336 {
8337 fail_msg_writer() << tr("error: ") << e.what();
8338 }
8339 return true;
8340 }
8341 //----------------------------------------------------------------------------------------------------
8342 bool simple_wallet::check_tx_key(const std::vector<std::string> &args_)
8343 {
8344 std::vector<std::string> local_args = args_;
8345
8346 if(local_args.size() != 3) {
8347 PRINT_USAGE(USAGE_CHECK_TX_KEY);
8348 return true;
8349 }
8350
8351 if (!try_connect_to_daemon())
8352 return true;
8353
8354 if (!m_wallet)
8355 {
8356 fail_msg_writer() << tr("wallet is null");
8357 return true;
8358 }
8359 crypto::hash txid;
8360 if(!epee::string_tools::hex_to_pod(local_args[0], txid))
8361 {
8362 fail_msg_writer() << tr("failed to parse txid");
8363 return true;
8364 }
8365
8366 crypto::secret_key tx_key;
8367 std::vector<crypto::secret_key> additional_tx_keys;
8368 if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
8369 {
8370 fail_msg_writer() << tr("failed to parse tx key");
8371 return true;
8372 }
8373 local_args[1] = local_args[1].substr(64);
8374 while (!local_args[1].empty())
8375 {
8376 additional_tx_keys.resize(additional_tx_keys.size() + 1);
8377 if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
8378 {
8379 fail_msg_writer() << tr("failed to parse tx key");
8380 return true;
8381 }
8382 local_args[1] = local_args[1].substr(64);
8383 }
8384
8385 cryptonote::address_parse_info info;
8386 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[2], oa_prompter))
8387 {
8388 fail_msg_writer() << tr("failed to parse address");
8389 return true;
8390 }
8391
8392 try
8393 {
8394 uint64_t received;
8395 bool in_pool;
8396 uint64_t confirmations;
8397 m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations);
8398
8399 if (received > 0)
8400 {
8401 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;
8402 if (in_pool)
8403 {
8404 success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
8405 }
8406 else
8407 {
8408 if (confirmations != (uint64_t)-1)
8409 {
8410 success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
8411 }
8412 else
8413 {
8414 success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
8415 }
8416 }
8417 }
8418 else
8419 {
8420 fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
8421 }
8422 }
8423 catch (const std::exception &e)
8424 {
8425 fail_msg_writer() << tr("error: ") << e.what();
8426 }
8427 return true;
8428 }
8429 //----------------------------------------------------------------------------------------------------
8430 bool simple_wallet::check_tx_proof(const std::vector<std::string> &args)
8431 {
8432 if(args.size() != 3 && args.size() != 4) {
8433 PRINT_USAGE(USAGE_CHECK_TX_PROOF);
8434 return true;
8435 }
8436
8437 if (!try_connect_to_daemon())
8438 return true;
8439
8440 // parse txid
8441 crypto::hash txid;
8442 if(!epee::string_tools::hex_to_pod(args[0], txid))
8443 {
8444 fail_msg_writer() << tr("failed to parse txid");
8445 return true;
8446 }
8447
8448 // parse address
8449 cryptonote::address_parse_info info;
8450 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
8451 {
8452 fail_msg_writer() << tr("failed to parse address");
8453 return true;
8454 }
8455
8456 // read signature file
8457 std::string sig_str;
8458 if (!m_wallet->load_from_file(args[2], sig_str))
8459 {
8460 fail_msg_writer() << tr("failed to load signature file");
8461 return true;
8462 }
8463
8464 try
8465 {
8466 uint64_t received;
8467 bool in_pool;
8468 uint64_t confirmations;
8469 if (m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, args.size() == 4 ? args[3] : "", sig_str, received, in_pool, confirmations))
8470 {
8471 success_msg_writer() << tr("Good signature");
8472 if (received > 0)
8473 {
8474 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;
8475 if (in_pool)
8476 {
8477 success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
8478 }
8479 else
8480 {
8481 if (confirmations != (uint64_t)-1)
8482 {
8483 success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
8484 }
8485 else
8486 {
8487 success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
8488 }
8489 }
8490 }
8491 else
8492 {
8493 fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
8494 }
8495 }
8496 else
8497 {
8498 fail_msg_writer() << tr("Bad signature");
8499 }
8500 }
8501 catch (const std::exception &e)
8502 {
8503 fail_msg_writer() << tr("error: ") << e.what();
8504 }
8505 return true;
8506 }
8507 //----------------------------------------------------------------------------------------------------
8508 bool simple_wallet::get_spend_proof(const std::vector<std::string> &args)
8509 {
8510 CHECK_IF_BACKGROUND_SYNCING("cannot get spend proof");
8511 if (m_wallet->key_on_device())
8512 {
8513 fail_msg_writer() << tr("command not supported by HW wallet");
8514 return true;
8515 }
8516 if(args.size() != 1 && args.size() != 2) {
8517 PRINT_USAGE(USAGE_GET_SPEND_PROOF);
8518 return true;
8519 }
8520
8521 if (m_wallet->watch_only())
8522 {
8523 fail_msg_writer() << tr("wallet is watch-only and cannot generate the proof");
8524 return true;
8525 }
8526
8527 crypto::hash txid;
8528 if (!epee::string_tools::hex_to_pod(args[0], txid))
8529 {
8530 fail_msg_writer() << tr("failed to parse txid");
8531 return true;
8532 }
8533
8534 if (!try_connect_to_daemon())
8535 return true;
8536
8537 SCOPED_WALLET_UNLOCK();
8538
8539 try
8540 {
8541 const std::string sig_str = m_wallet->get_spend_proof(txid, args.size() == 2 ? args[1] : "");
8542 const std::string filename = "monero_spend_proof";
8543 if (m_wallet->save_to_file(filename, sig_str, true))
8544 success_msg_writer() << tr("signature file saved to: ") << filename;
8545 else
8546 fail_msg_writer() << tr("failed to save signature file");
8547 }
8548 catch (const std::exception &e)
8549 {
8550 fail_msg_writer() << e.what();
8551 }
8552 return true;
8553 }
8554 //----------------------------------------------------------------------------------------------------
8555 bool simple_wallet::check_spend_proof(const std::vector<std::string> &args)
8556 {
8557 if(args.size() != 2 && args.size() != 3) {
8558 PRINT_USAGE(USAGE_CHECK_SPEND_PROOF);
8559 return true;
8560 }
8561
8562 crypto::hash txid;
8563 if (!epee::string_tools::hex_to_pod(args[0], txid))
8564 {
8565 fail_msg_writer() << tr("failed to parse txid");
8566 return true;
8567 }
8568
8569 if (!try_connect_to_daemon())
8570 return true;
8571
8572 std::string sig_str;
8573 if (!m_wallet->load_from_file(args[1], sig_str))
8574 {
8575 fail_msg_writer() << tr("failed to load signature file");
8576 return true;
8577 }
8578
8579 try
8580 {
8581 if (m_wallet->check_spend_proof(txid, args.size() == 3 ? args[2] : "", sig_str))
8582 success_msg_writer() << tr("Good signature");
8583 else
8584 fail_msg_writer() << tr("Bad signature");
8585 }
8586 catch (const std::exception& e)
8587 {
8588 fail_msg_writer() << e.what();
8589 }
8590 return true;
8591 }
8592 //----------------------------------------------------------------------------------------------------
8593 bool simple_wallet::get_reserve_proof(const std::vector<std::string> &args)
8594 {
8595 CHECK_IF_BACKGROUND_SYNCING("cannot get reserve proof");
8596 if (m_wallet->key_on_device())
8597 {
8598 fail_msg_writer() << tr("command not supported by HW wallet");
8599 return true;
8600 }
8601 if(args.size() != 1 && args.size() != 2) {
8602 PRINT_USAGE(USAGE_GET_RESERVE_PROOF);
8603 return true;
8604 }
8605
8606 if (m_wallet->watch_only() || m_wallet->multisig())
8607 {
8608 fail_msg_writer() << tr("The reserve proof can be generated only by a full wallet");
8609 return true;
8610 }
8611
8612 boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
8613 if (args[0] != "all")
8614 {
8615 account_minreserve = std::pair<uint32_t, uint64_t>();
8616 account_minreserve->first = m_current_subaddress_account;
8617 if (!cryptonote::parse_amount(account_minreserve->second, args[0]))
8618 {
8619 fail_msg_writer() << tr("amount is wrong: ") << args[0];
8620 return true;
8621 }
8622 }
8623
8624 if (!try_connect_to_daemon())
8625 return true;
8626
8627 SCOPED_WALLET_UNLOCK();
8628
8629 try
8630 {
8631 const std::string sig_str = m_wallet->get_reserve_proof(account_minreserve, args.size() == 2 ? args[1] : "");
8632 const std::string filename = "monero_reserve_proof";
8633 if (m_wallet->save_to_file(filename, sig_str, true))
8634 success_msg_writer() << tr("signature file saved to: ") << filename;
8635 else
8636 fail_msg_writer() << tr("failed to save signature file");
8637 }
8638 catch (const std::exception &e)
8639 {
8640 fail_msg_writer() << e.what();
8641 }
8642 return true;
8643 }
8644 //----------------------------------------------------------------------------------------------------
8645 bool simple_wallet::check_reserve_proof(const std::vector<std::string> &args)
8646 {
8647 if(args.size() != 2 && args.size() != 3) {
8648 PRINT_USAGE(USAGE_CHECK_RESERVE_PROOF);
8649 return true;
8650 }
8651
8652 if (!try_connect_to_daemon())
8653 return true;
8654
8655 cryptonote::address_parse_info info;
8656 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[0], oa_prompter))
8657 {
8658 fail_msg_writer() << tr("failed to parse address");
8659 return true;
8660 }
8661 if (info.is_subaddress)
8662 {
8663 fail_msg_writer() << tr("Address must not be a subaddress");
8664 return true;
8665 }
8666
8667 std::string sig_str;
8668 if (!m_wallet->load_from_file(args[1], sig_str))
8669 {
8670 fail_msg_writer() << tr("failed to load signature file");
8671 return true;
8672 }
8673
8674 LOCK_IDLE_SCOPE();
8675
8676 try
8677 {
8678 uint64_t total, spent;
8679 if (m_wallet->check_reserve_proof(info.address, args.size() == 3 ? args[2] : "", sig_str, total, spent))
8680 {
8681 success_msg_writer() << boost::format(tr("Good signature -- total: %s, spent: %s, unspent: %s")) % print_money(total) % print_money(spent) % print_money(total - spent);
8682 }
8683 else
8684 {
8685 fail_msg_writer() << tr("Bad signature");
8686 }
8687 }
8688 catch (const std::exception& e)
8689 {
8690 fail_msg_writer() << e.what();
8691 }
8692 return true;
8693 }
8694 //----------------------------------------------------------------------------------------------------
8695 static std::string get_human_readable_timespan(std::chrono::seconds seconds)
8696 {
8697 uint64_t ts = seconds.count();
8698 if (ts < 60)
8699 return std::to_string(ts) + sw::tr(" seconds");
8700 if (ts < 3600)
8701 return std::to_string((uint64_t)(ts / 60)) + sw::tr(" minutes");
8702 if (ts < 3600 * 24)
8703 return std::to_string((uint64_t)(ts / 3600)) + sw::tr(" hours");
8704 if (ts < 3600 * 24 * 30.5)
8705 return std::to_string((uint64_t)(ts / (3600 * 24))) + sw::tr(" days");
8706 if (ts < 3600 * 24 * 365.25)
8707 return std::to_string((uint64_t)(ts / (3600 * 24 * 30.5))) + sw::tr(" months");
8708 return sw::tr("a long time");
8709 }
8710 //----------------------------------------------------------------------------------------------------
8711 static std::string get_human_readable_timespan(uint64_t seconds)
8712 {
8713 return get_human_readable_timespan(std::chrono::seconds(seconds));
8714 }
8715 //----------------------------------------------------------------------------------------------------
8716 // mutates local_args as it parses and consumes arguments
8717 bool simple_wallet::get_transfers(std::vector<std::string>& local_args, std::vector<transfer_view>& transfers)
8718 {
8719 bool in = true;
8720 bool out = true;
8721 bool pending = true;
8722 bool failed = true;
8723 bool pool = true;
8724 bool coinbase = true;
8725 uint64_t min_height = 0;
8726 uint64_t max_height = (uint64_t)-1;
8727
8728 // optional in/out selector
8729 if (local_args.size() > 0) {
8730 if (local_args[0] == "in" || local_args[0] == "incoming") {
8731 out = pending = failed = false;
8732 local_args.erase(local_args.begin());
8733 }
8734 else if (local_args[0] == "out" || local_args[0] == "outgoing") {
8735 in = pool = coinbase = false;
8736 local_args.erase(local_args.begin());
8737 }
8738 else if (local_args[0] == "pending") {
8739 in = out = failed = coinbase = false;
8740 local_args.erase(local_args.begin());
8741 }
8742 else if (local_args[0] == "failed") {
8743 in = out = pending = pool = coinbase = false;
8744 local_args.erase(local_args.begin());
8745 }
8746 else if (local_args[0] == "pool") {
8747 in = out = pending = failed = coinbase = false;
8748 local_args.erase(local_args.begin());
8749 }
8750 else if (local_args[0] == "coinbase") {
8751 in = out = pending = failed = pool = false;
8752 coinbase = true;
8753 local_args.erase(local_args.begin());
8754 }
8755 else if (local_args[0] == "all" || local_args[0] == "both") {
8756 local_args.erase(local_args.begin());
8757 }
8758 }
8759
8760 // subaddr_index
8761 std::set<uint32_t> subaddr_indices;
8762 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
8763 {
8764 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
8765 return false;
8766 local_args.erase(local_args.begin());
8767 }
8768
8769 // min height
8770 if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
8771 try {
8772 min_height = boost::lexical_cast<uint64_t>(local_args[0]);
8773 }
8774 catch (const boost::bad_lexical_cast &) {
8775 fail_msg_writer() << tr("bad min_height parameter:") << " " << local_args[0];
8776 return false;
8777 }
8778 local_args.erase(local_args.begin());
8779 }
8780
8781 // max height
8782 if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
8783 try {
8784 max_height = boost::lexical_cast<uint64_t>(local_args[0]);
8785 }
8786 catch (const boost::bad_lexical_cast &) {
8787 fail_msg_writer() << tr("bad max_height parameter:") << " " << local_args[0];
8788 return false;
8789 }
8790 local_args.erase(local_args.begin());
8791 }
8792
8793 const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
8794
8795 if (in || coinbase) {
8796 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
8797 m_wallet->get_payments(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
8798 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8799 const tools::wallet2::payment_details &pd = i->second;
8800 if (!pd.m_coinbase && !in)
8801 continue;
8802 std::string payment_id = string_tools::pod_to_hex(i->first);
8803 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8804 payment_id = payment_id.substr(0,16);
8805 std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
8806 std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
8807 const std::string type = pd.m_coinbase ? tr("block") : tr("in");
8808 const bool unlocked = m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height);
8809 std::string locked_msg = "unlocked";
8810 if (!unlocked)
8811 {
8812 locked_msg = "locked";
8813 if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
8814 {
8815 uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
8816 if (bh >= last_block_height)
8817 locked_msg = std::to_string(bh - last_block_height) + " blks";
8818 }
8819 else
8820 {
8821 const uint64_t adjusted_time = m_wallet->get_daemon_adjusted_time();
8822 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);
8823 if (threshold < pd.m_unlock_time)
8824 locked_msg = get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
8825 }
8826 }
8827 transfers.push_back({
8828 type,
8829 pd.m_block_height,
8830 pd.m_timestamp,
8831 type,
8832 true,
8833 pd.m_amount,
8834 pd.m_tx_hash,
8835 payment_id,
8836 0,
8837 {{destination, pd.m_amount}},
8838 {pd.m_subaddr_index.minor},
8839 note,
8840 locked_msg
8841 });
8842 }
8843 }
8844
8845 if (out) {
8846 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments;
8847 m_wallet->get_payments_out(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
8848 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8849 const tools::wallet2::confirmed_transfer_details &pd = i->second;
8850 uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
8851 uint64_t fee = pd.m_amount_in - pd.m_amount_out;
8852 std::vector<std::pair<std::string, uint64_t>> destinations;
8853 for (const auto &d: pd.m_dests) {
8854 destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
8855 }
8856 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
8857 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8858 payment_id = payment_id.substr(0,16);
8859 std::string note = m_wallet->get_tx_note(i->first);
8860 transfers.push_back({
8861 "out",
8862 pd.m_block_height,
8863 pd.m_timestamp,
8864 "out",
8865 true,
8866 pd.m_amount_in - change - fee,
8867 i->first,
8868 payment_id,
8869 fee,
8870 destinations,
8871 pd.m_subaddr_indices,
8872 note,
8873 "-"
8874 });
8875 }
8876 }
8877
8878 if (pool) {
8879 try
8880 {
8881 m_in_manual_refresh.store(true, std::memory_order_relaxed);
8882 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);});
8883
8884 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
8885 m_wallet->update_pool_state(process_txs);
8886 if (!process_txs.empty())
8887 m_wallet->process_pool_state(process_txs);
8888
8889 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments;
8890 m_wallet->get_unconfirmed_payments(payments, m_current_subaddress_account, subaddr_indices);
8891 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
8892 const tools::wallet2::payment_details &pd = i->second.m_pd;
8893 std::string payment_id = string_tools::pod_to_hex(i->first);
8894 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8895 payment_id = payment_id.substr(0,16);
8896 std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
8897 std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
8898 std::string double_spend_note;
8899 if (i->second.m_double_spend_seen)
8900 double_spend_note = tr("[Double spend seen on the network: this transaction may or may not end up being mined] ");
8901 transfers.push_back({
8902 "pool",
8903 "pool",
8904 pd.m_timestamp,
8905 "in",
8906 false,
8907 pd.m_amount,
8908 pd.m_tx_hash,
8909 payment_id,
8910 0,
8911 {{destination, pd.m_amount}},
8912 {pd.m_subaddr_index.minor},
8913 note + double_spend_note,
8914 "locked"
8915 });
8916 }
8917 }
8918 catch (const std::exception& e)
8919 {
8920 fail_msg_writer() << "Failed to get pool state:" << e.what();
8921 }
8922 }
8923
8924 // print unconfirmed last
8925 if (pending || failed) {
8926 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
8927 m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account, subaddr_indices);
8928 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
8929 const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
8930 uint64_t amount = pd.m_amount_in;
8931 uint64_t fee = amount - pd.m_amount_out;
8932 std::vector<std::pair<std::string, uint64_t>> destinations;
8933 for (const auto &d: pd.m_dests) {
8934 destinations.push_back({d.address(m_wallet->nettype(), pd.m_payment_id), d.amount});
8935 }
8936 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
8937 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
8938 payment_id = payment_id.substr(0,16);
8939 std::string note = m_wallet->get_tx_note(i->first);
8940 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
8941 if ((failed && is_failed) || (!is_failed && pending)) {
8942 transfers.push_back({
8943 (is_failed ? "failed" : "pending"),
8944 (is_failed ? "failed" : "pending"),
8945 pd.m_timestamp,
8946 "out",
8947 false,
8948 amount - pd.m_change - fee,
8949 i->first,
8950 payment_id,
8951 fee,
8952 destinations,
8953 pd.m_subaddr_indices,
8954 note,
8955 "-"
8956 });
8957 }
8958 }
8959 }
8960 // sort by block, then by timestamp (unconfirmed last)
8961 std::sort(transfers.begin(), transfers.end(), [](const transfer_view& a, const transfer_view& b) -> bool {
8962 if (a.confirmed && !b.confirmed)
8963 return true;
8964 if (a.block == b.block)
8965 return a.timestamp < b.timestamp;
8966 return a.block < b.block;
8967 });
8968
8969 return true;
8970 }
8971 //----------------------------------------------------------------------------------------------------
8972 bool simple_wallet::show_transfers(const std::vector<std::string> &args_)
8973 {
8974 std::vector<std::string> local_args = args_;
8975
8976 if(local_args.size() > 4) {
8977 fail_msg_writer() << tr("usage: show_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
8978 return true;
8979 }
8980
8981 LOCK_IDLE_SCOPE();
8982
8983 std::vector<transfer_view> all_transfers;
8984
8985 if (!get_transfers(local_args, all_transfers))
8986 return true;
8987
8988 PAUSE_READLINE();
8989
8990 for (const auto& transfer : all_transfers)
8991 {
8992 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;
8993
8994 std::string destinations = "-";
8995 if (!transfer.outputs.empty())
8996 {
8997 destinations = "";
8998 for (const auto& output : transfer.outputs)
8999 {
9000 if (!destinations.empty())
9001 destinations += ", ";
9002 destinations += (transfer.direction == "in" ? output.first.substr(0, 6) : output.first) + ":" + print_money(output.second);
9003 }
9004 }
9005
9006 auto formatter = boost::format("%8.8llu %6.6s %8.8s %25.25s %20.20s %s %s %14.14s %s %s - %s");
9007
9008 message_writer(color, false) << formatter
9009 % transfer.block
9010 % transfer.direction
9011 % transfer.unlocked
9012 % tools::get_human_readable_timestamp(transfer.timestamp)
9013 % print_money(transfer.amount)
9014 % string_tools::pod_to_hex(transfer.hash)
9015 % transfer.payment_id
9016 % print_money(transfer.fee)
9017 % destinations
9018 % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
9019 % transfer.note;
9020 }
9021
9022 return true;
9023 }
9024 //----------------------------------------------------------------------------------------------------
9025 bool simple_wallet::export_transfers(const std::vector<std::string>& args_)
9026 {
9027 std::vector<std::string> local_args = args_;
9028
9029 if(local_args.size() > 6) {
9030 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>]");
9031 return true;
9032 }
9033
9034 std::vector<transfer_view> all_transfers;
9035
9036 // might consumes arguments in local_args
9037 if (!get_transfers(local_args, all_transfers))
9038 return true;
9039
9040 // output filename
9041 std::string filename = (boost::format("output%u.csv") % m_current_subaddress_account).str();
9042 if (local_args.size() > 0 && local_args[0].substr(0, 7) == "output=")
9043 {
9044 filename = local_args[0].substr(7, -1);
9045 local_args.erase(local_args.begin());
9046 }
9047 // check for export with tx keys
9048 bool export_keys = false;
9049 if (local_args.size() > 0 && local_args[0].substr(0, 7) == "option=")
9050 {
9051 export_keys = local_args[0].substr(7, -1) == "with_keys";
9052 local_args.erase(local_args.begin());
9053 }
9054 if (export_keys)
9055 {
9056 if (m_wallet->key_on_device() && m_wallet->get_account().get_device().get_type() != hw::device::TREZOR)
9057 {
9058 fail_msg_writer() << tr("command not supported by HW wallet");
9059 return true;
9060 }
9061 SCOPED_WALLET_UNLOCK();
9062 } else
9063 {
9064 LOCK_IDLE_SCOPE();
9065 }
9066
9067 std::ofstream file(filename);
9068
9069 // header
9070 file <<
9071 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") %
9072 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")
9073 << std::endl;
9074
9075 uint64_t running_balance = 0;
9076 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");
9077
9078 for (const auto& transfer : all_transfers)
9079 {
9080 // ignore unconfirmed transfers in running balance
9081 if (transfer.confirmed)
9082 {
9083 if (transfer.direction == "in" || transfer.direction == "block")
9084 running_balance += transfer.amount;
9085 else
9086 running_balance -= transfer.amount + transfer.fee;
9087 }
9088
9089 crypto::secret_key tx_key;
9090 std::vector<crypto::secret_key> additional_tx_keys;
9091 bool found_tx_key = m_wallet->get_tx_key(transfer.hash, tx_key, additional_tx_keys);
9092 std::string key_string;
9093 if (export_keys && found_tx_key)
9094 {
9095 key_string = get_tx_key_stream(tx_key, additional_tx_keys);
9096 }
9097
9098 file << formatter
9099 % transfer.block
9100 % transfer.direction
9101 % transfer.unlocked
9102 % tools::get_human_readable_timestamp(transfer.timestamp)
9103 % print_money(transfer.amount)
9104 % print_money(running_balance)
9105 % string_tools::pod_to_hex(transfer.hash)
9106 % transfer.payment_id
9107 % print_money(transfer.fee)
9108 % (transfer.outputs.size() ? transfer.outputs[0].first : "-")
9109 % (transfer.outputs.size() ? print_money(transfer.outputs[0].second) : "")
9110 % boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
9111 % transfer.note
9112 % key_string
9113 << std::endl;
9114
9115 for (size_t i = 1; i < transfer.outputs.size(); ++i)
9116 {
9117 file << formatter
9118 % ""
9119 % ""
9120 % ""
9121 % ""
9122 % ""
9123 % ""
9124 % ""
9125 % ""
9126 % ""
9127 % transfer.outputs[i].first
9128 % print_money(transfer.outputs[i].second)
9129 % ""
9130 % ""
9131 % ""
9132 << std::endl;
9133 }
9134 }
9135 file.close();
9136
9137 success_msg_writer() << tr("CSV exported to ") << filename;
9138
9139 return true;
9140 }
9141 //----------------------------------------------------------------------------------------------------
9142 bool simple_wallet::unspent_outputs(const std::vector<std::string> &args_)
9143 {
9144 if(args_.size() > 3)
9145 {
9146 PRINT_USAGE(USAGE_UNSPENT_OUTPUTS);
9147 return true;
9148 }
9149 auto local_args = args_;
9150
9151 std::set<uint32_t> subaddr_indices;
9152 if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
9153 {
9154 if (!parse_subaddress_indices(local_args[0], subaddr_indices))
9155 return true;
9156 local_args.erase(local_args.begin());
9157 }
9158
9159 uint64_t min_amount = 0;
9160 uint64_t max_amount = std::numeric_limits<uint64_t>::max();
9161 if (local_args.size() > 0)
9162 {
9163 if (!cryptonote::parse_amount(min_amount, local_args[0]))
9164 {
9165 fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
9166 return true;
9167 }
9168 local_args.erase(local_args.begin());
9169 if (local_args.size() > 0)
9170 {
9171 if (!cryptonote::parse_amount(max_amount, local_args[0]))
9172 {
9173 fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
9174 return true;
9175 }
9176 local_args.erase(local_args.begin());
9177 }
9178 if (min_amount > max_amount)
9179 {
9180 fail_msg_writer() << tr("<min_amount> should be smaller than <max_amount>");
9181 return true;
9182 }
9183 }
9184 tools::wallet2::transfer_container transfers;
9185 m_wallet->get_transfers(transfers);
9186 std::map<uint64_t, tools::wallet2::transfer_container> amount_to_tds;
9187 uint64_t min_height = std::numeric_limits<uint64_t>::max();
9188 uint64_t max_height = 0;
9189 uint64_t found_min_amount = std::numeric_limits<uint64_t>::max();
9190 uint64_t found_max_amount = 0;
9191 uint64_t count = 0;
9192 for (const auto& td : transfers)
9193 {
9194 uint64_t amount = td.amount();
9195 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()))
9196 continue;
9197 amount_to_tds[amount].push_back(td);
9198 if (min_height > td.m_block_height) min_height = td.m_block_height;
9199 if (max_height < td.m_block_height) max_height = td.m_block_height;
9200 if (found_min_amount > amount) found_min_amount = amount;
9201 if (found_max_amount < amount) found_max_amount = amount;
9202 ++count;
9203 }
9204 if (amount_to_tds.empty())
9205 {
9206 success_msg_writer() << tr("There is no unspent output in the specified address");
9207 return true;
9208 }
9209 for (const auto& amount_tds : amount_to_tds)
9210 {
9211 auto& tds = amount_tds.second;
9212 success_msg_writer() << tr("\nAmount: ") << print_money(amount_tds.first) << tr(", number of keys: ") << tds.size();
9213 for (size_t i = 0; i < tds.size(); )
9214 {
9215 std::ostringstream oss;
9216 for (size_t j = 0; j < 8 && i < tds.size(); ++i, ++j)
9217 oss << tds[i].m_block_height << tr(" ");
9218 success_msg_writer() << oss.str();
9219 }
9220 }
9221 success_msg_writer()
9222 << tr("\nMin block height: ") << min_height
9223 << tr("\nMax block height: ") << max_height
9224 << tr("\nMin amount found: ") << print_money(found_min_amount)
9225 << tr("\nMax amount found: ") << print_money(found_max_amount)
9226 << tr("\nTotal count: ") << count;
9227 const size_t histogram_height = 10;
9228 const size_t histogram_width = 50;
9229 double bin_size = (max_height - min_height + 1.0) / histogram_width;
9230 size_t max_bin_count = 0;
9231 std::vector<size_t> histogram(histogram_width, 0);
9232 for (const auto& amount_tds : amount_to_tds)
9233 {
9234 for (auto& td : amount_tds.second)
9235 {
9236 uint64_t bin_index = (td.m_block_height - min_height + 1) / bin_size;
9237 if (bin_index >= histogram_width)
9238 bin_index = histogram_width - 1;
9239 histogram[bin_index]++;
9240 if (max_bin_count < histogram[bin_index])
9241 max_bin_count = histogram[bin_index];
9242 }
9243 }
9244 for (size_t x = 0; x < histogram_width; ++x)
9245 {
9246 double bin_count = histogram[x];
9247 if (max_bin_count > histogram_height)
9248 bin_count *= histogram_height / (double)max_bin_count;
9249 if (histogram[x] > 0 && bin_count < 1.0)
9250 bin_count = 1.0;
9251 histogram[x] = bin_count;
9252 }
9253 std::vector<std::string> histogram_line(histogram_height, std::string(histogram_width, ' '));
9254 for (size_t y = 0; y < histogram_height; ++y)
9255 {
9256 for (size_t x = 0; x < histogram_width; ++x)
9257 {
9258 if (y < histogram[x])
9259 histogram_line[y][x] = '*';
9260 }
9261 }
9262 double count_per_star = max_bin_count / (double)histogram_height;
9263 if (count_per_star < 1)
9264 count_per_star = 1;
9265 success_msg_writer()
9266 << tr("\nBin size: ") << bin_size
9267 << tr("\nOutputs per *: ") << count_per_star;
9268 ostringstream histogram_str;
9269 histogram_str << tr("count\n ^\n");
9270 for (size_t y = histogram_height; y > 0; --y)
9271 histogram_str << tr(" |") << histogram_line[y - 1] << tr("|\n");
9272 histogram_str
9273 << tr(" +") << std::string(histogram_width, '-') << tr("+--> block height\n")
9274 << tr(" ^") << std::string(histogram_width - 2, ' ') << tr("^\n")
9275 << tr(" ") << min_height << std::string(histogram_width - 8, ' ') << max_height;
9276 success_msg_writer() << histogram_str.str();
9277 return true;
9278 }
9279 //----------------------------------------------------------------------------------------------------
9280 bool simple_wallet::rescan_blockchain(const std::vector<std::string> &args_)
9281 {
9282 CHECK_IF_BACKGROUND_SYNCING("cannot rescan");
9283
9284 uint64_t start_height = 0;
9285 ResetType reset_type = ResetSoft;
9286
9287 if (!args_.empty())
9288 {
9289 if (args_[0] == "hard")
9290 {
9291 reset_type = ResetHard;
9292 }
9293 else if (args_[0] == "soft")
9294 {
9295 reset_type = ResetSoft;
9296 }
9297 else if (args_[0] == "keep_ki")
9298 {
9299 reset_type = ResetSoftKeepKI;
9300 }
9301 else
9302 {
9303 PRINT_USAGE(USAGE_RESCAN_BC);
9304 return true;
9305 }
9306
9307 if (args_.size() > 1)
9308 {
9309 try
9310 {
9311 start_height = boost::lexical_cast<uint64_t>( args_[1] );
9312 }
9313 catch(const boost::bad_lexical_cast &)
9314 {
9315 start_height = 0;
9316 }
9317 }
9318 }
9319
9320 if (reset_type == ResetHard)
9321 {
9322 message_writer() << tr("Warning: this will lose any information which can not be recovered from the blockchain.");
9323 message_writer() << tr("This includes destination addresses, tx secret keys, tx notes, etc");
9324 std::string confirm = input_line(tr("Rescan anyway?"), true);
9325 if(!std::cin.eof())
9326 {
9327 if (!command_line::is_yes(confirm))
9328 return true;
9329 }
9330 }
9331
9332 const uint64_t wallet_from_height = m_wallet->get_refresh_from_block_height();
9333 if (start_height > wallet_from_height)
9334 {
9335 message_writer() << tr("Warning: your restore height is higher than wallet restore height: ") << wallet_from_height;
9336 std::string confirm = input_line(tr("Rescan anyway ? (Y/Yes/N/No): "));
9337 if(!std::cin.eof())
9338 {
9339 if (!command_line::is_yes(confirm))
9340 return true;
9341 }
9342 }
9343
9344 m_in_manual_refresh.store(true, std::memory_order_relaxed);
9345 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);});
9346 return refresh_main(start_height, reset_type, true);
9347 }
9348 //----------------------------------------------------------------------------------------------------
9349 void simple_wallet::check_for_messages()
9350 {
9351 try
9352 {
9353 std::vector<mms::message> new_messages;
9354 bool new_message = get_message_store().check_for_messages(get_multisig_wallet_state(), new_messages);
9355 if (new_message)
9356 {
9357 message_writer(console_color_magenta, true) << tr("MMS received new message");
9358 list_mms_messages(new_messages);
9359 m_cmd_binder.print_prompt();
9360 }
9361 }
9362 catch(...) {}
9363 }
9364 //----------------------------------------------------------------------------------------------------
9365 void simple_wallet::wallet_idle_thread()
9366 {
9367 const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
9368 while (true)
9369 {
9370 boost::unique_lock<boost::mutex> lock(m_idle_mutex);
9371 if (!m_idle_run.load(std::memory_order_relaxed))
9372 break;
9373
9374 // if another thread was busy (ie, a foreground refresh thread), we'll end up here at
9375 // some random time that's not what we slept for, so we should not call refresh now
9376 // or we'll be leaking that fact through timing
9377 const boost::posix_time::ptime now0 = boost::posix_time::microsec_clock::universal_time();
9378 const uint64_t dt_actual = (now0 - start_time).total_microseconds() % 1000000;
9379 #ifdef _WIN32
9380 static const uint64_t threshold = 10000;
9381 #else
9382 static const uint64_t threshold = 2000;
9383 #endif
9384 if (dt_actual < threshold) // if less than a threshold... would a very slow machine always miss it ?
9385 {
9386 #ifndef _WIN32
9387 m_inactivity_checker.do_call(boost::bind(&simple_wallet::check_inactivity, this));
9388 #endif
9389 m_refresh_checker.do_call(boost::bind(&simple_wallet::check_refresh, this));
9390 m_mms_checker.do_call(boost::bind(&simple_wallet::check_mms, this));
9391 m_rpc_payment_checker.do_call(boost::bind(&simple_wallet::check_rpc_payment, this));
9392
9393 if (!m_idle_run.load(std::memory_order_relaxed))
9394 break;
9395 }
9396
9397 // aim for the next multiple of 1 second
9398 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
9399 const auto dt = (now - start_time).total_microseconds();
9400 const auto wait = 1000000 - dt % 1000000;
9401 m_idle_cond.wait_for(lock, boost::chrono::microseconds(wait));
9402 }
9403 }
9404 //----------------------------------------------------------------------------------------------------
9405 bool simple_wallet::check_inactivity()
9406 {
9407 // inactivity lock
9408 if (!m_locked && !m_in_command)
9409 {
9410 const uint32_t seconds = m_wallet->inactivity_lock_timeout();
9411 if (seconds > 0 && time(NULL) - m_last_activity_time > seconds)
9412 {
9413 m_locked = true;
9414 m_cmd_binder.cancel_input();
9415 }
9416 }
9417 return true;
9418 }
9419 //----------------------------------------------------------------------------------------------------
9420 bool simple_wallet::check_refresh()
9421 {
9422 // auto refresh
9423 if (m_auto_refresh_enabled)
9424 {
9425 m_auto_refresh_refreshing = true;
9426 try
9427 {
9428 uint64_t fetched_blocks;
9429 bool received_money;
9430 if (try_connect_to_daemon(true))
9431 m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, fetched_blocks, received_money, false); // don't check the pool in background mode
9432 }
9433 catch(...) {}
9434 m_auto_refresh_refreshing = false;
9435 }
9436 return true;
9437 }
9438 //----------------------------------------------------------------------------------------------------
9439 bool simple_wallet::check_mms()
9440 {
9441 // Check for new MMS messages;
9442 // For simplicity auto message check is ALSO controlled by "m_auto_refresh_enabled" and has no
9443 // separate thread either; thread syncing is tricky enough with only this one idle thread here
9444 if (m_auto_refresh_enabled && get_message_store().get_active())
9445 {
9446 check_for_messages();
9447 }
9448 return true;
9449 }
9450 //----------------------------------------------------------------------------------------------------
9451 bool simple_wallet::check_rpc_payment()
9452 {
9453 if (!m_rpc_payment_mining_requested && m_wallet->auto_mine_for_rpc_payment_threshold() == 0.0f)
9454 return true;
9455
9456 uint64_t target = m_wallet->credits_target();
9457 if (target == 0)
9458 target = CREDITS_TARGET;
9459 if (m_rpc_payment_mining_requested)
9460 target = std::numeric_limits<uint64_t>::max();
9461 bool need_payment = m_need_payment || m_rpc_payment_mining_requested || (m_wallet->credits() < target && m_wallet->daemon_requires_payment());
9462 if (need_payment)
9463 {
9464 const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time();
9465 auto startfunc = [this](uint64_t diff, uint64_t credits_per_hash_found)
9466 {
9467 const float cph = credits_per_hash_found / (float)diff;
9468 bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE);
9469 if (credits_per_hash_found > 0 && cph >= m_wallet->auto_mine_for_rpc_payment_threshold())
9470 {
9471 MINFO(std::to_string(cph) << " credits per hash is >= our threshold (" << m_wallet->auto_mine_for_rpc_payment_threshold() << "), starting mining");
9472 return true;
9473 }
9474 else if (m_rpc_payment_mining_requested)
9475 {
9476 MINFO("Mining for RPC payment was requested, starting mining");
9477 return true;
9478 }
9479 else
9480 {
9481 if (!m_daemon_rpc_payment_message_displayed)
9482 {
9483 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")) %
9484 diff % cph % (low ? " - this is low" : "");
9485 m_cmd_binder.print_prompt();
9486 m_daemon_rpc_payment_message_displayed = true;
9487 }
9488 return false;
9489 }
9490 };
9491 auto contfunc = [&,this](unsigned n_hashes)
9492 {
9493 if (m_suspend_rpc_payment_mining.load(std::memory_order_relaxed))
9494 return false;
9495 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
9496 m_last_rpc_payment_mining_time = now;
9497 if ((now - start_time).total_microseconds() >= 2 * 1000000)
9498 m_rpc_payment_hash_rate = n_hashes / (float)((now - start_time).total_seconds());
9499 if ((now - start_time).total_microseconds() >= REFRESH_PERIOD * 1000000)
9500 return false;
9501 return true;
9502 };
9503 auto foundfunc = [this, target](uint64_t credits)
9504 {
9505 m_need_payment = false;
9506 return credits < target;
9507 };
9508 auto errorfunc = [this](const std::string &error)
9509 {
9510 fail_msg_writer() << tr("Error mining to daemon: ") << error;
9511 m_cmd_binder.print_prompt();
9512 };
9513 bool ret = m_wallet->search_for_rpc_payment(target, m_rpc_payment_threads, startfunc, contfunc, foundfunc, errorfunc);
9514 if (!ret)
9515 {
9516 fail_msg_writer() << tr("Failed to start mining for RPC payment");
9517 m_cmd_binder.print_prompt();
9518 }
9519 }
9520 return true;
9521 }
9522 //----------------------------------------------------------------------------------------------------
9523 std::string simple_wallet::get_prompt() const
9524 {
9525 if (m_locked)
9526 return std::string("[") + tr("locked due to inactivity") + "]";
9527 std::string addr_start = m_wallet->get_subaddress_as_str({m_current_subaddress_account, 0}).substr(0, 6);
9528 std::string prompt = std::string("[") + tr("wallet") + " " + addr_start;
9529 if (!m_wallet->check_connection(NULL))
9530 prompt += tr(" (no daemon)");
9531 else if (!m_wallet->is_synced())
9532 prompt += tr(" (out of sync)");
9533 prompt += "]: ";
9534 return prompt;
9535 }
9536 //----------------------------------------------------------------------------------------------------
9537 bool simple_wallet::run()
9538 {
9539 // check and display warning, but go on anyway
9540 try_connect_to_daemon();
9541
9542 refresh_main(0, ResetNone, true);
9543
9544 m_auto_refresh_enabled = !m_wallet->is_offline() && m_wallet->auto_refresh();
9545 m_idle_thread = boost::thread([&]{wallet_idle_thread();});
9546
9547 message_writer(console_color_green, false) << "Background refresh thread started";
9548 return m_cmd_binder.run_handling([this](){return get_prompt();}, "");
9549 }
9550 //----------------------------------------------------------------------------------------------------
9551 void simple_wallet::stop()
9552 {
9553 m_cmd_binder.stop_handling();
9554 }
9555 //----------------------------------------------------------------------------------------------------
9556 bool simple_wallet::account(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9557 {
9558 // Usage:
9559 // account
9560 // account new <label text with white spaces allowed>
9561 // account switch <index>
9562 // account label <index> <label text with white spaces allowed>
9563 // account tag <tag_name> <account_index_1> [<account_index_2> ...]
9564 // account untag <account_index_1> [<account_index_2> ...]
9565 // account tag_description <tag_name> <description>
9566
9567 if (args.empty())
9568 {
9569 // print all the existing accounts
9570 LOCK_IDLE_SCOPE();
9571 print_accounts();
9572 return true;
9573 }
9574
9575 std::vector<std::string> local_args = args;
9576 std::string command = local_args[0];
9577 local_args.erase(local_args.begin());
9578 if (command == "new")
9579 {
9580 // create a new account and switch to it
9581 CHECK_IF_BACKGROUND_SYNCING("cannot create new account");
9582 std::string label = boost::join(local_args, " ");
9583 if (label.empty())
9584 label = tr("(Untitled account)");
9585 m_wallet->add_subaddress_account(label);
9586 m_current_subaddress_account = m_wallet->get_num_subaddress_accounts() - 1;
9587 // update_prompt();
9588 LOCK_IDLE_SCOPE();
9589 print_accounts();
9590 }
9591 else if (command == "switch" && local_args.size() == 1)
9592 {
9593 // switch to the specified account
9594 uint32_t index_major;
9595 if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
9596 {
9597 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9598 return true;
9599 }
9600 if (index_major >= m_wallet->get_num_subaddress_accounts())
9601 {
9602 fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddress_accounts() - 1);
9603 return true;
9604 }
9605 m_current_subaddress_account = index_major;
9606 // update_prompt();
9607 show_balance();
9608 }
9609 else if (command == "label" && local_args.size() >= 1)
9610 {
9611 // set label of the specified account
9612 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9613 uint32_t index_major;
9614 if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
9615 {
9616 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9617 return true;
9618 }
9619 local_args.erase(local_args.begin());
9620 std::string label = boost::join(local_args, " ");
9621 try
9622 {
9623 m_wallet->set_subaddress_label({index_major, 0}, label);
9624 LOCK_IDLE_SCOPE();
9625 print_accounts();
9626 }
9627 catch (const std::exception& e)
9628 {
9629 fail_msg_writer() << e.what();
9630 }
9631 }
9632 else if (command == "tag" && local_args.size() >= 2)
9633 {
9634 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9635 const std::string tag = local_args[0];
9636 std::set<uint32_t> account_indices;
9637 for (size_t i = 1; i < local_args.size(); ++i)
9638 {
9639 uint32_t account_index;
9640 if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
9641 {
9642 fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
9643 return true;
9644 }
9645 account_indices.insert(account_index);
9646 }
9647 try
9648 {
9649 m_wallet->set_account_tag(account_indices, tag);
9650 print_accounts(tag);
9651 }
9652 catch (const std::exception& e)
9653 {
9654 fail_msg_writer() << e.what();
9655 }
9656 }
9657 else if (command == "untag" && local_args.size() >= 1)
9658 {
9659 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9660 std::set<uint32_t> account_indices;
9661 for (size_t i = 0; i < local_args.size(); ++i)
9662 {
9663 uint32_t account_index;
9664 if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
9665 {
9666 fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
9667 return true;
9668 }
9669 account_indices.insert(account_index);
9670 }
9671 try
9672 {
9673 m_wallet->set_account_tag(account_indices, "");
9674 print_accounts();
9675 }
9676 catch (const std::exception& e)
9677 {
9678 fail_msg_writer() << e.what();
9679 }
9680 }
9681 else if (command == "tag_description" && local_args.size() >= 1)
9682 {
9683 CHECK_IF_BACKGROUND_SYNCING("cannot modify account");
9684 const std::string tag = local_args[0];
9685 std::string description;
9686 if (local_args.size() > 1)
9687 {
9688 local_args.erase(local_args.begin());
9689 description = boost::join(local_args, " ");
9690 }
9691 try
9692 {
9693 m_wallet->set_account_tag_description(tag, description);
9694 print_accounts(tag);
9695 }
9696 catch (const std::exception& e)
9697 {
9698 fail_msg_writer() << e.what();
9699 }
9700 }
9701 else
9702 {
9703 PRINT_USAGE(USAGE_ACCOUNT);
9704 }
9705 return true;
9706 }
9707 //----------------------------------------------------------------------------------------------------
9708 void simple_wallet::print_accounts()
9709 {
9710 const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
9711 size_t num_untagged_accounts = m_wallet->get_num_subaddress_accounts();
9712 for (const std::pair<const std::string, std::string>& p : account_tags.first)
9713 {
9714 const std::string& tag = p.first;
9715 print_accounts(tag);
9716 num_untagged_accounts -= std::count(account_tags.second.begin(), account_tags.second.end(), tag);
9717 success_msg_writer() << "";
9718 }
9719
9720 if (num_untagged_accounts > 0)
9721 print_accounts("");
9722
9723 if (num_untagged_accounts < m_wallet->get_num_subaddress_accounts())
9724 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));
9725 }
9726 //----------------------------------------------------------------------------------------------------
9727 void simple_wallet::print_accounts(const std::string& tag)
9728 {
9729 const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
9730 if (tag.empty())
9731 {
9732 success_msg_writer() << tr("Untagged accounts:");
9733 }
9734 else
9735 {
9736 if (account_tags.first.count(tag) == 0)
9737 {
9738 fail_msg_writer() << boost::format(tr("Tag %s is unregistered.")) % tag;
9739 return;
9740 }
9741 success_msg_writer() << tr("Accounts with tag: ") << tag;
9742 success_msg_writer() << tr("Tag's description: ") << account_tags.first.find(tag)->second;
9743 }
9744 success_msg_writer() << boost::format(" %15s %21s %21s %21s") % tr("Account") % tr("Balance") % tr("Unlocked balance") % tr("Label");
9745 uint64_t total_balance = 0, total_unlocked_balance = 0;
9746 for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
9747 {
9748 if (account_tags.second[account_index] != tag)
9749 continue;
9750 success_msg_writer() << boost::format(tr(" %c%8u %6s %21s %21s %21s"))
9751 % (m_current_subaddress_account == account_index ? '*' : ' ')
9752 % account_index
9753 % m_wallet->get_subaddress_as_str({account_index, 0}).substr(0, 6)
9754 % print_money(m_wallet->balance(account_index, false))
9755 % print_money(m_wallet->unlocked_balance(account_index, false))
9756 % m_wallet->get_subaddress_label({account_index, 0});
9757 total_balance += m_wallet->balance(account_index, false);
9758 total_unlocked_balance += m_wallet->unlocked_balance(account_index, false);
9759 }
9760 success_msg_writer() << tr("------------------------------------------------------------------------------------");
9761 success_msg_writer() << boost::format(tr("%15s %21s %21s")) % "Total" % print_money(total_balance) % print_money(total_unlocked_balance);
9762 }
9763 //----------------------------------------------------------------------------------------------------
9764 bool simple_wallet::print_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9765 {
9766 // Usage:
9767 // address
9768 // address new <label text with white spaces allowed>
9769 // address all
9770 // address <index_min> [<index_max>]
9771 // address label <index> <label text with white spaces allowed>
9772 // address device [<index>]
9773
9774 std::vector<std::string> local_args = args;
9775 tools::wallet2::transfer_container transfers;
9776 m_wallet->get_transfers(transfers);
9777
9778 auto print_address_sub = [this, &transfers](uint32_t index)
9779 {
9780 bool used = std::find_if(
9781 transfers.begin(), transfers.end(),
9782 [this, &index](const tools::wallet2::transfer_details& td) {
9783 return td.m_subaddr_index == cryptonote::subaddress_index{ m_current_subaddress_account, index };
9784 }) != transfers.end();
9785 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)") : "");
9786 };
9787
9788 uint32_t index = 0;
9789 if (local_args.empty())
9790 {
9791 print_address_sub(index);
9792 }
9793 else if (local_args.size() == 1 && local_args[0] == "all")
9794 {
9795 local_args.erase(local_args.begin());
9796 for (; index < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++index)
9797 print_address_sub(index);
9798 }
9799 else if (local_args[0] == "new")
9800 {
9801 CHECK_IF_BACKGROUND_SYNCING("cannot add address");
9802 local_args.erase(local_args.begin());
9803 std::string label;
9804 if (local_args.size() > 0)
9805 label = boost::join(local_args, " ");
9806 if (label.empty())
9807 label = tr("(Untitled address)");
9808 m_wallet->add_subaddress(m_current_subaddress_account, label);
9809 print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9810 m_wallet->device_show_address(m_current_subaddress_account, m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1, boost::none);
9811 }
9812 else if (local_args[0] == "mnew")
9813 {
9814 CHECK_IF_BACKGROUND_SYNCING("cannot add addresses");
9815 local_args.erase(local_args.begin());
9816 if (local_args.size() != 1)
9817 {
9818 fail_msg_writer() << tr("Expected exactly one argument for the amount of new addresses");
9819 return true;
9820 }
9821 uint32_t n;
9822 if (!epee::string_tools::get_xtype_from_string(n, local_args[0]))
9823 {
9824 fail_msg_writer() << tr("failed to parse the amount of new addresses: ") << local_args[0];
9825 return true;
9826 }
9827 if (n > MAX_MNEW_ADDRESSES)
9828 {
9829 fail_msg_writer() << tr("the amount of new addresses must be lower or equal to ") << MAX_MNEW_ADDRESSES;
9830 return true;
9831 }
9832 for (uint32_t i = 0; i < n; ++i)
9833 {
9834 m_wallet->add_subaddress(m_current_subaddress_account, tr("(Untitled address)"));
9835 print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9836 }
9837 }
9838 else if (local_args[0] == "one-off")
9839 {
9840 CHECK_IF_BACKGROUND_SYNCING("cannot add address");
9841 local_args.erase(local_args.begin());
9842 std::string label;
9843 if (local_args.size() != 2)
9844 {
9845 fail_msg_writer() << tr("Expected exactly two arguments for index");
9846 return true;
9847 }
9848 uint32_t major, minor;
9849 if (!epee::string_tools::get_xtype_from_string(major, local_args[0]) || !epee::string_tools::get_xtype_from_string(minor, local_args[1]))
9850 {
9851 fail_msg_writer() << tr("failed to parse index: ") << local_args[0] << " " << local_args[1];
9852 return true;
9853 }
9854 m_wallet->create_one_off_subaddress({major, minor});
9855 success_msg_writer() << boost::format(tr("Address at %u %u: %s")) % major % minor % m_wallet->get_subaddress_as_str({major, minor});
9856 }
9857 else if (local_args.size() >= 2 && local_args[0] == "label")
9858 {
9859 CHECK_IF_BACKGROUND_SYNCING("cannot modify address");
9860 if (!epee::string_tools::get_xtype_from_string(index, local_args[1]))
9861 {
9862 fail_msg_writer() << tr("failed to parse index: ") << local_args[1];
9863 return true;
9864 }
9865 if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9866 {
9867 fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
9868 return true;
9869 }
9870 local_args.erase(local_args.begin());
9871 local_args.erase(local_args.begin());
9872 std::string label = boost::join(local_args, " ");
9873 m_wallet->set_subaddress_label({m_current_subaddress_account, index}, label);
9874 print_address_sub(index);
9875 }
9876 else if (local_args.size() <= 2 && epee::string_tools::get_xtype_from_string(index, local_args[0]))
9877 {
9878 local_args.erase(local_args.begin());
9879 uint32_t index_min = index;
9880 uint32_t index_max = index_min;
9881 if (local_args.size() > 0)
9882 {
9883 if (!epee::string_tools::get_xtype_from_string(index_max, local_args[0]))
9884 {
9885 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9886 return true;
9887 }
9888 local_args.erase(local_args.begin());
9889 }
9890 if (index_max < index_min)
9891 std::swap(index_min, index_max);
9892 if (index_min >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9893 {
9894 fail_msg_writer() << tr("<index_min> is already out of bound");
9895 return true;
9896 }
9897 if (index_max >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9898 {
9899 message_writer() << tr("<index_max> exceeds the bound");
9900 index_max = m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1;
9901 }
9902 for (index = index_min; index <= index_max; ++index)
9903 print_address_sub(index);
9904 }
9905 else if (local_args[0] == "device")
9906 {
9907 index = 0;
9908 local_args.erase(local_args.begin());
9909 if (local_args.size() > 0)
9910 {
9911 if (!epee::string_tools::get_xtype_from_string(index, local_args[0]))
9912 {
9913 fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
9914 return true;
9915 }
9916 if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
9917 {
9918 fail_msg_writer() << tr("<index> is out of bounds");
9919 return true;
9920 }
9921 }
9922
9923 print_address_sub(index);
9924 m_wallet->device_show_address(m_current_subaddress_account, index, boost::none);
9925 }
9926 else
9927 {
9928 PRINT_USAGE(USAGE_ADDRESS);
9929 }
9930
9931 return true;
9932 }
9933 //----------------------------------------------------------------------------------------------------
9934 bool simple_wallet::print_integrated_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
9935 {
9936 crypto::hash8 payment_id;
9937 bool display_on_device = false;
9938 std::vector<std::string> local_args = args;
9939
9940 if (local_args.size() > 0 && local_args[0] == "device")
9941 {
9942 local_args.erase(local_args.begin());
9943 display_on_device = true;
9944 }
9945
9946 auto device_show_integrated = [this, display_on_device](crypto::hash8 payment_id)
9947 {
9948 if (display_on_device)
9949 {
9950 m_wallet->device_show_address(m_current_subaddress_account, 0, payment_id);
9951 }
9952 };
9953
9954 if (local_args.size() > 1)
9955 {
9956 PRINT_USAGE(USAGE_INTEGRATED_ADDRESS);
9957 return true;
9958 }
9959 if (local_args.size() == 0)
9960 {
9961 if (m_current_subaddress_account != 0)
9962 {
9963 fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
9964 return true;
9965 }
9966 payment_id = crypto::rand<crypto::hash8>();
9967 success_msg_writer() << tr("Random payment ID: ") << payment_id;
9968 success_msg_writer() << tr("Matching integrated address: ") << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
9969 device_show_integrated(payment_id);
9970 return true;
9971 }
9972 if(tools::wallet2::parse_short_payment_id(local_args.back(), payment_id))
9973 {
9974 if (m_current_subaddress_account != 0)
9975 {
9976 fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
9977 return true;
9978 }
9979 success_msg_writer() << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
9980 device_show_integrated(payment_id);
9981 return true;
9982 }
9983 else {
9984 address_parse_info info;
9985 if(get_account_address_from_str(info, m_wallet->nettype(), local_args.back()))
9986 {
9987 if (info.has_payment_id)
9988 {
9989 success_msg_writer() << boost::format(tr("Standard address: %s, payment ID: %s")) %
9990 get_account_address_as_str(m_wallet->nettype(), false, info.address) % epee::string_tools::pod_to_hex(info.payment_id);
9991 device_show_integrated(info.payment_id);
9992 }
9993 else
9994 {
9995 success_msg_writer() << (info.is_subaddress ? tr("Subaddress: ") : tr("Standard address: ")) << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
9996 }
9997 return true;
9998 }
9999 }
10000 fail_msg_writer() << tr("failed to parse payment ID or address");
10001 return true;
10002 }
10003 //----------------------------------------------------------------------------------------------------
10004 bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
10005 {
10006 CHECK_IF_BACKGROUND_SYNCING("cannot get address book");
10007
10008 if (args.size() == 0)
10009 {
10010 }
10011 else if (args.size() == 1 || (args[0] != "add" && args[0] != "delete"))
10012 {
10013 PRINT_USAGE(USAGE_ADDRESS_BOOK);
10014 return true;
10015 }
10016 else if (args[0] == "add")
10017 {
10018 cryptonote::address_parse_info info;
10019 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
10020 {
10021 fail_msg_writer() << tr("failed to parse address");
10022 return true;
10023 }
10024 size_t description_start = 2;
10025 std::string description;
10026 for (size_t i = description_start; i < args.size(); ++i)
10027 {
10028 if (i > description_start)
10029 description += " ";
10030 description += args[i];
10031 }
10032 m_wallet->add_address_book_row(info.address, info.has_payment_id ? &info.payment_id : NULL, description, info.is_subaddress);
10033 }
10034 else
10035 {
10036 size_t row_id;
10037 if(!epee::string_tools::get_xtype_from_string(row_id, args[1]))
10038 {
10039 fail_msg_writer() << tr("failed to parse index");
10040 return true;
10041 }
10042 m_wallet->delete_address_book_row(row_id);
10043 }
10044 auto address_book = m_wallet->get_address_book();
10045 if (address_book.empty())
10046 {
10047 success_msg_writer() << tr("Address book is empty.");
10048 }
10049 else
10050 {
10051 for (size_t i = 0; i < address_book.size(); ++i) {
10052 auto& row = address_book[i];
10053 success_msg_writer() << tr("Index: ") << i;
10054 std::string address;
10055 if (row.m_has_payment_id)
10056 address = cryptonote::get_account_integrated_address_as_str(m_wallet->nettype(), row.m_address, row.m_payment_id);
10057 else
10058 address = get_account_address_as_str(m_wallet->nettype(), row.m_is_subaddress, row.m_address);
10059 success_msg_writer() << tr("Address: ") << address;
10060 success_msg_writer() << tr("Description: ") << row.m_description << "\n";
10061 }
10062 }
10063 return true;
10064 }
10065 //----------------------------------------------------------------------------------------------------
10066 bool simple_wallet::set_tx_note(const std::vector<std::string> &args)
10067 {
10068 CHECK_IF_BACKGROUND_SYNCING("cannot set tx note");
10069
10070 if (args.size() == 0)
10071 {
10072 PRINT_USAGE(USAGE_SET_TX_NOTE);
10073 return true;
10074 }
10075
10076 cryptonote::blobdata txid_data;
10077 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10078 {
10079 fail_msg_writer() << tr("failed to parse txid");
10080 return true;
10081 }
10082 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10083
10084 std::string note = "";
10085 for (size_t n = 1; n < args.size(); ++n)
10086 {
10087 if (n > 1)
10088 note += " ";
10089 note += args[n];
10090 }
10091 m_wallet->set_tx_note(txid, note);
10092
10093 return true;
10094 }
10095 //----------------------------------------------------------------------------------------------------
10096 bool simple_wallet::get_tx_note(const std::vector<std::string> &args)
10097 {
10098 CHECK_IF_BACKGROUND_SYNCING("cannot get tx note");
10099
10100 if (args.size() != 1)
10101 {
10102 PRINT_USAGE(USAGE_GET_TX_NOTE);
10103 return true;
10104 }
10105
10106 cryptonote::blobdata txid_data;
10107 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10108 {
10109 fail_msg_writer() << tr("failed to parse txid");
10110 return true;
10111 }
10112 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10113
10114 std::string note = m_wallet->get_tx_note(txid);
10115 if (note.empty())
10116 success_msg_writer() << "no note found";
10117 else
10118 success_msg_writer() << "note found: " << note;
10119
10120 return true;
10121 }
10122 //----------------------------------------------------------------------------------------------------
10123 bool simple_wallet::set_description(const std::vector<std::string> &args)
10124 {
10125 CHECK_IF_BACKGROUND_SYNCING("cannot set description");
10126
10127 // 0 arguments allowed, for setting the description to empty string
10128
10129 std::string description = "";
10130 for (size_t n = 0; n < args.size(); ++n)
10131 {
10132 if (n > 0)
10133 description += " ";
10134 description += args[n];
10135 }
10136 m_wallet->set_description(description);
10137
10138 return true;
10139 }
10140 //----------------------------------------------------------------------------------------------------
10141 bool simple_wallet::get_description(const std::vector<std::string> &args)
10142 {
10143 CHECK_IF_BACKGROUND_SYNCING("cannot get description");
10144
10145 if (args.size() != 0)
10146 {
10147 PRINT_USAGE(USAGE_GET_DESCRIPTION);
10148 return true;
10149 }
10150
10151 std::string description = m_wallet->get_description();
10152 if (description.empty())
10153 success_msg_writer() << tr("no description found");
10154 else
10155 success_msg_writer() << tr("description found: ") << description;
10156
10157 return true;
10158 }
10159 //----------------------------------------------------------------------------------------------------
10160 bool simple_wallet::status(const std::vector<std::string> &args)
10161 {
10162 uint64_t local_height = m_wallet->get_blockchain_current_height();
10163 uint32_t version = 0;
10164 bool ssl = false;
10165 if (!m_wallet->check_connection(&version, &ssl))
10166 {
10167 success_msg_writer() << "Refreshed " << local_height << "/?, no daemon connected";
10168 return true;
10169 }
10170
10171 std::string err;
10172 uint64_t bc_height = get_daemon_blockchain_height(err);
10173 if (err.empty())
10174 {
10175 bool synced = local_height == bc_height;
10176 success_msg_writer() << "Refreshed " << local_height << "/" << bc_height << ", " << (synced ? "synced" : "syncing")
10177 << ", daemon RPC v" << get_version_string(version) << ", " << (ssl ? "SSL" : "no SSL");
10178 }
10179 else
10180 {
10181 fail_msg_writer() << "Refreshed " << local_height << "/?, daemon connection error";
10182 }
10183 return true;
10184 }
10185 //----------------------------------------------------------------------------------------------------
10186 bool simple_wallet::wallet_info(const std::vector<std::string> &args)
10187 {
10188 bool ready;
10189 uint32_t threshold, total;
10190 std::string description = m_wallet->get_description();
10191 if (description.empty())
10192 {
10193 description = "<Not set>";
10194 }
10195 message_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
10196 message_writer() << tr("Description: ") << description;
10197 message_writer() << tr("Address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
10198 std::string type;
10199 if (m_wallet->watch_only())
10200 type = tr("Watch only");
10201 else if (m_wallet->multisig(&ready, &threshold, &total))
10202 type = (boost::format(tr("%u/%u multisig%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
10203 else if (m_wallet->is_background_wallet())
10204 type = tr("Background wallet");
10205 else
10206 type = tr("Normal");
10207 message_writer() << tr("Type: ") << type;
10208 message_writer() << tr("Network type: ") << (
10209 m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
10210 m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet"));
10211 return true;
10212 }
10213 //----------------------------------------------------------------------------------------------------
10214 bool simple_wallet::sign(const std::vector<std::string> &args)
10215 {
10216 CHECK_IF_BACKGROUND_SYNCING("cannot sign");
10217 if (m_wallet->key_on_device())
10218 {
10219 fail_msg_writer() << tr("command not supported by HW wallet");
10220 return true;
10221 }
10222 if (args.size() != 1 && args.size() != 2 && args.size() != 3)
10223 {
10224 PRINT_USAGE(USAGE_SIGN);
10225 return true;
10226 }
10227 if (m_wallet->watch_only())
10228 {
10229 fail_msg_writer() << tr("wallet is watch-only and cannot sign");
10230 return true;
10231 }
10232 if (m_wallet->multisig())
10233 {
10234 fail_msg_writer() << tr("This wallet is multisig and cannot sign");
10235 return true;
10236 }
10237
10238 tools::wallet2::message_signature_type_t message_signature_type = tools::wallet2::sign_with_spend_key;
10239 subaddress_index index{0, 0};
10240 for (unsigned int idx = 0; idx + 1 < args.size(); ++idx)
10241 {
10242 unsigned int a, b;
10243 if (sscanf(args[idx].c_str(), "%u,%u", &a, &b) == 2)
10244 {
10245 index.major = a;
10246 index.minor = b;
10247 }
10248 else if (args[idx] == "--spend")
10249 {
10250 message_signature_type = tools::wallet2::sign_with_spend_key;
10251 }
10252 else if (args[idx] == "--view")
10253 {
10254 message_signature_type = tools::wallet2::sign_with_view_key;
10255 }
10256 else
10257 {
10258 fail_msg_writer() << tr("Invalid subaddress index format, and not a signature type: ") << args[idx];
10259 return true;
10260 }
10261 }
10262
10263 const std::string &filename = args.back();
10264 std::string data;
10265 bool r = m_wallet->load_from_file(filename, data);
10266 if (!r)
10267 {
10268 fail_msg_writer() << tr("failed to read file ") << filename;
10269 return true;
10270 }
10271
10272 SCOPED_WALLET_UNLOCK();
10273
10274 std::string signature = m_wallet->sign(data, message_signature_type, index);
10275 success_msg_writer() << signature;
10276 return true;
10277 }
10278 //----------------------------------------------------------------------------------------------------
10279 bool simple_wallet::verify(const std::vector<std::string> &args)
10280 {
10281 if (args.size() != 3)
10282 {
10283 PRINT_USAGE(USAGE_VERIFY);
10284 return true;
10285 }
10286 std::string filename = args[0];
10287 std::string address_string = args[1];
10288 std::string signature= args[2];
10289
10290 std::string data;
10291 bool r = m_wallet->load_from_file(filename, data);
10292 if (!r)
10293 {
10294 fail_msg_writer() << tr("failed to read file ") << filename;
10295 return true;
10296 }
10297
10298 cryptonote::address_parse_info info;
10299 if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_string, oa_prompter))
10300 {
10301 fail_msg_writer() << tr("failed to parse address");
10302 return true;
10303 }
10304
10305 tools::wallet2::message_signature_result_t result = m_wallet->verify(data, info.address, signature);
10306 if (!result.valid)
10307 {
10308 fail_msg_writer() << tr("Bad signature from ") << address_string;
10309 }
10310 else
10311 {
10312 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)");
10313 }
10314 return true;
10315 }
10316 //----------------------------------------------------------------------------------------------------
10317 bool simple_wallet::export_key_images(const std::vector<std::string> &args_)
10318 {
10319 if (m_wallet->key_on_device())
10320 {
10321 fail_msg_writer() << tr("command not supported by HW wallet");
10322 return true;
10323 }
10324 CHECK_IF_BACKGROUND_SYNCING("cannot export key images");
10325 auto args = args_;
10326
10327 if (m_wallet->watch_only())
10328 {
10329 fail_msg_writer() << tr("wallet is watch-only and cannot export key images");
10330 return true;
10331 }
10332
10333 bool all = false;
10334 if (args.size() >= 2 && args[0] == "all")
10335 {
10336 all = true;
10337 args.erase(args.begin());
10338 }
10339
10340 if (args.size() != 1)
10341 {
10342 PRINT_USAGE(USAGE_EXPORT_KEY_IMAGES);
10343 return true;
10344 }
10345
10346 std::string filename = args[0];
10347 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
10348 return true;
10349
10350 SCOPED_WALLET_UNLOCK();
10351
10352 try
10353 {
10354 if (!m_wallet->export_key_images(filename, all))
10355 {
10356 fail_msg_writer() << tr("failed to save file ") << filename;
10357 return true;
10358 }
10359 }
10360 catch (const std::exception &e)
10361 {
10362 LOG_ERROR("Error exporting key images: " << e.what());
10363 fail_msg_writer() << "Error exporting key images: " << e.what();
10364 return true;
10365 }
10366
10367 success_msg_writer() << tr("Signed key images exported to ") << filename;
10368 return true;
10369 }
10370 //----------------------------------------------------------------------------------------------------
10371 bool simple_wallet::import_key_images(const std::vector<std::string> &args)
10372 {
10373 if (m_wallet->key_on_device())
10374 {
10375 fail_msg_writer() << tr("command not supported by HW wallet");
10376 return true;
10377 }
10378 CHECK_IF_BACKGROUND_SYNCING("cannot import key images");
10379 if (!m_wallet->is_trusted_daemon())
10380 {
10381 fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
10382 return true;
10383 }
10384
10385 if (args.size() != 1)
10386 {
10387 PRINT_USAGE(USAGE_IMPORT_KEY_IMAGES);
10388 return true;
10389 }
10390 std::string filename = args[0];
10391
10392 LOCK_IDLE_SCOPE();
10393 try
10394 {
10395 uint64_t spent = 0, unspent = 0;
10396 uint64_t height = m_wallet->import_key_images(filename, spent, unspent);
10397 success_msg_writer() << "Signed key images imported to height " << height << ", "
10398 << print_money(spent) << " spent, " << print_money(unspent) << " unspent";
10399 }
10400 catch (const std::exception &e)
10401 {
10402 fail_msg_writer() << "Failed to import key images: " << e.what();
10403 return true;
10404 }
10405
10406 return true;
10407 }
10408 //----------------------------------------------------------------------------------------------------
10409 bool simple_wallet::hw_key_images_sync(const std::vector<std::string> &args)
10410 {
10411 if (!m_wallet->key_on_device())
10412 {
10413 fail_msg_writer() << tr("command only supported by HW wallet");
10414 return true;
10415 }
10416 if (!m_wallet->get_account().get_device().has_ki_cold_sync())
10417 {
10418 fail_msg_writer() << tr("hw wallet does not support cold KI sync");
10419 return true;
10420 }
10421
10422 LOCK_IDLE_SCOPE();
10423 key_images_sync_intern();
10424 return true;
10425 }
10426 //----------------------------------------------------------------------------------------------------
10427 void simple_wallet::key_images_sync_intern(){
10428 try
10429 {
10430 message_writer(console_color_white, false) << tr("Please confirm the key image sync on the device");
10431
10432 uint64_t spent = 0, unspent = 0;
10433 uint64_t height = m_wallet->cold_key_image_sync(spent, unspent);
10434 if (height > 0)
10435 {
10436 success_msg_writer() << tr("Key images synchronized to height ") << height;
10437 if (!m_wallet->is_trusted_daemon())
10438 {
10439 message_writer() << tr("Running untrusted daemon, cannot determine which transaction output is spent. Use a trusted daemon with --trusted-daemon and run rescan_spent");
10440 } else
10441 {
10442 success_msg_writer() << print_money(spent) << tr(" spent, ") << print_money(unspent) << tr(" unspent");
10443 }
10444 }
10445 else {
10446 fail_msg_writer() << tr("Failed to import key images");
10447 }
10448 }
10449 catch (const std::exception &e)
10450 {
10451 fail_msg_writer() << tr("Failed to import key images: ") << e.what();
10452 }
10453 }
10454 //----------------------------------------------------------------------------------------------------
10455 bool simple_wallet::hw_reconnect(const std::vector<std::string> &args)
10456 {
10457 if (!m_wallet->key_on_device())
10458 {
10459 fail_msg_writer() << tr("command only supported by HW wallet");
10460 return true;
10461 }
10462
10463 LOCK_IDLE_SCOPE();
10464 try
10465 {
10466 bool r = m_wallet->reconnect_device();
10467 if (!r){
10468 fail_msg_writer() << tr("Failed to reconnect device");
10469 }
10470 }
10471 catch (const std::exception &e)
10472 {
10473 fail_msg_writer() << tr("Failed to reconnect device: ") << tr(e.what());
10474 return true;
10475 }
10476
10477 return true;
10478 }
10479 //----------------------------------------------------------------------------------------------------
10480 bool simple_wallet::export_outputs(const std::vector<std::string> &args_)
10481 {
10482 if (m_wallet->key_on_device())
10483 {
10484 fail_msg_writer() << tr("command not supported by HW wallet");
10485 return true;
10486 }
10487 CHECK_IF_BACKGROUND_SYNCING("cannot export outputs");
10488 auto args = args_;
10489
10490 bool all = false;
10491 if (args.size() >= 2 && args[0] == "all")
10492 {
10493 all = true;
10494 args.erase(args.begin());
10495 }
10496
10497 if (args.size() != 1)
10498 {
10499 PRINT_USAGE(USAGE_EXPORT_OUTPUTS);
10500 return true;
10501 }
10502
10503 std::string filename = args[0];
10504 if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
10505 return true;
10506
10507 SCOPED_WALLET_UNLOCK();
10508
10509 try
10510 {
10511 std::string data = m_wallet->export_outputs_to_str(all);
10512 bool r = m_wallet->save_to_file(filename, data);
10513 if (!r)
10514 {
10515 fail_msg_writer() << tr("failed to save file ") << filename;
10516 return true;
10517 }
10518 }
10519 catch (const std::exception &e)
10520 {
10521 LOG_ERROR("Error exporting outputs: " << e.what());
10522 fail_msg_writer() << "Error exporting outputs: " << e.what();
10523 return true;
10524 }
10525
10526 success_msg_writer() << tr("Outputs exported to ") << filename;
10527 return true;
10528 }
10529 //----------------------------------------------------------------------------------------------------
10530 bool simple_wallet::import_outputs(const std::vector<std::string> &args)
10531 {
10532 if (m_wallet->key_on_device())
10533 {
10534 fail_msg_writer() << tr("command not supported by HW wallet");
10535 return true;
10536 }
10537 CHECK_IF_BACKGROUND_SYNCING("cannot import outputs");
10538 if (args.size() != 1)
10539 {
10540 PRINT_USAGE(USAGE_IMPORT_OUTPUTS);
10541 return true;
10542 }
10543 std::string filename = args[0];
10544
10545 std::string data;
10546 bool r = m_wallet->load_from_file(filename, data);
10547 if (!r)
10548 {
10549 fail_msg_writer() << tr("failed to read file ") << filename;
10550 return true;
10551 }
10552
10553 try
10554 {
10555 SCOPED_WALLET_UNLOCK();
10556 size_t n_outputs = m_wallet->import_outputs_from_str(data);
10557 success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported";
10558 }
10559 catch (const std::exception &e)
10560 {
10561 fail_msg_writer() << "Failed to import outputs " << filename << ": " << e.what();
10562 return true;
10563 }
10564
10565 return true;
10566 }
10567 //----------------------------------------------------------------------------------------------------
10568 bool simple_wallet::show_transfer(const std::vector<std::string> &args)
10569 {
10570 if (args.size() != 1)
10571 {
10572 PRINT_USAGE(USAGE_SHOW_TRANSFER);
10573 return true;
10574 }
10575
10576 cryptonote::blobdata txid_data;
10577 if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
10578 {
10579 fail_msg_writer() << tr("failed to parse txid");
10580 return true;
10581 }
10582 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
10583
10584 const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
10585
10586 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
10587 m_wallet->get_payments(payments, 0, (uint64_t)-1, m_current_subaddress_account);
10588 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
10589 const tools::wallet2::payment_details &pd = i->second;
10590 if (pd.m_tx_hash == txid) {
10591 std::string payment_id = string_tools::pod_to_hex(i->first);
10592 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10593 payment_id = payment_id.substr(0,16);
10594 success_msg_writer() << "Incoming transaction found";
10595 success_msg_writer() << "txid: " << txid;
10596 success_msg_writer() << "Height: " << pd.m_block_height;
10597 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10598 success_msg_writer() << "Amount: " << print_money(pd.m_amount);
10599 success_msg_writer() << "Payment ID: " << payment_id;
10600 if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
10601 {
10602 uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
10603 uint64_t last_block_reward = m_wallet->get_last_block_reward();
10604 uint64_t suggested_threshold = last_block_reward ? (pd.m_amount + last_block_reward - 1) / last_block_reward : 0;
10605 if (bh >= last_block_height)
10606 success_msg_writer() << "Locked: " << (bh - last_block_height) << " blocks to unlock";
10607 else if (suggested_threshold > 0)
10608 success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations (" << suggested_threshold << " suggested threshold)";
10609 else
10610 success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations";
10611 }
10612 else
10613 {
10614 const uint64_t adjusted_time = m_wallet->get_daemon_adjusted_time();
10615 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);
10616 if (threshold >= pd.m_unlock_time)
10617 success_msg_writer() << "unlocked for " << get_human_readable_timespan(std::chrono::seconds(threshold - pd.m_unlock_time));
10618 else
10619 success_msg_writer() << "locked for " << get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
10620 }
10621 success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
10622 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10623 return true;
10624 }
10625 }
10626
10627 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out;
10628 m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, m_current_subaddress_account);
10629 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) {
10630 if (i->first == txid)
10631 {
10632 const tools::wallet2::confirmed_transfer_details &pd = i->second;
10633 uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
10634 uint64_t fee = pd.m_amount_in - pd.m_amount_out;
10635 std::string dests;
10636 for (const auto &d: pd.m_dests) {
10637 if (!dests.empty())
10638 dests += ", ";
10639 dests += d.address(m_wallet->nettype(), pd.m_payment_id) + ": " + print_money(d.amount);
10640 }
10641 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
10642 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10643 payment_id = payment_id.substr(0,16);
10644 success_msg_writer() << "Outgoing transaction found";
10645 success_msg_writer() << "txid: " << txid;
10646 success_msg_writer() << "Height: " << pd.m_block_height;
10647 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10648 success_msg_writer() << "Amount: " << print_money(pd.m_amount_in - change - fee);
10649 success_msg_writer() << "Payment ID: " << payment_id;
10650 success_msg_writer() << "Change: " << print_money(change);
10651 success_msg_writer() << "Fee: " << print_money(fee);
10652 success_msg_writer() << "Destinations: " << dests;
10653 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10654 return true;
10655 }
10656 }
10657
10658 try
10659 {
10660 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
10661 m_wallet->update_pool_state(process_txs);
10662 if (!process_txs.empty())
10663 m_wallet->process_pool_state(process_txs);
10664
10665 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments;
10666 m_wallet->get_unconfirmed_payments(pool_payments, m_current_subaddress_account);
10667 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) {
10668 const tools::wallet2::payment_details &pd = i->second.m_pd;
10669 if (pd.m_tx_hash == txid)
10670 {
10671 std::string payment_id = string_tools::pod_to_hex(i->first);
10672 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10673 payment_id = payment_id.substr(0,16);
10674 success_msg_writer() << "Unconfirmed incoming transaction found in the txpool";
10675 success_msg_writer() << "txid: " << txid;
10676 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10677 success_msg_writer() << "Amount: " << print_money(pd.m_amount);
10678 success_msg_writer() << "Payment ID: " << payment_id;
10679 success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
10680 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10681 if (i->second.m_double_spend_seen)
10682 success_msg_writer() << tr("Double spend seen on the network: this transaction may or may not end up being mined");
10683 return true;
10684 }
10685 }
10686 }
10687 catch (...)
10688 {
10689 fail_msg_writer() << "Failed to get pool state";
10690 }
10691
10692 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
10693 m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account);
10694 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
10695 if (i->first == txid)
10696 {
10697 const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
10698 uint64_t amount = pd.m_amount_in;
10699 uint64_t fee = amount - pd.m_amount_out;
10700 std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
10701 if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
10702 payment_id = payment_id.substr(0,16);
10703 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
10704
10705 success_msg_writer() << (is_failed ? "Failed" : "Pending") << " outgoing transaction found";
10706 success_msg_writer() << "txid: " << txid;
10707 success_msg_writer() << "Timestamp: " << tools::get_human_readable_timestamp(pd.m_timestamp);
10708 success_msg_writer() << "Amount: " << print_money(amount - pd.m_change - fee);
10709 success_msg_writer() << "Payment ID: " << payment_id;
10710 success_msg_writer() << "Change: " << print_money(pd.m_change);
10711 success_msg_writer() << "Fee: " << print_money(fee);
10712 success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
10713 return true;
10714 }
10715 }
10716
10717 fail_msg_writer() << tr("Transaction ID not found");
10718 return true;
10719 }
10720 //----------------------------------------------------------------------------------------------------
10721 bool simple_wallet::process_command(const std::vector<std::string> &args)
10722 {
10723 return m_cmd_binder.process_command_vec(args);
10724 }
10725 //----------------------------------------------------------------------------------------------------
10726 void simple_wallet::interrupt()
10727 {
10728 if (m_in_manual_refresh.load(std::memory_order_relaxed))
10729 {
10730 m_wallet->stop();
10731 }
10732 else
10733 {
10734 stop();
10735 }
10736 }
10737 //----------------------------------------------------------------------------------------------------
10738 void simple_wallet::commit_or_save(std::vector<tools::wallet2::pending_tx>& ptx_vector, bool do_not_relay)
10739 {
10740 size_t i = 0;
10741 while (!ptx_vector.empty())
10742 {
10743 auto & ptx = ptx_vector.back();
10744 const crypto::hash txid = get_transaction_hash(ptx.tx);
10745 if (do_not_relay)
10746 {
10747 cryptonote::blobdata blob;
10748 tx_to_blob(ptx.tx, blob);
10749 const std::string blob_hex = epee::string_tools::buff_to_hex_nodelimer(blob);
10750 const std::string filename = "raw_monero_tx" + (ptx_vector.size() == 1 ? "" : ("_" + std::to_string(i++)));
10751 if (m_wallet->save_to_file(filename, blob_hex, true))
10752 success_msg_writer(true) << tr("Transaction successfully saved to ") << filename << tr(", txid ") << txid;
10753 else
10754 fail_msg_writer() << tr("Failed to save transaction to ") << filename << tr(", txid ") << txid;
10755 }
10756 else
10757 {
10758 m_wallet->commit_tx(ptx);
10759 success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << txid << ENDL
10760 << tr("You can check its status by using the `show_transfers` command.");
10761 }
10762 // if no exception, remove element from vector
10763 ptx_vector.pop_back();
10764 }
10765 }
10766 //----------------------------------------------------------------------------------------------------
10767 int main(int argc, char* argv[])
10768 {
10769 TRY_ENTRY();
10770
10771 #ifdef WIN32
10772 // Activate UTF-8 support for Boost filesystem classes on Windows
10773 std::locale::global(boost::locale::generator().generate(""));
10774 boost::filesystem::path::imbue(std::locale());
10775 #endif
10776 setlocale(LC_CTYPE, "");
10777
10778 po::options_description desc_params(wallet_args::tr("Wallet options"));
10779 tools::wallet2::init_options(desc_params);
10780 command_line::add_arg(desc_params, arg_wallet_file);
10781 command_line::add_arg(desc_params, arg_generate_new_wallet);
10782 command_line::add_arg(desc_params, arg_generate_from_device);
10783 command_line::add_arg(desc_params, arg_generate_from_view_key);
10784 command_line::add_arg(desc_params, arg_generate_from_spend_key);
10785 command_line::add_arg(desc_params, arg_generate_from_keys);
10786 command_line::add_arg(desc_params, arg_generate_from_multisig_keys);
10787 command_line::add_arg(desc_params, arg_generate_from_json);
10788 command_line::add_arg(desc_params, arg_mnemonic_language);
10789 command_line::add_arg(desc_params, arg_command);
10790
10791 command_line::add_arg(desc_params, arg_restore_deterministic_wallet );
10792 command_line::add_arg(desc_params, arg_restore_from_seed );
10793 command_line::add_arg(desc_params, arg_restore_multisig_wallet );
10794 command_line::add_arg(desc_params, arg_non_deterministic );
10795 command_line::add_arg(desc_params, arg_electrum_seed );
10796 command_line::add_arg(desc_params, arg_restore_height);
10797 command_line::add_arg(desc_params, arg_restore_date);
10798 command_line::add_arg(desc_params, arg_do_not_relay);
10799 command_line::add_arg(desc_params, arg_create_address_file);
10800 command_line::add_arg(desc_params, arg_subaddress_lookahead);
10801 command_line::add_arg(desc_params, arg_use_english_language_names);
10802 command_line::add_arg(desc_params, arg_rpc_client_secret_key);
10803
10804 po::positional_options_description positional_options;
10805 positional_options.add(arg_command.name, -1);
10806
10807 boost::optional<po::variables_map> vm;
10808 bool should_terminate = false;
10809 std::tie(vm, should_terminate) = wallet_args::main(
10810 argc, argv,
10811 "monero-wallet-cli [--wallet-file=<filename>|--generate-new-wallet=<filename>] [<COMMAND>]",
10812 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."),
10813 desc_params,
10814 positional_options,
10815 [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; },
10816 "monero-wallet-cli.log"
10817 );
10818
10819 if (!vm)
10820 {
10821 return 1;
10822 }
10823
10824 if (should_terminate)
10825 {
10826 return 0;
10827 }
10828
10829 cryptonote::simple_wallet w;
10830 const bool r = w.init(*vm);
10831 CHECK_AND_ASSERT_MES(r, 1, sw::tr("Failed to initialize wallet"));
10832
10833 std::vector<std::string> command = command_line::get_arg(*vm, arg_command);
10834 if (!command.empty())
10835 {
10836 if (!w.process_command(command))
10837 fail_msg_writer() << sw::tr("Unknown command: ") << command.front();
10838 w.stop();
10839 w.deinit();
10840 }
10841 else
10842 {
10843 tools::signal_handler::install([&w](int type) {
10844 if (tools::password_container::is_prompting.load())
10845 {
10846 // must be prompting for password so return and let the signal stop prompt
10847 return;
10848 }
10849 #ifdef WIN32
10850 if (type == CTRL_C_EVENT)
10851 #else
10852 if (type == SIGINT)
10853 #endif
10854 {
10855 // if we're pressing ^C when refreshing, just stop refreshing
10856 w.interrupt();
10857 }
10858 else
10859 {
10860 w.stop();
10861 }
10862 });
10863 w.run();
10864
10865 w.deinit();
10866 }
10867 return 0;
10868 CATCH_ENTRY_L0("main", 1);
10869 }
10870
10871 // MMS ---------------------------------------------------------------------------------------------------
10872
10873 // Access to the message store, or more exactly to the list of the messages that can be changed
10874 // by the idle thread, is guarded by the same mutex-based mechanism as access to the wallet
10875 // as a whole and thus e.g. uses the "LOCK_IDLE_SCOPE" macro. This is a little over-cautious, but
10876 // simple and safe. Care has to be taken however where MMS methods call other simplewallet methods
10877 // that use "LOCK_IDLE_SCOPE" as this cannot be nested!
10878
10879 // Methods for commands like "export_multisig_info" usually read data from file(s) or write data
10880 // to files. The MMS calls now those methods as well, to produce data for messages and to process data
10881 // from messages. As it would be quite inconvenient for the MMS to write data for such methods to files
10882 // first or get data out of result files after the call, those methods detect a call from the MMS and
10883 // expect data as arguments instead of files and give back data by calling 'process_wallet_created_data'.
10884
10885 bool simple_wallet::user_confirms(const std::string &question)
10886 {
10887 std::string answer = input_line(question + tr(" (Y/Yes/N/No): "));
10888 return !std::cin.eof() && command_line::is_yes(answer);
10889 }
10890
10891 bool simple_wallet::user_confirms_auto_config()
10892 {
10893 message_writer(console_color_red, true) << tr("WARNING: Using MMS auto-config mechanisms is not trustless");
10894 message_writer() << tr("A malicious auto-config manager could send you info about own wallets instead of other signers' info");
10895 message_writer() << tr("If in doubt do not use auto-config or at least compare configs using the \"mms config_checksum\" command");
10896 return user_confirms("Accept the risks and continue?");
10897 }
10898
10899 bool simple_wallet::get_number_from_arg(const std::string &arg, uint32_t &number, const uint32_t lower_bound, const uint32_t upper_bound)
10900 {
10901 bool valid = false;
10902 try
10903 {
10904 number = boost::lexical_cast<uint32_t>(arg);
10905 valid = (number >= lower_bound) && (number <= upper_bound);
10906 }
10907 catch(const boost::bad_lexical_cast &)
10908 {
10909 }
10910 return valid;
10911 }
10912
10913 bool simple_wallet::choose_mms_processing(const std::vector<mms::processing_data> &data_list, uint32_t &choice)
10914 {
10915 size_t choices = data_list.size();
10916 if (choices == 1)
10917 {
10918 choice = 0;
10919 return true;
10920 }
10921 mms::message_store& ms = m_wallet->get_message_store();
10922 message_writer() << tr("Choose processing:");
10923 std::string text;
10924 for (size_t i = 0; i < choices; ++i)
10925 {
10926 const mms::processing_data &data = data_list[i];
10927 text = std::to_string(i+1) + ": ";
10928 switch (data.processing)
10929 {
10930 case mms::message_processing::sign_tx:
10931 text += tr("Sign tx");
10932 break;
10933 case mms::message_processing::send_tx:
10934 {
10935 mms::message m;
10936 ms.get_message_by_id(data.message_ids[0], m);
10937 if (m.type == mms::message_type::fully_signed_tx)
10938 {
10939 text += tr("Send the tx for submission to ");
10940 }
10941 else
10942 {
10943 text += tr("Send the tx for signing to ");
10944 }
10945 mms::authorized_signer signer = ms.get_signer(data.receiving_signer_index);
10946 text += ms.signer_to_string(signer, 50);
10947 break;
10948 }
10949 case mms::message_processing::submit_tx:
10950 text += tr("Submit tx");
10951 break;
10952 default:
10953 text += tr("unknown");
10954 break;
10955 }
10956 message_writer() << text;
10957 }
10958
10959 std::string line = input_line(tr("Choice: "));
10960 if (std::cin.eof() || line.empty())
10961 {
10962 return false;
10963 }
10964 bool choice_ok = get_number_from_arg(line, choice, 1, choices);
10965 if (choice_ok)
10966 {
10967 choice--;
10968 }
10969 else
10970 {
10971 fail_msg_writer() << tr("Wrong choice");
10972 }
10973 return choice_ok;
10974 }
10975
10976 void simple_wallet::list_mms_messages(const std::vector<mms::message> &messages)
10977 {
10978 message_writer() << boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") % tr("Id") % tr("I/O") % tr("Authorized Signer")
10979 % tr("Message Type") % tr("Height") % tr("R") % tr("Message State") % tr("Since");
10980 mms::message_store& ms = m_wallet->get_message_store();
10981 uint64_t now = (uint64_t)time(NULL);
10982 for (size_t i = 0; i < messages.size(); ++i)
10983 {
10984 const mms::message &m = messages[i];
10985 const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
10986 bool highlight = (m.state == mms::message_state::ready_to_send) || (m.state == mms::message_state::waiting);
10987 message_writer(m.direction == mms::message_direction::out ? console_color_green : console_color_magenta, highlight) <<
10988 boost::format("%4s %-4s %-30s %-21s %7s %3s %-15s %-40s") %
10989 m.id %
10990 ms.message_direction_to_string(m.direction) %
10991 ms.signer_to_string(signer, 30) %
10992 ms.message_type_to_string(m.type) %
10993 m.wallet_height %
10994 m.round %
10995 ms.message_state_to_string(m.state) %
10996 (tools::get_human_readable_timestamp(m.modified) + ", " + get_human_readable_timespan(std::chrono::seconds(now - m.modified)) + tr(" ago"));
10997 }
10998 }
10999
11000 void simple_wallet::list_signers(const std::vector<mms::authorized_signer> &signers)
11001 {
11002 message_writer() << boost::format("%2s %-20s %-s") % tr("#") % tr("Label") % tr("Transport Address");
11003 message_writer() << boost::format("%2s %-20s %-s") % "" % tr("Auto-Config Token") % tr("Monero Address");
11004 for (size_t i = 0; i < signers.size(); ++i)
11005 {
11006 const mms::authorized_signer &signer = signers[i];
11007 std::string label = signer.label.empty() ? tr("<not set>") : signer.label;
11008 std::string monero_address;
11009 if (signer.monero_address_known)
11010 {
11011 monero_address = get_account_address_as_str(m_wallet->nettype(), false, signer.monero_address);
11012 }
11013 else
11014 {
11015 monero_address = tr("<not set>");
11016 }
11017 std::string transport_address = signer.transport_address.empty() ? tr("<not set>") : signer.transport_address;
11018 message_writer() << boost::format("%2s %-20s %-s") % (i + 1) % label % transport_address;
11019 message_writer() << boost::format("%2s %-20s %-s") % "" % signer.auto_config_token % monero_address;
11020 message_writer() << "";
11021 }
11022 }
11023
11024 void simple_wallet::add_signer_config_messages()
11025 {
11026 mms::message_store& ms = m_wallet->get_message_store();
11027 std::string signer_config;
11028 ms.get_signer_config(signer_config);
11029
11030 const std::vector<mms::authorized_signer> signers = ms.get_all_signers();
11031 mms::multisig_wallet_state state = get_multisig_wallet_state();
11032 uint32_t num_authorized_signers = ms.get_num_authorized_signers();
11033 for (uint32_t i = 1 /* without me */; i < num_authorized_signers; ++i)
11034 {
11035 ms.add_message(state, i, mms::message_type::signer_config, mms::message_direction::out, signer_config);
11036 }
11037 }
11038
11039 void simple_wallet::show_message(const mms::message &m)
11040 {
11041 mms::message_store& ms = m_wallet->get_message_store();
11042 const mms::authorized_signer &signer = ms.get_signer(m.signer_index);
11043 bool display_content;
11044 std::string sanitized_text;
11045 switch (m.type)
11046 {
11047 case mms::message_type::key_set:
11048 case mms::message_type::additional_key_set:
11049 case mms::message_type::note:
11050 display_content = true;
11051 sanitized_text = mms::message_store::get_sanitized_text(m.content, 1000);
11052 break;
11053 default:
11054 display_content = false;
11055 }
11056 uint64_t now = (uint64_t)time(NULL);
11057 message_writer() << "";
11058 message_writer() << tr("Message ") << m.id;
11059 message_writer() << tr("In/out: ") << ms.message_direction_to_string(m.direction);
11060 message_writer() << tr("Type: ") << ms.message_type_to_string(m.type);
11061 message_writer() << tr("State: ") << boost::format(tr("%s since %s, %s ago")) %
11062 ms.message_state_to_string(m.state) % tools::get_human_readable_timestamp(m.modified) % get_human_readable_timespan(std::chrono::seconds(now - m.modified));
11063 if (m.sent == 0)
11064 {
11065 message_writer() << tr("Sent: Never");
11066 }
11067 else
11068 {
11069 message_writer() << boost::format(tr("Sent: %s, %s ago")) %
11070 tools::get_human_readable_timestamp(m.sent) % get_human_readable_timespan(std::chrono::seconds(now - m.sent));
11071 }
11072 message_writer() << tr("Authorized signer: ") << ms.signer_to_string(signer, 100);
11073 message_writer() << tr("Content size: ") << m.content.length() << tr(" bytes");
11074 message_writer() << tr("Content: ") << (display_content ? sanitized_text : tr("(binary data)"));
11075
11076 if (m.type == mms::message_type::note)
11077 {
11078 // Showing a note and read its text is "processing" it: Set the state accordingly
11079 // which will also delete it from Bitmessage as a side effect
11080 // (Without this little "twist" it would never change the state, and never get deleted)
11081 ms.set_message_processed_or_sent(m.id);
11082 }
11083 }
11084
11085 void simple_wallet::ask_send_all_ready_messages()
11086 {
11087 mms::message_store& ms = m_wallet->get_message_store();
11088 std::vector<mms::message> ready_messages;
11089 const std::vector<mms::message> &messages = ms.get_all_messages();
11090 for (size_t i = 0; i < messages.size(); ++i)
11091 {
11092 const mms::message &m = messages[i];
11093 if (m.state == mms::message_state::ready_to_send)
11094 {
11095 ready_messages.push_back(m);
11096 }
11097 }
11098 if (ready_messages.size() != 0)
11099 {
11100 list_mms_messages(ready_messages);
11101 bool send = ms.get_auto_send();
11102 if (!send)
11103 {
11104 send = user_confirms(tr("Send these messages now?"));
11105 }
11106 if (send)
11107 {
11108 mms::multisig_wallet_state state = get_multisig_wallet_state();
11109 for (size_t i = 0; i < ready_messages.size(); ++i)
11110 {
11111 ms.send_message(state, ready_messages[i].id);
11112 ms.set_message_processed_or_sent(ready_messages[i].id);
11113 }
11114 success_msg_writer() << tr("Queued for sending.");
11115 }
11116 }
11117 }
11118
11119 bool simple_wallet::get_message_from_arg(const std::string &arg, mms::message &m)
11120 {
11121 mms::message_store& ms = m_wallet->get_message_store();
11122 bool valid_id = false;
11123 uint32_t id;
11124 try
11125 {
11126 id = (uint32_t)boost::lexical_cast<uint32_t>(arg);
11127 valid_id = ms.get_message_by_id(id, m);
11128 }
11129 catch (const boost::bad_lexical_cast &)
11130 {
11131 }
11132 if (!valid_id)
11133 {
11134 fail_msg_writer() << tr("Invalid message id");
11135 }
11136 return valid_id;
11137 }
11138
11139 void simple_wallet::mms_init(const std::vector<std::string> &args)
11140 {
11141 if (args.size() != 3)
11142 {
11143 fail_msg_writer() << tr("usage: mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
11144 return;
11145 }
11146 mms::message_store& ms = m_wallet->get_message_store();
11147 if (ms.get_active())
11148 {
11149 if (!user_confirms(tr("The MMS is already initialized. Re-initialize by deleting all signer info and messages?")))
11150 {
11151 return;
11152 }
11153 }
11154 uint32_t num_required_signers;
11155 uint32_t num_authorized_signers;
11156 const std::string &mn = args[0];
11157 std::vector<std::string> numbers;
11158 boost::split(numbers, mn, boost::is_any_of("/"));
11159 bool mn_ok = (numbers.size() == 2)
11160 && get_number_from_arg(numbers[1], num_authorized_signers, 2, config::MULTISIG_MAX_SIGNERS)
11161 && get_number_from_arg(numbers[0], num_required_signers, 1, num_authorized_signers);
11162 if (!mn_ok)
11163 {
11164 fail_msg_writer() << tr("Error in the number of required signers and/or authorized signers");
11165 return;
11166 }
11167 LOCK_IDLE_SCOPE();
11168 ms.init(get_multisig_wallet_state(), args[1], args[2], num_authorized_signers, num_required_signers);
11169 }
11170
11171 void simple_wallet::mms_info(const std::vector<std::string> &args)
11172 {
11173 mms::message_store& ms = m_wallet->get_message_store();
11174 if (ms.get_active())
11175 {
11176 message_writer() << boost::format("The MMS is active for %s/%s multisig.")
11177 % ms.get_num_required_signers() % ms.get_num_authorized_signers();
11178 }
11179 else
11180 {
11181 message_writer() << tr("The MMS is not active.");
11182 }
11183 }
11184
11185 void simple_wallet::mms_signer(const std::vector<std::string> &args)
11186 {
11187 mms::message_store& ms = m_wallet->get_message_store();
11188 const std::vector<mms::authorized_signer> &signers = ms.get_all_signers();
11189 if (args.size() == 0)
11190 {
11191 // Without further parameters list all defined signers
11192 list_signers(signers);
11193 return;
11194 }
11195
11196 uint32_t index;
11197 bool index_valid = get_number_from_arg(args[0], index, 1, ms.get_num_authorized_signers());
11198 if (index_valid)
11199 {
11200 index--;
11201 }
11202 else
11203 {
11204 fail_msg_writer() << tr("Invalid signer number ") + args[0];
11205 return;
11206 }
11207 if ((args.size() < 2) || (args.size() > 4))
11208 {
11209 fail_msg_writer() << tr("mms signer [<number> <label> [<transport_address> [<monero_address>]]]");
11210 return;
11211 }
11212
11213 boost::optional<string> label = args[1];
11214 boost::optional<string> transport_address;
11215 if (args.size() >= 3)
11216 {
11217 transport_address = args[2];
11218 }
11219 boost::optional<cryptonote::account_public_address> monero_address;
11220 LOCK_IDLE_SCOPE();
11221 mms::multisig_wallet_state state = get_multisig_wallet_state();
11222 if (args.size() == 4)
11223 {
11224 cryptonote::address_parse_info info;
11225 bool ok = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[3], oa_prompter);
11226 if (!ok)
11227 {
11228 fail_msg_writer() << tr("Invalid Monero address");
11229 return;
11230 }
11231 monero_address = info.address;
11232 const std::vector<mms::message> &messages = ms.get_all_messages();
11233 if ((messages.size() > 0) || state.multisig)
11234 {
11235 fail_msg_writer() << tr("Wallet state does not allow changing Monero addresses anymore");
11236 return;
11237 }
11238 }
11239 ms.set_signer(state, index, label, transport_address, monero_address);
11240 }
11241
11242 void simple_wallet::mms_list(const std::vector<std::string> &args)
11243 {
11244 mms::message_store& ms = m_wallet->get_message_store();
11245 if (args.size() != 0)
11246 {
11247 fail_msg_writer() << tr("Usage: mms list");
11248 return;
11249 }
11250 LOCK_IDLE_SCOPE();
11251 const std::vector<mms::message> &messages = ms.get_all_messages();
11252 list_mms_messages(messages);
11253 }
11254
11255 void simple_wallet::mms_next(const std::vector<std::string> &args)
11256 {
11257 mms::message_store& ms = m_wallet->get_message_store();
11258 if ((args.size() > 1) || ((args.size() == 1) && (args[0] != "sync")))
11259 {
11260 fail_msg_writer() << tr("Usage: mms next [sync]");
11261 return;
11262 }
11263 bool avail = false;
11264 std::vector<mms::processing_data> data_list;
11265 bool force_sync = false;
11266 uint32_t choice = 0;
11267 {
11268 LOCK_IDLE_SCOPE();
11269 if ((args.size() == 1) && (args[0] == "sync"))
11270 {
11271 // Force the MMS to process any waiting sync info although on its own it would just ignore
11272 // those messages because no need to process them can be seen
11273 force_sync = true;
11274 }
11275 string wait_reason;
11276 {
11277 avail = ms.get_processable_messages(get_multisig_wallet_state(), force_sync, data_list, wait_reason);
11278 }
11279 if (avail)
11280 {
11281 avail = choose_mms_processing(data_list, choice);
11282 }
11283 else if (!wait_reason.empty())
11284 {
11285 message_writer() << tr("No next step: ") << wait_reason;
11286 }
11287 }
11288 if (avail)
11289 {
11290 mms::processing_data data = data_list[choice];
11291 bool command_successful = false;
11292 switch(data.processing)
11293 {
11294 case mms::message_processing::prepare_multisig:
11295 message_writer() << tr("prepare_multisig");
11296 command_successful = prepare_multisig_main(std::vector<std::string>(), true);
11297 break;
11298
11299 case mms::message_processing::make_multisig:
11300 {
11301 message_writer() << tr("make_multisig");
11302 size_t number_of_key_sets = data.message_ids.size();
11303 std::vector<std::string> sig_args(number_of_key_sets + 1);
11304 sig_args[0] = std::to_string(ms.get_num_required_signers());
11305 for (size_t i = 0; i < number_of_key_sets; ++i)
11306 {
11307 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11308 sig_args[i+1] = m.content;
11309 }
11310 command_successful = make_multisig_main(sig_args, true);
11311 break;
11312 }
11313
11314 case mms::message_processing::exchange_multisig_keys:
11315 {
11316 message_writer() << tr("exchange_multisig_keys");
11317 size_t number_of_key_sets = data.message_ids.size();
11318 // Other than "make_multisig" only the key sets as parameters, no num_required_signers
11319 std::vector<std::string> sig_args(number_of_key_sets);
11320 for (size_t i = 0; i < number_of_key_sets; ++i)
11321 {
11322 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11323 sig_args[i] = m.content;
11324 }
11325 // todo: update mms to enable 'key exchange force updating'
11326 command_successful = exchange_multisig_keys_main(sig_args, false, true);
11327 break;
11328 }
11329
11330 case mms::message_processing::create_sync_data:
11331 {
11332 message_writer() << tr("export_multisig_info");
11333 std::vector<std::string> export_args;
11334 export_args.push_back("MMS"); // dummy filename
11335 command_successful = export_multisig_main(export_args, true);
11336 break;
11337 }
11338
11339 case mms::message_processing::process_sync_data:
11340 {
11341 message_writer() << tr("import_multisig_info");
11342 std::vector<std::string> import_args;
11343 for (size_t i = 0; i < data.message_ids.size(); ++i)
11344 {
11345 mms::message m = ms.get_message_by_id(data.message_ids[i]);
11346 import_args.push_back(m.content);
11347 }
11348 command_successful = import_multisig_main(import_args, true);
11349 break;
11350 }
11351
11352 case mms::message_processing::sign_tx:
11353 {
11354 message_writer() << tr("sign_multisig");
11355 std::vector<std::string> sign_args;
11356 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11357 sign_args.push_back(m.content);
11358 command_successful = sign_multisig_main(sign_args, true);
11359 break;
11360 }
11361
11362 case mms::message_processing::submit_tx:
11363 {
11364 message_writer() << tr("submit_multisig");
11365 std::vector<std::string> submit_args;
11366 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11367 submit_args.push_back(m.content);
11368 command_successful = submit_multisig_main(submit_args, true);
11369 break;
11370 }
11371
11372 case mms::message_processing::send_tx:
11373 {
11374 message_writer() << tr("Send tx");
11375 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11376 LOCK_IDLE_SCOPE();
11377 ms.add_message(get_multisig_wallet_state(), data.receiving_signer_index, m.type, mms::message_direction::out,
11378 m.content);
11379 command_successful = true;
11380 break;
11381 }
11382
11383 case mms::message_processing::process_signer_config:
11384 {
11385 message_writer() << tr("Process signer config");
11386 LOCK_IDLE_SCOPE();
11387 mms::message m = ms.get_message_by_id(data.message_ids[0]);
11388 mms::authorized_signer me = ms.get_signer(0);
11389 mms::multisig_wallet_state state = get_multisig_wallet_state();
11390 if (!me.auto_config_running)
11391 {
11392 // If no auto-config is running, the config sent may be unsolicited or problematic
11393 // so show what arrived and ask for confirmation before taking it in
11394 std::vector<mms::authorized_signer> signers;
11395 ms.unpack_signer_config(state, m.content, signers);
11396 list_signers(signers);
11397 if (!user_confirms(tr("Replace current signer config with the one displayed above?")))
11398 {
11399 break;
11400 }
11401 if (!user_confirms_auto_config())
11402 {
11403 message_writer() << tr("You can use the \"mms delete\" command to delete any unwanted message");
11404 break;
11405 }
11406 }
11407 ms.process_signer_config(state, m.content);
11408 ms.stop_auto_config();
11409 list_signers(ms.get_all_signers());
11410 command_successful = true;
11411 break;
11412 }
11413
11414 case mms::message_processing::process_auto_config_data:
11415 {
11416 message_writer() << tr("Process auto config data");
11417 LOCK_IDLE_SCOPE();
11418 for (size_t i = 0; i < data.message_ids.size(); ++i)
11419 {
11420 ms.process_auto_config_data_message(data.message_ids[i]);
11421 }
11422 ms.stop_auto_config();
11423 list_signers(ms.get_all_signers());
11424 add_signer_config_messages();
11425 command_successful = true;
11426 break;
11427 }
11428
11429 default:
11430 message_writer() << tr("Nothing ready to process");
11431 break;
11432 }
11433
11434 if (command_successful)
11435 {
11436 {
11437 LOCK_IDLE_SCOPE();
11438 ms.set_messages_processed(data);
11439 ask_send_all_ready_messages();
11440 }
11441 }
11442 }
11443 }
11444
11445 void simple_wallet::mms_sync(const std::vector<std::string> &args)
11446 {
11447 if (args.size() != 0)
11448 {
11449 fail_msg_writer() << tr("Usage: mms sync");
11450 return;
11451 }
11452 // Force the start of a new sync round, for exceptional cases where something went wrong
11453 // Can e.g. solve the problem "This signature was made with stale data" after trying to
11454 // create 2 transactions in a row somehow
11455 // Code is identical to the code for 'message_processing::create_sync_data'
11456 message_writer() << tr("export_multisig_info");
11457 std::vector<std::string> export_args;
11458 export_args.push_back("MMS"); // dummy filename
11459 export_multisig_main(export_args, true);
11460 ask_send_all_ready_messages();
11461 }
11462
11463 void simple_wallet::mms_transfer(const std::vector<std::string> &args)
11464 {
11465 // It's too complicated to check any arguments here, just let 'transfer_main' do the whole job
11466 transfer_main(args, true);
11467 }
11468
11469 void simple_wallet::mms_delete(const std::vector<std::string> &args)
11470 {
11471 if (args.size() != 1)
11472 {
11473 fail_msg_writer() << tr("Usage: mms delete (<message_id> | all)");
11474 return;
11475 }
11476 LOCK_IDLE_SCOPE();
11477 mms::message_store& ms = m_wallet->get_message_store();
11478 if (args[0] == "all")
11479 {
11480 if (user_confirms(tr("Delete all messages?")))
11481 {
11482 ms.delete_all_messages();
11483 }
11484 }
11485 else
11486 {
11487 mms::message m;
11488 bool valid_id = get_message_from_arg(args[0], m);
11489 if (valid_id)
11490 {
11491 // If only a single message and not all delete even if unsent / unprocessed
11492 ms.delete_message(m.id);
11493 }
11494 }
11495 }
11496
11497 void simple_wallet::mms_send(const std::vector<std::string> &args)
11498 {
11499 if (args.size() == 0)
11500 {
11501 ask_send_all_ready_messages();
11502 return;
11503 }
11504 else if (args.size() != 1)
11505 {
11506 fail_msg_writer() << tr("Usage: mms send [<message_id>]");
11507 return;
11508 }
11509 LOCK_IDLE_SCOPE();
11510 mms::message_store& ms = m_wallet->get_message_store();
11511 mms::message m;
11512 bool valid_id = get_message_from_arg(args[0], m);
11513 if (valid_id)
11514 {
11515 ms.send_message(get_multisig_wallet_state(), m.id);
11516 }
11517 }
11518
11519 void simple_wallet::mms_receive(const std::vector<std::string> &args)
11520 {
11521 if (args.size() != 0)
11522 {
11523 fail_msg_writer() << tr("Usage: mms receive");
11524 return;
11525 }
11526 std::vector<mms::message> new_messages;
11527 LOCK_IDLE_SCOPE();
11528 mms::message_store& ms = m_wallet->get_message_store();
11529 bool avail = ms.check_for_messages(get_multisig_wallet_state(), new_messages);
11530 if (avail)
11531 {
11532 list_mms_messages(new_messages);
11533 }
11534 }
11535
11536 void simple_wallet::mms_export(const std::vector<std::string> &args)
11537 {
11538 if (args.size() != 1)
11539 {
11540 fail_msg_writer() << tr("Usage: mms export <message_id>");
11541 return;
11542 }
11543 LOCK_IDLE_SCOPE();
11544 mms::message m;
11545 bool valid_id = get_message_from_arg(args[0], m);
11546 if (valid_id)
11547 {
11548 const std::string filename = "mms_message_content";
11549 if (m_wallet->save_to_file(filename, m.content))
11550 {
11551 success_msg_writer() << tr("Message content saved to: ") << filename;
11552 }
11553 else
11554 {
11555 fail_msg_writer() << tr("Failed to to save message content");
11556 }
11557 }
11558 }
11559
11560 void simple_wallet::mms_note(const std::vector<std::string> &args)
11561 {
11562 mms::message_store& ms = m_wallet->get_message_store();
11563 if (args.size() == 0)
11564 {
11565 LOCK_IDLE_SCOPE();
11566 const std::vector<mms::message> &messages = ms.get_all_messages();
11567 for (size_t i = 0; i < messages.size(); ++i)
11568 {
11569 const mms::message &m = messages[i];
11570 if ((m.type == mms::message_type::note) && (m.state == mms::message_state::waiting))
11571 {
11572 show_message(m);
11573 }
11574 }
11575 return;
11576 }
11577 if (args.size() < 2)
11578 {
11579 fail_msg_writer() << tr("Usage: mms note [<label> <text>]");
11580 return;
11581 }
11582 uint32_t signer_index;
11583 bool found = ms.get_signer_index_by_label(args[0], signer_index);
11584 if (!found)
11585 {
11586 fail_msg_writer() << tr("No signer found with label ") << args[0];
11587 return;
11588 }
11589 std::string note = "";
11590 for (size_t n = 1; n < args.size(); ++n)
11591 {
11592 if (n > 1)
11593 {
11594 note += " ";
11595 }
11596 note += args[n];
11597 }
11598 LOCK_IDLE_SCOPE();
11599 ms.add_message(get_multisig_wallet_state(), signer_index, mms::message_type::note,
11600 mms::message_direction::out, note);
11601 ask_send_all_ready_messages();
11602 }
11603
11604 void simple_wallet::mms_show(const std::vector<std::string> &args)
11605 {
11606 if (args.size() != 1)
11607 {
11608 fail_msg_writer() << tr("Usage: mms show <message_id>");
11609 return;
11610 }
11611 LOCK_IDLE_SCOPE();
11612 mms::message m;
11613 bool valid_id = get_message_from_arg(args[0], m);
11614 if (valid_id)
11615 {
11616 show_message(m);
11617 }
11618 }
11619
11620 void simple_wallet::mms_set(const std::vector<std::string> &args)
11621 {
11622 bool set = args.size() == 2;
11623 bool query = args.size() == 1;
11624 if (!set && !query)
11625 {
11626 fail_msg_writer() << tr("Usage: mms set <option_name> [<option_value>]");
11627 return;
11628 }
11629 mms::message_store& ms = m_wallet->get_message_store();
11630 LOCK_IDLE_SCOPE();
11631 if (args[0] == "auto-send")
11632 {
11633 if (set)
11634 {
11635 bool result;
11636 bool ok = parse_bool(args[1], result);
11637 if (ok)
11638 {
11639 ms.set_auto_send(result);
11640 }
11641 else
11642 {
11643 fail_msg_writer() << tr("Wrong option value");
11644 }
11645 }
11646 else
11647 {
11648 message_writer() << (ms.get_auto_send() ? tr("Auto-send is on") : tr("Auto-send is off"));
11649 }
11650 }
11651 else
11652 {
11653 fail_msg_writer() << tr("Unknown option");
11654 }
11655 }
11656
11657 void simple_wallet::mms_help(const std::vector<std::string> &args)
11658 {
11659 if (args.size() > 1)
11660 {
11661 fail_msg_writer() << tr("Usage: help mms [<subcommand>]");
11662 return;
11663 }
11664 std::vector<std::string> help_args;
11665 help_args.push_back("mms");
11666 if (args.size() == 1)
11667 {
11668 help_args.push_back(args[0]);
11669 }
11670 help(help_args);
11671 }
11672
11673 void simple_wallet::mms_send_signer_config(const std::vector<std::string> &args)
11674 {
11675 if (args.size() != 0)
11676 {
11677 fail_msg_writer() << tr("Usage: mms send_signer_config");
11678 return;
11679 }
11680 mms::message_store& ms = m_wallet->get_message_store();
11681 if (!ms.signer_config_complete())
11682 {
11683 fail_msg_writer() << tr("Signer config not yet complete");
11684 return;
11685 }
11686 LOCK_IDLE_SCOPE();
11687 add_signer_config_messages();
11688 ask_send_all_ready_messages();
11689 }
11690
11691 void simple_wallet::mms_start_auto_config(const std::vector<std::string> &args)
11692 {
11693 mms::message_store& ms = m_wallet->get_message_store();
11694 uint32_t other_signers = ms.get_num_authorized_signers() - 1;
11695 size_t args_size = args.size();
11696 if ((args_size != 0) && (args_size != other_signers))
11697 {
11698 fail_msg_writer() << tr("Usage: mms start_auto_config [<label> <label> ...]");
11699 return;
11700 }
11701 if ((args_size == 0) && !ms.signer_labels_complete())
11702 {
11703 fail_msg_writer() << tr("There are signers without a label set. Complete labels before auto-config or specify them as parameters here.");
11704 return;
11705 }
11706 mms::authorized_signer me = ms.get_signer(0);
11707 if (me.auto_config_running)
11708 {
11709 if (!user_confirms(tr("Auto-config is already running. Cancel and restart?")))
11710 {
11711 return;
11712 }
11713 }
11714 LOCK_IDLE_SCOPE();
11715 mms::multisig_wallet_state state = get_multisig_wallet_state();
11716 if (args_size != 0)
11717 {
11718 // Set (or overwrite) all the labels except "me" from the arguments
11719 for (uint32_t i = 1; i < (other_signers + 1); ++i)
11720 {
11721 ms.set_signer(state, i, args[i - 1], boost::none, boost::none);
11722 }
11723 }
11724 ms.start_auto_config(state);
11725 // List the signers to show the generated auto-config tokens
11726 list_signers(ms.get_all_signers());
11727 }
11728
11729 void simple_wallet::mms_config_checksum(const std::vector<std::string> &args)
11730 {
11731 if (args.size() != 0)
11732 {
11733 fail_msg_writer() << tr("Usage: mms config_checksum");
11734 return;
11735 }
11736 mms::message_store& ms = m_wallet->get_message_store();
11737 LOCK_IDLE_SCOPE();
11738 message_writer() << ms.get_config_checksum();
11739 }
11740
11741 void simple_wallet::mms_stop_auto_config(const std::vector<std::string> &args)
11742 {
11743 if (args.size() != 0)
11744 {
11745 fail_msg_writer() << tr("Usage: mms stop_auto_config");
11746 return;
11747 }
11748 if (!user_confirms(tr("Delete any auto-config tokens and stop auto-config?")))
11749 {
11750 return;
11751 }
11752 mms::message_store& ms = m_wallet->get_message_store();
11753 LOCK_IDLE_SCOPE();
11754 ms.stop_auto_config();
11755 }
11756
11757 void simple_wallet::mms_auto_config(const std::vector<std::string> &args)
11758 {
11759 if (args.size() != 1)
11760 {
11761 fail_msg_writer() << tr("Usage: mms auto_config <auto_config_token>");
11762 return;
11763 }
11764 mms::message_store& ms = m_wallet->get_message_store();
11765 std::string adjusted_token;
11766 if (!ms.check_auto_config_token(args[0], adjusted_token))
11767 {
11768 fail_msg_writer() << tr("Invalid auto-config token");
11769 return;
11770 }
11771 if (!user_confirms_auto_config())
11772 {
11773 return;
11774 }
11775 mms::authorized_signer me = ms.get_signer(0);
11776 if (me.auto_config_running)
11777 {
11778 if (!user_confirms(tr("Auto-config already running. Cancel and restart?")))
11779 {
11780 return;
11781 }
11782 }
11783 LOCK_IDLE_SCOPE();
11784 ms.add_auto_config_data_message(get_multisig_wallet_state(), adjusted_token);
11785 ask_send_all_ready_messages();
11786 }
11787
11788 bool simple_wallet::mms(const std::vector<std::string> &args)
11789 {
11790 CHECK_MULTISIG_ENABLED();
11791 try
11792 {
11793 m_wallet->get_multisig_wallet_state();
11794 }
11795 catch(const std::exception &e)
11796 {
11797 fail_msg_writer() << tr("MMS not available in this wallet");
11798 return true;
11799 }
11800
11801 try
11802 {
11803 mms::message_store& ms = m_wallet->get_message_store();
11804 if (args.size() == 0)
11805 {
11806 mms_info(args);
11807 return true;
11808 }
11809
11810 const std::string &sub_command = args[0];
11811 std::vector<std::string> mms_args = args;
11812 mms_args.erase(mms_args.begin());
11813
11814 if (sub_command == "init")
11815 {
11816 mms_init(mms_args);
11817 return true;
11818 }
11819 if (!ms.get_active())
11820 {
11821 fail_msg_writer() << tr("The MMS is not active. Activate using the \"mms init\" command");
11822 return true;
11823 }
11824 else if (sub_command == "info")
11825 {
11826 mms_info(mms_args);
11827 }
11828 else if (sub_command == "signer")
11829 {
11830 mms_signer(mms_args);
11831 }
11832 else if (sub_command == "list")
11833 {
11834 mms_list(mms_args);
11835 }
11836 else if (sub_command == "next")
11837 {
11838 mms_next(mms_args);
11839 }
11840 else if (sub_command == "sync")
11841 {
11842 mms_sync(mms_args);
11843 }
11844 else if (sub_command == "transfer")
11845 {
11846 mms_transfer(mms_args);
11847 }
11848 else if (sub_command == "delete")
11849 {
11850 mms_delete(mms_args);
11851 }
11852 else if (sub_command == "send")
11853 {
11854 mms_send(mms_args);
11855 }
11856 else if (sub_command == "receive")
11857 {
11858 mms_receive(mms_args);
11859 }
11860 else if (sub_command == "export")
11861 {
11862 mms_export(mms_args);
11863 }
11864 else if (sub_command == "note")
11865 {
11866 mms_note(mms_args);
11867 }
11868 else if (sub_command == "show")
11869 {
11870 mms_show(mms_args);
11871 }
11872 else if (sub_command == "set")
11873 {
11874 mms_set(mms_args);
11875 }
11876 else if (sub_command == "help")
11877 {
11878 mms_help(mms_args);
11879 }
11880 else if (sub_command == "send_signer_config")
11881 {
11882 mms_send_signer_config(mms_args);
11883 }
11884 else if (sub_command == "start_auto_config")
11885 {
11886 mms_start_auto_config(mms_args);
11887 }
11888 else if (sub_command == "config_checksum")
11889 {
11890 mms_config_checksum(mms_args);
11891 }
11892 else if (sub_command == "stop_auto_config")
11893 {
11894 mms_stop_auto_config(mms_args);
11895 }
11896 else if (sub_command == "auto_config")
11897 {
11898 mms_auto_config(mms_args);
11899 }
11900 else
11901 {
11902 fail_msg_writer() << tr("Invalid MMS subcommand");
11903 }
11904 }
11905 catch (const tools::error::no_connection_to_daemon &e)
11906 {
11907 fail_msg_writer() << tr("Error in MMS command: ") << e.what() << " " << e.request();
11908 }
11909 catch (const std::exception &e)
11910 {
11911 fail_msg_writer() << tr("Error in MMS command: ") << e.what();
11912 PRINT_USAGE(USAGE_MMS);
11913 return true;
11914 }
11915 return true;
11916 }
11917 // End MMS ------------------------------------------------------------------------------------------------