forked from Beldex-Coin/beldex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet_rpc_server.cpp
More file actions
executable file
·3696 lines (3275 loc) · 154 KB
/
Copy pathwallet_rpc_server.cpp
File metadata and controls
executable file
·3696 lines (3275 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014-2018, The Monero Project
// Copyright (c) 2018, The Beldex Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <fmt/core.h>
#include <boost/asio/ip/address.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdint>
#include "cryptonote_basic/cryptonote_basic_impl.h"
#include <chrono>
#include <exception>
#include <oxenc/base64.h>
#include "wallet_rpc_server_error_codes.h"
#include "wallet_rpc_server.h"
#include "wallet/wallet_args.h"
#include "common/command_line.h"
#include "common/i18n.h"
#include "common/signal_handler.h"
#include "cryptonote_config.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_basic/account.h"
#include "multisig/multisig.h"
#include "epee/string_tools.h"
#include "epee/wipeable_string.h"
#include "crypto/hash.h"
#include "mnemonics/electrum-words.h"
#include "rpc/common/rpc_args.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "daemonizer/daemonizer.h"
#include "cryptonote_core/beldex_name_system.h"
#include "serialization/boost_std_variant.h"
#undef BELDEX_DEFAULT_LOG_CATEGORY
#define BELDEX_DEFAULT_LOG_CATEGORY "wallet.rpc"
namespace rpc = cryptonote::rpc;
using namespace tools::wallet_rpc;
namespace
{
constexpr auto DEFAULT_AUTO_REFRESH_PERIOD = 20s;
const command_line::arg_descriptor<uint16_t, true> arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"};
const command_line::arg_descriptor<bool> arg_disable_rpc_login = {"disable-rpc-login", "Disable HTTP authentication for RPC connections served by this process"};
const command_line::arg_descriptor<bool> arg_restricted = {"restricted-rpc", "Restricts to view-only commands", false};
const command_line::arg_descriptor<std::string> arg_wallet_dir = {"wallet-dir", "Directory for newly created wallets"};
const command_line::arg_descriptor<bool> arg_prompt_for_password = {"prompt-for-password", "Prompts for password when not provided", false};
constexpr const char default_rpc_username[] = "beldex";
std::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
{
auto pwd_container = tools::password_container::prompt(verify, prompt);
if (!pwd_container)
{
MERROR("failed to read wallet password");
}
return pwd_container;
}
using rpc_func_data = std::pair<
bool, // restricted
std::string(*)( // function to invoke
epee::serialization::portable_storage& ps,
epee::serialization::storage_entry id,
std::optional<epee::serialization::storage_entry> params,
tools::wallet_rpc_server& server)>;
template <typename RPC, std::enable_if_t<std::is_base_of_v<RPC_COMMAND, RPC>, int> = 0>
void register_rpc_command(std::unordered_map<std::string, rpc_func_data>& regs)
{
using Request = typename RPC::request;
using Response = typename RPC::response;
/// check that wallet_rpc_server.invoke(Request) returns a Response; the code below
/// will fail anyway if this isn't satisfied, but that compilation failure might be more cryptic.
using invoke_return_type = decltype(std::declval<tools::wallet_rpc_server>().invoke(std::declval<Request&&>()));
static_assert(std::is_same<Response, invoke_return_type>::value,
"Unable to register RPC command: wallet_rpc_server::invoke(Request) is not defined or does not return a Response");
rpc_func_data invoke = {
std::is_base_of_v<RESTRICTED, RPC>,
[]( epee::serialization::portable_storage& ps,
epee::serialization::storage_entry id,
std::optional<epee::serialization::storage_entry> params,
tools::wallet_rpc_server& server) {
Request req{};
if (params) {
if (auto* section = std::get_if<epee::serialization::section>(&*params)) {
if (!req.load(ps, section))
throw tools::wallet_rpc_server::parse_error{"Failed to parse JSON parameters"};
}
else
throw std::runtime_error{"only top-level JSON object values are currently supported"};
}
epee::json_rpc::response<Response> r{"2.0", server.invoke(std::move(req)), std::move(id)};
std::string response;
epee::serialization::store_t_to_json(r, response);
if (response.capacity() > response.size())
response += '\n';
return response;
}
};
for (const auto& name : RPC::names())
regs.emplace(name, invoke);
}
template <typename... RPC>
std::unordered_map<std::string, rpc_func_data> register_rpc_commands(tools::type_list<RPC...>) {
std::unordered_map<std::string, rpc_func_data> regs;
(register_rpc_command<RPC>(regs), ...);
return regs;
}
const auto rpc_commands = register_rpc_commands(wallet_rpc_types{});
// Thrown with a code and message to return a json_rpc error.
class wallet_rpc_error : public std::runtime_error {
public:
int16_t code;
std::string message;
wallet_rpc_error(int16_t code, std::string message)
: runtime_error{"Wallet rpc error: " + message + " (" + std::to_string(code) + ")"},
code{code},
message{std::move(message)}
{}
};
uint32_t convert_priority(uint32_t priority)
{
// NOTE: Map all priorites to flash for backwards compatibility purposes
// and leaving priority 'unimportant' or '1' as the only other alternative.
uint32_t result = priority;
if (result != tools::tx_priority_unimportant)
result = tools::tx_priority_flash;
return result;
}
} // anon namespace
namespace tools
{
const char* wallet_rpc_server::tr(const char* str)
{
return i18n_translate(str, "tools::wallet_rpc_server");
}
//------------------------------------------------------------------------------------------------------------------------------
wallet_rpc_server::wallet_rpc_server(boost::program_options::variables_map vm)
: rpc_login_file()
, m_stop(false)
, m_restricted(false)
, m_vm(std::move(vm))
{
}
//------------------------------------------------------------------------------------------------------------------------------
void wallet_rpc_server::create_rpc_endpoints(uWS::App& http)
{
http.post("/json_rpc", [this](HttpResponse* res, HttpRequest* req) {
if (m_login && !check_auth(*req, *res))
return;
handle_json_rpc_request(*res, *req);
});
// Fallback to send a 404 for anything else:
http.any("/*", [this](HttpResponse* res, HttpRequest* req) {
if (m_login && !check_auth(*req, *res))
return;
MINFO("Invalid HTTP request for " << req->getMethod() << " " << req->getUrl());
error_response(*res, HTTP_NOT_FOUND);
});
}
void wallet_rpc_server::handle_json_rpc_request(HttpResponse& res, HttpRequest& req)
{
std::vector<std::pair<std::string, std::string>> extra_headers;
handle_cors(req, extra_headers);
res.onAborted([] {});
res.onData([this, &res, extra_headers=std::move(extra_headers), buffer=""s](std::string_view d, bool done) mutable {
if (!done) {
buffer += d;
return;
}
std::string_view body;
if (buffer.empty())
body = d; // bypass copying the string_view to a string
else
body = (buffer += d);
epee::serialization::portable_storage ps;
if(!ps.load_from_json(body))
return jsonrpc_error_response(res, -32700, "Parse error", {});
nlohmann::json id;
epee::serialization::storage_entry epee_id{std::string{}};
if (std::string str_val; ps.get_value("id", str_val, nullptr)) {
epee_id = str_val;
id = std::move(str_val);
} else if (int64_t i64_val; ps.get_value("id", i64_val, nullptr)) {
epee_id = i64_val;
id = i64_val;
} else {
return jsonrpc_error_response(
res,
-32700,
"Parse error, missing a valid (string or integer) JSON RPC 'id'",
{});
}
std::string method;
if(!ps.get_value("method", method, nullptr))
{
MINFO("Invalid JSON RPC request from " << get_remote_address(res) << ": no 'method' in request");
return jsonrpc_error_response(res, -32600, "Invalid Request", id);
}
auto it = rpc_commands.find(method);
if (it == rpc_commands.end())
{
MINFO("Invalid JSON RPC request from " << get_remote_address(res) << ": method '" << method << "' is invalid");
return jsonrpc_error_response(res, -32601, "Method not found", id);
}
MDEBUG("Incoming JSON RPC request for " << method << " from " << get_remote_address(res));
const auto& [restricted, invoke_ptr] = it->second;
// If it's a restricted command and we're in restricted mode then deny it
if (restricted && m_restricted) {
MWARNING("JSON RPC request for restricted command " << method << " in restricted mode from " << get_remote_address(res));
return jsonrpc_error_response(res, error_code::DENIED, method + " is not available in restricted mode.", {});
}
// Try to load "params" into a generic epee value; if it fails (because there is no "params")
// then clear it and pass a null optionsl.
auto params = std::make_optional<epee::serialization::storage_entry>();
if (!ps.get_value("params", *params, nullptr))
params.reset();
std::string result;
wallet_rpc_error json_error{-32603, "Internal error"};
try {
result = invoke_ptr(ps, std::move(epee_id), std::move(params), *this);
json_error.code = 0;
} catch (const parse_error& e) {
json_error = {-32602, "Invalid params"}; // Reserved json code/message value for specifically this failure
} catch (const wallet_rpc_error& e) {
json_error = e;
} catch (const tools::error::no_connection_to_daemon& e) {
json_error = {error_code::NO_DAEMON_CONNECTION, e.what()};
} catch (const tools::error::daemon_busy& e) {
json_error = {error_code::DAEMON_IS_BUSY, e.what()};
} catch (const tools::error::zero_destination& e) {
json_error = {error_code::ZERO_DESTINATION, e.what()};
} catch (const tools::error::not_enough_money& e) {
json_error = {error_code::NOT_ENOUGH_MONEY, e.what()};
} catch (const tools::error::not_enough_unlocked_money& e) {
json_error = {error_code::NOT_ENOUGH_UNLOCKED_MONEY, e.what()};
} catch (const tools::error::tx_not_possible& e) {
json_error = { error_code::TX_NOT_POSSIBLE, fmt::format(tr("Transaction not possible. Available only {}, transaction amount {} = {} + {} (fee)"),
cryptonote::print_money(e.available()),
cryptonote::print_money(e.tx_amount() + e.fee()),
cryptonote::print_money(e.tx_amount()),
cryptonote::print_money(e.fee()))};
} catch (const tools::error::not_enough_outs_to_mix& e) {
json_error = {error_code::NOT_ENOUGH_OUTS_TO_MIX, e.what() + std::string(" Please use sweep_dust.")};
} catch (const error::file_exists& e) {
json_error = {error_code::WALLET_ALREADY_EXISTS, "Cannot create wallet. Already exists."};
} catch (const error::invalid_password& e) {
json_error = {error_code::INVALID_PASSWORD, "Invalid password."};
} catch (const error::account_index_outofbound& e) {
json_error = {error_code::ACCOUNT_INDEX_OUT_OF_BOUNDS, e.what()};
} catch (const error::address_index_outofbound& e) {
json_error = {error_code::ADDRESS_INDEX_OUT_OF_BOUNDS, e.what()};
} catch (const error::signature_check_failed& e) {
json_error = {error_code::WRONG_SIGNATURE, e.what()};
} catch (const error::tx_flash_rejected& e) {
json_error = {error_code::FLASH_FAILED, e.what()};
} catch (const std::exception& e) {
json_error = {error_code::UNKNOWN_ERROR, e.what()};
} catch (...) {
// leave it as unknown error
}
if (json_error.code != 0)
return jsonrpc_error_response(res, json_error.code, std::move(json_error.message), {});
res.writeHeader("Server", server_header());
res.writeHeader("Content-Type", "application/json");
for (const auto& [name, value] : extra_headers)
res.writeHeader(name, value);
if (closing()) res.writeHeader("Connection", "close");
res.end(result);
if (closing()) res.close();
});
}
//------------------------------------------------------------------------------------------------------------------------------
void wallet_rpc_server::run_loop()
{
// We start 1-2 threads here:
// - the uWS thread that handles all requests.
// - a long poll thread (optional).
// then this parent thread handles injecting refresh jobs (either on a timer, or because of long
// polling detecting a change) into the uWS thread loop, and shutting down on a signal.
std::promise<std::pair<uWS::Loop*, std::vector<us_listen_socket_t*>>> loop_promise;
auto loop_future = loop_promise.get_future();
// Start uWS in a thread, then join it.
std::thread uws_thread{[this, &loop_promise] {
uWS::App http;
try {
create_rpc_endpoints(http);
} catch (...) {
loop_promise.set_exception(std::current_exception());
}
bool bad = false;
int good = 0;
std::vector<us_listen_socket_t*> listening;
try {
for (const auto& [addr, port, required] : m_bind)
http.listen(addr, port, [&listening, req=required, &good, &bad](us_listen_socket_t* sock) {
listening.push_back(sock);
if (sock != nullptr) good++;
else if (req) bad = true;
});
if (!good || bad) {
std::ostringstream error;
error << "RPC HTTP server failed to bind; ";
if (listening.empty()) error << "no valid bind address(es) given";
else {
error << "tried to bind to:";
for (const auto& [addr, port, required] : m_bind)
error << ' ' << addr << ':' << port;
}
throw std::runtime_error{error.str()};
}
} catch (...) {
loop_promise.set_exception(std::current_exception());
return;
}
loop_promise.set_value(std::make_pair(uWS::Loop::get(), std::move(listening)));
http.run();
}};
// Wait for startup:
auto [loop, sockets] = loop_future.get();
m_loop = loop;
m_listen_socks = std::move(sockets);
if (m_wallet)
start_long_poll_thread();
// Used to prevent queuing up multiple refreshes at once
std::atomic<bool> refreshing = false;
// Now we just hang around and twiddle our thumbs until we're told to quit. (And once in a
// while we inject a wallet refresh into the uWS loop).
while (!m_stop.load(std::memory_order_relaxed))
{
bool refresh_now = !refreshing && m_wallet && (
(m_auto_refresh_period > 0s && std::chrono::steady_clock::now() > m_last_auto_refresh_time + m_auto_refresh_period)
|| m_long_poll_new_changes);
if (refresh_now)
{
refreshing = true;
// Queue the refresh to run in the uWS thread loop
loop_defer([this, &refreshing] {
m_long_poll_new_changes = false; // Always consume the change, if we miss one due to thread race, not the end of the world.
try {
if (m_wallet) m_wallet->refresh(m_wallet->is_trusted_daemon());
} catch (const std::exception& ex) {
LOG_ERROR("Exception while refreshing: " << ex.what());
}
m_last_auto_refresh_time = std::chrono::steady_clock::now();
refreshing = false;
});
}
std::this_thread::sleep_for(250ms);
}
MGINFO("Stopping wallet rpc server");
MINFO("Shutting down listening HTTP RPC sockets");
// Stopped: close the sockets, cancel the long poll, and rejoin the threads
for (auto* s : m_listen_socks)
us_listen_socket_close(/*ssl=*/false, s);
m_closing = true;
stop_long_poll_thread();
MDEBUG("Joining uws thread");
uws_thread.join();
MGINFO("Storing wallet...");
if (m_wallet)
m_wallet->store();
MGINFO("Wallet stopped.");
}
void wallet_rpc_server::start_long_poll_thread()
{
assert(m_wallet);
if (m_long_poll_thread.joinable() || m_long_poll_disabled)
{
MDEBUG("Not starting long poll thread: " << (m_long_poll_thread.joinable() ? "already running" : "long polling disabled"));
return;
}
MINFO("Starting long poll thread");
m_long_poll_thread = std::thread{[this] {
for (;;)
{
if (m_long_poll_disabled) return;
if (m_auto_refresh_period == 0s)
{
std::this_thread::sleep_for(100ms);
continue;
}
try
{
if (m_wallet->long_poll_pool_state())
m_long_poll_new_changes = true;
}
catch (...)
{
// NOTE: Don't care about error, non fatal.
}
}
}};
}
void wallet_rpc_server::stop_long_poll_thread()
{
assert(m_wallet);
if (!m_long_poll_thread.joinable())
{
MDEBUG("Not stopping long poll thread: not running");
return;
}
MINFO("Stopping long poll thread");
m_wallet->cancel_long_poll();
// Store this to revert it afterwards to its original state
bool disabled_state = m_long_poll_disabled;
m_long_poll_disabled = true;
m_long_poll_thread.join();
m_long_poll_disabled = disabled_state;
}
//------------------------------------------------------------------------------------------------------------------------------
bool wallet_rpc_server::init()
{
cryptonote::rpc_args rpc_config;
try {
rpc_config = cryptonote::rpc_args::process(m_vm);
} catch (const std::exception& e) {
MERROR("Failed to process rpc arguments: " << e.what());
return false;
}
const uint16_t port = command_line::get_arg(m_vm, arg_rpc_bind_port);
if (!port)
{
MERROR("Invalid port " << port << " specified");
return false;
}
if (!rpc_config.bind_ip || !rpc_config.bind_ip->empty())
m_bind.emplace_back(rpc_config.bind_ip.value_or("127.0.0.1"), port, rpc_config.require_ipv4);
if (rpc_config.use_ipv6 && (!rpc_config.bind_ipv6_address || !rpc_config.bind_ipv6_address->empty()))
m_bind.emplace_back(rpc_config.bind_ipv6_address.value_or("::1"), port, true);
const bool disable_auth = command_line::get_arg(m_vm, arg_disable_rpc_login);
m_restricted = command_line::get_arg(m_vm, arg_restricted);
m_server_header = "beldex-wallet-rpc/"s + (m_restricted ? std::to_string(BELDEX_VERSION[0]) : std::string{BELDEX_VERSION_STR});
m_cors = {rpc_config.access_control_origins.begin(), rpc_config.access_control_origins.end()};
if (!command_line::is_arg_defaulted(m_vm, arg_wallet_dir))
{
if (!command_line::is_arg_defaulted(m_vm, wallet_args::arg_wallet_file()))
{
MERROR(arg_wallet_dir.name << " and " << wallet_args::arg_wallet_file().name << " are incompatible, use only one of them");
return false;
}
m_wallet_dir = fs::u8path(command_line::get_arg(m_vm, arg_wallet_dir));
if (!m_wallet_dir.empty())
{
std::error_code ec;
if (fs::create_directories(m_wallet_dir, ec))
fs::permissions(m_wallet_dir, fs::perms::owner_all, ec);
else if (ec)
{
LOG_ERROR(tr("Failed to create directory ") << m_wallet_dir << ": " << ec.message());
return false;
}
}
}
if (disable_auth)
{
if (rpc_config.login)
{
const cryptonote::rpc_args::descriptors arg{};
LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg.rpc_login.name);
return false;
}
m_login = std::nullopt;
}
else // auth enabled
{
if (!rpc_config.login)
{
std::array<std::uint8_t, 16> rand_128bit{{}};
crypto::rand(rand_128bit.size(), rand_128bit.data());
m_login.emplace(
default_rpc_username,
oxenc::to_base64(rand_128bit.begin(), rand_128bit.end())
);
std::string temp = "beldex-wallet-rpc." + std::to_string(port) + ".login";
rpc_login_file = tools::private_file::create(temp);
if (!rpc_login_file.handle())
{
LOG_ERROR(tr("Failed to create file ") << temp << tr(". Check permissions or remove file"));
return false;
}
std::fputs(m_login->username.c_str(), rpc_login_file.handle());
std::fputc(':', rpc_login_file.handle());
const auto& password = m_login->password.password();
std::fwrite(password.data(), 1, password.size(), rpc_login_file.handle());
std::fputc('\n', rpc_login_file.handle());
std::fflush(rpc_login_file.handle());
if (std::ferror(rpc_login_file.handle()))
{
LOG_ERROR(tr("Error writing to file ") << temp);
return false;
}
LOG_PRINT_L0(tr("RPC username/password is stored in file ") << temp);
}
else // chosen user/pass
{
m_login = rpc_config.login;
}
assert(bool(m_login));
} // end auth enabled
m_auto_refresh_period = DEFAULT_AUTO_REFRESH_PERIOD;
m_last_auto_refresh_time = std::chrono::steady_clock::time_point::min();
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
void wallet_rpc_server::require_open()
{
if (!m_wallet)
throw wallet_rpc_error{error_code::NOT_OPEN, "No wallet file"};
}
//------------------------------------------------------------------------------------------------------------------------------
void wallet_rpc_server::close_wallet(bool save_current)
{
if (m_wallet)
{
MDEBUG(tools::wallet_rpc_server::tr("Closing wallet..."));
stop_long_poll_thread();
if (save_current)
{
MDEBUG(tools::wallet_rpc_server::tr("Saving wallet..."));
m_wallet->store();
MINFO(tools::wallet_rpc_server::tr("Wallet saved"));
}
m_wallet->deinit();
m_wallet.reset();
MINFO(tools::wallet_rpc_server::tr("Wallet closed"));
}
}
//------------------------------------------------------------------------------------------------------------------------------
GET_BALANCE::response wallet_rpc_server::invoke(GET_BALANCE::request&& req)
{
require_open();
GET_BALANCE::response res{};
{
res.balance = req.all_accounts ? m_wallet->balance_all(req.strict) : m_wallet->balance(req.account_index, req.strict);
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);
res.multisig_import_needed = m_wallet->multisig() && m_wallet->has_multisig_partial_key_images();
std::map<uint32_t, std::map<uint32_t, uint64_t>> balance_per_subaddress_per_account;
std::map<uint32_t, std::map<uint32_t, std::pair<uint64_t, std::pair<uint64_t, uint64_t>>>> unlocked_balance_per_subaddress_per_account;
if (req.all_accounts)
{
for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
{
balance_per_subaddress_per_account[account_index] = m_wallet->balance_per_subaddress(account_index, req.strict);
unlocked_balance_per_subaddress_per_account[account_index] = m_wallet->unlocked_balance_per_subaddress(account_index, req.strict);
}
}
else
{
balance_per_subaddress_per_account[req.account_index] = m_wallet->balance_per_subaddress(req.account_index, req.strict);
unlocked_balance_per_subaddress_per_account[req.account_index] = m_wallet->unlocked_balance_per_subaddress(req.account_index, req.strict);
}
std::vector<wallet::transfer_details> transfers;
m_wallet->get_transfers(transfers);
for (const auto& p : balance_per_subaddress_per_account)
{
uint32_t account_index = p.first;
std::map<uint32_t, uint64_t> balance_per_subaddress = p.second;
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];
std::set<uint32_t> address_indices;
if (!req.all_accounts && !req.address_indices.empty())
{
address_indices = req.address_indices;
}
else
{
for (const auto& i : balance_per_subaddress)
address_indices.insert(i.first);
}
for (uint32_t i : address_indices)
{
wallet_rpc::GET_BALANCE::per_subaddress_info info{};
info.account_index = account_index;
info.address_index = i;
cryptonote::subaddress_index index = {info.account_index, info.address_index};
info.address = m_wallet->get_subaddress_as_str(index);
info.balance = balance_per_subaddress[i];
info.unlocked_balance = unlocked_balance_per_subaddress[i].first;
info.blocks_to_unlock = unlocked_balance_per_subaddress[i].second.first;
info.time_to_unlock = unlocked_balance_per_subaddress[i].second.second;
info.label = m_wallet->get_subaddress_label(index);
info.num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&](const wallet::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == index; });
res.per_subaddress.emplace_back(std::move(info));
}
}
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
GET_ADDRESS::response wallet_rpc_server::invoke(GET_ADDRESS::request&& req)
{
require_open();
GET_ADDRESS::response res{};
{
THROW_WALLET_EXCEPTION_IF(req.account_index >= m_wallet->get_num_subaddress_accounts(), error::account_index_outofbound);
res.addresses.clear();
std::vector<uint32_t> req_address_index;
if (req.address_index.empty())
{
for (uint32_t i = 0; i < m_wallet->get_num_subaddresses(req.account_index); ++i)
req_address_index.push_back(i);
}
else
{
req_address_index = req.address_index;
}
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
for (uint32_t i : req_address_index)
{
THROW_WALLET_EXCEPTION_IF(i >= m_wallet->get_num_subaddresses(req.account_index), error::address_index_outofbound);
res.addresses.resize(res.addresses.size() + 1);
auto& info = res.addresses.back();
const cryptonote::subaddress_index index = {req.account_index, i};
info.address = m_wallet->get_subaddress_as_str(index);
info.label = m_wallet->get_subaddress_label(index);
info.address_index = index.minor;
info.used = std::find_if(transfers.begin(), transfers.end(), [&](const wallet::transfer_details& td) { return td.m_subaddr_index == index; }) != transfers.end();
}
res.address = m_wallet->get_subaddress_as_str({req.account_index, 0});
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
GET_ADDRESS_INDEX::response wallet_rpc_server::invoke(GET_ADDRESS_INDEX::request&& req)
{
require_open();
GET_ADDRESS_INDEX::response res{};
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, m_wallet->nettype(), req.address))
throw wallet_rpc_error{error_code::WRONG_ADDRESS, "Invalid address"};
auto index = m_wallet->get_subaddress_index(info.address);
if (!index)
throw wallet_rpc_error{error_code::WRONG_ADDRESS, "Address doesn't belong to the wallet"};
res.index = *index;
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
CREATE_ADDRESS::response wallet_rpc_server::invoke(CREATE_ADDRESS::request&& req)
{
require_open();
CREATE_ADDRESS::response res{};
{
if (req.count < 1 || req.count > 64)
throw wallet_rpc_error{error_code::UNKNOWN_ERROR, "Count must be between 1 and 64."};
std::vector<std::string> addresses;
std::vector<uint32_t> address_indices;
addresses.reserve(req.count);
address_indices.reserve(req.count);
for (uint32_t i = 0; i < req.count; i++) {
m_wallet->add_subaddress(req.account_index, req.label);
uint32_t new_address_index = m_wallet->get_num_subaddresses(req.account_index) - 1;
address_indices.push_back(new_address_index);
addresses.push_back(m_wallet->get_subaddress_as_str({req.account_index, new_address_index}));
}
res.address = addresses[0];
res.address_index = address_indices[0];
res.addresses = addresses;
res.address_indices = address_indices;
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
LABEL_ADDRESS::response wallet_rpc_server::invoke(LABEL_ADDRESS::request&& req)
{
require_open();
LABEL_ADDRESS::response res{};
{
m_wallet->set_subaddress_label(req.index, req.label);
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
GET_ACCOUNTS::response wallet_rpc_server::invoke(GET_ACCOUNTS::request&& req)
{
require_open();
GET_ACCOUNTS::response res{};
{
res.total_balance = 0;
res.total_unlocked_balance = 0;
const std::pair<std::map<std::string, std::string>, std::vector<std::string>> account_tags = m_wallet->get_account_tags();
if (!req.tag.empty() && account_tags.first.count(req.tag) == 0)
throw wallet_rpc_error{
error_code::UNKNOWN_ERROR,
fmt::format(tr("Tag {} is unregistered."), req.tag)};
for (cryptonote::subaddress_index subaddr_index = {0,0};
subaddr_index.major < m_wallet->get_num_subaddress_accounts();
++subaddr_index.major)
{
if (!req.tag.empty() && req.tag != account_tags.second[subaddr_index.major])
continue;
wallet_rpc::GET_ACCOUNTS::subaddress_account_info info;
info.account_index = subaddr_index.major;
info.base_address = m_wallet->get_subaddress_as_str(subaddr_index);
info.balance = m_wallet->balance(subaddr_index.major, req.strict_balances);
info.unlocked_balance = m_wallet->unlocked_balance(subaddr_index.major, req.strict_balances,NULL,NULL);
info.label = m_wallet->get_subaddress_label(subaddr_index);
info.tag = account_tags.second[subaddr_index.major];
res.subaddress_accounts.push_back(info);
res.total_balance += info.balance;
res.total_unlocked_balance += info.unlocked_balance;
}
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
CREATE_ACCOUNT::response wallet_rpc_server::invoke(CREATE_ACCOUNT::request&& req)
{
require_open();
CREATE_ACCOUNT::response res{};
{
m_wallet->add_subaddress_account(req.label);
res.account_index = m_wallet->get_num_subaddress_accounts() - 1;
res.address = m_wallet->get_subaddress_as_str({res.account_index, 0});
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
LABEL_ACCOUNT::response wallet_rpc_server::invoke(LABEL_ACCOUNT::request&& req)
{
require_open();
LABEL_ACCOUNT::response res{};
{
m_wallet->set_subaddress_label({req.account_index, 0}, req.label);
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
GET_ACCOUNT_TAGS::response wallet_rpc_server::invoke(GET_ACCOUNT_TAGS::request&& req)
{
require_open();
GET_ACCOUNT_TAGS::response res{};
const std::pair<std::map<std::string, std::string>, std::vector<std::string>> account_tags = m_wallet->get_account_tags();
for (const auto& p : account_tags.first)
{
res.account_tags.resize(res.account_tags.size() + 1);
auto& info = res.account_tags.back();
info.tag = p.first;
info.label = p.second;
for (size_t i = 0; i < account_tags.second.size(); ++i)
{
if (account_tags.second[i] == info.tag)
info.accounts.push_back(i);
}
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
TAG_ACCOUNTS::response wallet_rpc_server::invoke(TAG_ACCOUNTS::request&& req)
{
require_open();
TAG_ACCOUNTS::response res{};
{
m_wallet->set_account_tag(req.accounts, req.tag);
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
UNTAG_ACCOUNTS::response wallet_rpc_server::invoke(UNTAG_ACCOUNTS::request&& req)
{
require_open();
UNTAG_ACCOUNTS::response res{};
{
m_wallet->set_account_tag(req.accounts, "");
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
SET_ACCOUNT_TAG_DESCRIPTION::response wallet_rpc_server::invoke(SET_ACCOUNT_TAG_DESCRIPTION::request&& req)
{
require_open();
SET_ACCOUNT_TAG_DESCRIPTION::response res{};
{
m_wallet->set_account_tag_description(req.tag, req.description);
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
GET_HEIGHT::response wallet_rpc_server::invoke(GET_HEIGHT::request&& req)
{
require_open();
GET_HEIGHT::response res{};
{
res.height = m_wallet->get_blockchain_current_height();
res.immutable_height = m_wallet->get_immutable_height();
}
return res;
}
//------------------------------------------------------------------------------------------------------------------------------
cryptonote::address_parse_info wallet_rpc_server::extract_account_addr(
cryptonote::network_type nettype,
std::string_view addr)
{
cryptonote::address_parse_info info;
if (m_wallet->is_trusted_daemon())
{
std::optional<std::string> address = m_wallet->resolve_address(std::string{addr});
if (cryptonote::address_parse_info info; address && get_account_address_from_str(info, nettype, *address))
return info;
}
else if (get_account_address_from_str(info, nettype, addr))
return info;
throw wallet_rpc_error{error_code::WRONG_ADDRESS, "Invalid address: "s + std::string{addr}};
}
//------------------------------------------------------------------------------------------------------------------------------
void wallet_rpc_server::validate_transfer(const std::list<wallet::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)
{
crypto::hash8 integrated_payment_id = crypto::null_hash8;
std::string extra_nonce;
for (auto it = destinations.begin(); it != destinations.end(); it++)
{
cryptonote::address_parse_info info = extract_account_addr(m_wallet->nettype(), it->address);
cryptonote::tx_destination_entry de;
de.original = it->address;
de.addr = info.address;
de.is_subaddress = info.is_subaddress;
de.amount = it->amount;
de.is_integrated = info.has_payment_id;
dsts.push_back(de);
if (info.has_payment_id)
{
if (!payment_id.empty() || integrated_payment_id != crypto::null_hash8)
throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "A single payment id is allowed per transaction"};
integrated_payment_id = info.payment_id;
cryptonote::set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, integrated_payment_id);
/* Append Payment ID data into extra */
if (!cryptonote::add_extra_nonce_to_tx_extra(extra, extra_nonce))
throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "Something went wrong with integrated payment_id."};
}
}
if (at_least_one_destination && dsts.empty())
throw wallet_rpc_error{error_code::ZERO_DESTINATION, "No destinations for this transfer"};
if (!payment_id.empty())
throw wallet_rpc_error{error_code::WRONG_PAYMENT_ID, "Standalone payment IDs are obsolete. Use subaddresses or integrated addresses instead"};
}
//------------------------------------------------------------------------------------------------------------------------------
static std::string ptx_to_string(const wallet::pending_tx &ptx)
{
std::ostringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
try
{
ar << ptx;
}
catch (...)
{
return "";
}
return oxenc::to_hex(oss.str());
}
//------------------------------------------------------------------------------------------------------------------------------
template<typename T>
static bool is_empty_string(const T &val) {
if constexpr (std::is_same_v<T, std::string>)
return val.empty();
return false;
}
//------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename V>
static bool fill(T& where, V&& s)
{
if (is_empty_string(s)) return false;
where = std::forward<V>(s);
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename V>
static bool fill(std::list<T>& where, V&& s)
{
if (is_empty_string(s)) return false;
where.push_back(std::forward<V>(s));
return true;
}
//------------------------------------------------------------------------------------------------------------------------------
static uint64_t total_amount(const wallet::pending_tx &ptx)
{
uint64_t amount = 0;
for (const auto &dest: ptx.dests) amount += dest.amount;
return amount;
}
//------------------------------------------------------------------------------------------------------------------------------
static void append_hex_tx_keys(std::string& to, const crypto::secret_key& k, const std::vector<crypto::secret_key>& more) {
to.reserve(to.size() + oxenc::to_hex_size(sizeof(k.data) * (1 + more.size())));
oxenc::to_hex(std::begin(k.data), std::end(k.data), std::back_inserter(to));
for (const auto& key : more)
oxenc::to_hex(std::begin(key.data), std::end(key.data), std::back_inserter(to));
}
//------------------------------------------------------------------------------------------------------------------------------
static std::string hex_tx_keys(const crypto::secret_key& k, const std::vector<crypto::secret_key>& more) {
std::string s;
append_hex_tx_keys(s, k, more);
return s;
}
//------------------------------------------------------------------------------------------------------------------------------
static std::string hex_tx_keys(const wallet::pending_tx& ptx) {
return hex_tx_keys(ptx.tx_key, ptx.additional_tx_keys);
}
//------------------------------------------------------------------------------------------------------------------------------
template<typename Ts, typename Tu, typename Tk, typename Ta>