| 1 | // Copyright (c) 2018-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 <boost/archive/portable_binary_iarchive.hpp> |
| 30 | #include <boost/filesystem.hpp> |
| 31 | #include "cryptonote_config.h" |
| 32 | #include "include_base_utils.h" |
| 33 | #include "string_tools.h" |
| 34 | #include "file_io_utils.h" |
| 35 | #include "int-util.h" |
| 36 | #include "common/util.h" |
| 37 | #include "common/unordered_containers_boost_serialization.h" |
| 38 | #include "cryptonote_basic/cryptonote_boost_serialization.h" |
| 39 | #include "cryptonote_basic/cryptonote_format_utils.h" |
| 40 | #include "cryptonote_basic/difficulty.h" |
| 41 | #include "core_rpc_server_error_codes.h" |
| 42 | #include "rpc_payment.h" |
| 43 | |
| 44 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 45 | #define MONERO_DEFAULT_LOG_CATEGORY "daemon.rpc.payment" |
| 46 | |
| 47 | #define STALE_THRESHOLD 15 /* seconds */ |
| 48 | |
| 49 | #define PENALTY_FOR_STALE 0 |
| 50 | #define PENALTY_FOR_BAD_HASH 20 |
| 51 | #define PENALTY_FOR_DUPLICATE 20 |
| 52 | |
| 53 | #define DEFAULT_FLUSH_AGE (3600 * 24 * 180) // half a year |
| 54 | #define DEFAULT_ZERO_FLUSH_AGE (60 * 2) // 2 minutes |
| 55 | |
| 56 | namespace cryptonote |
| 57 | { |
| 58 | rpc_payment::client_info::client_info(): |
| 59 | previous_seed_height(0), |
| 60 | seed_height(0), |
| 61 | previous_seed_hash(crypto::null_hash), |
| 62 | seed_hash(crypto::null_hash), |
| 63 | cookie(0), |
| 64 | top(crypto::null_hash), |
| 65 | previous_top(crypto::null_hash), |
| 66 | credits(0), |
| 67 | update_time(time(NULL)), |
| 68 | last_request_timestamp(0), |
| 69 | block_template_update_time(0), |
| 70 | credits_total(0), |
| 71 | credits_used(0), |
| 72 | nonces_good(0), |
| 73 | nonces_stale(0), |
| 74 | nonces_bad(0), |
| 75 | nonces_dupe(0) |
| 76 | { |
| 77 | } |
| 78 | |
| 79 | rpc_payment::rpc_payment(const cryptonote::account_public_address &address, uint64_t diff, uint64_t credits_per_hash_found): |
| 80 | m_address(address), |
| 81 | m_diff(diff), |
| 82 | m_credits_per_hash_found(credits_per_hash_found), |
| 83 | m_credits_total(0), |
| 84 | m_credits_used(0), |
| 85 | m_nonces_good(0), |
| 86 | m_nonces_stale(0), |
| 87 | m_nonces_bad(0), |
| 88 | m_nonces_dupe(0) |
| 89 | { |
| 90 | } |
| 91 | |
| 92 | uint64_t rpc_payment::balance(const crypto::public_key &client, int64_t delta) |
| 93 | { |
| 94 | boost::lock_guard<boost::mutex> lock(mutex); |
| 95 | client_info &info = m_client_info[client]; // creates if not found |
| 96 | uint64_t credits = info.credits; |
| 97 | if (delta > 0 && credits > std::numeric_limits<uint64_t>::max() - delta) |
| 98 | credits = std::numeric_limits<uint64_t>::max(); |
| 99 | else if (delta < 0 && credits < (uint64_t)-delta) |
| 100 | credits = 0; |
| 101 | else |
| 102 | credits += delta; |
| 103 | if (delta) |
| 104 | MINFO("Client " << client << ": balance change from " << info.credits << " to " << credits); |
| 105 | return info.credits = credits; |
| 106 | } |
| 107 | |
| 108 | bool rpc_payment::pay(const crypto::public_key &client, uint64_t ts, uint64_t payment, const std::string &rpc, bool same_ts, uint64_t &credits) |
| 109 | { |
| 110 | boost::lock_guard<boost::mutex> lock(mutex); |
| 111 | client_info &info = m_client_info[client]; // creates if not found |
| 112 | if (ts < info.last_request_timestamp || (ts == info.last_request_timestamp && !same_ts)) |
| 113 | { |
| 114 | MDEBUG("Invalid ts: " << ts << " <= " << info.last_request_timestamp); |
| 115 | return false; |
| 116 | } |
| 117 | info.last_request_timestamp = ts; |
| 118 | if (info.credits < payment) |
| 119 | { |
| 120 | MDEBUG("Not enough credits: " << info.credits << " < " << payment); |
| 121 | credits = info.credits; |
| 122 | return false; |
| 123 | } |
| 124 | info.credits -= payment; |
| 125 | add64clamp(&info.credits_used, payment); |
| 126 | add64clamp(&m_credits_used, payment); |
| 127 | MDEBUG("client " << client << " paying " << payment << " for " << rpc << ", " << info.credits << " left"); |
| 128 | credits = info.credits; |
| 129 | return true; |
| 130 | } |
| 131 | |
| 132 | bool rpc_payment::get_info(const crypto::public_key &client, const std::function<bool(const cryptonote::blobdata&, cryptonote::block&, uint64_t &seed_height, crypto::hash &seed_hash)> &get_block_template, cryptonote::blobdata &hashing_blob, uint64_t &seed_height, crypto::hash &seed_hash, const crypto::hash &top, uint64_t &diff, uint64_t &credits_per_hash_found, uint64_t &credits, uint32_t &cookie) |
| 133 | { |
| 134 | boost::lock_guard<boost::mutex> lock(mutex); |
| 135 | client_info &info = m_client_info[client]; // creates if not found |
| 136 | const uint64_t now = time(NULL); |
| 137 | bool need_template = top != info.top || now >= info.block_template_update_time + STALE_THRESHOLD; |
| 138 | if (need_template) |
| 139 | { |
| 140 | cryptonote::block new_block; |
| 141 | uint64_t new_seed_height; |
| 142 | crypto::hash new_seed_hash; |
| 143 | cryptonote::blobdata extra_nonce("\x42\x42\x42\x42", 4); |
| 144 | if (!get_block_template(extra_nonce, new_block, new_seed_height, new_seed_hash)) |
| 145 | return false; |
| 146 | if(!remove_field_from_tx_extra(new_block.miner_tx.extra, typeid(cryptonote::tx_extra_nonce))) |
| 147 | return false; |
| 148 | char data[33]; |
| 149 | memcpy(data, &client, 32); |
| 150 | data[32] = config::HASH_KEY_RPC_PAYMENT_NONCE; |
| 151 | crypto::hash hash; |
| 152 | cn_fast_hash(data, sizeof(data), hash); |
| 153 | extra_nonce = cryptonote::blobdata((const char*)&hash, 4); |
| 154 | if(!add_extra_nonce_to_tx_extra(new_block.miner_tx.extra, extra_nonce)) |
| 155 | return false; |
| 156 | info.previous_block = std::move(info.block); |
| 157 | info.block = std::move(new_block); |
| 158 | hashing_blob = get_block_hashing_blob(info.block); |
| 159 | info.previous_hashing_blob = info.hashing_blob; |
| 160 | info.hashing_blob = hashing_blob; |
| 161 | info.previous_top = info.top; |
| 162 | info.previous_seed_height = info.seed_height; |
| 163 | info.seed_height = new_seed_height; |
| 164 | info.previous_seed_hash = info.seed_hash; |
| 165 | info.seed_hash = new_seed_hash; |
| 166 | std::swap(info.previous_payments, info.payments); |
| 167 | info.payments.clear(); |
| 168 | ++info.cookie; |
| 169 | info.block_template_update_time = now; |
| 170 | } |
| 171 | info.top = top; |
| 172 | info.update_time = now; |
| 173 | hashing_blob = info.hashing_blob; |
| 174 | diff = m_diff; |
| 175 | credits_per_hash_found = m_credits_per_hash_found; |
| 176 | credits = info.credits; |
| 177 | seed_height = info.seed_height; |
| 178 | seed_hash = info.seed_hash; |
| 179 | cookie = info.cookie; |
| 180 | return true; |
| 181 | } |
| 182 | |
| 183 | bool rpc_payment::submit_nonce(const crypto::public_key &client, uint32_t nonce, const crypto::hash &top, int64_t &error_code, std::string &error_message, uint64_t &credits, crypto::hash &hash, cryptonote::block &block, uint32_t cookie, bool &stale) |
| 184 | { |
| 185 | boost::lock_guard<boost::mutex> lock(mutex); |
| 186 | client_info &info = m_client_info[client]; // creates if not found |
| 187 | if (cookie != info.cookie && cookie != info.cookie - 1) |
| 188 | { |
| 189 | MWARNING("Very stale nonce"); |
| 190 | ++m_nonces_stale; |
| 191 | ++info.nonces_stale; |
| 192 | sub64clamp(&info.credits, PENALTY_FOR_STALE * m_credits_per_hash_found); |
| 193 | error_code = CORE_RPC_ERROR_CODE_STALE_PAYMENT; |
| 194 | error_message = "Very stale payment"; |
| 195 | return false; |
| 196 | } |
| 197 | const bool is_current = cookie == info.cookie; |
| 198 | MINFO("client " << client << " sends nonce: " << nonce << ", " << (is_current ? "current" : "stale")); |
| 199 | std::unordered_set<uint64_t> &payments = is_current ? info.payments : info.previous_payments; |
| 200 | if (!payments.insert(nonce).second) |
| 201 | { |
| 202 | MWARNING("Duplicate nonce " << nonce << " from " << (is_current ? "current" : "previous")); |
| 203 | ++m_nonces_dupe; |
| 204 | ++info.nonces_dupe; |
| 205 | sub64clamp(&info.credits, PENALTY_FOR_DUPLICATE * m_credits_per_hash_found); |
| 206 | error_code = CORE_RPC_ERROR_CODE_DUPLICATE_PAYMENT; |
| 207 | error_message = "Duplicate payment"; |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | const uint64_t now = time(NULL); |
| 212 | if (!is_current) |
| 213 | { |
| 214 | if (now > info.update_time + STALE_THRESHOLD) |
| 215 | { |
| 216 | MWARNING("Nonce is stale (top " << top << ", should be " << info.top << " or within " << STALE_THRESHOLD << " seconds"); |
| 217 | ++m_nonces_stale; |
| 218 | ++info.nonces_stale; |
| 219 | sub64clamp(&info.credits, PENALTY_FOR_STALE * m_credits_per_hash_found); |
| 220 | error_code = CORE_RPC_ERROR_CODE_STALE_PAYMENT; |
| 221 | error_message = "stale payment"; |
| 222 | return false; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | cryptonote::blobdata hashing_blob = is_current ? info.hashing_blob : info.previous_hashing_blob; |
| 227 | if (hashing_blob.size() < 43) |
| 228 | { |
| 229 | // not initialized ? |
| 230 | error_code = CORE_RPC_ERROR_CODE_WRONG_BLOCKBLOB; |
| 231 | error_message = "not initialized"; |
| 232 | return false; |
| 233 | } |
| 234 | |
| 235 | block = is_current ? info.block : info.previous_block; |
| 236 | *(uint32_t*)(hashing_blob.data() + 39) = SWAP32LE(nonce); |
| 237 | if (block.major_version >= RX_BLOCK_VERSION) |
| 238 | { |
| 239 | const crypto::hash &seed_hash = is_current ? info.seed_hash : info.previous_seed_hash; |
| 240 | crypto::rx_slow_hash(seed_hash.data, hashing_blob.data(), hashing_blob.size(), hash.data); |
| 241 | } |
| 242 | else |
| 243 | { |
| 244 | const int cn_variant = hashing_blob[0] >= 7 ? hashing_blob[0] - 6 : 0; |
| 245 | crypto::cn_slow_hash(hashing_blob.data(), hashing_blob.size(), hash, cn_variant, cryptonote::get_block_height(block)); |
| 246 | } |
| 247 | if (!check_hash(hash, m_diff)) |
| 248 | { |
| 249 | MWARNING("Payment too low"); |
| 250 | ++m_nonces_bad; |
| 251 | ++info.nonces_bad; |
| 252 | error_code = CORE_RPC_ERROR_CODE_PAYMENT_TOO_LOW; |
| 253 | error_message = "Hash does not meet difficulty (could be wrong PoW hash, or mining at lower difficulty than required, or attempt to defraud)"; |
| 254 | sub64clamp(&info.credits, PENALTY_FOR_BAD_HASH * m_credits_per_hash_found); |
| 255 | return false; |
| 256 | } |
| 257 | |
| 258 | add64clamp(&info.credits, m_credits_per_hash_found); |
| 259 | MINFO("client " << client << " credited for " << m_credits_per_hash_found << ", now " << info.credits << (is_current ? "" : " (close)")); |
| 260 | |
| 261 | m_hashrate[now] += m_diff; |
| 262 | add64clamp(&m_credits_total, m_credits_per_hash_found); |
| 263 | add64clamp(&info.credits_total, m_credits_per_hash_found); |
| 264 | ++m_nonces_good; |
| 265 | ++info.nonces_good; |
| 266 | |
| 267 | credits = info.credits; |
| 268 | block = info.block; |
| 269 | block.nonce = nonce; |
| 270 | stale = !is_current; |
| 271 | return true; |
| 272 | } |
| 273 | |
| 274 | bool rpc_payment::foreach(const std::function<bool(const crypto::public_key &client, const client_info &info)> &f) const |
| 275 | { |
| 276 | boost::lock_guard<boost::mutex> lock(mutex); |
| 277 | for (std::unordered_map<crypto::public_key, client_info>::const_iterator i = m_client_info.begin(); i != m_client_info.end(); ++i) |
| 278 | { |
| 279 | if (!f(i->first, i->second)) |
| 280 | return false; |
| 281 | } |
| 282 | return true; |
| 283 | } |
| 284 | |
| 285 | bool rpc_payment::load(std::string directory) |
| 286 | { |
| 287 | TRY_ENTRY(); |
| 288 | boost::lock_guard<boost::mutex> lock(mutex); |
| 289 | m_directory = std::move(directory); |
| 290 | std::string state_file_path = m_directory + "/" + RPC_PAYMENTS_DATA_FILENAME; |
| 291 | MINFO("loading rpc payments data from " << state_file_path); |
| 292 | std::ifstream data; |
| 293 | data.open(state_file_path, std::ios_base::binary | std::ios_base::in); |
| 294 | std::string bytes(std::istream_iterator<char>{data}, std::istream_iterator<char>{}); |
| 295 | if (!data.fail()) |
| 296 | { |
| 297 | bool loaded = false; |
| 298 | try |
| 299 | { |
| 300 | binary_archive<false> ar{epee::strspan<std::uint8_t>(bytes)}; |
| 301 | if (::serialization::serialize(ar, *this)) |
| 302 | if (::serialization::check_stream_state(ar)) |
| 303 | loaded = true; |
| 304 | } |
| 305 | catch (...) {} |
| 306 | if (!loaded) |
| 307 | { |
| 308 | bytes.clear(); |
| 309 | bytes.shrink_to_fit(); |
| 310 | try |
| 311 | { |
| 312 | boost::archive::portable_binary_iarchive a(data); |
| 313 | a >> *this; |
| 314 | loaded = true; |
| 315 | } |
| 316 | catch (...) {} |
| 317 | } |
| 318 | if (!loaded) |
| 319 | { |
| 320 | MERROR("Failed to load RPC payments file"); |
| 321 | m_client_info.clear(); |
| 322 | } |
| 323 | } |
| 324 | else |
| 325 | { |
| 326 | m_client_info.clear(); |
| 327 | } |
| 328 | |
| 329 | CATCH_ENTRY_L0("rpc_payment::load", false); |
| 330 | return true; |
| 331 | } |
| 332 | |
| 333 | bool rpc_payment::store(const std::string &directory_) const |
| 334 | { |
| 335 | TRY_ENTRY(); |
| 336 | boost::lock_guard<boost::mutex> lock(mutex); |
| 337 | const std::string &directory = directory_.empty() ? m_directory : directory_; |
| 338 | MDEBUG("storing rpc payments data to " << directory); |
| 339 | if (!tools::create_directories_if_necessary(directory)) |
| 340 | { |
| 341 | MWARNING("Failed to create data directory: " << directory); |
| 342 | return false; |
| 343 | } |
| 344 | const boost::filesystem::path state_file_path = (boost::filesystem::path(directory) / RPC_PAYMENTS_DATA_FILENAME); |
| 345 | if (boost::filesystem::exists(state_file_path)) |
| 346 | { |
| 347 | std::string state_file_path_old = state_file_path.string() + ".old"; |
| 348 | boost::system::error_code ec; |
| 349 | boost::filesystem::remove(state_file_path_old, ec); |
| 350 | std::error_code e = tools::replace_file(state_file_path.string(), state_file_path_old); |
| 351 | if (e) |
| 352 | MWARNING("Failed to rename " << state_file_path << " to " << state_file_path_old << ": " << e); |
| 353 | } |
| 354 | std::ofstream data; |
| 355 | data.open(state_file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc); |
| 356 | if (data.fail()) |
| 357 | { |
| 358 | MWARNING("Failed to save RPC payments to file " << state_file_path); |
| 359 | return false; |
| 360 | }; |
| 361 | binary_archive<true> ar(data); |
| 362 | if (!::serialization::serialize(ar, *const_cast<rpc_payment*>(this))) |
| 363 | return false; |
| 364 | return true; |
| 365 | CATCH_ENTRY_L0("rpc_payment::store", false); |
| 366 | } |
| 367 | |
| 368 | unsigned int rpc_payment::flush_by_age(time_t seconds) |
| 369 | { |
| 370 | boost::lock_guard<boost::mutex> lock(mutex); |
| 371 | unsigned int count = 0; |
| 372 | const time_t now = time(NULL); |
| 373 | time_t seconds0 = seconds; |
| 374 | if (seconds == 0) |
| 375 | { |
| 376 | seconds = DEFAULT_FLUSH_AGE; |
| 377 | seconds0 = DEFAULT_ZERO_FLUSH_AGE; |
| 378 | } |
| 379 | const time_t threshold = seconds > now ? 0 : now - seconds; |
| 380 | const time_t threshold0 = seconds0 > now ? 0 : now - seconds0; |
| 381 | for (std::unordered_map<crypto::public_key, client_info>::iterator i = m_client_info.begin(); i != m_client_info.end(); ) |
| 382 | { |
| 383 | std::unordered_map<crypto::public_key, client_info>::iterator j = i++; |
| 384 | const time_t t = std::max(j->second.last_request_timestamp / 1000000, j->second.update_time); |
| 385 | const bool erase = t < ((j->second.credits == 0) ? threshold0 : threshold); |
| 386 | if (erase) |
| 387 | { |
| 388 | MINFO("Erasing " << j->first << " with " << j->second.credits << " credits, inactive for " << (now-t)/86400 << " days"); |
| 389 | m_client_info.erase(j); |
| 390 | ++count; |
| 391 | } |
| 392 | } |
| 393 | return count; |
| 394 | } |
| 395 | |
| 396 | uint64_t rpc_payment::get_hashes(unsigned int seconds) const |
| 397 | { |
| 398 | boost::lock_guard<boost::mutex> lock(mutex); |
| 399 | const uint64_t now = time(NULL); |
| 400 | uint64_t hashes = 0; |
| 401 | for (std::map<uint64_t, uint64_t>::const_reverse_iterator i = m_hashrate.crbegin(); i != m_hashrate.crend(); ++i) |
| 402 | { |
| 403 | if (now > i->first + seconds) |
| 404 | break; |
| 405 | hashes += i->second; |
| 406 | } |
| 407 | return hashes; |
| 408 | } |
| 409 | |
| 410 | void rpc_payment::prune_hashrate(unsigned int seconds) |
| 411 | { |
| 412 | boost::lock_guard<boost::mutex> lock(mutex); |
| 413 | const uint64_t now = time(NULL); |
| 414 | std::map<uint64_t, uint64_t>::iterator i; |
| 415 | for (i = m_hashrate.begin(); i != m_hashrate.end(); ++i) |
| 416 | { |
| 417 | if (now <= i->first + seconds) |
| 418 | break; |
| 419 | } |
| 420 | m_hashrate.erase(m_hashrate.begin(), i); |
| 421 | } |
| 422 | |
| 423 | bool rpc_payment::on_idle() |
| 424 | { |
| 425 | flush_by_age(); |
| 426 | prune_hashrate(3600); |
| 427 | return true; |
| 428 | } |
| 429 | } |