Debian Codegraph @

monero/src/wallet/api/wallet.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 #include "wallet.h"
33 #include "pending_transaction.h"
34 #include "unsigned_transaction.h"
35 #include "common_defines.h"
36 #include "common/util.h"
37 #include "string_coding.h"
38
39 #include "mnemonics/electrum-words.h"
40 #include "mnemonics/english.h"
41 #include <boost/format.hpp>
42 #include <sstream>
43 #include <unordered_map>
44
45 #ifdef WIN32
46 #include <boost/locale.hpp>
47 #endif
48
49 #include <boost/filesystem.hpp>
50
51 using namespace std;
52 using namespace cryptonote;
53
54 #undef MONERO_DEFAULT_LOG_CATEGORY
55 #define MONERO_DEFAULT_LOG_CATEGORY "WalletAPI"
56
57 #define LOCK_REFRESH() \
58 bool refresh_enabled = m_refreshEnabled; \
59 m_refreshEnabled = false; \
60 m_wallet->stop(); \
61 m_refreshCV.notify_one(); \
62 boost::mutex::scoped_lock lock(m_refreshMutex); \
63 boost::mutex::scoped_lock lock2(m_refreshMutex2); \
64 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \
65 /* m_refreshMutex's still locked here */ \
66 if (refresh_enabled) \
67 startRefresh(); \
68 })
69
70 #define PRE_VALIDATE_BACKGROUND_SYNC() \
71 do \
72 { \
73 clearStatus(); \
74 if (m_wallet->key_on_device()) \
75 { \
76 setStatusError(tr("HW wallet cannot use background sync")); \
77 return false; \
78 } \
79 if (m_wallet->watch_only()) \
80 { \
81 setStatusError(tr("View only wallet cannot use background sync")); \
82 return false; \
83 } \
84 if (m_wallet->multisig()) \
85 { \
86 setStatusError(tr("Multisig wallet cannot use background sync")); \
87 return false; \
88 } \
89 } while (0)
90
91 namespace Monero {
92
93 namespace {
94 // copy-pasted from simplewallet
95 static const int DEFAULT_REFRESH_INTERVAL_MILLIS = 1000 * 10;
96 // limit maximum refresh interval as one minute
97 static const int MAX_REFRESH_INTERVAL_MILLIS = 1000 * 60 * 1;
98 // Default refresh interval when connected to remote node
99 static const int DEFAULT_REMOTE_NODE_REFRESH_INTERVAL_MILLIS = 1000 * 10;
100 // Connection timeout 30 sec
101 static const int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 1000 * 30;
102
103 std::string get_default_ringdb_path(cryptonote::network_type nettype)
104 {
105 boost::filesystem::path dir = tools::get_default_data_dir();
106 // remove .bitmonero, replace with .shared-ringdb
107 dir = dir.remove_filename();
108 dir /= ".shared-ringdb";
109 if (nettype == cryptonote::TESTNET)
110 dir /= "testnet";
111 else if (nettype == cryptonote::STAGENET)
112 dir /= "stagenet";
113 return dir.string();
114 }
115
116 void checkMultisigWalletReady(const tools::wallet2* wallet) {
117 if (!wallet) {
118 throw runtime_error("Wallet is not initialized yet");
119 }
120
121 bool ready;
122 if (!wallet->multisig(&ready)) {
123 throw runtime_error("Wallet is not multisig");
124 }
125
126 if (!ready) {
127 throw runtime_error("Multisig wallet is not finalized yet");
128 }
129 }
130 void checkMultisigWalletReady(const std::unique_ptr<tools::wallet2> &wallet) {
131 return checkMultisigWalletReady(wallet.get());
132 }
133
134 void checkMultisigWalletNotReady(const tools::wallet2* wallet) {
135 if (!wallet) {
136 throw runtime_error("Wallet is not initialized yet");
137 }
138
139 bool ready;
140 if (!wallet->multisig(&ready)) {
141 throw runtime_error("Wallet is not multisig");
142 }
143
144 if (ready) {
145 throw runtime_error("Multisig wallet is already finalized");
146 }
147 }
148 void checkMultisigWalletNotReady(const std::unique_ptr<tools::wallet2> &wallet) {
149 return checkMultisigWalletNotReady(wallet.get());
150 }
151 }
152
153 struct Wallet2CallbackImpl : public tools::i_wallet2_callback
154 {
155
156 Wallet2CallbackImpl(WalletImpl * wallet)
157 : m_listener(nullptr)
158 , m_wallet(wallet)
159 {
160
161 }
162
163 ~Wallet2CallbackImpl()
164 {
165
166 }
167
168 void setListener(WalletListener * listener)
169 {
170 m_listener = listener;
171 }
172
173 WalletListener * getListener() const
174 {
175 return m_listener;
176 }
177
178 virtual void on_new_block(uint64_t height, const cryptonote::block& block)
179 {
180 // Don't flood the GUI with signals. On fast refresh - send signal every 1000th block
181 // get_refresh_from_block_height() returns the blockheight from when the wallet was
182 // created or the restore height specified when wallet was recovered
183 if(height >= (m_wallet->m_wallet->get_refresh_from_block_height() - 1) || height % 1000 == 0) {
184 // LOG_PRINT_L3(__FUNCTION__ << ": new block. height: " << height);
185 if (m_listener) {
186 m_listener->newBlock(height);
187 }
188 }
189 }
190
191 virtual void 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)
192 {
193
194 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
195
196 LOG_PRINT_L3(__FUNCTION__ << ": money received. height: " << height
197 << ", tx: " << tx_hash
198 << ", amount: " << print_money(amount - burnt)
199 << ", burnt: " << print_money(burnt)
200 << ", raw_output_value: " << print_money(amount)
201 << ", idx: " << subaddr_index);
202 m_listener->moneyReceived(tx_hash, amount - burnt, cryptonote::is_coinbase(tx));
203 m_listener->updated();
204 }
205
206 virtual void on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index)
207 {
208
209 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
210
211 LOG_PRINT_L3(__FUNCTION__ << ": unconfirmed money received. height: " << height
212 << ", tx: " << tx_hash
213 << ", amount: " << print_money(amount)
214 << ", idx: " << subaddr_index);
215 m_listener->unconfirmedMoneyReceived(tx_hash, amount);
216 m_listener->updated();
217 }
218
219 virtual void on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx,
220 uint64_t amount, const cryptonote::transaction& spend_tx, const cryptonote::subaddress_index& subaddr_index)
221 {
222 // TODO;
223 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
224 LOG_PRINT_L3(__FUNCTION__ << ": money spent. height: " << height
225 << ", tx: " << tx_hash
226 << ", amount: " << print_money(amount)
227 << ", idx: " << subaddr_index);
228 m_listener->moneySpent(tx_hash, amount);
229 m_listener->updated();
230 }
231
232 virtual void on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx)
233 {
234 // TODO;
235 }
236
237 // Light wallet callbacks
238 virtual void on_lw_new_block(uint64_t height)
239 {
240 if (m_listener) {
241 m_listener->newBlock(height);
242 }
243 }
244
245 virtual void on_lw_money_received(uint64_t height, const crypto::hash &txid, uint64_t amount)
246 {
247 if (m_listener) {
248 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
249 m_listener->moneyReceived(tx_hash, amount, false);
250 }
251 }
252
253 virtual void on_lw_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, uint64_t amount)
254 {
255 if (m_listener) {
256 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
257 m_listener->unconfirmedMoneyReceived(tx_hash, amount);
258 }
259 }
260
261 virtual void on_lw_money_spent(uint64_t height, const crypto::hash &txid, uint64_t amount)
262 {
263 if (m_listener) {
264 std::string tx_hash = epee::string_tools::pod_to_hex(txid);
265 m_listener->moneySpent(tx_hash, amount);
266 }
267 }
268
269 virtual void on_device_button_request(uint64_t code)
270 {
271 if (m_listener) {
272 m_listener->onDeviceButtonRequest(code);
273 }
274 }
275
276 virtual void on_device_button_pressed()
277 {
278 if (m_listener) {
279 m_listener->onDeviceButtonPressed();
280 }
281 }
282
283 virtual void on_device_error(const std::string &message, unsigned int error_code)
284 {
285 if (m_listener) {
286 m_listener->onDeviceError(message, error_code);
287 }
288 }
289
290 virtual boost::optional<epee::wipeable_string> on_device_pin_request()
291 {
292 if (m_listener) {
293 auto pin = m_listener->onDevicePinRequest();
294 if (pin){
295 return boost::make_optional(epee::wipeable_string((*pin).data(), (*pin).size()));
296 }
297 }
298 return boost::none;
299 }
300
301 virtual boost::optional<epee::wipeable_string> on_device_passphrase_request(bool & on_device)
302 {
303 if (m_listener) {
304 auto passphrase = m_listener->onDevicePassphraseRequest(on_device);
305 if (passphrase) {
306 return boost::make_optional(epee::wipeable_string((*passphrase).data(), (*passphrase).size()));
307 }
308 } else {
309 on_device = true;
310 }
311 return boost::none;
312 }
313
314 virtual void on_device_progress(const hw::device_progress & event)
315 {
316 if (m_listener) {
317 m_listener->onDeviceProgress(DeviceProgress(event.progress(), event.indeterminate()));
318 }
319 }
320
321 WalletListener * m_listener;
322 WalletImpl * m_wallet;
323 };
324
325 Wallet::~Wallet() {}
326
327 WalletListener::~WalletListener() {}
328
329
330 string Wallet::displayAmount(uint64_t amount)
331 {
332 return cryptonote::print_money(amount);
333 }
334
335 uint64_t Wallet::amountFromString(const string &amount)
336 {
337 uint64_t result = 0;
338 cryptonote::parse_amount(result, amount);
339 return result;
340 }
341
342 uint64_t Wallet::amountFromDouble(double amount)
343 {
344 std::stringstream ss;
345 ss << std::fixed << std::setprecision(CRYPTONOTE_DISPLAY_DECIMAL_POINT) << amount;
346 return amountFromString(ss.str());
347 }
348
349 std::string Wallet::genPaymentId()
350 {
351 crypto::hash8 payment_id = crypto::rand<crypto::hash8>();
352 return epee::string_tools::pod_to_hex(payment_id);
353
354 }
355
356 bool Wallet::paymentIdValid(const string &paiment_id)
357 {
358 crypto::hash8 pid8;
359 if (tools::wallet2::parse_short_payment_id(paiment_id, pid8))
360 return true;
361 crypto::hash pid;
362 if (tools::wallet2::parse_long_payment_id(paiment_id, pid))
363 return true;
364 return false;
365 }
366
367 bool Wallet::addressValid(const std::string &str, NetworkType nettype)
368 {
369 cryptonote::address_parse_info info;
370 return get_account_address_from_str(info, static_cast<cryptonote::network_type>(nettype), str);
371 }
372
373 bool Wallet::keyValid(const std::string &secret_key_string, const std::string &address_string, bool isViewKey, NetworkType nettype, std::string &error)
374 {
375 cryptonote::address_parse_info info;
376 if(!get_account_address_from_str(info, static_cast<cryptonote::network_type>(nettype), address_string)) {
377 error = tr("Failed to parse address");
378 return false;
379 }
380
381 cryptonote::blobdata key_data;
382 if(!epee::string_tools::parse_hexstr_to_binbuff(secret_key_string, key_data) || key_data.size() != sizeof(crypto::secret_key))
383 {
384 error = tr("Failed to parse key");
385 return false;
386 }
387 crypto::secret_key key = *reinterpret_cast<const crypto::secret_key*>(key_data.data());
388
389 // check the key match the given address
390 crypto::public_key pkey;
391 if (!crypto::secret_key_to_public_key(key, pkey)) {
392 error = tr("failed to verify key");
393 return false;
394 }
395 bool matchAddress = false;
396 if(isViewKey)
397 matchAddress = info.address.m_view_public_key == pkey;
398 else
399 matchAddress = info.address.m_spend_public_key == pkey;
400
401 if(!matchAddress) {
402 error = tr("key does not match address");
403 return false;
404 }
405
406 return true;
407 }
408
409 std::string Wallet::paymentIdFromAddress(const std::string &str, NetworkType nettype)
410 {
411 cryptonote::address_parse_info info;
412 if (!get_account_address_from_str(info, static_cast<cryptonote::network_type>(nettype), str))
413 return "";
414 if (!info.has_payment_id)
415 return "";
416 return epee::string_tools::pod_to_hex(info.payment_id);
417 }
418
419 std::string Wallet::baseAddressFromIntegratedAddress(const std::string &str, NetworkType nettype)
420 {
421 cryptonote::address_parse_info info;
422 if (!get_account_address_from_str(info, static_cast<cryptonote::network_type>(nettype), str))
423 return "";
424 return get_account_address_as_str(static_cast<cryptonote::network_type>(nettype), info.is_subaddress, info.address);
425 }
426
427 uint64_t Wallet::maximumAllowedAmount()
428 {
429 return std::numeric_limits<uint64_t>::max();
430 }
431
432 void Wallet::init(const char *argv0, const char *default_log_base_name, const std::string &log_path, bool console) {
433 #ifdef WIN32
434 // Activate UTF-8 support for Boost filesystem classes on Windows
435 std::locale::global(boost::locale::generator().generate(""));
436 boost::filesystem::path::imbue(std::locale());
437 #endif
438 epee::string_tools::set_module_name_and_folder(argv0);
439 mlog_configure(log_path.empty() ? mlog_get_default_log_path(default_log_base_name) : log_path.c_str(), console);
440 }
441
442 void Wallet::debug(const std::string &category, const std::string &str) {
443 MCDEBUG(category.empty() ? MONERO_DEFAULT_LOG_CATEGORY : category.c_str(), str);
444 }
445
446 void Wallet::info(const std::string &category, const std::string &str) {
447 MCINFO(category.empty() ? MONERO_DEFAULT_LOG_CATEGORY : category.c_str(), str);
448 }
449
450 void Wallet::warning(const std::string &category, const std::string &str) {
451 MCWARNING(category.empty() ? MONERO_DEFAULT_LOG_CATEGORY : category.c_str(), str);
452 }
453
454 void Wallet::error(const std::string &category, const std::string &str) {
455 MCERROR(category.empty() ? MONERO_DEFAULT_LOG_CATEGORY : category.c_str(), str);
456 }
457
458 ///////////////////////// WalletImpl implementation ////////////////////////
459 WalletImpl::WalletImpl(NetworkType nettype, uint64_t kdf_rounds)
460 :m_wallet(nullptr)
461 , m_status(Wallet::Status_Ok)
462 , m_wallet2Callback(nullptr)
463 , m_recoveringFromSeed(false)
464 , m_recoveringFromDevice(false)
465 , m_synchronized(false)
466 , m_rebuildWalletCache(false)
467 , m_is_connected(false)
468 , m_refreshShouldRescan(false)
469 {
470 m_wallet.reset(new tools::wallet2(static_cast<cryptonote::network_type>(nettype), kdf_rounds, true));
471 m_wallet2Callback.reset(new Wallet2CallbackImpl(this));
472 m_wallet->callback(m_wallet2Callback.get());
473 m_refreshThreadDone = false;
474 m_refreshEnabled = false;
475
476
477 m_refreshIntervalMillis = DEFAULT_REFRESH_INTERVAL_MILLIS;
478 }
479
480 WalletImpl::~WalletImpl()
481 {
482
483 LOG_PRINT_L1(__FUNCTION__);
484 m_wallet->callback(NULL);
485 // Close wallet - stores cache and stops ongoing refresh operation
486 close(false); // do not store wallet as part of the closing activities
487
488 if (m_wallet2Callback->getListener()) {
489 m_wallet2Callback->getListener()->onSetWallet(nullptr);
490 }
491
492 LOG_PRINT_L1(__FUNCTION__ << " finished");
493 }
494
495 bool WalletImpl::create(const std::string &path, const std::string &password, const std::string &language)
496 {
497
498 clearStatus();
499 m_recoveringFromSeed = false;
500 m_recoveringFromDevice = false;
501 bool keys_file_exists;
502 bool wallet_file_exists;
503 tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists);
504 LOG_PRINT_L3("wallet_path: " << path << "");
505 LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
506 << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
507
508
509 // add logic to error out if new wallet requested but named wallet file exists
510 if (keys_file_exists || wallet_file_exists) {
511 std::string error = "attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting.";
512 LOG_ERROR(error);
513 setStatusCritical(error);
514 return false;
515 }
516 // TODO: validate language
517 m_wallet->set_seed_language(language);
518 crypto::secret_key recovery_val, secret_key;
519 try {
520 recovery_val = m_wallet->generate(path, password, secret_key, false, false);
521 clearStatus();
522 } catch (const std::exception &e) {
523 LOG_ERROR("Error creating wallet: " << e.what());
524 setStatusCritical(e.what());
525 return false;
526 }
527
528 return true;
529 }
530
531 bool WalletImpl::createWatchOnly(const std::string &path, const std::string &password, const std::string &language) const
532 {
533 clearStatus();
534 std::unique_ptr<tools::wallet2> view_wallet(new tools::wallet2(m_wallet->nettype()));
535
536 // Store same refresh height as original wallet
537 view_wallet->set_refresh_from_block_height(m_wallet->get_refresh_from_block_height());
538
539 bool keys_file_exists;
540 bool wallet_file_exists;
541 tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists);
542 LOG_PRINT_L3("wallet_path: " << path << "");
543 LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
544 << " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
545
546 // add logic to error out if new wallet requested but named wallet file exists
547 if (keys_file_exists || wallet_file_exists) {
548 std::string error = "attempting to generate view only wallet, but specified file(s) exist. Exiting to not risk overwriting.";
549 LOG_ERROR(error);
550 setStatusError(error);
551 return false;
552 }
553 // TODO: validate language
554 view_wallet->set_seed_language(language);
555
556 const crypto::secret_key viewkey = m_wallet->get_account().get_keys().m_view_secret_key;
557 const cryptonote::account_public_address address = m_wallet->get_account().get_keys().m_account_address;
558
559 try {
560 // Generate view only wallet
561 view_wallet->generate(path, password, address, viewkey);
562
563 // Export/Import outputs
564 auto outputs = m_wallet->export_outputs(true/*all*/);
565 view_wallet->import_outputs(outputs);
566
567 // Copy scanned blockchain
568 auto bc = m_wallet->export_blockchain();
569 view_wallet->import_blockchain(bc);
570
571 // copy payments
572 auto payments = m_wallet->export_payments();
573 view_wallet->import_payments(payments);
574
575 // copy confirmed outgoing payments
576 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> out_payments;
577 m_wallet->get_payments_out(out_payments, 0);
578 view_wallet->import_payments_out(out_payments);
579
580 // Export/Import key images
581 // We already know the spent status from the outputs we exported, thus no need to check them again
582 auto key_images = m_wallet->export_key_images(true/*all*/);
583 uint64_t spent = 0;
584 uint64_t unspent = 0;
585 view_wallet->import_key_images(key_images.second, key_images.first, spent, unspent, false);
586 clearStatus();
587 } catch (const std::exception &e) {
588 LOG_ERROR("Error creating view only wallet: " << e.what());
589 setStatusError(e.what());
590 return false;
591 }
592 // Store wallet
593 view_wallet->store();
594 return true;
595 }
596
597 bool WalletImpl::recoverFromKeys(const std::string &path,
598 const std::string &language,
599 const std::string &address_string,
600 const std::string &viewkey_string,
601 const std::string &spendkey_string)
602 {
603 return recoverFromKeysWithPassword(path, "", language, address_string, viewkey_string, spendkey_string);
604 }
605
606 bool WalletImpl::recoverFromKeysWithPassword(const std::string &path,
607 const std::string &password,
608 const std::string &language,
609 const std::string &address_string,
610 const std::string &viewkey_string,
611 const std::string &spendkey_string)
612 {
613 cryptonote::address_parse_info info;
614 if(!get_account_address_from_str(info, m_wallet->nettype(), address_string))
615 {
616 setStatusError(tr("failed to parse address"));
617 return false;
618 }
619
620 // parse optional spend key
621 crypto::secret_key spendkey;
622 bool has_spendkey = false;
623 if (!spendkey_string.empty()) {
624 cryptonote::blobdata spendkey_data;
625 if(!epee::string_tools::parse_hexstr_to_binbuff(spendkey_string, spendkey_data) || spendkey_data.size() != sizeof(crypto::secret_key))
626 {
627 setStatusError(tr("failed to parse secret spend key"));
628 return false;
629 }
630 has_spendkey = true;
631 spendkey = *reinterpret_cast<const crypto::secret_key*>(spendkey_data.data());
632 }
633
634 // parse view secret key
635 bool has_viewkey = true;
636 crypto::secret_key viewkey;
637 if (viewkey_string.empty()) {
638 if(has_spendkey) {
639 has_viewkey = false;
640 }
641 else {
642 setStatusError(tr("Neither view key nor spend key supplied, cancelled"));
643 return false;
644 }
645 }
646 if(has_viewkey) {
647 cryptonote::blobdata viewkey_data;
648 if(!epee::string_tools::parse_hexstr_to_binbuff(viewkey_string, viewkey_data) || viewkey_data.size() != sizeof(crypto::secret_key))
649 {
650 setStatusError(tr("failed to parse secret view key"));
651 return false;
652 }
653 viewkey = *reinterpret_cast<const crypto::secret_key*>(viewkey_data.data());
654 }
655 // check the spend and view keys match the given address
656 crypto::public_key pkey;
657 if(has_spendkey) {
658 if (!crypto::secret_key_to_public_key(spendkey, pkey)) {
659 setStatusError(tr("failed to verify secret spend key"));
660 return false;
661 }
662 if (info.address.m_spend_public_key != pkey) {
663 setStatusError(tr("spend key does not match address"));
664 return false;
665 }
666 }
667 if(has_viewkey) {
668 if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
669 setStatusError(tr("failed to verify secret view key"));
670 return false;
671 }
672 if (info.address.m_view_public_key != pkey) {
673 setStatusError(tr("view key does not match address"));
674 return false;
675 }
676 }
677
678 try
679 {
680 if (has_spendkey && has_viewkey) {
681 m_wallet->generate(path, password, info.address, spendkey, viewkey);
682 LOG_PRINT_L1("Generated new wallet from spend key and view key");
683 }
684 if(!has_spendkey && has_viewkey) {
685 m_wallet->generate(path, password, info.address, viewkey);
686 LOG_PRINT_L1("Generated new view only wallet from keys");
687 }
688 if(has_spendkey && !has_viewkey) {
689 m_wallet->generate(path, password, spendkey, true, false);
690 setSeedLanguage(language);
691 LOG_PRINT_L1("Generated deterministic wallet from spend key with seed language: " + language);
692 }
693
694 }
695 catch (const std::exception& e) {
696 setStatusError(string(tr("failed to generate new wallet: ")) + e.what());
697 return false;
698 }
699 return true;
700 }
701
702 bool WalletImpl::recoverFromDevice(const std::string &path, const std::string &password, const std::string &device_name)
703 {
704 clearStatus();
705 m_recoveringFromSeed = false;
706 m_recoveringFromDevice = true;
707 try
708 {
709 m_wallet->restore(path, password, device_name);
710 LOG_PRINT_L1("Generated new wallet from device: " + device_name);
711 }
712 catch (const std::exception& e) {
713 setStatusError(string(tr("failed to generate new wallet: ")) + e.what());
714 return false;
715 }
716 return true;
717 }
718
719 Wallet::Device WalletImpl::getDeviceType() const
720 {
721 return static_cast<Wallet::Device>(m_wallet->get_device_type());
722 }
723
724 bool WalletImpl::open(const std::string &path, const std::string &password, std::string ringDatabasePath)
725 {
726 clearStatus();
727 m_recoveringFromSeed = false;
728 m_recoveringFromDevice = false;
729 try {
730 // TODO: handle "deprecated"
731 // Check if wallet cache exists
732 bool keys_file_exists;
733 bool wallet_file_exists;
734 tools::wallet2::wallet_exists(path, keys_file_exists, wallet_file_exists);
735 if(!wallet_file_exists){
736 // Rebuilding wallet cache, using refresh height from .keys file
737 m_rebuildWalletCache = true;
738 }
739 if (ringDatabasePath.empty()) {
740 ringDatabasePath = get_default_ringdb_path(m_wallet->nettype());
741 }
742 m_wallet->set_ring_database(ringDatabasePath);
743 m_wallet->load(path, password);
744 } catch (const tools::error::invalid_password &e) {
745 LOG_ERROR("Error opening wallet: " << e.what());
746 setStatus(Status_BadPassword, e.what());
747 }
748 catch (const std::exception &e) {
749 LOG_ERROR("Error opening wallet: " << e.what());
750 setStatusCritical(e.what());
751 }
752 m_deviceConnected = true;
753 return status() == Status_Ok;
754 }
755
756 bool WalletImpl::recover(const std::string &path, const std::string &seed)
757 {
758 return recover(path, "", seed);
759 }
760
761 bool WalletImpl::recover(const std::string &path, const std::string &password, const std::string &seed, const std::string &seed_offset/* = {}*/)
762 {
763 clearStatus();
764 m_errorString.clear();
765 if (seed.empty()) {
766 LOG_ERROR("Electrum seed is empty");
767 setStatusError(tr("Electrum seed is empty"));
768 return false;
769 }
770
771 m_recoveringFromSeed = true;
772 m_recoveringFromDevice = false;
773 crypto::secret_key recovery_key;
774 std::string old_language;
775 if (!crypto::ElectrumWords::words_to_bytes(seed, recovery_key, old_language)) {
776 setStatusError(tr("Electrum-style word list failed verification"));
777 return false;
778 }
779 if (!seed_offset.empty())
780 {
781 recovery_key = cryptonote::decrypt_key(recovery_key, seed_offset);
782 }
783
784 if (old_language == crypto::ElectrumWords::old_language_name)
785 old_language = Language::English().get_language_name();
786
787 try {
788 m_wallet->set_seed_language(old_language);
789 m_wallet->generate(path, password, recovery_key, true, false);
790
791 } catch (const std::exception &e) {
792 setStatusCritical(e.what());
793 }
794 m_deviceConnected = true;
795 return status() == Status_Ok;
796 }
797
798 bool WalletImpl::recoverDeterministicWalletFromSpendKey(const std::string &path, const std::string &password, const std::string &language, const std::string &spendkey_string, const std::string &offset_passphrase)
799 {
800 clearStatus();
801 m_errorString.clear();
802
803 m_recoveringFromSeed = true;
804 m_recoveringFromDevice = false;
805
806 // parse spend key
807 crypto::secret_key spendkey;
808 if (!spendkey_string.empty()) {
809 cryptonote::blobdata spendkey_data;
810 if(!epee::string_tools::parse_hexstr_to_binbuff(spendkey_string, spendkey_data) || spendkey_data.size() != sizeof(crypto::secret_key))
811 {
812 setStatusError(tr("failed to parse secret spend key"));
813 return false;
814 }
815 spendkey = *reinterpret_cast<const crypto::secret_key*>(spendkey_data.data());
816 }
817 if (!offset_passphrase.empty())
818 {
819 spendkey = cryptonote::decrypt_key(spendkey, offset_passphrase);
820 }
821
822 try {
823 m_wallet->generate(path, password, spendkey, true, false);
824 setSeedLanguage(language);
825 } catch (const std::exception &e) {
826 setStatusCritical(e.what());
827 }
828 return status() == Status_Ok;
829 }
830
831 bool WalletImpl::close(bool store)
832 {
833 bool result = false;
834 LOG_PRINT_L1("closing wallet...");
835 try {
836 if (store) {
837 // Do not store wallet with invalid status
838 // Status Critical refers to errors on opening or creating wallets.
839 if (status() != Status_Critical && status() != Status_BadPassword)
840 m_wallet->store();
841 else
842 LOG_ERROR("Status_Critical - not saving wallet");
843 LOG_PRINT_L1("wallet::store done");
844 }
845 LOG_PRINT_L1("Calling wallet::stop...");
846 m_wallet->stop();
847 LOG_PRINT_L1("wallet::stop done");
848 m_wallet->deinit();
849 result = true;
850 clearStatus();
851 } catch (const std::exception &e) {
852 setStatusCritical(e.what());
853 LOG_ERROR("Error closing wallet: " << e.what());
854 }
855 return result;
856 }
857
858 std::string WalletImpl::seed(const std::string& seed_offset) const
859 {
860 if (checkBackgroundSync("cannot get seed"))
861 return std::string();
862 epee::wipeable_string seed;
863 if (m_wallet)
864 m_wallet->get_seed(seed, seed_offset);
865 return std::string(seed.data(), seed.size()); // TODO
866 }
867
868 std::string WalletImpl::getSeedLanguage() const
869 {
870 return m_wallet->get_seed_language();
871 }
872
873 void WalletImpl::setSeedLanguage(const std::string &arg)
874 {
875 if (checkBackgroundSync("cannot set seed language"))
876 return;
877 m_wallet->set_seed_language(arg);
878 }
879
880 int WalletImpl::status() const
881 {
882 boost::lock_guard<boost::mutex> l(m_statusMutex);
883 return m_status;
884 }
885
886 std::string WalletImpl::errorString() const
887 {
888 boost::lock_guard<boost::mutex> l(m_statusMutex);
889 return m_errorString;
890 }
891
892 void WalletImpl::statusWithErrorString(int& status, std::string& errorString) const {
893 boost::lock_guard<boost::mutex> l(m_statusMutex);
894 status = m_status;
895 errorString = m_errorString;
896 }
897
898 bool WalletImpl::setPassword(const std::string &old_password, const std::string &new_password)
899 {
900 if (checkBackgroundSync("cannot change password"))
901 return false;
902 clearStatus();
903 try {
904 m_wallet->change_password(m_wallet->get_wallet_file(), old_password, new_password);
905 } catch (const std::exception &e) {
906 setStatusError(e.what());
907 }
908 return status() == Status_Ok;
909 }
910
911 bool WalletImpl::verifyPassword(const std::string &password) const
912 {
913 return m_wallet->verify_password(password);
914 }
915
916 bool WalletImpl::setDevicePin(const std::string &pin)
917 {
918 clearStatus();
919 try {
920 m_wallet->get_account().get_device().set_pin(epee::wipeable_string(pin.data(), pin.size()));
921 } catch (const std::exception &e) {
922 setStatusError(e.what());
923 }
924 return status() == Status_Ok;
925 }
926
927 bool WalletImpl::setDevicePassphrase(const std::string &passphrase)
928 {
929 clearStatus();
930 try {
931 m_wallet->get_account().get_device().set_passphrase(epee::wipeable_string(passphrase.data(), passphrase.size()));
932 } catch (const std::exception &e) {
933 setStatusError(e.what());
934 }
935 return status() == Status_Ok;
936 }
937
938 std::string WalletImpl::address(uint32_t accountIndex, uint32_t addressIndex) const
939 {
940 return m_wallet->get_subaddress_as_str({accountIndex, addressIndex});
941 }
942
943 bool WalletImpl::subaddressIndex(std::string address, std::pair<uint32_t, uint32_t> &index) const
944 {
945 clearStatus();
946 cryptonote::address_parse_info info;
947
948 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address)) {
949 setStatusError(tr("Failed to parse address"));
950 return false;
951 }
952
953 auto i = m_wallet->get_subaddress_index(info.address);
954 if (!i) {
955 setStatusError(tr("Address doesn't belong to the wallet"));
956 return false;
957 }
958
959 index.first = i->major;
960 index.second = i->minor;
961 return true;
962 }
963
964 std::string WalletImpl::integratedAddress(const std::string &payment_id) const
965 {
966 crypto::hash8 pid;
967 if (!tools::wallet2::parse_short_payment_id(payment_id, pid)) {
968 return "";
969 }
970 return m_wallet->get_integrated_address_as_str(pid);
971 }
972
973 std::string WalletImpl::secretViewKey() const
974 {
975 bool hw_view_key = m_wallet->get_device_type() == hw::device::device_type::LEDGER && m_wallet->m_hw_view_key != crypto::null_skey;
976 return epee::string_tools::pod_to_hex(hw_view_key ? m_wallet->m_hw_view_key : unwrap(unwrap(m_wallet->get_account().get_keys().m_view_secret_key)));
977 }
978
979 std::string WalletImpl::publicViewKey() const
980 {
981 return epee::string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key);
982 }
983
984 std::string WalletImpl::secretSpendKey() const
985 {
986 return epee::string_tools::pod_to_hex(unwrap(unwrap(m_wallet->get_account().get_keys().m_spend_secret_key)));
987 }
988
989 std::string WalletImpl::publicSpendKey() const
990 {
991 return epee::string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key);
992 }
993
994 std::string WalletImpl::publicMultisigSignerKey() const
995 {
996 try {
997 crypto::public_key signer = m_wallet->get_multisig_signer_public_key();
998 return epee::string_tools::pod_to_hex(signer);
999 } catch (const std::exception&) {
1000 return "";
1001 }
1002 }
1003
1004 std::string WalletImpl::path() const
1005 {
1006 return m_wallet->path();
1007 }
1008
1009 void WalletImpl::stop()
1010 {
1011 m_wallet->stop();
1012 }
1013
1014 bool WalletImpl::store()
1015 {
1016 clearStatus();
1017 try {
1018 m_wallet->store();
1019 } catch (const std::exception &e) {
1020 LOG_ERROR("Error saving wallet: " << e.what());
1021 setStatusError(e.what());
1022 return false;
1023 }
1024
1025 return true;
1026 }
1027
1028 string WalletImpl::filename() const
1029 {
1030 return m_wallet->get_wallet_file();
1031 }
1032
1033 string WalletImpl::keysFilename() const
1034 {
1035 return m_wallet->get_keys_file();
1036 }
1037
1038 bool WalletImpl::init(const std::string &daemon_address, uint64_t upper_transaction_size_limit, const std::string &daemon_username, const std::string &daemon_password, bool use_ssl, bool lightWallet, const std::string &proxy_address, bool use_dns)
1039 {
1040 clearStatus();
1041 m_wallet->set_light_wallet(lightWallet);
1042
1043 boost::optional<epee::net_utils::http::login> daemon_login = epee::net_utils::http::login{daemon_username, daemon_password};
1044
1045 if (!m_wallet->init(daemon_address,
1046 daemon_login,
1047 proxy_address,
1048 upper_transaction_size_limit,
1049 trustedDaemon(),
1050 use_ssl ? epee::net_utils::ssl_support_t::e_ssl_support_autodetect : epee::net_utils::ssl_support_t::e_ssl_support_disabled))
1051 {
1052 return false;
1053 }
1054
1055 // Torsocks + dns = long timeouts
1056 m_wallet->enable_dns(use_dns);
1057
1058 if (m_rebuildWalletCache)
1059 LOG_PRINT_L2(__FUNCTION__ << ": Rebuilding wallet cache, fast refresh until block " << m_wallet->get_refresh_from_block_height());
1060
1061 return true;
1062 }
1063
1064 bool WalletImpl::setDaemon(const std::string &daemon_address, const std::string &daemon_username,
1065 const std::string &daemon_password, bool use_ssl) const {
1066 boost::optional<epee::net_utils::http::login> daemon_login = epee::net_utils::http::login{daemon_username, daemon_password};
1067 return m_wallet->set_daemon(daemon_address,
1068 daemon_login,
1069 trustedDaemon(),
1070 use_ssl ? epee::net_utils::ssl_support_t::e_ssl_support_autodetect
1071 : epee::net_utils::ssl_support_t::e_ssl_support_disabled);
1072 }
1073
1074 bool WalletImpl::lightWalletLogin(bool &isNewWallet) const
1075 {
1076 return m_wallet->light_wallet_login(isNewWallet);
1077 }
1078
1079 bool WalletImpl::lightWalletImportWalletRequest(std::string &payment_id, uint64_t &fee, bool &new_request, bool &request_fulfilled, std::string &payment_address, std::string &status)
1080 {
1081 try
1082 {
1083 tools::COMMAND_RPC_IMPORT_WALLET_REQUEST::response response;
1084 if(!m_wallet->light_wallet_import_wallet_request(response)){
1085 setStatusError(tr("Failed to send import wallet request"));
1086 return false;
1087 }
1088 fee = response.import_fee;
1089 payment_id = response.payment_id;
1090 new_request = response.new_request;
1091 request_fulfilled = response.request_fulfilled;
1092 payment_address = response.payment_address;
1093 status = response.status;
1094 }
1095 catch (const std::exception &e)
1096 {
1097 LOG_ERROR("Error sending import wallet request: " << e.what());
1098 setStatusError(e.what());
1099 return false;
1100 }
1101 return true;
1102 }
1103
1104 void WalletImpl::setRefreshFromBlockHeight(uint64_t refresh_from_block_height)
1105 {
1106 if (checkBackgroundSync("cannot change refresh height"))
1107 return;
1108 m_wallet->set_refresh_from_block_height(refresh_from_block_height);
1109 }
1110
1111 void WalletImpl::setRecoveringFromSeed(bool recoveringFromSeed)
1112 {
1113 m_recoveringFromSeed = recoveringFromSeed;
1114 }
1115
1116 void WalletImpl::setRecoveringFromDevice(bool recoveringFromDevice)
1117 {
1118 m_recoveringFromDevice = recoveringFromDevice;
1119 }
1120
1121 void WalletImpl::setSubaddressLookahead(uint32_t major, uint32_t minor)
1122 {
1123 m_wallet->set_subaddress_lookahead(major, minor);
1124 }
1125
1126 std::pair<size_t, size_t> WalletImpl::getSubaddressLookahead()
1127 {
1128 return m_wallet->get_subaddress_lookahead();
1129 }
1130
1131 uint64_t WalletImpl::balance(uint32_t accountIndex) const
1132 {
1133 return m_wallet->balance(accountIndex, false);
1134 }
1135
1136 uint64_t WalletImpl::unlockedBalance(uint32_t accountIndex) const
1137 {
1138 return m_wallet->unlocked_balance(accountIndex, false);
1139 }
1140
1141 uint64_t WalletImpl::viewOnlyBalance(uint32_t accountIndex, const std::vector<std::string> &key_images) const
1142 {
1143 clearStatus();
1144
1145 std::vector<crypto::key_image> kis;
1146 for (const auto &key_image : key_images) {
1147 crypto::key_image ki;
1148 if (!epee::string_tools::hex_to_pod(key_image, ki))
1149 {
1150 setStatusError(tr("failed to parse key image"));
1151 return 0;
1152 }
1153 kis.push_back(ki);
1154 }
1155
1156 return m_wallet->view_only_balance(accountIndex, kis);
1157 }
1158
1159 uint64_t WalletImpl::blockChainHeight() const
1160 {
1161 if(m_wallet->light_wallet()) {
1162 return m_wallet->get_light_wallet_scanned_block_height();
1163 }
1164 return m_wallet->get_blockchain_current_height();
1165 }
1166 uint64_t WalletImpl::approximateBlockChainHeight() const
1167 {
1168 return m_wallet->get_approximate_blockchain_height();
1169 }
1170
1171 uint64_t WalletImpl::estimateBlockChainHeight() const
1172 {
1173 return m_wallet->estimate_blockchain_height();
1174 }
1175
1176 uint64_t WalletImpl::daemonBlockChainHeight() const
1177 {
1178 if(m_wallet->light_wallet()) {
1179 return m_wallet->get_light_wallet_scanned_block_height();
1180 }
1181
1182 std::string err;
1183 uint64_t result = m_wallet->get_daemon_blockchain_height(err);
1184 if (!err.empty()) {
1185 LOG_ERROR(__FUNCTION__ << ": " << err);
1186 result = 0;
1187 setStatusError(err);
1188 } else {
1189 clearStatus();
1190 }
1191 return result;
1192 }
1193
1194 uint64_t WalletImpl::daemonBlockChainTargetHeight() const
1195 {
1196 if(m_wallet->light_wallet()) {
1197 return m_wallet->get_light_wallet_blockchain_height();
1198 }
1199
1200 std::string err;
1201 uint64_t result = m_wallet->get_daemon_blockchain_target_height(err);
1202 if (!err.empty()) {
1203 LOG_ERROR(__FUNCTION__ << ": " << err);
1204 result = 0;
1205 setStatusError(err);
1206 } else {
1207 clearStatus();
1208 }
1209
1210 return result;
1211 }
1212
1213 bool WalletImpl::daemonSynced() const
1214 {
1215 if(connected() == Wallet::ConnectionStatus_Disconnected)
1216 return false;
1217 uint64_t blockChainHeight = daemonBlockChainHeight();
1218 return (blockChainHeight >= daemonBlockChainTargetHeight() && blockChainHeight > 1);
1219 }
1220
1221 bool WalletImpl::synchronized() const
1222 {
1223 return m_synchronized;
1224 }
1225
1226 bool WalletImpl::refresh()
1227 {
1228 clearStatus();
1229 return doRefresh();
1230 }
1231
1232 void WalletImpl::refreshAsync()
1233 {
1234 LOG_PRINT_L3(__FUNCTION__ << ": Refreshing asynchronously..");
1235 clearStatus();
1236 m_refreshCV.notify_one();
1237 }
1238
1239 bool WalletImpl::rescanBlockchain()
1240 {
1241 if (checkBackgroundSync("cannot rescan blockchain"))
1242 return false;
1243 clearStatus();
1244 m_refreshShouldRescan = true;
1245 doRefresh();
1246 return status() == Status_Ok;
1247 }
1248
1249 void WalletImpl::rescanBlockchainAsync()
1250 {
1251 if (checkBackgroundSync("cannot rescan blockchain"))
1252 return;
1253 m_refreshShouldRescan = true;
1254 refreshAsync();
1255 }
1256
1257 void WalletImpl::setAutoRefreshInterval(int millis)
1258 {
1259 if (millis > MAX_REFRESH_INTERVAL_MILLIS) {
1260 LOG_ERROR(__FUNCTION__<< ": invalid refresh interval " << millis
1261 << " ms, maximum allowed is " << MAX_REFRESH_INTERVAL_MILLIS << " ms");
1262 m_refreshIntervalMillis = MAX_REFRESH_INTERVAL_MILLIS;
1263 } else {
1264 m_refreshIntervalMillis = millis;
1265 }
1266 }
1267
1268 int WalletImpl::autoRefreshInterval() const
1269 {
1270 return m_refreshIntervalMillis;
1271 }
1272
1273 UnsignedTransaction *WalletImpl::loadUnsignedTx(const std::string &unsigned_filename) {
1274 clearStatus();
1275 UnsignedTransactionImpl * transaction = new UnsignedTransactionImpl(*this);
1276 if (checkBackgroundSync("cannot load tx") || !m_wallet->load_unsigned_tx(unsigned_filename, transaction->m_unsigned_tx_set)){
1277 setStatusError(tr("Failed to load unsigned transactions"));
1278 transaction->m_status = UnsignedTransaction::Status::Status_Error;
1279 transaction->m_errorString = errorString();
1280
1281 return transaction;
1282 }
1283
1284 // Check tx data and construct confirmation message
1285 std::string extra_message;
1286 if (!std::get<2>(transaction->m_unsigned_tx_set.transfers).empty())
1287 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(transaction->m_unsigned_tx_set.transfers).size()).str();
1288 transaction->checkLoadedTx([&transaction](){return transaction->m_unsigned_tx_set.txes.size();}, [&transaction](size_t n)->const tools::wallet2::tx_construction_data&{return transaction->m_unsigned_tx_set.txes[n];}, extra_message);
1289 setStatus(transaction->status(), transaction->errorString());
1290
1291 return transaction;
1292 }
1293
1294 UnsignedTransaction *WalletImpl::loadUnsignedTxFromStr(const std::string &unsigned_tx) {
1295 clearStatus();
1296
1297 UnsignedTransactionImpl * transaction = new UnsignedTransactionImpl(*this);
1298 if (!m_wallet->parse_unsigned_tx_from_str(unsigned_tx, transaction->m_unsigned_tx_set)) {
1299 setStatusError(tr("Failed to load unsigned transactions"));
1300 transaction->m_status = UnsignedTransaction::Status::Status_Error;
1301 transaction->m_errorString = errorString();
1302
1303 return transaction;
1304 }
1305
1306 // Check tx data and construct confirmation message
1307 std::string extra_message;
1308 if (!std::get<2>(transaction->m_unsigned_tx_set.transfers).empty())
1309 extra_message = (boost::format("%u outputs to import. ") % (unsigned)std::get<2>(transaction->m_unsigned_tx_set.transfers).size()).str();
1310 transaction->checkLoadedTx([&transaction](){return transaction->m_unsigned_tx_set.txes.size();}, [&transaction](size_t n)->const tools::wallet2::tx_construction_data&{return transaction->m_unsigned_tx_set.txes[n];}, extra_message);
1311 setStatus(transaction->status(), transaction->errorString());
1312
1313 return transaction;
1314 }
1315
1316 UnsignedTransaction *WalletImpl::loadUnsignedTxFromBase64Str(const std::string &unsigned_tx_base64) {
1317 clearStatus();
1318
1319 std::string decoded_tx = epee::string_encoding::base64_decode(unsigned_tx_base64);
1320
1321 return this->loadUnsignedTxFromStr(decoded_tx);
1322 }
1323
1324 PendingTransaction *WalletImpl::loadSignedTx(const std::string &signed_filename) {
1325 clearStatus();
1326 PendingTransactionImpl * transaction = new PendingTransactionImpl(*this);
1327
1328 if (!m_wallet->load_tx(signed_filename, transaction->m_pending_tx)) {
1329 setStatusError(tr("Failed to load unsigned transactions"));
1330 return transaction;
1331 }
1332
1333 return transaction;
1334 }
1335
1336 PendingTransaction *WalletImpl::loadSignedTxFromStr(const std::string &data) {
1337 clearStatus();
1338 PendingTransactionImpl * transaction = new PendingTransactionImpl(*this);
1339
1340 if (!m_wallet->parse_tx_from_str(data, transaction->m_pending_tx, nullptr)) {
1341 setStatusError(tr("Failed to load unsigned transactions"));
1342 }
1343
1344 return transaction;
1345 }
1346
1347 bool WalletImpl::submitTransaction(const string &fileName) {
1348 clearStatus();
1349 if (checkBackgroundSync("cannot submit tx"))
1350 return false;
1351 std::unique_ptr<PendingTransactionImpl> transaction(new PendingTransactionImpl(*this));
1352
1353 bool r = m_wallet->load_tx(fileName, transaction->m_pending_tx);
1354 if (!r) {
1355 setStatus(Status_Ok, tr("Failed to load transaction from file"));
1356 return false;
1357 }
1358
1359 if(!transaction->commit()) {
1360 setStatusError(transaction->m_errorString);
1361 return false;
1362 }
1363
1364 return true;
1365 }
1366
1367 bool WalletImpl::hasUnknownKeyImages() const
1368 {
1369 return m_wallet->has_unknown_key_images();
1370 }
1371
1372 bool WalletImpl::exportKeyImages(const string &filename, bool all)
1373 {
1374 if (m_wallet->watch_only())
1375 {
1376 setStatusError(tr("Wallet is view only"));
1377 return false;
1378 }
1379 if (checkBackgroundSync("cannot export key images"))
1380 return false;
1381
1382 try
1383 {
1384 std::string data = m_wallet->export_key_images_to_str(all);
1385 bool r = m_wallet->save_to_file(filename, data);
1386 if (!r)
1387 {
1388 setStatusError(tr("failed to save file ") + filename);
1389 return false;
1390 }
1391 }
1392 catch (const std::exception &e)
1393 {
1394 LOG_ERROR("Error exporting key images: " << e.what());
1395 setStatusError(e.what());
1396 return false;
1397 }
1398 return true;
1399 }
1400
1401 bool WalletImpl::exportKeyImagesToStr(std::string &keyImages, bool all)
1402 {
1403 if (m_wallet->watch_only())
1404 {
1405 setStatusError(tr("Wallet is view only"));
1406 return false;
1407 }
1408
1409 try
1410 {
1411 keyImages = m_wallet->export_key_images_to_str(all);
1412 }
1413 catch (const std::exception &e)
1414 {
1415 LOG_ERROR("Error exporting key images: " << e.what());
1416 setStatusError(e.what());
1417 return false;
1418 }
1419 return true;
1420 }
1421
1422 bool WalletImpl::exportKeyImagesForOutputsFromStr(const std::string &outputs, std::string &keyImages)
1423 {
1424 if (m_wallet->watch_only())
1425 {
1426 setStatusError(tr("Wallet is view only"));
1427 return false;
1428 }
1429
1430 try
1431 {
1432 keyImages = m_wallet->export_key_images_for_outputs_from_str(outputs);
1433 }
1434 catch (const std::exception &e)
1435 {
1436 LOG_ERROR("Error exporting key images: " << e.what());
1437 setStatusError(e.what());
1438 return false;
1439 }
1440 return true;
1441 }
1442
1443 bool WalletImpl::importKeyImages(const string &filename)
1444 {
1445 if (checkBackgroundSync("cannot import key images"))
1446 return false;
1447 if (!trustedDaemon()) {
1448 setStatusError(tr("Key images can only be imported with a trusted daemon"));
1449 return false;
1450 }
1451 try
1452 {
1453 uint64_t spent = 0, unspent = 0;
1454 uint64_t height = m_wallet->import_key_images(filename, spent, unspent);
1455 LOG_PRINT_L2("Signed key images imported to height " << height << ", "
1456 << print_money(spent) << " spent, " << print_money(unspent) << " unspent");
1457 }
1458 catch (const std::exception &e)
1459 {
1460 LOG_ERROR("Error exporting key images: " << e.what());
1461 setStatusError(string(tr("Failed to import key images: ")) + e.what());
1462 return false;
1463 }
1464
1465 return true;
1466 }
1467
1468 bool WalletImpl::importKeyImagesFromStr(const std::string &keyImages)
1469 {
1470 if (!trustedDaemon()) {
1471 setStatusError(tr("Key images can only be imported with a trusted daemon"));
1472 return false;
1473 }
1474
1475 try
1476 {
1477 uint64_t spent = 0, unspent = 0;
1478 std::string data = keyImages;
1479 uint64_t height = m_wallet->import_key_images_from_str(data, spent, unspent);
1480 LOG_PRINT_L2("Signed key images imported to height " << height << ", "
1481 << print_money(spent) << " spent, " << print_money(unspent) << " unspent");
1482 }
1483 catch (const std::exception &e)
1484 {
1485 LOG_ERROR("Error exporting key images: " << e.what());
1486 setStatusError(string(tr("Failed to import key images: ")) + e.what());
1487 return false;
1488 }
1489
1490 return true;
1491 }
1492
1493 bool WalletImpl::exportOutputs(const string &filename, bool all)
1494 {
1495 if (checkBackgroundSync("cannot export outputs"))
1496 return false;
1497 if (m_wallet->key_on_device())
1498 {
1499 setStatusError(string(tr("Not supported on HW wallets.")) + filename);
1500 return false;
1501 }
1502
1503 try
1504 {
1505 std::string data = m_wallet->export_outputs_to_str(all);
1506 bool r = m_wallet->save_to_file(filename, data);
1507 if (!r)
1508 {
1509 LOG_ERROR("Failed to save file " << filename);
1510 setStatusError(string(tr("Failed to save file: ")) + filename);
1511 return false;
1512 }
1513 }
1514 catch (const std::exception &e)
1515 {
1516 LOG_ERROR("Error exporting outputs: " << e.what());
1517 setStatusError(string(tr("Error exporting outputs: ")) + e.what());
1518 return false;
1519 }
1520
1521 LOG_PRINT_L2("Outputs exported to " << filename);
1522 return true;
1523 }
1524
1525 bool WalletImpl::exportOutputsToStr(std::string &outputs, bool all)
1526 {
1527 if (m_wallet->key_on_device())
1528 {
1529 setStatusError(string(tr("Not supported on HW wallets.")));
1530 return false;
1531 }
1532
1533 try
1534 {
1535 outputs = m_wallet->export_outputs_to_str(all);
1536 }
1537 catch (const std::exception &e)
1538 {
1539 LOG_ERROR("Error exporting outputs: " << e.what());
1540 setStatusError(string(tr("Error exporting outputs: ")) + e.what());
1541 return false;
1542 }
1543
1544 return true;
1545 }
1546
1547 bool WalletImpl::importOutputs(const string &filename)
1548 {
1549 if (checkBackgroundSync("cannot import outputs"))
1550 return false;
1551 if (m_wallet->key_on_device())
1552 {
1553 setStatusError(string(tr("Not supported on HW wallets.")) + filename);
1554 return false;
1555 }
1556
1557 std::string data;
1558 bool r = m_wallet->load_from_file(filename, data);
1559 if (!r)
1560 {
1561 LOG_ERROR("Failed to read file: " << filename);
1562 setStatusError(string(tr("Failed to read file: ")) + filename);
1563 return false;
1564 }
1565
1566 try
1567 {
1568 size_t n_outputs = m_wallet->import_outputs_from_str(data);
1569 LOG_PRINT_L2(std::to_string(n_outputs) << " outputs imported");
1570 }
1571 catch (const std::exception &e)
1572 {
1573 LOG_ERROR("Failed to import outputs: " << e.what());
1574 setStatusError(string(tr("Failed to import outputs: ")) + e.what());
1575 return false;
1576 }
1577
1578 return true;
1579 }
1580
1581 bool WalletImpl::importOutputsFromStr(const std::string &outputs)
1582 {
1583 if (m_wallet->key_on_device())
1584 {
1585 setStatusError("Not supported on HW wallets.");
1586 return false;
1587 }
1588
1589 try
1590 {
1591 size_t n_outputs = m_wallet->import_outputs_from_str(outputs);
1592 LOG_PRINT_L2(std::to_string(n_outputs) << " outputs imported");
1593 }
1594 catch (const std::exception &e)
1595 {
1596 LOG_ERROR("Failed to import outputs: " << e.what());
1597 setStatusError(string(tr("Failed to import outputs: ")) + e.what());
1598 return false;
1599 }
1600
1601 return true;
1602 }
1603
1604 bool WalletImpl::scanTransactions(const std::vector<std::string> &txids)
1605 {
1606 if (checkBackgroundSync("cannot scan transactions"))
1607 return false;
1608 if (txids.empty())
1609 {
1610 setStatusError(string(tr("Failed to scan transactions: no transaction ids provided.")));
1611 return false;
1612 }
1613
1614 // Parse and dedup args
1615 std::unordered_set<crypto::hash> txids_u;
1616 for (const auto &s : txids)
1617 {
1618 crypto::hash txid;
1619 if (!epee::string_tools::hex_to_pod(s, txid))
1620 {
1621 setStatusError(string(tr("Invalid txid specified: ")) + s);
1622 return false;
1623 }
1624 txids_u.insert(txid);
1625 }
1626
1627 try
1628 {
1629 m_wallet->scan_tx(txids_u);
1630 }
1631 catch (const tools::error::wont_reprocess_recent_txs_via_untrusted_daemon &e)
1632 {
1633 setStatusError(e.what());
1634 return false;
1635 }
1636 catch (const std::exception &e)
1637 {
1638 LOG_ERROR("Failed to scan transaction: " << e.what());
1639 setStatusError(string(tr("Failed to scan transaction: ")) + e.what());
1640 return false;
1641 }
1642
1643 return true;
1644 }
1645
1646 bool WalletImpl::setupBackgroundSync(const Wallet::BackgroundSyncType background_sync_type, const std::string &wallet_password, const optional<std::string> &background_cache_password)
1647 {
1648 try
1649 {
1650 PRE_VALIDATE_BACKGROUND_SYNC();
1651
1652 tools::wallet2::BackgroundSyncType bgs_type;
1653 switch (background_sync_type)
1654 {
1655 case Wallet::BackgroundSync_Off: bgs_type = tools::wallet2::BackgroundSyncOff; break;
1656 case Wallet::BackgroundSync_ReusePassword: bgs_type = tools::wallet2::BackgroundSyncReusePassword; break;
1657 case Wallet::BackgroundSync_CustomPassword: bgs_type = tools::wallet2::BackgroundSyncCustomPassword; break;
1658 default: setStatusError(tr("Unknown background sync type")); return false;
1659 }
1660
1661 boost::optional<epee::wipeable_string> bgc_password = background_cache_password
1662 ? boost::optional<epee::wipeable_string>(*background_cache_password)
1663 : boost::none;
1664
1665 LOCK_REFRESH();
1666 m_wallet->setup_background_sync(bgs_type, wallet_password, bgc_password);
1667 }
1668 catch (const std::exception &e)
1669 {
1670 LOG_ERROR("Failed to setup background sync: " << e.what());
1671 setStatusError(string(tr("Failed to setup background sync: ")) + e.what());
1672 return false;
1673 }
1674 return true;
1675 }
1676
1677 Wallet::BackgroundSyncType WalletImpl::getBackgroundSyncType() const
1678 {
1679 switch (m_wallet->background_sync_type())
1680 {
1681 case tools::wallet2::BackgroundSyncOff: return Wallet::BackgroundSync_Off;
1682 case tools::wallet2::BackgroundSyncReusePassword: return Wallet::BackgroundSync_ReusePassword;
1683 case tools::wallet2::BackgroundSyncCustomPassword: return Wallet::BackgroundSync_CustomPassword;
1684 default: setStatusError(tr("Unknown background sync type")); return Wallet::BackgroundSync_Off;
1685 }
1686 }
1687
1688 bool WalletImpl::startBackgroundSync()
1689 {
1690 try
1691 {
1692 PRE_VALIDATE_BACKGROUND_SYNC();
1693 LOCK_REFRESH();
1694 m_wallet->start_background_sync();
1695 }
1696 catch (const std::exception &e)
1697 {
1698 LOG_ERROR("Failed to start background sync: " << e.what());
1699 setStatusError(string(tr("Failed to start background sync: ")) + e.what());
1700 return false;
1701 }
1702 return true;
1703 }
1704
1705 bool WalletImpl::stopBackgroundSync(const std::string &wallet_password)
1706 {
1707 try
1708 {
1709 PRE_VALIDATE_BACKGROUND_SYNC();
1710 LOCK_REFRESH();
1711 m_wallet->stop_background_sync(epee::wipeable_string(wallet_password));
1712 }
1713 catch (const std::exception &e)
1714 {
1715 LOG_ERROR("Failed to stop background sync: " << e.what());
1716 setStatusError(string(tr("Failed to stop background sync: ")) + e.what());
1717 return false;
1718 }
1719 return true;
1720 }
1721
1722 std::string WalletImpl::printBlockchain()
1723 {
1724 return m_wallet->printBlockchain();
1725 }
1726 std::string WalletImpl::printTransfers()
1727 {
1728 return m_wallet->printTransfers();
1729 }
1730 std::string WalletImpl::printPayments()
1731 {
1732 return m_wallet->printPayments();
1733 }
1734 std::string WalletImpl::printUnconfirmedPayments()
1735 {
1736 return m_wallet->printUnconfirmedPayments();
1737 }
1738 std::string WalletImpl::printConfirmedTransferDetails()
1739 {
1740 return m_wallet->printConfirmedTransferDetails();
1741 }
1742 std::string WalletImpl::printUnconfirmedTransferDetails()
1743 {
1744 return m_wallet->printUnconfirmedTransferDetails();
1745 }
1746 std::string WalletImpl::printPubKeys()
1747 {
1748 return m_wallet->printPubKeys();
1749 }
1750 std::string WalletImpl::printTxNotes()
1751 {
1752 return m_wallet->printTxNotes();
1753 }
1754 std::string WalletImpl::printSubaddresses()
1755 {
1756 return m_wallet->printSubaddresses();
1757 }
1758 std::string WalletImpl::printSubaddressLabels()
1759 {
1760 return m_wallet->printSubaddressLabels();
1761 }
1762 std::string WalletImpl::printAdditionalTxKeys()
1763 {
1764 return m_wallet->printAdditionalTxKeys();
1765 }
1766 std::string WalletImpl::printAttributes()
1767 {
1768 return m_wallet->printAttributes();
1769 }
1770 std::string WalletImpl::printKeyImages()
1771 {
1772 return m_wallet->printKeyImages();
1773 }
1774 std::string WalletImpl::printAccountTags()
1775 {
1776 return m_wallet->printAccountTags();
1777 }
1778 std::string WalletImpl::printTxKeys()
1779 {
1780 return m_wallet->printTxKeys();
1781 }
1782 std::string WalletImpl::printAddressBook()
1783 {
1784 return m_wallet->printAddressBook();
1785 }
1786 std::string WalletImpl::printScannedPoolTxs()
1787 {
1788 return m_wallet->printScannedPoolTxs();
1789 }
1790
1791 bool WalletImpl::haveTransaction(const std::string &txid)
1792 {
1793 crypto::hash txid_;
1794 if(!epee::string_tools::hex_to_pod(txid, txid_))
1795 {
1796 setStatusError(tr("Failed to parse txid"));
1797 return false;
1798 }
1799
1800 return m_wallet->have_tx(txid_);
1801 }
1802
1803 void WalletImpl::addSubaddressAccount(const std::string& label)
1804 {
1805 if (checkBackgroundSync("cannot add account"))
1806 return;
1807 m_wallet->add_subaddress_account(label);
1808 }
1809 size_t WalletImpl::numSubaddressAccounts() const
1810 {
1811 return m_wallet->get_num_subaddress_accounts();
1812 }
1813 size_t WalletImpl::numSubaddresses(uint32_t accountIndex) const
1814 {
1815 return m_wallet->get_num_subaddresses(accountIndex);
1816 }
1817 void WalletImpl::addSubaddress(uint32_t accountIndex, const std::string& label)
1818 {
1819 if (checkBackgroundSync("cannot add subbaddress"))
1820 return;
1821 m_wallet->add_subaddress(accountIndex, label);
1822 }
1823 std::string WalletImpl::getSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex) const
1824 {
1825 if (checkBackgroundSync("cannot get subbaddress label"))
1826 return "";
1827 try
1828 {
1829 return m_wallet->get_subaddress_label({accountIndex, addressIndex});
1830 }
1831 catch (const std::exception &e)
1832 {
1833 LOG_ERROR("Error getting subaddress label: " << e.what());
1834 setStatusError(string(tr("Failed to get subaddress label: ")) + e.what());
1835 return "";
1836 }
1837 }
1838 void WalletImpl::setSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex, const std::string &label)
1839 {
1840 if (checkBackgroundSync("cannot set subbaddress label"))
1841 return;
1842 try
1843 {
1844 return m_wallet->set_subaddress_label({accountIndex, addressIndex}, label);
1845 }
1846 catch (const std::exception &e)
1847 {
1848 LOG_ERROR("Error setting subaddress label: " << e.what());
1849 setStatusError(string(tr("Failed to set subaddress label: ")) + e.what());
1850 }
1851 }
1852
1853 MultisigState WalletImpl::multisig() const {
1854 MultisigState state;
1855 if (checkBackgroundSync("cannot use multisig"))
1856 return state;
1857 state.isMultisig = m_wallet->multisig(&state.isReady, &state.threshold, &state.total);
1858
1859 return state;
1860 }
1861
1862 string WalletImpl::getMultisigInfo() const {
1863 if (checkBackgroundSync("cannot use multisig"))
1864 return string();
1865 try {
1866 clearStatus();
1867 return m_wallet->get_multisig_first_kex_msg();
1868 } catch (const exception& e) {
1869 LOG_ERROR("Error on generating multisig info: " << e.what());
1870 setStatusError(string(tr("Failed to get multisig info: ")) + e.what());
1871 }
1872
1873 return string();
1874 }
1875
1876 string WalletImpl::makeMultisig(const vector<string>& info, const uint32_t threshold) {
1877 return string();
1878 }
1879
1880 std::string WalletImpl::exchangeMultisigKeys(const std::vector<std::string> &info, const bool force_update_use_with_caution /*= false*/) {
1881 return string();
1882 }
1883
1884 bool WalletImpl::exportMultisigImages(string& images) {
1885 try {
1886 clearStatus();
1887 checkMultisigWalletReady(m_wallet);
1888
1889 auto blob = m_wallet->export_multisig();
1890 images = epee::string_tools::buff_to_hex_nodelimer(blob);
1891 return true;
1892 } catch (const exception& e) {
1893 LOG_ERROR("Error on exporting multisig images: " << e.what());
1894 setStatusError(string(tr("Failed to export multisig images: ")) + e.what());
1895 }
1896
1897 return false;
1898 }
1899
1900 size_t WalletImpl::importMultisigImages(const vector<string>& images) {
1901 try {
1902 clearStatus();
1903 checkMultisigWalletReady(m_wallet);
1904
1905 std::vector<std::string> blobs;
1906 blobs.reserve(images.size());
1907
1908 for (const auto& image: images) {
1909 std::string blob;
1910 if (!epee::string_tools::parse_hexstr_to_binbuff(image, blob)) {
1911 LOG_ERROR("Failed to parse imported multisig images");
1912 setStatusError(tr("Failed to parse imported multisig images"));
1913 return 0;
1914 }
1915
1916 blobs.emplace_back(std::move(blob));
1917 }
1918
1919 return m_wallet->import_multisig(blobs);
1920 } catch (const exception& e) {
1921 LOG_ERROR("Error on importing multisig images: " << e.what());
1922 setStatusError(string(tr("Failed to import multisig images: ")) + e.what());
1923 }
1924
1925 return 0;
1926 }
1927
1928 bool WalletImpl::hasMultisigPartialKeyImages() const {
1929 try {
1930 clearStatus();
1931 checkMultisigWalletReady(m_wallet);
1932
1933 return m_wallet->has_multisig_partial_key_images();
1934 } catch (const exception& e) {
1935 LOG_ERROR("Error on checking for partial multisig key images: " << e.what());
1936 setStatusError(string(tr("Failed to check for partial multisig key images: ")) + e.what());
1937 }
1938
1939 return false;
1940 }
1941
1942 PendingTransaction* WalletImpl::restoreMultisigTransaction(const string& signData) {
1943 try {
1944 clearStatus();
1945 checkMultisigWalletReady(m_wallet);
1946
1947 string binary;
1948 if (!epee::string_tools::parse_hexstr_to_binbuff(signData, binary)) {
1949 throw runtime_error("Failed to deserialize multisig transaction");
1950 }
1951
1952 tools::wallet2::multisig_tx_set txSet;
1953 if (!m_wallet->load_multisig_tx(binary, txSet, {})) {
1954 throw runtime_error("couldn't parse multisig transaction data");
1955 }
1956
1957 auto ptx = new PendingTransactionImpl(*this);
1958 ptx->m_pending_tx = txSet.m_ptx;
1959 ptx->m_signers = txSet.m_signers;
1960
1961 return ptx;
1962 } catch (exception& e) {
1963 LOG_ERROR("Error on restoring multisig transaction: " << e.what());
1964 setStatusError(string(tr("Failed to restore multisig transaction: ")) + e.what());
1965 }
1966
1967 return nullptr;
1968 }
1969
1970 // TODO:
1971 // 1 - properly handle payment id (add another menthod with explicit 'payment_id' param)
1972 // 2 - check / design how "Transaction" can be single interface
1973 // (instead of few different data structures within wallet2 implementation:
1974 // - pending_tx;
1975 // - transfer_details;
1976 // - payment_details;
1977 // - unconfirmed_transfer_details;
1978 // - confirmed_transfer_details)
1979
1980 PendingTransaction *WalletImpl::createTransactionMultDest(const std::vector<string> &dst_addr, const string &payment_id, std::optional<std::vector<uint64_t>> amount, uint32_t mixin_count, PendingTransaction::Priority priority, uint32_t subaddr_account, std::set<uint32_t> subaddr_indices, const std::set<std::string> &preferred_inputs, bool subtractFeeFromAmount)
1981
1982 {
1983 clearStatus();
1984
1985 cryptonote::address_parse_info info;
1986
1987 PendingTransactionImpl * transaction = new PendingTransactionImpl(*this);
1988
1989 do {
1990 if (checkBackgroundSync("cannot create transactions"))
1991 break;
1992
1993 std::vector<uint8_t> extra;
1994 std::string extra_nonce;
1995 vector<cryptonote::tx_destination_entry> dsts;
1996 if (!amount && dst_addr.size() > 1) {
1997 setStatusError(tr("Sending all requires one destination address"));
1998 break;
1999 }
2000 if (amount && (dst_addr.size() != (*amount).size())) {
2001 setStatusError(tr("Destinations and amounts are unequal"));
2002 break;
2003 }
2004 if (!payment_id.empty()) {
2005 crypto::hash payment_id_long;
2006 if (tools::wallet2::parse_long_payment_id(payment_id, payment_id_long)) {
2007 cryptonote::set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id_long);
2008 } else {
2009 setStatusError(tr("payment id has invalid format, expected 64 character hex string: ") + payment_id);
2010 break;
2011 }
2012 }
2013 bool error = false;
2014 for (size_t i = 0; i < dst_addr.size() && !error; i++) {
2015 if(!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), dst_addr[i])) {
2016 // TODO: copy-paste 'if treating as an address fails, try as url' from simplewallet.cpp:1982
2017 setStatusError(tr("Invalid destination address"));
2018 error = true;
2019 break;
2020 }
2021 if (info.has_payment_id) {
2022 if (!extra_nonce.empty()) {
2023 setStatusError(tr("a single transaction cannot use more than one payment id"));
2024 error = true;
2025 break;
2026 }
2027 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
2028 }
2029
2030 if (amount) {
2031 cryptonote::tx_destination_entry de;
2032 de.original = dst_addr[i];
2033 de.addr = info.address;
2034 de.amount = (*amount)[i];
2035 de.is_subaddress = info.is_subaddress;
2036 de.is_integrated = info.has_payment_id;
2037 dsts.push_back(de);
2038 } else {
2039 if (subaddr_indices.empty()) {
2040 for (uint32_t index = 0; index < m_wallet->get_num_subaddresses(subaddr_account); ++index)
2041 subaddr_indices.insert(index);
2042 }
2043 }
2044 }
2045 std::vector<crypto::key_image> preferred_input_list;
2046 if (!preferred_inputs.empty()) {
2047 for (const auto &public_key : preferred_inputs) {
2048 crypto::key_image keyImage;
2049 bool r = epee::string_tools::hex_to_pod(public_key, keyImage);
2050 if (!r) {
2051 error = true;
2052 setStatusError(tr("failed to parse key image"));
2053 break;
2054 }
2055 preferred_input_list.push_back(keyImage);
2056 }
2057 }
2058 if (error) {
2059 break;
2060 }
2061 if (!extra_nonce.empty() && !add_extra_nonce_to_tx_extra(extra, extra_nonce)) {
2062 setStatusError(tr("failed to set up payment id, though it was decoded correctly"));
2063 break;
2064 }
2065 try {
2066 size_t fake_outs_count = mixin_count > 0 ? mixin_count : m_wallet->default_mixin();
2067 fake_outs_count = m_wallet->adjust_mixin(mixin_count);
2068
2069 tools::wallet2::unique_index_container subtract_fee_from_outputs;
2070 subtract_fee_from_outputs.clear();
2071
2072 if (subtractFeeFromAmount) {
2073 for (decltype(subtract_fee_from_outputs)::value_type i = 0; i < dsts.size(); ++i) {
2074 subtract_fee_from_outputs.insert(i);
2075 }
2076 }
2077
2078 if (amount) {
2079 transaction->m_pending_tx = m_wallet->create_transactions_2(dsts, fake_outs_count,
2080 priority,
2081 extra, subaddr_account, subaddr_indices,
2082 subtract_fee_from_outputs, preferred_input_list);
2083 } else {
2084 transaction->m_pending_tx = m_wallet->create_transactions_all(0, info.address, info.is_subaddress, 1, fake_outs_count,
2085 priority,
2086 extra, subaddr_account, subaddr_indices, preferred_input_list);
2087 }
2088 pendingTxPostProcess(transaction);
2089
2090 if (multisig().isMultisig) {
2091 auto tx_set = m_wallet->make_multisig_tx_set(transaction->m_pending_tx);
2092 transaction->m_pending_tx = tx_set.m_ptx;
2093 transaction->m_signers = tx_set.m_signers;
2094 }
2095 } catch (const std::exception& e) {
2096 transaction->exception = std::current_exception();
2097 setStatusError(e.what());
2098 } catch (...) {
2099 setStatusError(tr("unknown error"));
2100 }
2101 } while (false);
2102
2103 statusWithErrorString(transaction->m_status, transaction->m_errorString);
2104
2105 return transaction;
2106 }
2107
2108 PendingTransaction *WalletImpl::createTransaction(const string &dst_addr, const string &payment_id, std::optional<uint64_t> amount, uint32_t mixin_count,
2109 PendingTransaction::Priority priority, uint32_t subaddr_account, std::set<uint32_t> subaddr_indices, const std::set<std::string> &preferred_inputs, bool subtractFeeFromAmount)
2110
2111 {
2112 return createTransactionMultDest(std::vector<string> {dst_addr}, payment_id, amount ? (std::vector<uint64_t> {*amount}) : (std::optional<std::vector<uint64_t>>()), mixin_count, priority, subaddr_account, subaddr_indices, preferred_inputs, subtractFeeFromAmount);
2113 }
2114
2115 PendingTransaction *WalletImpl::createTransactionSingle(const std::string &key_image, const std::string &dst_addr,
2116 size_t outputs, PendingTransaction::Priority priority)
2117 {
2118 return createTransactionSelected({key_image}, dst_addr, outputs, priority);
2119 }
2120
2121 PendingTransaction *WalletImpl::createTransactionSelected(const std::vector<std::string> &key_images, const string &dst_addr,
2122 const size_t outputs, PendingTransaction::Priority priority)
2123 {
2124 clearStatus();
2125
2126 cryptonote::address_parse_info info;
2127
2128 PendingTransactionImpl * transaction = new PendingTransactionImpl(*this);
2129
2130 do {
2131 std::vector<uint8_t> extra;
2132 std::string extra_nonce;
2133 vector<cryptonote::tx_destination_entry> dsts;
2134
2135 bool error = false;
2136
2137 std::vector<crypto::key_image> kis;
2138 for (const auto &key_image : key_images) {
2139 crypto::key_image ki;
2140 if (!epee::string_tools::hex_to_pod(key_image, ki))
2141 {
2142 setStatusError(tr("failed to parse key image"));
2143 error = true;
2144 break;
2145 }
2146 kis.push_back(ki);
2147 }
2148 if (error) {
2149 break;
2150 }
2151
2152 if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), dst_addr))
2153 {
2154 setStatusError(tr("Invalid destination address"));
2155 error = true;
2156 break;
2157 }
2158 if (info.has_payment_id) {
2159 if (!extra_nonce.empty()) {
2160 setStatusError(tr("a single transaction cannot use more than one payment id"));
2161 error = true;
2162 break;
2163 }
2164 set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
2165 }
2166 if (error) {
2167 break;
2168 }
2169 if (!extra_nonce.empty() && !add_extra_nonce_to_tx_extra(extra, extra_nonce)) {
2170 setStatusError(tr("failed to set up payment id, though it was decoded correctly"));
2171 break;
2172 }
2173 try {
2174 size_t fake_outs_count = m_wallet->adjust_mixin(m_wallet->default_mixin()); // can trigger rpc request, may throw
2175
2176 transaction->m_pending_tx = m_wallet->create_transactions_selected(kis, info.address, info.is_subaddress,
2177 outputs, fake_outs_count, priority, extra);
2178
2179 pendingTxPostProcess(transaction);
2180
2181 if (multisig().isMultisig) {
2182 auto tx_set = m_wallet->make_multisig_tx_set(transaction->m_pending_tx);
2183 transaction->m_pending_tx = tx_set.m_ptx;
2184 transaction->m_signers = tx_set.m_signers;
2185 }
2186 } catch (const std::exception& e) {
2187 transaction->exception = std::current_exception();
2188 setStatusError(e.what());
2189 } catch (...) {
2190 setStatusError(tr("unknown error"));
2191 }
2192 } while (false);
2193
2194 statusWithErrorString(transaction->m_status, transaction->m_errorString);
2195
2196 return transaction;
2197 }
2198
2199 PendingTransaction *WalletImpl::createSweepUnmixableTransaction()
2200
2201 {
2202 clearStatus();
2203 cryptonote::tx_destination_entry de;
2204
2205 PendingTransactionImpl * transaction = new PendingTransactionImpl(*this);
2206
2207 do {
2208 if (checkBackgroundSync("cannot sweep"))
2209 break;
2210
2211 try {
2212 transaction->m_pending_tx = m_wallet->create_unmixable_sweep_transactions();
2213 pendingTxPostProcess(transaction);
2214 } catch (const std::exception& e) {
2215 transaction->exception = std::current_exception();
2216 setStatusError(e.what());
2217 } catch (...) {
2218 setStatusError(tr("unknown error"));
2219 }
2220 } while (false);
2221
2222 statusWithErrorString(transaction->m_status, transaction->m_errorString);
2223 return transaction;
2224 }
2225
2226 void WalletImpl::disposeTransaction(PendingTransaction *t)
2227 {
2228 delete t;
2229 }
2230
2231 uint64_t WalletImpl::estimateTransactionFee(const std::vector<std::pair<std::string, uint64_t>> &destinations,
2232 PendingTransaction::Priority priority) const
2233 {
2234 const size_t pubkey_size = 33;
2235 const size_t encrypted_paymentid_size = 11;
2236 const size_t extra_size = pubkey_size + encrypted_paymentid_size;
2237
2238 return m_wallet->estimate_fee(
2239 m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE, 0),
2240 m_wallet->use_fork_rules(4, 0),
2241 1,
2242 m_wallet->get_min_ring_size() - 1,
2243 destinations.size() + 1,
2244 extra_size,
2245 m_wallet->use_fork_rules(8, 0),
2246 m_wallet->use_fork_rules(HF_VERSION_CLSAG, 0),
2247 m_wallet->use_fork_rules(HF_VERSION_BULLETPROOF_PLUS, 0),
2248 m_wallet->use_fork_rules(HF_VERSION_VIEW_TAGS, 0),
2249 m_wallet->get_base_fee(priority),
2250 m_wallet->get_fee_quantization_mask());
2251 }
2252
2253 void WalletImpl::setListener(WalletListener *l)
2254 {
2255 // TODO thread synchronization;
2256 m_wallet2Callback->setListener(l);
2257 }
2258
2259 uint32_t WalletImpl::defaultMixin() const
2260 {
2261 return m_wallet->default_mixin();
2262 }
2263
2264 void WalletImpl::setDefaultMixin(uint32_t arg)
2265 {
2266 if (checkBackgroundSync("cannot set default mixin"))
2267 return;
2268 m_wallet->default_mixin(arg);
2269 }
2270
2271 bool WalletImpl::cacheAttributeExists(const std::string &key) {
2272 std::string value;
2273 return m_wallet->get_attribute(key, value);
2274 }
2275
2276 bool WalletImpl::setCacheAttribute(const std::string &key, const std::string &val)
2277 {
2278 if (checkBackgroundSync("cannot set cache attribute"))
2279 return false;
2280 m_wallet->set_attribute(key, val);
2281 return true;
2282 }
2283
2284 std::string WalletImpl::getCacheAttribute(const std::string &key) const
2285 {
2286 std::string value;
2287 m_wallet->get_attribute(key, value);
2288 return value;
2289 }
2290
2291 bool WalletImpl::setUserNote(const std::string &txid, const std::string &note)
2292 {
2293 if (checkBackgroundSync("cannot set user note"))
2294 return false;
2295 cryptonote::blobdata txid_data;
2296 if(!epee::string_tools::parse_hexstr_to_binbuff(txid, txid_data) || txid_data.size() != sizeof(crypto::hash))
2297 return false;
2298 const crypto::hash htxid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
2299
2300 m_wallet->set_tx_note(htxid, note);
2301 return true;
2302 }
2303
2304 std::string WalletImpl::getUserNote(const std::string &txid) const
2305 {
2306 if (checkBackgroundSync("cannot get user note"))
2307 return "";
2308 cryptonote::blobdata txid_data;
2309 if(!epee::string_tools::parse_hexstr_to_binbuff(txid, txid_data) || txid_data.size() != sizeof(crypto::hash))
2310 return "";
2311 const crypto::hash htxid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
2312
2313 return m_wallet->get_tx_note(htxid);
2314 }
2315
2316 std::string WalletImpl::getTxKey(const std::string &txid_str) const
2317 {
2318 if (checkBackgroundSync("cannot get tx key"))
2319 return "";
2320
2321 crypto::hash txid;
2322 if(!epee::string_tools::hex_to_pod(txid_str, txid))
2323 {
2324 setStatusError(tr("Failed to parse txid"));
2325 return "";
2326 }
2327
2328 crypto::secret_key tx_key;
2329 std::vector<crypto::secret_key> additional_tx_keys;
2330 try
2331 {
2332 clearStatus();
2333 if (m_wallet->get_tx_key(txid, tx_key, additional_tx_keys))
2334 {
2335 clearStatus();
2336 std::ostringstream oss;
2337 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(tx_key)));
2338 for (size_t i = 0; i < additional_tx_keys.size(); ++i)
2339 oss << epee::string_tools::pod_to_hex(unwrap(unwrap(additional_tx_keys[i])));
2340 return oss.str();
2341 }
2342 else
2343 {
2344 setStatusError(tr("no tx keys found for this txid"));
2345 return "";
2346 }
2347 }
2348 catch (const std::exception &e)
2349 {
2350 setStatusError(e.what());
2351 return "";
2352 }
2353 }
2354
2355 bool WalletImpl::checkTxKey(const std::string &txid_str, std::string tx_key_str, const std::string &address_str, uint64_t &received, bool &in_pool, uint64_t &confirmations)
2356 {
2357 crypto::hash txid;
2358 if (!epee::string_tools::hex_to_pod(txid_str, txid))
2359 {
2360 setStatusError(tr("Failed to parse txid"));
2361 return false;
2362 }
2363
2364 crypto::secret_key tx_key;
2365 std::vector<crypto::secret_key> additional_tx_keys;
2366 if (!epee::string_tools::hex_to_pod(tx_key_str.substr(0, 64), tx_key))
2367 {
2368 setStatusError(tr("Failed to parse tx key"));
2369 return false;
2370 }
2371 tx_key_str = tx_key_str.substr(64);
2372 while (!tx_key_str.empty())
2373 {
2374 additional_tx_keys.resize(additional_tx_keys.size() + 1);
2375 if (!epee::string_tools::hex_to_pod(tx_key_str.substr(0, 64), additional_tx_keys.back()))
2376 {
2377 setStatusError(tr("Failed to parse tx key"));
2378 return false;
2379 }
2380 tx_key_str = tx_key_str.substr(64);
2381 }
2382
2383 cryptonote::address_parse_info info;
2384 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address_str))
2385 {
2386 setStatusError(tr("Failed to parse address"));
2387 return false;
2388 }
2389
2390 try
2391 {
2392 m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations);
2393 clearStatus();
2394 return true;
2395 }
2396 catch (const std::exception &e)
2397 {
2398 setStatusError(e.what());
2399 return false;
2400 }
2401 }
2402
2403 std::string WalletImpl::getTxProof(const std::string &txid_str, const std::string &address_str, const std::string &message) const
2404 {
2405 if (checkBackgroundSync("cannot get tx proof"))
2406 return "";
2407
2408 crypto::hash txid;
2409 if (!epee::string_tools::hex_to_pod(txid_str, txid))
2410 {
2411 setStatusError(tr("Failed to parse txid"));
2412 return "";
2413 }
2414
2415 cryptonote::address_parse_info info;
2416 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address_str))
2417 {
2418 setStatusError(tr("Failed to parse address"));
2419 return "";
2420 }
2421
2422 try
2423 {
2424 clearStatus();
2425 return m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, message);
2426 }
2427 catch (const std::exception &e)
2428 {
2429 setStatusError(e.what());
2430 return "";
2431 }
2432 }
2433
2434 bool WalletImpl::checkTxProof(const std::string &txid_str, const std::string &address_str, const std::string &message, const std::string &signature, bool &good, uint64_t &received, bool &in_pool, uint64_t &confirmations)
2435 {
2436 crypto::hash txid;
2437 if (!epee::string_tools::hex_to_pod(txid_str, txid))
2438 {
2439 setStatusError(tr("Failed to parse txid"));
2440 return false;
2441 }
2442
2443 cryptonote::address_parse_info info;
2444 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address_str))
2445 {
2446 setStatusError(tr("Failed to parse address"));
2447 return false;
2448 }
2449
2450 try
2451 {
2452 good = m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, message, signature, received, in_pool, confirmations);
2453 clearStatus();
2454 return true;
2455 }
2456 catch (const std::exception &e)
2457 {
2458 setStatusError(e.what());
2459 return false;
2460 }
2461 }
2462
2463 std::string WalletImpl::getSpendProof(const std::string &txid_str, const std::string &message) const {
2464 if (checkBackgroundSync("cannot get spend proof"))
2465 return "";
2466
2467 crypto::hash txid;
2468 if(!epee::string_tools::hex_to_pod(txid_str, txid))
2469 {
2470 setStatusError(tr("Failed to parse txid"));
2471 return "";
2472 }
2473
2474 try
2475 {
2476 clearStatus();
2477 return m_wallet->get_spend_proof(txid, message);
2478 }
2479 catch (const std::exception &e)
2480 {
2481 setStatusError(e.what());
2482 return "";
2483 }
2484 }
2485
2486 bool WalletImpl::checkSpendProof(const std::string &txid_str, const std::string &message, const std::string &signature, bool &good) const {
2487 good = false;
2488 crypto::hash txid;
2489 if(!epee::string_tools::hex_to_pod(txid_str, txid))
2490 {
2491 setStatusError(tr("Failed to parse txid"));
2492 return false;
2493 }
2494
2495 try
2496 {
2497 clearStatus();
2498 good = m_wallet->check_spend_proof(txid, message, signature);
2499 return true;
2500 }
2501 catch (const std::exception &e)
2502 {
2503 setStatusError(e.what());
2504 return false;
2505 }
2506 }
2507
2508 std::string WalletImpl::getReserveProof(bool all, uint32_t account_index, uint64_t amount, const std::string &message) const {
2509 if (checkBackgroundSync("cannot get reserve proof"))
2510 return "";
2511
2512 try
2513 {
2514 clearStatus();
2515 boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
2516 if (!all)
2517 {
2518 account_minreserve = std::make_pair(account_index, amount);
2519 }
2520 return m_wallet->get_reserve_proof(account_minreserve, message);
2521 }
2522 catch (const std::exception &e)
2523 {
2524 setStatusError(e.what());
2525 return "";
2526 }
2527 }
2528
2529 bool WalletImpl::checkReserveProof(const std::string &address, const std::string &message, const std::string &signature, bool &good, uint64_t &total, uint64_t &spent) const {
2530 cryptonote::address_parse_info info;
2531 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address))
2532 {
2533 setStatusError(tr("Failed to parse address"));
2534 return false;
2535 }
2536 if (info.is_subaddress)
2537 {
2538 setStatusError(tr("Address must not be a subaddress"));
2539 return false;
2540 }
2541
2542 good = false;
2543 try
2544 {
2545 clearStatus();
2546 good = m_wallet->check_reserve_proof(info.address, message, signature, total, spent);
2547 return true;
2548 }
2549 catch (const std::exception &e)
2550 {
2551 setStatusError(e.what());
2552 return false;
2553 }
2554 }
2555
2556 std::string WalletImpl::signMessage(const std::string &message, const std::string &address)
2557 {
2558 if (checkBackgroundSync("cannot sign message"))
2559 return "";
2560
2561 if (address.empty()) {
2562 return m_wallet->sign(message, tools::wallet2::sign_with_spend_key);
2563 }
2564
2565 cryptonote::address_parse_info info;
2566
2567 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address)) {
2568 setStatusError(tr("Failed to parse address"));
2569 return "";
2570 }
2571
2572 auto index = m_wallet->get_subaddress_index(info.address);
2573 if (!index) {
2574 setStatusError(tr("Address doesn't belong to the wallet"));
2575 return "";
2576 }
2577
2578 return m_wallet->sign(message, tools::wallet2::sign_with_spend_key, *index);
2579 }
2580
2581 bool WalletImpl::verifySignedMessage(const std::string &message, const std::string &address, const std::string &signature) const
2582 {
2583 cryptonote::address_parse_info info;
2584
2585 if (!cryptonote::get_account_address_from_str(info, m_wallet->nettype(), address))
2586 return false;
2587
2588 return m_wallet->verify(message, info.address, signature).valid;
2589 }
2590
2591 std::string WalletImpl::signMultisigParticipant(const std::string &message) const
2592 {
2593 clearStatus();
2594
2595 bool ready = false;
2596 if (!m_wallet->multisig(&ready) || !ready) {
2597 m_status = Status_Error;
2598 m_errorString = tr("The wallet must be in multisig ready state");
2599 return {};
2600 }
2601
2602 try {
2603 return m_wallet->sign_multisig_participant(message);
2604 } catch (const std::exception& e) {
2605 m_status = Status_Error;
2606 m_errorString = e.what();
2607 }
2608
2609 return {};
2610 }
2611
2612 bool WalletImpl::verifyMessageWithPublicKey(const std::string &message, const std::string &publicKey, const std::string &signature) const
2613 {
2614 clearStatus();
2615
2616 cryptonote::blobdata pkeyData;
2617 if(!epee::string_tools::parse_hexstr_to_binbuff(publicKey, pkeyData) || pkeyData.size() != sizeof(crypto::public_key))
2618 {
2619 m_status = Status_Error;
2620 m_errorString = tr("Given string is not a key");
2621 return false;
2622 }
2623
2624 try {
2625 crypto::public_key pkey = *reinterpret_cast<const crypto::public_key*>(pkeyData.data());
2626 return m_wallet->verify_with_public_key(message, pkey, signature);
2627 } catch (const std::exception& e) {
2628 m_status = Status_Error;
2629 m_errorString = e.what();
2630 }
2631
2632 return false;
2633 }
2634
2635 bool WalletImpl::connectToDaemon()
2636 {
2637 bool result = m_wallet->check_connection(NULL, NULL, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
2638 if (!result) {
2639 setStatusError("Error connecting to daemon at " + m_wallet->get_daemon_address());
2640 } else {
2641 clearStatus();
2642 // start refreshing here
2643 }
2644 return result;
2645 }
2646
2647 Wallet::ConnectionStatus WalletImpl::connected() const
2648 {
2649 uint32_t version = 0;
2650 m_is_connected = m_wallet->check_connection(&version, NULL, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
2651 if (!m_is_connected)
2652 return Wallet::ConnectionStatus_Disconnected;
2653 // Version check is not implemented in light wallets nodes/wallets
2654 if (!m_wallet->light_wallet() && (version >> 16) != CORE_RPC_VERSION_MAJOR)
2655 return Wallet::ConnectionStatus_WrongVersion;
2656 return Wallet::ConnectionStatus_Connected;
2657 }
2658
2659 void WalletImpl::setTrustedDaemon(bool arg)
2660 {
2661 m_wallet->set_trusted_daemon(arg);
2662 }
2663
2664 bool WalletImpl::trustedDaemon() const
2665 {
2666 return m_wallet->is_trusted_daemon();
2667 }
2668
2669 bool WalletImpl::setProxy(const std::string &address)
2670 {
2671 return m_wallet->set_proxy(address);
2672 }
2673
2674 bool WalletImpl::watchOnly() const
2675 {
2676 return m_wallet->watch_only();
2677 }
2678
2679 bool WalletImpl::isDeterministic() const
2680 {
2681 return m_wallet->is_deterministic();
2682 }
2683
2684 bool WalletImpl::isBackgroundSyncing() const
2685 {
2686 return m_wallet->is_background_syncing();
2687 }
2688
2689 bool WalletImpl::isBackgroundWallet() const
2690 {
2691 return m_wallet->is_background_wallet();
2692 }
2693
2694 void WalletImpl::clearStatus() const
2695 {
2696 boost::lock_guard<boost::mutex> l(m_statusMutex);
2697 m_status = Status_Ok;
2698 m_errorString.clear();
2699 }
2700
2701 void WalletImpl::setStatusError(const std::string& message) const
2702 {
2703 setStatus(Status_Error, message);
2704 }
2705
2706 void WalletImpl::setStatusCritical(const std::string& message) const
2707 {
2708 setStatus(Status_Critical, message);
2709 }
2710
2711 void WalletImpl::setStatus(int status, const std::string& message) const
2712 {
2713 boost::lock_guard<boost::mutex> l(m_statusMutex);
2714 m_status = status;
2715 m_errorString = message;
2716 }
2717
2718 bool WalletImpl::doRefresh()
2719 {
2720 bool success = true;
2721 bool rescan = m_refreshShouldRescan.exchange(false);
2722 // synchronizing async and sync refresh calls
2723 boost::lock_guard<boost::mutex> guarg(m_refreshMutex2);
2724 do try {
2725 LOG_PRINT_L3(__FUNCTION__ << ": doRefresh, rescan = "<<rescan);
2726
2727 if(rescan)
2728 m_wallet->rescan_blockchain(false);
2729
2730 m_wallet->refresh(trustedDaemon());
2731 if (!m_synchronized) {
2732 // Cache output distribution for later
2733 m_wallet->cache_rct_distribution(0);
2734 m_synchronized = true;
2735 }
2736
2737 } catch (const std::exception &e) {
2738 LOG_ERROR(__FUNCTION__ << "Caught an exception in the refresh thread");
2739 success = false;
2740 setStatusError(e.what());
2741 break;
2742 }while(!rescan && (rescan=m_refreshShouldRescan.exchange(false))); // repeat if not rescanned and rescan was requested
2743
2744 if (m_wallet2Callback->getListener()) {
2745 m_wallet2Callback->getListener()->refreshed(success);
2746 }
2747
2748 return success;
2749 }
2750
2751
2752 void WalletImpl::startRefresh()
2753 {
2754 if (!m_refreshEnabled) {
2755 LOG_PRINT_L2(__FUNCTION__ << ": refresh started/resumed...");
2756 m_refreshEnabled = true;
2757 m_refreshCV.notify_one();
2758 }
2759 }
2760
2761
2762 void WalletImpl::pauseRefresh()
2763 {
2764 LOG_PRINT_L2(__FUNCTION__ << ": refresh paused...");
2765 // TODO synchronize access
2766 if (!m_refreshThreadDone) {
2767 m_refreshEnabled = false;
2768 }
2769 }
2770
2771
2772 bool WalletImpl::isNewWallet() const
2773 {
2774 // in case wallet created without daemon connection, closed and opened again,
2775 // it's the same case as if it created from scratch, i.e. we need "fast sync"
2776 // with the daemon (pull hashes instead of pull blocks).
2777 // If wallet cache is rebuilt, creation height stored in .keys is used.
2778 // Watch only wallet is a copy of an existing wallet.
2779 return !(blockChainHeight() > 1 || m_recoveringFromSeed || m_recoveringFromDevice || m_rebuildWalletCache) && !watchOnly();
2780 }
2781
2782 void WalletImpl::pendingTxPostProcess(PendingTransactionImpl * pending)
2783 {
2784 // If the device being used is HW device with cold signing protocol, cold sign then.
2785 if (!m_wallet->get_account().get_device().has_tx_cold_sign()){
2786 return;
2787 }
2788
2789 tools::wallet2::signed_tx_set exported_txs;
2790 std::vector<cryptonote::address_parse_info> dsts_info;
2791
2792 m_wallet->cold_sign_tx(pending->m_pending_tx, exported_txs, dsts_info, pending->m_tx_device_aux);
2793 pending->m_key_images = exported_txs.key_images;
2794 pending->m_pending_tx = exported_txs.ptx;
2795 }
2796
2797 bool WalletImpl::checkBackgroundSync(const std::string &message) const
2798 {
2799 clearStatus();
2800 if (m_wallet->is_background_wallet())
2801 {
2802 LOG_ERROR("Background wallets " + message);
2803 setStatusError(tr("Background wallets ") + message);
2804 return true;
2805 }
2806 if (m_wallet->is_background_syncing())
2807 {
2808 LOG_ERROR(message + " while background syncing");
2809 setStatusError(message + tr(" while background syncing. Stop background syncing first."));
2810 return true;
2811 }
2812 return false;
2813 }
2814
2815 bool WalletImpl::parse_uri(const std::string &uri, std::string &address, std::string &payment_id, uint64_t &amount, std::string &tx_description, std::string &recipient_name, std::vector<std::string> &unknown_parameters, std::string &error)
2816 {
2817 return m_wallet->parse_uri(uri, address, payment_id, amount, tx_description, recipient_name, unknown_parameters, error);
2818 }
2819
2820 std::string WalletImpl::make_uri(const std::string &address, const std::string &payment_id, uint64_t amount, const std::string &tx_description, const std::string &recipient_name, std::string &error) const
2821 {
2822 return m_wallet->make_uri(address, payment_id, amount, tx_description, recipient_name, error);
2823 }
2824
2825 std::string WalletImpl::getDefaultDataDir() const
2826 {
2827 return tools::get_default_data_dir();
2828 }
2829
2830 bool WalletImpl::rescanSpent()
2831 {
2832 clearStatus();
2833 if (checkBackgroundSync("cannot rescan spent"))
2834 return false;
2835 if (!trustedDaemon()) {
2836 setStatusError(tr("Rescan spent can only be used with a trusted daemon"));
2837 return false;
2838 }
2839 try {
2840 m_wallet->rescan_spent();
2841 } catch (const std::exception &e) {
2842 LOG_ERROR(__FUNCTION__ << " error: " << e.what());
2843 setStatusError(e.what());
2844 return false;
2845 }
2846 return true;
2847 }
2848
2849 void WalletImpl::setOffline(bool offline)
2850 {
2851 m_wallet->set_offline(offline);
2852 }
2853
2854 bool WalletImpl::isOffline() const
2855 {
2856 return m_wallet->is_offline();
2857 }
2858
2859 void WalletImpl::hardForkInfo(uint8_t &version, uint64_t &earliest_height) const
2860 {
2861 m_wallet->get_hard_fork_info(version, earliest_height);
2862 }
2863
2864 bool WalletImpl::useForkRules(uint8_t version, int64_t early_blocks) const
2865 {
2866 return m_wallet->use_fork_rules(version,early_blocks);
2867 }
2868
2869 bool WalletImpl::blackballOutputs(const std::vector<std::string> &outputs, bool add)
2870 {
2871 std::vector<std::pair<uint64_t, uint64_t>> raw_outputs;
2872 raw_outputs.reserve(outputs.size());
2873 uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets;
2874 for (const std::string &str: outputs)
2875 {
2876 if (sscanf(str.c_str(), "@%" PRIu64, &amount) == 1)
2877 continue;
2878 if (amount == std::numeric_limits<uint64_t>::max())
2879 {
2880 setStatusError("First line is not an amount");
2881 return true;
2882 }
2883 if (sscanf(str.c_str(), "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset)
2884 {
2885 while (num_offsets--)
2886 raw_outputs.push_back(std::make_pair(amount, offset++));
2887 }
2888 else if (sscanf(str.c_str(), "%" PRIu64, &offset) == 1)
2889 {
2890 raw_outputs.push_back(std::make_pair(amount, offset));
2891 }
2892 else
2893 {
2894 setStatusError(tr("Invalid output: ") + str);
2895 return false;
2896 }
2897 }
2898 bool ret = m_wallet->set_blackballed_outputs(raw_outputs, add);
2899 if (!ret)
2900 {
2901 setStatusError(tr("Failed to mark outputs as spent"));
2902 return false;
2903 }
2904 return true;
2905 }
2906
2907 bool WalletImpl::blackballOutput(const std::string &amount, const std::string &offset)
2908 {
2909 uint64_t raw_amount, raw_offset;
2910 if (!epee::string_tools::get_xtype_from_string(raw_amount, amount))
2911 {
2912 setStatusError(tr("Failed to parse output amount"));
2913 return false;
2914 }
2915 if (!epee::string_tools::get_xtype_from_string(raw_offset, offset))
2916 {
2917 setStatusError(tr("Failed to parse output offset"));
2918 return false;
2919 }
2920 bool ret = m_wallet->blackball_output(std::make_pair(raw_amount, raw_offset));
2921 if (!ret)
2922 {
2923 setStatusError(tr("Failed to mark output as spent"));
2924 return false;
2925 }
2926 return true;
2927 }
2928
2929 bool WalletImpl::unblackballOutput(const std::string &amount, const std::string &offset)
2930 {
2931 uint64_t raw_amount, raw_offset;
2932 if (!epee::string_tools::get_xtype_from_string(raw_amount, amount))
2933 {
2934 setStatusError(tr("Failed to parse output amount"));
2935 return false;
2936 }
2937 if (!epee::string_tools::get_xtype_from_string(raw_offset, offset))
2938 {
2939 setStatusError(tr("Failed to parse output offset"));
2940 return false;
2941 }
2942 bool ret = m_wallet->unblackball_output(std::make_pair(raw_amount, raw_offset));
2943 if (!ret)
2944 {
2945 setStatusError(tr("Failed to mark output as unspent"));
2946 return false;
2947 }
2948 return true;
2949 }
2950
2951 bool WalletImpl::getRing(const std::string &key_image, std::vector<uint64_t> &ring) const
2952 {
2953 crypto::key_image raw_key_image;
2954 if (!epee::string_tools::hex_to_pod(key_image, raw_key_image))
2955 {
2956 setStatusError(tr("Failed to parse key image"));
2957 return false;
2958 }
2959 bool ret = m_wallet->get_ring(raw_key_image, ring);
2960 if (!ret)
2961 {
2962 setStatusError(tr("Failed to get ring"));
2963 return false;
2964 }
2965 return true;
2966 }
2967
2968 bool WalletImpl::getRings(const std::string &txid, std::vector<std::pair<std::string, std::vector<uint64_t>>> &rings) const
2969 {
2970 crypto::hash raw_txid;
2971 if (!epee::string_tools::hex_to_pod(txid, raw_txid))
2972 {
2973 setStatusError(tr("Failed to parse txid"));
2974 return false;
2975 }
2976 std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> raw_rings;
2977 bool ret = m_wallet->get_rings(raw_txid, raw_rings);
2978 if (!ret)
2979 {
2980 setStatusError(tr("Failed to get rings"));
2981 return false;
2982 }
2983 for (const auto &r: raw_rings)
2984 {
2985 rings.push_back(std::make_pair(epee::string_tools::pod_to_hex(r.first), r.second));
2986 }
2987 return true;
2988 }
2989
2990 bool WalletImpl::setRing(const std::string &key_image, const std::vector<uint64_t> &ring, bool relative)
2991 {
2992 crypto::key_image raw_key_image;
2993 if (!epee::string_tools::hex_to_pod(key_image, raw_key_image))
2994 {
2995 setStatusError(tr("Failed to parse key image"));
2996 return false;
2997 }
2998 bool ret = m_wallet->set_ring(raw_key_image, ring, relative);
2999 if (!ret)
3000 {
3001 setStatusError(tr("Failed to set ring"));
3002 return false;
3003 }
3004 return true;
3005 }
3006
3007 void WalletImpl::segregatePreForkOutputs(bool segregate)
3008 {
3009 m_wallet->segregate_pre_fork_outputs(segregate);
3010 }
3011
3012 void WalletImpl::segregationHeight(uint64_t height)
3013 {
3014 m_wallet->segregation_height(height);
3015 }
3016
3017 void WalletImpl::keyReuseMitigation2(bool mitigation)
3018 {
3019 m_wallet->key_reuse_mitigation2(mitigation);
3020 }
3021
3022 bool WalletImpl::lockKeysFile()
3023 {
3024 return m_wallet->lock_keys_file();
3025 }
3026
3027 bool WalletImpl::unlockKeysFile()
3028 {
3029 return m_wallet->unlock_keys_file();
3030 }
3031
3032 bool WalletImpl::isKeysFileLocked()
3033 {
3034 return m_wallet->is_keys_file_locked();
3035 }
3036
3037 uint64_t WalletImpl::coldKeyImageSync(uint64_t &spent, uint64_t &unspent)
3038 {
3039 return m_wallet->cold_key_image_sync(spent, unspent);
3040 }
3041
3042 void WalletImpl::deviceShowAddress(uint32_t accountIndex, uint32_t addressIndex, const std::string &paymentId)
3043 {
3044 boost::optional<crypto::hash8> payment_id_param = boost::none;
3045 if (!paymentId.empty())
3046 {
3047 crypto::hash8 payment_id;
3048 bool res = tools::wallet2::parse_short_payment_id(paymentId, payment_id);
3049 if (!res)
3050 {
3051 throw runtime_error("Invalid payment ID");
3052 }
3053 payment_id_param = payment_id;
3054 }
3055
3056 m_wallet->device_show_address(accountIndex, addressIndex, payment_id_param);
3057 }
3058
3059 bool WalletImpl::reconnectDevice()
3060 {
3061 clearStatus();
3062
3063 bool r;
3064 try {
3065 r = m_wallet->reconnect_device();
3066 }
3067 catch (const std::exception &e) {
3068 LOG_ERROR(__FUNCTION__ << " error: " << e.what());
3069 setStatusError(e.what());
3070 return false;
3071 }
3072
3073 return r;
3074 }
3075
3076 uint64_t WalletImpl::getBytesReceived()
3077 {
3078 return m_wallet->get_bytes_received();
3079 }
3080
3081 uint64_t WalletImpl::getBytesSent()
3082 {
3083 return m_wallet->get_bytes_sent();
3084 }
3085
3086 bool WalletImpl::isDeviceConnected()
3087 {
3088 return m_wallet->device_connected();
3089 }
3090
3091 bool WalletImpl::setRingDatabase(const std::string &path) {
3092 std::string ringdb_path = path;
3093 if (ringdb_path.empty()) {
3094 ringdb_path = get_default_ringdb_path(m_wallet->nettype());
3095 }
3096 return m_wallet->set_ring_database(ringdb_path);
3097 }
3098
3099 tools::wallet2* WalletImpl::getWallet() {
3100 return m_wallet.get();
3101 }
3102
3103 } // namespace