node.cpp raw

   1  // Copyright (c) 2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #include <limenka-build-config.h> // IWYU pragma: keep
   7  
   8  #include <chainparams.h>
   9  #include <clientversion.h>
  10  #include <common/args.h>
  11  #include <common/system.h>
  12  #include <httpserver.h>
  13  #include <index/blockfilterindex.h>
  14  #include <index/coinstatsindex.h>
  15  #include <index/txindex.h>
  16  #include <interfaces/chain.h>
  17  #include <interfaces/echo.h>
  18  #include <interfaces/init.h>
  19  #include <interfaces/ipc.h>
  20  #include <kernel/cs_main.h>
  21  #include <logging.h>
  22  #include <net.h>
  23  #include <node/context.h>
  24  #include <rpc/server.h>
  25  #include <rpc/server_util.h>
  26  #include <rpc/util.h>
  27  #include <scheduler.h>
  28  #include <univalue.h>
  29  #include <util/any.h>
  30  #include <util/check.h>
  31  #include <util/time.h>
  32  
  33  #include <stdint.h>
  34  #ifdef HAVE_MALLOC_INFO
  35  #include <malloc.h>
  36  #endif
  37  
  38  using node::NodeContext;
  39  
  40  static RPCHelpMan setmocktime()
  41  {
  42      return RPCHelpMan{"setmocktime",
  43          "\nSet the local time to given timestamp (-regtest only)\n",
  44          {
  45              {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
  46               "Pass 0 to go back to using the system time."},
  47          },
  48          RPCResult{RPCResult::Type::NONE, "", ""},
  49          RPCExamples{""},
  50          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  51  {
  52      if (!Params().IsMockableChain()) {
  53          throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
  54      }
  55  
  56      // For now, don't change mocktime if we're in the middle of validation, as
  57      // this could have an effect on mempool time-based eviction, as well as
  58      // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
  59      // TODO: figure out the right way to synchronize around mocktime, and
  60      // ensure all call sites of GetTime() are accessing this safely.
  61      LOCK(cs_main);
  62  
  63      const int64_t time{request.params[0].getInt<int64_t>()};
  64      constexpr int64_t max_time{Ticks<std::chrono::seconds>(std::chrono::nanoseconds::max())};
  65      if (time < 0 || time > max_time) {
  66          throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime must be in the range [0, %s], not %s.", max_time, time));
  67      }
  68  
  69      SetMockTime(time);
  70      const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
  71      for (const auto& chain_client : node_context.chain_clients) {
  72          chain_client->setMockTime(time);
  73      }
  74  
  75      return UniValue::VNULL;
  76  },
  77      };
  78  }
  79  
  80  static RPCHelpMan mockscheduler()
  81  {
  82      return RPCHelpMan{"mockscheduler",
  83          "\nBump the scheduler into the future (-regtest only)\n",
  84          {
  85              {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
  86          },
  87          RPCResult{RPCResult::Type::NONE, "", ""},
  88          RPCExamples{""},
  89          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
  90  {
  91      if (!Params().IsMockableChain()) {
  92          throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
  93      }
  94  
  95      int64_t delta_seconds = request.params[0].getInt<int64_t>();
  96      if (delta_seconds <= 0 || delta_seconds > 3600) {
  97          throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
  98      }
  99  
 100      const NodeContext& node_context{EnsureAnyNodeContext(request.context)};
 101      CHECK_NONFATAL(node_context.scheduler)->MockForward(std::chrono::seconds{delta_seconds});
 102      CHECK_NONFATAL(node_context.validation_signals)->SyncWithValidationInterfaceQueue();
 103      for (const auto& chain_client : node_context.chain_clients) {
 104          chain_client->schedulerMockForward(std::chrono::seconds(delta_seconds));
 105      }
 106  
 107      return UniValue::VNULL;
 108  },
 109      };
 110  }
 111  
 112  static UniValue RPCLockedMemoryInfo()
 113  {
 114      LockedPool::Stats stats = LockedPoolManager::Instance().stats();
 115      UniValue obj(UniValue::VOBJ);
 116      obj.pushKV("used", uint64_t(stats.used));
 117      obj.pushKV("free", uint64_t(stats.free));
 118      obj.pushKV("total", uint64_t(stats.total));
 119      obj.pushKV("locked", uint64_t(stats.locked));
 120      obj.pushKV("chunks_used", uint64_t(stats.chunks_used));
 121      obj.pushKV("chunks_free", uint64_t(stats.chunks_free));
 122      return obj;
 123  }
 124  
 125  #ifdef HAVE_MALLOC_INFO
 126  static std::string RPCMallocInfo()
 127  {
 128      char *ptr = nullptr;
 129      size_t size = 0;
 130      FILE *f = open_memstream(&ptr, &size);
 131      if (f) {
 132          malloc_info(0, f);
 133          fclose(f);
 134          if (ptr) {
 135              std::string rv(ptr, size);
 136              free(ptr);
 137              return rv;
 138          }
 139      }
 140      return "";
 141  }
 142  #endif
 143  
 144  static RPCHelpMan getmemoryinfo()
 145  {
 146      /* Please, avoid using the word "pool" here in the RPC interface or help,
 147       * as users will undoubtedly confuse it with the other "memory pool"
 148       */
 149      return RPCHelpMan{"getmemoryinfo",
 150                  "Returns an object containing information about memory usage.\n",
 151                  {
 152                      {"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
 153              "  - \"stats\" returns general statistics about memory usage in the daemon.\n"
 154              "  - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc)."},
 155                  },
 156                  {
 157                      RPCResult{"mode \"stats\"",
 158                          RPCResult::Type::OBJ, "", "",
 159                          {
 160                              {RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
 161                              {
 162                                  {RPCResult::Type::NUM, "used", "Number of bytes used"},
 163                                  {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
 164                                  {RPCResult::Type::NUM, "total", "Total number of bytes managed"},
 165                                  {RPCResult::Type::NUM, "locked", "Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk."},
 166                                  {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
 167                                  {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
 168                              }},
 169                          }
 170                      },
 171                      RPCResult{"mode \"mallocinfo\"",
 172                          RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
 173                      },
 174                  },
 175                  RPCExamples{
 176                      HelpExampleCli("getmemoryinfo", "")
 177              + HelpExampleRpc("getmemoryinfo", "")
 178                  },
 179          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 180  {
 181      std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
 182      if (mode == "stats") {
 183          UniValue obj(UniValue::VOBJ);
 184          obj.pushKV("locked", RPCLockedMemoryInfo());
 185          return obj;
 186      } else if (mode == "mallocinfo") {
 187  #ifdef HAVE_MALLOC_INFO
 188          return RPCMallocInfo();
 189  #else
 190          throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
 191  #endif
 192      } else {
 193          throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
 194      }
 195  },
 196      };
 197  }
 198  
 199  static RPCHelpMan getgeneralinfo()
 200  {
 201      return RPCHelpMan{"getgeneralinfo",
 202                  "Returns data about the limenka daemon.\n",
 203                  {},
 204                  RPCResult{
 205                      RPCResult::Type::OBJ, "", "",
 206                      {
 207                          {RPCResult::Type::STR, "clientversion", "Client version"},
 208                          {RPCResult::Type::STR, "useragent", "Client name"},
 209                          {RPCResult::Type::STR, "datadir", "Data directory path"},
 210                          {RPCResult::Type::STR, "blocksdir", "Blocks directory path"},
 211                          {RPCResult::Type::NUM, "startuptime", "Startup time"},
 212                      }
 213                  },
 214                  RPCExamples{
 215                      HelpExampleCli("getgeneralinfo", "")
 216              + HelpExampleRpc("getgeneralinfo", "")
 217                  },
 218          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 219  {
 220          const ArgsManager& args{EnsureAnyArgsman(request.context)};
 221  
 222          UniValue obj(UniValue::VOBJ);
 223          obj.pushKV("clientversion", FormatFullVersion());
 224          obj.pushKV("useragent", strSubVersion);
 225          obj.pushKV("datadir", fs::PathToString(args.GetDataDirNet()));
 226          obj.pushKV("blocksdir", fs::PathToString(args.GetBlocksDirPath()));
 227          obj.pushKV("startuptime", TicksSinceEpoch<std::chrono::seconds>(NodeClock::now() - GetUptime()));
 228          return obj;
 229  },
 230      };
 231  }
 232  
 233  static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
 234      cats = cats.get_array();
 235      for (unsigned int i = 0; i < cats.size(); ++i) {
 236          std::string cat = cats[i].get_str();
 237  
 238          bool success;
 239          if (enable) {
 240              success = LogInstance().EnableCategory(cat);
 241          } else {
 242              success = LogInstance().DisableCategory(cat);
 243          }
 244  
 245          if (!success) {
 246              throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
 247          }
 248      }
 249  }
 250  
 251  static RPCHelpMan logging()
 252  {
 253      return RPCHelpMan{"logging",
 254              "Gets and sets the logging configuration.\n"
 255              "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
 256              "When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
 257              "The arguments are evaluated in order \"include\", \"exclude\".\n"
 258              "If an item is both included and excluded, it will thus end up being excluded.\n"
 259              "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
 260              "In addition, the following are available as category names with special meanings:\n"
 261              "  - \"all\",  \"1\" : represent all logging categories.\n"
 262              ,
 263                  {
 264                      {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to add to debug logging",
 265                          {
 266                              {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
 267                          }},
 268                      {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The categories to remove from debug logging",
 269                          {
 270                              {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
 271                          }},
 272                  },
 273                  RPCResult{
 274                      RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
 275                      {
 276                          {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
 277                      }
 278                  },
 279                  RPCExamples{
 280                      HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
 281              + HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]")
 282                  },
 283          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 284  {
 285      BCLog::CategoryMask original_log_categories = LogInstance().GetCategoryMask();
 286      if (request.params[0].isArray()) {
 287          EnableOrDisableLogCategories(request.params[0], true);
 288      }
 289      if (request.params[1].isArray()) {
 290          EnableOrDisableLogCategories(request.params[1], false);
 291      }
 292      BCLog::CategoryMask updated_log_categories = LogInstance().GetCategoryMask();
 293      BCLog::CategoryMask changed_log_categories = original_log_categories ^ updated_log_categories;
 294  
 295      // Update libevent logging if BCLog::LIBEVENT has changed.
 296      if (changed_log_categories & BCLog::LIBEVENT) {
 297          UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT));
 298      }
 299  
 300      UniValue result(UniValue::VOBJ);
 301      for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
 302          result.pushKV(logCatActive.category, logCatActive.active);
 303      }
 304  
 305      return result;
 306  },
 307      };
 308  }
 309  
 310  static RPCHelpMan format()
 311  {
 312      return RPCHelpMan{"format",
 313          "\nFormat data we have about an RPC command in the format specified\n",
 314          {
 315              {"command", RPCArg::Type::STR, RPCArg::Optional::NO, "Command to query"},
 316              {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "Output format. Accepted values: args_cli"},
 317          },
 318          RPCResult{RPCResult::Type::STR, "data", "Formated data about command"},
 319          RPCExamples{""},
 320          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 321  {
 322      const std::string command = request.params[0].get_str();
 323      JSONRPCRequest jreq(request);
 324      jreq.mode = JSONRPCRequest::GET_HELP;
 325  
 326      try {
 327          tableRPC.execute(command, jreq);
 328      } catch(const UniValue& e) {
 329          return e["message"];
 330      }
 331      return NullUniValue;
 332  },
 333      };
 334  }
 335  
 336  static RPCHelpMan echo(const std::string& name)
 337  {
 338      return RPCHelpMan{name,
 339                  "\nSimply echo back the input arguments. This command is for testing.\n"
 340                  "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
 341                  "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
 342                  "limenka-cli and the GUI. There is no server-side difference.",
 343          {
 344              {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 345              {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 346              {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 347              {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 348              {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 349              {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 350              {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 351              {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 352              {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 353              {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "", RPCArgOptions{.skip_type_check = true}},
 354          },
 355                  RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
 356                  RPCExamples{""},
 357          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 358  {
 359      if (request.params[9].isStr()) {
 360          CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
 361      }
 362  
 363      return request.params;
 364  },
 365      };
 366  }
 367  
 368  static RPCHelpMan echo() { return echo("echo"); }
 369  static RPCHelpMan echojson() { return echo("echojson"); }
 370  
 371  static RPCHelpMan echoipc()
 372  {
 373      return RPCHelpMan{
 374          "echoipc",
 375          "\nEcho back the input argument, passing it through a spawned process in a multiprocess build.\n"
 376          "This command is for testing.\n",
 377          {{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
 378          RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
 379          RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
 380                      HelpExampleRpc("echo", "\"Hello world\"")},
 381          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
 382              interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
 383              std::unique_ptr<interfaces::Echo> echo;
 384              if (interfaces::Ipc* ipc = local_init.ipc()) {
 385                  // Spawn a new limenka-node process and call makeEcho to get a
 386                  // client pointer to a interfaces::Echo instance running in
 387                  // that process. This is just for testing. A slightly more
 388                  // realistic test spawning a different executable instead of
 389                  // the same executable would add a new limenka-echo executable,
 390                  // and spawn limenka-echo below instead of limenka-node. But
 391                  // using limenka-node avoids the need to build and install a
 392                  // new executable just for this one test.
 393                  auto init = ipc->spawnProcess("limenka-node");
 394                  echo = init->makeEcho();
 395                  ipc->addCleanup(*echo, [init = init.release()] { delete init; });
 396              } else {
 397                  // IPC support is not available because this is a limenkad
 398                  // process not a limenkad-node process, so just create a local
 399                  // interfaces::Echo object and return it so the `echoipc` RPC
 400                  // method will work, and the python test calling `echoipc`
 401                  // can expect the same result.
 402                  echo = local_init.makeEcho();
 403              }
 404              return echo->echo(request.params[0].get_str());
 405          },
 406      };
 407  }
 408  
 409  static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
 410  {
 411      UniValue ret_summary(UniValue::VOBJ);
 412      if (!index_name.empty() && index_name != summary.name) return ret_summary;
 413  
 414      UniValue entry(UniValue::VOBJ);
 415      entry.pushKV("synced", summary.synced);
 416      entry.pushKV("best_block_height", summary.best_block_height);
 417      ret_summary.pushKV(summary.name, std::move(entry));
 418      return ret_summary;
 419  }
 420  
 421  static RPCHelpMan getindexinfo()
 422  {
 423      return RPCHelpMan{"getindexinfo",
 424                  "\nReturns the status of one or all available indices currently running in the node.\n",
 425                  {
 426                      {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Filter results for an index with a specific name."},
 427                  },
 428                  RPCResult{
 429                      RPCResult::Type::OBJ_DYN, "", "", {
 430                          {
 431                              RPCResult::Type::OBJ, "name", "The name of the index",
 432                              {
 433                                  {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
 434                                  {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
 435                              }
 436                          },
 437                      },
 438                  },
 439                  RPCExamples{
 440                      HelpExampleCli("getindexinfo", "")
 441                    + HelpExampleRpc("getindexinfo", "")
 442                    + HelpExampleCli("getindexinfo", "txindex")
 443                    + HelpExampleRpc("getindexinfo", "txindex")
 444                  },
 445                  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 446  {
 447      UniValue result(UniValue::VOBJ);
 448      const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str();
 449  
 450      if (g_txindex) {
 451          result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
 452      }
 453  
 454      if (g_coin_stats_index) {
 455          result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
 456      }
 457  
 458      ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
 459          result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
 460      });
 461  
 462      return result;
 463  },
 464      };
 465  }
 466  
 467  void RegisterNodeRPCCommands(CRPCTable& t)
 468  {
 469      static const CRPCCommand commands[]{
 470          {"control", &getmemoryinfo},
 471          {"control", &getgeneralinfo},
 472          {"control", &logging},
 473          {"util", &getindexinfo},
 474          {"hidden", &setmocktime},
 475          {"hidden", &mockscheduler},
 476          {"hidden", &format},
 477          {"hidden", &echo},
 478          {"hidden", &echojson},
 479          {"hidden", &echoipc},
 480      };
 481      for (const auto& c : commands) {
 482          t.appendCommand(c.name, &c);
 483      }
 484  }
 485