Debian Codegraph @

monero/src/rpc/core_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
31 #include <boost/preprocessor/stringize.hpp>
32 #include <boost/uuid/nil_generator.hpp>
33 #include <boost/filesystem.hpp>
34 #include "include_base_utils.h"
35 #include "string_tools.h"
36 using namespace epee;
37
38 #include "core_rpc_server.h"
39 #include "common/command_line.h"
40 #include "common/updates.h"
41 #include "common/download.h"
42 #include "common/util.h"
43 #include "common/perf_timer.h"
44 #include "int-util.h"
45 #include "cryptonote_basic/cryptonote_format_utils.h"
46 #include "cryptonote_basic/account.h"
47 #include "cryptonote_basic/cryptonote_basic_impl.h"
48 #include "cryptonote_basic/merge_mining.h"
49 #include "cryptonote_core/tx_sanity_check.h"
50 #include "misc_language.h"
51 #include "net/local_ip.h"
52 #include "net/parse.h"
53 #include "storages/http_abstract_invoke.h"
54 #include "crypto/hash.h"
55 #include "rpc/rpc_args.h"
56 #include "rpc/rpc_handler.h"
57 #include "rpc/rpc_payment_costs.h"
58 #include "rpc/rpc_payment_signature.h"
59 #include "core_rpc_server_error_codes.h"
60 #include "p2p/net_node.h"
61 #include "version.h"
62
63 #undef MONERO_DEFAULT_LOG_CATEGORY
64 #define MONERO_DEFAULT_LOG_CATEGORY "daemon.rpc"
65
66 #define MAX_RESTRICTED_FAKE_OUTS_COUNT 40
67 #define MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT 5000
68
69 #define OUTPUT_HISTOGRAM_RECENT_CUTOFF_RESTRICTION (3 * 86400) // 3 days max, the wallet requests 1.8 days
70
71 #define DEFAULT_PAYMENT_DIFFICULTY 1000
72 #define DEFAULT_PAYMENT_CREDITS_PER_HASH 100
73
74 #define RESTRICTED_BLOCK_HEADER_RANGE 1000
75 #define RESTRICTED_TRANSACTIONS_COUNT 100
76 #define RESTRICTED_SPENT_KEY_IMAGES_COUNT 5000
77 #define RESTRICTED_BLOCK_COUNT 1000
78
79 #define RPC_TRACKER(rpc) \
80 PERF_TIMER(rpc); \
81 RPCTracker tracker(#rpc, PERF_TIMER_NAME(rpc))
82
83 namespace
84 {
85 class RPCTracker
86 {
87 public:
88 struct entry_t
89 {
90 uint64_t count;
91 uint64_t time;
92 uint64_t credits;
93 };
94
95 RPCTracker(const char *rpc, tools::LoggingPerformanceTimer &timer): rpc(rpc), timer(timer) {
96 }
97 ~RPCTracker() {
98 try
99 {
100 boost::unique_lock<boost::mutex> lock(mutex);
101 auto &e = tracker[rpc];
102 ++e.count;
103 e.time += timer.value();
104 }
105 catch (...) { /* ignore */ }
106 }
107 void pay(uint64_t amount) {
108 boost::unique_lock<boost::mutex> lock(mutex);
109 auto &e = tracker[rpc];
110 e.credits += amount;
111 }
112 const std::string &rpc_name() const { return rpc; }
113 static void clear() { boost::unique_lock<boost::mutex> lock(mutex); tracker.clear(); }
114 static std::unordered_map<std::string, entry_t> data() { boost::unique_lock<boost::mutex> lock(mutex); return tracker; }
115 private:
116 std::string rpc;
117 tools::LoggingPerformanceTimer &timer;
118 static boost::mutex mutex;
119 static std::unordered_map<std::string, entry_t> tracker;
120 };
121 boost::mutex RPCTracker::mutex;
122 std::unordered_map<std::string, RPCTracker::entry_t> RPCTracker::tracker;
123
124 void add_reason(std::string &reasons, const char *reason)
125 {
126 if (!reasons.empty())
127 reasons += ", ";
128 reasons += reason;
129 }
130
131 uint64_t round_up(uint64_t value, uint64_t quantum)
132 {
133 return (value + quantum - 1) / quantum * quantum;
134 }
135
136 void store_128(boost::multiprecision::uint128_t value, uint64_t &slow64, std::string &swide, uint64_t &stop64)
137 {
138 slow64 = (value & 0xffffffffffffffff).convert_to<uint64_t>();
139 swide = cryptonote::hex(value);
140 stop64 = ((value >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
141 }
142
143 void store_difficulty(cryptonote::difficulty_type difficulty, uint64_t &sdiff, std::string &swdiff, uint64_t &stop64)
144 {
145 store_128(difficulty, sdiff, swdiff, stop64);
146 }
147 }
148
149 namespace cryptonote
150 {
151
152 //-----------------------------------------------------------------------------------
153 void core_rpc_server::init_options(boost::program_options::options_description& desc)
154 {
155 command_line::add_arg(desc, arg_rpc_bind_port);
156 command_line::add_arg(desc, arg_rpc_restricted_bind_port);
157 command_line::add_arg(desc, arg_restricted_rpc);
158 command_line::add_arg(desc, arg_bootstrap_daemon_address);
159 command_line::add_arg(desc, arg_bootstrap_daemon_login);
160 command_line::add_arg(desc, arg_bootstrap_daemon_proxy);
161 cryptonote::rpc_args::init_options(desc, true);
162 command_line::add_arg(desc, arg_rpc_payment_address);
163 command_line::add_arg(desc, arg_rpc_payment_difficulty);
164 command_line::add_arg(desc, arg_rpc_payment_credits);
165 command_line::add_arg(desc, arg_rpc_payment_allow_free_loopback);
166 command_line::add_arg(desc, arg_rpc_max_connections_per_public_ip);
167 command_line::add_arg(desc, arg_rpc_max_connections_per_private_ip);
168 command_line::add_arg(desc, arg_rpc_max_connections);
169 command_line::add_arg(desc, arg_rpc_response_soft_limit);
170 }
171 //------------------------------------------------------------------------------------------------------------------------------
172 core_rpc_server::core_rpc_server(
173 core& cr
174 , nodetool::node_server<cryptonote::t_cryptonote_protocol_handler<cryptonote::core> >& p2p
175 )
176 : m_core(cr)
177 , m_p2p(p2p)
178 , m_was_bootstrap_ever_used(false)
179 , disable_rpc_ban(false)
180 , m_rpc_payment_allow_free_loopback(false)
181 {}
182 //------------------------------------------------------------------------------------------------------------------------------
183 bool core_rpc_server::set_bootstrap_daemon(
184 const std::string &address,
185 const std::string &username_password,
186 const std::string &proxy)
187 {
188 boost::optional<epee::net_utils::http::login> credentials;
189 const auto loc = username_password.find(':');
190 if (loc != std::string::npos)
191 {
192 credentials = epee::net_utils::http::login(username_password.substr(0, loc), username_password.substr(loc + 1));
193 }
194 return set_bootstrap_daemon(address, credentials, proxy);
195 }
196 //------------------------------------------------------------------------------------------------------------------------------
197 std::map<std::string, bool> core_rpc_server::get_public_nodes(uint32_t credits_per_hash_threshold/* = 0*/)
198 {
199 COMMAND_RPC_GET_PUBLIC_NODES::request request;
200 COMMAND_RPC_GET_PUBLIC_NODES::response response;
201
202 request.gray = true;
203 request.white = true;
204 request.include_blocked = false;
205 if (!on_get_public_nodes(request, response) || response.status != CORE_RPC_STATUS_OK)
206 {
207 return {};
208 }
209
210 std::map<std::string, bool> result;
211
212 const auto append = [&result, &credits_per_hash_threshold](const std::vector<public_node> &nodes, bool white) {
213 for (const auto &node : nodes)
214 {
215 const bool rpc_payment_enabled = credits_per_hash_threshold > 0;
216 const bool node_rpc_payment_enabled = node.rpc_credits_per_hash > 0;
217 if (!node_rpc_payment_enabled ||
218 (rpc_payment_enabled && node.rpc_credits_per_hash >= credits_per_hash_threshold))
219 {
220 result.insert(std::make_pair(node.host + ":" + std::to_string(node.rpc_port), white));
221 }
222 }
223 };
224
225 append(response.white, true);
226 append(response.gray, false);
227
228 return result;
229 }
230 //------------------------------------------------------------------------------------------------------------------------------
231 bool core_rpc_server::set_bootstrap_daemon(
232 const std::string &address,
233 const boost::optional<epee::net_utils::http::login> &credentials,
234 const std::string &proxy)
235 {
236 boost::unique_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
237
238 constexpr const uint32_t credits_per_hash_threshold = 0;
239 constexpr const bool rpc_payment_enabled = credits_per_hash_threshold != 0;
240
241 if (address.empty())
242 {
243 m_bootstrap_daemon.reset(nullptr);
244 }
245 else if (address == "auto")
246 {
247 auto get_nodes = [this]() {
248 return get_public_nodes(credits_per_hash_threshold);
249 };
250 m_bootstrap_daemon.reset(new bootstrap_daemon(std::move(get_nodes), rpc_payment_enabled, m_bootstrap_daemon_proxy.empty() ? proxy : m_bootstrap_daemon_proxy));
251 }
252 else
253 {
254 m_bootstrap_daemon.reset(new bootstrap_daemon(address, credentials, rpc_payment_enabled, m_bootstrap_daemon_proxy.empty() ? proxy : m_bootstrap_daemon_proxy));
255 }
256
257 m_should_use_bootstrap_daemon = m_bootstrap_daemon.get() != nullptr;
258
259 return true;
260 }
261 core_rpc_server::~core_rpc_server()
262 {
263 if (m_rpc_payment)
264 m_rpc_payment->store();
265 }
266 //------------------------------------------------------------------------------------------------------------------------------
267 bool core_rpc_server::init(
268 const boost::program_options::variables_map& vm
269 , const bool restricted
270 , const std::string& port
271 , bool allow_rpc_payment
272 , const std::string& proxy
273 )
274 {
275 m_bootstrap_daemon_proxy = proxy;
276 m_restricted = restricted;
277 m_net_server.set_threads_prefix("RPC");
278 m_net_server.set_connection_filter(&m_p2p);
279
280 auto rpc_config = cryptonote::rpc_args::process(vm, true);
281 if (!rpc_config)
282 return false;
283
284 std::string bind_ip_str = rpc_config->bind_ip;
285 std::string bind_ipv6_str = rpc_config->bind_ipv6_address;
286 if (restricted)
287 {
288 const auto restricted_rpc_port_arg = cryptonote::core_rpc_server::arg_rpc_restricted_bind_port;
289 const bool has_restricted_rpc_port_arg = !command_line::is_arg_defaulted(vm, restricted_rpc_port_arg);
290 if (has_restricted_rpc_port_arg && port == command_line::get_arg(vm, restricted_rpc_port_arg))
291 {
292 bind_ip_str = rpc_config->restricted_bind_ip;
293 bind_ipv6_str = rpc_config->restricted_bind_ipv6_address;
294 }
295 }
296 disable_rpc_ban = rpc_config->disable_rpc_ban;
297 const std::string data_dir{command_line::get_arg(vm, cryptonote::arg_data_dir)};
298 std::string address = command_line::get_arg(vm, arg_rpc_payment_address);
299 if (!address.empty() && allow_rpc_payment)
300 {
301 if (!m_restricted && nettype() != FAKECHAIN)
302 {
303 MFATAL("RPC payment enabled, but server is not restricted, anyone can adjust their balance to bypass payment");
304 return false;
305 }
306 cryptonote::address_parse_info info;
307 if (!get_account_address_from_str(info, nettype(), address))
308 {
309 MFATAL("Invalid payment address: " << address);
310 return false;
311 }
312 if (info.is_subaddress)
313 {
314 MFATAL("Payment address may not be a subaddress: " << address);
315 return false;
316 }
317 uint64_t diff = command_line::get_arg(vm, arg_rpc_payment_difficulty);
318 uint64_t credits = command_line::get_arg(vm, arg_rpc_payment_credits);
319 if (diff == 0 || credits == 0)
320 {
321 MFATAL("Payments difficulty and/or payments credits are 0, but a payment address was given");
322 return false;
323 }
324 m_rpc_payment_allow_free_loopback = command_line::get_arg(vm, arg_rpc_payment_allow_free_loopback);
325 m_rpc_payment.reset(new rpc_payment(info.address, diff, credits));
326 m_rpc_payment->load(data_dir);
327 m_p2p.set_rpc_credits_per_hash(RPC_CREDITS_PER_HASH_SCALE * (credits / (float)diff));
328 }
329
330 if (!m_rpc_payment)
331 {
332 uint32_t bind_ip;
333 bool ok = epee::string_tools::get_ip_int32_from_string(bind_ip, bind_ip_str);
334 if (ok & !epee::net_utils::is_ip_loopback(bind_ip))
335 MWARNING("The RPC server is accessible from the outside, but no RPC payment was setup. RPC access will be free for all.");
336 }
337
338 if (!set_bootstrap_daemon(
339 command_line::get_arg(vm, arg_bootstrap_daemon_address),
340 command_line::get_arg(vm, arg_bootstrap_daemon_login),
341 command_line::get_arg(vm, arg_bootstrap_daemon_proxy)))
342 {
343 MFATAL("Failed to parse bootstrap daemon address");
344 return false;
345 }
346
347 boost::optional<epee::net_utils::http::login> http_login{};
348
349 if (rpc_config->login)
350 http_login.emplace(std::move(rpc_config->login->username), std::move(rpc_config->login->password).password());
351
352 if (m_rpc_payment)
353 m_net_server.add_idle_handler([this](){ return m_rpc_payment->on_idle(); }, 60 * 1000);
354
355 bool store_ssl_key = !restricted && rpc_config->ssl_options && rpc_config->ssl_options.auth.certificate_path.empty();
356 const auto ssl_base_path = (boost::filesystem::path{data_dir} / "rpc_ssl").string();
357 const bool ssl_cert_file_exists = boost::filesystem::exists(ssl_base_path + ".crt");
358 const bool ssl_pkey_file_exists = boost::filesystem::exists(ssl_base_path + ".key");
359 if (store_ssl_key)
360 {
361 // .key files are often given different read permissions as their corresponding .crt files.
362 // Consequently, sometimes the .key file wont't get copied, while the .crt file will.
363 if (ssl_cert_file_exists != ssl_pkey_file_exists)
364 {
365 MFATAL("Certificate (.crt) and private key (.key) files must both exist or both not exist at path: " << ssl_base_path);
366 return false;
367 }
368 else if (ssl_cert_file_exists) { // and ssl_pkey_file_exists
369 // load key from previous run, password prompted by OpenSSL
370 store_ssl_key = false;
371 rpc_config->ssl_options.auth =
372 epee::net_utils::ssl_authentication_t{ssl_base_path + ".key", ssl_base_path + ".crt"};
373 }
374 }
375
376 const auto max_connections_public = command_line::get_arg(vm, arg_rpc_max_connections_per_public_ip);
377 const auto max_connections_private = command_line::get_arg(vm, arg_rpc_max_connections_per_private_ip);
378 const auto max_connections = command_line::get_arg(vm, arg_rpc_max_connections);
379
380 if (max_connections < max_connections_public)
381 {
382 MFATAL(arg_rpc_max_connections_per_public_ip.name << " is bigger than " << arg_rpc_max_connections.name);
383 return false;
384 }
385 if (max_connections < max_connections_private)
386 {
387 MFATAL(arg_rpc_max_connections_per_private_ip.name << " is bigger than " << arg_rpc_max_connections.name);
388 return false;
389 }
390
391 auto rng = [](size_t len, uint8_t *ptr){ return crypto::rand(len, ptr); };
392 const bool inited = epee::http_server_impl_base<core_rpc_server, connection_context>::init(
393 rng, std::move(port), std::move(bind_ip_str),
394 std::move(bind_ipv6_str), std::move(rpc_config->use_ipv6), std::move(rpc_config->require_ipv4),
395 std::move(rpc_config->access_control_origins), std::move(http_login), std::move(rpc_config->ssl_options),
396 max_connections_public, max_connections_private, max_connections,
397 command_line::get_arg(vm, arg_rpc_response_soft_limit)
398 );
399
400 m_net_server.get_config_object().m_max_content_length = MAX_RPC_CONTENT_LENGTH;
401
402 if (store_ssl_key && inited)
403 {
404 // new keys were generated, store for next run
405 const auto error = epee::net_utils::store_ssl_keys(m_net_server.get_ssl_context(), ssl_base_path);
406 if (error)
407 MFATAL("Failed to store HTTP SSL cert/key for " << (restricted ? "restricted " : "") << "RPC server: " << error.message());
408 return !bool(error);
409 }
410 return inited;
411 }
412 //------------------------------------------------------------------------------------------------------------------------------
413 bool core_rpc_server::check_payment(const std::string &client_message, uint64_t payment, const std::string &rpc, bool same_ts, std::string &message, uint64_t &credits, std::string &top_hash)
414 {
415 if (m_rpc_payment == NULL)
416 {
417 credits = 0;
418 return true;
419 }
420 uint64_t height;
421 crypto::hash hash;
422 m_core.get_blockchain_top(height, hash);
423 top_hash = epee::string_tools::pod_to_hex(hash);
424 crypto::public_key client;
425 uint64_t ts;
426 #ifndef NDEBUG
427 if (nettype() == TESTNET && client_message == "debug")
428 {
429 credits = 0;
430 return true;
431 }
432 #endif
433 if (!cryptonote::verify_rpc_payment_signature(client_message, client, ts))
434 {
435 credits = 0;
436 message = "Client signature does not verify for " + rpc;
437 return false;
438 }
439 if (!m_rpc_payment->pay(client, ts, payment, rpc, same_ts, credits))
440 {
441 message = CORE_RPC_STATUS_PAYMENT_REQUIRED;
442 return false;
443 }
444 return true;
445 }
446 #define CHECK_PAYMENT_BASE(req, res, payment, same_ts) do { if (!ctx) break; uint64_t P = (uint64_t)payment; if (P > 0 && !check_payment(req.client, P, tracker.rpc_name(), same_ts, res.status, res.credits, res.top_hash)){return true;} tracker.pay(P); } while(0)
447 #define CHECK_PAYMENT(req, res, payment) CHECK_PAYMENT_BASE(req, res, payment, false)
448 #define CHECK_PAYMENT_SAME_TS(req, res, payment) CHECK_PAYMENT_BASE(req, res, payment, true)
449 #define CHECK_PAYMENT_MIN1(req, res, payment, same_ts) do { if (!ctx || (m_rpc_payment_allow_free_loopback && ctx->m_remote_address.is_loopback())) break; uint64_t P = (uint64_t)payment; if (P == 0) P = 1; if(!check_payment(req.client, P, tracker.rpc_name(), same_ts, res.status, res.credits, res.top_hash)){return true;} tracker.pay(P); } while(0)
450 //------------------------------------------------------------------------------------------------------------------------------
451 bool core_rpc_server::check_core_ready()
452 {
453 if(!m_p2p.get_payload_object().is_synchronized())
454 {
455 return false;
456 }
457 return true;
458 }
459 //------------------------------------------------------------------------------------------------------------------------------
460 bool core_rpc_server::add_host_fail(const connection_context *ctx, unsigned int score)
461 {
462 if(!ctx || !ctx->m_remote_address.is_blockable() || disable_rpc_ban)
463 return false;
464
465 CRITICAL_REGION_LOCAL(m_host_fails_score_lock);
466 uint64_t fails = m_host_fails_score[ctx->m_remote_address.host_str()] += score;
467 MDEBUG("Host " << ctx->m_remote_address.host_str() << " fail score=" << fails);
468 if(fails > RPC_IP_FAILS_BEFORE_BLOCK)
469 {
470 auto it = m_host_fails_score.find(ctx->m_remote_address.host_str());
471 CHECK_AND_ASSERT_MES(it != m_host_fails_score.end(), false, "internal error");
472 it->second = RPC_IP_FAILS_BEFORE_BLOCK/2;
473 m_p2p.block_host(ctx->m_remote_address);
474 }
475 return true;
476 }
477 #define CHECK_CORE_READY() do { if(!check_core_ready()){res.status = CORE_RPC_STATUS_BUSY;return true;} } while(0)
478
479 //------------------------------------------------------------------------------------------------------------------------------
480 bool core_rpc_server::on_get_height(const COMMAND_RPC_GET_HEIGHT::request& req, COMMAND_RPC_GET_HEIGHT::response& res, const connection_context *ctx)
481 {
482 RPC_TRACKER(get_height);
483 bool r;
484 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_HEIGHT>(invoke_http_mode::JON, "/getheight", req, res, r))
485 return r;
486
487 crypto::hash hash;
488 m_core.get_blockchain_top(res.height, hash);
489 ++res.height; // block height to chain height
490 res.hash = string_tools::pod_to_hex(hash);
491 res.status = CORE_RPC_STATUS_OK;
492 return true;
493 }
494 //------------------------------------------------------------------------------------------------------------------------------
495 bool core_rpc_server::on_get_info(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res, const connection_context *ctx)
496 {
497 RPC_TRACKER(get_info);
498 bool r;
499 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_INFO>(invoke_http_mode::JON, "/getinfo", req, res, r))
500 {
501 {
502 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
503 if (m_bootstrap_daemon.get() != nullptr)
504 {
505 res.bootstrap_daemon_address = m_bootstrap_daemon->address();
506 }
507 }
508 crypto::hash top_hash;
509 m_core.get_blockchain_top(res.height_without_bootstrap, top_hash);
510 ++res.height_without_bootstrap; // turn top block height into blockchain height
511 res.was_bootstrap_ever_used = true;
512 return r;
513 }
514
515 CHECK_PAYMENT_MIN1(req, res, COST_PER_GET_INFO, false);
516
517 const bool restricted = m_restricted && ctx;
518
519 crypto::hash top_hash;
520 m_core.get_blockchain_top(res.height, top_hash);
521 ++res.height; // turn top block height into blockchain height
522 res.top_block_hash = string_tools::pod_to_hex(top_hash);
523 res.target_height = m_p2p.get_payload_object().is_synchronized() ? 0 : m_core.get_target_blockchain_height();
524 store_difficulty(m_core.get_blockchain_storage().get_difficulty_for_next_block(), res.difficulty, res.wide_difficulty, res.difficulty_top64);
525 res.target = m_core.get_blockchain_storage().get_difficulty_target();
526 res.tx_count = m_core.get_blockchain_storage().get_total_transactions() - res.height; //without coinbase
527 res.tx_pool_size = m_core.get_pool_transactions_count(!restricted);
528 res.alt_blocks_count = restricted ? 0 : m_core.get_blockchain_storage().get_alternative_blocks_count();
529 uint64_t total_conn = restricted ? 0 : m_p2p.get_public_connections_count();
530 res.outgoing_connections_count = restricted ? 0 : m_p2p.get_public_outgoing_connections_count();
531 res.incoming_connections_count = restricted ? 0 : (total_conn - res.outgoing_connections_count);
532 res.rpc_connections_count = restricted ? 0 : get_connections_count();
533 res.white_peerlist_size = restricted ? 0 : m_p2p.get_public_white_peers_count();
534 res.grey_peerlist_size = restricted ? 0 : m_p2p.get_public_gray_peers_count();
535
536 cryptonote::network_type net_type = nettype();
537 res.mainnet = net_type == MAINNET;
538 res.testnet = net_type == TESTNET;
539 res.stagenet = net_type == STAGENET;
540 res.nettype = net_type == MAINNET ? "mainnet" : net_type == TESTNET ? "testnet" : net_type == STAGENET ? "stagenet" : "fakechain";
541 store_difficulty(m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.height - 1),
542 res.cumulative_difficulty, res.wide_cumulative_difficulty, res.cumulative_difficulty_top64);
543 res.block_size_limit = res.block_weight_limit = m_core.get_blockchain_storage().get_current_cumulative_block_weight_limit();
544 res.block_size_median = res.block_weight_median = m_core.get_blockchain_storage().get_current_cumulative_block_weight_median();
545 res.adjusted_time = m_core.get_blockchain_storage().get_adjusted_time(res.height);
546
547 res.start_time = restricted ? 0 : (uint64_t)m_core.get_start_time();
548 res.free_space = restricted ? std::numeric_limits<uint64_t>::max() : m_core.get_free_space();
549 res.offline = m_core.offline();
550 res.height_without_bootstrap = restricted ? 0 : res.height;
551 if (restricted)
552 {
553 res.bootstrap_daemon_address = "";
554 res.was_bootstrap_ever_used = false;
555 }
556 else
557 {
558 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
559 if (m_bootstrap_daemon.get() != nullptr)
560 {
561 res.bootstrap_daemon_address = m_bootstrap_daemon->address();
562 }
563 res.was_bootstrap_ever_used = m_was_bootstrap_ever_used;
564 }
565 res.database_size = m_core.get_blockchain_storage().get_db().get_database_size();
566 if (restricted)
567 res.database_size = round_up(res.database_size, 5ull* 1024 * 1024 * 1024);
568 res.update_available = restricted ? false : m_core.is_update_available();
569 res.version = restricted ? "" : MONERO_VERSION_FULL;
570 res.synchronized = check_core_ready();
571 res.busy_syncing = m_p2p.get_payload_object().is_busy_syncing();
572 res.restricted = restricted;
573
574 res.status = CORE_RPC_STATUS_OK;
575 return true;
576 }
577 //------------------------------------------------------------------------------------------------------------------------------
578 bool core_rpc_server::on_get_net_stats(const COMMAND_RPC_GET_NET_STATS::request& req, COMMAND_RPC_GET_NET_STATS::response& res, const connection_context *ctx)
579 {
580 RPC_TRACKER(get_net_stats);
581 // No bootstrap daemon check: Only ever get stats about local server
582 res.start_time = (uint64_t)m_core.get_start_time();
583 {
584 CRITICAL_REGION_LOCAL(epee::net_utils::network_throttle_manager::m_lock_get_global_throttle_in);
585 epee::net_utils::network_throttle_manager::get_global_throttle_in().get_stats(res.total_packets_in, res.total_bytes_in);
586 }
587 {
588 CRITICAL_REGION_LOCAL(epee::net_utils::network_throttle_manager::m_lock_get_global_throttle_out);
589 epee::net_utils::network_throttle_manager::get_global_throttle_out().get_stats(res.total_packets_out, res.total_bytes_out);
590 }
591 res.status = CORE_RPC_STATUS_OK;
592 return true;
593 }
594 //------------------------------------------------------------------------------------------------------------------------------
595 class pruned_transaction {
596 transaction& tx;
597 public:
598 pruned_transaction(transaction& tx) : tx(tx) {}
599 BEGIN_SERIALIZE_OBJECT()
600 bool r = tx.serialize_base(ar);
601 if (!r) return false;
602 END_SERIALIZE()
603 };
604 //------------------------------------------------------------------------------------------------------------------------------
605 bool core_rpc_server::on_get_blocks(const COMMAND_RPC_GET_BLOCKS_FAST::request& req, COMMAND_RPC_GET_BLOCKS_FAST::response& res, const connection_context *ctx)
606 {
607 RPC_TRACKER(get_blocks);
608
609 bool use_bootstrap_daemon;
610 {
611 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
612 use_bootstrap_daemon = m_should_use_bootstrap_daemon;
613 }
614 if (use_bootstrap_daemon)
615 {
616 bool r;
617 return use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCKS_FAST>(invoke_http_mode::BIN, "/getblocks.bin", req, res, r);
618 }
619
620 CHECK_PAYMENT(req, res, 1);
621
622 res.daemon_time = (uint64_t)time(NULL);
623 // Always set daemon time, and set it early rather than late, as delivering some incremental pool
624 // info twice because of slightly overlapping time intervals is no problem, whereas producing gaps
625 // and never delivering something is
626
627 bool get_blocks = false;
628 bool get_pool = false;
629 switch (req.requested_info)
630 {
631 case COMMAND_RPC_GET_BLOCKS_FAST::BLOCKS_ONLY:
632 // Compatibility value 0: Clients that do not set 'requested_info' want blocks, and only blocks
633 get_blocks = true;
634 break;
635 case COMMAND_RPC_GET_BLOCKS_FAST::BLOCKS_AND_POOL:
636 get_blocks = true;
637 get_pool = true;
638 break;
639 case COMMAND_RPC_GET_BLOCKS_FAST::POOL_ONLY:
640 get_pool = true;
641 break;
642 default:
643 res.status = "Failed, wrong requested info";
644 return true;
645 }
646
647 res.pool_info_extent = COMMAND_RPC_GET_BLOCKS_FAST::NONE;
648
649 if (get_pool)
650 {
651 const bool restricted = m_restricted && ctx;
652 const bool request_has_rpc_origin = ctx != NULL;
653 const bool allow_sensitive = !request_has_rpc_origin || !restricted;
654 const size_t max_tx_count = restricted ? RESTRICTED_TRANSACTIONS_COUNT : std::numeric_limits<size_t>::max();
655
656 bool incremental;
657 std::vector<std::pair<crypto::hash, tx_memory_pool::tx_details>> added_pool_txs;
658 bool success = m_core.get_pool_info((time_t)req.pool_info_since, allow_sensitive, max_tx_count, added_pool_txs, res.remaining_added_pool_txids, res.removed_pool_txids, incremental);
659 if (success)
660 {
661 res.added_pool_txs.clear();
662 if (m_rpc_payment)
663 {
664 CHECK_PAYMENT_SAME_TS(req, res, added_pool_txs.size() * COST_PER_TX + (res.remaining_added_pool_txids.size() + res.removed_pool_txids.size()) * COST_PER_POOL_HASH);
665 }
666 for (const auto &added_pool_tx: added_pool_txs)
667 {
668 COMMAND_RPC_GET_BLOCKS_FAST::pool_tx_info info;
669 info.tx_hash = added_pool_tx.first;
670 std::stringstream oss;
671 binary_archive<true> ar(oss);
672 bool r = req.prune
673 ? const_cast<cryptonote::transaction&>(added_pool_tx.second.tx).serialize_base(ar)
674 : ::serialization::serialize(ar, const_cast<cryptonote::transaction&>(added_pool_tx.second.tx));
675 if (!r)
676 {
677 res.status = "Failed to serialize transaction";
678 return true;
679 }
680 info.tx_blob = oss.str();
681 info.double_spend_seen = added_pool_tx.second.double_spend_seen;
682 res.added_pool_txs.push_back(std::move(info));
683 }
684 }
685 if (success)
686 {
687 res.pool_info_extent = incremental ? COMMAND_RPC_GET_BLOCKS_FAST::INCREMENTAL : COMMAND_RPC_GET_BLOCKS_FAST::FULL;
688 }
689 else
690 {
691 res.status = "Failed to get pool info";
692 return true;
693 }
694 }
695
696 if (get_blocks)
697 {
698 // quick check for noop
699 if (!req.block_ids.empty())
700 {
701 uint64_t last_block_height;
702 crypto::hash last_block_hash;
703 m_core.get_blockchain_top(last_block_height, last_block_hash);
704 if (last_block_hash == req.block_ids.front())
705 {
706 res.start_height = 0;
707 res.current_height = last_block_height + 1;
708 res.status = CORE_RPC_STATUS_OK;
709 return true;
710 }
711 }
712
713 size_t max_blocks = COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT;
714 if (m_rpc_payment)
715 {
716 max_blocks = res.credits / COST_PER_BLOCK;
717 if (max_blocks > COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT)
718 max_blocks = COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT;
719 if (max_blocks == 0)
720 {
721 res.status = CORE_RPC_STATUS_PAYMENT_REQUIRED;
722 return true;
723 }
724 }
725
726 std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata> > > > bs;
727 if(!m_core.find_blockchain_supplement(req.start_height, req.block_ids, bs, res.current_height, res.start_height, req.prune, !req.no_miner_tx, max_blocks, COMMAND_RPC_GET_BLOCKS_FAST_MAX_TX_COUNT))
728 {
729 res.status = "Failed";
730 add_host_fail(ctx);
731 return true;
732 }
733
734 CHECK_PAYMENT_SAME_TS(req, res, bs.size() * COST_PER_BLOCK);
735
736 size_t size = 0, ntxes = 0;
737 res.blocks.reserve(bs.size());
738 res.output_indices.reserve(bs.size());
739 for(auto& bd: bs)
740 {
741 res.blocks.resize(res.blocks.size()+1);
742 res.blocks.back().pruned = req.prune;
743 res.blocks.back().block = bd.first.first;
744 size += bd.first.first.size();
745 res.output_indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices());
746 ntxes += bd.second.size();
747 res.output_indices.back().indices.reserve(1 + bd.second.size());
748 if (req.no_miner_tx)
749 res.output_indices.back().indices.push_back(COMMAND_RPC_GET_BLOCKS_FAST::tx_output_indices());
750 res.blocks.back().txs.reserve(bd.second.size());
751 for (std::vector<std::pair<crypto::hash, cryptonote::blobdata>>::iterator i = bd.second.begin(); i != bd.second.end(); ++i)
752 {
753 res.blocks.back().txs.push_back({std::move(i->second), crypto::null_hash});
754 i->second.clear();
755 i->second.shrink_to_fit();
756 size += res.blocks.back().txs.back().blob.size();
757 }
758
759 const size_t n_txes_to_lookup = bd.second.size() + (req.no_miner_tx ? 0 : 1);
760 if (n_txes_to_lookup > 0)
761 {
762 std::vector<std::vector<uint64_t>> indices;
763 bool r = m_core.get_tx_outputs_gindexs(req.no_miner_tx ? bd.second.front().first : bd.first.second, n_txes_to_lookup, indices);
764 if (!r)
765 {
766 res.status = "Failed";
767 return true;
768 }
769 if (indices.size() != n_txes_to_lookup || res.output_indices.back().indices.size() != (req.no_miner_tx ? 1 : 0))
770 {
771 res.status = "Failed";
772 return true;
773 }
774 for (size_t i = 0; i < indices.size(); ++i)
775 res.output_indices.back().indices.push_back({std::move(indices[i])});
776 }
777 }
778 MDEBUG("on_get_blocks: " << bs.size() << " blocks, " << ntxes << " txes, size " << size);
779 }
780
781 res.status = CORE_RPC_STATUS_OK;
782 return true;
783 }
784 bool core_rpc_server::on_get_alt_blocks_hashes(const COMMAND_RPC_GET_ALT_BLOCKS_HASHES::request& req, COMMAND_RPC_GET_ALT_BLOCKS_HASHES::response& res, const connection_context *ctx)
785 {
786 RPC_TRACKER(get_alt_blocks_hashes);
787 bool r;
788 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_ALT_BLOCKS_HASHES>(invoke_http_mode::JON, "/get_alt_blocks_hashes", req, res, r))
789 return r;
790
791 std::vector<block> blks;
792
793 if(!m_core.get_alternative_blocks(blks))
794 {
795 res.status = "Failed";
796 return true;
797 }
798
799 res.blks_hashes.reserve(blks.size());
800
801 for (auto const& blk: blks)
802 {
803 res.blks_hashes.push_back(epee::string_tools::pod_to_hex(get_block_hash(blk)));
804 }
805
806 MDEBUG("on_get_alt_blocks_hashes: " << blks.size() << " blocks " );
807 res.status = CORE_RPC_STATUS_OK;
808 return true;
809 }
810 //------------------------------------------------------------------------------------------------------------------------------
811 bool core_rpc_server::on_get_blocks_by_height(const COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::request& req, COMMAND_RPC_GET_BLOCKS_BY_HEIGHT::response& res, const connection_context *ctx)
812 {
813 RPC_TRACKER(get_blocks_by_height);
814 bool r;
815 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCKS_BY_HEIGHT>(invoke_http_mode::BIN, "/getblocks_by_height.bin", req, res, r))
816 return r;
817
818 const bool restricted = m_restricted && ctx;
819 if (restricted && req.heights.size() > RESTRICTED_BLOCK_COUNT)
820 {
821 res.status = "Too many blocks requested in restricted mode";
822 return true;
823 }
824
825 res.status = "Failed";
826 res.blocks.clear();
827 res.blocks.reserve(req.heights.size());
828 CHECK_PAYMENT_MIN1(req, res, req.heights.size() * COST_PER_BLOCK, false);
829 for (uint64_t height : req.heights)
830 {
831 block blk;
832 try
833 {
834 blk = m_core.get_blockchain_storage().get_db().get_block_from_height(height);
835 }
836 catch (...)
837 {
838 res.status = "Error retrieving block at height " + std::to_string(height);
839 return true;
840 }
841 std::vector<transaction> txs;
842 std::vector<crypto::hash> missed_txs;
843 m_core.get_transactions(blk.tx_hashes, txs, missed_txs);
844 res.blocks.resize(res.blocks.size() + 1);
845 res.blocks.back().block = block_to_blob(blk);
846 for (auto& tx : txs)
847 res.blocks.back().txs.push_back({tx_to_blob(tx), crypto::null_hash});
848 }
849 res.status = CORE_RPC_STATUS_OK;
850 return true;
851 }
852 //------------------------------------------------------------------------------------------------------------------------------
853 bool core_rpc_server::on_get_hashes(const COMMAND_RPC_GET_HASHES_FAST::request& req, COMMAND_RPC_GET_HASHES_FAST::response& res, const connection_context *ctx)
854 {
855 RPC_TRACKER(get_hashes);
856 bool r;
857 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_HASHES_FAST>(invoke_http_mode::BIN, "/gethashes.bin", req, res, r))
858 return r;
859
860 CHECK_PAYMENT(req, res, 1);
861
862 res.start_height = req.start_height;
863 if(!m_core.get_blockchain_storage().find_blockchain_supplement(req.block_ids, res.m_block_ids, NULL, res.start_height, res.current_height, false))
864 {
865 res.status = "Failed";
866 add_host_fail(ctx);
867 return true;
868 }
869
870 CHECK_PAYMENT_SAME_TS(req, res, res.m_block_ids.size() * COST_PER_BLOCK_HASH);
871
872 res.status = CORE_RPC_STATUS_OK;
873 return true;
874 }
875 //------------------------------------------------------------------------------------------------------------------------------
876 bool core_rpc_server::on_get_outs_bin(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res, const connection_context *ctx)
877 {
878 RPC_TRACKER(get_outs_bin);
879 bool r;
880 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_OUTPUTS_BIN>(invoke_http_mode::BIN, "/get_outs.bin", req, res, r))
881 return r;
882
883 CHECK_PAYMENT_MIN1(req, res, req.outputs.size() * COST_PER_OUT, false);
884
885 res.status = "Failed";
886
887 const bool restricted = m_restricted && ctx;
888 if (restricted)
889 {
890 if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT)
891 {
892 res.status = "Too many outs requested";
893 return true;
894 }
895 }
896
897 if(!m_core.get_outs(req, res))
898 {
899 return true;
900 }
901
902 res.status = CORE_RPC_STATUS_OK;
903 return true;
904 }
905 //------------------------------------------------------------------------------------------------------------------------------
906 bool core_rpc_server::on_get_outs(const COMMAND_RPC_GET_OUTPUTS::request& req, COMMAND_RPC_GET_OUTPUTS::response& res, const connection_context *ctx)
907 {
908 RPC_TRACKER(get_outs);
909 bool r;
910 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_OUTPUTS>(invoke_http_mode::JON, "/get_outs", req, res, r))
911 return r;
912
913 CHECK_PAYMENT_MIN1(req, res, req.outputs.size() * COST_PER_OUT, false);
914
915 res.status = "Failed";
916
917 const bool restricted = m_restricted && ctx;
918 if (restricted)
919 {
920 if (req.outputs.size() > MAX_RESTRICTED_GLOBAL_FAKE_OUTS_COUNT)
921 {
922 res.status = "Too many outs requested";
923 return true;
924 }
925 }
926
927 cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::request req_bin;
928 req_bin.outputs = req.outputs;
929 req_bin.get_txid = req.get_txid;
930 cryptonote::COMMAND_RPC_GET_OUTPUTS_BIN::response res_bin;
931 if(!m_core.get_outs(req_bin, res_bin))
932 {
933 return true;
934 }
935
936 // convert to text
937 for (const auto &i: res_bin.outs)
938 {
939 res.outs.push_back(cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey());
940 cryptonote::COMMAND_RPC_GET_OUTPUTS::outkey &outkey = res.outs.back();
941 outkey.key = epee::string_tools::pod_to_hex(i.key);
942 outkey.mask = epee::string_tools::pod_to_hex(i.mask);
943 outkey.unlocked = i.unlocked;
944 outkey.height = i.height;
945 if (req.get_txid)
946 outkey.txid = epee::string_tools::pod_to_hex(i.txid);
947 }
948
949 res.status = CORE_RPC_STATUS_OK;
950 return true;
951 }
952 //------------------------------------------------------------------------------------------------------------------------------
953 bool core_rpc_server::on_get_indexes(const COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::request& req, COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::response& res, const connection_context *ctx)
954 {
955 RPC_TRACKER(get_indexes);
956 bool ok;
957 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES>(invoke_http_mode::BIN, "/get_o_indexes.bin", req, res, ok))
958 return ok;
959
960 CHECK_PAYMENT_MIN1(req, res, COST_PER_OUTPUT_INDEXES, false);
961
962 bool r = m_core.get_tx_outputs_gindexs(req.txid, res.o_indexes);
963 if(!r)
964 {
965 res.status = "Failed";
966 return true;
967 }
968 res.status = CORE_RPC_STATUS_OK;
969 LOG_PRINT_L2("COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES: [" << res.o_indexes.size() << "]");
970 return true;
971 }
972 //------------------------------------------------------------------------------------------------------------------------------
973 bool core_rpc_server::on_get_transactions(const COMMAND_RPC_GET_TRANSACTIONS::request& req, COMMAND_RPC_GET_TRANSACTIONS::response& res, const connection_context *ctx)
974 {
975 RPC_TRACKER(get_transactions);
976 bool ok;
977 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTIONS>(invoke_http_mode::JON, "/gettransactions", req, res, ok))
978 return ok;
979
980 const bool restricted = m_restricted && ctx;
981 const bool request_has_rpc_origin = ctx != NULL;
982
983 if (restricted && req.txs_hashes.size() > RESTRICTED_TRANSACTIONS_COUNT)
984 {
985 res.status = "Too many transactions requested in restricted mode";
986 return true;
987 }
988
989 CHECK_PAYMENT_MIN1(req, res, req.txs_hashes.size() * COST_PER_TX, false);
990
991 std::vector<crypto::hash> vh;
992 for(const auto& tx_hex_str: req.txs_hashes)
993 {
994 blobdata b;
995 if(!string_tools::parse_hexstr_to_binbuff(tx_hex_str, b))
996 {
997 res.status = "Failed to parse hex representation of transaction hash";
998 return true;
999 }
1000 if(b.size() != sizeof(crypto::hash))
1001 {
1002 res.status = "Failed, size of data mismatch";
1003 return true;
1004 }
1005 vh.push_back(*reinterpret_cast<const crypto::hash*>(b.data()));
1006 }
1007 std::vector<crypto::hash> missed_txs;
1008 std::vector<std::tuple<crypto::hash, cryptonote::blobdata, crypto::hash, cryptonote::blobdata>> txs;
1009 bool r = m_core.get_split_transactions_blobs(vh, txs, missed_txs);
1010 if(!r)
1011 {
1012 res.status = "Failed";
1013 return true;
1014 }
1015 LOG_PRINT_L2("Found " << txs.size() << "/" << vh.size() << " transactions on the blockchain");
1016
1017 // try the pool for any missing txes
1018 size_t found_in_pool = 0;
1019 std::unordered_set<crypto::hash> pool_tx_hashes;
1020 std::unordered_map<crypto::hash, tx_memory_pool::tx_details> per_tx_pool_tx_details;
1021 if (!missed_txs.empty())
1022 {
1023 std::vector<std::pair<crypto::hash, tx_memory_pool::tx_details>> pool_txs;
1024 bool r = m_core.get_pool_transactions_info(missed_txs, pool_txs, !request_has_rpc_origin || !restricted);
1025 if(r)
1026 {
1027 // sort to match original request
1028 std::vector<std::tuple<crypto::hash, cryptonote::blobdata, crypto::hash, cryptonote::blobdata>> sorted_txs;
1029 std::vector<std::pair<crypto::hash, tx_memory_pool::tx_details>>::const_iterator i;
1030 unsigned txs_processed = 0;
1031 for (const crypto::hash &h: vh)
1032 {
1033 if (std::find(missed_txs.begin(), missed_txs.end(), h) == missed_txs.end())
1034 {
1035 if (txs.size() == txs_processed)
1036 {
1037 res.status = "Failed: internal error - txs is empty";
1038 return true;
1039 }
1040 // core returns the ones it finds in the right order
1041 if (std::get<0>(txs[txs_processed]) != h)
1042 {
1043 res.status = "Failed: tx hash mismatch";
1044 return true;
1045 }
1046 sorted_txs.push_back(std::move(txs[txs_processed]));
1047 ++txs_processed;
1048 }
1049 else if ((i = std::find_if(pool_txs.begin(), pool_txs.end(), [h](const std::pair<crypto::hash, tx_memory_pool::tx_details> &pt) { return h == pt.first; })) != pool_txs.end())
1050 {
1051 const tx_memory_pool::tx_details &td = i->second;
1052 std::stringstream ss;
1053 binary_archive<true> ba(ss);
1054 bool r = const_cast<cryptonote::transaction&>(td.tx).serialize_base(ba);
1055 if (!r)
1056 {
1057 res.status = "Failed to serialize transaction base";
1058 return true;
1059 }
1060 const cryptonote::blobdata pruned = ss.str();
1061 const crypto::hash prunable_hash = td.tx.version == 1 ? crypto::null_hash : get_transaction_prunable_hash(td.tx);
1062 sorted_txs.push_back(std::make_tuple(h, pruned, prunable_hash, std::string(td.tx_blob, pruned.size())));
1063 missed_txs.erase(std::find(missed_txs.begin(), missed_txs.end(), h));
1064 pool_tx_hashes.insert(h);
1065 per_tx_pool_tx_details.insert(std::make_pair(h, td));
1066 ++found_in_pool;
1067 }
1068 }
1069 txs = sorted_txs;
1070 }
1071 LOG_PRINT_L2("Found " << found_in_pool << "/" << vh.size() << " transactions in the pool");
1072 }
1073
1074 CHECK_AND_ASSERT_MES(txs.size() + missed_txs.size() == vh.size(), false, "mismatched number of txs");
1075
1076 auto txhi = req.txs_hashes.cbegin();
1077 auto vhi = vh.cbegin();
1078 auto missedi = missed_txs.cbegin();
1079
1080 for(auto& tx: txs)
1081 {
1082 res.txs.push_back(COMMAND_RPC_GET_TRANSACTIONS::entry());
1083 COMMAND_RPC_GET_TRANSACTIONS::entry &e = res.txs.back();
1084
1085 while (missedi != missed_txs.end() && *missedi == *vhi)
1086 {
1087 ++vhi;
1088 ++txhi;
1089 ++missedi;
1090 }
1091
1092 crypto::hash tx_hash = *vhi++;
1093 CHECK_AND_ASSERT_MES(tx_hash == std::get<0>(tx), false, "mismatched tx hash");
1094 e.tx_hash = *txhi++;
1095 e.prunable_hash = epee::string_tools::pod_to_hex(std::get<2>(tx));
1096 if (req.split || req.prune || std::get<3>(tx).empty())
1097 {
1098 // use splitted form with pruned and prunable (filled only when prune=false and the daemon has it), leaving as_hex as empty
1099 e.pruned_as_hex = string_tools::buff_to_hex_nodelimer(std::get<1>(tx));
1100 if (!req.prune)
1101 e.prunable_as_hex = string_tools::buff_to_hex_nodelimer(std::get<3>(tx));
1102 if (req.decode_as_json)
1103 {
1104 cryptonote::blobdata tx_data;
1105 cryptonote::transaction t;
1106 if (req.prune || std::get<3>(tx).empty())
1107 {
1108 // decode pruned tx to JSON
1109 tx_data = std::get<1>(tx);
1110 if (cryptonote::parse_and_validate_tx_base_from_blob(tx_data, t))
1111 {
1112 pruned_transaction pruned_tx{t};
1113 e.as_json = obj_to_json_str(pruned_tx);
1114 }
1115 else
1116 {
1117 res.status = "Failed to parse and validate pruned tx from blob";
1118 return true;
1119 }
1120 }
1121 else
1122 {
1123 // decode full tx to JSON
1124 tx_data = std::get<1>(tx) + std::get<3>(tx);
1125 if (cryptonote::parse_and_validate_tx_from_blob(tx_data, t))
1126 {
1127 e.as_json = obj_to_json_str(t);
1128 }
1129 else
1130 {
1131 res.status = "Failed to parse and validate tx from blob";
1132 return true;
1133 }
1134 }
1135 }
1136 }
1137 else
1138 {
1139 // use non-splitted form, leaving pruned_as_hex and prunable_as_hex as empty
1140 cryptonote::blobdata tx_data = std::get<1>(tx) + std::get<3>(tx);
1141 e.as_hex = string_tools::buff_to_hex_nodelimer(tx_data);
1142 if (req.decode_as_json)
1143 {
1144 cryptonote::transaction t;
1145 if (cryptonote::parse_and_validate_tx_from_blob(tx_data, t))
1146 {
1147 e.as_json = obj_to_json_str(t);
1148 }
1149 else
1150 {
1151 res.status = "Failed to parse and validate tx from blob";
1152 return true;
1153 }
1154 }
1155 }
1156 e.in_pool = pool_tx_hashes.find(tx_hash) != pool_tx_hashes.end();
1157 if (e.in_pool)
1158 {
1159 e.block_height = e.block_timestamp = std::numeric_limits<uint64_t>::max();
1160 e.confirmations = 0;
1161 auto it = per_tx_pool_tx_details.find(tx_hash);
1162 if (it != per_tx_pool_tx_details.end())
1163 {
1164 e.double_spend_seen = it->second.double_spend_seen;
1165 e.relayed = it->second.relayed;
1166 e.received_timestamp = it->second.receive_time;
1167 }
1168 else
1169 {
1170 MERROR("Failed to determine pool info for " << tx_hash);
1171 e.double_spend_seen = false;
1172 e.relayed = false;
1173 e.received_timestamp = 0;
1174 }
1175 }
1176 else
1177 {
1178 e.block_height = m_core.get_blockchain_storage().get_db().get_tx_block_height(tx_hash);
1179 e.confirmations = m_core.get_current_blockchain_height() - e.block_height;
1180 e.block_timestamp = m_core.get_blockchain_storage().get_db().get_block_timestamp(e.block_height);
1181 e.received_timestamp = 0;
1182 e.double_spend_seen = false;
1183 e.relayed = false;
1184 }
1185
1186 // fill up old style responses too, in case an old wallet asks
1187 res.txs_as_hex.push_back(e.as_hex);
1188 if (req.decode_as_json)
1189 res.txs_as_json.push_back(e.as_json);
1190
1191 // output indices too if not in pool
1192 if (pool_tx_hashes.find(tx_hash) == pool_tx_hashes.end())
1193 {
1194 bool r = m_core.get_tx_outputs_gindexs(tx_hash, e.output_indices);
1195 if (!r)
1196 {
1197 res.status = "Failed";
1198 return true;
1199 }
1200 }
1201 }
1202
1203 for(const auto& miss_tx: missed_txs)
1204 {
1205 res.missed_tx.push_back(string_tools::pod_to_hex(miss_tx));
1206 }
1207
1208 LOG_PRINT_L2(res.txs.size() << " transactions found, " << res.missed_tx.size() << " not found");
1209 res.status = CORE_RPC_STATUS_OK;
1210 return true;
1211 }
1212 //------------------------------------------------------------------------------------------------------------------------------
1213 bool core_rpc_server::on_is_key_image_spent(const COMMAND_RPC_IS_KEY_IMAGE_SPENT::request& req, COMMAND_RPC_IS_KEY_IMAGE_SPENT::response& res, const connection_context *ctx)
1214 {
1215 RPC_TRACKER(is_key_image_spent);
1216 bool ok;
1217 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_IS_KEY_IMAGE_SPENT>(invoke_http_mode::JON, "/is_key_image_spent", req, res, ok))
1218 return ok;
1219
1220 const bool restricted = m_restricted && ctx;
1221 const bool request_has_rpc_origin = ctx != NULL;
1222
1223 if (restricted && req.key_images.size() > RESTRICTED_SPENT_KEY_IMAGES_COUNT)
1224 {
1225 res.status = "Too many key images queried in restricted mode";
1226 return true;
1227 }
1228
1229 CHECK_PAYMENT_MIN1(req, res, req.key_images.size() * COST_PER_KEY_IMAGE, false);
1230
1231 std::vector<crypto::key_image> key_images;
1232 for(const auto& ki_hex_str: req.key_images)
1233 {
1234 blobdata b;
1235 if(!string_tools::parse_hexstr_to_binbuff(ki_hex_str, b))
1236 {
1237 res.status = "Failed to parse hex representation of key image";
1238 return true;
1239 }
1240 if(b.size() != sizeof(crypto::key_image))
1241 {
1242 res.status = "Failed, size of data mismatch";
1243 }
1244 key_images.push_back(*reinterpret_cast<const crypto::key_image*>(b.data()));
1245 }
1246 std::vector<bool> spent_status;
1247 bool r = m_core.are_key_images_spent(key_images, spent_status);
1248 if(!r)
1249 {
1250 res.status = "Failed";
1251 return true;
1252 }
1253 res.spent_status.clear();
1254 for (size_t n = 0; n < spent_status.size(); ++n)
1255 res.spent_status.push_back(spent_status[n] ? COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_BLOCKCHAIN : COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT);
1256
1257 // check the pool too
1258 std::vector<cryptonote::tx_info> txs;
1259 std::vector<cryptonote::spent_key_image_info> ki;
1260 r = m_core.get_pool_transactions_and_spent_keys_info(txs, ki, !request_has_rpc_origin || !restricted);
1261 if(!r)
1262 {
1263 res.status = "Failed";
1264 return true;
1265 }
1266 for (std::vector<cryptonote::spent_key_image_info>::const_iterator i = ki.begin(); i != ki.end(); ++i)
1267 {
1268 crypto::hash hash;
1269 crypto::key_image spent_key_image;
1270 if (parse_hash256(i->id_hash, hash))
1271 {
1272 memcpy(&spent_key_image, &hash, sizeof(hash)); // a bit dodgy, should be other parse functions somewhere
1273 for (size_t n = 0; n < res.spent_status.size(); ++n)
1274 {
1275 if (res.spent_status[n] == COMMAND_RPC_IS_KEY_IMAGE_SPENT::UNSPENT)
1276 {
1277 if (key_images[n] == spent_key_image)
1278 {
1279 res.spent_status[n] = COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_POOL;
1280 break;
1281 }
1282 }
1283 }
1284 }
1285 }
1286
1287 res.status = CORE_RPC_STATUS_OK;
1288 return true;
1289 }
1290 //------------------------------------------------------------------------------------------------------------------------------
1291 bool core_rpc_server::on_send_raw_tx(const COMMAND_RPC_SEND_RAW_TX::request& req, COMMAND_RPC_SEND_RAW_TX::response& res, const connection_context *ctx)
1292 {
1293 RPC_TRACKER(send_raw_tx);
1294
1295 {
1296 bool ok;
1297 use_bootstrap_daemon_if_necessary<COMMAND_RPC_SEND_RAW_TX>(invoke_http_mode::JON, "/sendrawtransaction", req, res, ok);
1298 }
1299
1300 const bool restricted = m_restricted && ctx;
1301
1302 bool skip_validation = false;
1303 if (!restricted)
1304 {
1305 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
1306 if (m_should_use_bootstrap_daemon)
1307 {
1308 skip_validation = !check_core_ready();
1309 }
1310 else
1311 {
1312 CHECK_CORE_READY();
1313 }
1314 }
1315 else
1316 {
1317 CHECK_CORE_READY();
1318 }
1319
1320 CHECK_PAYMENT_MIN1(req, res, COST_PER_TX_RELAY, false);
1321
1322 std::string tx_blob;
1323 if(!string_tools::parse_hexstr_to_binbuff(req.tx_as_hex, tx_blob))
1324 {
1325 LOG_PRINT_L0("[on_send_raw_tx]: Failed to parse tx from hexbuff: " << req.tx_as_hex);
1326 res.status = "Failed";
1327 return true;
1328 }
1329
1330 if (req.do_sanity_checks && !cryptonote::tx_sanity_check(tx_blob, m_core.get_blockchain_storage().get_num_mature_outputs(0)))
1331 {
1332 res.status = "Failed";
1333 res.reason = "Sanity check failed";
1334 res.sanity_check_failed = true;
1335 return true;
1336 }
1337 res.sanity_check_failed = false;
1338
1339 if (!skip_validation)
1340 {
1341 tx_verification_context tvc{};
1342 if(!m_core.handle_incoming_tx(tx_blob, tvc, (req.do_not_relay ? relay_method::none : relay_method::local), false) || tvc.m_verifivation_failed)
1343 {
1344 res.status = "Failed";
1345 std::string reason = "";
1346 if ((res.low_mixin = tvc.m_low_mixin))
1347 add_reason(reason, "bad ring size");
1348 if ((res.double_spend = tvc.m_double_spend))
1349 add_reason(reason, "double spend");
1350 if ((res.invalid_input = tvc.m_invalid_input))
1351 add_reason(reason, "invalid input");
1352 if ((res.invalid_output = tvc.m_invalid_output))
1353 add_reason(reason, "invalid output");
1354 if ((res.too_big = tvc.m_too_big))
1355 add_reason(reason, "too big");
1356 if ((res.overspend = tvc.m_overspend))
1357 add_reason(reason, "overspend");
1358 if ((res.fee_too_low = tvc.m_fee_too_low))
1359 add_reason(reason, "fee too low");
1360 if ((res.too_few_outputs = tvc.m_too_few_outputs))
1361 add_reason(reason, "too few outputs");
1362 if ((res.tx_extra_too_big = tvc.m_tx_extra_too_big))
1363 add_reason(reason, "tx-extra too big");
1364 if ((res.nonzero_unlock_time = tvc.m_nonzero_unlock_time))
1365 add_reason(reason, "tx unlock time is not zero");
1366 const std::string punctuation = reason.empty() ? "" : ": ";
1367 if (tvc.m_verifivation_failed)
1368 {
1369 LOG_PRINT_L0("[on_send_raw_tx]: tx verification failed" << punctuation << reason);
1370 }
1371 else
1372 {
1373 LOG_PRINT_L0("[on_send_raw_tx]: Failed to process tx" << punctuation << reason);
1374 }
1375 return true;
1376 }
1377
1378 if(tvc.m_relay == relay_method::none)
1379 {
1380 LOG_PRINT_L0("[on_send_raw_tx]: tx accepted, but not relayed");
1381 res.reason = "Not relayed";
1382 res.not_relayed = true;
1383 res.status = CORE_RPC_STATUS_OK;
1384 return true;
1385 }
1386 }
1387
1388 NOTIFY_NEW_TRANSACTIONS::request r;
1389 r.txs.push_back(std::move(tx_blob));
1390 m_core.get_protocol()->relay_transactions(r, boost::uuids::nil_uuid(), epee::net_utils::zone::invalid, relay_method::local);
1391 //TODO: make sure that tx has reached other nodes here, probably wait to receive reflections from other nodes
1392 res.status = CORE_RPC_STATUS_OK;
1393 return true;
1394 }
1395 //------------------------------------------------------------------------------------------------------------------------------
1396 bool core_rpc_server::on_start_mining(const COMMAND_RPC_START_MINING::request& req, COMMAND_RPC_START_MINING::response& res, const connection_context *ctx)
1397 {
1398 RPC_TRACKER(start_mining);
1399 CHECK_CORE_READY();
1400 cryptonote::address_parse_info info;
1401 if(!get_account_address_from_str(info, nettype(), req.miner_address))
1402 {
1403 res.status = "Failed, wrong address";
1404 LOG_PRINT_L0(res.status);
1405 return true;
1406 }
1407 if (info.is_subaddress)
1408 {
1409 res.status = "Mining to subaddress isn't supported yet";
1410 LOG_PRINT_L0(res.status);
1411 return true;
1412 }
1413
1414 unsigned int concurrency_count = boost::thread::hardware_concurrency() * 4;
1415
1416 // if we couldn't detect threads, set it to a ridiculously high number
1417 if(concurrency_count == 0)
1418 {
1419 concurrency_count = 257;
1420 }
1421
1422 // if there are more threads requested than the hardware supports
1423 // then we fail and log that.
1424 if(req.threads_count > concurrency_count)
1425 {
1426 res.status = "Failed, too many threads relative to CPU cores.";
1427 LOG_PRINT_L0(res.status);
1428 return true;
1429 }
1430
1431 cryptonote::miner &miner= m_core.get_miner();
1432 if (miner.is_mining())
1433 {
1434 res.status = "Already mining";
1435 return true;
1436 }
1437 if(!miner.start(info.address, static_cast<size_t>(req.threads_count), req.do_background_mining, req.ignore_battery))
1438 {
1439 res.status = "Failed, mining not started";
1440 LOG_PRINT_L0(res.status);
1441 return true;
1442 }
1443 res.status = CORE_RPC_STATUS_OK;
1444 return true;
1445 }
1446 //------------------------------------------------------------------------------------------------------------------------------
1447 bool core_rpc_server::on_stop_mining(const COMMAND_RPC_STOP_MINING::request& req, COMMAND_RPC_STOP_MINING::response& res, const connection_context *ctx)
1448 {
1449 RPC_TRACKER(stop_mining);
1450 cryptonote::miner &miner= m_core.get_miner();
1451 if(!miner.is_mining())
1452 {
1453 res.status = "Mining never started";
1454 LOG_PRINT_L0(res.status);
1455 return true;
1456 }
1457 if(!miner.stop())
1458 {
1459 res.status = "Failed, mining not stopped";
1460 LOG_PRINT_L0(res.status);
1461 return true;
1462 }
1463 res.status = CORE_RPC_STATUS_OK;
1464 return true;
1465 }
1466 //------------------------------------------------------------------------------------------------------------------------------
1467 bool core_rpc_server::on_mining_status(const COMMAND_RPC_MINING_STATUS::request& req, COMMAND_RPC_MINING_STATUS::response& res, const connection_context *ctx)
1468 {
1469 RPC_TRACKER(mining_status);
1470
1471 const miner& lMiner = m_core.get_miner();
1472 res.active = lMiner.is_mining();
1473 res.is_background_mining_enabled = lMiner.get_is_background_mining_enabled();
1474 store_difficulty(m_core.get_blockchain_storage().get_difficulty_for_next_block(), res.difficulty, res.wide_difficulty, res.difficulty_top64);
1475
1476 res.block_target = m_core.get_blockchain_storage().get_current_hard_fork_version() < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2;
1477 if ( lMiner.is_mining() ) {
1478 res.speed = lMiner.get_speed();
1479 res.threads_count = lMiner.get_threads_count();
1480 res.block_reward = lMiner.get_block_reward();
1481 }
1482 const account_public_address& lMiningAdr = lMiner.get_mining_address();
1483 if (lMiner.is_mining() || lMiner.get_is_background_mining_enabled())
1484 res.address = get_account_address_as_str(nettype(), false, lMiningAdr);
1485 const uint8_t major_version = m_core.get_blockchain_storage().get_current_hard_fork_version();
1486 const unsigned variant = major_version >= 7 ? major_version - 6 : 0;
1487 switch (variant)
1488 {
1489 case 0: res.pow_algorithm = "Cryptonight"; break;
1490 case 1: res.pow_algorithm = "CNv1 (Cryptonight variant 1)"; break;
1491 case 2: case 3: res.pow_algorithm = "CNv2 (Cryptonight variant 2)"; break;
1492 case 4: case 5: res.pow_algorithm = "CNv4 (Cryptonight variant 4)"; break;
1493 case 6: case 7: case 8: case 9: res.pow_algorithm = "RandomX"; break;
1494 default: res.pow_algorithm = "RandomX"; break; // assumed
1495 }
1496 if (res.is_background_mining_enabled)
1497 {
1498 res.bg_idle_threshold = lMiner.get_idle_threshold();
1499 res.bg_min_idle_seconds = lMiner.get_min_idle_seconds();
1500 res.bg_ignore_battery = lMiner.get_ignore_battery();
1501 res.bg_target = lMiner.get_mining_target();
1502 }
1503
1504 res.status = CORE_RPC_STATUS_OK;
1505 return true;
1506 }
1507 //------------------------------------------------------------------------------------------------------------------------------
1508 bool core_rpc_server::on_save_bc(const COMMAND_RPC_SAVE_BC::request& req, COMMAND_RPC_SAVE_BC::response& res, const connection_context *ctx)
1509 {
1510 RPC_TRACKER(save_bc);
1511 if( !m_core.get_blockchain_storage().store_blockchain() )
1512 {
1513 res.status = "Error while storing blockchain";
1514 return true;
1515 }
1516 res.status = CORE_RPC_STATUS_OK;
1517 return true;
1518 }
1519 //------------------------------------------------------------------------------------------------------------------------------
1520 bool core_rpc_server::on_get_peer_list(const COMMAND_RPC_GET_PEER_LIST::request& req, COMMAND_RPC_GET_PEER_LIST::response& res, const connection_context *ctx)
1521 {
1522 RPC_TRACKER(get_peer_list);
1523 std::vector<nodetool::peerlist_entry> white_list;
1524 std::vector<nodetool::peerlist_entry> gray_list;
1525
1526 if (req.public_only)
1527 {
1528 m_p2p.get_public_peerlist(gray_list, white_list);
1529 }
1530 else
1531 {
1532 m_p2p.get_peerlist(gray_list, white_list);
1533 }
1534
1535 for (auto & entry : white_list)
1536 {
1537 if (!req.include_blocked && m_p2p.is_host_blocked(entry.adr, NULL))
1538 continue;
1539 if (entry.adr.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
1540 res.white_list.emplace_back(entry.id, entry.adr.as<epee::net_utils::ipv4_network_address>().ip(),
1541 entry.adr.as<epee::net_utils::ipv4_network_address>().port(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1542 else if (entry.adr.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id())
1543 res.white_list.emplace_back(entry.id, entry.adr.as<epee::net_utils::ipv6_network_address>().host_str(),
1544 entry.adr.as<epee::net_utils::ipv6_network_address>().port(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1545 else
1546 res.white_list.emplace_back(entry.id, entry.adr.str(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1547 }
1548
1549 for (auto & entry : gray_list)
1550 {
1551 if (!req.include_blocked && m_p2p.is_host_blocked(entry.adr, NULL))
1552 continue;
1553 if (entry.adr.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
1554 res.gray_list.emplace_back(entry.id, entry.adr.as<epee::net_utils::ipv4_network_address>().ip(),
1555 entry.adr.as<epee::net_utils::ipv4_network_address>().port(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1556 else if (entry.adr.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id())
1557 res.gray_list.emplace_back(entry.id, entry.adr.as<epee::net_utils::ipv6_network_address>().host_str(),
1558 entry.adr.as<epee::net_utils::ipv6_network_address>().port(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1559 else
1560 res.gray_list.emplace_back(entry.id, entry.adr.str(), entry.last_seen, entry.pruning_seed, entry.rpc_port, entry.rpc_credits_per_hash);
1561 }
1562
1563 res.status = CORE_RPC_STATUS_OK;
1564 return true;
1565 }
1566 //------------------------------------------------------------------------------------------------------------------------------
1567 bool core_rpc_server::on_get_public_nodes(const COMMAND_RPC_GET_PUBLIC_NODES::request& req, COMMAND_RPC_GET_PUBLIC_NODES::response& res, const connection_context *ctx)
1568 {
1569 RPC_TRACKER(get_public_nodes);
1570
1571 COMMAND_RPC_GET_PEER_LIST::request peer_list_req;
1572 COMMAND_RPC_GET_PEER_LIST::response peer_list_res;
1573 peer_list_req.include_blocked = req.include_blocked;
1574 const bool success = on_get_peer_list(peer_list_req, peer_list_res, ctx);
1575 res.status = peer_list_res.status;
1576 if (!success)
1577 {
1578 res.status = "Failed to get peer list";
1579 return true;
1580 }
1581 if (res.status != CORE_RPC_STATUS_OK)
1582 {
1583 return true;
1584 }
1585
1586 const auto collect = [](const std::vector<peer> &peer_list, std::vector<public_node> &public_nodes)
1587 {
1588 for (const auto &entry : peer_list)
1589 {
1590 if (entry.rpc_port != 0)
1591 {
1592 public_nodes.emplace_back(entry);
1593 }
1594 }
1595 };
1596
1597 if (req.white)
1598 {
1599 collect(peer_list_res.white_list, res.white);
1600 }
1601 if (req.gray)
1602 {
1603 collect(peer_list_res.gray_list, res.gray);
1604 }
1605
1606 return true;
1607 }
1608 //------------------------------------------------------------------------------------------------------------------------------
1609 bool core_rpc_server::on_set_log_hash_rate(const COMMAND_RPC_SET_LOG_HASH_RATE::request& req, COMMAND_RPC_SET_LOG_HASH_RATE::response& res, const connection_context *ctx)
1610 {
1611 RPC_TRACKER(set_log_hash_rate);
1612 if(m_core.get_miner().is_mining())
1613 {
1614 m_core.get_miner().do_print_hashrate(req.visible);
1615 res.status = CORE_RPC_STATUS_OK;
1616 }
1617 else
1618 {
1619 res.status = CORE_RPC_STATUS_NOT_MINING;
1620 }
1621 return true;
1622 }
1623 //------------------------------------------------------------------------------------------------------------------------------
1624 bool core_rpc_server::on_set_log_level(const COMMAND_RPC_SET_LOG_LEVEL::request& req, COMMAND_RPC_SET_LOG_LEVEL::response& res, const connection_context *ctx)
1625 {
1626 RPC_TRACKER(set_log_level);
1627 if (req.level < 0 || req.level > 4)
1628 {
1629 res.status = "Error: log level not valid";
1630 return true;
1631 }
1632 mlog_set_log_level(req.level);
1633 res.status = CORE_RPC_STATUS_OK;
1634 return true;
1635 }
1636 //------------------------------------------------------------------------------------------------------------------------------
1637 bool core_rpc_server::on_set_log_categories(const COMMAND_RPC_SET_LOG_CATEGORIES::request& req, COMMAND_RPC_SET_LOG_CATEGORIES::response& res, const connection_context *ctx)
1638 {
1639 RPC_TRACKER(set_log_categories);
1640 mlog_set_log(req.categories.c_str());
1641 res.categories = mlog_get_categories();
1642 res.status = CORE_RPC_STATUS_OK;
1643 return true;
1644 }
1645 //------------------------------------------------------------------------------------------------------------------------------
1646 bool core_rpc_server::on_get_transaction_pool(const COMMAND_RPC_GET_TRANSACTION_POOL::request& req, COMMAND_RPC_GET_TRANSACTION_POOL::response& res, const connection_context *ctx)
1647 {
1648 RPC_TRACKER(get_transaction_pool);
1649 bool r;
1650 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTION_POOL>(invoke_http_mode::JON, "/get_transaction_pool", req, res, r))
1651 return r;
1652
1653 CHECK_PAYMENT(req, res, 1);
1654
1655 const bool restricted = m_restricted && ctx;
1656 const bool request_has_rpc_origin = ctx != NULL;
1657 const bool allow_sensitive = !request_has_rpc_origin || !restricted;
1658
1659 size_t n_txes = m_core.get_pool_transactions_count(allow_sensitive);
1660 if (n_txes > 0)
1661 {
1662 CHECK_PAYMENT_SAME_TS(req, res, n_txes * COST_PER_TX);
1663 m_core.get_pool_transactions_and_spent_keys_info(res.transactions, res.spent_key_images, allow_sensitive);
1664 for (tx_info& txi : res.transactions)
1665 txi.tx_blob = epee::string_tools::buff_to_hex_nodelimer(txi.tx_blob);
1666 }
1667
1668 res.status = CORE_RPC_STATUS_OK;
1669 return true;
1670 }
1671 //------------------------------------------------------------------------------------------------------------------------------
1672 bool core_rpc_server::on_get_transaction_pool_hashes_bin(const COMMAND_RPC_GET_TRANSACTION_POOL_HASHES_BIN::request& req, COMMAND_RPC_GET_TRANSACTION_POOL_HASHES_BIN::response& res, const connection_context *ctx)
1673 {
1674 RPC_TRACKER(get_transaction_pool_hashes);
1675 bool r;
1676 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTION_POOL_HASHES_BIN>(invoke_http_mode::JON, "/get_transaction_pool_hashes.bin", req, res, r))
1677 return r;
1678
1679 CHECK_PAYMENT(req, res, 1);
1680
1681 const bool restricted = m_restricted && ctx;
1682 const bool request_has_rpc_origin = ctx != NULL;
1683 const bool allow_sensitive = !request_has_rpc_origin || !restricted;
1684
1685 size_t n_txes = m_core.get_pool_transactions_count(allow_sensitive);
1686 if (n_txes > 0)
1687 {
1688 CHECK_PAYMENT_SAME_TS(req, res, n_txes * COST_PER_POOL_HASH);
1689 m_core.get_pool_transaction_hashes(res.tx_hashes, allow_sensitive);
1690 }
1691
1692 res.status = CORE_RPC_STATUS_OK;
1693 return true;
1694 }
1695 //------------------------------------------------------------------------------------------------------------------------------
1696 bool core_rpc_server::on_get_transaction_pool_hashes(const COMMAND_RPC_GET_TRANSACTION_POOL_HASHES::request& req, COMMAND_RPC_GET_TRANSACTION_POOL_HASHES::response& res, const connection_context *ctx)
1697 {
1698 RPC_TRACKER(get_transaction_pool_hashes);
1699 bool r;
1700 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTION_POOL_HASHES>(invoke_http_mode::JON, "/get_transaction_pool_hashes", req, res, r))
1701 return r;
1702
1703 CHECK_PAYMENT(req, res, 1);
1704
1705 const bool restricted = m_restricted && ctx;
1706 const bool request_has_rpc_origin = ctx != NULL;
1707 const bool allow_sensitive = !request_has_rpc_origin || !restricted;
1708
1709 size_t n_txes = m_core.get_pool_transactions_count(allow_sensitive);
1710 if (n_txes > 0)
1711 {
1712 CHECK_PAYMENT_SAME_TS(req, res, n_txes * COST_PER_POOL_HASH);
1713 std::vector<crypto::hash> tx_hashes;
1714 m_core.get_pool_transaction_hashes(tx_hashes, allow_sensitive);
1715 res.tx_hashes.reserve(tx_hashes.size());
1716 for (const crypto::hash &tx_hash: tx_hashes)
1717 res.tx_hashes.push_back(epee::string_tools::pod_to_hex(tx_hash));
1718 }
1719
1720 res.status = CORE_RPC_STATUS_OK;
1721 return true;
1722 }
1723 //------------------------------------------------------------------------------------------------------------------------------
1724 bool core_rpc_server::on_get_transaction_pool_stats(const COMMAND_RPC_GET_TRANSACTION_POOL_STATS::request& req, COMMAND_RPC_GET_TRANSACTION_POOL_STATS::response& res, const connection_context *ctx)
1725 {
1726 RPC_TRACKER(get_transaction_pool_stats);
1727 bool r;
1728 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTION_POOL_STATS>(invoke_http_mode::JON, "/get_transaction_pool_stats", req, res, r))
1729 return r;
1730
1731 CHECK_PAYMENT_MIN1(req, res, COST_PER_TX_POOL_STATS, false);
1732
1733 const bool restricted = m_restricted && ctx;
1734 const bool request_has_rpc_origin = ctx != NULL;
1735 m_core.get_pool_transaction_stats(res.pool_stats, !request_has_rpc_origin || !restricted);
1736
1737 res.status = CORE_RPC_STATUS_OK;
1738 return true;
1739 }
1740 //------------------------------------------------------------------------------------------------------------------------------
1741 bool core_rpc_server::on_set_bootstrap_daemon(const COMMAND_RPC_SET_BOOTSTRAP_DAEMON::request& req, COMMAND_RPC_SET_BOOTSTRAP_DAEMON::response& res, const connection_context *ctx)
1742 {
1743 PERF_TIMER(on_set_bootstrap_daemon);
1744
1745 boost::optional<epee::net_utils::http::login> credentials;
1746 if (!req.username.empty() || !req.password.empty())
1747 {
1748 credentials = epee::net_utils::http::login(req.username, req.password);
1749 }
1750
1751 if (set_bootstrap_daemon(req.address, credentials, req.proxy))
1752 {
1753 res.status = CORE_RPC_STATUS_OK;
1754 }
1755 else
1756 {
1757 res.status = "Failed to set bootstrap daemon";
1758 }
1759
1760 return true;
1761 }
1762 //------------------------------------------------------------------------------------------------------------------------------
1763 bool core_rpc_server::on_stop_daemon(const COMMAND_RPC_STOP_DAEMON::request& req, COMMAND_RPC_STOP_DAEMON::response& res, const connection_context *ctx)
1764 {
1765 RPC_TRACKER(stop_daemon);
1766 // FIXME: replace back to original m_p2p.send_stop_signal() after
1767 // investigating why that isn't working quite right.
1768 m_p2p.send_stop_signal();
1769 res.status = CORE_RPC_STATUS_OK;
1770 return true;
1771 }
1772 //------------------------------------------------------------------------------------------------------------------------------
1773 bool core_rpc_server::on_getblockcount(const COMMAND_RPC_GETBLOCKCOUNT::request& req, COMMAND_RPC_GETBLOCKCOUNT::response& res, const connection_context *ctx)
1774 {
1775 RPC_TRACKER(getblockcount);
1776 {
1777 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
1778 if (m_should_use_bootstrap_daemon)
1779 {
1780 res.status = "This command is unsupported for bootstrap daemon";
1781 return true;
1782 }
1783 }
1784 res.count = m_core.get_current_blockchain_height();
1785 res.status = CORE_RPC_STATUS_OK;
1786 return true;
1787 }
1788 //------------------------------------------------------------------------------------------------------------------------------
1789 bool core_rpc_server::on_getblockhash(const COMMAND_RPC_GETBLOCKHASH::request& req, COMMAND_RPC_GETBLOCKHASH::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
1790 {
1791 RPC_TRACKER(getblockhash);
1792 {
1793 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
1794 if (m_should_use_bootstrap_daemon)
1795 {
1796 res = "This command is unsupported for bootstrap daemon";
1797 return true;
1798 }
1799 }
1800 if(req.size() != 1)
1801 {
1802 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
1803 error_resp.message = "Wrong parameters, expected height";
1804 return false;
1805 }
1806 uint64_t h = req[0];
1807 if(m_core.get_current_blockchain_height() <= h)
1808 {
1809 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
1810 error_resp.message = std::string("Requested block height: ") + std::to_string(h) + " greater than current top block height: " + std::to_string(m_core.get_current_blockchain_height() - 1);
1811 }
1812 res = string_tools::pod_to_hex(m_core.get_block_id_by_height(h));
1813 return true;
1814 }
1815 //------------------------------------------------------------------------------------------------------------------------------
1816 // equivalent of strstr, but with arbitrary bytes (ie, NULs)
1817 // This does not differentiate between "not found" and "found at offset 0"
1818 size_t slow_memmem(const void* start_buff, size_t buflen,const void* pat,size_t patlen)
1819 {
1820 const void* buf = start_buff;
1821 const void* end=(const char*)buf+buflen;
1822 if (patlen > buflen || patlen == 0) return 0;
1823 while(buflen>0 && (buf=memchr(buf,((const char*)pat)[0],buflen-patlen+1)))
1824 {
1825 if(memcmp(buf,pat,patlen)==0)
1826 return (const char*)buf - (const char*)start_buff;
1827 buf=(const char*)buf+1;
1828 buflen = (const char*)end - (const char*)buf;
1829 }
1830 return 0;
1831 }
1832 //------------------------------------------------------------------------------------------------------------------------------
1833 bool core_rpc_server::get_block_template(const account_public_address &address, const crypto::hash *prev_block, const cryptonote::blobdata &extra_nonce, size_t &reserved_offset, cryptonote::difficulty_type &difficulty, uint64_t &height, uint64_t &expected_reward, block &b, uint64_t &seed_height, crypto::hash &seed_hash, crypto::hash &next_seed_hash, epee::json_rpc::error &error_resp)
1834 {
1835 b = boost::value_initialized<cryptonote::block>();
1836 if(!m_core.get_block_template(b, prev_block, address, difficulty, height, expected_reward, extra_nonce, seed_height, seed_hash))
1837 {
1838 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1839 error_resp.message = "Internal error: failed to create block template";
1840 LOG_ERROR("Failed to create block template");
1841 return false;
1842 }
1843 blobdata block_blob = t_serializable_object_to_blob(b);
1844 crypto::public_key tx_pub_key = cryptonote::get_tx_pub_key_from_extra(b.miner_tx);
1845 if(tx_pub_key == crypto::null_pkey)
1846 {
1847 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1848 error_resp.message = "Internal error: failed to create block template";
1849 LOG_ERROR("Failed to get tx pub key in coinbase extra");
1850 return false;
1851 }
1852
1853 uint64_t next_height;
1854 crypto::rx_seedheights(height, &seed_height, &next_height);
1855 if (next_height != seed_height)
1856 next_seed_hash = m_core.get_block_id_by_height(next_height);
1857 else
1858 next_seed_hash = seed_hash;
1859
1860 if (extra_nonce.empty())
1861 {
1862 reserved_offset = 0;
1863 return true;
1864 }
1865
1866 reserved_offset = slow_memmem((void*)block_blob.data(), block_blob.size(), &tx_pub_key, sizeof(tx_pub_key));
1867 if(!reserved_offset)
1868 {
1869 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1870 error_resp.message = "Internal error: failed to create block template";
1871 LOG_ERROR("Failed to find tx pub key in blockblob");
1872 return false;
1873 }
1874 reserved_offset += sizeof(tx_pub_key) + 2; //2 bytes: tag for TX_EXTRA_NONCE(1 byte), counter in TX_EXTRA_NONCE(1 byte)
1875 if(reserved_offset + extra_nonce.size() > block_blob.size())
1876 {
1877 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1878 error_resp.message = "Internal error: failed to create block template";
1879 LOG_ERROR("Failed to calculate offset for ");
1880 return false;
1881 }
1882 return true;
1883 }
1884 //------------------------------------------------------------------------------------------------------------------------------
1885 bool core_rpc_server::on_getblocktemplate(const COMMAND_RPC_GETBLOCKTEMPLATE::request& req, COMMAND_RPC_GETBLOCKTEMPLATE::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
1886 {
1887 RPC_TRACKER(getblocktemplate);
1888 bool r;
1889 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GETBLOCKTEMPLATE>(invoke_http_mode::JON_RPC, "getblocktemplate", req, res, r))
1890 return r;
1891
1892 if(!check_core_ready())
1893 {
1894 error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
1895 error_resp.message = "Core is busy";
1896 return false;
1897 }
1898
1899 if(req.reserve_size > 255)
1900 {
1901 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_RESERVE_SIZE;
1902 error_resp.message = "Too big reserved size, maximum 255";
1903 return false;
1904 }
1905
1906 if(req.reserve_size && !req.extra_nonce.empty())
1907 {
1908 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
1909 error_resp.message = "Cannot specify both a reserve_size and an extra_nonce";
1910 return false;
1911 }
1912
1913 if(req.extra_nonce.size() > 510)
1914 {
1915 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_RESERVE_SIZE;
1916 error_resp.message = "Too big extra_nonce size, maximum 510 hex chars";
1917 return false;
1918 }
1919
1920 cryptonote::address_parse_info info;
1921
1922 if(!req.wallet_address.size() || !cryptonote::get_account_address_from_str(info, nettype(), req.wallet_address))
1923 {
1924 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_WALLET_ADDRESS;
1925 error_resp.message = "Failed to parse wallet address";
1926 return false;
1927 }
1928 if (info.is_subaddress)
1929 {
1930 error_resp.code = CORE_RPC_ERROR_CODE_MINING_TO_SUBADDRESS;
1931 error_resp.message = "Mining to subaddress is not supported yet";
1932 return false;
1933 }
1934
1935 block b;
1936 cryptonote::blobdata blob_reserve;
1937 size_t reserved_offset;
1938 if(!req.extra_nonce.empty())
1939 {
1940 if(!string_tools::parse_hexstr_to_binbuff(req.extra_nonce, blob_reserve))
1941 {
1942 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
1943 error_resp.message = "Parameter extra_nonce should be a hex string";
1944 return false;
1945 }
1946 }
1947 else
1948 blob_reserve.resize(req.reserve_size, 0);
1949 cryptonote::difficulty_type wdiff;
1950 crypto::hash prev_block;
1951 if (!req.prev_block.empty())
1952 {
1953 if (!epee::string_tools::hex_to_pod(req.prev_block, prev_block))
1954 {
1955 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1956 error_resp.message = "Invalid prev_block";
1957 return false;
1958 }
1959 }
1960 crypto::hash seed_hash, next_seed_hash;
1961 if (!get_block_template(info.address, req.prev_block.empty() ? NULL : &prev_block, blob_reserve, reserved_offset, wdiff, res.height, res.expected_reward, b, res.seed_height, seed_hash, next_seed_hash, error_resp))
1962 return false;
1963 if (b.major_version >= RX_BLOCK_VERSION)
1964 {
1965 res.seed_hash = string_tools::pod_to_hex(seed_hash);
1966 if (seed_hash != next_seed_hash)
1967 res.next_seed_hash = string_tools::pod_to_hex(next_seed_hash);
1968 }
1969
1970 res.reserved_offset = reserved_offset;
1971 store_difficulty(wdiff, res.difficulty, res.wide_difficulty, res.difficulty_top64);
1972 blobdata block_blob = t_serializable_object_to_blob(b);
1973 blobdata hashing_blob = get_block_hashing_blob(b);
1974 res.prev_hash = string_tools::pod_to_hex(b.prev_id);
1975 res.blocktemplate_blob = string_tools::buff_to_hex_nodelimer(block_blob);
1976 res.blockhashing_blob = string_tools::buff_to_hex_nodelimer(hashing_blob);
1977 res.status = CORE_RPC_STATUS_OK;
1978 return true;
1979 }
1980 //------------------------------------------------------------------------------------------------------------------------------
1981 bool core_rpc_server::on_getminerdata(const COMMAND_RPC_GETMINERDATA::request& req, COMMAND_RPC_GETMINERDATA::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
1982 {
1983 if(!check_core_ready())
1984 {
1985 error_resp.code = CORE_RPC_ERROR_CODE_CORE_BUSY;
1986 error_resp.message = "Core is busy";
1987 return false;
1988 }
1989
1990 crypto::hash prev_id, seed_hash;
1991 difficulty_type difficulty;
1992
1993 std::vector<tx_block_template_backlog_entry> tx_backlog;
1994 if (!m_core.get_miner_data(res.major_version, res.height, prev_id, seed_hash, difficulty, res.median_weight, res.already_generated_coins, tx_backlog))
1995 {
1996 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
1997 error_resp.message = "Internal error: failed to get miner data";
1998 LOG_ERROR("Failed to get miner data");
1999 return false;
2000 }
2001
2002 res.tx_backlog.clear();
2003 res.tx_backlog.reserve(tx_backlog.size());
2004
2005 for (const auto& entry : tx_backlog)
2006 {
2007 res.tx_backlog.emplace_back(COMMAND_RPC_GETMINERDATA::response::tx_backlog_entry{string_tools::pod_to_hex(entry.id), entry.weight, entry.fee});
2008 }
2009
2010 res.prev_id = string_tools::pod_to_hex(prev_id);
2011 res.seed_hash = string_tools::pod_to_hex(seed_hash);
2012 res.difficulty = cryptonote::hex(difficulty);
2013
2014 res.status = CORE_RPC_STATUS_OK;
2015 return true;
2016 }
2017 //------------------------------------------------------------------------------------------------------------------------------
2018 bool core_rpc_server::on_calcpow(const COMMAND_RPC_CALCPOW::request& req, COMMAND_RPC_CALCPOW::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2019 {
2020 RPC_TRACKER(calcpow);
2021
2022 blobdata blockblob;
2023 if(!string_tools::parse_hexstr_to_binbuff(req.block_blob, blockblob))
2024 {
2025 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2026 error_resp.message = "Wrong block blob";
2027 return false;
2028 }
2029 if(!m_core.check_incoming_block_size(blockblob))
2030 {
2031 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB_SIZE;
2032 error_resp.message = "Block blob size is too big, rejecting block";
2033 return false;
2034 }
2035 crypto::hash seed_hash, pow_hash;
2036 std::string buf;
2037 if(req.seed_hash.size())
2038 {
2039 if (!string_tools::parse_hexstr_to_binbuff(req.seed_hash, buf) ||
2040 buf.size() != sizeof(crypto::hash))
2041 {
2042 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2043 error_resp.message = "Wrong seed hash";
2044 return false;
2045 }
2046 buf.copy(reinterpret_cast<char *>(&seed_hash), sizeof(crypto::hash));
2047 }
2048
2049 cryptonote::get_block_longhash(&(m_core.get_blockchain_storage()), blockblob, pow_hash, req.height,
2050 req.major_version, req.seed_hash.size() ? &seed_hash : NULL, 0);
2051 res = string_tools::pod_to_hex(pow_hash);
2052 return true;
2053 }
2054 //------------------------------------------------------------------------------------------------------------------------------
2055 bool core_rpc_server::on_add_aux_pow(const COMMAND_RPC_ADD_AUX_POW::request& req, COMMAND_RPC_ADD_AUX_POW::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2056 {
2057 RPC_TRACKER(add_aux_pow);
2058 bool r;
2059 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ADD_AUX_POW>(invoke_http_mode::JON_RPC, "add_aux_pow", req, res, r))
2060 return r;
2061
2062 if (req.aux_pow.empty())
2063 {
2064 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2065 error_resp.message = "Empty aux pow hash vector";
2066 return false;
2067 }
2068
2069 crypto::hash merkle_root;
2070 size_t merkle_tree_depth = 0;
2071 std::vector<std::pair<crypto::hash, crypto::hash>> aux_pow;
2072 std::vector<crypto::hash> aux_pow_raw;
2073 aux_pow.reserve(req.aux_pow.size());
2074 aux_pow_raw.reserve(req.aux_pow.size());
2075 for (const auto &s: req.aux_pow)
2076 {
2077 aux_pow.push_back({});
2078 if (!epee::string_tools::hex_to_pod(s.id, aux_pow.back().first))
2079 {
2080 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2081 error_resp.message = "Invalid aux pow id";
2082 return false;
2083 }
2084 if (!epee::string_tools::hex_to_pod(s.hash, aux_pow.back().second))
2085 {
2086 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2087 error_resp.message = "Invalid aux pow hash";
2088 return false;
2089 }
2090 aux_pow_raw.push_back(aux_pow.back().second);
2091 }
2092
2093 size_t path_domain = 1;
2094 while ((1u << path_domain) < aux_pow.size())
2095 ++path_domain;
2096 uint32_t nonce;
2097 const uint32_t max_nonce = 65535;
2098 bool collision = true;
2099 for (nonce = 0; nonce <= max_nonce; ++nonce)
2100 {
2101 std::vector<bool> slots(aux_pow.size(), false);
2102 collision = false;
2103 for (size_t idx = 0; idx < aux_pow.size(); ++idx)
2104 {
2105 const uint32_t slot = cryptonote::get_aux_slot(aux_pow[idx].first, nonce, aux_pow.size());
2106 if (slot >= aux_pow.size())
2107 {
2108 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2109 error_resp.message = "Computed slot is out of range";
2110 return false;
2111 }
2112 if (slots[slot])
2113 {
2114 collision = true;
2115 break;
2116 }
2117 slots[slot] = true;
2118 }
2119 if (!collision)
2120 break;
2121 }
2122 if (collision)
2123 {
2124 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2125 error_resp.message = "Failed to find a suitable nonce";
2126 return false;
2127 }
2128
2129 crypto::tree_hash((const char(*)[crypto::HASH_SIZE])aux_pow_raw.data(), aux_pow_raw.size(), merkle_root.data);
2130 res.merkle_root = epee::string_tools::pod_to_hex(merkle_root);
2131 res.merkle_tree_depth = cryptonote::encode_mm_depth(aux_pow.size(), nonce);
2132
2133 blobdata blocktemplate_blob;
2134 if (!epee::string_tools::parse_hexstr_to_binbuff(req.blocktemplate_blob, blocktemplate_blob))
2135 {
2136 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2137 error_resp.message = "Invalid blocktemplate_blob";
2138 return false;
2139 }
2140
2141 block b;
2142 if (!parse_and_validate_block_from_blob(blocktemplate_blob, b))
2143 {
2144 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2145 error_resp.message = "Wrong blocktemplate_blob";
2146 return false;
2147 }
2148
2149 if (!remove_field_from_tx_extra(b.miner_tx.extra, typeid(cryptonote::tx_extra_merge_mining_tag)))
2150 {
2151 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2152 error_resp.message = "Error removing existing merkle root";
2153 return false;
2154 }
2155 if (!add_mm_merkle_root_to_tx_extra(b.miner_tx.extra, merkle_root, merkle_tree_depth))
2156 {
2157 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2158 error_resp.message = "Error adding merkle root";
2159 return false;
2160 }
2161 b.invalidate_hashes();
2162 b.miner_tx.invalidate_hashes();
2163
2164 const blobdata block_blob = t_serializable_object_to_blob(b);
2165 const blobdata hashing_blob = get_block_hashing_blob(b);
2166
2167 res.blocktemplate_blob = string_tools::buff_to_hex_nodelimer(block_blob);
2168 res.blockhashing_blob = string_tools::buff_to_hex_nodelimer(hashing_blob);
2169 res.aux_pow = req.aux_pow;
2170 res.status = CORE_RPC_STATUS_OK;
2171 return true;
2172 }
2173 //------------------------------------------------------------------------------------------------------------------------------
2174 bool core_rpc_server::on_submitblock(const COMMAND_RPC_SUBMITBLOCK::request& req, COMMAND_RPC_SUBMITBLOCK::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2175 {
2176 RPC_TRACKER(submitblock);
2177 {
2178 boost::shared_lock<boost::shared_mutex> lock(m_bootstrap_daemon_mutex);
2179 if (m_should_use_bootstrap_daemon)
2180 {
2181 error_resp.code = CORE_RPC_ERROR_CODE_UNSUPPORTED_BOOTSTRAP;
2182 error_resp.message = "This command is unsupported for bootstrap daemon";
2183 return false;
2184 }
2185 }
2186 CHECK_CORE_READY();
2187 if(req.size()!=1)
2188 {
2189 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2190 error_resp.message = "Wrong param";
2191 return false;
2192 }
2193 blobdata blockblob;
2194 if(!string_tools::parse_hexstr_to_binbuff(req[0], blockblob))
2195 {
2196 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2197 error_resp.message = "Wrong block blob";
2198 return false;
2199 }
2200
2201 // Fixing of high orphan issue for most pools
2202 // Thanks Boolberry!
2203 block b;
2204 crypto::hash blk_id;
2205 if(!parse_and_validate_block_from_blob(blockblob, b, blk_id))
2206 {
2207 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2208 error_resp.message = "Wrong block blob";
2209 return false;
2210 }
2211
2212 // Fix from Boolberry neglects to check block
2213 // size, do that with the function below
2214 if(!m_core.check_incoming_block_size(blockblob))
2215 {
2216 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB_SIZE;
2217 error_resp.message = "Block bloc size is too big, rejecting block";
2218 return false;
2219 }
2220
2221 block_verification_context bvc;
2222 if(!m_core.handle_block_found(b, bvc))
2223 {
2224 error_resp.code = CORE_RPC_ERROR_CODE_BLOCK_NOT_ACCEPTED;
2225 error_resp.message = "Block not accepted";
2226 return false;
2227 }
2228 res.block_id = epee::string_tools::pod_to_hex(blk_id);
2229 res.status = CORE_RPC_STATUS_OK;
2230 return true;
2231 }
2232 //------------------------------------------------------------------------------------------------------------------------------
2233 bool core_rpc_server::on_generateblocks(const COMMAND_RPC_GENERATEBLOCKS::request& req, COMMAND_RPC_GENERATEBLOCKS::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2234 {
2235 RPC_TRACKER(generateblocks);
2236
2237 CHECK_CORE_READY();
2238
2239 res.status = CORE_RPC_STATUS_OK;
2240
2241 if(m_core.get_nettype() != FAKECHAIN)
2242 {
2243 error_resp.code = CORE_RPC_ERROR_CODE_REGTEST_REQUIRED;
2244 error_resp.message = "Regtest required when generating blocks";
2245 return false;
2246 }
2247
2248 COMMAND_RPC_GETBLOCKTEMPLATE::request template_req;
2249 COMMAND_RPC_GETBLOCKTEMPLATE::response template_res;
2250 COMMAND_RPC_SUBMITBLOCK::request submit_req;
2251 COMMAND_RPC_SUBMITBLOCK::response submit_res;
2252
2253 template_req.reserve_size = 1;
2254 template_req.wallet_address = req.wallet_address;
2255 template_req.prev_block = req.prev_block;
2256 submit_req.push_back(std::string{});
2257 res.height = m_core.get_blockchain_storage().get_current_blockchain_height();
2258
2259 for(size_t i = 0; i < req.amount_of_blocks; i++)
2260 {
2261 bool r = on_getblocktemplate(template_req, template_res, error_resp, ctx);
2262 res.status = template_res.status;
2263 template_req.prev_block.clear();
2264
2265 if (!r) return false;
2266
2267 blobdata blockblob;
2268 if(!string_tools::parse_hexstr_to_binbuff(template_res.blocktemplate_blob, blockblob))
2269 {
2270 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2271 error_resp.message = "Wrong block blob";
2272 return false;
2273 }
2274 block b;
2275 if(!parse_and_validate_block_from_blob(blockblob, b))
2276 {
2277 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
2278 error_resp.message = "Wrong block blob";
2279 return false;
2280 }
2281 b.nonce = req.starting_nonce;
2282 crypto::hash seed_hash = crypto::null_hash;
2283 if (b.major_version >= RX_BLOCK_VERSION && !epee::string_tools::hex_to_pod(template_res.seed_hash, seed_hash))
2284 {
2285 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2286 error_resp.message = "Error converting seed hash";
2287 return false;
2288 }
2289 miner::find_nonce_for_given_block([this](const cryptonote::block &b, uint64_t height, const crypto::hash *seed_hash, unsigned int threads, crypto::hash &hash) {
2290 return cryptonote::get_block_longhash(&(m_core.get_blockchain_storage()), b, hash, height, seed_hash, threads);
2291 }, b, template_res.difficulty, template_res.height, &seed_hash);
2292
2293 submit_req.front() = string_tools::buff_to_hex_nodelimer(block_to_blob(b));
2294 r = on_submitblock(submit_req, submit_res, error_resp, ctx);
2295 res.status = submit_res.status;
2296
2297 if (!r) return false;
2298
2299 res.blocks.push_back(epee::string_tools::pod_to_hex(get_block_hash(b)));
2300 template_req.prev_block = res.blocks.back();
2301 res.height = template_res.height;
2302 }
2303
2304 return true;
2305 }
2306 //------------------------------------------------------------------------------------------------------------------------------
2307 uint64_t core_rpc_server::get_block_reward(const block& blk)
2308 {
2309 uint64_t reward = 0;
2310 for(const tx_out& out: blk.miner_tx.vout)
2311 {
2312 reward += out.amount;
2313 }
2314 return reward;
2315 }
2316 //------------------------------------------------------------------------------------------------------------------------------
2317 bool core_rpc_server::fill_block_header_response(const block& blk, bool orphan_status, uint64_t height, const crypto::hash& hash, block_header_response& response, bool fill_pow_hash)
2318 {
2319 PERF_TIMER(fill_block_header_response);
2320 response.major_version = blk.major_version;
2321 response.minor_version = blk.minor_version;
2322 response.timestamp = blk.timestamp;
2323 response.prev_hash = string_tools::pod_to_hex(blk.prev_id);
2324 response.nonce = blk.nonce;
2325 response.orphan_status = orphan_status;
2326 response.height = height;
2327 response.depth = m_core.get_current_blockchain_height() - height - 1;
2328 response.hash = string_tools::pod_to_hex(hash);
2329 store_difficulty(m_core.get_blockchain_storage().block_difficulty(height),
2330 response.difficulty, response.wide_difficulty, response.difficulty_top64);
2331 store_difficulty(m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(height),
2332 response.cumulative_difficulty, response.wide_cumulative_difficulty, response.cumulative_difficulty_top64);
2333 response.reward = get_block_reward(blk);
2334 response.block_size = response.block_weight = m_core.get_blockchain_storage().get_db().get_block_weight(height);
2335 response.num_txes = blk.tx_hashes.size();
2336 response.pow_hash = fill_pow_hash ? string_tools::pod_to_hex(get_block_longhash(&(m_core.get_blockchain_storage()), blk, height, 0)) : "";
2337 response.long_term_weight = m_core.get_blockchain_storage().get_db().get_block_long_term_weight(height);
2338 response.miner_tx_hash = string_tools::pod_to_hex(cryptonote::get_transaction_hash(blk.miner_tx));
2339 return true;
2340 }
2341 //------------------------------------------------------------------------------------------------------------------------------
2342 template <typename COMMAND_TYPE>
2343 bool core_rpc_server::use_bootstrap_daemon_if_necessary(const invoke_http_mode &mode, const std::string &command_name, const typename COMMAND_TYPE::request& req, typename COMMAND_TYPE::response& res, bool &r)
2344 {
2345 res.untrusted = false;
2346
2347 boost::upgrade_lock<boost::shared_mutex> upgrade_lock(m_bootstrap_daemon_mutex);
2348
2349 if (m_bootstrap_daemon.get() == nullptr)
2350 {
2351 return false;
2352 }
2353
2354 if (!m_should_use_bootstrap_daemon)
2355 {
2356 MINFO("The local daemon is fully synced. Not switching back to the bootstrap daemon");
2357 return false;
2358 }
2359
2360 auto current_time = std::chrono::system_clock::now();
2361 if (current_time - m_bootstrap_height_check_time > std::chrono::seconds(30)) // update every 30s
2362 {
2363 {
2364 boost::upgrade_to_unique_lock<boost::shared_mutex> lock(upgrade_lock);
2365 m_bootstrap_height_check_time = current_time;
2366 }
2367
2368 boost::optional<std::pair<uint64_t, uint64_t>> bootstrap_daemon_height_info = m_bootstrap_daemon->get_height();
2369 if (!bootstrap_daemon_height_info)
2370 {
2371 MERROR("Failed to fetch bootstrap daemon height");
2372 return false;
2373 }
2374
2375 const uint64_t bootstrap_daemon_height = bootstrap_daemon_height_info->first;
2376 const uint64_t bootstrap_daemon_target_height = bootstrap_daemon_height_info->second;
2377 if (bootstrap_daemon_height < bootstrap_daemon_target_height)
2378 {
2379 MINFO("Bootstrap daemon is out of sync");
2380 return m_bootstrap_daemon->handle_result(false, {});
2381 }
2382
2383 if (bootstrap_daemon_height < m_core.get_checkpoints().get_max_height())
2384 {
2385 MINFO("Bootstrap daemon height is lower than the latest checkpoint");
2386 return m_bootstrap_daemon->handle_result(false, {});
2387 }
2388
2389 if (!m_p2p.get_payload_object().no_sync())
2390 {
2391 uint64_t top_height = m_core.get_current_blockchain_height();
2392 m_should_use_bootstrap_daemon = top_height + 10 < bootstrap_daemon_height;
2393 MINFO((m_should_use_bootstrap_daemon ? "Using" : "Not using") << " the bootstrap daemon (our height: " << top_height << ", bootstrap daemon's height: " << bootstrap_daemon_height << ")");
2394
2395 if (!m_should_use_bootstrap_daemon)
2396 return false;
2397 }
2398 }
2399
2400 if (mode == invoke_http_mode::JON)
2401 {
2402 r = m_bootstrap_daemon->invoke_http_json(command_name, req, res);
2403 }
2404 else if (mode == invoke_http_mode::BIN)
2405 {
2406 r = m_bootstrap_daemon->invoke_http_bin(command_name, req, res);
2407 }
2408 else if (mode == invoke_http_mode::JON_RPC)
2409 {
2410 r = m_bootstrap_daemon->invoke_http_json_rpc(command_name, req, res);
2411 }
2412 else
2413 {
2414 MERROR("Unknown invoke_http_mode: " << mode);
2415 return false;
2416 }
2417
2418 {
2419 boost::upgrade_to_unique_lock<boost::shared_mutex> lock(upgrade_lock);
2420 m_was_bootstrap_ever_used = true;
2421 }
2422
2423 if (r && res.status != CORE_RPC_STATUS_PAYMENT_REQUIRED && res.status != CORE_RPC_STATUS_OK)
2424 {
2425 MINFO("Failing RPC " << command_name << " due to peer return status " << res.status);
2426 r = false;
2427 }
2428 res.untrusted = true;
2429 return r;
2430 }
2431 //------------------------------------------------------------------------------------------------------------------------------
2432 bool core_rpc_server::on_get_last_block_header(const COMMAND_RPC_GET_LAST_BLOCK_HEADER::request& req, COMMAND_RPC_GET_LAST_BLOCK_HEADER::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2433 {
2434 RPC_TRACKER(get_last_block_header);
2435 bool r;
2436 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_LAST_BLOCK_HEADER>(invoke_http_mode::JON_RPC, "getlastblockheader", req, res, r))
2437 return r;
2438
2439 CHECK_CORE_READY();
2440 CHECK_PAYMENT_MIN1(req, res, COST_PER_BLOCK_HEADER, false);
2441 uint64_t last_block_height;
2442 crypto::hash last_block_hash;
2443 m_core.get_blockchain_top(last_block_height, last_block_hash);
2444 block last_block;
2445 bool have_last_block = m_core.get_block_by_hash(last_block_hash, last_block);
2446 if (!have_last_block)
2447 {
2448 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2449 error_resp.message = "Internal error: can't get last block.";
2450 return false;
2451 }
2452 const bool restricted = m_restricted && ctx;
2453 bool response_filled = fill_block_header_response(last_block, false, last_block_height, last_block_hash, res.block_header, req.fill_pow_hash && !restricted);
2454 if (!response_filled)
2455 {
2456 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2457 error_resp.message = "Internal error: can't produce valid response.";
2458 return false;
2459 }
2460 res.status = CORE_RPC_STATUS_OK;
2461 return true;
2462 }
2463 //------------------------------------------------------------------------------------------------------------------------------
2464 bool core_rpc_server::on_get_block_header_by_hash(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2465 {
2466 RPC_TRACKER(get_block_header_by_hash);
2467 bool r;
2468 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCK_HEADER_BY_HASH>(invoke_http_mode::JON_RPC, "getblockheaderbyhash", req, res, r))
2469 return r;
2470
2471 CHECK_PAYMENT_MIN1(req, res, COST_PER_BLOCK_HEADER, false);
2472
2473 const bool restricted = m_restricted && ctx;
2474 if (restricted && req.hashes.size() > RESTRICTED_BLOCK_COUNT)
2475 {
2476 error_resp.code = CORE_RPC_ERROR_CODE_RESTRICTED;
2477 error_resp.message = "Too many block headers requested in restricted mode";
2478 return false;
2479 }
2480
2481 auto get = [this](const std::string &hash, bool fill_pow_hash, block_header_response &block_header, bool restricted, epee::json_rpc::error& error_resp) -> bool {
2482 crypto::hash block_hash;
2483 bool hash_parsed = parse_hash256(hash, block_hash);
2484 if(!hash_parsed)
2485 {
2486 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2487 error_resp.message = "Failed to parse hex representation of block hash. Hex = " + hash + '.';
2488 return false;
2489 }
2490 block blk;
2491 bool orphan = false;
2492 bool have_block = m_core.get_block_by_hash(block_hash, blk, &orphan);
2493 if (!have_block)
2494 {
2495 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2496 error_resp.message = "Internal error: can't get block by hash. Hash = " + hash + '.';
2497 return false;
2498 }
2499 if (blk.miner_tx.vin.size() != 1 || blk.miner_tx.vin.front().type() != typeid(txin_gen))
2500 {
2501 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2502 error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
2503 return false;
2504 }
2505 uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
2506 bool response_filled = fill_block_header_response(blk, orphan, block_height, block_hash, block_header, fill_pow_hash && !restricted);
2507 if (!response_filled)
2508 {
2509 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2510 error_resp.message = "Internal error: can't produce valid response.";
2511 return false;
2512 }
2513 return true;
2514 };
2515
2516 if (!req.hash.empty())
2517 {
2518 if (!get(req.hash, req.fill_pow_hash, res.block_header, restricted, error_resp))
2519 return false;
2520 }
2521 res.block_headers.reserve(req.hashes.size());
2522 for (const std::string &hash: req.hashes)
2523 {
2524 res.block_headers.push_back({});
2525 if (!get(hash, req.fill_pow_hash, res.block_headers.back(), restricted, error_resp))
2526 return false;
2527 }
2528
2529 res.status = CORE_RPC_STATUS_OK;
2530 return true;
2531 }
2532 //------------------------------------------------------------------------------------------------------------------------------
2533 bool core_rpc_server::on_get_block_headers_range(const COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request& req, COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2534 {
2535 RPC_TRACKER(get_block_headers_range);
2536 bool r;
2537 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCK_HEADERS_RANGE>(invoke_http_mode::JON_RPC, "getblockheadersrange", req, res, r))
2538 return r;
2539
2540 const uint64_t bc_height = m_core.get_current_blockchain_height();
2541 if (req.start_height >= bc_height || req.end_height >= bc_height || req.start_height > req.end_height)
2542 {
2543 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
2544 error_resp.message = "Invalid start/end heights.";
2545 return false;
2546 }
2547 const bool restricted = m_restricted && ctx;
2548 if (restricted && req.end_height - req.start_height > RESTRICTED_BLOCK_HEADER_RANGE)
2549 {
2550 error_resp.code = CORE_RPC_ERROR_CODE_RESTRICTED;
2551 error_resp.message = "Too many block headers requested.";
2552 return false;
2553 }
2554
2555 CHECK_PAYMENT_MIN1(req, res, (req.end_height - req.start_height + 1) * COST_PER_BLOCK_HEADER, false);
2556 for (uint64_t h = req.start_height; h <= req.end_height; ++h)
2557 {
2558 crypto::hash block_hash = m_core.get_block_id_by_height(h);
2559 block blk;
2560 bool have_block = m_core.get_block_by_hash(block_hash, blk);
2561 if (!have_block)
2562 {
2563 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2564 error_resp.message = "Internal error: can't get block by height. Height = " + boost::lexical_cast<std::string>(h) + ". Hash = " + epee::string_tools::pod_to_hex(block_hash) + '.';
2565 return false;
2566 }
2567 if (blk.miner_tx.vin.size() != 1 || blk.miner_tx.vin.front().type() != typeid(txin_gen))
2568 {
2569 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2570 error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
2571 return false;
2572 }
2573 uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
2574 if (block_height != h)
2575 {
2576 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2577 error_resp.message = "Internal error: coinbase transaction in the block has the wrong height";
2578 return false;
2579 }
2580 res.headers.push_back(block_header_response());
2581 bool response_filled = fill_block_header_response(blk, false, block_height, block_hash, res.headers.back(), req.fill_pow_hash && !restricted);
2582 if (!response_filled)
2583 {
2584 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2585 error_resp.message = "Internal error: can't produce valid response.";
2586 return false;
2587 }
2588 }
2589 res.status = CORE_RPC_STATUS_OK;
2590 return true;
2591 }
2592 //------------------------------------------------------------------------------------------------------------------------------
2593 bool core_rpc_server::on_get_block_header_by_height(const COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::request& req, COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2594 {
2595 RPC_TRACKER(get_block_header_by_height);
2596 bool r;
2597 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCK_HEADER_BY_HEIGHT>(invoke_http_mode::JON_RPC, "getblockheaderbyheight", req, res, r))
2598 return r;
2599
2600 if(m_core.get_current_blockchain_height() <= req.height)
2601 {
2602 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
2603 error_resp.message = std::string("Requested block height: ") + std::to_string(req.height) + " greater than current top block height: " + std::to_string(m_core.get_current_blockchain_height() - 1);
2604 return false;
2605 }
2606 CHECK_PAYMENT_MIN1(req, res, COST_PER_BLOCK_HEADER, false);
2607 crypto::hash block_hash = m_core.get_block_id_by_height(req.height);
2608 block blk;
2609 bool have_block = m_core.get_block_by_hash(block_hash, blk);
2610 if (!have_block)
2611 {
2612 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2613 error_resp.message = "Internal error: can't get block by height. Height = " + std::to_string(req.height) + '.';
2614 return false;
2615 }
2616 const bool restricted = m_restricted && ctx;
2617 bool response_filled = fill_block_header_response(blk, false, req.height, block_hash, res.block_header, req.fill_pow_hash && !restricted);
2618 if (!response_filled)
2619 {
2620 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2621 error_resp.message = "Internal error: can't produce valid response.";
2622 return false;
2623 }
2624 res.status = CORE_RPC_STATUS_OK;
2625 return true;
2626 }
2627 //------------------------------------------------------------------------------------------------------------------------------
2628 bool core_rpc_server::on_get_block(const COMMAND_RPC_GET_BLOCK::request& req, COMMAND_RPC_GET_BLOCK::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2629 {
2630 RPC_TRACKER(get_block);
2631 bool r;
2632 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BLOCK>(invoke_http_mode::JON_RPC, "getblock", req, res, r))
2633 return r;
2634
2635 CHECK_PAYMENT_MIN1(req, res, COST_PER_BLOCK, false);
2636
2637 crypto::hash block_hash;
2638 if (!req.hash.empty())
2639 {
2640 bool hash_parsed = parse_hash256(req.hash, block_hash);
2641 if(!hash_parsed)
2642 {
2643 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2644 error_resp.message = "Failed to parse hex representation of block hash. Hex = " + req.hash + '.';
2645 return false;
2646 }
2647 }
2648 else
2649 {
2650 if(m_core.get_current_blockchain_height() <= req.height)
2651 {
2652 error_resp.code = CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT;
2653 error_resp.message = std::string("Requested block height: ") + std::to_string(req.height) + " greater than current top block height: " + std::to_string(m_core.get_current_blockchain_height() - 1);
2654 return false;
2655 }
2656 block_hash = m_core.get_block_id_by_height(req.height);
2657 }
2658 block blk;
2659 bool orphan = false;
2660 bool have_block = m_core.get_block_by_hash(block_hash, blk, &orphan);
2661 if (!have_block)
2662 {
2663 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2664 error_resp.message = "Internal error: can't get block by hash. Hash = " + req.hash + '.';
2665 return false;
2666 }
2667 if (blk.miner_tx.vin.size() != 1 || blk.miner_tx.vin.front().type() != typeid(txin_gen))
2668 {
2669 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2670 error_resp.message = "Internal error: coinbase transaction in the block has the wrong type";
2671 return false;
2672 }
2673 uint64_t block_height = boost::get<txin_gen>(blk.miner_tx.vin.front()).height;
2674 const bool restricted = m_restricted && ctx;
2675 bool response_filled = fill_block_header_response(blk, orphan, block_height, block_hash, res.block_header, req.fill_pow_hash && !restricted);
2676 if (!response_filled)
2677 {
2678 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2679 error_resp.message = "Internal error: can't produce valid response.";
2680 return false;
2681 }
2682 res.miner_tx_hash = res.block_header.miner_tx_hash;
2683 for (size_t n = 0; n < blk.tx_hashes.size(); ++n)
2684 {
2685 res.tx_hashes.push_back(epee::string_tools::pod_to_hex(blk.tx_hashes[n]));
2686 }
2687 res.blob = string_tools::buff_to_hex_nodelimer(t_serializable_object_to_blob(blk));
2688 res.json = obj_to_json_str(blk);
2689 res.status = CORE_RPC_STATUS_OK;
2690 return true;
2691 }
2692 //------------------------------------------------------------------------------------------------------------------------------
2693 bool core_rpc_server::on_get_connections(const COMMAND_RPC_GET_CONNECTIONS::request& req, COMMAND_RPC_GET_CONNECTIONS::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2694 {
2695 RPC_TRACKER(get_connections);
2696
2697 res.connections = m_p2p.get_payload_object().get_connections();
2698
2699 res.status = CORE_RPC_STATUS_OK;
2700
2701 return true;
2702 }
2703 //------------------------------------------------------------------------------------------------------------------------------
2704 bool core_rpc_server::on_get_info_json(const COMMAND_RPC_GET_INFO::request& req, COMMAND_RPC_GET_INFO::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2705 {
2706 if (!on_get_info(req, res, ctx) || res.status != CORE_RPC_STATUS_OK)
2707 {
2708 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
2709 error_resp.message = res.status;
2710 return false;
2711 }
2712 return true;
2713 }
2714 //------------------------------------------------------------------------------------------------------------------------------
2715 bool core_rpc_server::on_hard_fork_info(const COMMAND_RPC_HARD_FORK_INFO::request& req, COMMAND_RPC_HARD_FORK_INFO::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2716 {
2717 RPC_TRACKER(hard_fork_info);
2718 bool r;
2719 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_HARD_FORK_INFO>(invoke_http_mode::JON_RPC, "hard_fork_info", req, res, r))
2720 return r;
2721
2722 CHECK_PAYMENT(req, res, COST_PER_HARD_FORK_INFO);
2723 const Blockchain &blockchain = m_core.get_blockchain_storage();
2724 uint8_t version = req.version > 0 ? req.version : blockchain.get_next_hard_fork_version();
2725 res.version = blockchain.get_current_hard_fork_version();
2726 res.enabled = blockchain.get_hard_fork_voting_info(version, res.window, res.votes, res.threshold, res.earliest_height, res.voting);
2727 res.state = blockchain.get_hard_fork_state();
2728 res.status = CORE_RPC_STATUS_OK;
2729 return true;
2730 }
2731 //------------------------------------------------------------------------------------------------------------------------------
2732 bool core_rpc_server::on_get_bans(const COMMAND_RPC_GETBANS::request& req, COMMAND_RPC_GETBANS::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2733 {
2734 RPC_TRACKER(get_bans);
2735
2736 auto now = time(nullptr);
2737 std::map<std::string, time_t> blocked_hosts = m_p2p.get_blocked_hosts();
2738 for (std::map<std::string, time_t>::const_iterator i = blocked_hosts.begin(); i != blocked_hosts.end(); ++i)
2739 {
2740 if (i->second > now) {
2741 COMMAND_RPC_GETBANS::ban b;
2742 b.host = i->first;
2743 b.ip = 0;
2744 uint32_t ip;
2745 if (epee::string_tools::get_ip_int32_from_string(ip, b.host))
2746 b.ip = ip;
2747 b.seconds = i->second - now;
2748 res.bans.push_back(b);
2749 }
2750 }
2751 std::map<epee::net_utils::ipv4_network_subnet, time_t> blocked_subnets = m_p2p.get_blocked_subnets();
2752 for (std::map<epee::net_utils::ipv4_network_subnet, time_t>::const_iterator i = blocked_subnets.begin(); i != blocked_subnets.end(); ++i)
2753 {
2754 if (i->second > now) {
2755 COMMAND_RPC_GETBANS::ban b;
2756 b.host = i->first.host_str();
2757 b.ip = 0;
2758 b.seconds = i->second - now;
2759 res.bans.push_back(b);
2760 }
2761 }
2762
2763 res.status = CORE_RPC_STATUS_OK;
2764 return true;
2765 }
2766 //------------------------------------------------------------------------------------------------------------------------------
2767 bool core_rpc_server::on_banned(const COMMAND_RPC_BANNED::request& req, COMMAND_RPC_BANNED::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2768 {
2769 PERF_TIMER(on_banned);
2770
2771 auto na_parsed = net::get_network_address(req.address, 0);
2772 if (!na_parsed)
2773 {
2774 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2775 error_resp.message = "Unsupported host type";
2776 return false;
2777 }
2778 epee::net_utils::network_address na = std::move(*na_parsed);
2779
2780 time_t seconds;
2781 if (m_p2p.is_host_blocked(na, &seconds))
2782 {
2783 res.banned = true;
2784 res.seconds = seconds;
2785 }
2786 else
2787 {
2788 res.banned = false;
2789 res.seconds = 0;
2790 }
2791
2792 res.status = CORE_RPC_STATUS_OK;
2793 return true;
2794 }
2795 //------------------------------------------------------------------------------------------------------------------------------
2796 bool core_rpc_server::on_set_bans(const COMMAND_RPC_SETBANS::request& req, COMMAND_RPC_SETBANS::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2797 {
2798 RPC_TRACKER(set_bans);
2799
2800 for (auto i = req.bans.begin(); i != req.bans.end(); ++i)
2801 {
2802 epee::net_utils::network_address na;
2803
2804 // try subnet first
2805 if (!i->host.empty())
2806 {
2807 auto ns_parsed = net::get_ipv4_subnet_address(i->host);
2808 if (ns_parsed)
2809 {
2810 if (i->ban)
2811 m_p2p.block_subnet(*ns_parsed, i->seconds);
2812 else
2813 m_p2p.unblock_subnet(*ns_parsed);
2814 continue;
2815 }
2816 }
2817
2818 // then host
2819 if (!i->host.empty())
2820 {
2821 auto na_parsed = net::get_network_address(i->host, 0);
2822 if (!na_parsed)
2823 {
2824 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2825 error_resp.message = "Unsupported host/subnet type";
2826 return false;
2827 }
2828 na = std::move(*na_parsed);
2829 }
2830 else
2831 {
2832 if (!i->ip)
2833 {
2834 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_PARAM;
2835 error_resp.message = "No ip/host supplied";
2836 return false;
2837 }
2838 na = epee::net_utils::ipv4_network_address{i->ip, 0};
2839 }
2840 if (i->ban)
2841 m_p2p.block_host(na, i->seconds);
2842 else
2843 m_p2p.unblock_host(na);
2844 }
2845
2846 res.status = CORE_RPC_STATUS_OK;
2847 return true;
2848 }
2849 //------------------------------------------------------------------------------------------------------------------------------
2850 bool core_rpc_server::on_flush_txpool(const COMMAND_RPC_FLUSH_TRANSACTION_POOL::request& req, COMMAND_RPC_FLUSH_TRANSACTION_POOL::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2851 {
2852 RPC_TRACKER(flush_txpool);
2853
2854 bool failed = false;
2855 std::vector<crypto::hash> txids;
2856 if (req.txids.empty())
2857 {
2858 std::vector<transaction> pool_txs;
2859 bool r = m_core.get_pool_transactions(pool_txs, true);
2860 if (!r)
2861 {
2862 res.status = "Failed to get txpool contents";
2863 return true;
2864 }
2865 for (const auto &tx: pool_txs)
2866 {
2867 txids.push_back(cryptonote::get_transaction_hash(tx));
2868 }
2869 }
2870 else
2871 {
2872 for (const auto &str: req.txids)
2873 {
2874 crypto::hash txid;
2875 if(!epee::string_tools::hex_to_pod(str, txid))
2876 {
2877 failed = true;
2878 }
2879 else
2880 {
2881 txids.push_back(txid);
2882 }
2883 }
2884 }
2885 if (!m_core.get_blockchain_storage().flush_txes_from_pool(txids))
2886 {
2887 res.status = "Failed to remove one or more tx(es)";
2888 return true;
2889 }
2890
2891 if (failed)
2892 {
2893 if (txids.empty())
2894 res.status = "Failed to parse txid";
2895 else
2896 res.status = "Failed to parse some of the txids";
2897 return true;
2898 }
2899
2900 res.status = CORE_RPC_STATUS_OK;
2901 return true;
2902 }
2903 //------------------------------------------------------------------------------------------------------------------------------
2904 bool core_rpc_server::on_get_output_histogram(const COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request& req, COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2905 {
2906 RPC_TRACKER(get_output_histogram);
2907 bool r;
2908 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_OUTPUT_HISTOGRAM>(invoke_http_mode::JON_RPC, "get_output_histogram", req, res, r))
2909 return r;
2910
2911 const bool restricted = m_restricted && ctx;
2912 size_t amounts = req.amounts.size();
2913 if (restricted && amounts == 0)
2914 {
2915 res.status = "Restricted RPC will not serve histograms on the whole blockchain. Use your own node.";
2916 return true;
2917 }
2918
2919 uint64_t cost = req.amounts.empty() ? COST_PER_FULL_OUTPUT_HISTOGRAM : (COST_PER_OUTPUT_HISTOGRAM * amounts);
2920 CHECK_PAYMENT_MIN1(req, res, cost, false);
2921
2922 if (restricted && req.recent_cutoff > 0 && req.recent_cutoff < (uint64_t)time(NULL) - OUTPUT_HISTOGRAM_RECENT_CUTOFF_RESTRICTION)
2923 {
2924 res.status = "Recent cutoff is too old";
2925 return true;
2926 }
2927
2928 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> histogram;
2929 try
2930 {
2931 histogram = m_core.get_blockchain_storage().get_output_histogram(req.amounts, req.unlocked, req.recent_cutoff, req.min_count);
2932 }
2933 catch (const std::exception &e)
2934 {
2935 res.status = "Failed to get output histogram";
2936 return true;
2937 }
2938
2939 res.histogram.clear();
2940 res.histogram.reserve(histogram.size());
2941 for (const auto &i: histogram)
2942 {
2943 if (std::get<0>(i.second) >= req.min_count && (std::get<0>(i.second) <= req.max_count || req.max_count == 0))
2944 res.histogram.push_back(COMMAND_RPC_GET_OUTPUT_HISTOGRAM::entry(i.first, std::get<0>(i.second), std::get<1>(i.second), std::get<2>(i.second)));
2945 }
2946
2947 res.status = CORE_RPC_STATUS_OK;
2948 return true;
2949 }
2950 //------------------------------------------------------------------------------------------------------------------------------
2951 bool core_rpc_server::on_get_version(const COMMAND_RPC_GET_VERSION::request& req, COMMAND_RPC_GET_VERSION::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2952 {
2953 RPC_TRACKER(get_version);
2954 bool r;
2955 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_VERSION>(invoke_http_mode::JON_RPC, "get_version", req, res, r))
2956 return r;
2957
2958 res.version = CORE_RPC_VERSION;
2959 res.release = MONERO_VERSION_IS_RELEASE;
2960 res.status = CORE_RPC_STATUS_OK;
2961 return true;
2962 }
2963 //------------------------------------------------------------------------------------------------------------------------------
2964 bool core_rpc_server::on_get_coinbase_tx_sum(const COMMAND_RPC_GET_COINBASE_TX_SUM::request& req, COMMAND_RPC_GET_COINBASE_TX_SUM::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2965 {
2966 RPC_TRACKER(get_coinbase_tx_sum);
2967 const uint64_t bc_height = m_core.get_current_blockchain_height();
2968 if (req.height >= bc_height || req.count > bc_height)
2969 {
2970 res.status = "height or count is too large";
2971 return true;
2972 }
2973 CHECK_PAYMENT_MIN1(req, res, COST_PER_COINBASE_TX_SUM_BLOCK * req.count, false);
2974 std::pair<boost::multiprecision::uint128_t, boost::multiprecision::uint128_t> amounts = m_core.get_coinbase_tx_sum(req.height, req.count);
2975 store_128(amounts.first, res.emission_amount, res.wide_emission_amount, res.emission_amount_top64);
2976 store_128(amounts.second, res.fee_amount, res.wide_fee_amount, res.fee_amount_top64);
2977 res.status = CORE_RPC_STATUS_OK;
2978 return true;
2979 }
2980 //------------------------------------------------------------------------------------------------------------------------------
2981 bool core_rpc_server::on_get_base_fee_estimate(const COMMAND_RPC_GET_BASE_FEE_ESTIMATE::request& req, COMMAND_RPC_GET_BASE_FEE_ESTIMATE::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
2982 {
2983 RPC_TRACKER(get_base_fee_estimate);
2984 bool r;
2985 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_BASE_FEE_ESTIMATE>(invoke_http_mode::JON_RPC, "get_fee_estimate", req, res, r))
2986 return r;
2987
2988 CHECK_PAYMENT(req, res, COST_PER_FEE_ESTIMATE);
2989
2990 const uint8_t version = m_core.get_blockchain_storage().get_current_hard_fork_version();
2991 if (version >= HF_VERSION_2021_SCALING)
2992 {
2993 m_core.get_blockchain_storage().get_dynamic_base_fee_estimate_2021_scaling(req.grace_blocks, res.fees);
2994 res.fee = res.fees[0];
2995 }
2996 else
2997 {
2998 res.fee = m_core.get_blockchain_storage().get_dynamic_base_fee_estimate(req.grace_blocks);
2999 }
3000 res.quantization_mask = Blockchain::get_fee_quantization_mask();
3001 res.status = CORE_RPC_STATUS_OK;
3002 return true;
3003 }
3004 //------------------------------------------------------------------------------------------------------------------------------
3005 bool core_rpc_server::on_get_alternate_chains(const COMMAND_RPC_GET_ALTERNATE_CHAINS::request& req, COMMAND_RPC_GET_ALTERNATE_CHAINS::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3006 {
3007 RPC_TRACKER(get_alternate_chains);
3008 try
3009 {
3010 std::vector<std::pair<Blockchain::block_extended_info, std::vector<crypto::hash>>> chains = m_core.get_blockchain_storage().get_alternative_chains();
3011 for (const auto &i: chains)
3012 {
3013 difficulty_type wdiff = i.first.cumulative_difficulty;
3014 res.chains.push_back(COMMAND_RPC_GET_ALTERNATE_CHAINS::chain_info{epee::string_tools::pod_to_hex(get_block_hash(i.first.bl)), i.first.height, i.second.size(), 0, "", 0, {}, std::string()});
3015 store_difficulty(wdiff, res.chains.back().difficulty, res.chains.back().wide_difficulty, res.chains.back().difficulty_top64);
3016 res.chains.back().block_hashes.reserve(i.second.size());
3017 for (const crypto::hash &block_id: i.second)
3018 res.chains.back().block_hashes.push_back(epee::string_tools::pod_to_hex(block_id));
3019 if (i.first.height < i.second.size())
3020 {
3021 res.status = "Error finding alternate chain attachment point";
3022 return true;
3023 }
3024 cryptonote::block main_chain_parent_block;
3025 try { main_chain_parent_block = m_core.get_blockchain_storage().get_db().get_block_from_height(i.first.height - i.second.size()); }
3026 catch (const std::exception &e) { res.status = "Error finding alternate chain attachment point"; return true; }
3027 res.chains.back().main_chain_parent_block = epee::string_tools::pod_to_hex(get_block_hash(main_chain_parent_block));
3028 }
3029 res.status = CORE_RPC_STATUS_OK;
3030 }
3031 catch (...)
3032 {
3033 res.status = "Error retrieving alternate chains";
3034 }
3035 return true;
3036 }
3037 //------------------------------------------------------------------------------------------------------------------------------
3038 bool core_rpc_server::on_get_limit(const COMMAND_RPC_GET_LIMIT::request& req, COMMAND_RPC_GET_LIMIT::response& res, const connection_context *ctx)
3039 {
3040 RPC_TRACKER(get_limit);
3041 bool r;
3042 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_LIMIT>(invoke_http_mode::JON, "/get_limit", req, res, r))
3043 return r;
3044
3045 res.limit_down = epee::net_utils::connection_basic::get_rate_down_limit();
3046 res.limit_up = epee::net_utils::connection_basic::get_rate_up_limit();
3047 res.status = CORE_RPC_STATUS_OK;
3048 return true;
3049 }
3050 //------------------------------------------------------------------------------------------------------------------------------
3051 bool core_rpc_server::on_set_limit(const COMMAND_RPC_SET_LIMIT::request& req, COMMAND_RPC_SET_LIMIT::response& res, const connection_context *ctx)
3052 {
3053 RPC_TRACKER(set_limit);
3054 // -1 = reset to default
3055 // 0 = do not modify
3056
3057 if (req.limit_down > 0)
3058 {
3059 epee::net_utils::connection_basic::set_rate_down_limit(req.limit_down);
3060 }
3061 else if (req.limit_down < 0)
3062 {
3063 if (req.limit_down != -1)
3064 {
3065 res.status = "Invalid parameter";
3066 return true;
3067 }
3068 epee::net_utils::connection_basic::set_rate_down_limit(nodetool::default_limit_down);
3069 }
3070
3071 if (req.limit_up > 0)
3072 {
3073 epee::net_utils::connection_basic::set_rate_up_limit(req.limit_up);
3074 }
3075 else if (req.limit_up < 0)
3076 {
3077 if (req.limit_up != -1)
3078 {
3079 res.status = "Invalid parameter";
3080 return true;
3081 }
3082 epee::net_utils::connection_basic::set_rate_up_limit(nodetool::default_limit_up);
3083 }
3084
3085 res.limit_down = epee::net_utils::connection_basic::get_rate_down_limit();
3086 res.limit_up = epee::net_utils::connection_basic::get_rate_up_limit();
3087 res.status = CORE_RPC_STATUS_OK;
3088 return true;
3089 }
3090 //------------------------------------------------------------------------------------------------------------------------------
3091 bool core_rpc_server::on_out_peers(const COMMAND_RPC_OUT_PEERS::request& req, COMMAND_RPC_OUT_PEERS::response& res, const connection_context *ctx)
3092 {
3093 RPC_TRACKER(out_peers);
3094 if (req.set)
3095 m_p2p.change_max_out_public_peers(req.out_peers);
3096 res.out_peers = m_p2p.get_max_out_public_peers();
3097 res.status = CORE_RPC_STATUS_OK;
3098 return true;
3099 }
3100 //------------------------------------------------------------------------------------------------------------------------------
3101 bool core_rpc_server::on_in_peers(const COMMAND_RPC_IN_PEERS::request& req, COMMAND_RPC_IN_PEERS::response& res, const connection_context *ctx)
3102 {
3103 RPC_TRACKER(in_peers);
3104 if (req.set)
3105 m_p2p.change_max_in_public_peers(req.in_peers);
3106 res.in_peers = m_p2p.get_max_in_public_peers();
3107 res.status = CORE_RPC_STATUS_OK;
3108 return true;
3109 }
3110 //------------------------------------------------------------------------------------------------------------------------------
3111 bool core_rpc_server::on_update(const COMMAND_RPC_UPDATE::request& req, COMMAND_RPC_UPDATE::response& res, const connection_context *ctx)
3112 {
3113 RPC_TRACKER(update);
3114
3115 res.update = false;
3116 if (m_core.offline())
3117 {
3118 res.status = "Daemon is running offline";
3119 return true;
3120 }
3121
3122 static const char software[] = "monero";
3123 #ifdef BUILD_TAG
3124 static const char buildtag[] = BOOST_PP_STRINGIZE(BUILD_TAG);
3125 static const char subdir[] = "cli";
3126 #else
3127 static const char buildtag[] = "source";
3128 static const char subdir[] = "source";
3129 #endif
3130
3131 if (req.command != "check" && req.command != "download" && req.command != "update")
3132 {
3133 res.status = std::string("unknown command: '") + req.command + "'";
3134 return true;
3135 }
3136
3137 std::string version, hash;
3138 if (!tools::check_updates(software, buildtag, version, hash))
3139 {
3140 res.status = "Error checking for updates";
3141 return true;
3142 }
3143 if (tools::vercmp(version.c_str(), MONERO_VERSION) <= 0)
3144 {
3145 res.update = false;
3146 res.status = CORE_RPC_STATUS_OK;
3147 return true;
3148 }
3149 res.update = true;
3150 res.version = version;
3151 res.user_uri = tools::get_update_url(software, subdir, buildtag, version, true);
3152 res.auto_uri = tools::get_update_url(software, subdir, buildtag, version, false);
3153 res.hash = hash;
3154 if (req.command == "check")
3155 {
3156 res.status = CORE_RPC_STATUS_OK;
3157 return true;
3158 }
3159
3160 boost::filesystem::path path;
3161 if (req.path.empty())
3162 {
3163 std::string filename;
3164 const char *slash = strrchr(res.auto_uri.c_str(), '/');
3165 if (slash)
3166 filename = slash + 1;
3167 else
3168 filename = std::string(software) + "-update-" + version;
3169 path = epee::string_tools::get_current_module_folder();
3170 path /= filename;
3171 }
3172 else
3173 {
3174 path = req.path;
3175 }
3176
3177 crypto::hash file_hash;
3178 if (!tools::sha256sum(path.string(), file_hash) || (hash != epee::string_tools::pod_to_hex(file_hash)))
3179 {
3180 MDEBUG("We don't have that file already, downloading");
3181 if (!tools::download(path.string(), res.auto_uri))
3182 {
3183 MERROR("Failed to download " << res.auto_uri);
3184 return true;
3185 }
3186 if (!tools::sha256sum(path.string(), file_hash))
3187 {
3188 MERROR("Failed to hash " << path);
3189 return true;
3190 }
3191 if (hash != epee::string_tools::pod_to_hex(file_hash))
3192 {
3193 MERROR("Download from " << res.auto_uri << " does not match the expected hash");
3194 return true;
3195 }
3196 MINFO("New version downloaded to " << path);
3197 }
3198 else
3199 {
3200 MDEBUG("We already have " << path << " with expected hash");
3201 }
3202 res.path = path.string();
3203
3204 if (req.command == "download")
3205 {
3206 res.status = CORE_RPC_STATUS_OK;
3207 return true;
3208 }
3209
3210 res.status = "'update' not implemented yet";
3211 return true;
3212 }
3213 //------------------------------------------------------------------------------------------------------------------------------
3214 bool core_rpc_server::on_pop_blocks(const COMMAND_RPC_POP_BLOCKS::request& req, COMMAND_RPC_POP_BLOCKS::response& res, const connection_context *ctx)
3215 {
3216 RPC_TRACKER(pop_blocks);
3217
3218 m_core.get_blockchain_storage().pop_blocks(req.nblocks);
3219
3220 res.height = m_core.get_current_blockchain_height();
3221 res.status = CORE_RPC_STATUS_OK;
3222
3223 return true;
3224 }
3225 //------------------------------------------------------------------------------------------------------------------------------
3226 bool core_rpc_server::on_relay_tx(const COMMAND_RPC_RELAY_TX::request& req, COMMAND_RPC_RELAY_TX::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3227 {
3228 RPC_TRACKER(relay_tx);
3229 CHECK_PAYMENT_MIN1(req, res, req.txids.size() * COST_PER_TX_RELAY, false);
3230
3231 const bool restricted = m_restricted && ctx;
3232
3233 bool failed = false;
3234 res.status = "";
3235 for (const auto &str: req.txids)
3236 {
3237 crypto::hash txid;
3238 if(!epee::string_tools::hex_to_pod(str, txid))
3239 {
3240 if (!res.status.empty()) res.status += ", ";
3241 res.status += std::string("invalid transaction id: ") + str;
3242 failed = true;
3243 continue;
3244 }
3245
3246 //TODO: The get_pool_transaction could have an optional meta parameter
3247 bool broadcasted = false;
3248 cryptonote::blobdata txblob;
3249 if ((broadcasted = m_core.get_pool_transaction(txid, txblob, relay_category::broadcasted)) || (!restricted && m_core.get_pool_transaction(txid, txblob, relay_category::all)))
3250 {
3251 // The settings below always choose i2p/tor if enabled. Otherwise, do fluff iff previously relayed else dandelion++ stem.
3252 NOTIFY_NEW_TRANSACTIONS::request r;
3253 r.txs.push_back(std::move(txblob));
3254 const auto tx_relay = broadcasted ? relay_method::fluff : relay_method::local;
3255 m_core.get_protocol()->relay_transactions(r, boost::uuids::nil_uuid(), epee::net_utils::zone::invalid, tx_relay);
3256 //TODO: make sure that tx has reached other nodes here, probably wait to receive reflections from other nodes
3257 }
3258 else
3259 {
3260 if (!res.status.empty()) res.status += ", ";
3261 res.status += std::string("transaction not found in pool: ") + str;
3262 failed = true;
3263 continue;
3264 }
3265 }
3266
3267 if (failed)
3268 {
3269 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3270 error_resp.message = res.status;
3271 return false;
3272 }
3273
3274 res.status = CORE_RPC_STATUS_OK;
3275 return true;
3276 }
3277 //------------------------------------------------------------------------------------------------------------------------------
3278 bool core_rpc_server::on_sync_info(const COMMAND_RPC_SYNC_INFO::request& req, COMMAND_RPC_SYNC_INFO::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3279 {
3280 RPC_TRACKER(sync_info);
3281 CHECK_PAYMENT(req, res, COST_PER_SYNC_INFO);
3282
3283 crypto::hash top_hash;
3284 m_core.get_blockchain_top(res.height, top_hash);
3285 ++res.height; // turn top block height into blockchain height
3286 res.target_height = m_p2p.get_payload_object().is_synchronized() ? 0 : m_core.get_target_blockchain_height();
3287 res.next_needed_pruning_seed = m_p2p.get_payload_object().get_next_needed_pruning_stripe().second;
3288
3289 for (const auto &c: m_p2p.get_payload_object().get_connections())
3290 res.peers.push_back({c});
3291 const cryptonote::block_queue &block_queue = m_p2p.get_payload_object().get_block_queue();
3292 block_queue.foreach([&](const cryptonote::block_queue::span &span) {
3293 const std::string span_connection_id = epee::string_tools::pod_to_hex(span.connection_id);
3294 uint32_t speed = (uint32_t)(100.0f * block_queue.get_speed(span.connection_id) + 0.5f);
3295 res.spans.push_back({span.start_block_height, span.nblocks, span_connection_id, (uint32_t)(span.rate + 0.5f), speed, span.size, span.origin.str()});
3296 return true;
3297 });
3298 res.overview = block_queue.get_overview(res.height);
3299
3300 res.status = CORE_RPC_STATUS_OK;
3301 return true;
3302 }
3303 //------------------------------------------------------------------------------------------------------------------------------
3304 bool core_rpc_server::on_get_txpool_backlog(const COMMAND_RPC_GET_TRANSACTION_POOL_BACKLOG::request& req, COMMAND_RPC_GET_TRANSACTION_POOL_BACKLOG::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3305 {
3306 RPC_TRACKER(get_txpool_backlog);
3307 bool r;
3308 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_TRANSACTION_POOL_BACKLOG>(invoke_http_mode::JON_RPC, "get_txpool_backlog", req, res, r))
3309 return r;
3310 size_t n_txes = m_core.get_pool_transactions_count();
3311 CHECK_PAYMENT_MIN1(req, res, COST_PER_TX_POOL_STATS * n_txes, false);
3312
3313 if (!m_core.get_txpool_backlog(res.backlog))
3314 {
3315 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3316 error_resp.message = "Failed to get txpool backlog";
3317 return false;
3318 }
3319
3320 res.status = CORE_RPC_STATUS_OK;
3321 return true;
3322 }
3323 //------------------------------------------------------------------------------------------------------------------------------
3324 bool core_rpc_server::on_get_output_distribution(const COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::request& req, COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3325 {
3326 RPC_TRACKER(get_output_distribution);
3327 bool r;
3328 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_OUTPUT_DISTRIBUTION>(invoke_http_mode::JON_RPC, "get_output_distribution", req, res, r))
3329 return r;
3330
3331 const bool restricted = m_restricted && ctx;
3332 if (restricted && req.amounts != std::vector<uint64_t>(1, 0))
3333 {
3334 error_resp.code = CORE_RPC_ERROR_CODE_RESTRICTED;
3335 error_resp.message = "Restricted RPC can only get output distribution for rct outputs. Use your own node.";
3336 return false;
3337 }
3338
3339 size_t n_0 = 0, n_non0 = 0;
3340 for (uint64_t amount: req.amounts)
3341 if (amount) ++n_non0; else ++n_0;
3342 CHECK_PAYMENT_MIN1(req, res, n_0 * COST_PER_OUTPUT_DISTRIBUTION_0 + n_non0 * COST_PER_OUTPUT_DISTRIBUTION, false);
3343
3344 try
3345 {
3346 // 0 is placeholder for the whole chain
3347 const uint64_t req_to_height = req.to_height ? req.to_height : (m_core.get_current_blockchain_height() - 1);
3348 for (uint64_t amount: req.amounts)
3349 {
3350 auto data = rpc::RpcHandler::get_output_distribution([this](uint64_t amount, uint64_t from, uint64_t to, uint64_t &start_height, std::vector<uint64_t> &distribution, uint64_t &base) { return m_core.get_output_distribution(amount, from, to, start_height, distribution, base); }, amount, req.from_height, req_to_height, [this](uint64_t height) { return m_core.get_blockchain_storage().get_db().get_block_hash_from_height(height); }, req.cumulative, m_core.get_current_blockchain_height());
3351 if (!data)
3352 {
3353 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3354 error_resp.message = "Failed to get output distribution";
3355 return false;
3356 }
3357
3358 res.distributions.push_back({std::move(*data), amount, "", req.binary, req.compress});
3359 }
3360 }
3361 catch (const std::exception &e)
3362 {
3363 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3364 error_resp.message = "Failed to get output distribution";
3365 return false;
3366 }
3367
3368 res.status = CORE_RPC_STATUS_OK;
3369 return true;
3370 }
3371 //------------------------------------------------------------------------------------------------------------------------------
3372 bool core_rpc_server::on_get_output_distribution_bin(const COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::request& req, COMMAND_RPC_GET_OUTPUT_DISTRIBUTION::response& res, const connection_context *ctx)
3373 {
3374 RPC_TRACKER(get_output_distribution_bin);
3375
3376 bool r;
3377 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_GET_OUTPUT_DISTRIBUTION>(invoke_http_mode::BIN, "/get_output_distribution.bin", req, res, r))
3378 return r;
3379
3380 const bool restricted = m_restricted && ctx;
3381 if (restricted && req.amounts != std::vector<uint64_t>(1, 0))
3382 {
3383 res.status = "Restricted RPC can only get output distribution for rct outputs. Use your own node.";
3384 return false;
3385 }
3386
3387 size_t n_0 = 0, n_non0 = 0;
3388 for (uint64_t amount: req.amounts)
3389 if (amount) ++n_non0; else ++n_0;
3390 CHECK_PAYMENT_MIN1(req, res, n_0 * COST_PER_OUTPUT_DISTRIBUTION_0 + n_non0 * COST_PER_OUTPUT_DISTRIBUTION, false);
3391
3392 res.status = "Failed";
3393
3394 if (!req.binary)
3395 {
3396 res.status = "Binary only call";
3397 return true;
3398 }
3399 try
3400 {
3401 // 0 is placeholder for the whole chain
3402 const uint64_t req_to_height = req.to_height ? req.to_height : (m_core.get_current_blockchain_height() - 1);
3403 for (uint64_t amount: req.amounts)
3404 {
3405 auto data = rpc::RpcHandler::get_output_distribution([this](uint64_t amount, uint64_t from, uint64_t to, uint64_t &start_height, std::vector<uint64_t> &distribution, uint64_t &base) { return m_core.get_output_distribution(amount, from, to, start_height, distribution, base); }, amount, req.from_height, req_to_height, [this](uint64_t height) { return m_core.get_blockchain_storage().get_db().get_block_hash_from_height(height); }, req.cumulative, m_core.get_current_blockchain_height());
3406 if (!data)
3407 {
3408 res.status = "Failed to get output distribution";
3409 return true;
3410 }
3411
3412 res.distributions.push_back({std::move(*data), amount, "", req.binary, req.compress});
3413 }
3414 }
3415 catch (const std::exception &e)
3416 {
3417 res.status = "Failed to get output distribution";
3418 return true;
3419 }
3420
3421 res.status = CORE_RPC_STATUS_OK;
3422 return true;
3423 }
3424 //------------------------------------------------------------------------------------------------------------------------------
3425 bool core_rpc_server::on_prune_blockchain(const COMMAND_RPC_PRUNE_BLOCKCHAIN::request& req, COMMAND_RPC_PRUNE_BLOCKCHAIN::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3426 {
3427 RPC_TRACKER(prune_blockchain);
3428
3429 try
3430 {
3431 if (!(req.check ? m_core.check_blockchain_pruning() : m_core.prune_blockchain()))
3432 {
3433 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3434 error_resp.message = req.check ? "Failed to check blockchain pruning" : "Failed to prune blockchain";
3435 return false;
3436 }
3437 res.pruning_seed = m_core.get_blockchain_pruning_seed();
3438 res.pruned = res.pruning_seed != 0;
3439 }
3440 catch (const std::exception &e)
3441 {
3442 error_resp.code = CORE_RPC_ERROR_CODE_INTERNAL_ERROR;
3443 error_resp.message = "Failed to prune blockchain";
3444 return false;
3445 }
3446 res.status = CORE_RPC_STATUS_OK;
3447 return true;
3448 }
3449 //------------------------------------------------------------------------------------------------------------------------------
3450 bool core_rpc_server::on_rpc_access_info(const COMMAND_RPC_ACCESS_INFO::request& req, COMMAND_RPC_ACCESS_INFO::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3451 {
3452 RPC_TRACKER(rpc_access_info);
3453
3454 bool r;
3455 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ACCESS_INFO>(invoke_http_mode::JON_RPC, "rpc_access_info", req, res, r))
3456 return r;
3457
3458 // if RPC payment is not enabled
3459 if (m_rpc_payment == NULL)
3460 {
3461 res.diff = 0;
3462 res.credits_per_hash_found = 0;
3463 res.credits = 0;
3464 res.height = 0;
3465 res.seed_height = 0;
3466 res.status = CORE_RPC_STATUS_OK;
3467 return true;
3468 }
3469
3470 crypto::public_key client;
3471 uint64_t ts;
3472 if (!cryptonote::verify_rpc_payment_signature(req.client, client, ts))
3473 {
3474 error_resp.code = CORE_RPC_ERROR_CODE_INVALID_CLIENT;
3475 error_resp.message = "Invalid client ID";
3476 return false;
3477 }
3478
3479 crypto::hash top_hash;
3480 m_core.get_blockchain_top(res.height, top_hash);
3481 ++res.height;
3482 cryptonote::blobdata hashing_blob;
3483 crypto::hash seed_hash, next_seed_hash;
3484 if (!m_rpc_payment->get_info(client, [&](const cryptonote::blobdata &extra_nonce, cryptonote::block &b, uint64_t &seed_height, crypto::hash &seed_hash)->bool{
3485 cryptonote::difficulty_type difficulty;
3486 uint64_t height, expected_reward;
3487 size_t reserved_offset;
3488 if (!get_block_template(m_rpc_payment->get_payment_address(), NULL, extra_nonce, reserved_offset, difficulty, height, expected_reward, b, seed_height, seed_hash, next_seed_hash, error_resp))
3489 return false;
3490 return true;
3491 }, hashing_blob, res.seed_height, seed_hash, top_hash, res.diff, res.credits_per_hash_found, res.credits, res.cookie))
3492 {
3493 return false;
3494 }
3495 if (hashing_blob.empty())
3496 {
3497 error_resp.code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB;
3498 error_resp.message = "Invalid hashing blob";
3499 return false;
3500 }
3501 res.hashing_blob = epee::string_tools::buff_to_hex_nodelimer(hashing_blob);
3502 res.top_hash = epee::string_tools::pod_to_hex(top_hash);
3503 if (hashing_blob[0] >= RX_BLOCK_VERSION)
3504 {
3505 res.seed_hash = string_tools::pod_to_hex(seed_hash);
3506 if (seed_hash != next_seed_hash)
3507 res.next_seed_hash = string_tools::pod_to_hex(next_seed_hash);
3508 }
3509
3510 res.status = CORE_RPC_STATUS_OK;
3511 return true;
3512 }
3513 //------------------------------------------------------------------------------------------------------------------------------
3514 bool core_rpc_server::on_flush_cache(const COMMAND_RPC_FLUSH_CACHE::request& req, COMMAND_RPC_FLUSH_CACHE::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3515 {
3516 RPC_TRACKER(flush_cache);
3517 if (req.bad_blocks)
3518 m_core.flush_invalid_blocks();
3519 res.status = CORE_RPC_STATUS_OK;
3520 return true;
3521 }
3522 //------------------------------------------------------------------------------------------------------------------------------
3523 bool core_rpc_server::on_rpc_access_submit_nonce(const COMMAND_RPC_ACCESS_SUBMIT_NONCE::request& req, COMMAND_RPC_ACCESS_SUBMIT_NONCE::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3524 {
3525 RPC_TRACKER(rpc_access_submit_nonce);
3526 bool r;
3527 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ACCESS_SUBMIT_NONCE>(invoke_http_mode::JON_RPC, "rpc_access_submit_nonce", req, res, r))
3528 return r;
3529
3530 // if RPC payment is not enabled
3531 if (m_rpc_payment == NULL)
3532 {
3533 res.status = "Payment not necessary";
3534 return true;
3535 }
3536
3537 crypto::public_key client;
3538 uint64_t ts;
3539 if (!cryptonote::verify_rpc_payment_signature(req.client, client, ts))
3540 {
3541 res.credits = 0;
3542 error_resp.code = CORE_RPC_ERROR_CODE_INVALID_CLIENT;
3543 error_resp.message = "Invalid client ID";
3544 return false;
3545 }
3546
3547 crypto::hash hash;
3548 cryptonote::block block;
3549 crypto::hash top_hash;
3550 uint64_t height;
3551 bool stale;
3552 m_core.get_blockchain_top(height, top_hash);
3553 if (!m_rpc_payment->submit_nonce(client, req.nonce, top_hash, error_resp.code, error_resp.message, res.credits, hash, block, req.cookie, stale))
3554 {
3555 return false;
3556 }
3557
3558 if (!stale)
3559 {
3560 // it might be a valid block!
3561 const difficulty_type current_difficulty = m_core.get_blockchain_storage().get_difficulty_for_next_block();
3562 if (check_hash(hash, current_difficulty))
3563 {
3564 MINFO("This payment meets the current network difficulty");
3565 block_verification_context bvc;
3566 if(m_core.handle_block_found(block, bvc))
3567 MGINFO_GREEN("Block found by RPC user at height " << get_block_height(block) << ": " <<
3568 print_money(cryptonote::get_outs_money_amount(block.miner_tx)));
3569 else
3570 MERROR("Seemingly valid block was not accepted");
3571 }
3572 }
3573
3574 m_core.get_blockchain_top(height, top_hash);
3575 res.top_hash = epee::string_tools::pod_to_hex(top_hash);
3576
3577 res.status = CORE_RPC_STATUS_OK;
3578 return true;
3579 }
3580 //------------------------------------------------------------------------------------------------------------------------------
3581 bool core_rpc_server::on_rpc_access_pay(const COMMAND_RPC_ACCESS_PAY::request& req, COMMAND_RPC_ACCESS_PAY::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3582 {
3583 RPC_TRACKER(rpc_access_pay);
3584
3585 bool r;
3586 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ACCESS_PAY>(invoke_http_mode::JON_RPC, "rpc_access_pay", req, res, r))
3587 return r;
3588
3589 // if RPC payment is not enabled
3590 if (m_rpc_payment == NULL)
3591 {
3592 res.status = "Payment not necessary";
3593 return true;
3594 }
3595
3596 crypto::public_key client;
3597 uint64_t ts;
3598 if (!cryptonote::verify_rpc_payment_signature(req.client, client, ts))
3599 {
3600 res.credits = 0;
3601 error_resp.code = CORE_RPC_ERROR_CODE_INVALID_CLIENT;
3602 error_resp.message = "Invalid client ID";
3603 return false;
3604 }
3605
3606 RPCTracker ext_tracker(("external:" + req.paying_for).c_str(), PERF_TIMER_NAME(rpc_access_pay));
3607 if (!check_payment(req.client, req.payment, req.paying_for, false, res.status, res.credits, res.top_hash))
3608 return true;
3609 ext_tracker.pay(req.payment);
3610
3611 res.status = CORE_RPC_STATUS_OK;
3612 return true;
3613 }
3614 //------------------------------------------------------------------------------------------------------------------------------
3615 bool core_rpc_server::on_rpc_access_tracking(const COMMAND_RPC_ACCESS_TRACKING::request& req, COMMAND_RPC_ACCESS_TRACKING::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3616 {
3617 RPC_TRACKER(rpc_access_tracking);
3618
3619 if (req.clear)
3620 {
3621 RPCTracker::clear();
3622 res.status = CORE_RPC_STATUS_OK;
3623 return true;
3624 }
3625
3626 auto data = RPCTracker::data();
3627 for (const auto &d: data)
3628 {
3629 res.data.resize(res.data.size() + 1);
3630 res.data.back().rpc = d.first;
3631 res.data.back().count = d.second.count;
3632 res.data.back().time = d.second.time;
3633 res.data.back().credits = d.second.credits;
3634 }
3635
3636 res.status = CORE_RPC_STATUS_OK;
3637 return true;
3638 }
3639 //------------------------------------------------------------------------------------------------------------------------------
3640 bool core_rpc_server::on_rpc_access_data(const COMMAND_RPC_ACCESS_DATA::request& req, COMMAND_RPC_ACCESS_DATA::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3641 {
3642 RPC_TRACKER(rpc_access_data);
3643
3644 bool r;
3645 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ACCESS_DATA>(invoke_http_mode::JON_RPC, "rpc_access_data", req, res, r))
3646 return r;
3647
3648 if (!m_rpc_payment)
3649 {
3650 error_resp.code = CORE_RPC_ERROR_CODE_PAYMENTS_NOT_ENABLED;
3651 error_resp.message = "Payments not enabled";
3652 return false;
3653 }
3654
3655 m_rpc_payment->foreach([&](const crypto::public_key &client, const rpc_payment::client_info &info){
3656 res.entries.push_back({
3657 epee::string_tools::pod_to_hex(client), info.credits, std::max(info.last_request_timestamp / 1000000, info.update_time),
3658 info.credits_total, info.credits_used, info.nonces_good, info.nonces_stale, info.nonces_bad, info.nonces_dupe
3659 });
3660 return true;
3661 });
3662
3663 res.hashrate = m_rpc_payment->get_hashes(600) / 600;
3664
3665 res.status = CORE_RPC_STATUS_OK;
3666 return true;
3667 }
3668 //------------------------------------------------------------------------------------------------------------------------------
3669 bool core_rpc_server::on_rpc_access_account(const COMMAND_RPC_ACCESS_ACCOUNT::request& req, COMMAND_RPC_ACCESS_ACCOUNT::response& res, epee::json_rpc::error& error_resp, const connection_context *ctx)
3670 {
3671 RPC_TRACKER(rpc_access_account);
3672
3673 bool r;
3674 if (use_bootstrap_daemon_if_necessary<COMMAND_RPC_ACCESS_ACCOUNT>(invoke_http_mode::JON_RPC, "rpc_access_account", req, res, r))
3675 return r;
3676
3677 if (!m_rpc_payment)
3678 {
3679 error_resp.code = CORE_RPC_ERROR_CODE_PAYMENTS_NOT_ENABLED;
3680 error_resp.message = "Payments not enabled";
3681 return false;
3682 }
3683
3684 crypto::public_key client;
3685 if (!epee::string_tools::hex_to_pod(req.client.substr(0, 2 * sizeof(client)), client))
3686 {
3687 error_resp.code = CORE_RPC_ERROR_CODE_INVALID_CLIENT;
3688 error_resp.message = "Invalid client ID";
3689 return false;
3690 }
3691
3692 res.credits = m_rpc_payment->balance(client, req.delta_balance);
3693
3694 res.status = CORE_RPC_STATUS_OK;
3695 return true;
3696 }
3697 //------------------------------------------------------------------------------------------------------------------------------
3698 const command_line::arg_descriptor<std::string, false, true, 2> core_rpc_server::arg_rpc_bind_port = {
3699 "rpc-bind-port"
3700 , "Port for RPC server"
3701 , std::to_string(config::RPC_DEFAULT_PORT)
3702 , {{ &cryptonote::arg_testnet_on, &cryptonote::arg_stagenet_on }}
3703 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
3704 if (testnet_stagenet[0] && defaulted)
3705 return std::to_string(config::testnet::RPC_DEFAULT_PORT);
3706 else if (testnet_stagenet[1] && defaulted)
3707 return std::to_string(config::stagenet::RPC_DEFAULT_PORT);
3708 return val;
3709 }
3710 };
3711
3712 const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_restricted_bind_port = {
3713 "rpc-restricted-bind-port"
3714 , "Port for restricted RPC server"
3715 , ""
3716 };
3717
3718 const command_line::arg_descriptor<bool> core_rpc_server::arg_restricted_rpc = {
3719 "restricted-rpc"
3720 , "Restrict RPC to view only commands and do not return privacy sensitive data in RPC calls"
3721 , false
3722 };
3723
3724 const command_line::arg_descriptor<std::string> core_rpc_server::arg_bootstrap_daemon_address = {
3725 "bootstrap-daemon-address"
3726 , "URL of a 'bootstrap' remote daemon that the connected wallets can use while this daemon is still not fully synced.\n"
3727 "Use 'auto' to enable automatic public nodes discovering and bootstrap daemon switching"
3728 , ""
3729 };
3730
3731 const command_line::arg_descriptor<std::string> core_rpc_server::arg_bootstrap_daemon_login = {
3732 "bootstrap-daemon-login"
3733 , "Specify username:password for the bootstrap daemon login"
3734 , ""
3735 };
3736
3737 const command_line::arg_descriptor<std::string> core_rpc_server::arg_bootstrap_daemon_proxy = {
3738 "bootstrap-daemon-proxy"
3739 , "<ip>:<port> socks proxy to use for bootstrap daemon connections"
3740 , ""
3741 };
3742
3743 const command_line::arg_descriptor<std::string> core_rpc_server::arg_rpc_payment_address = {
3744 "rpc-payment-address"
3745 , "Restrict RPC to clients sending micropayment to this address"
3746 , ""
3747 };
3748
3749 const command_line::arg_descriptor<uint64_t> core_rpc_server::arg_rpc_payment_difficulty = {
3750 "rpc-payment-difficulty"
3751 , "Restrict RPC to clients sending micropayment at this difficulty"
3752 , DEFAULT_PAYMENT_DIFFICULTY
3753 };
3754
3755 const command_line::arg_descriptor<uint64_t> core_rpc_server::arg_rpc_payment_credits = {
3756 "rpc-payment-credits"
3757 , "Restrict RPC to clients sending micropayment, yields that many credits per payment"
3758 , DEFAULT_PAYMENT_CREDITS_PER_HASH
3759 };
3760
3761 const command_line::arg_descriptor<bool> core_rpc_server::arg_rpc_payment_allow_free_loopback = {
3762 "rpc-payment-allow-free-loopback"
3763 , "Allow free access from the loopback address (ie, the local host)"
3764 , false
3765 };
3766
3767 const command_line::arg_descriptor<std::size_t> core_rpc_server::arg_rpc_max_connections_per_public_ip = {
3768 "rpc-max-connections-per-public-ip"
3769 , "Max RPC connections per public IP permitted"
3770 , DEFAULT_RPC_MAX_CONNECTIONS_PER_PUBLIC_IP
3771 };
3772
3773 const command_line::arg_descriptor<std::size_t> core_rpc_server::arg_rpc_max_connections_per_private_ip = {
3774 "rpc-max-connections-per-private-ip"
3775 , "Max RPC connections per private and localhost IP permitted"
3776 , DEFAULT_RPC_MAX_CONNECTIONS_PER_PRIVATE_IP
3777 };
3778
3779 const command_line::arg_descriptor<std::size_t> core_rpc_server::arg_rpc_max_connections = {
3780 "rpc-max-connections"
3781 , "Max RPC connections permitted"
3782 , DEFAULT_RPC_MAX_CONNECTIONS
3783 };
3784
3785 const command_line::arg_descriptor<std::size_t> core_rpc_server::arg_rpc_response_soft_limit = {
3786 "rpc-response-soft-limit"
3787 , "Max response bytes that can be queued, enforced at next response attempt"
3788 , DEFAULT_RPC_SOFT_LIMIT_SIZE
3789 };
3790 } // namespace cryptonote