Fabcoin Core  0.16.2
P2P Digital Currency
misc.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core 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 <base58.h>
7 #include <chain.h>
8 #include <clientversion.h>
9 #include <core_io.h>
10 #include <init.h>
11 #include <validation.h>
12 #include <httpserver.h>
13 #include <net.h>
14 #include <netbase.h>
15 #include <rpc/blockchain.h>
16 #include <rpc/server.h>
17 #include <timedata.h>
18 #include <util.h>
19 #include <utilstrencodings.h>
20 #ifdef ENABLE_WALLET
21 #include <wallet/rpcwallet.h>
22 #include <wallet/wallet.h>
23 #include <wallet/walletdb.h>
24 #endif
25 #include <warnings.h>
26 
27 #include <stdint.h>
28 #ifdef HAVE_MALLOC_INFO
29 #include <malloc.h>
30 #endif
31 
32 #include <univalue.h>
33 
48 {
49  if (request.fHelp || request.params.size() != 0)
50  throw std::runtime_error(
51  "getinfo\n"
52  "\nDEPRECATED. Returns an object containing various state info.\n"
53  "\nResult:\n"
54  "{\n"
55  " \"deprecation-warning\": \"...\" (string) warning that the getinfo command is deprecated and will be removed in 0.16\n"
56  " \"version\": xxxxx, (numeric) the server version\n"
57  " \"protocolversion\": xxxxx, (numeric) the protocol version\n"
58  " \"walletversion\": xxxxx, (numeric) the wallet version\n"
59  " \"balance\": xxxxxxx, (numeric) the total fabcoin balance of the wallet\n"
60  " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
61  " \"timeoffset\": xxxxx, (numeric) the time offset\n"
62  " \"connections\": xxxxx, (numeric) the number of connections\n"
63  " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
64  " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
65  " \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
66  " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
67  " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
68  " \"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"
69  " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in " + CURRENCY_UNIT + "/kB\n"
70  " \"relayfee\": x.xxxx, (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
71  " \"errors\": \"...\" (string) any error messages\n"
72  "}\n"
73  "\nExamples:\n"
74  + HelpExampleCli("getinfo", "")
75  + HelpExampleRpc("getinfo", "")
76  );
77 
78 #ifdef ENABLE_WALLET
79  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
80 
81  LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
82 #else
83  LOCK(cs_main);
84 #endif
85 
86  proxyType proxy;
87  GetProxy(NET_IPV4, proxy);
88 
90  obj.push_back(Pair("deprecation-warning", "WARNING: getinfo is deprecated and will be fully removed in 0.16."
91  " Projects should transition to using getblockchaininfo, getnetworkinfo, and getwalletinfo before upgrading to 0.16"));
93  obj.push_back(Pair("version", CLIENT_VERSION));
94  obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
95 #ifdef ENABLE_WALLET
96  if (pwallet) {
97  obj.push_back(Pair("walletversion", pwallet->GetVersion()));
98  obj.push_back(Pair("balance", ValueFromAmount(pwallet->GetBalance())));
99  }
100 #endif
101  obj.push_back(Pair("blocks", (int)chainActive.Height()));
102  obj.push_back(Pair("timeoffset", GetTimeOffset()));
103  if(g_connman)
104  obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
105  obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
106  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
107  obj.push_back(Pair("testnet", Params().NetworkIDString() == CBaseChainParams::TESTNET));
108 #ifdef ENABLE_WALLET
109  if (pwallet) {
110  obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
111  obj.push_back(Pair("keypoolsize", (int)pwallet->GetKeyPoolSize()));
112  }
113  if (pwallet && pwallet->IsCrypted()) {
114  obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
115  }
116  obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
117 #endif
118  obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
119  obj.push_back(Pair("errors", GetWarnings("statusbar")));
120  return obj;
121 }
122 
123 #ifdef ENABLE_WALLET
124 class DescribeAddressVisitor : public boost::static_visitor<UniValue>
125 {
126 public:
127  CWallet * const pwallet;
128 
129  DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
130 
131  UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
132 
133  UniValue operator()(const CKeyID &keyID) const {
135  CPubKey vchPubKey;
136  obj.push_back(Pair("isscript", false));
137  if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
138  obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
139  obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
140  }
141  return obj;
142  }
143 
144  UniValue operator()(const CScriptID &scriptID) const {
146  CScript subscript;
147  obj.push_back(Pair("isscript", true));
148  if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
149  std::vector<CTxDestination> addresses;
150  txnouttype whichType;
151  int nRequired;
152  ExtractDestinations(subscript, whichType, addresses, nRequired);
153  obj.push_back(Pair("script", GetTxnOutputType(whichType)));
154  obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
156  for (const CTxDestination& addr : addresses)
157  a.push_back(CFabcoinAddress(addr).ToString());
158  obj.push_back(Pair("addresses", a));
159  if (whichType == TX_MULTISIG)
160  obj.push_back(Pair("sigsrequired", nRequired));
161  }
162  return obj;
163  }
164 };
165 #endif
166 
168 {
169  if (request.fHelp || request.params.size() != 1)
170  throw std::runtime_error(
171  "validateaddress \"address\"\n"
172  "\nReturn information about the given fabcoin address.\n"
173  "\nArguments:\n"
174  "1. \"address\" (string, required) The fabcoin address to validate\n"
175  "\nResult:\n"
176  "{\n"
177  " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
178  " \"address\" : \"address\", (string) The fabcoin address validated\n"
179  " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
180  " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
181  " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
182  " \"isscript\" : true|false, (boolean) If the key is a script\n"
183  " \"script\" : \"type\" (string, optional) The output script type. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash\n"
184  " \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n"
185  " \"addresses\" (string, optional) Array of addresses associated with the known redeemscript\n"
186  " [\n"
187  " \"address\"\n"
188  " ,...\n"
189  " ]\n"
190  " \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output\n"
191  " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
192  " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
193  " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
194  " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
195  " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
196  " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n"
197  "}\n"
198  "\nExamples:\n"
199  + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
200  + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
201  );
202 
203 #ifdef ENABLE_WALLET
204  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
205 
206  LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
207 #else
208  LOCK(cs_main);
209 #endif
210 
211  CFabcoinAddress address(request.params[0].get_str());
212  bool isValid = address.IsValid();
213 
215  ret.push_back(Pair("isvalid", isValid));
216  if (isValid)
217  {
218  CTxDestination dest = address.Get();
219  std::string currentAddress = address.ToString();
220  ret.push_back(Pair("address", currentAddress));
221 
222  CScript scriptPubKey = GetScriptForDestination(dest);
223  ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
224 
225 #ifdef ENABLE_WALLET
226  isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO;
227  ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE)));
228  ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)));
229  UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest);
230  ret.pushKVs(detail);
231  if (pwallet && pwallet->mapAddressBook.count(dest)) {
232  ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name));
233  }
234  CKeyID keyID;
235  if (pwallet) {
236  const auto& meta = pwallet->mapKeyMetadata;
237  auto it = address.GetKeyID(keyID) ? meta.find(keyID) : meta.end();
238  if (it == meta.end()) {
239  it = meta.find(CScriptID(scriptPubKey));
240  }
241  if (it != meta.end()) {
242  ret.push_back(Pair("timestamp", it->second.nCreateTime));
243  if (!it->second.hdKeypath.empty()) {
244  ret.push_back(Pair("hdkeypath", it->second.hdKeypath));
245  ret.push_back(Pair("hdmasterkeyid", it->second.hdMasterKeyID.GetHex()));
246  }
247  }
248  }
249 #endif
250  }
251  return ret;
252 }
253 
254 // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around
255 class CWallet;
256 
260 CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params)
261 {
262  int nRequired = params[0].get_int();
263  const UniValue& keys = params[1].get_array();
264 
265  // Gather public keys
266  if (nRequired < 1)
267  throw std::runtime_error("a multisignature address must require at least one key to redeem");
268  if ((int)keys.size() < nRequired)
269  throw std::runtime_error(
270  strprintf("not enough keys supplied "
271  "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
272  if (keys.size() > 16)
273  throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
274  std::vector<CPubKey> pubkeys;
275  pubkeys.resize(keys.size());
276  for (unsigned int i = 0; i < keys.size(); i++)
277  {
278  const std::string& ks = keys[i].get_str();
279 #ifdef ENABLE_WALLET
280  // Case 1: Fabcoin address and we have full public key:
282  if (pwallet && address.IsValid()) {
283  CKeyID keyID;
284  if (!address.GetKeyID(keyID))
285  throw std::runtime_error(
286  strprintf("%s does not refer to a key",ks));
287  CPubKey vchPubKey;
288  if (!pwallet->GetPubKey(keyID, vchPubKey)) {
289  throw std::runtime_error(
290  strprintf("no full public key for address %s",ks));
291  }
292  if (!vchPubKey.IsFullyValid())
293  throw std::runtime_error(" Invalid public key: "+ks);
294  pubkeys[i] = vchPubKey;
295  }
296 
297  // Case 2: hex public key
298  else
299 #endif
300  if (IsHex(ks))
301  {
302  CPubKey vchPubKey(ParseHex(ks));
303  if (!vchPubKey.IsFullyValid())
304  throw std::runtime_error(" Invalid public key: "+ks);
305  pubkeys[i] = vchPubKey;
306  }
307  else
308  {
309  throw std::runtime_error(" Invalid public key: "+ks);
310  }
311  }
312  CScript result = GetScriptForMultisig(nRequired, pubkeys);
313 
314  if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
315  throw std::runtime_error(
316  strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
317 
318  return result;
319 }
320 
322 {
323 #ifdef ENABLE_WALLET
324  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
325 #else
326  CWallet * const pwallet = nullptr;
327 #endif
328 
329  if (request.fHelp || request.params.size() < 2 || request.params.size() > 2)
330  {
331  std::string msg = "createmultisig nrequired [\"key\",...]\n"
332  "\nCreates a multi-signature address with n signature of m keys required.\n"
333  "It returns a json object with the address and redeemScript.\n"
334 
335  "\nArguments:\n"
336  "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
337  "2. \"keys\" (string, required) A json array of keys which are fabcoin addresses or hex-encoded public keys\n"
338  " [\n"
339  " \"key\" (string) fabcoin address or hex-encoded public key\n"
340  " ,...\n"
341  " ]\n"
342 
343  "\nResult:\n"
344  "{\n"
345  " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
346  " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
347  "}\n"
348 
349  "\nExamples:\n"
350  "\nCreate a multisig address from 2 addresses\n"
351  + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
352  "\nAs a json rpc call\n"
353  + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
354  ;
355  throw std::runtime_error(msg);
356  }
357 
358  // Construct using pay-to-script-hash:
359  CScript inner = _createmultisig_redeemScript(pwallet, request.params);
360  CScriptID innerID(inner);
361  CFabcoinAddress address(innerID);
362 
363  UniValue result(UniValue::VOBJ);
364  result.push_back(Pair("address", address.ToString()));
365  result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
366 
367  return result;
368 }
369 
371 {
372  if (request.fHelp || request.params.size() != 3)
373  throw std::runtime_error(
374  "verifymessage \"address\" \"signature\" \"message\"\n"
375  "\nVerify a signed message\n"
376  "\nArguments:\n"
377  "1. \"address\" (string, required) The fabcoin address to use for the signature.\n"
378  "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
379  "3. \"message\" (string, required) The message that was signed.\n"
380  "\nResult:\n"
381  "true|false (boolean) If the signature is verified or not.\n"
382  "\nExamples:\n"
383  "\nUnlock the wallet for 30 seconds\n"
384  + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
385  "\nCreate the signature\n"
386  + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
387  "\nVerify the signature\n"
388  + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
389  "\nAs json rpc\n"
390  + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"")
391  );
392 
393  LOCK(cs_main);
394 
395  std::string strAddress = request.params[0].get_str();
396  std::string strSign = request.params[1].get_str();
397  std::string strMessage = request.params[2].get_str();
398 
399  CFabcoinAddress addr(strAddress);
400  if (!addr.IsValid())
401  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
402 
403  CKeyID keyID;
404  if (!addr.GetKeyID(keyID))
405  throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
406 
407  bool fInvalid = false;
408  std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
409 
410  if (fInvalid)
411  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
412 
413  CHashWriter ss(SER_GETHASH, 0);
414  ss << strMessageMagic;
415  ss << strMessage;
416 
417  CPubKey pubkey;
418  if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
419  return false;
420 
421  return (pubkey.GetID() == keyID);
422 }
423 
425 {
426  if (request.fHelp || request.params.size() != 2)
427  throw std::runtime_error(
428  "signmessagewithprivkey \"privkey\" \"message\"\n"
429  "\nSign a message with the private key of an address\n"
430  "\nArguments:\n"
431  "1. \"privkey\" (string, required) The private key to sign the message with.\n"
432  "2. \"message\" (string, required) The message to create a signature of.\n"
433  "\nResult:\n"
434  "\"signature\" (string) The signature of the message encoded in base 64\n"
435  "\nExamples:\n"
436  "\nCreate the signature\n"
437  + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
438  "\nVerify the signature\n"
439  + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
440  "\nAs json rpc\n"
441  + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
442  );
443 
444  std::string strPrivkey = request.params[0].get_str();
445  std::string strMessage = request.params[1].get_str();
446 
447  CFabcoinSecret vchSecret;
448  bool fGood = vchSecret.SetString(strPrivkey);
449  if (!fGood)
450  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
451  CKey key = vchSecret.GetKey();
452  if (!key.IsValid())
453  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
454 
455  CHashWriter ss(SER_GETHASH, 0);
456  ss << strMessageMagic;
457  ss << strMessage;
458 
459  std::vector<unsigned char> vchSig;
460  if (!key.SignCompact(ss.GetHash(), vchSig))
461  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
462 
463  return EncodeBase64(&vchSig[0], vchSig.size());
464 }
465 
467 {
468  if (request.fHelp || request.params.size() != 1)
469  throw std::runtime_error(
470  "setmocktime timestamp\n"
471  "\nSet the local time to given timestamp (-regtest only)\n"
472  "\nArguments:\n"
473  "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
474  " Pass 0 to go back to using the system time."
475  );
476 
477  if (!Params().MineBlocksOnDemand())
478  throw std::runtime_error("setmocktime for regression testing (-regtest mode) only");
479 
480  // For now, don't change mocktime if we're in the middle of validation, as
481  // this could have an effect on mempool time-based eviction, as well as
482  // IsCurrentForFeeEstimation() and IsInitialBlockDownload().
483  // TODO: figure out the right way to synchronize around mocktime, and
484  // ensure all call sites of GetTime() are accessing this safely.
485  LOCK(cs_main);
486 
487  RPCTypeCheck(request.params, {UniValue::VNUM});
488  SetMockTime(request.params[0].get_int64());
489 
490  return NullUniValue;
491 }
492 
493 static UniValue RPCLockedMemoryInfo()
494 {
497  obj.push_back(Pair("used", uint64_t(stats.used)));
498  obj.push_back(Pair("free", uint64_t(stats.free)));
499  obj.push_back(Pair("total", uint64_t(stats.total)));
500  obj.push_back(Pair("locked", uint64_t(stats.locked)));
501  obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used)));
502  obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free)));
503  return obj;
504 }
505 
506 #ifdef HAVE_MALLOC_INFO
507 static std::string RPCMallocInfo()
508 {
509  char *ptr = nullptr;
510  size_t size = 0;
511  FILE *f = open_memstream(&ptr, &size);
512  if (f) {
513  malloc_info(0, f);
514  fclose(f);
515  if (ptr) {
516  std::string rv(ptr, size);
517  free(ptr);
518  return rv;
519  }
520  }
521  return "";
522 }
523 #endif
524 
526 {
527  /* Please, avoid using the word "pool" here in the RPC interface or help,
528  * as users will undoubtedly confuse it with the other "memory pool"
529  */
530  if (request.fHelp || request.params.size() > 1)
531  throw std::runtime_error(
532  "getmemoryinfo (\"mode\")\n"
533  "Returns an object containing information about memory usage.\n"
534  "Arguments:\n"
535  "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n"
536  " - \"stats\" returns general statistics about memory usage in the daemon.\n"
537  " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n"
538  "\nResult (mode \"stats\"):\n"
539  "{\n"
540  " \"locked\": { (json object) Information about locked memory manager\n"
541  " \"used\": xxxxx, (numeric) Number of bytes used\n"
542  " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n"
543  " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n"
544  " \"locked\": xxxxxx, (numeric) 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.\n"
545  " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n"
546  " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n"
547  " }\n"
548  "}\n"
549  "\nResult (mode \"mallocinfo\"):\n"
550  "\"<malloc version=\"1\">...\"\n"
551  "\nExamples:\n"
552  + HelpExampleCli("getmemoryinfo", "")
553  + HelpExampleRpc("getmemoryinfo", "")
554  );
555 
556  std::string mode = (request.params.size() < 1 || request.params[0].isNull()) ? "stats" : request.params[0].get_str();
557  if (mode == "stats") {
559  obj.push_back(Pair("locked", RPCLockedMemoryInfo()));
560  return obj;
561  } else if (mode == "mallocinfo") {
562 #ifdef HAVE_MALLOC_INFO
563  return RPCMallocInfo();
564 #else
565  throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+");
566 #endif
567  } else {
568  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
569  }
570 }
571 
572 uint32_t getCategoryMask(UniValue cats) {
573  cats = cats.get_array();
574  uint32_t mask = 0;
575  for (unsigned int i = 0; i < cats.size(); ++i) {
576  uint32_t flag = 0;
577  std::string cat = cats[i].get_str();
578  if (!GetLogCategory(&flag, &cat)) {
579  throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
580  }
581  mask |= flag;
582  }
583  return mask;
584 }
585 
587 {
588  if (request.fHelp || request.params.size() > 2) {
589  throw std::runtime_error(
590  "logging [include,...] <exclude>\n"
591  "Gets and sets the logging configuration.\n"
592  "When called without an argument, returns the list of categories that are currently being debug logged.\n"
593  "When called with arguments, adds or removes categories from debug logging.\n"
594  "The valid logging categories are: " + ListLogCategories() + "\n"
595  "libevent logging is configured on startup and cannot be modified by this RPC during runtime."
596  "Arguments:\n"
597  "1. \"include\" (array of strings) add debug logging for these categories.\n"
598  "2. \"exclude\" (array of strings) remove debug logging for these categories.\n"
599  "\nResult: <categories> (string): a list of the logging categories that are active.\n"
600  "\nExamples:\n"
601  + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
602  + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"")
603  );
604  }
605 
606  uint32_t originalLogCategories = logCategories;
607  if (request.params.size() > 0 && request.params[0].isArray()) {
608  logCategories |= getCategoryMask(request.params[0]);
609  }
610 
611  if (request.params.size() > 1 && request.params[1].isArray()) {
612  logCategories &= ~getCategoryMask(request.params[1]);
613  }
614 
615  // Update libevent logging if BCLog::LIBEVENT has changed.
616  // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
617  // in which case we should clear the BCLog::LIBEVENT flag.
618  // Throw an error if the user has explicitly asked to change only the libevent
619  // flag and it failed.
620  uint32_t changedLogCategories = originalLogCategories ^ logCategories;
621  if (changedLogCategories & BCLog::LIBEVENT) {
622  if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
623  logCategories &= ~BCLog::LIBEVENT;
624  if (changedLogCategories == BCLog::LIBEVENT) {
625  throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
626  }
627  }
628  }
629 
630  UniValue result(UniValue::VOBJ);
631  std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories();
632  for (const auto& logCatActive : vLogCatActive) {
633  result.pushKV(logCatActive.category, logCatActive.active);
634  }
635 
636  return result;
637 }
638 
639 UniValue echo(const JSONRPCRequest& request)
640 {
641  if (request.fHelp)
642  throw std::runtime_error(
643  "echo|echojson \"message\" ...\n"
644  "\nSimply echo back the input arguments. This command is for testing.\n"
645  "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in"
646  "fabcoin-cli and the GUI. There is no server-side difference."
647  );
648 
649  return request.params;
650 }
651 
652 static const CRPCCommand commands[] =
653 { // category name actor (function) okSafeMode
654  // --------------------- ------------------------ ----------------------- ----------
655  { "control", "getinfo", &getinfo, true, {} }, /* uses wallet if enabled */
656  { "control", "getmemoryinfo", &getmemoryinfo, true, {"mode"} },
657  { "util", "validateaddress", &validateaddress, true, {"address"} }, /* uses wallet if enabled */
658  { "util", "createmultisig", &createmultisig, true, {"nrequired","keys"} },
659  { "util", "verifymessage", &verifymessage, true, {"address","signature","message"} },
660  { "util", "signmessagewithprivkey", &signmessagewithprivkey, true, {"privkey","message"} },
661 
662  /* Not shown in help */
663  { "hidden", "setmocktime", &setmocktime, true, {"timestamp"}},
664  { "hidden", "echo", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
665  { "hidden", "echojson", &echo, true, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}},
666  { "hidden", "logging", &logging, true, {"include", "exclude"}},
667 };
668 
670 {
671  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
672  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
673 }
int get_int() const
A base58-encoded secret key.
Definition: base58.h:126
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
CAmount GetFeePerK() const
Return the fee in liu for a size of 1000 bytes.
Definition: feerate.h:38
const std::string & get_str() const
std::string ListLogCategories()
Returns a string with the log categories.
Definition: util.cpp:291
size_t size() const
Definition: univalue.h:70
bool IsCrypted() const
Definition: crypter.h:140
bool SetString(const char *pszSecret)
Definition: base58.cpp:317
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:79
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:76
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3524
std::vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
Fabcoin RPC command dispatcher.
Definition: server.h:200
UniValue createmultisig(const JSONRPCRequest &request)
Definition: misc.cpp:321
static LockedPoolManager & Instance()
Return the current instance, or create it once.
Definition: lockedpool.h:213
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:826
CCriticalSection cs_wallet
Definition: wallet.h:748
Definition: util.h:86
#define strprintf
Definition: tinyformat.h:1054
std::string ToStringIPPort() const
Definition: netaddress.cpp:587
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
Definition: keystore.cpp:55
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:29
CCriticalSection cs_main
Definition: validation.cpp:77
base58-encoded Fabcoin addresses.
Definition: base58.h:104
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
evm_mode mode
Definition: SmartVM.cpp:47
bool isArray() const
Definition: univalue.h:85
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey, SigVersion sigversion)
Definition: ismine.cpp:29
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:559
bool IsValid() const
Definition: base58.cpp:247
unsigned int GetKeyPoolSize()
Definition: wallet.h:1075
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index, or the chain tip if not provided...
Definition: blockchain.cpp:105
uint32_t getCategoryMask(UniValue cats)
Definition: misc.cpp:572
std::map< CTxDestination, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:773
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:304
int64_t GetTimeOffset()
"Never go to sea with two chronometers; take one or three." Our three time sources are: ...
Definition: timedata.cpp:29
std::atomic< uint32_t > logCategories
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:148
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:298
const std::string strMessageMagic
Definition: validation.cpp:115
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:59
Invalid, missing or duplicate parameter.
Definition: protocol.h:53
UniValue getmemoryinfo(const JSONRPCRequest &request)
Definition: misc.cpp:525
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Definition: crypter.cpp:260
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:92
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:302
bool IsValid() const
Definition: netbase.h:34
size_type size() const
Definition: prevector.h:282
#define a(i)
UniValue getinfo(const JSONRPCRequest &request)
Definition: misc.cpp:47
iterator end()
Definition: prevector.h:292
#define LOCK2(cs1, cs2)
Definition: sync.h:176
std::string name
Definition: server.h:191
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
int64_t get_int64() const
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:103
UniValue params
Definition: server.h:59
isminetype
IsMine() return codes.
Definition: ismine.h:17
#define LOCK(cs)
Definition: sync.h:175
bool RecoverCompact(const uint256 &hash, const std::vector< unsigned char > &vchSig)
Recover a public key from a compact signature.
Definition: pubkey.cpp:184
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1090
An encapsulated public key.
Definition: pubkey.h:39
CAmount GetBalance() const
Definition: wallet.cpp:2019
bool IsHex(const std::string &str)
Unexpected type was passed as parameter.
Definition: protocol.h:50
const char * GetTxnOutputType(txnouttype t)
Definition: standard.cpp:25
UniValue logging(const JSONRPCRequest &request)
Definition: misc.cpp:586
std::string ToString() const
Definition: base58.cpp:193
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:135
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:40
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
Invalid address or key.
Definition: protocol.h:51
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:370
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:554
UniValue setmocktime(const JSONRPCRequest &request)
Definition: misc.cpp:466
CKey GetKey()
Definition: base58.cpp:302
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:171
uint256 GetHash()
Definition: hash.h:149
bool fHelp
Definition: server.h:60
txnouttype
Definition: standard.h:51
bool GetKeyID(CKeyID &keyID) const
Definition: base58.cpp:274
#define f(x)
Definition: gost.cpp:57
UniValue validateaddress(const JSONRPCRequest &request)
Definition: misc.cpp:167
CService proxy
Definition: netbase.h:36
void RegisterMiscRPCCommands(CRPCTable &t)
Register miscellaneous RPC commands.
Definition: misc.cpp:669
UniValue signmessagewithprivkey(const JSONRPCRequest &request)
Definition: misc.cpp:424
UniValue verifymessage(const JSONRPCRequest &request)
Definition: misc.cpp:370
#define ARRAYLEN(array)
CScript _createmultisig_redeemScript(CWallet *const pwallet, const UniValue &params)
Used by addmultisigaddress / createmultisig:
Definition: misc.cpp:260
const UniValue & get_array() const
uint8_t const size_t const size
Definition: sha3.h:20
bool SignCompact(const uint256 &hash, std::vector< unsigned char > &vchSig) const
Create a compact signature (65 bytes), which allows reconstructing the used public key...
Definition: key.cpp:189
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
N diff(N const &_a, N const &_b)
Definition: Common.h:212
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
Definition: pubkey.cpp:204
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:672
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:75
const UniValue NullUniValue
Definition: univalue.cpp:15
CWallet * GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: rpcwallet.cpp:41
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
iterator begin()
Definition: prevector.h:290
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:28
static const std::string TESTNET
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:130
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Definition: standard.cpp:383
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:556
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
An encapsulated private key.
Definition: key.h:35
bool GetLogCategory(uint32_t *f, const std::string *str)
Return true if str parses as a log category and set the flags in f.
Definition: util.cpp:274
bool isNull() const
Definition: univalue.h:79
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:146
Config::Pair_type Pair
UniValue echo(const JSONRPCRequest &request)
Definition: misc.cpp:639
void mine(Client &c, int numBlocks)
Definition: TestHelper.cpp:39
std::vector< CLogCategoryActive > ListActiveLogCategories()
Returns a vector of the active log categories.
Definition: util.cpp:306
int64_t nRelockTime
Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
Definition: wallet.h:922
std::string EncodeBase64(const unsigned char *pch, size_t len)
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:437
Memory statistics.
Definition: lockedpool.h:136
std::vector< unsigned char > ParseHex(const char *psz)