Debian Codegraph @

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