Debian Codegraph @

src/rpc/daemon_handler.cpp

raw symbols SCIP
1 // Copyright (c) 2017-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 #include "daemon_handler.h"
30 #include "rpc/zmq_restricted_methods.h"
31
32 #include <algorithm>
33 #include <chrono>
34 #include <cstring>
35 #include <stdexcept>
36
37 #include <boost/uuid/nil_generator.hpp>
38 #include <boost/utility/string_ref.hpp>
39 // likely included by daemon_handler.h's includes,
40 // but including here for clarity
41 #include "cryptonote_core/cryptonote_core.h"
42 #include "cryptonote_basic/cryptonote_format_utils.h"
43 #include "cryptonote_basic/blobdatatype.h"
44 #include "ringct/rctSigs.h"
45 #include "version.h"
46
47 namespace
48 {
49 constexpr size_t restricted_max_fake_outs = 5000;
50 constexpr auto restricted_histogram_cutoff = std::chrono::hours{3 * 24};
51 constexpr size_t restricted_max_txs = 100;
52 constexpr size_t restricted_max_key_images = 5000;
53 constexpr size_t restricted_max_block_headers = 1000;
54 }
55
56 namespace cryptonote
57 {
58
59 namespace rpc
60 {
61 namespace
62 {
63 using handler_function = epee::byte_slice(DaemonHandler& handler, const rapidjson::Value& id, const rapidjson::Value& msg);
64 struct handler_map
65 {
66 const char* method_name;
67 handler_function* call;
68 };
69
70 bool operator<(const handler_map& lhs, const handler_map& rhs) noexcept
71 {
72 return std::strcmp(lhs.method_name, rhs.method_name) < 0;
73 }
74
75 bool operator<(const handler_map& lhs, const std::string& rhs) noexcept
76 {
77 return std::strcmp(lhs.method_name, rhs.c_str()) < 0;
78 }
79
80 template<typename Message>
81 epee::byte_slice handle_message(DaemonHandler& handler, const rapidjson::Value& id, const rapidjson::Value& parameters)
82 {
83 typename Message::Request request{};
84 request.fromJson(parameters);
85
86 typename Message::Response response{};
87 handler.handle(request, response);
88 return FullMessage::getResponse(response, id);
89 }
90
91 constexpr const handler_map handlers[] =
92 {
93 {u8"get_block_hash", handle_message<GetBlockHash>},
94 {u8"get_block_header_by_hash", handle_message<GetBlockHeaderByHash>},
95 {u8"get_block_header_by_height", handle_message<GetBlockHeaderByHeight>},
96 {u8"get_block_headers_by_height", handle_message<GetBlockHeadersByHeight>},
97 {u8"get_blocks_fast", handle_message<GetBlocksFast>},
98 {u8"get_dynamic_fee_estimate", handle_message<GetFeeEstimate>},
99 {u8"get_hashes_fast", handle_message<GetHashesFast>},
100 {u8"get_height", handle_message<GetHeight>},
101 {u8"get_info", handle_message<GetInfo>},
102 {u8"get_last_block_header", handle_message<GetLastBlockHeader>},
103 {u8"get_output_distribution", handle_message<GetOutputDistribution>},
104 {u8"get_output_histogram", handle_message<GetOutputHistogram>},
105 {u8"get_output_keys", handle_message<GetOutputKeys>},
106 {u8"get_peer_list", handle_message<GetPeerList>},
107 {u8"get_rpc_version", handle_message<GetRPCVersion>},
108 {u8"get_transaction_pool", handle_message<GetTransactionPool>},
109 {u8"get_transactions", handle_message<GetTransactions>},
110 {u8"get_tx_global_output_indices", handle_message<GetTxGlobalOutputIndices>},
111 {u8"hard_fork_info", handle_message<HardForkInfo>},
112 {u8"key_images_spent", handle_message<KeyImagesSpent>},
113 {u8"mining_status", handle_message<MiningStatus>},
114 {u8"save_bc", handle_message<SaveBC>},
115 {u8"send_raw_tx", handle_message<SendRawTx>},
116 {u8"send_raw_tx_hex", handle_message<SendRawTxHex>},
117 {u8"set_log_level", handle_message<SetLogLevel>},
118 {u8"start_mining", handle_message<StartMining>},
119 {u8"stop_mining", handle_message<StopMining>}
120 };
121 } // anonymous
122
123 DaemonHandler::DaemonHandler(cryptonote::core& c, t_p2p& p2p, bool restricted)
124 : m_core(c), m_p2p(p2p), m_restricted(restricted)
125 {
126 const auto last_sorted = std::is_sorted_until(std::begin(handlers), std::end(handlers));
127 if (last_sorted != std::end(handlers))
128 throw std::logic_error{std::string{"ZMQ JSON-RPC handlers map is not properly sorted, see "} + last_sorted->method_name};
129
130 check_blocked_methods_sorted();
131 }
132
133 void DaemonHandler::handle(const GetHeight::Request& req, GetHeight::Response& res)
134 {
135 res.height = m_core.get_current_blockchain_height();
136
137 res.status = Message::STATUS_OK;
138 }
139
140 void DaemonHandler::handle(const GetBlocksFast::Request& req, GetBlocksFast::Response& res)
141 {
142 std::vector<std::pair<std::pair<blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, blobdata> > > > blocks;
143
144 if(!m_core.find_blockchain_supplement(req.start_height, req.block_ids, blocks, res.current_height, res.start_height, req.prune, true, COMMAND_RPC_GET_BLOCKS_FAST_MAX_BLOCK_COUNT, COMMAND_RPC_GET_BLOCKS_FAST_MAX_TX_COUNT))
145 {
146 res.status = Message::STATUS_FAILED;
147 res.error_details = "core::find_blockchain_supplement() returned false";
148 return;
149 }
150
151 res.blocks.resize(blocks.size());
152 res.output_indices.resize(blocks.size());
153
154 auto it = blocks.begin();
155
156 uint64_t block_count = 0;
157 while (it != blocks.end())
158 {
159 cryptonote::rpc::block_with_transactions& bwt = res.blocks[block_count];
160
161 if (!parse_and_validate_block_from_blob(it->first.first, bwt.block))
162 {
163 res.blocks.clear();
164 res.output_indices.clear();
165 res.status = Message::STATUS_FAILED;
166 res.error_details = "failed retrieving a requested block";
167 return;
168 }
169
170 if (it->second.size() != bwt.block.tx_hashes.size())
171 {
172 res.blocks.clear();
173 res.output_indices.clear();
174 res.status = Message::STATUS_FAILED;
175 res.error_details = "incorrect number of transactions retrieved for block";
176 return;
177 }
178
179 cryptonote::rpc::block_output_indices& indices = res.output_indices[block_count];
180
181 // miner tx output indices
182 {
183 cryptonote::rpc::tx_output_indices tx_indices;
184 if (!m_core.get_tx_outputs_gindexs(get_transaction_hash(bwt.block.miner_tx), tx_indices))
185 {
186 res.status = Message::STATUS_FAILED;
187 res.error_details = "core::get_tx_outputs_gindexs() returned false";
188 return;
189 }
190 indices.push_back(std::move(tx_indices));
191 }
192
193 auto hash_it = bwt.block.tx_hashes.begin();
194 bwt.transactions.reserve(it->second.size());
195 for (const auto& blob : it->second)
196 {
197 bwt.transactions.emplace_back();
198 bwt.transactions.back().pruned = req.prune;
199
200 const bool parsed = req.prune ?
201 parse_and_validate_tx_base_from_blob(blob.second, bwt.transactions.back()) :
202 parse_and_validate_tx_from_blob(blob.second, bwt.transactions.back());
203 if (!parsed)
204 {
205 res.blocks.clear();
206 res.output_indices.clear();
207 res.status = Message::STATUS_FAILED;
208 res.error_details = "failed retrieving a requested transaction";
209 return;
210 }
211
212 cryptonote::rpc::tx_output_indices tx_indices;
213 if (!m_core.get_tx_outputs_gindexs(*hash_it, tx_indices))
214 {
215 res.status = Message::STATUS_FAILED;
216 res.error_details = "core::get_tx_outputs_gindexs() returned false";
217 return;
218 }
219
220 indices.push_back(std::move(tx_indices));
221 ++hash_it;
222 }
223
224 it++;
225 block_count++;
226 }
227
228 res.status = Message::STATUS_OK;
229 }
230
231 void DaemonHandler::handle(const GetHashesFast::Request& req, GetHashesFast::Response& res)
232 {
233 res.start_height = req.start_height;
234
235 auto& chain = m_core.get_blockchain_storage();
236
237 if (!chain.find_blockchain_supplement(req.known_hashes, res.hashes, NULL, res.start_height, res.current_height, false))
238 {
239 res.status = Message::STATUS_FAILED;
240 res.error_details = "Blockchain::find_blockchain_supplement() returned false";
241 return;
242 }
243
244 res.status = Message::STATUS_OK;
245 }
246
247 void DaemonHandler::handle(const GetTransactions::Request& req, GetTransactions::Response& res)
248 {
249 if (m_restricted && req.tx_hashes.size() > restricted_max_txs)
250 {
251 res.status = Message::STATUS_FAILED;
252 res.error_details = "Too many transactions requested in restricted mode";
253 return;
254 }
255
256 std::vector<cryptonote::transaction> found_txs_vec;
257 std::vector<crypto::hash> missed_vec;
258
259 bool r = m_core.get_transactions(req.tx_hashes, found_txs_vec, missed_vec);
260
261 // TODO: consider fixing core::get_transactions to not hide exceptions
262 if (!r)
263 {
264 res.status = Message::STATUS_FAILED;
265 res.error_details = "core::get_transactions() returned false (exception caught there)";
266 return;
267 }
268
269 size_t num_found = found_txs_vec.size();
270
271 std::vector<uint64_t> heights(num_found);
272 std::vector<bool> in_pool(num_found, false);
273 std::vector<crypto::hash> found_hashes(num_found);
274
275 for (size_t i=0; i < num_found; i++)
276 {
277 found_hashes[i] = get_transaction_hash(found_txs_vec[i]);
278 heights[i] = m_core.get_blockchain_storage().get_db().get_tx_block_height(found_hashes[i]);
279 }
280
281 // if any missing from blockchain, check in tx pool
282 if (!missed_vec.empty())
283 {
284 std::vector<cryptonote::transaction> pool_txs;
285
286 m_core.get_pool_transactions(pool_txs);
287
288 for (const auto& tx : pool_txs)
289 {
290 crypto::hash h = get_transaction_hash(tx);
291
292 auto itr = std::find(missed_vec.begin(), missed_vec.end(), h);
293
294 if (itr != missed_vec.end())
295 {
296 found_hashes.push_back(h);
297 found_txs_vec.push_back(tx);
298 heights.push_back(std::numeric_limits<uint64_t>::max());
299 in_pool.push_back(true);
300 missed_vec.erase(itr);
301 }
302 }
303 }
304
305 for (size_t i=0; i < found_hashes.size(); i++)
306 {
307 cryptonote::rpc::transaction_info info;
308 info.height = heights[i];
309 info.in_pool = in_pool[i];
310 info.transaction = std::move(found_txs_vec[i]);
311
312 res.txs.emplace(found_hashes[i], std::move(info));
313 }
314
315 res.missed_hashes = std::move(missed_vec);
316 res.status = Message::STATUS_OK;
317 }
318
319 void DaemonHandler::handle(const KeyImagesSpent::Request& req, KeyImagesSpent::Response& res)
320 {
321 if (m_restricted && req.key_images.size() > restricted_max_key_images)
322 {
323 res.status = Message::STATUS_FAILED;
324 res.error_details = "Too many key images queried in restricted mode";
325 return;
326 }
327
328 res.spent_status.resize(req.key_images.size(), KeyImagesSpent::STATUS::UNSPENT);
329
330 std::vector<bool> chain_spent_status;
331 std::vector<bool> pool_spent_status;
332
333 m_core.are_key_images_spent(req.key_images, chain_spent_status);
334 m_core.are_key_images_spent_in_pool(req.key_images, pool_spent_status);
335
336 if ((chain_spent_status.size() != req.key_images.size()) || (pool_spent_status.size() != req.key_images.size()))
337 {
338 res.status = Message::STATUS_FAILED;
339 res.error_details = "tx_pool::have_key_images_as_spent() gave vectors of wrong size(s).";
340 return;
341 }
342
343 for(size_t i=0; i < req.key_images.size(); i++)
344 {
345 if ( chain_spent_status[i] )
346 {
347 res.spent_status[i] = KeyImagesSpent::STATUS::SPENT_IN_BLOCKCHAIN;
348 }
349 else if ( pool_spent_status[i] )
350 {
351 res.spent_status[i] = KeyImagesSpent::STATUS::SPENT_IN_POOL;
352 }
353 }
354
355 res.status = Message::STATUS_OK;
356 }
357
358 void DaemonHandler::handle(const GetTxGlobalOutputIndices::Request& req, GetTxGlobalOutputIndices::Response& res)
359 {
360 if (!m_core.get_tx_outputs_gindexs(req.tx_hash, res.output_indices))
361 {
362 res.status = Message::STATUS_FAILED;
363 res.error_details = "core::get_tx_outputs_gindexs() returned false";
364 return;
365 }
366
367 res.status = Message::STATUS_OK;
368
369 }
370
371 void DaemonHandler::handle(const SendRawTx::Request& req, SendRawTx::Response& res)
372 {
373 handleTxBlob(cryptonote::tx_to_blob(req.tx), req.relay, res);
374 }
375
376 void DaemonHandler::handle(const SendRawTxHex::Request& req, SendRawTxHex::Response& res)
377 {
378 std::string tx_blob;
379 if(!epee::string_tools::parse_hexstr_to_binbuff(req.tx_as_hex, tx_blob))
380 {
381 MERROR("[SendRawTxHex]: Failed to parse tx from hexbuff: " << req.tx_as_hex);
382 res.status = Message::STATUS_FAILED;
383 res.error_details = "Invalid hex";
384 return;
385 }
386 handleTxBlob(std::move(tx_blob), req.relay, res);
387 }
388
389 void DaemonHandler::handleTxBlob(std::string&& tx_blob, bool relay, SendRawTx::Response& res)
390 {
391 if (!m_p2p.get_payload_object().is_synchronized())
392 {
393 res.status = Message::STATUS_FAILED;
394 res.error_details = "Not ready to accept transactions; try again later";
395 return;
396 }
397
398 tx_verification_context tvc = AUTO_VAL_INIT(tvc);
399
400 if(!m_core.handle_incoming_tx(tx_blob, tvc, (relay ? relay_method::local : relay_method::none), false) || tvc.m_verifivation_failed)
401 {
402 if (tvc.m_verifivation_failed)
403 {
404 MERROR("[SendRawTx]: tx verification failed");
405 }
406 else
407 {
408 MERROR("[SendRawTx]: Failed to process tx");
409 }
410 res.status = Message::STATUS_FAILED;
411 res.error_details = "";
412
413 if (tvc.m_low_mixin)
414 {
415 res.error_details = "mixin too low";
416 }
417 if (tvc.m_double_spend)
418 {
419 if (!res.error_details.empty()) res.error_details += " and ";
420 res.error_details += "double spend";
421 }
422 if (tvc.m_invalid_input)
423 {
424 if (!res.error_details.empty()) res.error_details += " and ";
425 res.error_details += "invalid input";
426 }
427 if (tvc.m_invalid_output)
428 {
429 if (!res.error_details.empty()) res.error_details += " and ";
430 res.error_details += "invalid output";
431 }
432 if (tvc.m_too_big)
433 {
434 if (!res.error_details.empty()) res.error_details += " and ";
435 res.error_details += "too big";
436 }
437 if (tvc.m_overspend)
438 {
439 if (!res.error_details.empty()) res.error_details += " and ";
440 res.error_details += "overspend";
441 }
442 if (tvc.m_fee_too_low)
443 {
444 if (!res.error_details.empty()) res.error_details += " and ";
445 res.error_details += "fee too low";
446 }
447 if (tvc.m_too_few_outputs)
448 {
449 if (!res.error_details.empty()) res.error_details += " and ";
450 res.error_details += "too few outputs";
451 }
452 if (tvc.m_tx_extra_too_big)
453 {
454 if (!res.error_details.empty()) res.error_details += " and ";
455 res.error_details += "tx_extra too long";
456 }
457 if (tvc.m_nonzero_unlock_time)
458 {
459 if (!res.error_details.empty()) res.error_details += " and ";
460 res.error_details += "non-zero unlock time";
461 }
462 if (res.error_details.empty())
463 {
464 res.error_details = "an unknown issue was found with the transaction";
465 }
466
467 return;
468 }
469
470 if(tvc.m_relay == relay_method::none || !relay)
471 {
472 MERROR("[SendRawTx]: tx accepted, but not relayed");
473 res.error_details = "Not relayed";
474 res.relayed = false;
475 res.status = Message::STATUS_OK;
476
477 return;
478 }
479
480 NOTIFY_NEW_TRANSACTIONS::request r;
481 r.txs.push_back(std::move(tx_blob));
482 m_core.get_protocol()->relay_transactions(r, boost::uuids::nil_uuid(), epee::net_utils::zone::invalid, relay_method::local);
483
484 //TODO: make sure that tx has reached other nodes here, probably wait to receive reflections from other nodes
485 res.status = Message::STATUS_OK;
486 res.relayed = true;
487
488 return;
489 }
490
491 void DaemonHandler::handle(const StartMining::Request& req, StartMining::Response& res)
492 {
493 cryptonote::address_parse_info info;
494 if(!get_account_address_from_str(info, m_core.get_nettype(), req.miner_address))
495 {
496 res.error_details = "Failed, wrong address";
497 LOG_PRINT_L0(res.error_details);
498 res.status = Message::STATUS_FAILED;
499 return;
500 }
501 if (info.is_subaddress)
502 {
503 res.error_details = "Failed, mining to subaddress isn't supported yet";
504 LOG_PRINT_L0(res.error_details);
505 res.status = Message::STATUS_FAILED;
506 return;
507 }
508
509 unsigned int concurrency_count = boost::thread::hardware_concurrency() * 4;
510
511 // if we couldn't detect threads, set it to a ridiculously high number
512 if(concurrency_count == 0)
513 {
514 concurrency_count = 257;
515 }
516
517 // if there are more threads requested than the hardware supports
518 // then we fail and log that.
519 if(req.threads_count > concurrency_count)
520 {
521 res.error_details = "Failed, too many threads relative to CPU cores.";
522 LOG_PRINT_L0(res.error_details);
523 res.status = Message::STATUS_FAILED;
524 return;
525 }
526
527 if(!m_core.get_miner().start(info.address, static_cast<size_t>(req.threads_count), req.do_background_mining, req.ignore_battery))
528 {
529 res.error_details = "Failed, mining not started";
530 LOG_PRINT_L0(res.error_details);
531 res.status = Message::STATUS_FAILED;
532 return;
533 }
534 res.status = Message::STATUS_OK;
535 res.error_details = "";
536
537 }
538
539 void DaemonHandler::handle(const GetInfo::Request& req, GetInfo::Response& res)
540 {
541 res.info.height = m_core.get_current_blockchain_height();
542
543 res.info.target_height = m_core.get_target_blockchain_height();
544
545 if (res.info.height > res.info.target_height)
546 {
547 res.info.target_height = res.info.height;
548 }
549
550 m_core.get_blockchain_top(res.info.top_block_height, res.info.top_block_hash);
551
552 auto& chain = m_core.get_blockchain_storage();
553
554 res.info.wide_difficulty = chain.get_difficulty_for_next_block();
555 res.info.difficulty = (res.info.wide_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
556
557 res.info.target = chain.get_difficulty_target();
558
559 res.info.tx_count = chain.get_total_transactions() - res.info.height; //without coinbase
560
561 res.info.tx_pool_size = m_core.get_pool_transactions_count(!m_restricted);
562
563 res.info.alt_blocks_count = m_restricted ? 0 : chain.get_alternative_blocks_count();
564
565 uint64_t total_conn = m_restricted ? 0 : m_p2p.get_public_connections_count();
566 res.info.outgoing_connections_count = m_restricted ? 0 : m_p2p.get_public_outgoing_connections_count();
567 res.info.incoming_connections_count = m_restricted ? 0 : total_conn - res.info.outgoing_connections_count;
568
569 res.info.white_peerlist_size = m_restricted ? 0 : m_p2p.get_public_white_peers_count();
570
571 res.info.grey_peerlist_size = m_restricted ? 0 : m_p2p.get_public_gray_peers_count();
572
573 res.info.mainnet = m_core.get_nettype() == MAINNET;
574 res.info.testnet = m_core.get_nettype() == TESTNET;
575 res.info.stagenet = m_core.get_nettype() == STAGENET;
576 res.info.wide_cumulative_difficulty = m_core.get_blockchain_storage().get_db().get_block_cumulative_difficulty(res.info.height - 1);
577 res.info.cumulative_difficulty = (res.info.wide_cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
578 res.info.block_size_limit = res.info.block_weight_limit = m_core.get_blockchain_storage().get_current_cumulative_block_weight_limit();
579 res.info.block_size_median = res.info.block_weight_median = m_core.get_blockchain_storage().get_current_cumulative_block_weight_median();
580 res.info.adjusted_time = m_core.get_blockchain_storage().get_adjusted_time(res.info.height);
581 res.info.start_time = m_restricted ? 0 : (uint64_t)m_core.get_start_time();
582 res.info.version = m_restricted ? "" : MONERO_VERSION;
583
584 res.status = Message::STATUS_OK;
585 res.error_details = "";
586 }
587
588 void DaemonHandler::handle(const StopMining::Request& req, StopMining::Response& res)
589 {
590 if(!m_core.get_miner().stop())
591 {
592 res.error_details = "Failed, mining not stopped";
593 LOG_PRINT_L0(res.error_details);
594 res.status = Message::STATUS_FAILED;
595 return;
596 }
597
598 res.status = Message::STATUS_OK;
599 res.error_details = "";
600 }
601
602 void DaemonHandler::handle(const MiningStatus::Request& req, MiningStatus::Response& res)
603 {
604 const cryptonote::miner& lMiner = m_core.get_miner();
605 res.active = lMiner.is_mining();
606 res.is_background_mining_enabled = lMiner.get_is_background_mining_enabled();
607
608 if ( lMiner.is_mining() ) {
609 res.speed = lMiner.get_speed();
610 res.threads_count = lMiner.get_threads_count();
611 const account_public_address& lMiningAdr = lMiner.get_mining_address();
612 res.address = get_account_address_as_str(m_core.get_nettype(), false, lMiningAdr);
613 }
614
615 res.status = Message::STATUS_OK;
616 res.error_details = "";
617 }
618
619 void DaemonHandler::handle(const SaveBC::Request& req, SaveBC::Response& res)
620 {
621 if (!m_core.get_blockchain_storage().store_blockchain())
622 {
623 res.status = Message::STATUS_FAILED;
624 res.error_details = "Error storing the blockchain";
625 }
626 else
627 {
628 res.status = Message::STATUS_OK;
629 }
630 }
631
632 void DaemonHandler::handle(const GetBlockHash::Request& req, GetBlockHash::Response& res)
633 {
634 if (m_core.get_current_blockchain_height() <= req.height)
635 {
636 res.hash = crypto::null_hash;
637 res.status = Message::STATUS_FAILED;
638 res.error_details = "height given is higher than current chain height";
639 return;
640 }
641
642 res.hash = m_core.get_block_id_by_height(req.height);
643
644 res.status = Message::STATUS_OK;
645 }
646
647 void DaemonHandler::handle(const GetBlockTemplate::Request& req, GetBlockTemplate::Response& res)
648 {
649 res.status = Message::STATUS_FAILED;
650 res.error_details = "RPC method not yet implemented.";
651 }
652
653 void DaemonHandler::handle(const SubmitBlock::Request& req, SubmitBlock::Response& res)
654 {
655 res.status = Message::STATUS_FAILED;
656 res.error_details = "RPC method not yet implemented.";
657 }
658
659 void DaemonHandler::handle(const GetLastBlockHeader::Request& req, GetLastBlockHeader::Response& res)
660 {
661 const crypto::hash block_hash = m_core.get_tail_id();
662
663 if (!getBlockHeaderByHash(block_hash, res.header))
664 {
665 res.status = Message::STATUS_FAILED;
666 res.error_details = "Requested block does not exist";
667 return;
668 }
669
670 res.status = Message::STATUS_OK;
671 }
672
673 void DaemonHandler::handle(const GetBlockHeaderByHash::Request& req, GetBlockHeaderByHash::Response& res)
674 {
675 if (!getBlockHeaderByHash(req.hash, res.header))
676 {
677 res.status = Message::STATUS_FAILED;
678 res.error_details = "Requested block does not exist";
679 return;
680 }
681
682 res.status = Message::STATUS_OK;
683 }
684
685 void DaemonHandler::handle(const GetBlockHeaderByHeight::Request& req, GetBlockHeaderByHeight::Response& res)
686 {
687 const crypto::hash block_hash = m_core.get_block_id_by_height(req.height);
688
689 if (!getBlockHeaderByHash(block_hash, res.header))
690 {
691 res.status = Message::STATUS_FAILED;
692 res.error_details = "Requested block does not exist";
693 return;
694 }
695
696 res.status = Message::STATUS_OK;
697 }
698
699 void DaemonHandler::handle(const GetBlockHeadersByHeight::Request& req, GetBlockHeadersByHeight::Response& res)
700 {
701 if (m_restricted && req.heights.size() > restricted_max_block_headers)
702 {
703 res.status = Message::STATUS_FAILED;
704 res.error_details = "Too many block headers requested in restricted mode";
705 return;
706 }
707
708 res.headers.resize(req.heights.size());
709
710 for (size_t i=0; i < req.heights.size(); i++)
711 {
712 const crypto::hash block_hash = m_core.get_block_id_by_height(req.heights[i]);
713
714 if (!getBlockHeaderByHash(block_hash, res.headers[i]))
715 {
716 res.status = Message::STATUS_FAILED;
717 res.error_details = "A requested block does not exist";
718 return;
719 }
720 }
721
722 res.status = Message::STATUS_OK;
723 }
724
725 void DaemonHandler::handle(const GetBlock::Request& req, GetBlock::Response& res)
726 {
727 res.status = Message::STATUS_FAILED;
728 res.error_details = "RPC method not yet implemented.";
729 }
730
731 void DaemonHandler::handle(const GetPeerList::Request& req, GetPeerList::Response& res)
732 {
733 res.status = Message::STATUS_FAILED;
734 res.error_details = "RPC method not yet implemented.";
735 }
736
737 void DaemonHandler::handle(const SetLogHashRate::Request& req, SetLogHashRate::Response& res)
738 {
739 res.status = Message::STATUS_FAILED;
740 res.error_details = "RPC method not yet implemented.";
741 }
742
743 void DaemonHandler::handle(const SetLogLevel::Request& req, SetLogLevel::Response& res)
744 {
745 if (req.level < 0 || req.level > 4)
746 {
747 res.status = Message::STATUS_FAILED;
748 res.error_details = "Error: log level not valid";
749 }
750 else
751 {
752 res.status = Message::STATUS_OK;
753 mlog_set_log_level(req.level);
754 }
755 }
756
757 void DaemonHandler::handle(const GetTransactionPool::Request& req, GetTransactionPool::Response& res)
758 {
759 bool r = m_core.get_pool_for_rpc(res.transactions, res.key_images);
760
761 if (!r) res.status = Message::STATUS_FAILED;
762 else res.status = Message::STATUS_OK;
763 }
764
765 void DaemonHandler::handle(const GetConnections::Request& req, GetConnections::Response& res)
766 {
767 res.status = Message::STATUS_FAILED;
768 res.error_details = "RPC method not yet implemented.";
769 }
770
771 void DaemonHandler::handle(const GetBlockHeadersRange::Request& req, GetBlockHeadersRange::Response& res)
772 {
773 res.status = Message::STATUS_FAILED;
774 res.error_details = "RPC method not yet implemented.";
775 }
776
777 void DaemonHandler::handle(const StopDaemon::Request& req, StopDaemon::Response& res)
778 {
779 res.status = Message::STATUS_FAILED;
780 res.error_details = "RPC method not yet implemented.";
781 }
782
783 void DaemonHandler::handle(const StartSaveGraph::Request& req, StartSaveGraph::Response& res)
784 {
785 res.status = Message::STATUS_FAILED;
786 res.error_details = "RPC method not yet implemented.";
787 }
788
789 void DaemonHandler::handle(const StopSaveGraph::Request& req, StopSaveGraph::Response& res)
790 {
791 res.status = Message::STATUS_FAILED;
792 res.error_details = "RPC method not yet implemented.";
793 }
794
795 void DaemonHandler::handle(const HardForkInfo::Request& req, HardForkInfo::Response& res)
796 {
797 const Blockchain &blockchain = m_core.get_blockchain_storage();
798 uint8_t version = req.version > 0 ? req.version : blockchain.get_ideal_hard_fork_version();
799 res.info.version = blockchain.get_current_hard_fork_version();
800 res.info.enabled = blockchain.get_hard_fork_voting_info(version, res.info.window, res.info.votes, res.info.threshold, res.info.earliest_height, res.info.voting);
801 res.info.state = blockchain.get_hard_fork_state();
802 res.status = Message::STATUS_OK;
803 }
804
805 void DaemonHandler::handle(const GetBans::Request& req, GetBans::Response& res)
806 {
807 res.status = Message::STATUS_FAILED;
808 res.error_details = "RPC method not yet implemented.";
809 }
810
811 void DaemonHandler::handle(const SetBans::Request& req, SetBans::Response& res)
812 {
813 res.status = Message::STATUS_FAILED;
814 res.error_details = "RPC method not yet implemented.";
815 }
816
817 void DaemonHandler::handle(const FlushTransactionPool::Request& req, FlushTransactionPool::Response& res)
818 {
819 res.status = Message::STATUS_FAILED;
820 res.error_details = "RPC method not yet implemented.";
821 }
822
823 void DaemonHandler::handle(const GetOutputHistogram::Request& req, GetOutputHistogram::Response& res)
824 {
825 size_t amounts = req.amounts.size();
826 if (m_restricted && amounts == 0)
827 {
828 res.status = Message::STATUS_FAILED;
829 res.error_details = "Restricted RPC will not serve histograms on the whole blockchain. Use your own node.";
830 return;
831 }
832
833 using clock = std::chrono::system_clock;
834 const clock::time_point cutoff{std::chrono::seconds{req.recent_cutoff}};
835 if (m_restricted && clock::now() - cutoff > restricted_histogram_cutoff)
836 {
837 res.status = Message::STATUS_FAILED;
838 res.error_details = "Recent cutoff is too old";
839 return;
840 }
841
842 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t> > histogram;
843 try
844 {
845 histogram = m_core.get_blockchain_storage().get_output_histogram(req.amounts, req.unlocked, req.recent_cutoff);
846 }
847 catch (const std::exception &e)
848 {
849 res.status = Message::STATUS_FAILED;
850 res.error_details = e.what();
851 return;
852 }
853
854 res.histogram.clear();
855 res.histogram.reserve(histogram.size());
856 for (const auto &i: histogram)
857 {
858 if (std::get<0>(i.second) >= req.min_count && (std::get<0>(i.second) <= req.max_count || req.max_count == 0))
859 res.histogram.emplace_back(output_amount_count{i.first, std::get<0>(i.second), std::get<1>(i.second), std::get<2>(i.second)});
860 }
861
862 res.status = Message::STATUS_OK;
863 }
864
865 void DaemonHandler::handle(const GetOutputKeys::Request& req, GetOutputKeys::Response& res)
866 {
867 if (m_restricted && req.outputs.size() > restricted_max_fake_outs)
868 {
869 res.status = Message::STATUS_FAILED;
870 res.error_details = "Too many outs requested";
871 return;
872 }
873
874 try
875 {
876 for (const auto& i : req.outputs)
877 {
878 crypto::public_key key;
879 rct::key mask;
880 bool unlocked;
881 m_core.get_blockchain_storage().get_output_key_mask_unlocked(i.amount, i.index, key, mask, unlocked);
882 res.keys.emplace_back(output_key_mask_unlocked{key, mask, unlocked});
883 }
884 }
885 catch (const std::exception& e)
886 {
887 res.status = Message::STATUS_FAILED;
888 res.error_details = e.what();
889 return;
890 }
891
892 res.status = Message::STATUS_OK;
893 }
894
895 void DaemonHandler::handle(const GetRPCVersion::Request& req, GetRPCVersion::Response& res)
896 {
897 res.version = DAEMON_RPC_VERSION_ZMQ;
898 res.status = Message::STATUS_OK;
899 }
900
901 void DaemonHandler::handle(const GetFeeEstimate::Request& req, GetFeeEstimate::Response& res)
902 {
903 res.hard_fork_version = m_core.get_blockchain_storage().get_current_hard_fork_version();
904
905
906 if (res.hard_fork_version < HF_VERSION_PER_BYTE_FEE)
907 {
908 res.fees.clear();
909 res.estimated_base_fee = m_core.get_blockchain_storage().get_dynamic_base_fee_estimate(req.num_grace_blocks);
910 res.size_scale = 1024; // per KiB fee
911 res.fee_mask = 1;
912 }
913 else
914 {
915 m_core.get_blockchain_storage().get_dynamic_base_fee_estimate_2021_scaling(req.num_grace_blocks, res.fees);
916 res.estimated_base_fee = res.fees.at(0);
917
918 res.size_scale = 1; // per byte fee
919 res.fee_mask = Blockchain::get_fee_quantization_mask();
920 }
921 res.status = Message::STATUS_OK;
922 }
923
924 void DaemonHandler::handle(const GetOutputDistribution::Request& req, GetOutputDistribution::Response& res)
925 {
926 try
927 {
928 if (m_restricted && req.amounts != std::vector<uint64_t>(1, 0))
929 {
930 res.distributions.clear();
931 res.status = Message::STATUS_FAILED;
932 res.error_details = "Restricted RPC can only get output distribution for rct outputs. Use your own node.";
933 return;
934 }
935 res.distributions.reserve(req.amounts.size());
936
937 const uint64_t req_to_height = req.to_height ? req.to_height : (m_core.get_current_blockchain_height() - 1);
938 for (std::uint64_t amount : req.amounts)
939 {
940 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());
941 if (!data)
942 {
943 res.distributions.clear();
944 res.status = Message::STATUS_FAILED;
945 res.error_details = "Failed to get output distribution";
946 return;
947 }
948 res.distributions.push_back(output_distribution{std::move(*data), amount, req.cumulative});
949 }
950 res.status = Message::STATUS_OK;
951 }
952 catch (const std::exception& e)
953 {
954 res.distributions.clear();
955 res.status = Message::STATUS_FAILED;
956 res.error_details = e.what();
957 }
958 }
959
960 bool DaemonHandler::getBlockHeaderByHash(const crypto::hash& hash_in, cryptonote::rpc::BlockHeaderResponse& header)
961 {
962 block b;
963
964 if (!m_core.get_block_by_hash(hash_in, b))
965 {
966 return false;
967 }
968
969 header.hash = hash_in;
970 if (b.miner_tx.vin.size() != 1 || b.miner_tx.vin.front().type() != typeid(txin_gen))
971 {
972 return false;
973 }
974 header.height = boost::get<txin_gen>(b.miner_tx.vin.front()).height;
975
976 header.major_version = b.major_version;
977 header.minor_version = b.minor_version;
978 header.timestamp = b.timestamp;
979 header.nonce = b.nonce;
980 header.prev_id = b.prev_id;
981
982 header.depth = m_core.get_current_blockchain_height() - header.height - 1;
983
984 header.reward = 0;
985 for (const auto& out : b.miner_tx.vout)
986 {
987 header.reward += out.amount;
988 }
989
990 header.wide_difficulty = m_core.get_blockchain_storage().block_difficulty(header.height);
991 header.difficulty = (header.wide_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
992
993 return true;
994 }
995
996 epee::byte_slice DaemonHandler::handle(std::string&& request)
997 {
998 if (m_restricted)
999 MDEBUG("Handling RPC request");
1000 else
1001 MDEBUG("Handling RPC request: " << request);
1002
1003 try
1004 {
1005 FullMessage req_full(std::move(request), true);
1006
1007 const std::string request_type = req_full.getRequestType();
1008 if (m_restricted && is_blocked_in_restricted_mode(request_type))
1009 {
1010 Message fail;
1011 fail.status = Message::STATUS_FAILED;
1012 fail.error_details = "\"" + request_type + "\" is not available in restricted mode.";
1013 return FullMessage::getResponse(fail, req_full.getID());
1014 }
1015
1016 const auto matched_handler = std::lower_bound(std::begin(handlers), std::end(handlers), request_type);
1017 if (matched_handler == std::end(handlers) || matched_handler->method_name != request_type)
1018 return BAD_REQUEST(request_type, req_full.getID());
1019
1020 epee::byte_slice response = matched_handler->call(*this, req_full.getID(), req_full.getMessage());
1021
1022 const boost::string_ref response_view{reinterpret_cast<const char*>(response.data()), response.size()};
1023 MDEBUG("Returning RPC response: " << response_view);
1024
1025 return response;
1026 }
1027 catch (const std::exception& e)
1028 {
1029 return BAD_JSON(e.what());
1030 }
1031 }
1032
1033 } // namespace rpc
1034
1035 } // namespace cryptonote