Debian Codegraph @

src/wallet/wallet_rpc_server.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 #include <boost/format.hpp>
31 #include <boost/asio/ip/address.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/algorithm/string.hpp>
34 #include <boost/preprocessor/stringize.hpp>
35 #include <cstdint>
36 #include <chrono>
37 #include "include_base_utils.h"
38 using namespace epee;
39
40 #include "version.h"
41 #include "wallet_rpc_server.h"
42 #include "wallet/wallet_args.h"
43 #include "common/command_line.h"
44 #include "common/i18n.h"
45 #include "common/scoped_message_writer.h"
46 #include "cryptonote_config.h"
47 #include "cryptonote_basic/cryptonote_format_utils.h"
48 #include "cryptonote_basic/account.h"
49 #include "multisig/multisig.h"
50 #include "wallet_rpc_server_commands_defs.h"
51 #include "misc_language.h"
52 #include "string_coding.h"
53 #include "string_tools.h"
54 #include "crypto/hash.h"
55 #include "mnemonics/electrum-words.h"
56 #include "rpc/rpc_args.h"
57 #include "rpc/core_rpc_server_commands_defs.h"
58 #include "daemonizer/daemonizer.h"
59
60 #undef MONERO_DEFAULT_LOG_CATEGORY
61 #define MONERO_DEFAULT_LOG_CATEGORY "wallet.rpc"
62
63 #define DEFAULT_AUTO_REFRESH_PERIOD 20 // seconds
64 #define REFRESH_INDICATIVE_BLOCK_CHUNK_SIZE 256 // just to split refresh in separate calls to play nicer with other threads
65
66 #define CHECK_MULTISIG_ENABLED() \
67 do \
68 { \
69 if (m_wallet->multisig() && !m_wallet->is_multisig_enabled()) \
70 { \
71 er.code = WALLET_RPC_ERROR_CODE_DISABLED; \
72 er.message = "This wallet is multisig, and multisig is disabled. Multisig is an experimental feature and may have bugs. Things that could go wrong include: funds sent to a multisig wallet can't be spent at all, can only be spent with the participation of a malicious group member, or can be stolen by a malicious group member. You can enable it by running this once in monero-wallet-cli: set enable-multisig-experimental 1"; \
73 return false; \
74 } \
75 } while(0)
76
77 #define CHECK_IF_BACKGROUND_SYNCING() \
78 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING_BASE(false)
79
80 #define CHECK_IF_RESTRICTED_BACKGROUND_SYNCING() \
81 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING_BASE(true)
82
83 #define CHECK_IF_RESTRICTED_BACKGROUND_SYNCING_BASE(check_restricted) \
84 do \
85 { \
86 if (check_restricted && m_restricted) \
87 { \
88 er.code = WALLET_RPC_ERROR_CODE_DENIED; \
89 er.message = "Command unavailable in restricted mode."; \
90 return false; \
91 } \
92 if (!m_wallet) { return not_open(er); } \
93 if (m_wallet->is_background_wallet()) \
94 { \
95 er.code = WALLET_RPC_ERROR_CODE_IS_BACKGROUND_WALLET; \
96 er.message = "This command is disabled for background wallets."; \
97 return false; \
98 } \
99 if (m_wallet->is_background_syncing()) \
100 { \
101 er.code = WALLET_RPC_ERROR_CODE_IS_BACKGROUND_SYNCING; \
102 er.message = "This command is disabled while background syncing. Stop background syncing to use this command."; \
103 return false; \
104 } \
105 } while(0)
106
107 #define PRE_VALIDATE_BACKGROUND_SYNC() \
108 do \
109 { \
110 if (m_restricted) \
111 { \
112 er.code = WALLET_RPC_ERROR_CODE_DENIED; \
113 er.message = "Command unavailable in restricted mode."; \
114 return false; \
115 } \
116 if (!m_wallet) { return not_open(er); } \
117 if (m_wallet->key_on_device()) \
118 { \
119 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR; \
120 er.message = "Command not supported by HW wallet"; \
121 return false; \
122 } \
123 if (m_wallet->multisig()) \
124 { \
125 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR; \
126 er.message = "Multisig wallet cannot enable background sync"; \
127 return false; \
128 } \
129 if (m_wallet->watch_only()) \
130 { \
131 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY; \
132 er.message = "Watch-only wallet cannot enable background sync"; \
133 return false; \
134 } \
135 } while (0)
136
137 namespace
138 {
139 const command_line::arg_descriptor<std::string, true> arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"};
140 const command_line::arg_descriptor<bool> arg_disable_rpc_login = {"disable-rpc-login", "Disable HTTP authentication for RPC connections served by this process"};
141 const command_line::arg_descriptor<bool> arg_restricted = {"restricted-rpc", "Restricts to view-only commands", false};
142 const command_line::arg_descriptor<std::string> arg_wallet_dir = {"wallet-dir", "Directory for newly created wallets"};
143 const command_line::arg_descriptor<bool> arg_prompt_for_password = {"prompt-for-password", "Prompts for password when not provided", false};
144 const command_line::arg_descriptor<bool> arg_no_initial_sync = {"no-initial-sync", "Skips the initial sync before listening for connections", false};
145 const command_line::arg_descriptor<std::size_t> arg_rpc_max_connections_per_public_ip = {"rpc-max-connections-per-public-ip", "Max RPC connections per public IP permitted", DEFAULT_RPC_MAX_CONNECTIONS_PER_PUBLIC_IP};
146 const command_line::arg_descriptor<std::size_t> arg_rpc_max_connections_per_private_ip = {"rpc-max-connections-per-private-ip", "Max RPC connections per private and localhost IP permitted", DEFAULT_RPC_MAX_CONNECTIONS_PER_PRIVATE_IP};
147 const command_line::arg_descriptor<std::size_t> arg_rpc_max_connections = {"rpc-max-connections", "Max RPC connections permitted", DEFAULT_RPC_MAX_CONNECTIONS};
148 const command_line::arg_descriptor<std::size_t> arg_rpc_response_soft_limit = {"rpc-response-soft-limit", "Max response bytes that can be queued, enforced at next response attempt", DEFAULT_RPC_SOFT_LIMIT_SIZE};
149
150 constexpr const char default_rpc_username[] = "monero";
151
152 boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
153 {
154 auto pwd_container = tools::password_container::prompt(verify, prompt);
155 if (!pwd_container)
156 {
157 MERROR("failed to read wallet password");
158 }
159 return pwd_container;
160 }
161 //------------------------------------------------------------------------------------------------------------------------------
162 void set_confirmations(tools::wallet_rpc::transfer_entry &entry, uint64_t blockchain_height, uint64_t block_reward, uint64_t unlock_time)
163 {
164 if (entry.height >= blockchain_height || (entry.height == 0 && (!strcmp(entry.type.c_str(), "pending") || !strcmp(entry.type.c_str(), "pool"))))
165 entry.confirmations = 0;
166 else
167 entry.confirmations = blockchain_height - entry.height;
168
169 if (block_reward == 0)
170 entry.suggested_confirmations_threshold = 0;
171 else
172 entry.suggested_confirmations_threshold = (entry.amount + block_reward - 1) / block_reward;
173
174 if (unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
175 {
176 if (unlock_time > blockchain_height)
177 entry.suggested_confirmations_threshold = std::max(entry.suggested_confirmations_threshold, unlock_time - blockchain_height);
178 }
179 else
180 {
181 const uint64_t now = time(NULL);
182 if (unlock_time > now)
183 entry.suggested_confirmations_threshold = std::max(entry.suggested_confirmations_threshold, (unlock_time - now + DIFFICULTY_TARGET_V2 - 1) / DIFFICULTY_TARGET_V2);
184 }
185 }
186 }
187
188 namespace tools
189 {
190 const char* wallet_rpc_server::tr(const char* str)
191 {
192 return i18n_translate(str, "tools::wallet_rpc_server");
193 }
194
195 //------------------------------------------------------------------------------------------------------------------------------
196 wallet_rpc_server::wallet_rpc_server():m_wallet(NULL), rpc_login_file(), m_stop(false), m_restricted(false), m_vm(NULL)
197 {
198 }
199 //------------------------------------------------------------------------------------------------------------------------------
200 wallet_rpc_server::~wallet_rpc_server()
201 {
202 if (m_wallet)
203 delete m_wallet;
204 }
205 //------------------------------------------------------------------------------------------------------------------------------
206 void wallet_rpc_server::set_wallet(wallet2 *cr)
207 {
208 m_wallet = cr;
209 }
210 //------------------------------------------------------------------------------------------------------------------------------
211 bool wallet_rpc_server::run()
212 {
213 m_stop = false;
214
215 const auto auto_refresh_evaluation_ms = std::chrono::milliseconds(200);
216
217 m_net_server.add_idle_handler([=] { // Implicit capture of this-pointer deprecated in C++20.
218 const auto auto_refresh_period = m_auto_refresh_period.load(std::memory_order_relaxed);
219 if (auto_refresh_period == 0) // disabled
220 return true;
221
222 // Check if m_auto_refresh_period seconds have passed since the last refresh attempt.
223 const auto auto_refresh_interval_ms = std::chrono::milliseconds(auto_refresh_period * 1'000);
224 if (auto_refresh_interval_ms <= auto_refresh_evaluation_ms)
225 {
226 LOG_PRINT_L0((boost::format(tr("The auto wallet sync evaluation interval of %i ms must be larger than the refresh interval of %i ms"))
227 % auto_refresh_evaluation_ms.count()
228 % auto_refresh_interval_ms.count()).str());
229 return true;
230 }
231
232 const auto now = std::chrono::steady_clock::now();
233 if (now < m_last_auto_refresh_time + auto_refresh_interval_ms)
234 return true;
235
236 uint64_t blocks_fetched = 0;
237 bool refresh_success = false;
238 const auto start = std::chrono::steady_clock::now();
239
240 try
241 {
242 bool received_money = false;
243 if (m_wallet) m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, blocks_fetched, received_money, true, true, REFRESH_INDICATIVE_BLOCK_CHUNK_SIZE);
244 refresh_success = true;
245 }
246 catch (const std::exception& ex)
247 {
248 LOG_ERROR("Exception at while refreshing, what=" << ex.what());
249 }
250
251 const auto end = std::chrono::steady_clock::now();
252 const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
253
254 if (refresh_success)
255 LOG_PRINT_L3((boost::format(tr("Automated wallet block refresh took %i ms")) % elapsed.count()).str());
256
257 const bool syncing_against_tip_of_chain = blocks_fetched < REFRESH_INDICATIVE_BLOCK_CHUNK_SIZE;
258 if (syncing_against_tip_of_chain)
259 {
260 // At this point, we can poll for a refresh every m_auto_refresh_period seconds.
261 m_last_auto_refresh_time = end;
262 }
263 else
264 {
265 // We are in a state of synchronization, blasting through the maximum chunks of blocks
266 // because we are not at the tip of the chain. In this case, if we update m_last_auto_refresh_time,
267 // we'll need to wait an entire m_refresh_interval_ms before processing the next batch. On the other hand,
268 // if we do not update m_last_auto_refresh_time, we'll never yield (other calls to the RPC will hang)
269 // in the case that elapsed > auto_refresh_evaluation_ms since we'll immediately be scheduled for another block sync.
270 const bool over_one_refresh_period_passed = end > m_last_auto_refresh_time + auto_refresh_interval_ms;
271 if (over_one_refresh_period_passed)
272 {
273 // auto_refresh_interval_ms of straight-blasting through blocks has elapsed without end.
274 // Let's freee up the network thread for between 200ms to 300ms (non-deterministic) to handle other requests.
275 const auto refresh_throttle = auto_refresh_evaluation_ms + std::chrono::milliseconds(100);
276 m_last_auto_refresh_time = end - auto_refresh_interval_ms + refresh_throttle;
277 LOG_PRINT_L3((boost::format(tr("Temporarily throttling wallet block refresh by around %i ms")) % refresh_throttle.count()).str());
278 }
279 }
280 return true;
281 }, auto_refresh_evaluation_ms.count());
282 m_net_server.add_idle_handler([this](){
283 if (m_stop.load(std::memory_order_relaxed))
284 {
285 send_stop_signal();
286 return false;
287 }
288 return true;
289 }, 500);
290
291 //DO NOT START THIS SERVER IN MORE THEN 1 THREADS WITHOUT REFACTORING
292 return epee::http_server_impl_base<wallet_rpc_server, connection_context>::run(1, true);
293 }
294 //------------------------------------------------------------------------------------------------------------------------------
295 void wallet_rpc_server::stop()
296 {
297 if (m_wallet)
298 {
299 m_wallet->store();
300 m_wallet->deinit();
301 delete m_wallet;
302 m_wallet = NULL;
303 }
304 }
305 //------------------------------------------------------------------------------------------------------------------------------
306 bool wallet_rpc_server::init(const boost::program_options::variables_map *vm)
307 {
308 auto rpc_config = cryptonote::rpc_args::process(*vm);
309 if (!rpc_config)
310 return false;
311
312 m_vm = vm;
313
314 boost::optional<epee::net_utils::http::login> http_login{};
315 std::string bind_port = command_line::get_arg(*m_vm, arg_rpc_bind_port);
316 const bool disable_auth = command_line::get_arg(*m_vm, arg_disable_rpc_login);
317 m_restricted = command_line::get_arg(*m_vm, arg_restricted);
318 if (!command_line::is_arg_defaulted(*m_vm, arg_wallet_dir))
319 {
320 if (!command_line::is_arg_defaulted(*m_vm, wallet_args::arg_wallet_file()))
321 {
322 MERROR(arg_wallet_dir.name << " and " << wallet_args::arg_wallet_file().name << " are incompatible, use only one of them");
323 return false;
324 }
325 m_wallet_dir = command_line::get_arg(*m_vm, arg_wallet_dir);
326 #ifdef _WIN32
327 #define MKDIR(path, mode) mkdir(path)
328 #else
329 #define MKDIR(path, mode) mkdir(path, mode)
330 #endif
331 if (!m_wallet_dir.empty() && MKDIR(m_wallet_dir.c_str(), 0700) < 0 && errno != EEXIST)
332 {
333 #ifdef _WIN32
334 LOG_ERROR(tr("Failed to create directory ") + m_wallet_dir);
335 #else
336 LOG_ERROR((boost::format(tr("Failed to create directory %s: %s")) % m_wallet_dir % strerror(errno)).str());
337 #endif
338 return false;
339 }
340 }
341
342 if (disable_auth)
343 {
344 if (rpc_config->login)
345 {
346 const cryptonote::rpc_args::descriptors arg{};
347 LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg.rpc_login.name);
348 return false;
349 }
350 }
351 else // auth enabled
352 {
353 if (!rpc_config->login)
354 {
355 std::array<std::uint8_t, 16> rand_128bit{{}};
356 crypto::rand(rand_128bit.size(), rand_128bit.data());
357 http_login.emplace(
358 default_rpc_username,
359 string_encoding::base64_encode(rand_128bit.data(), rand_128bit.size())
360 );
361
362 std::string temp = "monero-wallet-rpc." + bind_port + ".login";
363 rpc_login_file = tools::private_file::drop_and_recreate(temp);
364 if (!rpc_login_file.handle())
365 {
366 LOG_ERROR(tr("Failed to create file ") << temp << tr(". Check permissions or remove file"));
367 return false;
368 }
369 std::fputs(http_login->username.c_str(), rpc_login_file.handle());
370 std::fputc(':', rpc_login_file.handle());
371 const epee::wipeable_string password = http_login->password;
372 std::fwrite(password.data(), 1, password.size(), rpc_login_file.handle());
373 std::fflush(rpc_login_file.handle());
374 if (std::ferror(rpc_login_file.handle()))
375 {
376 LOG_ERROR(tr("Error writing to file ") << temp);
377 return false;
378 }
379 LOG_PRINT_L0(tr("RPC username/password is stored in file ") << temp);
380 }
381 else // chosen user/pass
382 {
383 http_login.emplace(
384 std::move(rpc_config->login->username), std::move(rpc_config->login->password).password()
385 );
386 }
387 assert(bool(http_login));
388 } // end auth enabled
389
390 m_auto_refresh_period.store(DEFAULT_AUTO_REFRESH_PERIOD, std::memory_order_relaxed);
391 const auto over_one_period_ago = std::chrono::steady_clock::now() - std::chrono::seconds(m_auto_refresh_period.load(std::memory_order_relaxed) * 2);
392 m_last_auto_refresh_time = over_one_period_ago;
393
394 check_background_mining();
395
396 const auto max_connections_public = command_line::get_arg(vm, arg_rpc_max_connections_per_public_ip);
397 const auto max_connections_private = command_line::get_arg(vm, arg_rpc_max_connections_per_private_ip);
398 const auto max_connections = command_line::get_arg(vm, arg_rpc_max_connections);
399
400 if (max_connections < max_connections_public)
401 {
402 MFATAL(arg_rpc_max_connections_per_public_ip.name << " is bigger than " << arg_rpc_max_connections.name);
403 return false;
404 }
405 if (max_connections < max_connections_private)
406 {
407 MFATAL(arg_rpc_max_connections_per_private_ip.name << " is bigger than " << arg_rpc_max_connections.name);
408 return false;
409 }
410
411 m_net_server.set_threads_prefix("RPC");
412 auto rng = [](size_t len, uint8_t *ptr) { return crypto::rand(len, ptr); };
413 return epee::http_server_impl_base<wallet_rpc_server, connection_context>::init(
414 rng, std::move(bind_port), std::move(rpc_config->bind_ip),
415 std::move(rpc_config->bind_ipv6_address), std::move(rpc_config->use_ipv6), std::move(rpc_config->require_ipv4),
416 std::move(rpc_config->access_control_origins), std::move(http_login),
417 std::move(rpc_config->ssl_options),
418 max_connections_public, max_connections_private, max_connections,
419 command_line::get_arg(vm, arg_rpc_response_soft_limit)
420 );
421 }
422 //------------------------------------------------------------------------------------------------------------------------------
423 void wallet_rpc_server::check_background_mining()
424 {
425 if (!m_wallet)
426 return;
427 // Background mining can be toggled from the main wallet
428 if (m_wallet->is_background_wallet() || m_wallet->is_background_syncing())
429 return;
430
431 tools::wallet2::BackgroundMiningSetupType setup = m_wallet->setup_background_mining();
432 if (setup == tools::wallet2::BackgroundMiningNo)
433 {
434 MLOG_RED(el::Level::Warning, "Background mining not enabled. Run \"set setup-background-mining 1\" in monero-wallet-cli to change.");
435 return;
436 }
437
438 if (!m_wallet->is_trusted_daemon())
439 {
440 MDEBUG("Using an untrusted daemon, skipping background mining check");
441 return;
442 }
443
444 cryptonote::COMMAND_RPC_MINING_STATUS::request req;
445 cryptonote::COMMAND_RPC_MINING_STATUS::response res;
446 bool r = m_wallet->invoke_http_json("/mining_status", req, res);
447 if (!r || res.status != CORE_RPC_STATUS_OK)
448 {
449 MERROR("Failed to query mining status: " << (r ? res.status : "No connection to daemon"));
450 return;
451 }
452 if (res.active || res.is_background_mining_enabled)
453 return;
454
455 if (setup == tools::wallet2::BackgroundMiningMaybe)
456 {
457 MINFO("The daemon is not set up to background mine.");
458 MINFO("With background mining enabled, the daemon will mine when idle and not on battery.");
459 MINFO("Enabling this supports the network you are using, and makes you eligible for receiving new monero");
460 MINFO("Set setup-background-mining to 1 in monero-wallet-cli to change.");
461 return;
462 }
463
464 cryptonote::COMMAND_RPC_START_MINING::request req2;
465 cryptonote::COMMAND_RPC_START_MINING::response res2;
466 req2.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
467 req2.threads_count = 1;
468 req2.do_background_mining = true;
469 req2.ignore_battery = false;
470 r = m_wallet->invoke_http_json("/start_mining", req2, res);
471 if (!r || res2.status != CORE_RPC_STATUS_OK)
472 {
473 MERROR("Failed to setup background mining: " << (r ? res.status : "No connection to daemon"));
474 return;
475 }
476
477 MINFO("Background mining enabled. The daemon will mine when idle and not on battery.");
478 }
479 //------------------------------------------------------------------------------------------------------------------------------
480 bool wallet_rpc_server::not_open(epee::json_rpc::error& er)
481 {
482 er.code = WALLET_RPC_ERROR_CODE_NOT_OPEN;
483 er.message = "No wallet file";
484 return false;
485 }
486 //------------------------------------------------------------------------------------------------------------------------------
487 void wallet_rpc_server::fill_transfer_entry(tools::wallet_rpc::transfer_entry &entry, const crypto::hash &txid, const crypto::hash &payment_id, const tools::wallet2::payment_details &pd)
488 {
489 entry.txid = string_tools::pod_to_hex(pd.m_tx_hash);
490 entry.payment_id = string_tools::pod_to_hex(payment_id);
491 if (entry.payment_id.substr(16).find_first_not_of('0') == std::string::npos)
492 entry.payment_id = entry.payment_id.substr(0,16);
493 entry.height = pd.m_block_height;
494 entry.timestamp = pd.m_timestamp;
495 entry.amount = pd.m_amount;
496 entry.amounts = pd.m_amounts;
497 entry.unlock_time = pd.m_unlock_time;
498 entry.locked = !m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height);
499 entry.fee = pd.m_fee;
500 entry.note = m_wallet->get_tx_note(pd.m_tx_hash);
501 entry.type = pd.m_coinbase ? "block" : "in";
502 entry.subaddr_index = pd.m_subaddr_index;
503 entry.subaddr_indices.push_back(pd.m_subaddr_index);
504 entry.address = m_wallet->get_subaddress_as_str(pd.m_subaddr_index);
505 set_confirmations(entry, m_wallet->get_blockchain_current_height(), m_wallet->get_last_block_reward(), pd.m_unlock_time);
506 }
507 //------------------------------------------------------------------------------------------------------------------------------
508 void wallet_rpc_server::fill_transfer_entry(tools::wallet_rpc::transfer_entry &entry, const crypto::hash &txid, const tools::wallet2::confirmed_transfer_details &pd)
509 {
510 entry.txid = string_tools::pod_to_hex(txid);
511 entry.payment_id = string_tools::pod_to_hex(pd.m_payment_id);
512 if (entry.payment_id.substr(16).find_first_not_of('0') == std::string::npos)
513 entry.payment_id = entry.payment_id.substr(0,16);
514 entry.height = pd.m_block_height;
515 entry.timestamp = pd.m_timestamp;
516 entry.unlock_time = pd.m_unlock_time;
517 entry.locked = !m_wallet->is_transfer_unlocked(pd.m_unlock_time, pd.m_block_height);
518 entry.fee = pd.m_amount_in - pd.m_amount_out;
519 uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
520 entry.amount = pd.m_amount_in - change - entry.fee;
521 entry.note = m_wallet->get_tx_note(txid);
522
523 for (const auto &d: pd.m_dests) {
524 entry.destinations.push_back(wallet_rpc::transfer_destination());
525 wallet_rpc::transfer_destination &td = entry.destinations.back();
526 td.amount = d.amount;
527 td.address = d.address(m_wallet->nettype(), pd.m_payment_id);
528 }
529
530 entry.type = "out";
531 entry.subaddr_index = { pd.m_subaddr_account, 0 };
532 for (uint32_t i: pd.m_subaddr_indices)
533 entry.subaddr_indices.push_back({pd.m_subaddr_account, i});
534 entry.address = m_wallet->get_subaddress_as_str({pd.m_subaddr_account, 0});
535 set_confirmations(entry, m_wallet->get_blockchain_current_height(), m_wallet->get_last_block_reward(), pd.m_unlock_time);
536 }
537 //------------------------------------------------------------------------------------------------------------------------------
538 void wallet_rpc_server::fill_transfer_entry(tools::wallet_rpc::transfer_entry &entry, const crypto::hash &txid, const tools::wallet2::unconfirmed_transfer_details &pd)
539 {
540 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
541 entry.txid = string_tools::pod_to_hex(txid);
542 entry.payment_id = string_tools::pod_to_hex(pd.m_payment_id);
543 entry.payment_id = string_tools::pod_to_hex(pd.m_payment_id);
544 if (entry.payment_id.substr(16).find_first_not_of('0') == std::string::npos)
545 entry.payment_id = entry.payment_id.substr(0,16);
546 entry.height = 0;
547 entry.timestamp = pd.m_timestamp;
548 entry.fee = pd.m_amount_in - pd.m_amount_out;
549 entry.amount = pd.m_amount_in - pd.m_change - entry.fee;
550 entry.unlock_time = pd.m_tx.unlock_time;
551 entry.locked = true;
552 entry.note = m_wallet->get_tx_note(txid);
553
554 for (const auto &d: pd.m_dests) {
555 entry.destinations.push_back(wallet_rpc::transfer_destination());
556 wallet_rpc::transfer_destination &td = entry.destinations.back();
557 td.amount = d.amount;
558 td.address = d.address(m_wallet->nettype(), pd.m_payment_id);
559 }
560
561 entry.type = is_failed ? "failed" : "pending";
562 entry.subaddr_index = { pd.m_subaddr_account, 0 };
563 for (uint32_t i: pd.m_subaddr_indices)
564 entry.subaddr_indices.push_back({pd.m_subaddr_account, i});
565 entry.address = m_wallet->get_subaddress_as_str({pd.m_subaddr_account, 0});
566 set_confirmations(entry, m_wallet->get_blockchain_current_height(), m_wallet->get_last_block_reward(), pd.m_tx.unlock_time);
567 }
568 //------------------------------------------------------------------------------------------------------------------------------
569 void wallet_rpc_server::fill_transfer_entry(tools::wallet_rpc::transfer_entry &entry, const crypto::hash &payment_id, const tools::wallet2::pool_payment_details &ppd)
570 {
571 const tools::wallet2::payment_details &pd = ppd.m_pd;
572 entry.txid = string_tools::pod_to_hex(pd.m_tx_hash);
573 entry.payment_id = string_tools::pod_to_hex(payment_id);
574 if (entry.payment_id.substr(16).find_first_not_of('0') == std::string::npos)
575 entry.payment_id = entry.payment_id.substr(0,16);
576 entry.height = 0;
577 entry.timestamp = pd.m_timestamp;
578 entry.amount = pd.m_amount;
579 entry.amounts = pd.m_amounts;
580 entry.unlock_time = pd.m_unlock_time;
581 entry.locked = true;
582 entry.fee = pd.m_fee;
583 entry.note = m_wallet->get_tx_note(pd.m_tx_hash);
584 entry.double_spend_seen = ppd.m_double_spend_seen;
585 entry.type = "pool";
586 entry.subaddr_index = pd.m_subaddr_index;
587 entry.subaddr_indices.push_back(pd.m_subaddr_index);
588 entry.address = m_wallet->get_subaddress_as_str(pd.m_subaddr_index);
589 set_confirmations(entry, m_wallet->get_blockchain_current_height(), m_wallet->get_last_block_reward(), pd.m_unlock_time);
590 }
591 //------------------------------------------------------------------------------------------------------------------------------
592 bool wallet_rpc_server::on_getbalance(const wallet_rpc::COMMAND_RPC_GET_BALANCE::request& req, wallet_rpc::COMMAND_RPC_GET_BALANCE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
593 {
594 if (!m_wallet) return not_open(er);
595 try
596 {
597 res.balance = req.all_accounts ? m_wallet->balance_all(req.strict) : m_wallet->balance(req.account_index, req.strict);
598 res.unlocked_balance = req.all_accounts ? m_wallet->unlocked_balance_all(req.strict, &res.blocks_to_unlock, &res.time_to_unlock) : m_wallet->unlocked_balance(req.account_index, req.strict, &res.blocks_to_unlock, &res.time_to_unlock);
599 res.multisig_import_needed = m_wallet->multisig() && m_wallet->has_multisig_partial_key_images();
600 std::map<uint32_t, std::map<uint32_t, uint64_t>> balance_per_subaddress_per_account;
601 std::map<uint32_t, std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>>> unlocked_balance_per_subaddress_per_account;
602 if (req.all_accounts)
603 {
604 for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
605 {
606 balance_per_subaddress_per_account[account_index] = m_wallet->balance_per_subaddress(account_index, req.strict);
607 unlocked_balance_per_subaddress_per_account[account_index] = m_wallet->unlocked_balance_per_subaddress(account_index, req.strict);
608 }
609 }
610 else
611 {
612 balance_per_subaddress_per_account[req.account_index] = m_wallet->balance_per_subaddress(req.account_index, req.strict);
613 unlocked_balance_per_subaddress_per_account[req.account_index] = m_wallet->unlocked_balance_per_subaddress(req.account_index, req.strict);
614 }
615 std::vector<tools::wallet2::transfer_details> transfers;
616 m_wallet->get_transfers(transfers);
617 for (const auto& p : balance_per_subaddress_per_account)
618 {
619 uint32_t account_index = p.first;
620 std::map<uint32_t, uint64_t> balance_per_subaddress = p.second;
621 std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>> unlocked_balance_per_subaddress = unlocked_balance_per_subaddress_per_account[account_index];
622 std::set<uint32_t> address_indices;
623 if (!req.all_accounts && !req.address_indices.empty())
624 {
625 address_indices = req.address_indices;
626 }
627 else
628 {
629 for (const auto& i : balance_per_subaddress)
630 address_indices.insert(i.first);
631 }
632 for (uint32_t i : address_indices)
633 {
634 wallet_rpc::COMMAND_RPC_GET_BALANCE::per_subaddress_info info;
635 info.account_index = account_index;
636 info.address_index = i;
637 cryptonote::subaddress_index index = {info.account_index, info.address_index};
638 info.address = m_wallet->get_subaddress_as_str(index);
639 info.balance = balance_per_subaddress[i];
640 info.unlocked_balance = unlocked_balance_per_subaddress[i].first;
641 info.blocks_to_unlock = unlocked_balance_per_subaddress[i].second.first;
642 info.time_to_unlock = unlocked_balance_per_subaddress[i].second.second;
643 info.label = m_wallet->get_subaddress_label(index);
644 info.num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&](const tools::wallet2::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == index; });
645 res.per_subaddress.emplace_back(std::move(info));
646 }
647 }
648 }
649 catch (const std::exception& e)
650 {
651 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
652 return false;
653 }
654 return true;
655 }
656 //------------------------------------------------------------------------------------------------------------------------------
657 bool wallet_rpc_server::on_getaddress(const wallet_rpc::COMMAND_RPC_GET_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_GET_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
658 {
659 if (!m_wallet) return not_open(er);
660 try
661 {
662 THROW_WALLET_EXCEPTION_IF(req.account_index >= m_wallet->get_num_subaddress_accounts(), error::account_index_outofbound);
663 res.addresses.clear();
664 std::vector<uint32_t> req_address_index;
665 if (req.address_index.empty())
666 {
667 for (uint32_t i = 0; i < m_wallet->get_num_subaddresses(req.account_index); ++i)
668 req_address_index.push_back(i);
669 }
670 else
671 {
672 req_address_index = req.address_index;
673 }
674 tools::wallet2::transfer_container transfers;
675 m_wallet->get_transfers(transfers);
676 for (uint32_t i : req_address_index)
677 {
678 THROW_WALLET_EXCEPTION_IF(i >= m_wallet->get_num_subaddresses(req.account_index), error::address_index_outofbound);
679 res.addresses.resize(res.addresses.size() + 1);
680 auto& info = res.addresses.back();
681 const cryptonote::subaddress_index index = {req.account_index, i};
682 info.address = m_wallet->get_subaddress_as_str(index);
683 info.label = m_wallet->get_subaddress_label(index);
684 info.address_index = index.minor;
685 info.used = std::find_if(transfers.begin(), transfers.end(), [&](const tools::wallet2::transfer_details& td) { return td.m_subaddr_index == index; }) != transfers.end();
686 }
687 res.address = m_wallet->get_subaddress_as_str({req.account_index, 0});
688 }
689 catch (const std::exception& e)
690 {
691 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
692 return false;
693 }
694 return true;
695 }
696 //------------------------------------------------------------------------------------------------------------------------------
697 bool wallet_rpc_server::on_getaddress_index(const wallet_rpc::COMMAND_RPC_GET_ADDRESS_INDEX::request& req, wallet_rpc::COMMAND_RPC_GET_ADDRESS_INDEX::response& res, epee::json_rpc::error& er, const connection_context *ctx)
698 {
699 if (!m_wallet) return not_open(er);
700 cryptonote::address_parse_info info;
701 if(!get_account_address_from_str(info, m_wallet->nettype(), req.address))
702 {
703 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
704 er.message = "Invalid address";
705 return false;
706 }
707 auto index = m_wallet->get_subaddress_index(info.address);
708 if (!index)
709 {
710 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
711 er.message = "Address doesn't belong to the wallet";
712 return false;
713 }
714 res.index = *index;
715 return true;
716 }
717 bool wallet_rpc_server::on_set_subaddr_lookahead(const wallet_rpc::COMMAND_RPC_SET_SUBADDR_LOOKAHEAD::request& req, wallet_rpc::COMMAND_RPC_SET_SUBADDR_LOOKAHEAD::response& res, epee::json_rpc::error& er, const connection_context *ctx)
718 {
719 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
720 const std::string wallet_file = m_wallet->get_wallet_file();
721 if (wallet_file == "" || m_wallet->verify_password(req.password))
722 {
723 try
724 {
725 m_wallet->set_subaddress_lookahead(req.major_idx, req.minor_idx);
726 m_wallet->rewrite(wallet_file, req.password);
727 }
728 catch (const std::exception& e) {
729 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
730 return false;
731 }
732 }
733 else
734 {
735 er.code = WALLET_RPC_ERROR_CODE_INVALID_PASSWORD;
736 er.message = "Invalid password.";
737 return false;
738 }
739 return true;
740 }
741 //------------------------------------------------------------------------------------------------------------------------------
742 bool wallet_rpc_server::on_create_address(const wallet_rpc::COMMAND_RPC_CREATE_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_CREATE_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
743 {
744 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
745 try
746 {
747 if (req.count < 1 || req.count > 65536) {
748 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
749 er.message = "Count must be between 1 and 65536.";
750 return false;
751 }
752
753 std::vector<std::string> addresses;
754 std::vector<uint32_t> address_indices;
755
756 addresses.reserve(req.count);
757 address_indices.reserve(req.count);
758
759 for (uint32_t i = 0; i < req.count; i++) {
760 m_wallet->add_subaddress(req.account_index, req.label);
761 uint32_t new_address_index = m_wallet->get_num_subaddresses(req.account_index) - 1;
762 address_indices.push_back(new_address_index);
763 addresses.push_back(m_wallet->get_subaddress_as_str({req.account_index, new_address_index}));
764 }
765
766 res.address = addresses[0];
767 res.address_index = address_indices[0];
768 res.addresses = addresses;
769 res.address_indices = address_indices;
770 }
771 catch (const std::exception& e)
772 {
773 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
774 return false;
775 }
776 return true;
777 }
778 //------------------------------------------------------------------------------------------------------------------------------
779 bool wallet_rpc_server::on_label_address(const wallet_rpc::COMMAND_RPC_LABEL_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_LABEL_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
780 {
781 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
782 try
783 {
784 m_wallet->set_subaddress_label(req.index, req.label);
785 }
786 catch (const std::exception& e)
787 {
788 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
789 return false;
790 }
791 return true;
792 }
793 //------------------------------------------------------------------------------------------------------------------------------
794 bool wallet_rpc_server::on_get_accounts(const wallet_rpc::COMMAND_RPC_GET_ACCOUNTS::request& req, wallet_rpc::COMMAND_RPC_GET_ACCOUNTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
795 {
796 if (!m_wallet) return not_open(er);
797 try
798 {
799 res.total_balance = 0;
800 res.total_unlocked_balance = 0;
801 cryptonote::subaddress_index subaddr_index = {0,0};
802 const std::pair<std::map<std::string, std::string>, std::vector<std::string>> account_tags = m_wallet->get_account_tags();
803 if (!req.tag.empty() && account_tags.first.count(req.tag) == 0 && !req.regexp)
804 {
805 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
806 er.message = (boost::format(tr("Tag %s is unregistered.")) % req.tag).str();
807 return false;
808 }
809 for (; subaddr_index.major < m_wallet->get_num_subaddress_accounts(); ++subaddr_index.major)
810 {
811 bool no_match = !req.regexp ? (!req.tag.empty() && req.tag != account_tags.second[subaddr_index.major])
812 : (!req.tag.empty() && !boost::regex_match(account_tags.second[subaddr_index.major], boost::regex(req.tag)));
813 if (no_match)
814 continue;
815 wallet_rpc::COMMAND_RPC_GET_ACCOUNTS::subaddress_account_info info;
816 info.account_index = subaddr_index.major;
817 info.base_address = m_wallet->get_subaddress_as_str(subaddr_index);
818 info.balance = m_wallet->balance(subaddr_index.major, req.strict_balances);
819 info.unlocked_balance = m_wallet->unlocked_balance(subaddr_index.major, req.strict_balances);
820 info.label = m_wallet->get_subaddress_label(subaddr_index);
821 info.tag = account_tags.second[subaddr_index.major];
822 res.subaddress_accounts.push_back(info);
823 res.total_balance += info.balance;
824 res.total_unlocked_balance += info.unlocked_balance;
825 }
826 if (res.subaddress_accounts.size() == 0 && req.regexp)
827 {
828 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
829 er.message = (boost::format(tr("No matches for regex filter %s .")) % req.tag).str();
830 return false;
831 }
832 }
833 catch (const std::exception& e)
834 {
835 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
836 return false;
837 }
838 return true;
839 }
840 //------------------------------------------------------------------------------------------------------------------------------
841 bool wallet_rpc_server::on_create_account(const wallet_rpc::COMMAND_RPC_CREATE_ACCOUNT::request& req, wallet_rpc::COMMAND_RPC_CREATE_ACCOUNT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
842 {
843 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
844 try
845 {
846 m_wallet->add_subaddress_account(req.label);
847 res.account_index = m_wallet->get_num_subaddress_accounts() - 1;
848 res.address = m_wallet->get_subaddress_as_str({res.account_index, 0});
849 }
850 catch (const std::exception& e)
851 {
852 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
853 return false;
854 }
855 return true;
856 }
857 //------------------------------------------------------------------------------------------------------------------------------
858 bool wallet_rpc_server::on_label_account(const wallet_rpc::COMMAND_RPC_LABEL_ACCOUNT::request& req, wallet_rpc::COMMAND_RPC_LABEL_ACCOUNT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
859 {
860 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
861 try
862 {
863 m_wallet->set_subaddress_label({req.account_index, 0}, req.label);
864 }
865 catch (const std::exception& e)
866 {
867 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
868 return false;
869 }
870 return true;
871 }
872 //------------------------------------------------------------------------------------------------------------------------------
873 bool wallet_rpc_server::on_get_account_tags(const wallet_rpc::COMMAND_RPC_GET_ACCOUNT_TAGS::request& req, wallet_rpc::COMMAND_RPC_GET_ACCOUNT_TAGS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
874 {
875 if (!m_wallet) return not_open(er);
876 CHECK_IF_BACKGROUND_SYNCING();
877 const std::pair<std::map<std::string, std::string>, std::vector<std::string>> account_tags = m_wallet->get_account_tags();
878 for (const std::pair<const std::string, std::string>& p : account_tags.first)
879 {
880 res.account_tags.resize(res.account_tags.size() + 1);
881 auto& info = res.account_tags.back();
882 info.tag = p.first;
883 info.label = p.second;
884 for (size_t i = 0; i < account_tags.second.size(); ++i)
885 {
886 if (account_tags.second[i] == info.tag)
887 info.accounts.push_back(i);
888 }
889 }
890 return true;
891 }
892 //------------------------------------------------------------------------------------------------------------------------------
893 bool wallet_rpc_server::on_tag_accounts(const wallet_rpc::COMMAND_RPC_TAG_ACCOUNTS::request& req, wallet_rpc::COMMAND_RPC_TAG_ACCOUNTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
894 {
895 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
896 try
897 {
898 m_wallet->set_account_tag(req.accounts, req.tag);
899 }
900 catch (const std::exception& e)
901 {
902 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
903 return false;
904 }
905 return true;
906 }
907 //------------------------------------------------------------------------------------------------------------------------------
908 bool wallet_rpc_server::on_untag_accounts(const wallet_rpc::COMMAND_RPC_UNTAG_ACCOUNTS::request& req, wallet_rpc::COMMAND_RPC_UNTAG_ACCOUNTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
909 {
910 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
911 try
912 {
913 m_wallet->set_account_tag(req.accounts, "");
914 }
915 catch (const std::exception& e)
916 {
917 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
918 return false;
919 }
920 return true;
921 }
922 //------------------------------------------------------------------------------------------------------------------------------
923 bool wallet_rpc_server::on_set_account_tag_description(const wallet_rpc::COMMAND_RPC_SET_ACCOUNT_TAG_DESCRIPTION::request& req, wallet_rpc::COMMAND_RPC_SET_ACCOUNT_TAG_DESCRIPTION::response& res, epee::json_rpc::error& er, const connection_context *ctx)
924 {
925 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
926 try
927 {
928 m_wallet->set_account_tag_description(req.tag, req.description);
929 }
930 catch (const std::exception& e)
931 {
932 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
933 return false;
934 }
935 return true;
936 }
937 //------------------------------------------------------------------------------------------------------------------------------
938 bool wallet_rpc_server::on_getheight(const wallet_rpc::COMMAND_RPC_GET_HEIGHT::request& req, wallet_rpc::COMMAND_RPC_GET_HEIGHT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
939 {
940 if (!m_wallet) return not_open(er);
941 try
942 {
943 res.height = m_wallet->get_blockchain_current_height();
944 }
945 catch (const std::exception& e)
946 {
947 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
948 return false;
949 }
950 return true;
951 }
952 //------------------------------------------------------------------------------------------------------------------------------
953 bool wallet_rpc_server::on_freeze(const wallet_rpc::COMMAND_RPC_FREEZE::request& req, wallet_rpc::COMMAND_RPC_FREEZE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
954 {
955 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
956 try
957 {
958 if (req.key_image.empty())
959 {
960 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
961 er.message = std::string("Must specify key image to freeze");
962 return false;
963 }
964 crypto::key_image ki;
965 if (!epee::string_tools::hex_to_pod(req.key_image, ki))
966 {
967 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY_IMAGE;
968 er.message = "failed to parse key image";
969 return false;
970 }
971 m_wallet->freeze(ki);
972 }
973 catch (const std::exception& e)
974 {
975 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
976 return false;
977 }
978 return true;
979 }
980 //------------------------------------------------------------------------------------------------------------------------------
981 bool wallet_rpc_server::on_thaw(const wallet_rpc::COMMAND_RPC_THAW::request& req, wallet_rpc::COMMAND_RPC_THAW::response& res, epee::json_rpc::error& er, const connection_context *ctx)
982 {
983 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
984 try
985 {
986 if (req.key_image.empty())
987 {
988 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
989 er.message = std::string("Must specify key image to thaw");
990 return false;
991 }
992 crypto::key_image ki;
993 if (!epee::string_tools::hex_to_pod(req.key_image, ki))
994 {
995 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY_IMAGE;
996 er.message = "failed to parse key image";
997 return false;
998 }
999 m_wallet->thaw(ki);
1000 }
1001 catch (const std::exception& e)
1002 {
1003 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
1004 return false;
1005 }
1006 return true;
1007 }
1008 //------------------------------------------------------------------------------------------------------------------------------
1009 bool wallet_rpc_server::on_frozen(const wallet_rpc::COMMAND_RPC_FROZEN::request& req, wallet_rpc::COMMAND_RPC_FROZEN::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1010 {
1011 if (!m_wallet) return not_open(er);
1012 CHECK_IF_BACKGROUND_SYNCING();
1013 try
1014 {
1015 if (req.key_image.empty())
1016 {
1017 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1018 er.message = std::string("Must specify key image to check if frozen");
1019 return false;
1020 }
1021 crypto::key_image ki;
1022 if (!epee::string_tools::hex_to_pod(req.key_image, ki))
1023 {
1024 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY_IMAGE;
1025 er.message = "failed to parse key image";
1026 return false;
1027 }
1028 res.frozen = m_wallet->frozen(ki);
1029 }
1030 catch (const std::exception& e)
1031 {
1032 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
1033 return false;
1034 }
1035 return true;
1036 }
1037 //------------------------------------------------------------------------------------------------------------------------------
1038 bool wallet_rpc_server::validate_transfer(const std::list<wallet_rpc::transfer_destination>& destinations, const std::string& payment_id, std::vector<cryptonote::tx_destination_entry>& dsts, std::vector<uint8_t>& extra, bool at_least_one_destination, epee::json_rpc::error& er)
1039 {
1040 CHECK_IF_BACKGROUND_SYNCING();
1041
1042 crypto::hash8 integrated_payment_id = crypto::null_hash8;
1043 std::string extra_nonce;
1044 for (auto it = destinations.begin(); it != destinations.end(); it++)
1045 {
1046 cryptonote::address_parse_info info;
1047 cryptonote::tx_destination_entry de;
1048 er.message = "";
1049 if(!get_account_address_from_str_or_url(info, m_wallet->nettype(), it->address,
1050 [&er](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)->std::string {
1051 if (!dnssec_valid)
1052 {
1053 er.message = std::string("Invalid DNSSEC for ") + url;
1054 return {};
1055 }
1056 if (addresses.empty())
1057 {
1058 er.message = std::string("No Monero address found at ") + url;
1059 return {};
1060 }
1061 return addresses[0];
1062 }))
1063 {
1064 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
1065 if (er.message.empty())
1066 er.message = std::string("WALLET_RPC_ERROR_CODE_WRONG_ADDRESS: ") + it->address;
1067 return false;
1068 }
1069
1070 de.original = it->address;
1071 de.addr = info.address;
1072 de.is_subaddress = info.is_subaddress;
1073 de.amount = it->amount;
1074 de.is_integrated = info.has_payment_id;
1075 dsts.push_back(de);
1076
1077 if (info.has_payment_id)
1078 {
1079 if (!payment_id.empty() || integrated_payment_id != crypto::null_hash8)
1080 {
1081 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
1082 er.message = "A single payment id is allowed per transaction";
1083 return false;
1084 }
1085 integrated_payment_id = info.payment_id;
1086 cryptonote::set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, integrated_payment_id);
1087
1088 /* Append Payment ID data into extra */
1089 if (!cryptonote::add_extra_nonce_to_tx_extra(extra, extra_nonce)) {
1090 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
1091 er.message = "Something went wrong with integrated payment_id.";
1092 return false;
1093 }
1094 }
1095 }
1096
1097 if (at_least_one_destination && dsts.empty())
1098 {
1099 er.code = WALLET_RPC_ERROR_CODE_ZERO_DESTINATION;
1100 er.message = "Transaction has no destination";
1101 return false;
1102 }
1103
1104 if (!payment_id.empty())
1105 {
1106 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
1107 er.message = "Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead";
1108 return false;
1109 }
1110 return true;
1111 }
1112 //------------------------------------------------------------------------------------------------------------------------------
1113 static std::string ptx_to_string(const tools::wallet2::pending_tx &ptx)
1114 {
1115 std::ostringstream oss;
1116 binary_archive<true> ar(oss);
1117 try
1118 {
1119 if (!::serialization::serialize(ar, const_cast<tools::wallet2::pending_tx&>(ptx)))
1120 return "";
1121 }
1122 catch (...)
1123 {
1124 return "";
1125 }
1126 return epee::string_tools::buff_to_hex_nodelimer(oss.str());
1127 }
1128 //------------------------------------------------------------------------------------------------------------------------------
1129 template<typename T> static bool is_error_value(const T &val) { return false; }
1130 static bool is_error_value(const std::string &s) { return s.empty(); }
1131 //------------------------------------------------------------------------------------------------------------------------------
1132 template<typename T, typename V>
1133 static bool fill(T &where, V s)
1134 {
1135 if (is_error_value(s)) return false;
1136 where = std::move(s);
1137 return true;
1138 }
1139 //------------------------------------------------------------------------------------------------------------------------------
1140 template<typename T, typename V>
1141 static bool fill(std::list<T> &where, V s)
1142 {
1143 if (is_error_value(s)) return false;
1144 where.emplace_back(std::move(s));
1145 return true;
1146 }
1147 //------------------------------------------------------------------------------------------------------------------------------
1148 static uint64_t total_amount(const tools::wallet2::pending_tx &ptx)
1149 {
1150 uint64_t amount = 0;
1151 for (const auto &dest: ptx.dests) amount += dest.amount;
1152 return amount;
1153 }
1154 //------------------------------------------------------------------------------------------------------------------------------
1155 template<typename Ts, typename Tu, typename Tk, typename Ta>
1156 bool wallet_rpc_server::fill_response(std::vector<tools::wallet2::pending_tx> &ptx_vector,
1157 bool get_tx_key, Ts& tx_key, Tu &amount, Ta &amounts_by_dest, Tu &fee, Tu &weight, std::string &multisig_txset, std::string &unsigned_txset, bool do_not_relay,
1158 Ts &tx_hash, bool get_tx_hex, Ts &tx_blob, bool get_tx_metadata, Ts &tx_metadata, Tk &spent_key_images, epee::json_rpc::error &er)
1159 {
1160 for (const auto & ptx : ptx_vector)
1161 {
1162 if (get_tx_key)
1163 {
1164 epee::wipeable_string s = epee::to_hex::wipeable_string(ptx.tx_key);
1165 for (const crypto::secret_key& additional_tx_key : ptx.additional_tx_keys)
1166 s += epee::to_hex::wipeable_string(additional_tx_key);
1167 fill(tx_key, std::string(s.data(), s.size()));
1168 }
1169 // Compute amount leaving wallet in tx. By convention dests does not include change outputs
1170 fill(amount, total_amount(ptx));
1171 fill(fee, ptx.fee);
1172 fill(weight, cryptonote::get_transaction_weight(ptx.tx));
1173
1174 // add amounts by destination
1175 tools::wallet_rpc::amounts_list abd;
1176 for (const auto& dst : ptx.dests)
1177 abd.amounts.push_back(dst.amount);
1178 fill(amounts_by_dest, abd);
1179
1180 // add spent key images
1181 tools::wallet_rpc::key_image_list key_image_list;
1182 bool all_are_txin_to_key = std::all_of(ptx.tx.vin.begin(), ptx.tx.vin.end(), [&](const cryptonote::txin_v& s_e) -> bool
1183 {
1184 CHECKED_GET_SPECIFIC_VARIANT(s_e, const cryptonote::txin_to_key, in, false);
1185 key_image_list.key_images.push_back(epee::string_tools::pod_to_hex(in.k_image));
1186 return true;
1187 });
1188 THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, ptx.tx);
1189 fill(spent_key_images, key_image_list);
1190 }
1191
1192 if (m_wallet->multisig())
1193 {
1194 multisig_txset = epee::string_tools::buff_to_hex_nodelimer(m_wallet->save_multisig_tx(ptx_vector));
1195 if (multisig_txset.empty())
1196 {
1197 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1198 er.message = "Failed to save multisig tx set after creation";
1199 return false;
1200 }
1201 }
1202 else
1203 {
1204 if (m_wallet->watch_only()){
1205 unsigned_txset = epee::string_tools::buff_to_hex_nodelimer(m_wallet->dump_tx_to_str(ptx_vector));
1206 if (unsigned_txset.empty())
1207 {
1208 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1209 er.message = "Failed to save unsigned tx set after creation";
1210 return false;
1211 }
1212 }
1213 else if (!do_not_relay)
1214 m_wallet->commit_tx(ptx_vector);
1215
1216 // populate response with tx hashes
1217 for (auto & ptx : ptx_vector)
1218 {
1219 bool r = fill(tx_hash, epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)));
1220 r = r && (!get_tx_hex || fill(tx_blob, epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(ptx.tx))));
1221 r = r && (!get_tx_metadata || fill(tx_metadata, ptx_to_string(ptx)));
1222 if (!r)
1223 {
1224 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1225 er.message = "Failed to save tx info";
1226 return false;
1227 }
1228 }
1229 }
1230 return true;
1231 }
1232 //------------------------------------------------------------------------------------------------------------------------------
1233 bool wallet_rpc_server::on_transfer(const wallet_rpc::COMMAND_RPC_TRANSFER::request& req, wallet_rpc::COMMAND_RPC_TRANSFER::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1234 {
1235
1236 std::vector<cryptonote::tx_destination_entry> dsts;
1237 std::vector<uint8_t> extra;
1238
1239 LOG_PRINT_L3("on_transfer starts");
1240 if (m_restricted)
1241 {
1242 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1243 er.message = "Command unavailable in restricted mode.";
1244 return false;
1245 }
1246 if (!m_wallet) return not_open(er);
1247 else if (req.unlock_time)
1248 {
1249 er.code = WALLET_RPC_ERROR_CODE_NONZERO_UNLOCK_TIME;
1250 er.message = "Transaction cannot have non-zero unlock time";
1251 return false;
1252 }
1253
1254 CHECK_MULTISIG_ENABLED();
1255
1256 // validate the transfer requested and populate dsts & extra
1257 if (!validate_transfer(req.destinations, req.payment_id, dsts, extra, true, er))
1258 {
1259 return false;
1260 }
1261
1262 try
1263 {
1264 uint64_t mixin = m_wallet->adjust_mixin(req.ring_size ? req.ring_size - 1 : 0);
1265 uint32_t priority = m_wallet->adjust_priority(req.priority);
1266 std::vector<wallet2::pending_tx> ptx_vector = m_wallet->create_transactions_2(dsts, mixin, priority, extra, req.account_index, req.subaddr_indices, req.subtract_fee_from_outputs);
1267
1268 if (ptx_vector.empty())
1269 {
1270 er.code = WALLET_RPC_ERROR_CODE_TX_NOT_POSSIBLE;
1271 er.message = "No transaction created";
1272 return false;
1273 }
1274
1275 // reject proposed transactions if there are more than one. see on_transfer_split below.
1276 if (ptx_vector.size() != 1)
1277 {
1278 er.code = WALLET_RPC_ERROR_CODE_TX_TOO_LARGE;
1279 er.message = "Transaction would be too large. try /transfer_split.";
1280 return false;
1281 }
1282
1283 return fill_response(ptx_vector, req.get_tx_key, res.tx_key, res.amount, res.amounts_by_dest, res.fee, res.weight, res.multisig_txset, res.unsigned_txset, req.do_not_relay,
1284 res.tx_hash, req.get_tx_hex, res.tx_blob, req.get_tx_metadata, res.tx_metadata, res.spent_key_images, er);
1285 }
1286 catch (const std::exception& e)
1287 {
1288 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR);
1289 return false;
1290 }
1291 return true;
1292 }
1293 //------------------------------------------------------------------------------------------------------------------------------
1294 bool wallet_rpc_server::on_transfer_split(const wallet_rpc::COMMAND_RPC_TRANSFER_SPLIT::request& req, wallet_rpc::COMMAND_RPC_TRANSFER_SPLIT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1295 {
1296
1297 std::vector<cryptonote::tx_destination_entry> dsts;
1298 std::vector<uint8_t> extra;
1299
1300 if (m_restricted)
1301 {
1302 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1303 er.message = "Command unavailable in restricted mode.";
1304 return false;
1305 }
1306 if (!m_wallet) return not_open(er);
1307 else if (req.unlock_time)
1308 {
1309 er.code = WALLET_RPC_ERROR_CODE_NONZERO_UNLOCK_TIME;
1310 er.message = "Transaction cannot have non-zero unlock time";
1311 return false;
1312 }
1313
1314 CHECK_MULTISIG_ENABLED();
1315
1316 // validate the transfer requested and populate dsts & extra; RPC_TRANSFER::request and RPC_TRANSFER_SPLIT::request are identical types.
1317 if (!validate_transfer(req.destinations, req.payment_id, dsts, extra, true, er))
1318 {
1319 return false;
1320 }
1321
1322 try
1323 {
1324 uint64_t mixin = m_wallet->adjust_mixin(req.ring_size ? req.ring_size - 1 : 0);
1325 uint32_t priority = m_wallet->adjust_priority(req.priority);
1326 LOG_PRINT_L2("on_transfer_split calling create_transactions_2");
1327 std::vector<wallet2::pending_tx> ptx_vector = m_wallet->create_transactions_2(dsts, mixin, priority, extra, req.account_index, req.subaddr_indices);
1328 LOG_PRINT_L2("on_transfer_split called create_transactions_2");
1329
1330 if (ptx_vector.empty())
1331 {
1332 er.code = WALLET_RPC_ERROR_CODE_TX_NOT_POSSIBLE;
1333 er.message = "No transaction created";
1334 return false;
1335 }
1336
1337 return fill_response(ptx_vector, req.get_tx_keys, res.tx_key_list, res.amount_list, res.amounts_by_dest_list, res.fee_list, res.weight_list, res.multisig_txset, res.unsigned_txset, req.do_not_relay,
1338 res.tx_hash_list, req.get_tx_hex, res.tx_blob_list, req.get_tx_metadata, res.tx_metadata_list, res.spent_key_images_list, er);
1339 }
1340 catch (const std::exception& e)
1341 {
1342 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR);
1343 return false;
1344 }
1345 return true;
1346 }
1347 //------------------------------------------------------------------------------------------------------------------------------
1348 bool wallet_rpc_server::on_sign_transfer(const wallet_rpc::COMMAND_RPC_SIGN_TRANSFER::request& req, wallet_rpc::COMMAND_RPC_SIGN_TRANSFER::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1349 {
1350 if (m_restricted)
1351 {
1352 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1353 er.message = "Command unavailable in restricted mode.";
1354 return false;
1355 }
1356 if (!m_wallet) return not_open(er);
1357 if (m_wallet->key_on_device())
1358 {
1359 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1360 er.message = "command not supported by HW wallet";
1361 return false;
1362 }
1363 if(m_wallet->watch_only())
1364 {
1365 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
1366 er.message = "command not supported by watch-only wallet";
1367 return false;
1368 }
1369
1370 CHECK_MULTISIG_ENABLED();
1371 CHECK_IF_BACKGROUND_SYNCING();
1372
1373 cryptonote::blobdata blob;
1374 if (!epee::string_tools::parse_hexstr_to_binbuff(req.unsigned_txset, blob))
1375 {
1376 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
1377 er.message = "Failed to parse hex.";
1378 return false;
1379 }
1380
1381 tools::wallet2::unsigned_tx_set exported_txs;
1382 if(!m_wallet->parse_unsigned_tx_from_str(blob, exported_txs))
1383 {
1384 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1385 er.message = "cannot load unsigned_txset";
1386 return false;
1387 }
1388
1389 std::vector<tools::wallet2::pending_tx> ptxs;
1390 try
1391 {
1392 tools::wallet2::signed_tx_set signed_txs;
1393 std::string ciphertext = m_wallet->sign_tx_dump_to_str(exported_txs, ptxs, signed_txs);
1394 if (ciphertext.empty())
1395 {
1396 er.code = WALLET_RPC_ERROR_CODE_SIGN_UNSIGNED;
1397 er.message = "Failed to sign unsigned tx";
1398 return false;
1399 }
1400
1401 res.signed_txset = epee::string_tools::buff_to_hex_nodelimer(ciphertext);
1402 }
1403 catch (const std::exception &e)
1404 {
1405 er.code = WALLET_RPC_ERROR_CODE_SIGN_UNSIGNED;
1406 er.message = std::string("Failed to sign unsigned tx: ") + e.what();
1407 return false;
1408 }
1409
1410 for (auto &ptx: ptxs)
1411 {
1412 res.tx_hash_list.push_back(epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)));
1413 if (req.get_tx_keys)
1414 {
1415 res.tx_key_list.push_back(epee::string_tools::pod_to_hex(unwrap(unwrap(ptx.tx_key))));
1416 for (const crypto::secret_key& additional_tx_key : ptx.additional_tx_keys)
1417 res.tx_key_list.back() += epee::string_tools::pod_to_hex(unwrap(unwrap(additional_tx_key)));
1418 }
1419 }
1420
1421 if (req.export_raw)
1422 {
1423 for (auto &ptx: ptxs)
1424 {
1425 res.tx_raw_list.push_back(epee::string_tools::buff_to_hex_nodelimer(cryptonote::tx_to_blob(ptx.tx)));
1426 }
1427 }
1428
1429 return true;
1430 }
1431 //------------------------------------------------------------------------------------------------------------------------------
1432 bool wallet_rpc_server::on_describe_transfer(const wallet_rpc::COMMAND_RPC_DESCRIBE_TRANSFER::request& req, wallet_rpc::COMMAND_RPC_DESCRIBE_TRANSFER::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1433 {
1434 if (m_restricted)
1435 {
1436 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1437 er.message = "Command unavailable in restricted mode.";
1438 return false;
1439 }
1440 if (!m_wallet) return not_open(er);
1441 if (m_wallet->key_on_device())
1442 {
1443 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1444 er.message = "command not supported by HW wallet";
1445 return false;
1446 }
1447 if(m_wallet->watch_only())
1448 {
1449 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
1450 er.message = "command not supported by watch-only wallet";
1451 return false;
1452 }
1453 CHECK_IF_BACKGROUND_SYNCING();
1454 if(req.unsigned_txset.empty() && req.multisig_txset.empty())
1455 {
1456 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1457 er.message = "no txset provided";
1458 return false;
1459 }
1460
1461 std::vector <wallet2::tx_construction_data> tx_constructions;
1462 if (!req.unsigned_txset.empty()) {
1463 try {
1464 tools::wallet2::unsigned_tx_set exported_txs;
1465 cryptonote::blobdata blob;
1466 if (!epee::string_tools::parse_hexstr_to_binbuff(req.unsigned_txset, blob)) {
1467 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
1468 er.message = "Failed to parse hex.";
1469 return false;
1470 }
1471 if (!m_wallet->parse_unsigned_tx_from_str(blob, exported_txs)) {
1472 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1473 er.message = "cannot load unsigned_txset";
1474 return false;
1475 }
1476 tx_constructions = exported_txs.txes;
1477 }
1478 catch (const std::exception &e) {
1479 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1480 er.message = "failed to parse unsigned transfers: " + std::string(e.what());
1481 return false;
1482 }
1483 } else if (!req.multisig_txset.empty()) {
1484 try {
1485 tools::wallet2::multisig_tx_set exported_txs;
1486 cryptonote::blobdata blob;
1487 if (!epee::string_tools::parse_hexstr_to_binbuff(req.multisig_txset, blob)) {
1488 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
1489 er.message = "Failed to parse hex.";
1490 return false;
1491 }
1492 if (!m_wallet->parse_multisig_tx_from_str(blob, exported_txs)) {
1493 er.code = WALLET_RPC_ERROR_CODE_BAD_MULTISIG_TX_DATA;
1494 er.message = "cannot load multisig_txset";
1495 return false;
1496 }
1497
1498 for (size_t n = 0; n < exported_txs.m_ptx.size(); ++n) {
1499 tx_constructions.push_back(exported_txs.m_ptx[n].construction_data);
1500 }
1501 }
1502 catch (const std::exception &e) {
1503 er.code = WALLET_RPC_ERROR_CODE_BAD_MULTISIG_TX_DATA;
1504 er.message = "failed to parse multisig transfers: " + std::string(e.what());
1505 return false;
1506 }
1507 }
1508
1509 try
1510 {
1511 // gather info to ask the user
1512 std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> tx_dests;
1513 std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> all_dests;
1514 int first_known_non_zero_change_index = -1;
1515 res.summary.amount_in = 0;
1516 res.summary.amount_out = 0;
1517 res.summary.change_amount = 0;
1518 res.summary.fee = 0;
1519 for (size_t n = 0; n < tx_constructions.size(); ++n)
1520 {
1521 const tools::wallet2::tx_construction_data &cd = tx_constructions[n];
1522 res.desc.push_back({0, 0, std::numeric_limits<uint32_t>::max(), 0, {}, {}, "", 0, "", 0, 0, ""});
1523 wallet_rpc::COMMAND_RPC_DESCRIBE_TRANSFER::transfer_description &desc = res.desc.back();
1524 // Clear the recipients collection ready for this loop iteration
1525 tx_dests.clear();
1526
1527 std::vector<cryptonote::tx_extra_field> tx_extra_fields;
1528 bool has_encrypted_payment_id = false;
1529 crypto::hash8 payment_id8 = crypto::null_hash8;
1530 if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields))
1531 {
1532 cryptonote::tx_extra_nonce extra_nonce;
1533 if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
1534 {
1535 crypto::hash payment_id;
1536 if(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
1537 {
1538 if (payment_id8 != crypto::null_hash8)
1539 {
1540 desc.payment_id = epee::string_tools::pod_to_hex(payment_id8);
1541 has_encrypted_payment_id = true;
1542 }
1543 }
1544 else if (cryptonote::get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
1545 {
1546 desc.payment_id = epee::string_tools::pod_to_hex(payment_id);
1547 }
1548 }
1549 }
1550
1551 for (size_t s = 0; s < cd.sources.size(); ++s)
1552 {
1553 const cryptonote::tx_source_entry &src_in = cd.sources[s];
1554 desc.sources.emplace_back();
1555 wallet_rpc::COMMAND_RPC_DESCRIBE_TRANSFER::source &src_out = desc.sources.back();
1556 src_out.amount = src_in.amount;
1557 src_out.global_index = src_in.outputs.at(src_in.real_output_in_tx_index).first;
1558 src_out.rct = src_in.rct;
1559 src_out.pubkey = epee::string_tools::pod_to_hex(src_in.outputs.at(src_in.real_output_in_tx_index).second);
1560 desc.amount_in += src_in.amount;
1561 size_t ring_size = src_in.outputs.size();
1562 if (ring_size < desc.ring_size)
1563 desc.ring_size = ring_size;
1564 }
1565 for (size_t d = 0; d < cd.splitted_dsts.size(); ++d)
1566 {
1567 const cryptonote::tx_destination_entry &entry = cd.splitted_dsts[d];
1568 std::string address = cryptonote::get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr);
1569 if (has_encrypted_payment_id && !entry.is_subaddress && address != entry.original)
1570 address = cryptonote::get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8);
1571 auto i = tx_dests.find(entry.addr);
1572 if (i == tx_dests.end())
1573 tx_dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount)));
1574 else
1575 i->second.second += entry.amount;
1576 desc.amount_out += entry.amount;
1577 }
1578 if (cd.change_dts.amount > 0)
1579 {
1580 auto it = tx_dests.find(cd.change_dts.addr);
1581 if (it == tx_dests.end())
1582 {
1583 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1584 er.message = "Claimed change does not go to a paid address";
1585 return false;
1586 }
1587 if (it->second.second < cd.change_dts.amount)
1588 {
1589 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1590 er.message = "Claimed change is larger than payment to the change address";
1591 return false;
1592 }
1593 if (cd.change_dts.amount > 0)
1594 {
1595 if (first_known_non_zero_change_index == -1)
1596 first_known_non_zero_change_index = n;
1597 const tools::wallet2::tx_construction_data &cdn = tx_constructions[first_known_non_zero_change_index];
1598 if (memcmp(&cd.change_dts.addr, &cdn.change_dts.addr, sizeof(cd.change_dts.addr)))
1599 {
1600 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1601 er.message = "Change goes to more than one address";
1602 return false;
1603 }
1604 }
1605 desc.change_amount += cd.change_dts.amount;
1606 it->second.second -= cd.change_dts.amount;
1607 if (it->second.second == 0)
1608 tx_dests.erase(cd.change_dts.addr);
1609 }
1610
1611 for (auto i = tx_dests.begin(); i != tx_dests.end(); ++i)
1612 {
1613 if (i->second.second > 0)
1614 {
1615 desc.recipients.push_back({i->second.first, i->second.second});
1616 auto it_in_all = all_dests.find(i->first);
1617 if (it_in_all == all_dests.end())
1618 all_dests.insert(std::make_pair(i->first, i->second));
1619 else
1620 it_in_all->second.second += i->second.second;
1621 }
1622 else
1623 ++desc.dummy_outputs;
1624 }
1625
1626 if (desc.change_amount > 0)
1627 {
1628 const tools::wallet2::tx_construction_data &cd0 = tx_constructions[0];
1629 desc.change_address = get_account_address_as_str(m_wallet->nettype(), cd0.subaddr_account > 0, cd0.change_dts.addr);
1630 res.summary.change_address = desc.change_address;
1631 }
1632
1633 desc.fee = desc.amount_in - desc.amount_out;
1634 desc.unlock_time = cd.unlock_time;
1635 desc.extra = epee::to_hex::string({cd.extra.data(), cd.extra.size()});
1636
1637 // Update summary items
1638 res.summary.amount_in += desc.amount_in;
1639 res.summary.amount_out += desc.amount_out;
1640 res.summary.change_amount += desc.change_amount;
1641 res.summary.fee += desc.fee;
1642 }
1643 // Populate the summary recipients list
1644 for (auto i = all_dests.begin(); i != all_dests.end(); ++i)
1645 {
1646 res.summary.recipients.push_back({i->second.first, i->second.second});
1647 }
1648 }
1649 catch (const std::exception &e)
1650 {
1651 er.code = WALLET_RPC_ERROR_CODE_BAD_UNSIGNED_TX_DATA;
1652 er.message = "failed to parse unsigned transfers";
1653 return false;
1654 }
1655
1656 return true;
1657 }
1658 //------------------------------------------------------------------------------------------------------------------------------
1659 bool wallet_rpc_server::on_submit_transfer(const wallet_rpc::COMMAND_RPC_SUBMIT_TRANSFER::request& req, wallet_rpc::COMMAND_RPC_SUBMIT_TRANSFER::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1660 {
1661 if (m_restricted)
1662 {
1663 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1664 er.message = "Command unavailable in restricted mode.";
1665 return false;
1666 }
1667 if (!m_wallet) return not_open(er);
1668 if (m_wallet->key_on_device())
1669 {
1670 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1671 er.message = "command not supported by HW wallet";
1672 return false;
1673 }
1674
1675 cryptonote::blobdata blob;
1676 if (!epee::string_tools::parse_hexstr_to_binbuff(req.tx_data_hex, blob))
1677 {
1678 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
1679 er.message = "Failed to parse hex.";
1680 return false;
1681 }
1682
1683 std::vector<tools::wallet2::pending_tx> ptx_vector;
1684 try
1685 {
1686 bool r = m_wallet->parse_tx_from_str(blob, ptx_vector, NULL);
1687 if (!r)
1688 {
1689 er.code = WALLET_RPC_ERROR_CODE_BAD_SIGNED_TX_DATA;
1690 er.message = "Failed to parse signed tx data.";
1691 return false;
1692 }
1693 }
1694 catch (const std::exception &e)
1695 {
1696 er.code = WALLET_RPC_ERROR_CODE_BAD_SIGNED_TX_DATA;
1697 er.message = std::string("Failed to parse signed tx: ") + e.what();
1698 return false;
1699 }
1700
1701 try
1702 {
1703 for (auto &ptx: ptx_vector)
1704 {
1705 m_wallet->commit_tx(ptx);
1706 res.tx_hash_list.push_back(epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)));
1707 }
1708 }
1709 catch (const std::exception &e)
1710 {
1711 er.code = WALLET_RPC_ERROR_CODE_SIGNED_SUBMISSION;
1712 er.message = std::string("Failed to submit signed tx: ") + e.what();
1713 return false;
1714 }
1715
1716 return true;
1717 }
1718 //------------------------------------------------------------------------------------------------------------------------------
1719 bool wallet_rpc_server::on_sweep_dust(const wallet_rpc::COMMAND_RPC_SWEEP_DUST::request& req, wallet_rpc::COMMAND_RPC_SWEEP_DUST::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1720 {
1721 if (m_restricted)
1722 {
1723 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1724 er.message = "Command unavailable in restricted mode.";
1725 return false;
1726 }
1727 if (!m_wallet) return not_open(er);
1728
1729 CHECK_MULTISIG_ENABLED();
1730 CHECK_IF_BACKGROUND_SYNCING();
1731
1732 try
1733 {
1734 std::vector<wallet2::pending_tx> ptx_vector = m_wallet->create_unmixable_sweep_transactions();
1735
1736 return fill_response(ptx_vector, req.get_tx_keys, res.tx_key_list, res.amount_list, res.amounts_by_dest_list, res.fee_list, res.weight_list, res.multisig_txset, res.unsigned_txset, req.do_not_relay,
1737 res.tx_hash_list, req.get_tx_hex, res.tx_blob_list, req.get_tx_metadata, res.tx_metadata_list, res.spent_key_images_list, er);
1738 }
1739 catch (const std::exception& e)
1740 {
1741 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR);
1742 return false;
1743 }
1744 return true;
1745 }
1746 //------------------------------------------------------------------------------------------------------------------------------
1747 bool wallet_rpc_server::on_sweep_all(const wallet_rpc::COMMAND_RPC_SWEEP_ALL::request& req, wallet_rpc::COMMAND_RPC_SWEEP_ALL::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1748 {
1749 std::vector<cryptonote::tx_destination_entry> dsts;
1750 std::vector<uint8_t> extra;
1751
1752 if (m_restricted)
1753 {
1754 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1755 er.message = "Command unavailable in restricted mode.";
1756 return false;
1757 }
1758 if (!m_wallet) return not_open(er);
1759 else if (req.unlock_time)
1760 {
1761 er.code = WALLET_RPC_ERROR_CODE_NONZERO_UNLOCK_TIME;
1762 er.message = "Transaction cannot have non-zero unlock time";
1763 return false;
1764 }
1765
1766 CHECK_MULTISIG_ENABLED();
1767
1768 // validate the transfer requested and populate dsts & extra
1769 std::list<wallet_rpc::transfer_destination> destination;
1770 destination.push_back(wallet_rpc::transfer_destination());
1771 destination.back().amount = 0;
1772 destination.back().address = req.address;
1773 if (!validate_transfer(destination, req.payment_id, dsts, extra, true, er))
1774 {
1775 return false;
1776 }
1777
1778 if (req.outputs < 1)
1779 {
1780 er.code = WALLET_RPC_ERROR_CODE_TX_NOT_POSSIBLE;
1781 er.message = "Amount of outputs should be greater than 0.";
1782 return false;
1783 }
1784
1785 std::set<uint32_t> subaddr_indices;
1786 if (req.subaddr_indices_all)
1787 {
1788 for (uint32_t i = 0; i < m_wallet->get_num_subaddresses(req.account_index); ++i)
1789 subaddr_indices.insert(i);
1790 }
1791 else
1792 {
1793 subaddr_indices= req.subaddr_indices;
1794 }
1795
1796 try
1797 {
1798 uint64_t mixin = m_wallet->adjust_mixin(req.ring_size ? req.ring_size - 1 : 0);
1799 uint32_t priority = m_wallet->adjust_priority(req.priority);
1800 std::vector<wallet2::pending_tx> ptx_vector = m_wallet->create_transactions_all(req.below_amount, dsts[0].addr, dsts[0].is_subaddress, req.outputs, mixin, priority, extra, req.account_index, subaddr_indices);
1801
1802 return fill_response(ptx_vector, req.get_tx_keys, res.tx_key_list, res.amount_list, res.amounts_by_dest_list, res.fee_list, res.weight_list, res.multisig_txset, res.unsigned_txset, req.do_not_relay,
1803 res.tx_hash_list, req.get_tx_hex, res.tx_blob_list, req.get_tx_metadata, res.tx_metadata_list, res.spent_key_images_list, er);
1804 }
1805 catch (const std::exception& e)
1806 {
1807 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR);
1808 return false;
1809 }
1810 return true;
1811 }
1812 //------------------------------------------------------------------------------------------------------------------------------
1813 bool wallet_rpc_server::on_sweep_single(const wallet_rpc::COMMAND_RPC_SWEEP_SINGLE::request& req, wallet_rpc::COMMAND_RPC_SWEEP_SINGLE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1814 {
1815 std::vector<cryptonote::tx_destination_entry> dsts;
1816 std::vector<uint8_t> extra;
1817
1818 if (m_restricted)
1819 {
1820 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1821 er.message = "Command unavailable in restricted mode.";
1822 return false;
1823 }
1824 if (!m_wallet) return not_open(er);
1825 else if (req.unlock_time)
1826 {
1827 er.code = WALLET_RPC_ERROR_CODE_NONZERO_UNLOCK_TIME;
1828 er.message = "Transaction cannot have non-zero unlock time";
1829 return false;
1830 }
1831
1832 if (req.outputs < 1)
1833 {
1834 er.code = WALLET_RPC_ERROR_CODE_TX_NOT_POSSIBLE;
1835 er.message = "Amount of outputs should be greater than 0.";
1836 return false;
1837 }
1838
1839 CHECK_MULTISIG_ENABLED();
1840
1841 // validate the transfer requested and populate dsts & extra
1842 std::list<wallet_rpc::transfer_destination> destination;
1843 destination.push_back(wallet_rpc::transfer_destination());
1844 destination.back().amount = 0;
1845 destination.back().address = req.address;
1846 if (!validate_transfer(destination, req.payment_id, dsts, extra, true, er))
1847 {
1848 return false;
1849 }
1850
1851 crypto::key_image ki;
1852 if (!epee::string_tools::hex_to_pod(req.key_image, ki))
1853 {
1854 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY_IMAGE;
1855 er.message = "failed to parse key image";
1856 return false;
1857 }
1858
1859 try
1860 {
1861 uint64_t mixin = m_wallet->adjust_mixin(req.ring_size ? req.ring_size - 1 : 0);
1862 uint32_t priority = m_wallet->adjust_priority(req.priority);
1863 std::vector<wallet2::pending_tx> ptx_vector = m_wallet->create_transactions_single(ki, dsts[0].addr, dsts[0].is_subaddress, req.outputs, mixin, priority, extra);
1864
1865 if (ptx_vector.empty())
1866 {
1867 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1868 er.message = "No outputs found";
1869 return false;
1870 }
1871 if (ptx_vector.size() > 1)
1872 {
1873 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1874 er.message = "Multiple transactions are created, which is not supposed to happen";
1875 return false;
1876 }
1877 const wallet2::pending_tx &ptx = ptx_vector[0];
1878 if (ptx.selected_transfers.size() > 1)
1879 {
1880 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1881 er.message = "The transaction uses multiple inputs, which is not supposed to happen";
1882 return false;
1883 }
1884
1885 return fill_response(ptx_vector, req.get_tx_key, res.tx_key, res.amount, res.amounts_by_dest, res.fee, res.weight, res.multisig_txset, res.unsigned_txset, req.do_not_relay,
1886 res.tx_hash, req.get_tx_hex, res.tx_blob, req.get_tx_metadata, res.tx_metadata, res.spent_key_images, er);
1887 }
1888 catch (const std::exception& e)
1889 {
1890 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR);
1891 return false;
1892 }
1893 catch (...)
1894 {
1895 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
1896 er.message = "WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR";
1897 return false;
1898 }
1899 return true;
1900 }
1901 //------------------------------------------------------------------------------------------------------------------------------
1902 bool wallet_rpc_server::on_relay_tx(const wallet_rpc::COMMAND_RPC_RELAY_TX::request& req, wallet_rpc::COMMAND_RPC_RELAY_TX::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1903 {
1904 if (m_restricted)
1905 {
1906 er.code = WALLET_RPC_ERROR_CODE_DENIED;
1907 er.message = "Command unavailable in restricted mode.";
1908 return false;
1909 }
1910
1911 if (!m_wallet) return not_open(er);
1912
1913 cryptonote::blobdata blob;
1914 if (!epee::string_tools::parse_hexstr_to_binbuff(req.hex, blob))
1915 {
1916 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
1917 er.message = "Failed to parse hex.";
1918 return false;
1919 }
1920
1921 bool loaded = false;
1922 tools::wallet2::pending_tx ptx;
1923
1924 try
1925 {
1926 binary_archive<false> ar{epee::strspan<std::uint8_t>(blob)};
1927 if (::serialization::serialize(ar, ptx))
1928 loaded = true;
1929 }
1930 catch(...) {}
1931
1932 if (!loaded && !m_restricted)
1933 {
1934 try
1935 {
1936 std::istringstream iss(blob);
1937 boost::archive::portable_binary_iarchive ar(iss);
1938 ar >> ptx;
1939 loaded = true;
1940 }
1941 catch (...) {}
1942 }
1943
1944 if (!loaded)
1945 {
1946 er.code = WALLET_RPC_ERROR_CODE_BAD_TX_METADATA;
1947 er.message = "Failed to parse tx metadata.";
1948 return false;
1949 }
1950
1951 try
1952 {
1953 m_wallet->commit_tx(ptx);
1954 }
1955 catch(const std::exception &e)
1956 {
1957 er.code = WALLET_RPC_ERROR_CODE_GENERIC_TRANSFER_ERROR;
1958 er.message = "Failed to commit tx.";
1959 return false;
1960 }
1961
1962 res.tx_hash = epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx));
1963
1964 return true;
1965 }
1966 //------------------------------------------------------------------------------------------------------------------------------
1967 bool wallet_rpc_server::on_make_integrated_address(const wallet_rpc::COMMAND_RPC_MAKE_INTEGRATED_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_MAKE_INTEGRATED_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
1968 {
1969 if (!m_wallet) return not_open(er);
1970 try
1971 {
1972 crypto::hash8 payment_id;
1973 if (req.payment_id.empty())
1974 {
1975 payment_id = crypto::rand<crypto::hash8>();
1976 }
1977 else
1978 {
1979 if (!tools::wallet2::parse_short_payment_id(req.payment_id,payment_id))
1980 {
1981 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
1982 er.message = "Invalid payment ID";
1983 return false;
1984 }
1985 }
1986
1987 if (req.standard_address.empty())
1988 {
1989 res.integrated_address = m_wallet->get_integrated_address_as_str(payment_id);
1990 }
1991 else
1992 {
1993 cryptonote::address_parse_info info;
1994 if(!get_account_address_from_str(info, m_wallet->nettype(), req.standard_address))
1995 {
1996 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
1997 er.message = "Invalid address";
1998 return false;
1999 }
2000 if (info.is_subaddress)
2001 {
2002 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2003 er.message = "Subaddress shouldn't be used";
2004 return false;
2005 }
2006 if (info.has_payment_id)
2007 {
2008 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2009 er.message = "Already integrated address";
2010 return false;
2011 }
2012 res.integrated_address = get_account_integrated_address_as_str(m_wallet->nettype(), info.address, payment_id);
2013 }
2014 res.payment_id = epee::string_tools::pod_to_hex(payment_id);
2015 return true;
2016 }
2017 catch (const std::exception& e)
2018 {
2019 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2020 return false;
2021 }
2022 return true;
2023 }
2024 //------------------------------------------------------------------------------------------------------------------------------
2025 bool wallet_rpc_server::on_split_integrated_address(const wallet_rpc::COMMAND_RPC_SPLIT_INTEGRATED_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_SPLIT_INTEGRATED_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2026 {
2027 if (!m_wallet) return not_open(er);
2028 try
2029 {
2030 cryptonote::address_parse_info info;
2031
2032 if(!get_account_address_from_str(info, m_wallet->nettype(), req.integrated_address))
2033 {
2034 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2035 er.message = "Invalid address";
2036 return false;
2037 }
2038 if(!info.has_payment_id)
2039 {
2040 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2041 er.message = "Address is not an integrated address";
2042 return false;
2043 }
2044 res.standard_address = get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
2045 res.payment_id = epee::string_tools::pod_to_hex(info.payment_id);
2046 return true;
2047 }
2048 catch (const std::exception& e)
2049 {
2050 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2051 return false;
2052 }
2053 return true;
2054 }
2055 //------------------------------------------------------------------------------------------------------------------------------
2056 bool wallet_rpc_server::on_store(const wallet_rpc::COMMAND_RPC_STORE::request& req, wallet_rpc::COMMAND_RPC_STORE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2057 {
2058 if (m_restricted)
2059 {
2060 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2061 er.message = "Command unavailable in restricted mode.";
2062 return false;
2063 }
2064 if (!m_wallet) return not_open(er);
2065
2066 try
2067 {
2068 m_wallet->store();
2069 }
2070 catch (const std::exception& e)
2071 {
2072 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2073 return false;
2074 }
2075 return true;
2076 }
2077 //------------------------------------------------------------------------------------------------------------------------------
2078 bool wallet_rpc_server::on_get_payments(const wallet_rpc::COMMAND_RPC_GET_PAYMENTS::request& req, wallet_rpc::COMMAND_RPC_GET_PAYMENTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2079 {
2080 if (!m_wallet) return not_open(er);
2081 crypto::hash payment_id;
2082 crypto::hash8 payment_id8;
2083 cryptonote::blobdata payment_id_blob;
2084 if(!epee::string_tools::parse_hexstr_to_binbuff(req.payment_id, payment_id_blob))
2085 {
2086 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
2087 er.message = "Payment ID has invalid format";
2088 return false;
2089 }
2090
2091 if(sizeof(payment_id) == payment_id_blob.size())
2092 {
2093 payment_id = *reinterpret_cast<const crypto::hash*>(payment_id_blob.data());
2094 }
2095 else if(sizeof(payment_id8) == payment_id_blob.size())
2096 {
2097 payment_id8 = *reinterpret_cast<const crypto::hash8*>(payment_id_blob.data());
2098 memcpy(payment_id.data, payment_id8.data, 8);
2099 memset(payment_id.data + 8, 0, 24);
2100 }
2101 else
2102 {
2103 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
2104 er.message = "Payment ID has invalid size: " + req.payment_id;
2105 return false;
2106 }
2107
2108 res.payments.clear();
2109 std::list<wallet2::payment_details> payment_list;
2110 m_wallet->get_payments(payment_id, payment_list);
2111 for (auto & payment : payment_list)
2112 {
2113 wallet_rpc::payment_details rpc_payment;
2114 rpc_payment.payment_id = req.payment_id;
2115 rpc_payment.tx_hash = epee::string_tools::pod_to_hex(payment.m_tx_hash);
2116 rpc_payment.amount = payment.m_amount;
2117 rpc_payment.block_height = payment.m_block_height;
2118 rpc_payment.unlock_time = payment.m_unlock_time;
2119 rpc_payment.locked = !m_wallet->is_transfer_unlocked(payment.m_unlock_time, payment.m_block_height);
2120 rpc_payment.subaddr_index = payment.m_subaddr_index;
2121 rpc_payment.address = m_wallet->get_subaddress_as_str(payment.m_subaddr_index);
2122 res.payments.push_back(rpc_payment);
2123 }
2124
2125 return true;
2126 }
2127 //------------------------------------------------------------------------------------------------------------------------------
2128 bool wallet_rpc_server::on_get_bulk_payments(const wallet_rpc::COMMAND_RPC_GET_BULK_PAYMENTS::request& req, wallet_rpc::COMMAND_RPC_GET_BULK_PAYMENTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2129 {
2130 res.payments.clear();
2131 if (!m_wallet) return not_open(er);
2132
2133 /* If the payment ID list is empty, we get payments to any payment ID (or lack thereof) */
2134 if (req.payment_ids.empty())
2135 {
2136 std::list<std::pair<crypto::hash,wallet2::payment_details>> payment_list;
2137 m_wallet->get_payments(payment_list, req.min_block_height);
2138
2139 for (auto & payment : payment_list)
2140 {
2141 wallet_rpc::payment_details rpc_payment;
2142 rpc_payment.payment_id = epee::string_tools::pod_to_hex(payment.first);
2143 rpc_payment.tx_hash = epee::string_tools::pod_to_hex(payment.second.m_tx_hash);
2144 rpc_payment.amount = payment.second.m_amount;
2145 rpc_payment.block_height = payment.second.m_block_height;
2146 rpc_payment.unlock_time = payment.second.m_unlock_time;
2147 rpc_payment.subaddr_index = payment.second.m_subaddr_index;
2148 rpc_payment.address = m_wallet->get_subaddress_as_str(payment.second.m_subaddr_index);
2149 rpc_payment.locked = !m_wallet->is_transfer_unlocked(payment.second.m_unlock_time, payment.second.m_block_height);
2150 res.payments.push_back(std::move(rpc_payment));
2151 }
2152
2153 return true;
2154 }
2155
2156 for (auto & payment_id_str : req.payment_ids)
2157 {
2158 crypto::hash payment_id;
2159 crypto::hash8 payment_id8;
2160 cryptonote::blobdata payment_id_blob;
2161
2162 // TODO - should the whole thing fail because of one bad id?
2163 bool r;
2164 if (payment_id_str.size() == 2 * sizeof(payment_id))
2165 {
2166 r = epee::string_tools::hex_to_pod(payment_id_str, payment_id);
2167 }
2168 else if (payment_id_str.size() == 2 * sizeof(payment_id8))
2169 {
2170 r = epee::string_tools::hex_to_pod(payment_id_str, payment_id8);
2171 if (r)
2172 {
2173 memcpy(payment_id.data, payment_id8.data, 8);
2174 memset(payment_id.data + 8, 0, 24);
2175 }
2176 }
2177 else
2178 {
2179 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
2180 er.message = "Payment ID has invalid size: " + payment_id_str;
2181 return false;
2182 }
2183
2184 if(!r)
2185 {
2186 er.code = WALLET_RPC_ERROR_CODE_WRONG_PAYMENT_ID;
2187 er.message = "Payment ID has invalid format: " + payment_id_str;
2188 return false;
2189 }
2190
2191 std::list<wallet2::payment_details> payment_list;
2192 m_wallet->get_payments(payment_id, payment_list, req.min_block_height);
2193
2194 for (auto & payment : payment_list)
2195 {
2196 wallet_rpc::payment_details rpc_payment;
2197 rpc_payment.payment_id = payment_id_str;
2198 rpc_payment.tx_hash = epee::string_tools::pod_to_hex(payment.m_tx_hash);
2199 rpc_payment.amount = payment.m_amount;
2200 rpc_payment.block_height = payment.m_block_height;
2201 rpc_payment.unlock_time = payment.m_unlock_time;
2202 rpc_payment.subaddr_index = payment.m_subaddr_index;
2203 rpc_payment.address = m_wallet->get_subaddress_as_str(payment.m_subaddr_index);
2204 rpc_payment.locked = !m_wallet->is_transfer_unlocked(payment.m_unlock_time, payment.m_block_height);
2205 res.payments.push_back(std::move(rpc_payment));
2206 }
2207 }
2208
2209 return true;
2210 }
2211 //------------------------------------------------------------------------------------------------------------------------------
2212 bool wallet_rpc_server::on_incoming_transfers(const wallet_rpc::COMMAND_RPC_INCOMING_TRANSFERS::request& req, wallet_rpc::COMMAND_RPC_INCOMING_TRANSFERS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2213 {
2214 if (!m_wallet) return not_open(er);
2215 if(req.transfer_type.compare("all") != 0 && req.transfer_type.compare("available") != 0 && req.transfer_type.compare("unavailable") != 0)
2216 {
2217 er.code = WALLET_RPC_ERROR_CODE_TRANSFER_TYPE;
2218 er.message = "Transfer type must be one of: all, available, or unavailable";
2219 return false;
2220 }
2221
2222 bool filter = false;
2223 bool available = false;
2224 if (req.transfer_type.compare("available") == 0)
2225 {
2226 filter = true;
2227 available = true;
2228 }
2229 else if (req.transfer_type.compare("unavailable") == 0)
2230 {
2231 filter = true;
2232 available = false;
2233 }
2234
2235 wallet2::transfer_container transfers;
2236 m_wallet->get_transfers(transfers);
2237
2238 for (const auto& td : transfers)
2239 {
2240 if (!filter || available != td.m_spent)
2241 {
2242 if (req.account_index != td.m_subaddr_index.major || (!req.subaddr_indices.empty() && req.subaddr_indices.count(td.m_subaddr_index.minor) == 0))
2243 continue;
2244 wallet_rpc::transfer_details rpc_transfers;
2245 rpc_transfers.amount = td.amount();
2246 rpc_transfers.spent = td.m_spent;
2247 rpc_transfers.global_index = td.m_global_output_index;
2248 rpc_transfers.tx_hash = epee::string_tools::pod_to_hex(td.m_txid);
2249 rpc_transfers.subaddr_index = {td.m_subaddr_index.major, td.m_subaddr_index.minor};
2250 rpc_transfers.key_image = td.m_key_image_known ? epee::string_tools::pod_to_hex(td.m_key_image) : "";
2251 rpc_transfers.pubkey = epee::string_tools::pod_to_hex(td.get_public_key());
2252 rpc_transfers.block_height = td.m_block_height;
2253 rpc_transfers.frozen = td.m_frozen;
2254 rpc_transfers.unlocked = m_wallet->is_transfer_unlocked(td);
2255 res.transfers.push_back(rpc_transfers);
2256 }
2257 }
2258
2259 return true;
2260 }
2261 //------------------------------------------------------------------------------------------------------------------------------
2262 bool wallet_rpc_server::on_query_key(const wallet_rpc::COMMAND_RPC_QUERY_KEY::request& req, wallet_rpc::COMMAND_RPC_QUERY_KEY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2263 {
2264 if (m_restricted)
2265 {
2266 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2267 er.message = "Command unavailable in restricted mode.";
2268 return false;
2269 }
2270 if (!m_wallet) return not_open(er);
2271
2272 if (req.key_type.compare("mnemonic") == 0)
2273 {
2274 epee::wipeable_string seed;
2275 bool ready;
2276 if (m_wallet->multisig(&ready))
2277 {
2278 if (!ready)
2279 {
2280 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
2281 er.message = "This wallet is multisig, but not yet finalized";
2282 return false;
2283 }
2284 if (!m_wallet->get_multisig_seed(seed))
2285 {
2286 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2287 er.message = "Failed to get multisig seed.";
2288 return false;
2289 }
2290 }
2291 else
2292 {
2293 if (m_wallet->watch_only())
2294 {
2295 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
2296 er.message = "The wallet is watch-only. Cannot retrieve seed.";
2297 return false;
2298 }
2299 CHECK_IF_BACKGROUND_SYNCING();
2300 if (!m_wallet->is_deterministic())
2301 {
2302 er.code = WALLET_RPC_ERROR_CODE_NON_DETERMINISTIC;
2303 er.message = "The wallet is non-deterministic. Cannot display seed.";
2304 return false;
2305 }
2306 if (!m_wallet->get_seed(seed))
2307 {
2308 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2309 er.message = "Failed to get seed.";
2310 return false;
2311 }
2312 }
2313 res.key = std::string(seed.data(), seed.size()); // send to the network, then wipe RAM :D
2314 }
2315 else if(req.key_type.compare("view_key") == 0)
2316 {
2317 epee::wipeable_string key = epee::to_hex::wipeable_string(m_wallet->get_account().get_keys().m_view_secret_key);
2318 res.key = std::string(key.data(), key.size());
2319 }
2320 else if(req.key_type.compare("spend_key") == 0)
2321 {
2322 if (m_wallet->watch_only())
2323 {
2324 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
2325 er.message = "The wallet is watch-only. Cannot retrieve spend key.";
2326 return false;
2327 }
2328 CHECK_IF_BACKGROUND_SYNCING();
2329 epee::wipeable_string key = epee::to_hex::wipeable_string(m_wallet->get_account().get_keys().m_spend_secret_key);
2330 res.key = std::string(key.data(), key.size());
2331 }
2332 else
2333 {
2334 er.message = "key_type " + req.key_type + " not found";
2335 return false;
2336 }
2337
2338 return true;
2339 }
2340 //------------------------------------------------------------------------------------------------------------------------------
2341 bool wallet_rpc_server::on_rescan_blockchain(const wallet_rpc::COMMAND_RPC_RESCAN_BLOCKCHAIN::request& req, wallet_rpc::COMMAND_RPC_RESCAN_BLOCKCHAIN::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2342 {
2343 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
2344
2345 try
2346 {
2347 m_wallet->rescan_blockchain(req.hard);
2348 }
2349 catch (const std::exception& e)
2350 {
2351 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2352 return false;
2353 }
2354 return true;
2355 }
2356 //------------------------------------------------------------------------------------------------------------------------------
2357 bool wallet_rpc_server::on_setup_background_sync(const wallet_rpc::COMMAND_RPC_SETUP_BACKGROUND_SYNC::request& req, wallet_rpc::COMMAND_RPC_SETUP_BACKGROUND_SYNC::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2358 {
2359 try
2360 {
2361 PRE_VALIDATE_BACKGROUND_SYNC();
2362 const tools::wallet2::BackgroundSyncType background_sync_type = tools::wallet2::background_sync_type_from_str(req.background_sync_type);
2363 boost::optional<epee::wipeable_string> background_cache_password = boost::none;
2364 if (background_sync_type == tools::wallet2::BackgroundSyncCustomPassword)
2365 background_cache_password = boost::optional<epee::wipeable_string>(req.background_cache_password);
2366 m_wallet->setup_background_sync(background_sync_type, req.wallet_password, background_cache_password);
2367 }
2368 catch (...)
2369 {
2370 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2371 return false;
2372 }
2373 return true;
2374 }
2375 //------------------------------------------------------------------------------------------------------------------------------
2376 bool wallet_rpc_server::on_start_background_sync(const wallet_rpc::COMMAND_RPC_START_BACKGROUND_SYNC::request& req, wallet_rpc::COMMAND_RPC_START_BACKGROUND_SYNC::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2377 {
2378 try
2379 {
2380 PRE_VALIDATE_BACKGROUND_SYNC();
2381 m_wallet->start_background_sync();
2382 }
2383 catch (...)
2384 {
2385 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2386 return false;
2387 }
2388 return true;
2389 }
2390 //------------------------------------------------------------------------------------------------------------------------------
2391 bool wallet_rpc_server::on_stop_background_sync(const wallet_rpc::COMMAND_RPC_STOP_BACKGROUND_SYNC::request& req, wallet_rpc::COMMAND_RPC_STOP_BACKGROUND_SYNC::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2392 {
2393 try
2394 {
2395 PRE_VALIDATE_BACKGROUND_SYNC();
2396 crypto::secret_key spend_secret_key = crypto::null_skey;
2397
2398 // Load the spend key from seed if seed is provided
2399 if (!req.seed.empty())
2400 {
2401 crypto::secret_key recovery_key;
2402 std::string language;
2403
2404 if (!crypto::ElectrumWords::words_to_bytes(req.seed, recovery_key, language))
2405 {
2406 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2407 er.message = "Electrum-style word list failed verification";
2408 return false;
2409 }
2410
2411 if (!req.seed_offset.empty())
2412 recovery_key = cryptonote::decrypt_key(recovery_key, req.seed_offset);
2413
2414 // generate spend key
2415 cryptonote::account_base account;
2416 account.generate(recovery_key, true, false);
2417 spend_secret_key = account.get_keys().m_spend_secret_key;
2418 }
2419
2420 m_wallet->stop_background_sync(req.wallet_password, spend_secret_key);
2421 }
2422 catch (...)
2423 {
2424 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2425 return false;
2426 }
2427 return true;
2428 }
2429 //------------------------------------------------------------------------------------------------------------------------------
2430 bool wallet_rpc_server::on_sign(const wallet_rpc::COMMAND_RPC_SIGN::request& req, wallet_rpc::COMMAND_RPC_SIGN::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2431 {
2432 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
2433
2434 tools::wallet2::message_signature_type_t signature_type = tools::wallet2::sign_with_spend_key;
2435 if (req.signature_type == "spend" || req.signature_type == "")
2436 signature_type = tools::wallet2::sign_with_spend_key;
2437 else if (req.signature_type == "view")
2438 signature_type = tools::wallet2::sign_with_view_key;
2439 else
2440 {
2441 er.code = WALLET_RPC_ERROR_CODE_INVALID_SIGNATURE_TYPE;
2442 er.message = "Invalid signature type requested";
2443 return false;
2444 }
2445 res.signature = m_wallet->sign(req.data, signature_type, {req.account_index, req.address_index});
2446 return true;
2447 }
2448 //------------------------------------------------------------------------------------------------------------------------------
2449 bool wallet_rpc_server::on_verify(const wallet_rpc::COMMAND_RPC_VERIFY::request& req, wallet_rpc::COMMAND_RPC_VERIFY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2450 {
2451 if (m_restricted)
2452 {
2453 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2454 er.message = "Command unavailable in restricted mode.";
2455 return false;
2456 }
2457 if (!m_wallet) return not_open(er);
2458
2459 cryptonote::address_parse_info info;
2460 er.message = "";
2461 if(!get_account_address_from_str_or_url(info, m_wallet->nettype(), req.address,
2462 [&er](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)->std::string {
2463 if (!dnssec_valid)
2464 {
2465 er.message = std::string("Invalid DNSSEC for ") + url;
2466 return {};
2467 }
2468 if (addresses.empty())
2469 {
2470 er.message = std::string("No Monero address found at ") + url;
2471 return {};
2472 }
2473 return addresses[0];
2474 }))
2475 {
2476 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2477 return false;
2478 }
2479
2480 const auto result = m_wallet->verify(req.data, info.address, req.signature);
2481 res.good = result.valid;
2482 res.version = result.version;
2483 res.old = result.old;
2484 switch (result.type)
2485 {
2486 case tools::wallet2::sign_with_spend_key: res.signature_type = "spend"; break;
2487 case tools::wallet2::sign_with_view_key: res.signature_type = "view"; break;
2488 default: res.signature_type = "invalid"; break;
2489 }
2490 return true;
2491 }
2492 //------------------------------------------------------------------------------------------------------------------------------
2493 bool wallet_rpc_server::on_stop_wallet(const wallet_rpc::COMMAND_RPC_STOP_WALLET::request& req, wallet_rpc::COMMAND_RPC_STOP_WALLET::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2494 {
2495 if (m_restricted)
2496 {
2497 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2498 er.message = "Command unavailable in restricted mode.";
2499 return false;
2500 }
2501 if (!m_wallet) return not_open(er);
2502
2503 try
2504 {
2505 m_wallet->store();
2506 m_stop.store(true, std::memory_order_relaxed);
2507 }
2508 catch (const std::exception& e)
2509 {
2510 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
2511 return false;
2512 }
2513 return true;
2514 }
2515 //------------------------------------------------------------------------------------------------------------------------------
2516 bool wallet_rpc_server::on_set_tx_notes(const wallet_rpc::COMMAND_RPC_SET_TX_NOTES::request& req, wallet_rpc::COMMAND_RPC_SET_TX_NOTES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2517 {
2518 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
2519
2520 if (req.txids.size() != req.notes.size())
2521 {
2522 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2523 er.message = "Different amount of txids and notes";
2524 return false;
2525 }
2526
2527 std::list<crypto::hash> txids;
2528 std::list<std::string>::const_iterator i = req.txids.begin();
2529 while (i != req.txids.end())
2530 {
2531 cryptonote::blobdata txid_blob;
2532 if(!epee::string_tools::parse_hexstr_to_binbuff(*i++, txid_blob) || txid_blob.size() != sizeof(crypto::hash))
2533 {
2534 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2535 er.message = "TX ID has invalid format";
2536 return false;
2537 }
2538
2539 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_blob.data());
2540 txids.push_back(txid);
2541 }
2542
2543 std::list<crypto::hash>::const_iterator il = txids.begin();
2544 std::list<std::string>::const_iterator in = req.notes.begin();
2545 while (il != txids.end())
2546 {
2547 m_wallet->set_tx_note(*il++, *in++);
2548 }
2549
2550 return true;
2551 }
2552 //------------------------------------------------------------------------------------------------------------------------------
2553 bool wallet_rpc_server::on_get_tx_notes(const wallet_rpc::COMMAND_RPC_GET_TX_NOTES::request& req, wallet_rpc::COMMAND_RPC_GET_TX_NOTES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2554 {
2555 res.notes.clear();
2556 if (!m_wallet) return not_open(er);
2557
2558 std::list<crypto::hash> txids;
2559 std::list<std::string>::const_iterator i = req.txids.begin();
2560 while (i != req.txids.end())
2561 {
2562 cryptonote::blobdata txid_blob;
2563 if(!epee::string_tools::parse_hexstr_to_binbuff(*i++, txid_blob) || txid_blob.size() != sizeof(crypto::hash))
2564 {
2565 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2566 er.message = "TX ID has invalid format";
2567 return false;
2568 }
2569
2570 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_blob.data());
2571 txids.push_back(txid);
2572 }
2573
2574 std::list<crypto::hash>::const_iterator il = txids.begin();
2575 while (il != txids.end())
2576 {
2577 res.notes.push_back(m_wallet->get_tx_note(*il++));
2578 }
2579 return true;
2580 }
2581 //------------------------------------------------------------------------------------------------------------------------------
2582 bool wallet_rpc_server::on_set_attribute(const wallet_rpc::COMMAND_RPC_SET_ATTRIBUTE::request& req, wallet_rpc::COMMAND_RPC_SET_ATTRIBUTE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2583 {
2584 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
2585
2586 m_wallet->set_attribute(req.key, req.value);
2587
2588 return true;
2589 }
2590 //------------------------------------------------------------------------------------------------------------------------------
2591 bool wallet_rpc_server::on_get_attribute(const wallet_rpc::COMMAND_RPC_GET_ATTRIBUTE::request& req, wallet_rpc::COMMAND_RPC_GET_ATTRIBUTE::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2592 {
2593 if (m_restricted)
2594 {
2595 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2596 er.message = "Command unavailable in restricted mode.";
2597 return false;
2598 }
2599 if (!m_wallet) return not_open(er);
2600
2601 if (!m_wallet->get_attribute(req.key, res.value))
2602 {
2603 er.code = WALLET_RPC_ERROR_CODE_ATTRIBUTE_NOT_FOUND;
2604 er.message = "Attribute not found.";
2605 return false;
2606 }
2607 return true;
2608 }
2609 bool wallet_rpc_server::on_get_tx_key(const wallet_rpc::COMMAND_RPC_GET_TX_KEY::request& req, wallet_rpc::COMMAND_RPC_GET_TX_KEY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2610 {
2611 if (!m_wallet) return not_open(er);
2612 CHECK_IF_BACKGROUND_SYNCING();
2613
2614 crypto::hash txid;
2615 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2616 {
2617 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2618 er.message = "TX ID has invalid format";
2619 return false;
2620 }
2621
2622 crypto::secret_key tx_key;
2623 std::vector<crypto::secret_key> additional_tx_keys;
2624 if (!m_wallet->get_tx_key(txid, tx_key, additional_tx_keys))
2625 {
2626 er.code = WALLET_RPC_ERROR_CODE_NO_TXKEY;
2627 er.message = "No tx secret key is stored for this tx";
2628 return false;
2629 }
2630
2631 epee::wipeable_string s;
2632 s += epee::to_hex::wipeable_string(tx_key);
2633 for (size_t i = 0; i < additional_tx_keys.size(); ++i)
2634 s += epee::to_hex::wipeable_string(additional_tx_keys[i]);
2635 res.tx_key = std::string(s.data(), s.size());
2636 return true;
2637 }
2638 //------------------------------------------------------------------------------------------------------------------------------
2639 bool wallet_rpc_server::on_check_tx_key(const wallet_rpc::COMMAND_RPC_CHECK_TX_KEY::request& req, wallet_rpc::COMMAND_RPC_CHECK_TX_KEY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2640 {
2641 if (!m_wallet) return not_open(er);
2642
2643 crypto::hash txid;
2644 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2645 {
2646 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2647 er.message = "TX ID has invalid format";
2648 return false;
2649 }
2650
2651 epee::wipeable_string tx_key_str = req.tx_key;
2652 if (tx_key_str.size() < 64 || tx_key_str.size() % 64)
2653 {
2654 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY;
2655 er.message = "Tx key has invalid format";
2656 return false;
2657 }
2658 const char *data = tx_key_str.data();
2659 crypto::secret_key tx_key;
2660 if (!epee::wipeable_string(data, 64).hex_to_pod(unwrap(unwrap(tx_key))))
2661 {
2662 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY;
2663 er.message = "Tx key has invalid format";
2664 return false;
2665 }
2666 size_t offset = 64;
2667 std::vector<crypto::secret_key> additional_tx_keys;
2668 while (offset < tx_key_str.size())
2669 {
2670 additional_tx_keys.resize(additional_tx_keys.size() + 1);
2671 if (!epee::wipeable_string(data + offset, 64).hex_to_pod(unwrap(unwrap(additional_tx_keys.back()))))
2672 {
2673 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY;
2674 er.message = "Tx key has invalid format";
2675 return false;
2676 }
2677 offset += 64;
2678 }
2679
2680 cryptonote::address_parse_info info;
2681 if(!get_account_address_from_str(info, m_wallet->nettype(), req.address))
2682 {
2683 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2684 er.message = "Invalid address";
2685 return false;
2686 }
2687
2688 try
2689 {
2690 m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, res.received, res.in_pool, res.confirmations);
2691 }
2692 catch (const std::exception &e)
2693 {
2694 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2695 er.message = e.what();
2696 return false;
2697 }
2698 return true;
2699 }
2700 //------------------------------------------------------------------------------------------------------------------------------
2701 bool wallet_rpc_server::on_get_tx_proof(const wallet_rpc::COMMAND_RPC_GET_TX_PROOF::request& req, wallet_rpc::COMMAND_RPC_GET_TX_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2702 {
2703 if (!m_wallet) return not_open(er);
2704 CHECK_IF_BACKGROUND_SYNCING();
2705
2706 crypto::hash txid;
2707 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2708 {
2709 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2710 er.message = "TX ID has invalid format";
2711 return false;
2712 }
2713
2714 cryptonote::address_parse_info info;
2715 if(!get_account_address_from_str(info, m_wallet->nettype(), req.address))
2716 {
2717 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2718 er.message = "Invalid address";
2719 return false;
2720 }
2721
2722 try
2723 {
2724 res.signature = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, req.message);
2725 }
2726 catch (const std::exception &e)
2727 {
2728 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2729 er.message = e.what();
2730 return false;
2731 }
2732 return true;
2733 }
2734 //------------------------------------------------------------------------------------------------------------------------------
2735 bool wallet_rpc_server::on_check_tx_proof(const wallet_rpc::COMMAND_RPC_CHECK_TX_PROOF::request& req, wallet_rpc::COMMAND_RPC_CHECK_TX_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2736 {
2737 if (!m_wallet) return not_open(er);
2738
2739 crypto::hash txid;
2740 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2741 {
2742 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2743 er.message = "TX ID has invalid format";
2744 return false;
2745 }
2746
2747 cryptonote::address_parse_info info;
2748 if(!get_account_address_from_str(info, m_wallet->nettype(), req.address))
2749 {
2750 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2751 er.message = "Invalid address";
2752 return false;
2753 }
2754
2755 try
2756 {
2757 res.good = m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, req.message, req.signature, res.received, res.in_pool, res.confirmations);
2758 }
2759 catch (const std::exception &e)
2760 {
2761 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2762 er.message = e.what();
2763 return false;
2764 }
2765 return true;
2766 }
2767 //------------------------------------------------------------------------------------------------------------------------------
2768 bool wallet_rpc_server::on_get_spend_proof(const wallet_rpc::COMMAND_RPC_GET_SPEND_PROOF::request& req, wallet_rpc::COMMAND_RPC_GET_SPEND_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2769 {
2770 if (!m_wallet) return not_open(er);
2771
2772 crypto::hash txid;
2773 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2774 {
2775 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2776 er.message = "TX ID has invalid format";
2777 return false;
2778 }
2779
2780 try
2781 {
2782 res.signature = m_wallet->get_spend_proof(txid, req.message);
2783 }
2784 catch (const std::exception &e)
2785 {
2786 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2787 er.message = e.what();
2788 return false;
2789 }
2790 return true;
2791 }
2792 //------------------------------------------------------------------------------------------------------------------------------
2793 bool wallet_rpc_server::on_check_spend_proof(const wallet_rpc::COMMAND_RPC_CHECK_SPEND_PROOF::request& req, wallet_rpc::COMMAND_RPC_CHECK_SPEND_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2794 {
2795 if (!m_wallet) return not_open(er);
2796
2797 crypto::hash txid;
2798 if (!epee::string_tools::hex_to_pod(req.txid, txid))
2799 {
2800 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2801 er.message = "TX ID has invalid format";
2802 return false;
2803 }
2804
2805 try
2806 {
2807 res.good = m_wallet->check_spend_proof(txid, req.message, req.signature);
2808 }
2809 catch (const std::exception &e)
2810 {
2811 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2812 er.message = e.what();
2813 return false;
2814 }
2815 return true;
2816 }
2817 //------------------------------------------------------------------------------------------------------------------------------
2818 bool wallet_rpc_server::on_get_reserve_proof(const wallet_rpc::COMMAND_RPC_GET_RESERVE_PROOF::request& req, wallet_rpc::COMMAND_RPC_GET_RESERVE_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2819 {
2820 if (!m_wallet) return not_open(er);
2821 CHECK_IF_BACKGROUND_SYNCING();
2822
2823 boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
2824 if (!req.all)
2825 {
2826 if (req.account_index >= m_wallet->get_num_subaddress_accounts())
2827 {
2828 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2829 er.message = "Account index is out of bound";
2830 return false;
2831 }
2832 account_minreserve = std::make_pair(req.account_index, req.amount);
2833 }
2834
2835 try
2836 {
2837 res.signature = m_wallet->get_reserve_proof(account_minreserve, req.message);
2838 }
2839 catch (const std::exception &e)
2840 {
2841 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2842 er.message = e.what();
2843 return false;
2844 }
2845 return true;
2846 }
2847 //------------------------------------------------------------------------------------------------------------------------------
2848 bool wallet_rpc_server::on_check_reserve_proof(const wallet_rpc::COMMAND_RPC_CHECK_RESERVE_PROOF::request& req, wallet_rpc::COMMAND_RPC_CHECK_RESERVE_PROOF::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2849 {
2850 if (!m_wallet) return not_open(er);
2851
2852 cryptonote::address_parse_info info;
2853 if (!get_account_address_from_str(info, m_wallet->nettype(), req.address))
2854 {
2855 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
2856 er.message = "Invalid address";
2857 return false;
2858 }
2859 if (info.is_subaddress)
2860 {
2861 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2862 er.message = "Address must not be a subaddress";
2863 return false;
2864 }
2865
2866 try
2867 {
2868 res.good = m_wallet->check_reserve_proof(info.address, req.message, req.signature, res.total, res.spent);
2869 }
2870 catch (const std::exception &e)
2871 {
2872 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
2873 er.message = e.what();
2874 return false;
2875 }
2876 return true;
2877 }
2878 //------------------------------------------------------------------------------------------------------------------------------
2879 bool wallet_rpc_server::on_get_transfers(const wallet_rpc::COMMAND_RPC_GET_TRANSFERS::request& req, wallet_rpc::COMMAND_RPC_GET_TRANSFERS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2880 {
2881 if (m_restricted)
2882 {
2883 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2884 er.message = "Command unavailable in restricted mode.";
2885 return false;
2886 }
2887 if (!m_wallet) return not_open(er);
2888
2889 uint64_t min_height = 0, max_height = CRYPTONOTE_MAX_BLOCK_NUMBER;
2890 if (req.filter_by_height)
2891 {
2892 min_height = req.min_height;
2893 max_height = req.max_height <= max_height ? req.max_height : max_height;
2894 }
2895
2896 boost::optional<uint32_t> account_index = req.account_index;
2897 std::set<uint32_t> subaddr_indices = req.subaddr_indices;
2898 if (req.all_accounts)
2899 {
2900 account_index = boost::none;
2901 subaddr_indices.clear();
2902 }
2903
2904 if (req.in)
2905 {
2906 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
2907 m_wallet->get_payments(payments, min_height, max_height, account_index, subaddr_indices);
2908 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
2909 res.in.push_back(wallet_rpc::transfer_entry());
2910 fill_transfer_entry(res.in.back(), i->second.m_tx_hash, i->first, i->second);
2911 }
2912 }
2913
2914 if (req.out)
2915 {
2916 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments;
2917 m_wallet->get_payments_out(payments, min_height, max_height, account_index, subaddr_indices);
2918 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
2919 res.out.push_back(wallet_rpc::transfer_entry());
2920 fill_transfer_entry(res.out.back(), i->first, i->second);
2921 }
2922 }
2923
2924 if (req.pending || req.failed) {
2925 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
2926 m_wallet->get_unconfirmed_payments_out(upayments, account_index, subaddr_indices);
2927 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
2928 const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
2929 bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
2930 if (!((req.failed && is_failed) || (!is_failed && req.pending)))
2931 continue;
2932 std::list<wallet_rpc::transfer_entry> &entries = is_failed ? res.failed : res.pending;
2933 entries.push_back(wallet_rpc::transfer_entry());
2934 fill_transfer_entry(entries.back(), i->first, i->second);
2935 }
2936 }
2937
2938 if (req.pool)
2939 {
2940 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
2941 m_wallet->update_pool_state(process_txs);
2942 if (!process_txs.empty())
2943 m_wallet->process_pool_state(process_txs);
2944
2945 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments;
2946 m_wallet->get_unconfirmed_payments(payments, account_index, subaddr_indices);
2947 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
2948 res.pool.push_back(wallet_rpc::transfer_entry());
2949 fill_transfer_entry(res.pool.back(), i->first, i->second);
2950 }
2951 }
2952
2953 return true;
2954 }
2955 //------------------------------------------------------------------------------------------------------------------------------
2956 bool wallet_rpc_server::on_get_transfer_by_txid(const wallet_rpc::COMMAND_RPC_GET_TRANSFER_BY_TXID::request& req, wallet_rpc::COMMAND_RPC_GET_TRANSFER_BY_TXID::response& res, epee::json_rpc::error& er, const connection_context *ctx)
2957 {
2958 if (m_restricted)
2959 {
2960 er.code = WALLET_RPC_ERROR_CODE_DENIED;
2961 er.message = "Command unavailable in restricted mode.";
2962 return false;
2963 }
2964 if (!m_wallet) return not_open(er);
2965
2966 crypto::hash txid;
2967 cryptonote::blobdata txid_blob;
2968 if(!epee::string_tools::parse_hexstr_to_binbuff(req.txid, txid_blob))
2969 {
2970 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2971 er.message = "Transaction ID has invalid format";
2972 return false;
2973 }
2974
2975 if(sizeof(txid) == txid_blob.size())
2976 {
2977 txid = *reinterpret_cast<const crypto::hash*>(txid_blob.data());
2978 }
2979 else
2980 {
2981 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
2982 er.message = "Transaction ID has invalid size: " + req.txid;
2983 return false;
2984 }
2985
2986 if (req.account_index >= m_wallet->get_num_subaddress_accounts())
2987 {
2988 er.code = WALLET_RPC_ERROR_CODE_ACCOUNT_INDEX_OUT_OF_BOUNDS;
2989 er.message = "Account index is out of bound";
2990 return false;
2991 }
2992
2993 std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
2994 m_wallet->get_payments(payments, 0, (uint64_t)-1, req.account_index);
2995 for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
2996 if (i->second.m_tx_hash == txid)
2997 {
2998 res.transfers.resize(res.transfers.size() + 1);
2999 fill_transfer_entry(res.transfers.back(), i->second.m_tx_hash, i->first, i->second);
3000 }
3001 }
3002
3003 std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out;
3004 m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, req.account_index);
3005 for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) {
3006 if (i->first == txid)
3007 {
3008 res.transfers.resize(res.transfers.size() + 1);
3009 fill_transfer_entry(res.transfers.back(), i->first, i->second);
3010 }
3011 }
3012
3013 std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
3014 m_wallet->get_unconfirmed_payments_out(upayments, req.account_index);
3015 for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
3016 if (i->first == txid)
3017 {
3018 res.transfers.resize(res.transfers.size() + 1);
3019 fill_transfer_entry(res.transfers.back(), i->first, i->second);
3020 }
3021 }
3022
3023 std::vector<std::tuple<cryptonote::transaction, crypto::hash, bool>> process_txs;
3024 m_wallet->update_pool_state(process_txs);
3025 if (!process_txs.empty())
3026 m_wallet->process_pool_state(process_txs);
3027
3028 std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments;
3029 m_wallet->get_unconfirmed_payments(pool_payments, req.account_index);
3030 for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) {
3031 if (i->second.m_pd.m_tx_hash == txid)
3032 {
3033 res.transfers.resize(res.transfers.size() + 1);
3034 fill_transfer_entry(res.transfers.back(), i->first, i->second);
3035 }
3036 }
3037
3038 if (!res.transfers.empty())
3039 {
3040 res.transfer = res.transfers.front(); // backward compat
3041 return true;
3042 }
3043
3044 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
3045 er.message = "Transaction not found.";
3046 return false;
3047 }
3048 //------------------------------------------------------------------------------------------------------------------------------
3049 bool wallet_rpc_server::on_export_outputs(const wallet_rpc::COMMAND_RPC_EXPORT_OUTPUTS::request& req, wallet_rpc::COMMAND_RPC_EXPORT_OUTPUTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3050 {
3051 if (m_restricted)
3052 {
3053 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3054 er.message = "Command unavailable in restricted mode.";
3055 return false;
3056 }
3057 if (!m_wallet) return not_open(er);
3058 if (m_wallet->key_on_device())
3059 {
3060 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3061 er.message = "command not supported by HW wallet";
3062 return false;
3063 }
3064 CHECK_IF_BACKGROUND_SYNCING();
3065
3066 try
3067 {
3068 res.outputs_data_hex = epee::string_tools::buff_to_hex_nodelimer(m_wallet->export_outputs_to_str(req.all, req.start, req.count));
3069 }
3070 catch (const std::exception &e)
3071 {
3072 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3073 return false;
3074 }
3075
3076 return true;
3077 }
3078 //------------------------------------------------------------------------------------------------------------------------------
3079 bool wallet_rpc_server::on_import_outputs(const wallet_rpc::COMMAND_RPC_IMPORT_OUTPUTS::request& req, wallet_rpc::COMMAND_RPC_IMPORT_OUTPUTS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3080 {
3081 if (m_restricted)
3082 {
3083 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3084 er.message = "Command unavailable in restricted mode.";
3085 return false;
3086 }
3087 if (!m_wallet) return not_open(er);
3088 if (m_wallet->key_on_device())
3089 {
3090 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3091 er.message = "command not supported by HW wallet";
3092 return false;
3093 }
3094 CHECK_IF_BACKGROUND_SYNCING();
3095
3096 cryptonote::blobdata blob;
3097 if (!epee::string_tools::parse_hexstr_to_binbuff(req.outputs_data_hex, blob))
3098 {
3099 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
3100 er.message = "Failed to parse hex.";
3101 return false;
3102 }
3103
3104 try
3105 {
3106 res.num_imported = m_wallet->import_outputs_from_str(blob);
3107 }
3108 catch (const std::exception &e)
3109 {
3110 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3111 return false;
3112 }
3113
3114 return true;
3115 }
3116 //------------------------------------------------------------------------------------------------------------------------------
3117 bool wallet_rpc_server::on_export_key_images(const wallet_rpc::COMMAND_RPC_EXPORT_KEY_IMAGES::request& req, wallet_rpc::COMMAND_RPC_EXPORT_KEY_IMAGES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3118 {
3119 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3120 try
3121 {
3122 std::pair<uint64_t, std::vector<std::pair<crypto::key_image, crypto::signature>>> ski = m_wallet->export_key_images(req.all);
3123 res.offset = ski.first;
3124 res.signed_key_images.resize(ski.second.size());
3125 for (size_t n = 0; n < ski.second.size(); ++n)
3126 {
3127 res.signed_key_images[n].key_image = epee::string_tools::pod_to_hex(ski.second[n].first);
3128 res.signed_key_images[n].signature = epee::string_tools::pod_to_hex(ski.second[n].second);
3129 }
3130 }
3131
3132 catch (const std::exception& e)
3133 {
3134 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3135 return false;
3136 }
3137
3138 return true;
3139 }
3140 //------------------------------------------------------------------------------------------------------------------------------
3141 bool wallet_rpc_server::on_import_key_images(const wallet_rpc::COMMAND_RPC_IMPORT_KEY_IMAGES::request& req, wallet_rpc::COMMAND_RPC_IMPORT_KEY_IMAGES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3142 {
3143 if (m_restricted)
3144 {
3145 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3146 er.message = "Command unavailable in restricted mode.";
3147 return false;
3148 }
3149 if (!m_wallet) return not_open(er);
3150 if (!m_wallet->is_trusted_daemon())
3151 {
3152 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3153 er.message = "This command requires a trusted daemon.";
3154 return false;
3155 }
3156 CHECK_IF_BACKGROUND_SYNCING();
3157 try
3158 {
3159 std::vector<std::pair<crypto::key_image, crypto::signature>> ski;
3160 ski.resize(req.signed_key_images.size());
3161 for (size_t n = 0; n < ski.size(); ++n)
3162 {
3163 if (!epee::string_tools::hex_to_pod(req.signed_key_images[n].key_image, ski[n].first))
3164 {
3165 er.code = WALLET_RPC_ERROR_CODE_WRONG_KEY_IMAGE;
3166 er.message = "failed to parse key image";
3167 return false;
3168 }
3169
3170 if (!epee::string_tools::hex_to_pod(req.signed_key_images[n].signature, ski[n].second))
3171 {
3172 er.code = WALLET_RPC_ERROR_CODE_WRONG_SIGNATURE;
3173 er.message = "failed to parse signature";
3174 return false;
3175 }
3176 }
3177 uint64_t spent = 0, unspent = 0;
3178 uint64_t height = m_wallet->import_key_images(ski, req.offset, spent, unspent);
3179 res.spent = spent;
3180 res.unspent = unspent;
3181 res.height = height;
3182 }
3183
3184 catch (const std::exception& e)
3185 {
3186 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3187 return false;
3188 }
3189
3190 return true;
3191 }
3192 //------------------------------------------------------------------------------------------------------------------------------
3193 bool wallet_rpc_server::on_make_uri(const wallet_rpc::COMMAND_RPC_MAKE_URI::request& req, wallet_rpc::COMMAND_RPC_MAKE_URI::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3194 {
3195 if (!m_wallet) return not_open(er);
3196 std::string error;
3197 std::string uri = m_wallet->make_uri(req.address, req.payment_id, req.amount, req.tx_description, req.recipient_name, error);
3198 if (uri.empty())
3199 {
3200 er.code = WALLET_RPC_ERROR_CODE_WRONG_URI;
3201 er.message = std::string("Cannot make URI from supplied parameters: ") + error;
3202 return false;
3203 }
3204
3205 res.uri = uri;
3206 return true;
3207 }
3208 //------------------------------------------------------------------------------------------------------------------------------
3209 bool wallet_rpc_server::on_parse_uri(const wallet_rpc::COMMAND_RPC_PARSE_URI::request& req, wallet_rpc::COMMAND_RPC_PARSE_URI::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3210 {
3211 if (!m_wallet) return not_open(er);
3212 std::string error;
3213 if (!m_wallet->parse_uri(req.uri, res.uri.address, res.uri.payment_id, res.uri.amount, res.uri.tx_description, res.uri.recipient_name, res.unknown_parameters, error))
3214 {
3215 er.code = WALLET_RPC_ERROR_CODE_WRONG_URI;
3216 er.message = "Error parsing URI: " + error;
3217 return false;
3218 }
3219 return true;
3220 }
3221 //------------------------------------------------------------------------------------------------------------------------------
3222 bool wallet_rpc_server::on_get_address_book(const wallet_rpc::COMMAND_RPC_GET_ADDRESS_BOOK_ENTRY::request& req, wallet_rpc::COMMAND_RPC_GET_ADDRESS_BOOK_ENTRY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3223 {
3224 if (!m_wallet) return not_open(er);
3225 CHECK_IF_BACKGROUND_SYNCING();
3226 const auto ab = m_wallet->get_address_book();
3227 if (req.entries.empty())
3228 {
3229 uint64_t idx = 0;
3230 for (const auto &entry: ab)
3231 {
3232 std::string address;
3233 if (entry.m_has_payment_id)
3234 address = cryptonote::get_account_integrated_address_as_str(m_wallet->nettype(), entry.m_address, entry.m_payment_id);
3235 else
3236 address = get_account_address_as_str(m_wallet->nettype(), entry.m_is_subaddress, entry.m_address);
3237 res.entries.push_back(wallet_rpc::COMMAND_RPC_GET_ADDRESS_BOOK_ENTRY::entry{idx++, address, entry.m_description});
3238 }
3239 }
3240 else
3241 {
3242 for (uint64_t idx: req.entries)
3243 {
3244 if (idx >= ab.size())
3245 {
3246 er.code = WALLET_RPC_ERROR_CODE_WRONG_INDEX;
3247 er.message = "Index out of range: " + std::to_string(idx);
3248 return false;
3249 }
3250 const auto &entry = ab[idx];
3251 std::string address;
3252 if (entry.m_has_payment_id)
3253 address = cryptonote::get_account_integrated_address_as_str(m_wallet->nettype(), entry.m_address, entry.m_payment_id);
3254 else
3255 address = get_account_address_as_str(m_wallet->nettype(), entry.m_is_subaddress, entry.m_address);
3256 res.entries.push_back(wallet_rpc::COMMAND_RPC_GET_ADDRESS_BOOK_ENTRY::entry{idx, address, entry.m_description});
3257 }
3258 }
3259 return true;
3260 }
3261 //------------------------------------------------------------------------------------------------------------------------------
3262 bool wallet_rpc_server::on_add_address_book(const wallet_rpc::COMMAND_RPC_ADD_ADDRESS_BOOK_ENTRY::request& req, wallet_rpc::COMMAND_RPC_ADD_ADDRESS_BOOK_ENTRY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3263 {
3264 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3265
3266 cryptonote::address_parse_info info;
3267 er.message = "";
3268 if(!get_account_address_from_str_or_url(info, m_wallet->nettype(), req.address,
3269 [&er](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)->std::string {
3270 if (!dnssec_valid)
3271 {
3272 er.message = std::string("Invalid DNSSEC for ") + url;
3273 return {};
3274 }
3275 if (addresses.empty())
3276 {
3277 er.message = std::string("No Monero address found at ") + url;
3278 return {};
3279 }
3280 return addresses[0];
3281 }))
3282 {
3283 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
3284 if (er.message.empty())
3285 er.message = std::string("WALLET_RPC_ERROR_CODE_WRONG_ADDRESS: ") + req.address;
3286 return false;
3287 }
3288 if (!m_wallet->add_address_book_row(info.address, info.has_payment_id ? &info.payment_id : NULL, req.description, info.is_subaddress))
3289 {
3290 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3291 er.message = "Failed to add address book entry";
3292 return false;
3293 }
3294 res.index = m_wallet->get_address_book().size() - 1;
3295 return true;
3296 }
3297 //------------------------------------------------------------------------------------------------------------------------------
3298 bool wallet_rpc_server::on_edit_address_book(const wallet_rpc::COMMAND_RPC_EDIT_ADDRESS_BOOK_ENTRY::request& req, wallet_rpc::COMMAND_RPC_EDIT_ADDRESS_BOOK_ENTRY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3299 {
3300 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3301
3302 const auto ab = m_wallet->get_address_book();
3303 if (req.index >= ab.size())
3304 {
3305 er.code = WALLET_RPC_ERROR_CODE_WRONG_INDEX;
3306 er.message = "Index out of range: " + std::to_string(req.index);
3307 return false;
3308 }
3309
3310 tools::wallet2::address_book_row entry = ab[req.index];
3311
3312 cryptonote::address_parse_info info;
3313 if (req.set_address)
3314 {
3315 er.message = "";
3316 if(!get_account_address_from_str_or_url(info, m_wallet->nettype(), req.address,
3317 [&er](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)->std::string {
3318 if (!dnssec_valid)
3319 {
3320 er.message = std::string("Invalid DNSSEC for ") + url;
3321 return {};
3322 }
3323 if (addresses.empty())
3324 {
3325 er.message = std::string("No Monero address found at ") + url;
3326 return {};
3327 }
3328 return addresses[0];
3329 }))
3330 {
3331 er.code = WALLET_RPC_ERROR_CODE_WRONG_ADDRESS;
3332 if (er.message.empty())
3333 er.message = std::string("WALLET_RPC_ERROR_CODE_WRONG_ADDRESS: ") + req.address;
3334 return false;
3335 }
3336 entry.m_address = info.address;
3337 entry.m_is_subaddress = info.is_subaddress;
3338 if (info.has_payment_id)
3339 entry.m_payment_id = info.payment_id;
3340 }
3341
3342 if (req.set_description)
3343 entry.m_description = req.description;
3344
3345 if (!m_wallet->set_address_book_row(req.index, entry.m_address, req.set_address && entry.m_has_payment_id ? &entry.m_payment_id : NULL, entry.m_description, entry.m_is_subaddress))
3346 {
3347 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3348 er.message = "Failed to edit address book entry";
3349 return false;
3350 }
3351 return true;
3352 }
3353 //------------------------------------------------------------------------------------------------------------------------------
3354 bool wallet_rpc_server::on_delete_address_book(const wallet_rpc::COMMAND_RPC_DELETE_ADDRESS_BOOK_ENTRY::request& req, wallet_rpc::COMMAND_RPC_DELETE_ADDRESS_BOOK_ENTRY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3355 {
3356 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3357
3358 const auto ab = m_wallet->get_address_book();
3359 if (req.index >= ab.size())
3360 {
3361 er.code = WALLET_RPC_ERROR_CODE_WRONG_INDEX;
3362 er.message = "Index out of range: " + std::to_string(req.index);
3363 return false;
3364 }
3365 if (!m_wallet->delete_address_book_row(req.index))
3366 {
3367 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3368 er.message = "Failed to delete address book entry";
3369 return false;
3370 }
3371 return true;
3372 }
3373 //------------------------------------------------------------------------------------------------------------------------------
3374 bool wallet_rpc_server::on_refresh(const wallet_rpc::COMMAND_RPC_REFRESH::request& req, wallet_rpc::COMMAND_RPC_REFRESH::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3375 {
3376 if (m_restricted)
3377 {
3378 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3379 er.message = "Command unavailable in restricted mode.";
3380 return false;
3381 }
3382 if (!m_wallet) return not_open(er);
3383 try
3384 {
3385 m_wallet->refresh(m_wallet->is_trusted_daemon(), req.start_height, res.blocks_fetched, res.received_money);
3386 return true;
3387 }
3388 catch (const std::exception& e)
3389 {
3390 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3391 return false;
3392 }
3393 return true;
3394 }
3395 //------------------------------------------------------------------------------------------------------------------------------
3396 bool wallet_rpc_server::on_auto_refresh(const wallet_rpc::COMMAND_RPC_AUTO_REFRESH::request& req, wallet_rpc::COMMAND_RPC_AUTO_REFRESH::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3397 {
3398 if (m_restricted)
3399 {
3400 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3401 er.message = "Command unavailable in restricted mode.";
3402 return false;
3403 }
3404 try
3405 {
3406 const auto new_period = req.enable ? req.period ? req.period : DEFAULT_AUTO_REFRESH_PERIOD : 0;
3407 m_auto_refresh_period.store(new_period, std::memory_order_relaxed);
3408 MINFO("Auto refresh now " << (new_period ? std::to_string(new_period) + " seconds" : std::string("disabled")));
3409 return true;
3410 }
3411 catch (const std::exception& e)
3412 {
3413 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3414 return false;
3415 }
3416 return true;
3417 }
3418 //------------------------------------------------------------------------------------------------------------------------------
3419 bool wallet_rpc_server::on_scan_tx(const wallet_rpc::COMMAND_RPC_SCAN_TX::request& req, wallet_rpc::COMMAND_RPC_SCAN_TX::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3420 {
3421 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3422
3423 std::unordered_set<crypto::hash> txids;
3424 std::list<std::string>::const_iterator i = req.txids.begin();
3425 while (i != req.txids.end())
3426 {
3427 cryptonote::blobdata txid_blob;
3428 if(!epee::string_tools::parse_hexstr_to_binbuff(*i++, txid_blob) || txid_blob.size() != sizeof(crypto::hash))
3429 {
3430 er.code = WALLET_RPC_ERROR_CODE_WRONG_TXID;
3431 er.message = "TX ID has invalid format";
3432 return false;
3433 }
3434
3435 crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_blob.data());
3436 txids.insert(txid);
3437 }
3438
3439 try {
3440 m_wallet->scan_tx(txids);
3441 } catch (const tools::error::wont_reprocess_recent_txs_via_untrusted_daemon &e) {
3442 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3443 er.message = e.what() + std::string(". Either connect to a trusted daemon or rescan the chain.");
3444 return false;
3445 } catch (const std::exception &e) {
3446 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3447 return false;
3448 }
3449 return true;
3450 }
3451 //------------------------------------------------------------------------------------------------------------------------------
3452 bool wallet_rpc_server::on_rescan_spent(const wallet_rpc::COMMAND_RPC_RESCAN_SPENT::request& req, wallet_rpc::COMMAND_RPC_RESCAN_SPENT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3453 {
3454 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3455 try
3456 {
3457 m_wallet->rescan_spent();
3458 return true;
3459 }
3460 catch (const std::exception& e)
3461 {
3462 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3463 return false;
3464 }
3465 return true;
3466 }
3467 //------------------------------------------------------------------------------------------------------------------------------
3468 bool wallet_rpc_server::on_start_mining(const wallet_rpc::COMMAND_RPC_START_MINING::request& req, wallet_rpc::COMMAND_RPC_START_MINING::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3469 {
3470 if (m_restricted)
3471 {
3472 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3473 er.message = "Command unavailable in restricted mode.";
3474 return false;
3475 }
3476 if (!m_wallet) return not_open(er);
3477 if (!m_wallet->is_trusted_daemon())
3478 {
3479 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3480 er.message = "This command requires a trusted daemon.";
3481 return false;
3482 }
3483
3484 size_t max_mining_threads_count = (std::max)(tools::get_max_concurrency(), static_cast<unsigned>(2));
3485 if (req.threads_count < 1 || max_mining_threads_count < req.threads_count)
3486 {
3487 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3488 er.message = "The specified number of threads is inappropriate.";
3489 return false;
3490 }
3491
3492 cryptonote::COMMAND_RPC_START_MINING::request daemon_req = AUTO_VAL_INIT(daemon_req);
3493 daemon_req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
3494 daemon_req.threads_count = req.threads_count;
3495 daemon_req.do_background_mining = req.do_background_mining;
3496 daemon_req.ignore_battery = req.ignore_battery;
3497
3498 cryptonote::COMMAND_RPC_START_MINING::response daemon_res;
3499 bool r = m_wallet->invoke_http_json("/start_mining", daemon_req, daemon_res);
3500 if (!r || daemon_res.status != CORE_RPC_STATUS_OK)
3501 {
3502 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3503 er.message = "Couldn't start mining due to unknown error.";
3504 return false;
3505 }
3506 return true;
3507 }
3508 //------------------------------------------------------------------------------------------------------------------------------
3509 bool wallet_rpc_server::on_stop_mining(const wallet_rpc::COMMAND_RPC_STOP_MINING::request& req, wallet_rpc::COMMAND_RPC_STOP_MINING::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3510 {
3511 if (m_restricted)
3512 {
3513 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3514 er.message = "Command unavailable in restricted mode.";
3515 return false;
3516 }
3517 if (!m_wallet) return not_open(er);
3518 cryptonote::COMMAND_RPC_STOP_MINING::request daemon_req;
3519 cryptonote::COMMAND_RPC_STOP_MINING::response daemon_res;
3520 bool r = m_wallet->invoke_http_json("/stop_mining", daemon_req, daemon_res);
3521 if (!r || daemon_res.status != CORE_RPC_STATUS_OK)
3522 {
3523 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3524 er.message = "Couldn't stop mining due to unknown error.";
3525 return false;
3526 }
3527 return true;
3528 }
3529 //------------------------------------------------------------------------------------------------------------------------------
3530 bool wallet_rpc_server::on_get_languages(const wallet_rpc::COMMAND_RPC_GET_LANGUAGES::request& req, wallet_rpc::COMMAND_RPC_GET_LANGUAGES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3531 {
3532 crypto::ElectrumWords::get_language_list(res.languages, true);
3533 crypto::ElectrumWords::get_language_list(res.languages_local, false);
3534 return true;
3535 }
3536 //------------------------------------------------------------------------------------------------------------------------------
3537 bool wallet_rpc_server::on_create_wallet(const wallet_rpc::COMMAND_RPC_CREATE_WALLET::request& req, wallet_rpc::COMMAND_RPC_CREATE_WALLET::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3538 {
3539 if (m_restricted)
3540 {
3541 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3542 er.message = "Command unavailable in restricted mode.";
3543 return false;
3544 }
3545 if (m_wallet_dir.empty())
3546 {
3547 er.code = WALLET_RPC_ERROR_CODE_NO_WALLET_DIR;
3548 er.message = "No wallet dir configured";
3549 return false;
3550 }
3551
3552 namespace po = boost::program_options;
3553 po::variables_map vm2;
3554 const char *ptr = strchr(req.filename.c_str(), '/');
3555 #ifdef _WIN32
3556 if (!ptr)
3557 ptr = strchr(req.filename.c_str(), '\\');
3558 if (!ptr)
3559 ptr = strchr(req.filename.c_str(), ':');
3560 #endif
3561 if (ptr)
3562 {
3563 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3564 er.message = "Invalid filename";
3565 return false;
3566 }
3567 std::string wallet_file = req.filename.empty() ? "" : (m_wallet_dir + "/" + req.filename);
3568 {
3569 if (!crypto::ElectrumWords::is_valid_language(req.language))
3570 {
3571 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3572 er.message = "Unknown language: " + req.language;
3573 return false;
3574 }
3575 }
3576 {
3577 po::options_description desc("dummy");
3578 const command_line::arg_descriptor<std::string, true> arg_password = {"password", "password"};
3579 const char *argv[4];
3580 int argc = 3;
3581 argv[0] = "wallet-rpc";
3582 argv[1] = "--password";
3583 argv[2] = req.password.c_str();
3584 argv[3] = NULL;
3585 vm2 = *m_vm;
3586 command_line::add_arg(desc, arg_password);
3587 po::store(po::parse_command_line(argc, argv, desc), vm2);
3588 }
3589 std::unique_ptr<tools::wallet2> wal = tools::wallet2::make_new(vm2, true, nullptr).first;
3590 if (!wal)
3591 {
3592 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3593 er.message = "Failed to create wallet";
3594 return false;
3595 }
3596 wal->set_seed_language(req.language);
3597 cryptonote::COMMAND_RPC_GET_HEIGHT::request hreq;
3598 cryptonote::COMMAND_RPC_GET_HEIGHT::response hres;
3599 hres.height = 0;
3600 bool r = wal->invoke_http_json("/getheight", hreq, hres);
3601 if (r)
3602 wal->set_refresh_from_block_height(hres.height);
3603 crypto::secret_key dummy_key;
3604 try {
3605 wal->generate(wallet_file, req.password, dummy_key, false, false);
3606 }
3607 catch (const std::exception& e)
3608 {
3609 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3610 return false;
3611 }
3612 if (!wal)
3613 {
3614 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3615 er.message = "Failed to generate wallet";
3616 return false;
3617 }
3618
3619 if (m_wallet)
3620 {
3621 try
3622 {
3623 m_wallet->store();
3624 }
3625 catch (const std::exception& e)
3626 {
3627 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3628 return false;
3629 }
3630 delete m_wallet;
3631 }
3632 m_wallet = wal.release();
3633 return true;
3634 }
3635 //------------------------------------------------------------------------------------------------------------------------------
3636 bool wallet_rpc_server::on_open_wallet(const wallet_rpc::COMMAND_RPC_OPEN_WALLET::request& req, wallet_rpc::COMMAND_RPC_OPEN_WALLET::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3637 {
3638 if (m_restricted)
3639 {
3640 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3641 er.message = "Command unavailable in restricted mode.";
3642 return false;
3643 }
3644 if (m_wallet_dir.empty())
3645 {
3646 er.code = WALLET_RPC_ERROR_CODE_NO_WALLET_DIR;
3647 er.message = "No wallet dir configured";
3648 return false;
3649 }
3650
3651 namespace po = boost::program_options;
3652 po::variables_map vm2;
3653 const char *ptr = strchr(req.filename.c_str(), '/');
3654 #ifdef _WIN32
3655 if (!ptr)
3656 ptr = strchr(req.filename.c_str(), '\\');
3657 if (!ptr)
3658 ptr = strchr(req.filename.c_str(), ':');
3659 #endif
3660 if (ptr)
3661 {
3662 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3663 er.message = "Invalid filename";
3664 return false;
3665 }
3666 if (m_wallet && req.autosave_current)
3667 {
3668 try
3669 {
3670 m_wallet->store();
3671 }
3672 catch (const std::exception& e)
3673 {
3674 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3675 return false;
3676 }
3677 }
3678 std::string wallet_file = m_wallet_dir + "/" + req.filename;
3679 {
3680 po::options_description desc("dummy");
3681 const command_line::arg_descriptor<std::string, true> arg_password = {"password", "password"};
3682 const char *argv[4];
3683 int argc = 3;
3684 argv[0] = "wallet-rpc";
3685 argv[1] = "--password";
3686 argv[2] = req.password.c_str();
3687 argv[3] = NULL;
3688 vm2 = *m_vm;
3689 command_line::add_arg(desc, arg_password);
3690 po::store(po::parse_command_line(argc, argv, desc), vm2);
3691 }
3692 std::unique_ptr<tools::wallet2> wal = nullptr;
3693 try {
3694 wal = tools::wallet2::make_from_file(vm2, true, wallet_file, nullptr).first;
3695 }
3696 catch (const std::exception& e)
3697 {
3698 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3699 }
3700 if (!wal)
3701 {
3702 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3703 er.message = "Failed to open wallet : " + (!er.message.empty() ? er.message : "Unknown.");
3704 return false;
3705 }
3706
3707 if (m_wallet)
3708 delete m_wallet;
3709 m_wallet = wal.release();
3710 return true;
3711 }
3712 //------------------------------------------------------------------------------------------------------------------------------
3713 bool wallet_rpc_server::on_close_wallet(const wallet_rpc::COMMAND_RPC_CLOSE_WALLET::request& req, wallet_rpc::COMMAND_RPC_CLOSE_WALLET::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3714 {
3715 if (m_restricted)
3716 {
3717 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3718 er.message = "Command unavailable in restricted mode.";
3719 return false;
3720 }
3721 if (!m_wallet) return not_open(er);
3722
3723 if (req.autosave_current)
3724 {
3725 try
3726 {
3727 m_wallet->store();
3728 }
3729 catch (const std::exception& e)
3730 {
3731 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3732 return false;
3733 }
3734 }
3735 delete m_wallet;
3736 m_wallet = NULL;
3737 return true;
3738 }
3739 //------------------------------------------------------------------------------------------------------------------------------
3740 bool wallet_rpc_server::on_change_wallet_password(const wallet_rpc::COMMAND_RPC_CHANGE_WALLET_PASSWORD::request& req, wallet_rpc::COMMAND_RPC_CHANGE_WALLET_PASSWORD::response& res, epee::json_rpc::error& er, const connection_context *ctx)
3741 {
3742 CHECK_IF_RESTRICTED_BACKGROUND_SYNCING();
3743 if (m_wallet->verify_password(req.old_password))
3744 {
3745 try
3746 {
3747 m_wallet->change_password(m_wallet->get_wallet_file(), req.old_password, req.new_password);
3748 LOG_PRINT_L0("Wallet password changed.");
3749 }
3750 catch (const std::exception& e)
3751 {
3752 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3753 return false;
3754 }
3755 }
3756 else
3757 {
3758 er.code = WALLET_RPC_ERROR_CODE_INVALID_PASSWORD;
3759 er.message = "Invalid original password.";
3760 return false;
3761 }
3762 return true;
3763 }
3764 //------------------------------------------------------------------------------------------------------------------------------
3765 void wallet_rpc_server::handle_rpc_exception(const std::exception_ptr& e, epee::json_rpc::error& er, int default_error_code) {
3766 try
3767 {
3768 std::rethrow_exception(e);
3769 }
3770 catch (const tools::error::no_connection_to_daemon& e)
3771 {
3772 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
3773 er.message = e.what();
3774 }
3775 catch (const tools::error::daemon_busy& e)
3776 {
3777 er.code = WALLET_RPC_ERROR_CODE_DAEMON_IS_BUSY;
3778 er.message = e.what();
3779 }
3780 catch (const tools::error::zero_amount& e)
3781 {
3782 er.code = WALLET_RPC_ERROR_CODE_ZERO_AMOUNT;
3783 er.message = e.what();
3784 }
3785 catch (const tools::error::zero_destination& e)
3786 {
3787 er.code = WALLET_RPC_ERROR_CODE_ZERO_DESTINATION;
3788 er.message = e.what();
3789 }
3790 catch (const tools::error::not_enough_money& e)
3791 {
3792 er.code = WALLET_RPC_ERROR_CODE_NOT_ENOUGH_MONEY;
3793 er.message = e.what();
3794 }
3795 catch (const tools::error::not_enough_unlocked_money& e)
3796 {
3797 er.code = WALLET_RPC_ERROR_CODE_NOT_ENOUGH_UNLOCKED_MONEY;
3798 er.message = e.what();
3799 }
3800 catch (const tools::error::tx_not_possible& e)
3801 {
3802 er.code = WALLET_RPC_ERROR_CODE_TX_NOT_POSSIBLE;
3803 er.message = (boost::format(tr("Transaction not possible. Available only %s, transaction amount %s = %s + %s (fee)")) %
3804 cryptonote::print_money(e.available()) %
3805 cryptonote::print_money(e.tx_amount() + e.fee()) %
3806 cryptonote::print_money(e.tx_amount()) %
3807 cryptonote::print_money(e.fee())).str();
3808 er.message = e.what();
3809 }
3810 catch (const tools::error::not_enough_outs_to_mix& e)
3811 {
3812 er.code = WALLET_RPC_ERROR_CODE_NOT_ENOUGH_OUTS_TO_MIX;
3813 er.message = e.what() + std::string(" Please use sweep_dust.");
3814 }
3815 catch (const error::file_exists& e)
3816 {
3817 er.code = WALLET_RPC_ERROR_CODE_WALLET_ALREADY_EXISTS;
3818 er.message = "Cannot create wallet. Already exists.";
3819 }
3820 catch (const error::invalid_password& e)
3821 {
3822 er.code = WALLET_RPC_ERROR_CODE_INVALID_PASSWORD;
3823 er.message = "Invalid password.";
3824 }
3825 catch (const error::account_index_outofbound& e)
3826 {
3827 er.code = WALLET_RPC_ERROR_CODE_ACCOUNT_INDEX_OUT_OF_BOUNDS;
3828 er.message = e.what();
3829 }
3830 catch (const error::address_index_outofbound& e)
3831 {
3832 er.code = WALLET_RPC_ERROR_CODE_ADDRESS_INDEX_OUT_OF_BOUNDS;
3833 er.message = e.what();
3834 }
3835 catch (const error::signature_check_failed& e)
3836 {
3837 er.code = WALLET_RPC_ERROR_CODE_WRONG_SIGNATURE;
3838 er.message = e.what();
3839 }
3840 catch (const std::exception& e)
3841 {
3842 er.code = default_error_code;
3843 er.message = e.what();
3844 }
3845 catch (...)
3846 {
3847 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3848 er.message = "WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR";
3849 }
3850 }
3851 //------------------------------------------------------------------------------------------------------------------------------
3852 bool wallet_rpc_server::on_generate_from_keys(const wallet_rpc::COMMAND_RPC_GENERATE_FROM_KEYS::request &req, wallet_rpc::COMMAND_RPC_GENERATE_FROM_KEYS::response &res, epee::json_rpc::error &er, const connection_context *ctx)
3853 {
3854 if (m_restricted)
3855 {
3856 er.code = WALLET_RPC_ERROR_CODE_DENIED;
3857 er.message = "Command unavailable in restricted mode.";
3858 return false;
3859 }
3860 if (m_wallet_dir.empty())
3861 {
3862 er.code = WALLET_RPC_ERROR_CODE_NO_WALLET_DIR;
3863 er.message = "No wallet dir configured";
3864 return false;
3865 }
3866
3867 // early check for mandatory fields
3868 if (req.viewkey.empty())
3869 {
3870 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3871 er.message = "field 'viewkey' is mandatory. Please provide a view key you want to restore from.";
3872 return false;
3873 }
3874 if (req.address.empty())
3875 {
3876 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3877 er.message = "field 'address' is mandatory. Please provide a public address.";
3878 return false;
3879 }
3880
3881 namespace po = boost::program_options;
3882 po::variables_map vm2;
3883 const char *ptr = strchr(req.filename.c_str(), '/');
3884 #ifdef _WIN32
3885 if (!ptr)
3886 ptr = strchr(req.filename.c_str(), '\\');
3887 if (!ptr)
3888 ptr = strchr(req.filename.c_str(), ':');
3889 #endif
3890 if (ptr)
3891 {
3892 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3893 er.message = "Invalid filename";
3894 return false;
3895 }
3896 std::string wallet_file = req.filename.empty() ? "" : (m_wallet_dir + "/" + req.filename);
3897 // check if wallet file already exists
3898 if (!wallet_file.empty())
3899 {
3900 try
3901 {
3902 boost::system::error_code ignored_ec;
3903 THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(wallet_file, ignored_ec), error::file_exists, wallet_file);
3904 }
3905 catch (const std::exception &e)
3906 {
3907 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3908 er.message = "Wallet already exists.";
3909 return false;
3910 }
3911 }
3912
3913 {
3914 po::options_description desc("dummy");
3915 const command_line::arg_descriptor<std::string, true> arg_password = {"password", "password"};
3916 const char *argv[4];
3917 int argc = 3;
3918 argv[0] = "wallet-rpc";
3919 argv[1] = "--password";
3920 argv[2] = req.password.c_str();
3921 argv[3] = NULL;
3922 vm2 = *m_vm;
3923 command_line::add_arg(desc, arg_password);
3924 po::store(po::parse_command_line(argc, argv, desc), vm2);
3925 }
3926
3927 auto rc = tools::wallet2::make_new(vm2, true, nullptr);
3928 std::unique_ptr<wallet2> wal;
3929 wal = std::move(rc.first);
3930 if (!wal)
3931 {
3932 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3933 er.message = "Failed to create wallet";
3934 return false;
3935 }
3936
3937 cryptonote::address_parse_info info;
3938 if(!get_account_address_from_str(info, wal->nettype(), req.address))
3939 {
3940 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3941 er.message = "Failed to parse public address";
3942 return false;
3943 }
3944
3945 epee::wipeable_string password = rc.second.password();
3946 epee::wipeable_string viewkey_string = req.viewkey;
3947 crypto::secret_key viewkey;
3948 if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
3949 {
3950 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3951 er.message = "Failed to parse view key secret key";
3952 return false;
3953 }
3954
3955 if (m_wallet && req.autosave_current)
3956 {
3957 try
3958 {
3959 if (!wallet_file.empty())
3960 m_wallet->store();
3961 }
3962 catch (const std::exception &e)
3963 {
3964 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3965 return false;
3966 }
3967 }
3968
3969 try
3970 {
3971 if (!req.spendkey.empty())
3972 {
3973 epee::wipeable_string spendkey_string = req.spendkey;
3974 crypto::secret_key spendkey;
3975 if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey))))
3976 {
3977 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
3978 er.message = "Failed to parse spend key secret key";
3979 return false;
3980 }
3981 wal->generate(wallet_file, std::move(rc.second).password(), info.address, spendkey, viewkey, false);
3982 res.info = "Wallet has been generated successfully.";
3983 }
3984 else
3985 {
3986 wal->generate(wallet_file, std::move(rc.second).password(), info.address, viewkey, false);
3987 res.info = "Watch-only wallet has been generated successfully.";
3988 }
3989 MINFO("Wallet has been generated.\n");
3990 }
3991 catch (const std::exception &e)
3992 {
3993 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
3994 return false;
3995 }
3996
3997 if (!wal)
3998 {
3999 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4000 er.message = "Failed to generate wallet";
4001 return false;
4002 }
4003
4004 if (!req.language.empty())
4005 {
4006 if (!crypto::ElectrumWords::is_valid_language(req.language))
4007 {
4008 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4009 er.message = "The specified seed language is invalid.";
4010 return false;
4011 }
4012 wal->set_seed_language(req.language);
4013 }
4014
4015 // set blockheight if given
4016 try
4017 {
4018 wal->set_refresh_from_block_height(req.restore_height);
4019 wal->rewrite(wallet_file, password);
4020 }
4021 catch (const std::exception &e)
4022 {
4023 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
4024 return false;
4025 }
4026
4027 if (m_wallet)
4028 delete m_wallet;
4029 m_wallet = wal.release();
4030 res.address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
4031 return true;
4032 }
4033 //------------------------------------------------------------------------------------------------------------------------------
4034 bool wallet_rpc_server::on_restore_deterministic_wallet(const wallet_rpc::COMMAND_RPC_RESTORE_DETERMINISTIC_WALLET::request &req, wallet_rpc::COMMAND_RPC_RESTORE_DETERMINISTIC_WALLET::response &res, epee::json_rpc::error &er, const connection_context *ctx)
4035 {
4036 if (m_restricted)
4037 {
4038 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4039 er.message = "Command unavailable in restricted mode.";
4040 return false;
4041 }
4042 if (m_wallet_dir.empty())
4043 {
4044 er.code = WALLET_RPC_ERROR_CODE_NO_WALLET_DIR;
4045 er.message = "No wallet dir configured";
4046 return false;
4047 }
4048
4049 // early check for mandatory fields
4050 if (req.seed.empty())
4051 {
4052 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4053 er.message = "field 'seed' is mandatory. Please provide a seed you want to restore from.";
4054 return false;
4055 }
4056
4057 namespace po = boost::program_options;
4058 po::variables_map vm2;
4059 const char *ptr = strchr(req.filename.c_str(), '/');
4060 #ifdef _WIN32
4061 if (!ptr)
4062 ptr = strchr(req.filename.c_str(), '\\');
4063 if (!ptr)
4064 ptr = strchr(req.filename.c_str(), ':');
4065 #endif
4066 if (ptr)
4067 {
4068 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4069 er.message = "Invalid filename";
4070 return false;
4071 }
4072 std::string wallet_file = req.filename.empty() ? "" : (m_wallet_dir + "/" + req.filename);
4073 // check if wallet file already exists
4074 if (!wallet_file.empty())
4075 {
4076 try
4077 {
4078 boost::system::error_code ignored_ec;
4079 THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(wallet_file, ignored_ec), error::file_exists, wallet_file);
4080 }
4081 catch (const std::exception &e)
4082 {
4083 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4084 er.message = "Wallet already exists.";
4085 return false;
4086 }
4087 }
4088 crypto::secret_key recovery_key;
4089 std::string old_language;
4090
4091 // check the given seed
4092 if (!req.enable_multisig_experimental) {
4093 if (!crypto::ElectrumWords::words_to_bytes(req.seed, recovery_key, old_language))
4094 {
4095 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4096 er.message = "Electrum-style word list failed verification";
4097 return false;
4098 }
4099 }
4100 if (m_wallet && req.autosave_current)
4101 {
4102 try
4103 {
4104 m_wallet->store();
4105 }
4106 catch (const std::exception &e)
4107 {
4108 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
4109 return false;
4110 }
4111 }
4112
4113 // process seed_offset if given
4114 {
4115 if (req.enable_multisig_experimental && !req.seed_offset.empty())
4116 {
4117 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4118 er.message = "Multisig seeds are not compatible with seed offsets";
4119 return false;
4120 }
4121
4122 if (!req.seed_offset.empty())
4123 {
4124 recovery_key = cryptonote::decrypt_key(recovery_key, req.seed_offset);
4125 }
4126 }
4127 {
4128 po::options_description desc("dummy");
4129 const command_line::arg_descriptor<std::string, true> arg_password = {"password", "password"};
4130 const char *argv[4];
4131 int argc = 3;
4132 argv[0] = "wallet-rpc";
4133 argv[1] = "--password";
4134 argv[2] = req.password.c_str();
4135 argv[3] = NULL;
4136 vm2 = *m_vm;
4137 command_line::add_arg(desc, arg_password);
4138 po::store(po::parse_command_line(argc, argv, desc), vm2);
4139 }
4140
4141 auto rc = tools::wallet2::make_new(vm2, true, nullptr);
4142 std::unique_ptr<wallet2> wal;
4143 wal = std::move(rc.first);
4144 if (!wal)
4145 {
4146 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4147 er.message = "Failed to create wallet";
4148 return false;
4149 }
4150
4151 epee::wipeable_string password = rc.second.password();
4152
4153 bool was_deprecated_wallet = ((old_language == crypto::ElectrumWords::old_language_name) ||
4154 crypto::ElectrumWords::get_is_old_style_seed(req.seed));
4155
4156 std::string mnemonic_language = old_language;
4157 if (was_deprecated_wallet)
4158 {
4159 // The user had used an older version of the wallet with old style mnemonics.
4160 res.was_deprecated = true;
4161 }
4162
4163 if (old_language == crypto::ElectrumWords::old_language_name)
4164 {
4165 if (req.language.empty())
4166 {
4167 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4168 er.message = "Wallet was using the old seed language. You need to specify a new seed language.";
4169 return false;
4170 }
4171 if (!crypto::ElectrumWords::is_valid_language(req.language))
4172 {
4173 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4174 er.message = "Wallet was using the old seed language, and the specified new seed language is invalid.";
4175 return false;
4176 }
4177 mnemonic_language = req.language;
4178 }
4179
4180 wal->set_seed_language(mnemonic_language);
4181
4182 crypto::secret_key recovery_val;
4183 try
4184 {
4185 if (req.enable_multisig_experimental)
4186 {
4187 // Parse multisig seed into raw multisig data
4188 epee::wipeable_string multisig_data;
4189 multisig_data.resize(req.seed.size() / 2);
4190 if (!epee::from_hex::to_buffer(epee::to_mut_byte_span(multisig_data), req.seed))
4191 {
4192 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4193 er.message = "Multisig seed not represented as hexadecimal string";
4194 return false;
4195 }
4196
4197 // Generate multisig wallet
4198 wal->generate(wallet_file, std::move(rc.second).password(), multisig_data, false);
4199 wal->enable_multisig(true);
4200 }
4201 else
4202 {
4203 // Generate normal wallet
4204 recovery_val = wal->generate(wallet_file, std::move(rc.second).password(), recovery_key, true, false, false);
4205 }
4206 MINFO("Wallet has been restored.\n");
4207 }
4208 catch (const std::exception &e)
4209 {
4210 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
4211 return false;
4212 }
4213
4214 // // Convert the secret key back to seed
4215 epee::wipeable_string electrum_words;
4216 if (!req.enable_multisig_experimental && !crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language))
4217 {
4218 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4219 er.message = "Failed to encode seed";
4220 return false;
4221 }
4222 res.seed = std::string(electrum_words.data(), electrum_words.size());
4223
4224 if (!wal)
4225 {
4226 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4227 er.message = "Failed to generate wallet";
4228 return false;
4229 }
4230
4231 // set blockheight if given
4232 try
4233 {
4234 wal->set_refresh_from_block_height(req.restore_height);
4235 wal->rewrite(wallet_file, password);
4236 }
4237 catch (const std::exception &e)
4238 {
4239 handle_rpc_exception(std::current_exception(), er, WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR);
4240 return false;
4241 }
4242
4243 if (m_wallet)
4244 delete m_wallet;
4245 m_wallet = wal.release();
4246 res.address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
4247 res.info = "Wallet has been restored successfully.";
4248 return true;
4249 }
4250 //------------------------------------------------------------------------------------------------------------------------------
4251 bool wallet_rpc_server::on_is_multisig(const wallet_rpc::COMMAND_RPC_IS_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_IS_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4252 {
4253 if (!m_wallet) return not_open(er);
4254 res.multisig = m_wallet->multisig(&res.ready, &res.threshold, &res.total);
4255 return true;
4256 }
4257 //------------------------------------------------------------------------------------------------------------------------------
4258 bool wallet_rpc_server::on_prepare_multisig(const wallet_rpc::COMMAND_RPC_PREPARE_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_PREPARE_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4259 {
4260 if (m_restricted)
4261 {
4262 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4263 er.message = "Command unavailable in restricted mode.";
4264 return false;
4265 }
4266 if (!m_wallet) return not_open(er);
4267 if (m_wallet->multisig())
4268 {
4269 er.code = WALLET_RPC_ERROR_CODE_ALREADY_MULTISIG;
4270 er.message = "This wallet is already multisig";
4271 return false;
4272 }
4273 if (req.enable_multisig_experimental)
4274 m_wallet->enable_multisig(true);
4275 CHECK_MULTISIG_ENABLED();
4276 if (m_wallet->watch_only())
4277 {
4278 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
4279 er.message = "wallet is watch-only and cannot be made multisig";
4280 return false;
4281 }
4282 CHECK_IF_BACKGROUND_SYNCING();
4283
4284 res.multisig_info = m_wallet->get_multisig_first_kex_msg();
4285 return true;
4286 }
4287 //------------------------------------------------------------------------------------------------------------------------------
4288 bool wallet_rpc_server::on_make_multisig(const wallet_rpc::COMMAND_RPC_MAKE_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_MAKE_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4289 {
4290 if (m_restricted)
4291 {
4292 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4293 er.message = "Command unavailable in restricted mode.";
4294 return false;
4295 }
4296 if (!m_wallet) return not_open(er);
4297 if (m_wallet->multisig())
4298 {
4299 er.code = WALLET_RPC_ERROR_CODE_ALREADY_MULTISIG;
4300 er.message = "This wallet is already multisig";
4301 return false;
4302 }
4303 CHECK_MULTISIG_ENABLED();
4304 if (m_wallet->watch_only())
4305 {
4306 er.code = WALLET_RPC_ERROR_CODE_WATCH_ONLY;
4307 er.message = "wallet is watch-only and cannot be made multisig";
4308 return false;
4309 }
4310 CHECK_IF_BACKGROUND_SYNCING();
4311
4312 try
4313 {
4314 res.multisig_info = m_wallet->make_multisig(req.password, req.multisig_info, req.threshold);
4315 res.address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
4316 }
4317 catch (const std::exception &e)
4318 {
4319 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4320 er.message = e.what();
4321 return false;
4322 }
4323
4324 return true;
4325 }
4326 //------------------------------------------------------------------------------------------------------------------------------
4327 bool wallet_rpc_server::on_export_multisig(const wallet_rpc::COMMAND_RPC_EXPORT_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_EXPORT_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4328 {
4329 if (m_restricted)
4330 {
4331 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4332 er.message = "Command unavailable in restricted mode.";
4333 return false;
4334 }
4335 if (!m_wallet) return not_open(er);
4336 bool ready;
4337 if (!m_wallet->multisig(&ready))
4338 {
4339 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4340 er.message = "This wallet is not multisig";
4341 return false;
4342 }
4343 if (!ready)
4344 {
4345 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4346 er.message = "This wallet is multisig, but not yet finalized";
4347 return false;
4348 }
4349 CHECK_MULTISIG_ENABLED();
4350
4351 cryptonote::blobdata info;
4352 try
4353 {
4354 info = m_wallet->export_multisig();
4355 }
4356 catch (const std::exception &e)
4357 {
4358 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4359 er.message = e.what();
4360 return false;
4361 }
4362
4363 res.info = epee::string_tools::buff_to_hex_nodelimer(info);
4364
4365 return true;
4366 }
4367 //------------------------------------------------------------------------------------------------------------------------------
4368 bool wallet_rpc_server::on_import_multisig(const wallet_rpc::COMMAND_RPC_IMPORT_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_IMPORT_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4369 {
4370 if (m_restricted)
4371 {
4372 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4373 er.message = "Command unavailable in restricted mode.";
4374 return false;
4375 }
4376 if (!m_wallet) return not_open(er);
4377 bool ready;
4378 uint32_t threshold, total;
4379 if (!m_wallet->multisig(&ready, &threshold, &total))
4380 {
4381 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4382 er.message = "This wallet is not multisig";
4383 return false;
4384 }
4385 if (!ready)
4386 {
4387 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4388 er.message = "This wallet is multisig, but not yet finalized";
4389 return false;
4390 }
4391 CHECK_MULTISIG_ENABLED();
4392
4393 if (req.info.size() < threshold - 1)
4394 {
4395 er.code = WALLET_RPC_ERROR_CODE_THRESHOLD_NOT_REACHED;
4396 er.message = "Needs multisig export info from more participants";
4397 return false;
4398 }
4399
4400 std::vector<cryptonote::blobdata> info;
4401 info.resize(req.info.size());
4402 for (size_t n = 0; n < info.size(); ++n)
4403 {
4404 if (!epee::string_tools::parse_hexstr_to_binbuff(req.info[n], info[n]))
4405 {
4406 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
4407 er.message = "Failed to parse hex.";
4408 return false;
4409 }
4410 }
4411
4412 try
4413 {
4414 res.n_outputs = m_wallet->import_multisig(info, req.refresh_after_import);
4415 }
4416 catch (const std::exception &e)
4417 {
4418 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4419 er.message = std::string{"Error calling import_multisig: "} + e.what();
4420 return false;
4421 }
4422
4423 if (req.refresh_after_import)
4424 {
4425 if (m_wallet->is_trusted_daemon())
4426 {
4427 try
4428 {
4429 m_wallet->rescan_spent();
4430 }
4431 catch (const std::exception &e)
4432 {
4433 er.message = std::string("Success, but failed to update spent status after import multisig info: ") + e.what();
4434 }
4435 }
4436 else
4437 {
4438 er.message = "Success, but cannot update spent status after import multisig info as daemon is untrusted";
4439 }
4440 }
4441
4442 return true;
4443 }
4444 //------------------------------------------------------------------------------------------------------------------------------
4445 bool wallet_rpc_server::on_finalize_multisig(const wallet_rpc::COMMAND_RPC_FINALIZE_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_FINALIZE_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4446 {
4447 CHECK_MULTISIG_ENABLED();
4448 return false;
4449 }
4450 //------------------------------------------------------------------------------------------------------------------------------
4451 bool wallet_rpc_server::on_exchange_multisig_keys(const wallet_rpc::COMMAND_RPC_EXCHANGE_MULTISIG_KEYS::request& req, wallet_rpc::COMMAND_RPC_EXCHANGE_MULTISIG_KEYS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4452 {
4453 if (m_restricted)
4454 {
4455 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4456 er.message = "Command unavailable in restricted mode.";
4457 return false;
4458 }
4459 if (!m_wallet) return not_open(er);
4460 bool ready;
4461 uint32_t threshold, total;
4462 if (!m_wallet->multisig(&ready, &threshold, &total))
4463 {
4464 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4465 er.message = "This wallet is not multisig";
4466 return false;
4467 }
4468 CHECK_MULTISIG_ENABLED();
4469
4470 if (req.multisig_info.size() + 1 < total)
4471 {
4472 er.code = WALLET_RPC_ERROR_CODE_THRESHOLD_NOT_REACHED;
4473 er.message = "Needs multisig info from more participants";
4474 return false;
4475 }
4476
4477 try
4478 {
4479 res.multisig_info = m_wallet->exchange_multisig_keys(req.password, req.multisig_info, req.force_update_use_with_caution);
4480 m_wallet->multisig(&ready);
4481 if (ready)
4482 {
4483 res.address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
4484 }
4485 }
4486 catch (const std::exception &e)
4487 {
4488 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4489 er.message = std::string("Error calling exchange_multisig_info: ") + e.what();
4490 return false;
4491 }
4492 return true;
4493 }
4494 //------------------------------------------------------------------------------------------------------------------------------
4495 bool wallet_rpc_server::on_sign_multisig(const wallet_rpc::COMMAND_RPC_SIGN_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_SIGN_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4496 {
4497 if (m_restricted)
4498 {
4499 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4500 er.message = "Command unavailable in restricted mode.";
4501 return false;
4502 }
4503 if (!m_wallet) return not_open(er);
4504 bool ready;
4505 uint32_t threshold, total;
4506 if (!m_wallet->multisig(&ready, &threshold, &total))
4507 {
4508 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4509 er.message = "This wallet is not multisig";
4510 return false;
4511 }
4512 if (!ready)
4513 {
4514 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4515 er.message = "This wallet is multisig, but not yet finalized";
4516 return false;
4517 }
4518 CHECK_MULTISIG_ENABLED();
4519
4520 cryptonote::blobdata blob;
4521 if (!epee::string_tools::parse_hexstr_to_binbuff(req.tx_data_hex, blob))
4522 {
4523 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
4524 er.message = "Failed to parse hex.";
4525 return false;
4526 }
4527
4528 tools::wallet2::multisig_tx_set txs;
4529 bool r = m_wallet->load_multisig_tx(blob, txs, NULL);
4530 if (!r)
4531 {
4532 er.code = WALLET_RPC_ERROR_CODE_BAD_MULTISIG_TX_DATA;
4533 er.message = "Failed to parse multisig tx data.";
4534 return false;
4535 }
4536
4537 std::vector<crypto::hash> txids;
4538 try
4539 {
4540 bool r = m_wallet->sign_multisig_tx(txs, txids);
4541 if (!r)
4542 {
4543 er.code = WALLET_RPC_ERROR_CODE_MULTISIG_SIGNATURE;
4544 er.message = "Failed to sign multisig tx";
4545 return false;
4546 }
4547 }
4548 catch (const std::exception &e)
4549 {
4550 er.code = WALLET_RPC_ERROR_CODE_MULTISIG_SIGNATURE;
4551 er.message = std::string("Failed to sign multisig tx: ") + e.what();
4552 return false;
4553 }
4554
4555 res.tx_data_hex = epee::string_tools::buff_to_hex_nodelimer(m_wallet->save_multisig_tx(txs));
4556 if (!txids.empty())
4557 {
4558 for (const crypto::hash &txid: txids)
4559 res.tx_hash_list.push_back(epee::string_tools::pod_to_hex(txid));
4560 }
4561
4562 return true;
4563 }
4564 //------------------------------------------------------------------------------------------------------------------------------
4565 bool wallet_rpc_server::on_submit_multisig(const wallet_rpc::COMMAND_RPC_SUBMIT_MULTISIG::request& req, wallet_rpc::COMMAND_RPC_SUBMIT_MULTISIG::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4566 {
4567 if (m_restricted)
4568 {
4569 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4570 er.message = "Command unavailable in restricted mode.";
4571 return false;
4572 }
4573 if (!m_wallet) return not_open(er);
4574 bool ready;
4575 uint32_t threshold, total;
4576 if (!m_wallet->multisig(&ready, &threshold, &total))
4577 {
4578 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4579 er.message = "This wallet is not multisig";
4580 return false;
4581 }
4582 if (!ready)
4583 {
4584 er.code = WALLET_RPC_ERROR_CODE_NOT_MULTISIG;
4585 er.message = "This wallet is multisig, but not yet finalized";
4586 return false;
4587 }
4588 CHECK_MULTISIG_ENABLED();
4589
4590 cryptonote::blobdata blob;
4591 if (!epee::string_tools::parse_hexstr_to_binbuff(req.tx_data_hex, blob))
4592 {
4593 er.code = WALLET_RPC_ERROR_CODE_BAD_HEX;
4594 er.message = "Failed to parse hex.";
4595 return false;
4596 }
4597
4598 tools::wallet2::multisig_tx_set txs;
4599 bool r = m_wallet->load_multisig_tx(blob, txs, NULL);
4600 if (!r)
4601 {
4602 er.code = WALLET_RPC_ERROR_CODE_BAD_MULTISIG_TX_DATA;
4603 er.message = "Failed to parse multisig tx data.";
4604 return false;
4605 }
4606
4607 if (txs.m_signers.size() < threshold)
4608 {
4609 er.code = WALLET_RPC_ERROR_CODE_THRESHOLD_NOT_REACHED;
4610 er.message = "Not enough signers signed this transaction.";
4611 return false;
4612 }
4613
4614 try
4615 {
4616 for (auto &ptx: txs.m_ptx)
4617 {
4618 m_wallet->commit_tx(ptx);
4619 res.tx_hash_list.push_back(epee::string_tools::pod_to_hex(cryptonote::get_transaction_hash(ptx.tx)));
4620 }
4621 }
4622 catch (const std::exception &e)
4623 {
4624 er.code = WALLET_RPC_ERROR_CODE_MULTISIG_SUBMISSION;
4625 er.message = std::string("Failed to submit multisig tx: ") + e.what();
4626 return false;
4627 }
4628
4629 return true;
4630 }
4631 //------------------------------------------------------------------------------------------------------------------------------
4632 bool wallet_rpc_server::on_validate_address(const wallet_rpc::COMMAND_RPC_VALIDATE_ADDRESS::request& req, wallet_rpc::COMMAND_RPC_VALIDATE_ADDRESS::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4633 {
4634 cryptonote::address_parse_info info;
4635 static const struct { cryptonote::network_type type; const char *stype; } net_types[] = {
4636 { cryptonote::MAINNET, "mainnet" },
4637 { cryptonote::TESTNET, "testnet" },
4638 { cryptonote::STAGENET, "stagenet" },
4639 };
4640 if (!req.any_net_type && !m_wallet) return not_open(er);
4641 for (const auto &net_type: net_types)
4642 {
4643 if (!req.any_net_type && (!m_wallet || net_type.type != m_wallet->nettype()))
4644 continue;
4645 if (req.allow_openalias)
4646 {
4647 std::string address;
4648 res.valid = get_account_address_from_str_or_url(info, net_type.type, req.address,
4649 [&er, &address](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)->std::string {
4650 if (!dnssec_valid)
4651 {
4652 er.message = std::string("Invalid DNSSEC for ") + url;
4653 return {};
4654 }
4655 if (addresses.empty())
4656 {
4657 er.message = std::string("No Monero address found at ") + url;
4658 return {};
4659 }
4660 address = addresses[0];
4661 return address;
4662 });
4663 if (res.valid)
4664 res.openalias_address = address;
4665 }
4666 else
4667 {
4668 res.valid = cryptonote::get_account_address_from_str(info, net_type.type, req.address);
4669 }
4670 if (res.valid)
4671 {
4672 res.integrated = info.has_payment_id;
4673 res.subaddress = info.is_subaddress;
4674 res.nettype = net_type.stype;
4675 return true;
4676 }
4677 }
4678
4679 res.valid = false;
4680 return true;
4681 }
4682 //------------------------------------------------------------------------------------------------------------------------------
4683 bool wallet_rpc_server::on_set_daemon(const wallet_rpc::COMMAND_RPC_SET_DAEMON::request& req, wallet_rpc::COMMAND_RPC_SET_DAEMON::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4684 {
4685 if (m_restricted)
4686 {
4687 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4688 er.message = "Command unavailable in restricted mode.";
4689 return false;
4690 }
4691 if (!m_wallet) return not_open(er);
4692
4693 if (m_wallet->has_proxy_option() && !req.proxy.empty())
4694 {
4695 er.code = WALLET_RPC_ERROR_CODE_PROXY_ALREADY_DEFINED;
4696 er.message = "It is not possible to set daemon specific proxy when --proxy is defined.";
4697 return false;
4698 }
4699
4700 std::vector<std::vector<uint8_t>> ssl_allowed_fingerprints;
4701 ssl_allowed_fingerprints.reserve(req.ssl_allowed_fingerprints.size());
4702 for (const std::string &fp: req.ssl_allowed_fingerprints)
4703 {
4704 std::vector<uint8_t> decoded;
4705 try
4706 {
4707 decoded = epee::from_hex_locale::to_vector(fp);
4708 }
4709 catch (const std::exception &)
4710 {
4711 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
4712 er.message = "ssl_allowed_fingerprints[] entries must be hex-encoded SHA-256 values";
4713 return false;
4714 }
4715
4716 if (decoded.size() != SSL_FINGERPRINT_SIZE)
4717 {
4718 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
4719 er.message = "Each ssl_allowed_fingerprints[] entry must decode to exactly " BOOST_PP_STRINGIZE(SSL_FINGERPRINT_SIZE) " bytes";
4720 return false;
4721 }
4722 ssl_allowed_fingerprints.emplace_back(std::move(decoded));
4723 }
4724
4725 epee::net_utils::ssl_options_t ssl_options = epee::net_utils::ssl_support_t::e_ssl_support_enabled;
4726 if (req.ssl_allow_any_cert)
4727 ssl_options.verification = epee::net_utils::ssl_verification_t::none;
4728 else if (!ssl_allowed_fingerprints.empty() || !req.ssl_ca_file.empty())
4729 ssl_options = epee::net_utils::ssl_options_t{std::move(ssl_allowed_fingerprints), std::move(req.ssl_ca_file)};
4730
4731 if (!epee::net_utils::ssl_support_from_string(ssl_options.support, req.ssl_support))
4732 {
4733 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
4734 er.message = std::string("Invalid ssl support mode");
4735 return false;
4736 }
4737
4738 ssl_options.auth = epee::net_utils::ssl_authentication_t{
4739 std::move(req.ssl_private_key_path), std::move(req.ssl_certificate_path)
4740 };
4741
4742 const bool verification_required =
4743 ssl_options.verification != epee::net_utils::ssl_verification_t::none &&
4744 ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_enabled;
4745
4746 if (verification_required && !ssl_options.has_strong_verification(boost::string_ref{}))
4747 {
4748 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
4749 er.message = "SSL is enabled but no user certificate or fingerprints were provided";
4750 return false;
4751 }
4752
4753 boost::optional<epee::net_utils::http::login> daemon_login{};
4754 if (!req.username.empty() || !req.password.empty())
4755 daemon_login.emplace(req.username, req.password);
4756
4757 if (!m_wallet->set_daemon(req.address, daemon_login, req.trusted, std::move(ssl_options), req.proxy))
4758 {
4759 er.code = WALLET_RPC_ERROR_CODE_NO_DAEMON_CONNECTION;
4760 er.message = std::string("Unable to set daemon");
4761 return false;
4762 }
4763 return true;
4764 }
4765 //------------------------------------------------------------------------------------------------------------------------------
4766 bool wallet_rpc_server::on_set_log_level(const wallet_rpc::COMMAND_RPC_SET_LOG_LEVEL::request& req, wallet_rpc::COMMAND_RPC_SET_LOG_LEVEL::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4767 {
4768 if (m_restricted)
4769 {
4770 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4771 er.message = "Command unavailable in restricted mode.";
4772 return false;
4773 }
4774
4775 if (req.level < 0 || req.level > 4)
4776 {
4777 er.code = WALLET_RPC_ERROR_CODE_INVALID_LOG_LEVEL;
4778 er.message = "Error: log level not valid";
4779 return false;
4780 }
4781 mlog_set_log_level(req.level);
4782 return true;
4783 }
4784 //------------------------------------------------------------------------------------------------------------------------------
4785 bool wallet_rpc_server::on_set_log_categories(const wallet_rpc::COMMAND_RPC_SET_LOG_CATEGORIES::request& req, wallet_rpc::COMMAND_RPC_SET_LOG_CATEGORIES::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4786 {
4787 if (m_restricted)
4788 {
4789 er.code = WALLET_RPC_ERROR_CODE_DENIED;
4790 er.message = "Command unavailable in restricted mode.";
4791 return false;
4792 }
4793
4794 mlog_set_log(req.categories.c_str());
4795 res.categories = mlog_get_categories();
4796 return true;
4797 }
4798 //------------------------------------------------------------------------------------------------------------------------------
4799 bool wallet_rpc_server::on_estimate_tx_size_and_weight(const wallet_rpc::COMMAND_RPC_ESTIMATE_TX_SIZE_AND_WEIGHT::request& req, wallet_rpc::COMMAND_RPC_ESTIMATE_TX_SIZE_AND_WEIGHT::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4800 {
4801 if (!m_wallet) return not_open(er);
4802 try
4803 {
4804 size_t extra_size = 34 /* pubkey */ + 10 /* encrypted payment id */; // typical makeup
4805 const std::pair<size_t, uint64_t> sw = m_wallet->estimate_tx_size_and_weight(req.rct, req.n_inputs, req.ring_size, req.n_outputs, extra_size);
4806 res.size = sw.first;
4807 res.weight = sw.second;
4808 }
4809 catch (const std::exception &e)
4810 {
4811 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4812 er.message = "Failed to determine size and weight";
4813 return false;
4814 }
4815 return true;
4816 }
4817 //------------------------------------------------------------------------------------------------------------------------------
4818 bool wallet_rpc_server::on_get_default_fee_priority(const wallet_rpc::COMMAND_RPC_GET_DEFAULT_FEE_PRIORITY::request& req, wallet_rpc::COMMAND_RPC_GET_DEFAULT_FEE_PRIORITY::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4819 {
4820 if (!m_wallet) return not_open(er);
4821 try
4822 {
4823 uint32_t priority = m_wallet->adjust_priority(0);
4824 if (priority == 0)
4825 {
4826 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4827 er.message = "Failed to get adjusted fee priority";
4828 return false;
4829 }
4830 res.priority = priority;
4831 }
4832 catch (const std::exception& e)
4833 {
4834 er.code = WALLET_RPC_ERROR_CODE_UNKNOWN_ERROR;
4835 er.message = "Failed to get adjusted fee priority";
4836 return false;
4837 }
4838 return true;
4839 }
4840 //------------------------------------------------------------------------------------------------------------------------------
4841 bool wallet_rpc_server::on_get_version(const wallet_rpc::COMMAND_RPC_GET_VERSION::request& req, wallet_rpc::COMMAND_RPC_GET_VERSION::response& res, epee::json_rpc::error& er, const connection_context *ctx)
4842 {
4843 res.version = WALLET_RPC_VERSION;
4844 res.release = MONERO_VERSION_IS_RELEASE;
4845 return true;
4846 }
4847 //------------------------------------------------------------------------------------------------------------------------------
4848 }
4849
4850 class t_daemon
4851 {
4852 private:
4853 const boost::program_options::variables_map& vm;
4854
4855 std::unique_ptr<tools::wallet_rpc_server> wrpc;
4856
4857 public:
4858 t_daemon(boost::program_options::variables_map const & _vm)
4859 : vm(_vm)
4860 , wrpc(new tools::wallet_rpc_server)
4861 {
4862 }
4863
4864 bool run()
4865 {
4866 std::unique_ptr<tools::wallet2> wal;
4867 try
4868 {
4869 const bool testnet = tools::wallet2::has_testnet_option(vm);
4870 const bool stagenet = tools::wallet2::has_stagenet_option(vm);
4871 if (testnet && stagenet)
4872 {
4873 MERROR(tools::wallet_rpc_server::tr("Can't specify more than one of --testnet and --stagenet"));
4874 return false;
4875 }
4876
4877 const auto arg_wallet_file = wallet_args::arg_wallet_file();
4878 const auto arg_from_json = wallet_args::arg_generate_from_json();
4879 const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key();
4880 const auto arg_password_file = wallet_args::arg_password_file();
4881
4882 const auto wallet_file = command_line::get_arg(vm, arg_wallet_file);
4883 const auto from_json = command_line::get_arg(vm, arg_from_json);
4884 const auto wallet_dir = command_line::get_arg(vm, arg_wallet_dir);
4885 const auto password_file = command_line::get_arg(vm, arg_password_file);
4886 const auto prompt_for_password = command_line::get_arg(vm, arg_prompt_for_password);
4887 const auto password_prompt = prompt_for_password ? password_prompter : nullptr;
4888 const auto no_initial_sync = command_line::get_arg(vm, arg_no_initial_sync);
4889
4890 if(!wallet_file.empty() && !from_json.empty())
4891 {
4892 LOG_ERROR(tools::wallet_rpc_server::tr("Can't specify more than one of --wallet-file and --generate-from-json"));
4893 return false;
4894 }
4895
4896 if(!wallet_dir.empty() && !password_file.empty())
4897 {
4898 LOG_ERROR(tools::wallet_rpc_server::tr("--password-file is not allowed in combination with --wallet-dir"));
4899 return false;
4900 }
4901
4902 if (!wallet_dir.empty())
4903 {
4904 wal = NULL;
4905 goto just_dir;
4906 }
4907
4908 if (wallet_file.empty() && from_json.empty())
4909 {
4910 LOG_ERROR(tools::wallet_rpc_server::tr("Must specify --wallet-file or --generate-from-json or --wallet-dir"));
4911 return false;
4912 }
4913
4914 LOG_PRINT_L0(tools::wallet_rpc_server::tr("Loading wallet..."));
4915 if(!wallet_file.empty())
4916 {
4917 wal = tools::wallet2::make_from_file(vm, true, wallet_file, password_prompt).first;
4918 }
4919 else
4920 {
4921 try
4922 {
4923 auto rc = tools::wallet2::make_from_json(vm, true, from_json, password_prompt);
4924 wal = std::move(rc.first);
4925 }
4926 catch (const std::exception &e)
4927 {
4928 MERROR("Error creating wallet: " << e.what());
4929 return false;
4930 }
4931 }
4932 if (!wal)
4933 {
4934 return false;
4935 }
4936
4937 if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key))
4938 {
4939 crypto::secret_key client_secret_key;
4940 if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), client_secret_key))
4941 {
4942 MERROR(arg_rpc_client_secret_key.name << ": RPC client secret key should be 32 byte in hex format");
4943 return false;
4944 }
4945 wal->set_rpc_client_secret_key(client_secret_key);
4946 }
4947
4948 bool quit = false;
4949 tools::signal_handler::install([&wal, &quit](int) {
4950 assert(wal);
4951 quit = true;
4952 wal->stop();
4953 });
4954
4955 try
4956 {
4957 if (!no_initial_sync)
4958 wal->refresh(wal->is_trusted_daemon());
4959 }
4960 catch (const std::exception& e)
4961 {
4962 LOG_ERROR(tools::wallet_rpc_server::tr("Initial refresh failed: ") << e.what());
4963 }
4964 // if we ^C during potentially length load/refresh, there's no server loop yet
4965 if (quit)
4966 {
4967 MINFO(tools::wallet_rpc_server::tr("Saving wallet..."));
4968 wal->store();
4969 MINFO(tools::wallet_rpc_server::tr("Successfully saved"));
4970 return false;
4971 }
4972 MINFO(tools::wallet_rpc_server::tr("Successfully loaded"));
4973 }
4974 catch (const std::exception& e)
4975 {
4976 LOG_ERROR(tools::wallet_rpc_server::tr("Wallet initialization failed: ") << e.what());
4977 return false;
4978 }
4979 just_dir:
4980 if (wal) wrpc->set_wallet(wal.release());
4981 bool r = wrpc->init(&vm);
4982 CHECK_AND_ASSERT_MES(r, false, tools::wallet_rpc_server::tr("Failed to initialize wallet RPC server"));
4983 tools::signal_handler::install([this](int) {
4984 wrpc->send_stop_signal();
4985 });
4986 LOG_PRINT_L0(tools::wallet_rpc_server::tr("Starting wallet RPC server"));
4987 try
4988 {
4989 wrpc->run();
4990 }
4991 catch (const std::exception &e)
4992 {
4993 LOG_ERROR(tools::wallet_rpc_server::tr("Failed to run wallet: ") << e.what());
4994 return false;
4995 }
4996 LOG_PRINT_L0(tools::wallet_rpc_server::tr("Stopped wallet RPC server"));
4997 try
4998 {
4999 LOG_PRINT_L0(tools::wallet_rpc_server::tr("Saving wallet..."));
5000 wrpc->stop();
5001 LOG_PRINT_L0(tools::wallet_rpc_server::tr("Successfully saved"));
5002 }
5003 catch (const std::exception& e)
5004 {
5005 LOG_ERROR(tools::wallet_rpc_server::tr("Failed to save wallet: ") << e.what());
5006 return false;
5007 }
5008 return true;
5009 }
5010
5011 void stop()
5012 {
5013 wrpc->send_stop_signal();
5014 }
5015 };
5016
5017 class t_executor final
5018 {
5019 public:
5020 static std::string const NAME;
5021
5022 typedef ::t_daemon t_daemon;
5023
5024 std::string const & name() const
5025 {
5026 return NAME;
5027 }
5028
5029 t_daemon create_daemon(boost::program_options::variables_map const & vm)
5030 {
5031 return t_daemon(vm);
5032 }
5033
5034 bool run_non_interactive(boost::program_options::variables_map const & vm)
5035 {
5036 return t_daemon(vm).run();
5037 }
5038
5039 bool run_interactive(boost::program_options::variables_map const & vm)
5040 {
5041 return t_daemon(vm).run();
5042 }
5043 };
5044
5045 std::string const t_executor::NAME = "Wallet RPC Daemon";
5046
5047 int main(int argc, char** argv) {
5048 TRY_ENTRY();
5049
5050 namespace po = boost::program_options;
5051
5052 const auto arg_wallet_file = wallet_args::arg_wallet_file();
5053 const auto arg_from_json = wallet_args::arg_generate_from_json();
5054 const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key();
5055
5056 po::options_description hidden_options("Hidden");
5057
5058 po::options_description desc_params(wallet_args::tr("Wallet options"));
5059 tools::wallet2::init_options(desc_params);
5060 command_line::add_arg(desc_params, arg_rpc_bind_port);
5061 command_line::add_arg(desc_params, arg_disable_rpc_login);
5062 command_line::add_arg(desc_params, arg_restricted);
5063 cryptonote::rpc_args::init_options(desc_params);
5064 command_line::add_arg(desc_params, arg_wallet_file);
5065 command_line::add_arg(desc_params, arg_from_json);
5066 command_line::add_arg(desc_params, arg_wallet_dir);
5067 command_line::add_arg(desc_params, arg_prompt_for_password);
5068 command_line::add_arg(desc_params, arg_rpc_client_secret_key);
5069 command_line::add_arg(desc_params, arg_no_initial_sync);
5070 command_line::add_arg(desc_params, arg_rpc_max_connections_per_public_ip);
5071 command_line::add_arg(desc_params, arg_rpc_max_connections_per_private_ip);
5072 command_line::add_arg(desc_params, arg_rpc_max_connections);
5073 command_line::add_arg(desc_params, arg_rpc_response_soft_limit);
5074
5075 daemonizer::init_options(hidden_options, desc_params);
5076 desc_params.add(hidden_options);
5077
5078 boost::optional<po::variables_map> vm;
5079 bool should_terminate = false;
5080 std::tie(vm, should_terminate) = wallet_args::main(
5081 argc, argv,
5082 "monero-wallet-rpc [--wallet-file=<file>|--generate-from-json=<file>|--wallet-dir=<directory>] [--rpc-bind-port=<port>]",
5083 tools::wallet_rpc_server::tr("This is the RPC monero wallet. It needs to connect to a monero\ndaemon to work correctly."),
5084 desc_params,
5085 po::positional_options_description(),
5086 [](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; },
5087 "monero-wallet-rpc.log",
5088 true
5089 );
5090 if (!vm)
5091 {
5092 return 1;
5093 }
5094 if (should_terminate)
5095 {
5096 return 0;
5097 }
5098
5099 return daemonizer::daemonize(argc, const_cast<const char**>(argv), t_executor{}, *vm) ? 0 : 1;
5100 CATCH_ENTRY_L0("main", 1);
5101 }