Debian Codegraph @

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