-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathsimplewallet.cpp
11561 lines (10783 loc) · 420 KB
/
simplewallet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014-2024, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
/*!
* \file simplewallet.cpp
*
* \brief Source file that defines simple_wallet class.
*/
// use boost bind placeholders for now
#define BOOST_BIND_GLOBAL_PLACEHOLDERS 1
#include <boost/bind.hpp>
#include <locale.h>
#include <thread>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctype.h>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/filesystem.hpp>
#include "include_base_utils.h"
#include "console_handler.h"
#include "common/i18n.h"
#include "common/command_line.h"
#include "common/util.h"
#include "common/dns_utils.h"
#include "common/base58.h"
#include "common/scoped_message_writer.h"
#include "cryptonote_protocol/cryptonote_protocol_handler.h"
#include "simplewallet.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "storages/http_abstract_invoke.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "crypto/crypto.h" // for crypto::secret_key definition
#include "mnemonics/electrum-words.h"
#include "rapidjson/document.h"
#include "common/json_util.h"
#include "ringct/rctSigs.h"
#include "multisig/multisig.h"
#include "wallet/wallet_args.h"
#include "version.h"
#include <stdexcept>
#include "wallet/message_store.h"
#include "QrCode.hpp"
#ifdef WIN32
#include <boost/locale.hpp>
#include <boost/filesystem.hpp>
#include <fcntl.h>
#endif
#ifdef HAVE_READLINE
#include "readline_buffer.h"
#endif
using namespace std;
using namespace epee;
using namespace cryptonote;
using boost::lexical_cast;
namespace po = boost::program_options;
typedef cryptonote::simple_wallet sw;
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "wallet.simplewallet"
#define EXTENDED_LOGS_FILE "wallet_details.log"
#define OLD_AGE_WARN_THRESHOLD (30 * 86400 / DIFFICULTY_TARGET_V2) // 30 days
#define LOCK_IDLE_SCOPE() \
bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \
m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \
/* stop any background refresh and other processes, and take over */ \
m_wallet->stop(); \
boost::unique_lock<boost::mutex> lock(m_idle_mutex); \
m_idle_cond.notify_all(); \
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \
/* m_idle_mutex is still locked here */ \
m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \
m_idle_cond.notify_one(); \
})
#define SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(code) \
LOCK_IDLE_SCOPE(); \
boost::optional<tools::password_container> pwd_container = boost::none; \
if (m_wallet->ask_password() && !(pwd_container = get_and_verify_password())) { code; } \
tools::wallet_keys_unlocker unlocker(*m_wallet, pwd_container);
#define SCOPED_WALLET_UNLOCK() SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(return true;)
#define PRINT_USAGE(usage_help) fail_msg_writer() << boost::format(tr("usage: %s")) % usage_help;
#define LONG_PAYMENT_ID_SUPPORT_CHECK() \
do { \
fail_msg_writer() << tr("Error: Long payment IDs are obsolete."); \
fail_msg_writer() << tr("Long payment IDs were not encrypted on the blockchain and would harm your privacy."); \
fail_msg_writer() << tr("If the party you're sending to still requires a long payment ID, please notify them."); \
return true; \
} while(0)
#define REFRESH_PERIOD 90 // seconds
#define MAX_MNEW_ADDRESSES 1000
#define CHECK_MULTISIG_ENABLED() \
do \
{ \
if (!m_wallet->is_multisig_enabled()) \
{ \
fail_msg_writer() << tr("Multisig is disabled."); \
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."); \
fail_msg_writer() << tr("You can enable it with:"); \
fail_msg_writer() << tr(" set enable-multisig-experimental 1"); \
return false; \
} \
} while(0)
#define CHECK_IF_BACKGROUND_SYNCING(msg) \
do \
{ \
if (m_wallet->is_background_wallet() || m_wallet->is_background_syncing()) \
{ \
std::string type = m_wallet->is_background_wallet() ? "background wallet" : "background syncing wallet"; \
fail_msg_writer() << boost::format(tr("%s %s")) % type % msg; \
return false; \
} \
} while (0)
static std::string get_human_readable_timespan(std::chrono::seconds seconds);
static std::string get_human_readable_timespan(uint64_t seconds);
namespace
{
const std::array<const char* const, 5> allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}};
const auto arg_wallet_file = wallet_args::arg_wallet_file();
const command_line::arg_descriptor<std::string> arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to <arg>"), ""};
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>"), ""};
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"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_spend_key = {"generate-from-spend-key", sw::tr("Generate deterministic wallet from spend key"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_keys = {"generate-from-keys", sw::tr("Generate wallet from private keys"), ""};
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"), ""};
const auto arg_generate_from_json = wallet_args::arg_generate_from_json();
const command_line::arg_descriptor<std::string> arg_mnemonic_language = {"mnemonic-language", sw::tr("Language for mnemonic"), ""};
const command_line::arg_descriptor<std::string> arg_electrum_seed = {"electrum-seed", sw::tr("Specify Electrum seed for wallet recovery/creation"), ""};
const command_line::arg_descriptor<bool> arg_restore_deterministic_wallet = {"restore-deterministic-wallet", sw::tr("Recover wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_restore_from_seed = {"restore-from-seed", sw::tr("alias for --restore-deterministic-wallet"), false};
const command_line::arg_descriptor<bool> arg_restore_multisig_wallet = {"restore-multisig-wallet", sw::tr("Recover multisig wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_non_deterministic = {"non-deterministic", sw::tr("Generate non-deterministic view and spend keys"), false};
const command_line::arg_descriptor<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0};
const command_line::arg_descriptor<std::string> arg_restore_date = {"restore-date", sw::tr("Restore from estimated blockchain height on specified date"), ""};
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};
const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false};
const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""};
const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false};
const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""};
const char* USAGE_START_MINING("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]");
const char* USAGE_SET_DAEMON("set_daemon <host>[:<port>] [trusted|untrusted|this-is-probably-a-spy-node]");
const char* USAGE_SHOW_BALANCE("balance [detail]");
const char* USAGE_INCOMING_TRANSFERS("incoming_transfers [available|unavailable] [verbose] [uses] [index=<N1>[,<N2>[,...]]]");
const char* USAGE_PAYMENTS("payments <PID_1> [<PID_2> ... <PID_N>]");
const char* USAGE_PAYMENT_ID("payment_id");
const char* USAGE_TRANSFER("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [subtractfeefrom=<D0>[,<D1>,all,...]] [<payment_id>]");
const char* USAGE_SWEEP_ALL("sweep_all [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_ACCOUNT("sweep_account <account> [index=<N1>[,<N2>,...] | index=all] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_BELOW("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id (obsolete)>]");
const char* USAGE_SWEEP_SINGLE("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id (obsolete)>]");
const char* USAGE_DONATE("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id (obsolete)>]");
const char* USAGE_SIGN_TRANSFER("sign_transfer [export_raw] [<filename>]");
const char* USAGE_SET_LOG("set_log <level>|{+,-,}<categories>");
const char* USAGE_ACCOUNT("account\n"
" account new <label text with white spaces allowed>\n"
" account switch <index> \n"
" account label <index> <label text with white spaces allowed>\n"
" account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
" account untag <account_index_1> [<account_index_2> ...]\n"
" account tag_description <tag_name> <description>");
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>]");
const char* USAGE_INTEGRATED_ADDRESS("integrated_address [device] [<payment_id> | <address>]");
const char* USAGE_ADDRESS_BOOK("address_book [(add (<address>|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]");
const char* USAGE_SET_VARIABLE("set <option> [<value>]");
const char* USAGE_GET_TX_KEY("get_tx_key <txid>");
const char* USAGE_SET_TX_KEY("set_tx_key <txid> <tx_key> [<subaddress>]");
const char* USAGE_CHECK_TX_KEY("check_tx_key <txid> <txkey> <address>");
const char* USAGE_GET_TX_PROOF("get_tx_proof <txid> <address> [<message>]");
const char* USAGE_CHECK_TX_PROOF("check_tx_proof <txid> <address> <signature_file> [<message>]");
const char* USAGE_GET_SPEND_PROOF("get_spend_proof <txid> [<message>]");
const char* USAGE_CHECK_SPEND_PROOF("check_spend_proof <txid> <signature_file> [<message>]");
const char* USAGE_GET_RESERVE_PROOF("get_reserve_proof (all|<amount>) [<message>]");
const char* USAGE_CHECK_RESERVE_PROOF("check_reserve_proof <address> <signature_file> [<message>]");
const char* USAGE_SHOW_TRANSFERS("show_transfers [in|out|all|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
const char* USAGE_UNSPENT_OUTPUTS("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]");
const char* USAGE_RESCAN_BC("rescan_bc [hard|soft|keep_ki] [start_height=0]");
const char* USAGE_SET_TX_NOTE("set_tx_note <txid> [free text note]");
const char* USAGE_GET_TX_NOTE("get_tx_note <txid>");
const char* USAGE_GET_DESCRIPTION("get_description");
const char* USAGE_SET_DESCRIPTION("set_description [free text note]");
const char* USAGE_SIGN("sign [<account_index>,<address_index>] [--spend|--view] <filename>");
const char* USAGE_VERIFY("verify <filename> <address> <signature>");
const char* USAGE_EXPORT_KEY_IMAGES("export_key_images [all] <filename>");
const char* USAGE_IMPORT_KEY_IMAGES("import_key_images <filename>");
const char* USAGE_HW_KEY_IMAGES_SYNC("hw_key_images_sync");
const char* USAGE_HW_RECONNECT("hw_reconnect");
const char* USAGE_EXPORT_OUTPUTS("export_outputs [all] <filename>");
const char* USAGE_IMPORT_OUTPUTS("import_outputs <filename>");
const char* USAGE_SHOW_TRANSFER("show_transfer <txid>");
const char* USAGE_MAKE_MULTISIG("make_multisig <threshold> <string1> [<string>...]");
const char* USAGE_EXCHANGE_MULTISIG_KEYS("exchange_multisig_keys [force-update-use-with-caution] <string> [<string>...]");
const char* USAGE_EXPORT_MULTISIG_INFO("export_multisig_info <filename>");
const char* USAGE_IMPORT_MULTISIG_INFO("import_multisig_info <filename> [<filename>...]");
const char* USAGE_SIGN_MULTISIG("sign_multisig <filename>");
const char* USAGE_SUBMIT_MULTISIG("submit_multisig <filename>");
const char* USAGE_EXPORT_RAW_MULTISIG_TX("export_raw_multisig_tx <filename>");
const char* USAGE_MMS("mms [<subcommand> [<subcommand_parameters>]]");
const char* USAGE_MMS_INIT("mms init <required_signers>/<authorized_signers> <own_label> <own_transport_address>");
const char* USAGE_MMS_INFO("mms info");
const char* USAGE_MMS_SIGNER("mms signer [<number> <label> [<transport_address> [<monero_address>]]]");
const char* USAGE_MMS_LIST("mms list");
const char* USAGE_MMS_NEXT("mms next [sync]");
const char* USAGE_MMS_SYNC("mms sync");
const char* USAGE_MMS_TRANSFER("mms transfer <transfer_command_arguments>");
const char* USAGE_MMS_DELETE("mms delete (<message_id> | all)");
const char* USAGE_MMS_SEND("mms send [<message_id>]");
const char* USAGE_MMS_RECEIVE("mms receive");
const char* USAGE_MMS_EXPORT("mms export <message_id>");
const char* USAGE_MMS_NOTE("mms note [<label> <text>]");
const char* USAGE_MMS_SHOW("mms show <message_id>");
const char* USAGE_MMS_SET("mms set <option_name> [<option_value>]");
const char* USAGE_MMS_SEND_SIGNER_CONFIG("mms send_signer_config");
const char* USAGE_MMS_START_AUTO_CONFIG("mms start_auto_config [<label> <label> ...]");
const char* USAGE_MMS_CONFIG_CHECKSUM("mms config_checksum");
const char* USAGE_MMS_STOP_AUTO_CONFIG("mms stop_auto_config");
const char* USAGE_MMS_AUTO_CONFIG("mms auto_config <auto_config_token>");
const char* USAGE_PRINT_RING("print_ring <key_image> | <txid>");
const char* USAGE_SET_RING("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )");
const char* USAGE_UNSET_RING("unset_ring <txid> | ( <key_image> [<key_image>...] )");
const char* USAGE_SAVE_KNOWN_RINGS("save_known_rings");
const char* USAGE_MARK_OUTPUT_SPENT("mark_output_spent <amount>/<offset> | <filename> [add]");
const char* USAGE_MARK_OUTPUT_UNSPENT("mark_output_unspent <amount>/<offset>");
const char* USAGE_IS_OUTPUT_SPENT("is_output_spent <amount>/<offset>");
const char* USAGE_FREEZE("freeze <key_image>");
const char* USAGE_THAW("thaw <key_image>");
const char* USAGE_FROZEN("frozen <key_image>");
const char* USAGE_LOCK("lock");
const char* USAGE_NET_STATS("net_stats");
const char* USAGE_PUBLIC_NODES("public_nodes");
const char* USAGE_WELCOME("welcome");
const char* USAGE_SHOW_QR_CODE("show_qr_code [<subaddress_index>]");
const char* USAGE_VERSION("version");
const char* USAGE_HELP("help [<command> | all]");
const char* USAGE_APROPOS("apropos <keyword> [<keyword> ...]");
const char* USAGE_SCAN_TX("scan_tx <txid> [<txid> ...]");
std::string input_line(const std::string& prompt, bool yesno = false)
{
PAUSE_READLINE();
std::cout << prompt;
if (yesno)
std::cout << " (Y/Yes/N/No)";
std::cout << ": " << std::flush;
std::string buf;
#ifdef _WIN32
buf = tools::input_line_win();
#else
std::getline(std::cin, buf);
#endif
return epee::string_tools::trim(buf);
}
epee::wipeable_string input_secure_line(const char *prompt)
{
PAUSE_READLINE();
auto pwd_container = tools::password_container::prompt(false, prompt, false);
if (!pwd_container)
{
MERROR("Failed to read secure line");
return "";
}
epee::wipeable_string buf = pwd_container->password();
buf.trim();
return buf;
}
boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
{
PAUSE_READLINE();
auto pwd_container = tools::password_container::prompt(verify, prompt);
if (!pwd_container)
{
tools::fail_msg_writer() << sw::tr("failed to read password");
}
return pwd_container;
}
boost::optional<tools::password_container> default_password_prompter(bool verify)
{
return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify);
}
boost::optional<tools::password_container> background_sync_cache_password_prompter(bool verify)
{
return password_prompter(verify ? sw::tr("Enter a custom password for the background sync cache") : sw::tr("Background sync cache password"), verify);
}
inline std::string interpret_rpc_response(bool ok, const std::string& status)
{
std::string err;
if (ok)
{
if (status == CORE_RPC_STATUS_BUSY)
{
err = sw::tr("daemon is busy. Please try again later.");
}
else if (status != CORE_RPC_STATUS_OK)
{
err = status;
}
}
else
{
err = sw::tr("possibly lost connection to daemon");
}
return err;
}
tools::scoped_message_writer success_msg_writer(bool color = false)
{
return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info);
}
tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false)
{
return tools::scoped_message_writer(color, bright);
}
tools::scoped_message_writer fail_msg_writer()
{
return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error);
}
bool parse_bool(const std::string& s, bool& result)
{
if (s == "1" || command_line::is_yes(s))
{
result = true;
return true;
}
if (s == "0" || command_line::is_no(s))
{
result = false;
return true;
}
boost::algorithm::is_iequal ignore_case{};
if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case))
{
result = true;
return true;
}
if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case))
{
result = false;
return true;
}
return false;
}
template <typename F>
bool parse_bool_and_use(const std::string& s, F func)
{
bool r;
if (parse_bool(s, r))
{
func(r);
return true;
}
else
{
fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no");
return false;
}
}
const struct
{
const char *name;
tools::wallet2::RefreshType refresh_type;
} refresh_type_names[] =
{
{ "full", tools::wallet2::RefreshFull },
{ "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "no-coinbase", tools::wallet2::RefreshNoCoinbase },
{ "default", tools::wallet2::RefreshDefault },
};
bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (s == refresh_type_names[n].name)
{
refresh_type = refresh_type_names[n].refresh_type;
return true;
}
}
fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type");
return false;
}
std::string get_refresh_type_name(tools::wallet2::RefreshType type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (type == refresh_type_names[n].refresh_type)
return refresh_type_names[n].name;
}
return "invalid";
}
const struct
{
const char *name;
tools::wallet2::BackgroundSyncType background_sync_type;
} background_sync_type_names[] =
{
{ "off", tools::wallet2::BackgroundSyncOff },
{ "reuse-wallet-password", tools::wallet2::BackgroundSyncReusePassword },
{ "custom-background-password", tools::wallet2::BackgroundSyncCustomPassword },
};
bool parse_background_sync_type(const std::string &s, tools::wallet2::BackgroundSyncType &background_sync_type)
{
for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
{
if (s == background_sync_type_names[n].name)
{
background_sync_type = background_sync_type_names[n].background_sync_type;
return true;
}
}
fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse background sync type");
return false;
}
std::string get_background_sync_type_name(tools::wallet2::BackgroundSyncType type)
{
for (size_t n = 0; n < sizeof(background_sync_type_names) / sizeof(background_sync_type_names[0]); ++n)
{
if (type == background_sync_type_names[n].background_sync_type)
return background_sync_type_names[n].name;
}
return "invalid";
}
std::string get_version_string(uint32_t version)
{
return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff);
}
std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)
{
if (addresses.empty())
return {};
// prompt user for confirmation.
// inform user of DNSSEC validation status as well.
std::string dnssec_str;
if (dnssec_valid)
{
dnssec_str = sw::tr("DNSSEC validation passed");
}
else
{
dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!");
}
std::stringstream prompt;
prompt << sw::tr("For URL: ") << url
<< ", " << dnssec_str << std::endl
<< sw::tr(" Monero Address = ") << addresses[0]
<< std::endl
<< sw::tr("Is this OK?")
;
// prompt the user for confirmation given the dns query and dnssec status
std::string confirm_dns_ok = input_line(prompt.str(), true);
if (std::cin.eof())
{
return {};
}
if (!command_line::is_yes(confirm_dns_ok))
{
std::cout << sw::tr("you have cancelled the transfer request") << std::endl;
return {};
}
return addresses[0];
}
bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices)
{
subaddr_indices.clear();
if (arg.substr(0, 6) != "index=")
return false;
std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6);
std::vector<std::string> subaddr_indices_str;
boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(","));
for (const auto& subaddr_index_str : subaddr_indices_str)
{
uint32_t subaddr_index;
if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str))
{
fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str;
subaddr_indices.clear();
return false;
}
subaddr_indices.insert(subaddr_index);
}
return true;
}
boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str)
{
auto r = tools::parse_subaddress_lookahead(str);
if (!r)
fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>");
return r;
}
static constexpr std::string_view SFFD_ARG_NAME{"subtractfeefrom="};
bool parse_subtract_fee_from_outputs
(
const std::string& arg,
tools::wallet2::unique_index_container& subtract_fee_from_outputs,
bool& subtract_fee_from_all,
bool& matches
)
{
matches = false;
if (!boost::string_ref{arg}.starts_with(SFFD_ARG_NAME.data())) // if arg doesn't match
return true;
matches = true;
const char* arg_end = arg.c_str() + arg.size();
for (const char* p = arg.c_str() + SFFD_ARG_NAME.size(); p < arg_end;)
{
const char* new_p = nullptr;
const unsigned long dest_index = strtoul(p, const_cast<char**>(&new_p), 10);
if (dest_index == 0 && new_p == p) // numerical conversion failed
{
if (0 != strncmp(p, "all", 3))
{
fail_msg_writer() << tr("Failed to parse subtractfeefrom list");
return false;
}
subtract_fee_from_all = true;
break;
}
else if (dest_index > std::numeric_limits<uint32_t>::max())
{
fail_msg_writer() << tr("Destination index is too large") << ": " << dest_index;
return false;
}
else
{
subtract_fee_from_outputs.insert(dest_index);
p = new_p + 1; // skip the comma
}
}
return true;
}
} // anonymous namespace
void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon)
{
bool warn_of_possible_attack = !trusted_daemon;
try
{
std::rethrow_exception(e);
}
catch (const tools::error::deprecated_rpc_access&)
{
fail_msg_writer() << tr("Daemon requires deprecated RPC payment. See https://github.com/monero-project/monero/issues/8722");
}
catch (const tools::error::no_connection_to_daemon&)
{
fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::daemon_busy&)
{
fail_msg_writer() << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
fail_msg_writer() << sw::tr("RPC error: ") << e.what();
}
catch (const tools::error::get_outs_error &e)
{
fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what();
}
catch (const tools::error::not_enough_unlocked_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_not_possible& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") %
print_money(e.available()) %
print_money(e.tx_amount() + e.fee()) %
print_money(e.tx_amount()) %
print_money(e.fee()));
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");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_outs_to_mix& e)
{
auto writer = fail_msg_writer();
writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":";
for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs())
{
writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second;
}
writer << sw::tr("Please use sweep_unmixable.");
}
catch (const tools::error::tx_not_constructed&)
{
fail_msg_writer() << sw::tr("transaction was not constructed");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_rejected& e)
{
fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon")) % get_transaction_hash(e.tx()));
std::string reason = e.reason();
if (!reason.empty())
fail_msg_writer() << sw::tr("Reason: ") << reason;
}
catch (const tools::error::tx_sum_overflow& e)
{
fail_msg_writer() << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::zero_amount&)
{
fail_msg_writer() << sw::tr("destination amount is zero");
warn_of_possible_attack = false;
}
catch (const tools::error::zero_destination&)
{
fail_msg_writer() << sw::tr("transaction has no destination");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_too_big& e)
{
fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions");
warn_of_possible_attack = false;
}
catch (const tools::error::transfer_error& e)
{
LOG_ERROR("unknown transfer error: " << e.to_string());
fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what();
}
catch (const tools::error::multisig_export_needed& e)
{
LOG_ERROR("Multisig error: " << e.to_string());
fail_msg_writer() << sw::tr("Multisig error: ") << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::wallet_internal_error& e)
{
LOG_ERROR("internal error: " << e.to_string());
fail_msg_writer() << sw::tr("internal error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << sw::tr("unexpected error: ") << e.what();
}
if (warn_of_possible_attack)
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.");
}
namespace
{
bool check_file_overwrite(const std::string &filename)
{
boost::system::error_code errcode;
if (boost::filesystem::exists(filename, errcode))
{
if (boost::ends_with(filename, ".keys"))
{
fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename;
return false;
}
return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it?")) % filename).str(), true));
}
return true;
}
void print_secret_key(const crypto::secret_key &k)
{
static constexpr const char hex[] = u8"0123456789abcdef";
const uint8_t *ptr = (const uint8_t*)k.data;
for (size_t i = 0, sz = sizeof(k); i < sz; ++i)
{
putchar(hex[*ptr >> 4]);
putchar(hex[*ptr & 15]);
++ptr;
}
}
}
bool parse_priority(const std::string& arg, uint32_t& priority)
{
auto priority_pos = std::find(
allowed_priority_strings.begin(),
allowed_priority_strings.end(),
arg);
if(priority_pos != allowed_priority_strings.end()) {
priority = std::distance(allowed_priority_strings.begin(), priority_pos);
return true;
}
return false;
}
std::string join_priority_strings(const char *delimiter)
{
std::string s;
for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
{
if (!s.empty())
s += delimiter;
s += allowed_priority_strings[n];
}
return s;
}
std::string simple_wallet::get_commands_str()
{
std::stringstream ss;
ss << tr("Commands: ") << ENDL;
std::string usage = m_cmd_binder.get_usage();
boost::replace_all(usage, "\n", "\n ");
usage.insert(0, " ");
ss << usage << ENDL;
return ss.str();
}
std::string simple_wallet::get_command_usage(const std::vector<std::string> &args)
{
std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args);
std::stringstream ss;
if(documentation.first.empty())
{
ss << tr("Unknown command: ") << args.front();
}
else
{
std::string usage = documentation.second.empty() ? args.front() : documentation.first;
std::string description = documentation.second.empty() ? documentation.first : documentation.second;
usage.insert(0, " ");
ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL;
boost::replace_all(description, "\n", "\n ");
description.insert(0, " ");
ss << tr("Command description: ") << ENDL << description << ENDL;
}
return ss.str();
}
bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl;
return true;
}
bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no spend key");
return true;
}
CHECK_IF_BACKGROUND_SYNCING("has no spend key");
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl;
return true;
}
bool simple_wallet::print_seed(bool encrypted)
{
bool success = false;
epee::wipeable_string seed;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
CHECK_IF_BACKGROUND_SYNCING("has no seed");
const multisig::multisig_account_status ms_status{m_wallet->get_multisig_status()};
if (ms_status.multisig_is_active)
{
if (!ms_status.is_ready)
{
fail_msg_writer() << tr("wallet is multisig but not yet finalized");
return true;
}
}
SCOPED_WALLET_UNLOCK();
if (!ms_status.multisig_is_active && !m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
epee::wipeable_string seed_pass;
if (encrypted)
{
auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true);
if (std::cin.eof() || !pwd_container)
return true;
seed_pass = pwd_container->password();
}
if (ms_status.multisig_is_active)
success = m_wallet->get_multisig_seed(seed, seed_pass);
else if (m_wallet->is_deterministic())
success = m_wallet->get_seed(seed, seed_pass);
if (success)
{
print_seed(seed);
}
else
{
fail_msg_writer() << tr("Failed to retrieve seed");
}
return true;
}
bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(false);
}
bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(true);
}
bool simple_wallet::restore_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
success_msg_writer() << m_wallet->get_refresh_from_block_height();
return true;
}
bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->get_multisig_status().multisig_is_active)
{
fail_msg_writer() << tr("wallet is multisig and has no seed");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
CHECK_IF_BACKGROUND_SYNCING("has no seed");
epee::wipeable_string password;
{
SCOPED_WALLET_UNLOCK();
if (!m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
// we need the password, even if ask-password is unset
if (!pwd_container)
{
pwd_container = get_and_verify_password();
if (pwd_container == boost::none)
{
fail_msg_writer() << tr("Incorrect password");
return true;
}
}
password = pwd_container->password();
}
std::string mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return true;
m_wallet->set_seed_language(std::move(mnemonic_language));
m_wallet->rewrite(m_wallet_file, password);
return true;
}
bool simple_wallet::change_password(const std::vector<std::string> &args)
{
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
// prompts for a new password, pass true to verify the password