PRCYCoin  2.0.0.7rc1
P2P Digital Currency
misc.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "base58.h"
10 #include "clientversion.h"
11 #include "httpserver.h"
12 #include "init.h"
13 #include "main.h"
14 #include "masternode-sync.h"
15 #include "net.h"
16 #include "netbase.h"
17 #include "rpc/server.h"
18 #include "timedata.h"
19 #include "util.h"
20 
21 #ifdef ENABLE_WALLET
22 #include "wallet/wallet.h"
23 #include "wallet/walletdb.h"
24 #endif
25 
26 #include <stdint.h>
27 
28 #include <univalue.h>
29 #include <boost/assign/list_of.hpp>
30 
31 
45 UniValue getinfo(const UniValue &params, bool fHelp) {
46  if (fHelp || params.size() != 0)
47  throw std::runtime_error(
48  "getinfo\n"
49  "Returns an object containing various state info.\n"
50  "\nResult:\n"
51  "{\n"
52  " \"version\": xxxxx, (numeric) the server version\n"
53  " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
54  " \"walletversion\": xxxxx, (numeric) the wallet version\n"
55  " \"balance\": xxxxxxx, (numeric) the total prcycoin balance of the wallet\n"
56  " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
57  " \"synced\": xxxxxx, (boolean) if the server is synced or not\n"
58  " \"timeoffset\": xxxxx, (numeric) the time offset\n"
59  " \"connections\": xxxxx, (numeric) the number of connections\n"
60  " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
61  " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
62  " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
63  " \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n"
64  " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
65  " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
66  " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
67  " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in prcycoin/kb\n"
68  " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in prcycoin/kb\n"
69  " \"staking mode\": enabled|disabled, (string) if staking is enabled or disabled\n"
70  " \"staking status\": active|inactive, (string) if staking is active or inactive\n"
71  " \"errors\": \"...\" (string) any error messages\n"
72  "}\n"
73  "\nExamples:\n" +
74  HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", ""));
75  LOCK(cs_main);
76  proxyType proxy;
77  GetProxy(NET_IPV4, proxy);
78 
80  obj.push_back(Pair("version", CLIENT_VERSION));
81  obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
82 #ifdef ENABLE_WALLET
83  if (pwalletMain) {
84  obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
85  obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
86  }
87 #endif
88  obj.push_back(Pair("blocks", (int) chainActive.Height()));
89  obj.push_back(Pair("synced", masternodeSync.IsBlockchainSynced()));
90  obj.push_back(Pair("timeoffset", GetTimeOffset()));
91  obj.push_back(Pair("connections", (int) vNodes.size()));
92  obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
93  obj.push_back(Pair("difficulty", (double) GetDifficulty()));
94  obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
95  obj.push_back(Pair("moneysupply",ValueFromAmount(chainActive.Tip()->nMoneySupply)));
96 
97 #ifdef ENABLE_WALLET
98  if (pwalletMain) {
99  obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
100  }
102  obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
103  obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
104 #endif
105  obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
106 #ifdef ENABLE_WALLET
107  if (pwalletMain) {
108  bool nStaking = false;
109  if (mapHashedBlocks.count(chainActive.Tip()->nHeight))
110  nStaking = true;
112  nStaking = true;
113  if (pwalletMain->IsLocked()) {
114  obj.push_back(Pair("staking mode", ("disabled")));
115  obj.push_back(Pair("staking status", ("inactive (wallet locked)")));
116  } else {
117  obj.push_back(Pair("staking mode", (pwalletMain->ReadStakingStatus() ? "enabled" : "disabled")));
118  if (vNodes.empty()) {
119  obj.push_back(Pair("staking status", ("inactive (no peer connections)")));
120  } else if (!masternodeSync.IsSynced()) {
121  obj.push_back(Pair("staking status", ("inactive (syncing masternode list)")));
123  obj.push_back(Pair("staking status", ("delayed (waiting for 100 blocks)")));
124  } else if (!pwalletMain->MintableCoins()) {
125  obj.push_back(Pair("staking status", ("inactive (no mintable coins)")));
126  } else {
127  obj.push_back(Pair("staking status", (nStaking ? "active (attempting to mint a block)" : "idle (waiting for next round)")));
128  }
129  }
130  }
131 #endif
132  obj.push_back(Pair("errors", GetWarnings("statusbar")));
133  return obj;
134 }
135 
136 UniValue getversion(const UniValue &params, bool fHelp) {
137  if (fHelp || params.size() != 0)
138  throw std::runtime_error(
139  "getversion\n"
140  "Returns the server version.\n"
141  "\nResult:\n"
142  "{\n"
143  " \"version\": xxxxx, (numeric) the server version\n"
144  "}\n"
145  "\nExamples:\n" +
146  HelpExampleCli("getversion", "") + HelpExampleRpc("getversion", ""));
147  LOCK(cs_main);
148 
150  obj.push_back(Pair("version", CLIENT_VERSION));
151  return obj;
152 }
153 
154 UniValue mnsync(const UniValue &params, bool fHelp) {
155  std::string strMode;
156  if (params.size() == 1)
157  strMode = params[0].get_str();
158 
159  if (fHelp || params.size() != 1 || (strMode != "status" && strMode != "reset")) {
160  throw std::runtime_error(
161  "mnsync \"status|reset\"\n"
162  "\nReturns the sync status or resets sync.\n"
163 
164  "\nArguments:\n"
165  "1. \"mode\" (string, required) either 'status' or 'reset'\n"
166 
167  "\nResult ('status' mode):\n"
168  "{\n"
169  " \"IsBlockchainSynced\": true|false, (boolean) 'true' if blockchain is synced\n"
170  " \"lastMasternodeList\": xxxx, (numeric) Timestamp of last MN list message\n"
171  " \"lastMasternodeWinner\": xxxx, (numeric) Timestamp of last MN winner message\n"
172  " \"lastBudgetItem\": xxxx, (numeric) Timestamp of last MN budget message\n"
173  " \"lastFailure\": xxxx, (numeric) Timestamp of last failed sync\n"
174  " \"nCountFailures\": n, (numeric) Number of failed syncs (total)\n"
175  " \"sumMasternodeList\": n, (numeric) Number of MN list messages (total)\n"
176  " \"sumMasternodeWinner\": n, (numeric) Number of MN winner messages (total)\n"
177  " \"sumBudgetItemProp\": n, (numeric) Number of MN budget messages (total)\n"
178  " \"sumBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (total)\n"
179  " \"countMasternodeList\": n, (numeric) Number of MN list messages (local)\n"
180  " \"countMasternodeWinner\": n, (numeric) Number of MN winner messages (local)\n"
181  " \"countBudgetItemProp\": n, (numeric) Number of MN budget messages (local)\n"
182  " \"countBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (local)\n"
183  " \"RequestedMasternodeAssets\": n, (numeric) Status code of last sync phase\n"
184  " \"RequestedMasternodeAttempt\": n, (numeric) Status code of last sync attempt\n"
185  "}\n"
186 
187  "\nResult ('reset' mode):\n"
188  "\"status\" (string) 'success'\n"
189  "\nExamples:\n" +
190  HelpExampleCli("mnsync", "\"status\"") + HelpExampleRpc("mnsync", "\"status\""));
191  }
192 
193  if (strMode == "status") {
195 
196  obj.push_back(Pair("IsBlockchainSynced", masternodeSync.IsBlockchainSynced()));
197  obj.push_back(Pair("lastMasternodeList", masternodeSync.lastMasternodeList));
198  obj.push_back(Pair("lastMasternodeWinner", masternodeSync.lastMasternodeWinner));
199  obj.push_back(Pair("lastBudgetItem", masternodeSync.lastBudgetItem));
200  obj.push_back(Pair("lastFailure", masternodeSync.lastFailure));
201  obj.push_back(Pair("nCountFailures", masternodeSync.nCountFailures));
202  obj.push_back(Pair("sumMasternodeList", masternodeSync.sumMasternodeList));
203  obj.push_back(Pair("sumMasternodeWinner", masternodeSync.sumMasternodeWinner));
204  obj.push_back(Pair("sumBudgetItemProp", masternodeSync.sumBudgetItemProp));
205  obj.push_back(Pair("sumBudgetItemFin", masternodeSync.sumBudgetItemFin));
206  obj.push_back(Pair("countMasternodeList", masternodeSync.countMasternodeList));
207  obj.push_back(Pair("countMasternodeWinner", masternodeSync.countMasternodeWinner));
208  obj.push_back(Pair("countBudgetItemProp", masternodeSync.countBudgetItemProp));
209  obj.push_back(Pair("countBudgetItemFin", masternodeSync.countBudgetItemFin));
210  obj.push_back(Pair("RequestedMasternodeAssets", masternodeSync.RequestedMasternodeAssets));
211  obj.push_back(Pair("RequestedMasternodeAttempt", masternodeSync.RequestedMasternodeAttempt));
212 
213  return obj;
214  }
215 
216  if (strMode == "reset") {
218  return "success";
219  }
220  return "failure";
221 }
222 
223 #ifdef ENABLE_WALLET
224 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
225 {
226 private:
227  isminetype mine;
228 
229 public:
230  DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
231 
232  UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
233 
234  UniValue operator()(const CKeyID &keyID) const
235  {
237  CPubKey vchPubKey;
238  obj.push_back(Pair("isscript", false));
239  if (mine == ISMINE_SPENDABLE) {
240  pwalletMain->GetPubKey(keyID, vchPubKey);
241  obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
242  obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
243  }
244  return obj;
245  }
246 
247  UniValue operator()(const CScriptID &scriptID) const
248  {
250  obj.push_back(Pair("isscript", true));
251  CScript subscript;
252  pwalletMain->GetCScript(scriptID, subscript);
253  std::vector<CTxDestination> addresses;
254  txnouttype whichType;
255  int nRequired;
256  ExtractDestinations(subscript, whichType, addresses, nRequired);
257  obj.push_back(Pair("script", GetTxnOutputType(whichType)));
258  obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
260  for (const CTxDestination& addr : addresses)
261  a.push_back(CBitcoinAddress(addr).ToString());
262  obj.push_back(Pair("addresses", a));
263  if (whichType == TX_MULTISIG)
264  obj.push_back(Pair("sigsrequired", nRequired));
265  return obj;
266  }
267 };
268 #endif
269 
270 UniValue validateaddress(const UniValue& params, bool fHelp)
271 {
272  if (fHelp || params.size() != 1)
273  throw std::runtime_error(
274  "validateaddress \"prcycoinaddress\"\n"
275  "\nReturn information about the given prcycoin address.\n"
276  "\nArguments:\n"
277  "1. \"prcycoinaddress\" (string, required) The prcycoin address to validate\n"
278  "\nResult:\n"
279  "{\n"
280  " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
281  " \"address\" : \"prcycoinaddress\", (string) The prcycoin address validated\n"
282  " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
283  " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
284  " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
285  " \"isscript\" : true|false, (boolean) If the key is a script\n"
286  " \"hex\" : \"hex\", (string, optional) The redeemscript for the P2SH address\n"
287  " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
288  " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
289  " \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
290  "}\n"
291  "\nExamples:\n" +
292  HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") +
293  HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\""));
294 
295 #ifdef ENABLE_WALLET
297 #else
298  LOCK(cs_main);
299 #endif
300 
301  CBitcoinAddress address(params[0].get_str());
302  bool isValid = address.IsValid();
303 
305  ret.push_back(Pair("isvalid", isValid));
306  if (isValid) {
307  CTxDestination dest = address.Get();
308  std::string currentAddress = address.ToString();
309  ret.push_back(Pair("address", currentAddress));
310  CScript scriptPubKey = GetScriptForDestination(dest);
311  ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
312 
313 #ifdef ENABLE_WALLET
315  ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
316  ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
317  UniValue detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
318  ret.pushKVs(detail);
319  if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
320  ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
321 #endif
322  }
323  return ret;
324 }
325 
326 UniValue validatestealthaddress(const UniValue& params, bool fHelp)
327 {
328  if (fHelp || params.size() != 1)
329  throw std::runtime_error(
330  "validatestealthaddress \"prcycoinstealthaddress\"\n"
331  "\nReturn information about the given prcycoin stealth address.\n"
332  "\nArguments:\n"
333  "1. \"prcycoinstealthaddress\" (string, required) The prcycoin stealth address to validate\n"
334  "\nResult:\n"
335  "{\n"
336  " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
337  "}\n"
338  "\nExamples:\n" +
339  HelpExampleCli("validatestealthaddress", "\"Pap5WCV4SjVMGLyYf98MEX82ErBEMVpg9ViQ1up3aBib6Fz4841SahrRXG6eSNSLBSNvEiGuQiWKXJC3RDfmotKv15oCrh6N2Ym\"") +
340  HelpExampleRpc("validatestealthaddress", "\"Pap5WCV4SjVMGLyYf98MEX82ErBEMVpg9ViQ1up3aBib6Fz4841SahrRXG6eSNSLBSNvEiGuQiWKXJC3RDfmotKv15oCrh6N2Ym\""));
341  EnsureWallet();
342 
343  std::string addr = params[0].get_str();
344 
346  CPubKey viewKey, spendKey;
347  bool hasPaymentID;
348  uint64_t paymentID;
349  bool isValid = true;
350 
351  if (!CWallet::DecodeStealthAddress(addr, viewKey, spendKey, hasPaymentID, paymentID)) {
352  isValid = false;
353  }
354  ret.push_back(Pair("isvalid", isValid));
355 
356  return ret;
357 }
358 
363  int nRequired = params[0].get_int();
364  const UniValue& keys = params[1].get_array();
365 
366  // Gather public keys
367  if (nRequired < 1)
368  throw std::runtime_error("a multisignature address must require at least one key to redeem");
369  if ((int) keys.size() < nRequired)
370  throw std::runtime_error(
371  strprintf("not enough keys supplied "
372  "(got %u keys, but need at least %d to redeem)",
373  keys.size(), nRequired));
374  if (keys.size() > 16)
375  throw std::runtime_error(
376  "Number of addresses involved in the multisignature address creation > 16\nReduce the number");
377  std::vector <CPubKey> pubkeys;
378  pubkeys.resize(keys.size());
379  for (unsigned int i = 0; i < keys.size(); i++) {
380  const std::string &ks = keys[i].get_str();
381 #ifdef ENABLE_WALLET
382  // Case 1: PRCY address and we have full public key:
383  CBitcoinAddress address(ks);
384  if (pwalletMain && address.IsValid()) {
385  CKeyID keyID;
386  if (!address.GetKeyID(keyID))
387  throw std::runtime_error(
388  strprintf("%s does not refer to a key", ks));
389  CPubKey vchPubKey;
390  if (!pwalletMain->GetPubKey(keyID, vchPubKey))
391  throw std::runtime_error(
392  strprintf("no full public key for address %s", ks));
393  if (!vchPubKey.IsFullyValid())
394  throw std::runtime_error(" Invalid public key: " + ks);
395  pubkeys[i] = vchPubKey;
396  }
397 
398  // Case 2: hex public key
399  else
400 #endif
401  if (IsHex(ks)) {
402  CPubKey vchPubKey(ParseHex(ks));
403  if (!vchPubKey.IsFullyValid())
404  throw std::runtime_error(" Invalid public key: " + ks);
405  pubkeys[i] = vchPubKey;
406  } else {
407  throw std::runtime_error(" Invalid public key: " + ks);
408  }
409  }
410  CScript result = GetScriptForMultisig(nRequired, pubkeys);
411 
412  if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
413  throw std::runtime_error(
414  strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
415 
416  return result;
417 }
418 
419 UniValue createmultisig(const UniValue& params, bool fHelp) {
420  if (fHelp || params.size() < 2 || params.size() > 2) {
421  std::string msg = "createmultisig nrequired [\"key\",...]\n"
422  "\nCreates a multi-signature address with n signature of m keys required.\n"
423  "It returns a json object with the address and redeemScript.\n"
424 
425  "\nArguments:\n"
426  "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
427  "2. \"keys\" (string, required) A json array of keys which are prcycoin addresses or hex-encoded public keys\n"
428  " [\n"
429  " \"key\" (string) prcycoin address or hex-encoded public key\n"
430  " ,...\n"
431  " ]\n"
432 
433  "\nResult:\n"
434  "{\n"
435  " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
436  " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
437  "}\n"
438 
439  "\nExamples:\n"
440  "\nCreate a multisig address from 2 addresses\n" +
441  HelpExampleCli("createmultisig",
442  "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
443  "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig",
444  "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"");
445  throw std::runtime_error(msg);
446  }
447 
448  // Construct using pay-to-script-hash:
449  CScript inner = _createmultisig_redeemScript(params);
450  CScriptID innerID(inner);
451  CBitcoinAddress address(innerID);
452 
453  UniValue result(UniValue::VOBJ);
454  result.push_back(Pair("address", address.ToString()));
455  result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
456 
457  return result;
458 }
459 
460 UniValue verifymessage(const UniValue& params, bool fHelp) {
461  if (fHelp || params.size() != 3)
462  throw std::runtime_error(
463  "verifymessage \"prcycoinaddress\" \"signature\" \"message\"\n"
464  "\nVerify a signed message\n"
465  "\nArguments:\n"
466  "1. \"prcycoinaddress\" (string, required) The prcycoin address to use for the signature.\n"
467  "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
468  "3. \"message\" (string, required) The message that was signed.\n"
469  "\nResult:\n"
470  "true|false (boolean) If the signature is verified or not.\n"
471  "\nExamples:\n"
472  "\nUnlock the wallet for 30 seconds\n" +
473  HelpExampleCli("unlockwallet", "\"mypassphrase\" 30") +
474  "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
475  "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
476  "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\""));
477 
478  std::string strAddress = params[0].get_str();
479  std::string strSign = params[1].get_str();
480  std::string strMessage = params[2].get_str();
481 
482  CBitcoinAddress addr(strAddress);
483  if (!addr.IsValid())
484  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
485 
486  CKeyID keyID;
487  if (!addr.GetKeyID(keyID))
488  throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
489 
490  bool fInvalid = false;
491  std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
492 
493  if (fInvalid)
494  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
495 
496  CHashWriter ss(SER_GETHASH, 0);
497  ss << strMessageMagic;
498  ss << strMessage;
499 
500  CPubKey pubkey;
501  if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
502  return false;
503 
504  return (pubkey.GetID() == keyID);
505 }
506 
507 UniValue setmocktime(const UniValue& params, bool fHelp) {
508  if (fHelp || params.size() != 1)
509  throw std::runtime_error(
510  "setmocktime timestamp\n"
511  "\nSet the local time to given timestamp (-regtest only)\n"
512  "\nArguments:\n"
513  "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
514  " Pass 0 to go back to using the system time.");
515 
516  if (!Params().MineBlocksOnDemand())
517  throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
518 
519  LOCK(cs_main);
520 
521  RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
522  SetMockTime(params[0].get_int64());
523 
524  return NullUniValue;
525 }
526 
527 void EnableOrDisableLogCategories(UniValue cats, bool enable) {
528  cats = cats.get_array();
529  for (unsigned int i = 0; i < cats.size(); ++i) {
530  std::string cat = cats[i].get_str();
531 
532  bool success;
533  if (enable) {
534  success = g_logger->EnableCategory(cat);
535  } else {
536  success = g_logger->DisableCategory(cat);
537  }
538 
539  if (!success)
540  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
541  }
542 }
543 
544 UniValue logging(const UniValue& params, bool fHelp)
545 {
546  if (fHelp || params.size() > 2) {
547  throw std::runtime_error(
548  "logging [include,...] <exclude>\n"
549  "Gets and sets the logging configuration.\n"
550  "When called without an argument, returns the list of categories that are currently being debug logged.\n"
551  "When called with arguments, adds or removes categories from debug logging.\n"
552  "The valid logging categories are: " + ListLogCategories() + "\n"
553  "libevent logging is configured on startup and cannot be modified by this RPC during runtime."
554  "Arguments:\n"
555  "1. \"include\" (array of strings) add debug logging for these categories.\n"
556  "2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
557  "\nResult: <categories> (string): a list of the logging categories that are active.\n"
558  "\nExamples:\n"
559  + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
560  + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
561  );
562  }
563 
564  uint32_t original_log_categories = g_logger->GetCategoryMask();
565  if (params.size() > 0 && params[0].isArray()) {
566  EnableOrDisableLogCategories(params[0], true);
567  }
568 
569  if (params.size() > 1 && params[1].isArray()) {
570  EnableOrDisableLogCategories(params[1], false);
571  }
572 
573  uint32_t updated_log_categories = g_logger->GetCategoryMask();
574  uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
575 
576  // Update libevent logging if BCLog::LIBEVENT has changed.
577  // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
578  // in which case we should clear the BCLog::LIBEVENT flag.
579  // Throw an error if the user has explicitly asked to change only the libevent
580  // flag and it failed.
581  if (changed_log_categories & BCLog::LIBEVENT) {
584  if (changed_log_categories == BCLog::LIBEVENT) {
585  throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
586  }
587  }
588  }
589 
590  UniValue result(UniValue::VOBJ);
591  std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
592  for (const auto& logCatActive : vLogCatActive) {
593  result.pushKV(logCatActive.category, logCatActive.active);
594  }
595 
596  return result;
597 }
598 
599 #ifdef ENABLE_WALLET
600 UniValue getstakingstatus(const UniValue& params, bool fHelp)
601 {
602  if (fHelp || params.size() != 0)
603  throw std::runtime_error(
604  "getstakingstatus\n"
605  "Returns an object containing various staking information.\n"
606  "\nResult:\n"
607  "{\n"
608  " \"haveconnections\": true|false, (boolean) if network connections are present\n"
609  " \"walletunlocked\": true|false, (boolean) if the wallet is unlocked\n"
610  " \"mintablecoins\": true|false, (boolean) if the wallet has mintable coins\n"
611  " \"enoughcoins\": true|false, (boolean) if available coins are greater than reserve balance\n"
612  " \"masternodes-synced\": true|false, (boolean) if masternode data is synced\n"
613  " \"staking mode\": enabled|disabled, (string) if staking is enabled or disabled\n"
614  " \"staking status\": active|inactive, (string) if staking is active or inactive\n"
615  "}\n"
616  "\nExamples:\n" +
617  HelpExampleCli("getstakingstatus", "") + HelpExampleRpc("getstakingstatus", ""));
618 
619 #ifdef ENABLE_WALLET
621 #else
622  LOCK(cs_main);
623 #endif
624 
625 
627  obj.push_back(Pair("haveconnections", !vNodes.empty()));
628  if (pwalletMain) {
629  obj.push_back(Pair("walletunlocked", !pwalletMain->IsLocked()));
630  obj.push_back(Pair("mintablecoins", pwalletMain->MintableCoins()));
631  obj.push_back(Pair("enoughcoins", nReserveBalance <= pwalletMain->GetBalance()));
632  }
633  obj.push_back(Pair("masternodes-synced", masternodeSync.IsSynced()));
634 
635  bool nStaking = false;
636  if (mapHashedBlocks.count(chainActive.Tip()->nHeight))
637  nStaking = true;
639  nStaking = true;
640  if (pwalletMain->IsLocked()) {
641  obj.push_back(Pair("staking mode", ("disabled")));
642  obj.push_back(Pair("staking status", ("inactive (wallet locked)")));
643  } else {
644  obj.push_back(Pair("staking mode", (pwalletMain->ReadStakingStatus() ? "enabled" : "disabled")));
645  if (vNodes.empty()) {
646  obj.push_back(Pair("staking status", ("inactive (no peer connections)")));
647  } else if (!masternodeSync.IsSynced()) {
648  obj.push_back(Pair("staking status", ("inactive (syncing masternode list)")));
650  obj.push_back(Pair("staking status", ("delayed (waiting for 100 blocks)")));
651  } else if (!pwalletMain->MintableCoins()) {
652  obj.push_back(Pair("staking status", ("inactive (no mintable coins)")));
653  } else {
654  obj.push_back(Pair("staking status", (nStaking ? "active (attempting to mint a block)" : "idle (waiting for next round)")));
655  }
656  }
657  return obj;
658 }
659 #endif // ENABLE_WALLET
CMasternodeSync::sumMasternodeList
int sumMasternodeList
Definition: masternode-sync.h:46
CMasternodeSync::Reset
void Reset()
Definition: masternode-sync.cpp:64
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:183
verifymessage
UniValue verifymessage(const UniValue &params, bool fHelp)
Definition: misc.cpp:460
vNodes
std::vector< CNode * > vNodes
Definition: net.cpp:85
IsMine
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
Definition: wallet_ismine.cpp:30
CWallet::MintableCoins
bool MintableCoins()
Definition: wallet.cpp:2674
minRelayTxFee
CFeeRate minRelayTxFee
Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) We are ~100 times...
Definition: main.cpp:100
proxyType::IsValid
bool IsValid() const
Definition: netbase.h:34
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:21
CMasternodeSync::countBudgetItemProp
int countBudgetItemProp
Definition: masternode-sync.h:53
getversion
UniValue getversion(const UniValue &params, bool fHelp)
Definition: misc.cpp:136
ListActiveLogCategories
std::vector< CLogCategoryActive > ListActiveLogCategories()
Returns a vector of the active log categories.
Definition: logging.cpp:164
SER_GETHASH
@ SER_GETHASH
Definition: serialize.h:161
NET_IPV4
@ NET_IPV4
Definition: netaddress.h:22
CWallet::ReadStakingStatus
bool ReadStakingStatus()
Definition: wallet.cpp:370
CMasternodeSync::RequestedMasternodeAssets
int RequestedMasternodeAssets
Definition: masternode-sync.h:57
BCLog::Logger::WillLogCategory
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:84
CWallet::GetOldestKeyPoolTime
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:4847
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: utilstrencodings.cpp:77
CBitcoinAddress::GetKeyID
bool GetKeyID(CKeyID &keyID) const
Definition: base58.cpp:281
ISMINE_NO
@ ISMINE_NO
Definition: wallet_ismine.h:17
ValueFromAmount
UniValue ValueFromAmount(const CAmount &amount)
Definition: server.cpp:118
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
timedata.h
CBlockIndex::nMoneySupply
int64_t nMoneySupply
Definition: chain.h:223
NullUniValue
const UniValue NullUniValue
Definition: univalue.cpp:78
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:285
CMasternodeSync::lastFailure
int64_t lastFailure
Definition: masternode-sync.h:39
CBitcoinAddress
base58-encoded PRCY addresses.
Definition: base58.h:109
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Ran out of memory during operation.
Definition: protocol.h:45
CMasternodeSync::IsBlockchainSynced
bool IsBlockchainSynced()
Definition: masternode-sync.cpp:32
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
SetMockTime
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:26
CMasternodeSync::lastMasternodeWinner
int64_t lastMasternodeWinner
Definition: masternode-sync.h:37
wallet.h
CMasternodeSync::countMasternodeWinner
int countMasternodeWinner
Definition: masternode-sync.h:52
CMasternodeSync::countBudgetItemFin
int countBudgetItemFin
Definition: masternode-sync.h:54
masternode-sync.h
g_logger
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:28
CMasternodeSync::RequestedMasternodeAttempt
int RequestedMasternodeAttempt
Definition: masternode-sync.h:58
BCLog::Logger::GetCategoryMask
uint32_t GetCategoryMask() const
Definition: logging.h:109
clientversion.h
isminetype
isminetype
IsMine() return codes.
Definition: wallet_ismine.h:16
CKeyID
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
validateaddress
UniValue validateaddress(const UniValue &params, bool fHelp)
Definition: misc.cpp:270
RPCTypeCheck
void RPCTypeCheck(const UniValue &params, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:70
CBase58Data::ToString
std::string ToString() const
Definition: base58.cpp:200
payTxFee
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
proxyType
Definition: netbase.h:28
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:192
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:559
UniValue
Definition: univalue.h:19
CMasternodeSync::sumBudgetItemFin
int sumBudgetItemFin
Definition: masternode-sync.h:49
nWalletUnlockTime
int64_t nWalletUnlockTime
Definition: rpcwallet.cpp:29
DecodeBase64
std::vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
Definition: utilstrencodings.cpp:150
masternodeSync
CMasternodeSync masternodeSync
Definition: masternode-sync.cpp:19
CMasternodeSync::countMasternodeList
int countMasternodeList
Definition: masternode-sync.h:51
UniValue::get_str
const std::string & get_str() const
Definition: univalue.cpp:309
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
prevector::end
iterator end()
Definition: prevector.h:292
TX_MULTISIG
@ TX_MULTISIG
Definition: standard.h:64
GetTxnOutputType
const char * GetTxnOutputType(txnouttype t)
Definition: standard.cpp:20
CMasternodeSync::lastBudgetItem
int64_t lastBudgetItem
Definition: masternode-sync.h:38
UniValue::pushKVs
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:202
IsHex
bool IsHex(const std::string &str)
Definition: utilstrencodings.cpp:68
GetWarnings
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
Definition: main.cpp:5739
UpdateHTTPServerLogging
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:459
GetScriptForMultisig
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Definition: standard.cpp:298
init.h
BCLog::LIBEVENT
@ LIBEVENT
Definition: logging.h:57
univalue.h
CMasternodeSync::sumMasternodeWinner
int sumMasternodeWinner
Definition: masternode-sync.h:47
HexStr
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: utilstrencodings.h:85
CWallet::GetVersion
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.cpp:6238
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:60
BCLog::Logger::EnableCategory
void EnableCategory(LogFlags flag)
Definition: logging.cpp:58
validatestealthaddress
UniValue validatestealthaddress(const UniValue &params, bool fHelp)
Definition: misc.cpp:326
ISMINE_SPENDABLE
@ ISMINE_SPENDABLE
Definition: wallet_ismine.h:20
logging
UniValue logging(const UniValue &params, bool fHelp)
Definition: misc.cpp:544
mapHashedBlocks
std::map< unsigned int, unsigned int > mapHashedBlocks
Definition: main.cpp:69
HelpExampleRpc
std::string HelpExampleRpc(std::string methodname, std::string args)
Definition: server.cpp:607
UniValue::VNUM
@ VNUM
Definition: univalue.h:21
CWallet::GetBalance
CAmount GetBalance()
Definition: wallet.cpp:2243
_createmultisig_redeemScript
CScript _createmultisig_redeemScript(const UniValue &params)
Used by addmultisigaddress / createmultisig:
Definition: misc.cpp:362
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
UniValue::isArray
bool isArray() const
Definition: univalue.h:83
CBasicKeyStore::GetCScript
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const
Definition: keystore.cpp:50
ISMINE_WATCH_ONLY
@ ISMINE_WATCH_ONLY
Indicates that we dont know how to create a scriptSig that would solve this if we were given the appr...
Definition: wallet_ismine.h:19
CMasternodeSync::IsSynced
bool IsSynced()
Definition: masternode-sync.cpp:27
CNoDestination
Definition: standard.h:68
CPubKey::RecoverCompact
bool RecoverCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig)
Recover a public key from a compact signature.
Definition: pubkey.cpp:32
CTxDestination
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:81
createmultisig
UniValue createmultisig(const UniValue &params, bool fHelp)
Definition: misc.cpp:419
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
getinfo
UniValue getinfo(const UniValue &params, bool fHelp)
Definition: misc.cpp:45
CMasternodeSync::lastMasternodeList
int64_t lastMasternodeList
Definition: masternode-sync.h:36
CMasternodeSync::nCountFailures
int nCountFailures
Definition: masternode-sync.h:40
HelpExampleCli
std::string HelpExampleCli(std::string methodname, std::string args)
Definition: server.cpp:603
RPC_INVALID_ADDRESS_OR_KEY
@ RPC_INVALID_ADDRESS_OR_KEY
Unexpected type was passed as parameter.
Definition: protocol.h:43
CPubKey::IsCompressed
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:168
ListLogCategories
std::string ListLogCategories()
Returns a string with the supported log categories.
Definition: logging.cpp:149
nLastCoinStakeSearchInterval
int64_t nLastCoinStakeSearchInterval
Definition: miner.cpp:67
CWallet::DecodeStealthAddress
static bool DecodeStealthAddress(const std::string &stealth, CPubKey &pubViewKey, CPubKey &pubSpendKey, bool &hasPaymentID, uint64_t &paymentID)
Definition: wallet.cpp:6522
strprintf
#define strprintf
Definition: tinyformat.h:1056
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
EnsureWallet
void EnsureWallet()
Definition: rpcwallet.cpp:37
UniValue::get_int
int get_int() const
Definition: univalue.cpp:316
ON
@ ON
Definition: wallet.h:236
main.h
LOCK
#define LOCK(cs)
Definition: sync.h:182
CWallet::GetPubKey
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
GetPubKey implementation that also checks the mapHdPubKeys.
Definition: wallet.cpp:6894
CHashWriter
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:259
prevector::size
size_type size() const
Definition: prevector.h:282
prevector::begin
iterator begin()
Definition: prevector.h:290
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:173
strMessageMagic
const std::string strMessageMagic
Definition: main.cpp:119
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
CPubKey::IsFullyValid
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:54
GetProxy
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:558
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:301
setmocktime
UniValue setmocktime(const UniValue &params, bool fHelp)
Definition: misc.cpp:507
base58.h
CWallet::combineMode
CombineMode combineMode
Definition: wallet.h:365
UniValue::size
size_t size() const
Definition: univalue.h:69
CCryptoKeyStore::IsCrypted
bool IsCrypted() const
Definition: crypter.h:154
netbase.h
walletdb.h
CChain::Tip
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:596
txnouttype
txnouttype
Definition: standard.h:57
httpserver.h
RPC_TYPE_ERROR
@ RPC_TYPE_ERROR
Server is in safe mode, and command is not allowed in safe mode.
Definition: protocol.h:42
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags flag)
Definition: logging.cpp:71
EnableOrDisableLogCategories
void EnableOrDisableLogCategories(UniValue cats, bool enable)
Definition: misc.cpp:527
mnsync
UniValue mnsync(const UniValue &params, bool fHelp)
Definition: misc.cpp:154
GetTimeOffset
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are:
Definition: timedata.cpp:24
UniValue::get_array
const UniValue & get_array() const
Definition: univalue.cpp:353
UniValue::VARR
@ VARR
Definition: univalue.h:21
CHashWriter::GetHash
uint256 GetHash()
Definition: hash.h:277
CBitcoinAddress::IsValid
bool IsValid() const
Definition: base58.cpp:254
server.h
net.h
ExtractDestinations
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:223
CScriptID
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:20
CMasternodeSync::sumBudgetItemProp
int sumBudgetItemProp
Definition: masternode-sync.h:48
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Definition: amount.h:50
CBitcoinAddress::Get
CTxDestination Get() const
Definition: base58.cpp:267
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
getstakingstatus
UniValue getstakingstatus(const UniValue &params, bool fHelp)
CWallet::mapAddressBook
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:354
CCryptoKeyStore::IsLocked
bool IsLocked() const
Definition: crypter.h:159
proxyType::proxy
CService proxy
Definition: netbase.h:36
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:143
GetDifficulty
double GetDifficulty(const CBlockIndex *blockindex=NULL)
Definition: blockchain.cpp:39