From 2899379791b7542e4eb920b5d9d58cf232806937 Mon Sep 17 00:00:00 2001 From: moneromooo-monero Date: Sun, 11 Feb 2018 15:15:56 +0000 Subject: daemon, wallet: new pay for RPC use system Daemons intended for public use can be set up to require payment in the form of hashes in exchange for RPC service. This enables public daemons to receive payment for their work over a large number of calls. This system behaves similarly to a pool, so payment takes the form of valid blocks every so often, yielding a large one off payment, rather than constant micropayments. This system can also be used by third parties as a "paywall" layer, where users of a service can pay for use by mining Monero to the service provider's address. An example of this for web site access is Primo, a Monero mining based website "paywall": https://github.com/selene-kovri/primo This has some advantages: - incentive to run a node providing RPC services, thereby promoting the availability of third party nodes for those who can't run their own - incentive to run your own node instead of using a third party's, thereby promoting decentralization - decentralized: payment is done between a client and server, with no third party needed - private: since the system is "pay as you go", you don't need to identify yourself to claim a long lived balance - no payment occurs on the blockchain, so there is no extra transactional load - one may mine with a beefy server, and use those credits from a phone, by reusing the client ID (at the cost of some privacy) - no barrier to entry: anyone may run a RPC node, and your expected revenue depends on how much work you do - Sybil resistant: if you run 1000 idle RPC nodes, you don't magically get more revenue - no large credit balance maintained on servers, so they have no incentive to exit scam - you can use any/many node(s), since there's little cost in switching servers - market based prices: competition between servers to lower costs - incentive for a distributed third party node system: if some public nodes are overused/slow, traffic can move to others - increases network security - helps counteract mining pools' share of the network hash rate - zero incentive for a payer to "double spend" since a reorg does not give any money back to the miner And some disadvantages: - low power clients will have difficulty mining (but one can optionally mine in advance and/or with a faster machine) - payment is "random", so a server might go a long time without a block before getting one - a public node's overall expected payment may be small Public nodes are expected to compete to find a suitable level for cost of service. The daemon can be set up this way to require payment for RPC services: monerod --rpc-payment-address 4xxxxxx \ --rpc-payment-credits 250 --rpc-payment-difficulty 1000 These values are an example only. The --rpc-payment-difficulty switch selects how hard each "share" should be, similar to a mining pool. The higher the difficulty, the fewer shares a client will find. The --rpc-payment-credits switch selects how many credits are awarded for each share a client finds. Considering both options, clients will be awarded credits/difficulty credits for every hash they calculate. For example, in the command line above, 0.25 credits per hash. A client mining at 100 H/s will therefore get an average of 25 credits per second. For reference, in the current implementation, a credit is enough to sync 20 blocks, so a 100 H/s client that's just starting to use Monero and uses this daemon will be able to sync 500 blocks per second. The wallet can be set to automatically mine if connected to a daemon which requires payment for RPC usage. It will try to keep a balance of 50000 credits, stopping mining when it's at this level, and starting again as credits are spent. With the example above, a new client will mine this much credits in about half an hour, and this target is enough to sync 500000 blocks (currently about a third of the monero blockchain). There are three new settings in the wallet: - credits-target: this is the amount of credits a wallet will try to reach before stopping mining. The default of 0 means 50000 credits. - auto-mine-for-rpc-payment-threshold: this controls the minimum credit rate which the wallet considers worth mining for. If the daemon credits less than this ratio, the wallet will consider mining to be not worth it. In the example above, the rate is 0.25 - persistent-rpc-client-id: if set, this allows the wallet to reuse a client id across runs. This means a public node can tell a wallet that's connecting is the same as one that connected previously, but allows a wallet to keep their credit balance from one run to the other. Since the wallet only mines to keep a small credit balance, this is not normally worth doing. However, someone may want to mine on a fast server, and use that credit balance on a low power device such as a phone. If left unset, a new client ID is generated at each wallet start, for privacy reasons. To mine and use a credit balance on two different devices, you can use the --rpc-client-secret-key switch. A wallet's client secret key can be found using the new rpc_payments command in the wallet. Note: anyone knowing your RPC client secret key is able to use your credit balance. The wallet has a few new commands too: - start_mining_for_rpc: start mining to acquire more credits, regardless of the auto mining settings - stop_mining_for_rpc: stop mining to acquire more credits - rpc_payments: display information about current credits with the currently selected daemon The node has an extra command: - rpc_payments: display information about clients and their balances The node will forget about any balance for clients which have been inactive for 6 months. Balances carry over on node restart. --- src/simplewallet/simplewallet.cpp | 382 +++++++++++++++++++++++++++++++++++++- 1 file changed, 375 insertions(+), 7 deletions(-) (limited to 'src/simplewallet/simplewallet.cpp') diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 6a54c24fb..d203f905d 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -58,6 +58,7 @@ #include "cryptonote_basic/cryptonote_format_utils.h" #include "storages/http_abstract_invoke.h" #include "rpc/core_rpc_server_commands_defs.h" +#include "rpc/rpc_payment_signature.h" #include "crypto/crypto.h" // for crypto::secret_key definition #include "mnemonics/electrum-words.h" #include "rapidjson/document.h" @@ -99,12 +100,17 @@ typedef cryptonote::simple_wallet sw; #define LOCK_IDLE_SCOPE() \ bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \ m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \ - /* stop any background refresh, and take over */ \ + /* stop any background refresh and other processes, and take over */ \ + m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); \ m_wallet->stop(); \ boost::unique_lock lock(m_idle_mutex); \ m_idle_cond.notify_all(); \ epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \ + /* m_idle_mutex is still locked here */ \ m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \ + m_suspend_rpc_payment_mining.store(false, std::memory_order_relaxed);; \ + m_rpc_payment_checker.trigger(); \ + m_idle_cond.notify_one(); \ }) #define SCOPED_WALLET_UNLOCK_ON_BAD_PASSWORD(code) \ @@ -125,15 +131,24 @@ typedef cryptonote::simple_wallet sw; return true; \ } while(0) +#define REFRESH_PERIOD 90 // seconds + +#define CREDITS_TARGET 50000 +#define MAX_PAYMENT_DIFF 10000 +#define MIN_PAYMENT_RATE 0.01f // per hash + enum TransferType { Transfer, TransferLocked, }; +static std::string get_human_readable_timespan(std::chrono::seconds seconds); + namespace { const std::array allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}}; const auto arg_wallet_file = wallet_args::arg_wallet_file(); + const auto arg_rpc_client_secret_key = wallet_args::arg_rpc_client_secret_key(); const command_line::arg_descriptor arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to "), ""}; const command_line::arg_descriptor arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to "), ""}; const command_line::arg_descriptor arg_generate_from_view_key = {"generate-from-view-key", sw::tr("Generate incoming-only wallet from view key"), ""}; @@ -248,6 +263,9 @@ namespace const char* USAGE_LOCK("lock"); const char* USAGE_NET_STATS("net_stats"); const char* USAGE_WELCOME("welcome"); + const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info"); + const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc"); + const char* USAGE_STOP_MINING_FOR_RPC("stop_mining_for_rpc"); const char* USAGE_VERSION("version"); const char* USAGE_HELP("help []"); @@ -490,22 +508,28 @@ namespace fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be :"); return r; } +} - void handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon) - { +void simple_wallet::handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon) +{ bool warn_of_possible_attack = !trusted_daemon; try { std::rethrow_exception(e); } - catch (const tools::error::daemon_busy&) + catch (const tools::error::payment_required&) { - fail_msg_writer() << sw::tr("daemon is busy. Please try again later."); + fail_msg_writer() << tr("Payment required, see the 'rpc_payment_info' command"); + m_need_payment = true; } catch (const tools::error::no_connection_to_daemon&) { fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running."); } + catch (const tools::error::daemon_busy&) + { + fail_msg_writer() << tr("daemon is busy. Please try again later."); + } catch (const tools::error::wallet_rpc_error& e) { LOG_ERROR("RPC error: " << e.to_string()); @@ -602,8 +626,10 @@ namespace if (warn_of_possible_attack) fail_msg_writer() << sw::tr("There was an error, which could mean the node may be trying to get you to retry creating a transaction, and zero in on which outputs you own. Or it could be a bona fide error. It may be prudent to disconnect from this node, and not try to send a transaction immediately. Alternatively, connect to another node so the original node cannot correlate information."); - } +} +namespace +{ bool check_file_overwrite(const std::string &filename) { boost::system::error_code errcode; @@ -1908,6 +1934,77 @@ bool simple_wallet::unset_ring(const std::vector &args) return true; } +bool simple_wallet::rpc_payment_info(const std::vector &args) +{ + if (!try_connect_to_daemon()) + return true; + + LOCK_IDLE_SCOPE(); + + try + { + bool payment_required; + uint64_t credits, diff, credits_per_hash_found, height, seed_height; + uint32_t cookie; + std::string hashing_blob; + crypto::hash seed_hash, next_seed_hash; + crypto::public_key pkey; + crypto::secret_key_to_public_key(m_wallet->get_rpc_client_secret_key(), pkey); + message_writer() << tr("RPC client ID: ") << pkey; + message_writer() << tr("RPC client secret key: ") << m_wallet->get_rpc_client_secret_key(); + if (!m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie)) + { + fail_msg_writer() << tr("Failed to query daemon"); + return true; + } + if (payment_required) + { + uint64_t target = m_wallet->credits_target(); + if (target == 0) + target = CREDITS_TARGET; + message_writer() << tr("Using daemon: ") << m_wallet->get_daemon_address(); + message_writer() << tr("Payments required for node use, current credits: ") << credits; + message_writer() << tr("Credits target: ") << target; + uint64_t expected, discrepancy; + m_wallet->credit_report(expected, discrepancy); + message_writer() << tr("Credits spent this session: ") << expected; + if (expected) + message_writer() << tr("Credit discrepancy this session: ") << discrepancy << " (" << 100.0f * discrepancy / expected << "%)"; + float cph = credits_per_hash_found / (float)diff; + message_writer() << tr("Difficulty: ") << diff << ", " << credits_per_hash_found << " " << tr("credits per hash found, ") << cph << " " << tr("credits/hash");; + const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); + bool mining = (now - m_last_rpc_payment_mining_time).total_microseconds() < 1000000; + if (mining) + { + float hash_rate = m_rpc_payment_hash_rate; + if (hash_rate > 0) + { + message_writer() << (boost::format(tr("Mining for payment at %.1f H/s")) % hash_rate).str(); + if (credits < target) + { + std::chrono::seconds seconds((unsigned)((target - credits) / cph / hash_rate)); + std::string target_string = get_human_readable_timespan(seconds); + message_writer() << (boost::format(tr("Estimated time till %u credits target mined: %s")) % target % target_string).str(); + } + } + else + message_writer() << tr("Mining for payment"); + } + else + message_writer() << tr("Not mining"); + } + else + message_writer() << tr("No payment needed for node use"); + } + catch (const std::exception& e) + { + LOG_ERROR("unexpected error: " << e.what()); + fail_msg_writer() << tr("unexpected error: ") << e.what(); + } + + return true; +} + bool simple_wallet::blackball(const std::vector &args) { uint64_t amount = std::numeric_limits::max(), offset, num_offsets; @@ -2214,6 +2311,50 @@ bool simple_wallet::cold_sign_tx(const std::vector& return m_wallet->import_key_images(exported_txs, 0, true); } +bool simple_wallet::start_mining_for_rpc(const std::vector &args) +{ + if (!try_connect_to_daemon()) + return true; + + LOCK_IDLE_SCOPE(); + + bool payment_required; + uint64_t credits, diff, credits_per_hash_found, height, seed_height; + uint32_t cookie; + std::string hashing_blob; + crypto::hash seed_hash, next_seed_hash; + if (!m_wallet->get_rpc_payment_info(true, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie)) + { + fail_msg_writer() << tr("Failed to query daemon"); + return true; + } + if (!payment_required) + { + fail_msg_writer() << tr("Daemon does not require payment for RPC access"); + return true; + } + + m_rpc_payment_mining_requested = true; + m_rpc_payment_checker.trigger(); + const float cph = credits_per_hash_found / (float)diff; + bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE); + success_msg_writer() << (boost::format(tr("Starting mining for RPC access: diff %llu, %f credits/hash%s")) % diff % cph % (low ? " - this is low" : "")).str(); + success_msg_writer() << tr("Run stop_mining_for_rpc to stop"); + return true; +} + +bool simple_wallet::stop_mining_for_rpc(const std::vector &args) +{ + if (!try_connect_to_daemon()) + return true; + + LOCK_IDLE_SCOPE(); + m_rpc_payment_mining_requested = false; + m_last_rpc_payment_mining_time = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)); + m_rpc_payment_hash_rate = -1.0f; + return true; +} + bool simple_wallet::set_always_confirm_transfers(const std::vector &args/* = std::vector()*/) { const auto pwd_container = get_and_verify_password(); @@ -2602,6 +2743,53 @@ bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector &args/* = std::vector()*/) +{ + const auto pwd_container = get_and_verify_password(); + if (pwd_container) + { + parse_bool_and_use(args[1], [&](bool r) { + m_wallet->persistent_rpc_client_id(r); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); + }); + } + return true; +} + +bool simple_wallet::set_auto_mine_for_rpc_payment_threshold(const std::vector &args/* = std::vector()*/) +{ + const auto pwd_container = get_and_verify_password(); + if (pwd_container) + { + float threshold; + if (!epee::string_tools::get_xtype_from_string(threshold, args[1]) || threshold < 0.0f) + { + fail_msg_writer() << tr("Invalid threshold"); + return true; + } + m_wallet->auto_mine_for_rpc_payment_threshold(threshold); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); + } + return true; +} + +bool simple_wallet::set_credits_target(const std::vector &args/* = std::vector()*/) +{ + const auto pwd_container = get_and_verify_password(); + if (pwd_container) + { + uint64_t target; + if (!epee::string_tools::get_xtype_from_string(target, args[1])) + { + fail_msg_writer() << tr("Invalid target"); + return true; + } + m_wallet->credits_target(target); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); + } + return true; +} + bool simple_wallet::set_key_reuse_mitigation2(const std::vector &args/* = std::vector()*/) { const auto pwd_container = get_and_verify_password(); @@ -2844,6 +3032,12 @@ simple_wallet::simple_wallet() , m_last_activity_time(time(NULL)) , m_locked(false) , m_in_command(false) + , m_need_payment(false) + , m_rpc_payment_mining_requested(false) + , m_last_rpc_payment_mining_time(boost::gregorian::date(1970, 1, 1)) + , m_daemon_rpc_payment_message_displayed(false) + , m_rpc_payment_hash_rate(-1.0f) + , m_suspend_rpc_payment_mining(false) { m_cmd_binder.set_handler("start_mining", boost::bind(&simple_wallet::on_command, this, &simple_wallet::start_mining, _1), @@ -3022,7 +3216,13 @@ simple_wallet::simple_wallet() "device-name \n " " Device name for hardware wallet.\n " "export-format <\"binary\"|\"ascii\">\n " - " Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n ")); + " Save all exported files as binary (cannot be copied and pasted) or ascii (can be).\n " + "persistent-client-id <1|0>\n " + " Whether to keep using the same client id for RPC payment over wallet restarts.\n" + "auto-mine-for-rpc-payment-threshold \n " + " Whether to automatically start mining for RPC payment if the daemon requires it.\n" + "credits-target \n" + " The RPC payment credits balance to target (0 for default).")); m_cmd_binder.set_handler("encrypted_seed", boost::bind(&simple_wallet::on_command, this, &simple_wallet::encrypted_seed, _1), tr("Display the encrypted Electrum-style mnemonic seed.")); @@ -3333,6 +3533,18 @@ simple_wallet::simple_wallet() boost::bind(&simple_wallet::on_command, this, &simple_wallet::version, _1), tr(USAGE_VERSION), tr("Returns version information")); + m_cmd_binder.set_handler("rpc_payment_info", + boost::bind(&simple_wallet::rpc_payment_info, this, _1), + tr(USAGE_RPC_PAYMENT_INFO), + tr("Get info about RPC payments to current node")); + m_cmd_binder.set_handler("start_mining_for_rpc", + boost::bind(&simple_wallet::start_mining_for_rpc, this, _1), + tr(USAGE_START_MINING_FOR_RPC), + tr("Start mining to pay for RPC access")); + m_cmd_binder.set_handler("stop_mining_for_rpc", + boost::bind(&simple_wallet::stop_mining_for_rpc, this, _1), + tr(USAGE_STOP_MINING_FOR_RPC), + tr("Stop mining to pay for RPC access")); m_cmd_binder.set_handler("help", boost::bind(&simple_wallet::on_command, this, &simple_wallet::help, _1), tr(USAGE_HELP), @@ -3402,6 +3614,9 @@ bool simple_wallet::set_variable(const std::vector &args) << " (disabled on Windows)" #endif ; + success_msg_writer() << "persistent-rpc-client-id = " << m_wallet->persistent_rpc_client_id(); + success_msg_writer() << "auto-mine-for-rpc-payment-threshold = " << m_wallet->auto_mine_for_rpc_payment_threshold(); + success_msg_writer() << "credits-target = " << m_wallet->credits_target(); return true; } else @@ -3463,6 +3678,9 @@ bool simple_wallet::set_variable(const std::vector &args) CHECK_SIMPLE_VARIABLE("setup-background-mining", set_setup_background_mining, tr("1/yes or 0/no")); CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("")); CHECK_SIMPLE_VARIABLE("export-format", set_export_format, tr("\"binary\" or \"ascii\"")); + CHECK_SIMPLE_VARIABLE("persistent-rpc-client-id", set_persistent_rpc_client_id, tr("0 or 1")); + CHECK_SIMPLE_VARIABLE("auto-mine-for-rpc-payment-threshold", set_auto_mine_for_rpc_payment_threshold, tr("floating point >= 0")); + CHECK_SIMPLE_VARIABLE("credits-target", set_credits_target, tr("unsigned integer")); } fail_msg_writer() << tr("set: unrecognized argument(s)"); return true; @@ -4227,6 +4445,17 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) return false; } + if (!command_line::is_arg_defaulted(vm, arg_rpc_client_secret_key)) + { + crypto::secret_key rpc_client_secret_key; + if (!epee::string_tools::hex_to_pod(command_line::get_arg(vm, arg_rpc_client_secret_key), rpc_client_secret_key)) + { + fail_msg_writer() << tr("RPC client secret key should be 32 byte in hex format"); + return false; + } + m_wallet->set_rpc_client_secret_key(rpc_client_secret_key); + } + if (!m_wallet->is_trusted_daemon()) { message_writer(console_color_red, true) << (boost::format(tr("Warning: using an untrusted daemon at %s")) % m_wallet->get_daemon_address()).str(); @@ -4742,6 +4971,7 @@ bool simple_wallet::close_wallet() if (m_idle_run.load(std::memory_order_relaxed)) { m_idle_run.store(false, std::memory_order_relaxed); + m_suspend_rpc_payment_mining.store(true, std::memory_order_relaxed); m_wallet->stop(); { boost::unique_lock lock(m_idle_mutex); @@ -5009,6 +5239,57 @@ bool simple_wallet::stop_mining(const std::vector& args) return true; } //---------------------------------------------------------------------------------------------------- +bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph) +{ + try + { + auto i = m_claimed_cph.find(daemon_url); + if (i == m_claimed_cph.end()) + return false; + + claimed_cph = m_claimed_cph[daemon_url]; + bool payment_required; + uint64_t credits, diff, credits_per_hash_found, height, seed_height; + uint32_t cookie; + cryptonote::blobdata hashing_blob; + crypto::hash seed_hash, next_seed_hash; + if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, seed_height, seed_hash, next_seed_hash, cookie) && payment_required) + { + actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff); + return true; + } + else + { + const std::string host = node.host + ":" + std::to_string(node.rpc_port); + if (host == daemon_url) + { + claimed_cph = node.rpc_credits_per_hash; + bool payment_required; + uint64_t credits, diff, credits_per_hash_found, height; + uint32_t cookie; + cryptonote::blobdata hashing_blob; + if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, cookie) && payment_required) + { + actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff); + return true; + } + else + { + fail_msg_writer() << tr("Error checking daemon RPC access prices"); + } + } + } + } + catch (const std::exception &e) + { + // can't check + fail_msg_writer() << tr("Error checking daemon RPC access prices: ") << e.what(); + return false; + } + // no record found for this daemon + return false; +} +//---------------------------------------------------------------------------------------------------- bool simple_wallet::set_daemon(const std::vector& args) { std::string daemon_url; @@ -5066,6 +5347,8 @@ bool simple_wallet::set_daemon(const std::vector& args) catch (const std::exception &e) { } } success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted")); + + m_daemon_rpc_payment_message_displayed = false; } else { fail_msg_writer() << tr("This does not seem to be a valid daemon URL."); } @@ -5304,6 +5587,11 @@ bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bo { ss << tr("no connection to daemon. Please make sure daemon is running."); } + catch (const tools::error::payment_required&) + { + ss << tr("payment required."); + m_need_payment = true; + } catch (const tools::error::wallet_rpc_error& e) { LOG_ERROR("RPC error: " << e.to_string()); @@ -5630,6 +5918,11 @@ bool simple_wallet::rescan_spent(const std::vector &args) { fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running."); } + catch (const tools::error::payment_required&) + { + fail_msg_writer() << tr("payment required."); + m_need_payment = true; + } catch (const tools::error::is_key_image_spent_error&) { fail_msg_writer() << tr("failed to get spent status"); @@ -5733,6 +6026,7 @@ bool simple_wallet::print_ring_members(const std::vectorget_rpc_client_secret_key()); bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res); err = interpret_rpc_response(r, res.status); if (!err.empty()) @@ -8474,6 +8768,7 @@ void simple_wallet::wallet_idle_thread() #endif m_refresh_checker.do_call(boost::bind(&simple_wallet::check_refresh, this)); m_mms_checker.do_call(boost::bind(&simple_wallet::check_mms, this)); + m_rpc_payment_checker.do_call(boost::bind(&simple_wallet::check_rpc_payment, this)); if (!m_idle_run.load(std::memory_order_relaxed)) break; @@ -8527,6 +8822,78 @@ bool simple_wallet::check_mms() return true; } //---------------------------------------------------------------------------------------------------- +bool simple_wallet::check_rpc_payment() +{ + if (!m_rpc_payment_mining_requested && m_wallet->auto_mine_for_rpc_payment_threshold() == 0.0f) + return true; + + uint64_t target = m_wallet->credits_target(); + if (target == 0) + target = CREDITS_TARGET; + if (m_rpc_payment_mining_requested) + target = std::numeric_limits::max(); + bool need_payment = m_need_payment || m_rpc_payment_mining_requested || (m_wallet->credits() < target && m_wallet->daemon_requires_payment()); + if (need_payment) + { + const boost::posix_time::ptime start_time = boost::posix_time::microsec_clock::universal_time(); + auto startfunc = [this](uint64_t diff, uint64_t credits_per_hash_found) + { + const float cph = credits_per_hash_found / (float)diff; + bool low = (diff > MAX_PAYMENT_DIFF || cph < MIN_PAYMENT_RATE); + if (credits_per_hash_found > 0 && cph >= m_wallet->auto_mine_for_rpc_payment_threshold()) + { + MINFO(std::to_string(cph) << " credits per hash is >= our threshold (" << m_wallet->auto_mine_for_rpc_payment_threshold() << "), starting mining"); + return true; + } + else if (m_rpc_payment_mining_requested) + { + MINFO("Mining for RPC payment was requested, starting mining"); + return true; + } + else + { + if (!m_daemon_rpc_payment_message_displayed) + { + success_msg_writer() << boost::format(tr("Daemon requests payment at diff %llu, with %f credits/hash%s. Run start_mining_for_rpc to start mining to pay for RPC access, or use another daemon")) % + diff % cph % (low ? " - this is low" : ""); + m_cmd_binder.print_prompt(); + m_daemon_rpc_payment_message_displayed = true; + } + return false; + } + }; + auto contfunc = [&,this](unsigned n_hashes) + { + if (m_suspend_rpc_payment_mining.load(std::memory_order_relaxed)) + return false; + const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); + m_last_rpc_payment_mining_time = now; + if ((now - start_time).total_microseconds() >= 2 * 1000000) + m_rpc_payment_hash_rate = n_hashes / (float)((now - start_time).total_seconds()); + if ((now - start_time).total_microseconds() >= REFRESH_PERIOD * 1000000) + return false; + return true; + }; + auto foundfunc = [this, target](uint64_t credits) + { + m_need_payment = false; + return credits < target; + }; + auto errorfunc = [this](const std::string &error) + { + fail_msg_writer() << tr("Error mining to daemon: ") << error; + m_cmd_binder.print_prompt(); + }; + bool ret = m_wallet->search_for_rpc_payment(target, startfunc, contfunc, foundfunc, errorfunc); + if (!ret) + { + fail_msg_writer() << tr("Failed to start mining for RPC payment"); + m_cmd_binder.print_prompt(); + } + } + return true; +} +//---------------------------------------------------------------------------------------------------- std::string simple_wallet::get_prompt() const { if (m_locked) @@ -9728,6 +10095,7 @@ int main(int argc, char* argv[]) command_line::add_arg(desc_params, arg_create_address_file); command_line::add_arg(desc_params, arg_subaddress_lookahead); command_line::add_arg(desc_params, arg_use_english_language_names); + command_line::add_arg(desc_params, arg_rpc_client_secret_key); po::positional_options_description positional_options; positional_options.add(arg_command.name, -1); -- cgit v1.2.3 From ffa46026b5360decf5343b85fb267d026f41e760 Mon Sep 17 00:00:00 2001 From: moneromooo-monero Date: Tue, 25 Jun 2019 16:50:08 +0000 Subject: simplewallet: add public_nodes command Lists nodes exposing their RPC port for public use --- src/rpc/core_rpc_server.h | 2 +- src/rpc/core_rpc_server_commands_defs.h | 6 ++- src/rpc/rpc_payment_costs.h | 1 + src/simplewallet/simplewallet.cpp | 84 +++++++++++++++++++++++++-------- src/simplewallet/simplewallet.h | 5 ++ src/wallet/wallet2.cpp | 21 +++++++++ src/wallet/wallet2.h | 2 + 7 files changed, 99 insertions(+), 22 deletions(-) (limited to 'src/simplewallet/simplewallet.cpp') diff --git a/src/rpc/core_rpc_server.h b/src/rpc/core_rpc_server.h index 1f12815b3..6655d621e 100644 --- a/src/rpc/core_rpc_server.h +++ b/src/rpc/core_rpc_server.h @@ -116,7 +116,7 @@ namespace cryptonote MAP_URI_AUTO_JON2_IF("/mining_status", on_mining_status, COMMAND_RPC_MINING_STATUS, !m_restricted) MAP_URI_AUTO_JON2_IF("/save_bc", on_save_bc, COMMAND_RPC_SAVE_BC, !m_restricted) MAP_URI_AUTO_JON2_IF("/get_peer_list", on_get_peer_list, COMMAND_RPC_GET_PEER_LIST, !m_restricted) - MAP_URI_AUTO_JON2_IF("/get_public_nodes", on_get_public_nodes, COMMAND_RPC_GET_PUBLIC_NODES, !m_restricted) + MAP_URI_AUTO_JON2("/get_public_nodes", on_get_public_nodes, COMMAND_RPC_GET_PUBLIC_NODES) MAP_URI_AUTO_JON2_IF("/set_log_hash_rate", on_set_log_hash_rate, COMMAND_RPC_SET_LOG_HASH_RATE, !m_restricted) MAP_URI_AUTO_JON2_IF("/set_log_level", on_set_log_level, COMMAND_RPC_SET_LOG_LEVEL, !m_restricted) MAP_URI_AUTO_JON2_IF("/set_log_categories", on_set_log_categories, COMMAND_RPC_SET_LOG_CATEGORIES, !m_restricted) diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index 1f8286951..89c88a835 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -1216,17 +1216,19 @@ namespace cryptonote std::string host; uint64_t last_seen; uint16_t rpc_port; + uint32_t rpc_credits_per_hash; - public_node() = delete; + public_node(): last_seen(0), rpc_port(0), rpc_credits_per_hash(0) {} public_node(const peer &peer) - : host(peer.host), last_seen(peer.last_seen), rpc_port(peer.rpc_port) + : host(peer.host), last_seen(peer.last_seen), rpc_port(peer.rpc_port), rpc_credits_per_hash(peer.rpc_credits_per_hash) {} BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(host) KV_SERIALIZE(last_seen) KV_SERIALIZE(rpc_port) + KV_SERIALIZE(rpc_credits_per_hash) END_KV_SERIALIZE_MAP() }; diff --git a/src/rpc/rpc_payment_costs.h b/src/rpc/rpc_payment_costs.h index 066557f42..3b27bf286 100644 --- a/src/rpc/rpc_payment_costs.h +++ b/src/rpc/rpc_payment_costs.h @@ -47,3 +47,4 @@ #define COST_PER_FEE_ESTIMATE 1 #define COST_PER_SYNC_INFO 2 #define COST_PER_HARD_FORK_INFO 1 +#define COST_PER_PEER_LIST 2 diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index d203f905d..5c01e99fb 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -262,6 +262,7 @@ namespace const char* USAGE_FROZEN("frozen "); const char* USAGE_LOCK("lock"); const char* USAGE_NET_STATS("net_stats"); + const char* USAGE_PUBLIC_NODES("public_nodes"); const char* USAGE_WELCOME("welcome"); const char* USAGE_RPC_PAYMENT_INFO("rpc_payment_info"); const char* USAGE_START_MINING_FOR_RPC("start_mining_for_rpc"); @@ -2247,6 +2248,45 @@ bool simple_wallet::net_stats(const std::vector &args) return true; } +bool simple_wallet::public_nodes(const std::vector &args) +{ + try + { + auto nodes = m_wallet->get_public_nodes(false); + m_claimed_cph.clear(); + if (nodes.empty()) + { + fail_msg_writer() << tr("No known public nodes"); + return true; + } + std::sort(nodes.begin(), nodes.end(), [](const public_node &node0, const public_node &node1) { + if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash == 0) + return true; + if (node0.rpc_credits_per_hash && node1.rpc_credits_per_hash) + return node0.rpc_credits_per_hash < node1.rpc_credits_per_hash; + return false; + }); + + const uint64_t now = time(NULL); + message_writer() << boost::format("%32s %12s %16s") % tr("address") % tr("credits/hash") % tr("last_seen"); + for (const auto &node: nodes) + { + const float cph = node.rpc_credits_per_hash / RPC_CREDITS_PER_HASH_SCALE; + char cphs[9]; + snprintf(cphs, sizeof(cphs), "%.3f", cph); + const std::string last_seen = node.last_seen == 0 ? tr("never") : get_human_readable_timespan(std::chrono::seconds(now - node.last_seen)); + std::string host = node.host + ":" + std::to_string(node.rpc_port); + message_writer() << boost::format("%32s %12s %16s") % host % cphs % last_seen; + m_claimed_cph[host] = node.rpc_credits_per_hash; + } + } + catch (const std::exception &e) + { + fail_msg_writer() << tr("Error retrieving public node list: ") << e.what(); + } + return true; +} + bool simple_wallet::welcome(const std::vector &args) { message_writer() << tr("Welcome to Monero, the private cryptocurrency."); @@ -3525,6 +3565,10 @@ simple_wallet::simple_wallet() boost::bind(&simple_wallet::on_command, this, &simple_wallet::net_stats, _1), tr(USAGE_NET_STATS), tr("Prints simple network stats")); + m_cmd_binder.set_handler("public_nodes", + boost::bind(&simple_wallet::public_nodes, this, _1), + tr(USAGE_PUBLIC_NODES), + tr("Lists known public nodes")); m_cmd_binder.set_handler("welcome", boost::bind(&simple_wallet::on_command, this, &simple_wallet::welcome, _1), tr(USAGE_WELCOME), @@ -5260,24 +5304,7 @@ bool simple_wallet::check_daemon_rpc_prices(const std::string &daemon_url, uint3 } else { - const std::string host = node.host + ":" + std::to_string(node.rpc_port); - if (host == daemon_url) - { - claimed_cph = node.rpc_credits_per_hash; - bool payment_required; - uint64_t credits, diff, credits_per_hash_found, height; - uint32_t cookie; - cryptonote::blobdata hashing_blob; - if (m_wallet->get_rpc_payment_info(false, payment_required, credits, diff, credits_per_hash_found, hashing_blob, height, cookie) && payment_required) - { - actual_cph = RPC_CREDITS_PER_HASH_SCALE * (credits_per_hash_found / (float)diff); - return true; - } - else - { - fail_msg_writer() << tr("Error checking daemon RPC access prices"); - } - } + fail_msg_writer() << tr("Error checking daemon RPC access prices"); } } catch (const std::exception &e) @@ -5313,7 +5340,7 @@ bool simple_wallet::set_daemon(const std::vector& args) // If no port has been provided, use the default from config if (!match[3].length()) { - int daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT; + uint16_t daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT; daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port); } else { daemon_url = args[0]; @@ -5346,8 +5373,27 @@ bool simple_wallet::set_daemon(const std::vector& args) } catch (const std::exception &e) { } } + + if (!try_connect_to_daemon()) + { + fail_msg_writer() << tr("Failed to connect to daemon"); + return true; + } + success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted")); + // check whether the daemon's prices match the claim, and disconnect if not, to disincentivize daemons lying + uint32_t actual_cph, claimed_cph; + if (check_daemon_rpc_prices(daemon_url, actual_cph, claimed_cph)) + { + if (actual_cph < claimed_cph) + { + fail_msg_writer() << tr("Daemon RPC credits/hash is less than was claimed. Either this daemon is cheating, or it changed its setup recently."); + fail_msg_writer() << tr("Claimed: ") << claimed_cph / (float)RPC_CREDITS_PER_HASH_SCALE; + fail_msg_writer() << tr("Actual: ") << actual_cph / (float)RPC_CREDITS_PER_HASH_SCALE; + } + } + m_daemon_rpc_payment_message_displayed = false; } else { fail_msg_writer() << tr("This does not seem to be a valid daemon URL."); diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index 1ce135287..e8f96ad54 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -257,6 +257,7 @@ namespace cryptonote bool start_mining_for_rpc(const std::vector &args); bool stop_mining_for_rpc(const std::vector &args); bool net_stats(const std::vector& args); + bool public_nodes(const std::vector& args); bool welcome(const std::vector& args); bool version(const std::vector& args); bool on_unknown_command(const std::vector& args); @@ -335,6 +336,8 @@ namespace cryptonote void handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon); + bool check_daemon_rpc_prices(const std::string &daemon_url, uint32_t &actual_cph, uint32_t &claimed_cph); + //----------------- i_wallet2_callback --------------------- virtual void on_new_block(uint64_t height, const cryptonote::block& block); virtual void on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index, uint64_t unlock_time); @@ -457,6 +460,8 @@ namespace cryptonote float m_rpc_payment_hash_rate; std::atomic m_suspend_rpc_payment_mining; + std::unordered_map m_claimed_cph; + // MMS mms::message_store& get_message_store() const { return m_wallet->get_message_store(); }; mms::multisig_wallet_state get_multisig_wallet_state() const { return m_wallet->get_multisig_wallet_state(); }; diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index aecd01dec..5cebc7c23 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -13549,4 +13549,25 @@ uint64_t wallet2::get_bytes_received() const { return m_http_client.get_bytes_received(); } +//---------------------------------------------------------------------------------------------------- +std::vector wallet2::get_public_nodes(bool white_only) +{ + cryptonote::COMMAND_RPC_GET_PUBLIC_NODES::request req = AUTO_VAL_INIT(req); + cryptonote::COMMAND_RPC_GET_PUBLIC_NODES::response res = AUTO_VAL_INIT(res); + + req.white = true; + req.gray = !white_only; + + { + const boost::lock_guard lock{m_daemon_rpc_mutex}; + bool r = epee::net_utils::invoke_http_json("/get_public_nodes", req, res, m_http_client, rpc_timeout); + THROW_ON_RPC_RESPONSE_ERROR_GENERIC(r, {}, res, "/get_public_nodes"); + } + + std::vector nodes; + nodes = res.white; + nodes.reserve(nodes.size() + res.gray.size()); + std::copy(res.gray.begin(), res.gray.end(), std::back_inserter(nodes)); + return nodes; +} } diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 3635cf227..640565a4e 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -886,6 +886,8 @@ private: uint64_t get_last_block_reward() const { return m_last_block_reward; } uint64_t get_device_last_key_image_sync() const { return m_device_last_key_image_sync; } + std::vector get_public_nodes(bool white_only = true); + template inline void serialize(t_archive &a, const unsigned int ver) { -- cgit v1.2.3