Debian Codegraph @

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