1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/asio.hpp>
8 #include <boost/iostreams/concepts.hpp>
9 #include <boost/iostreams/stream.hpp>
11 #include <boost/asio/ssl.hpp>
12 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
14 #include "json/json_spirit_reader_template.h"
15 #include "json/json_spirit_writer_template.h"
16 #include "json/json_spirit_utils.h"
17 #define printf OutputDebugStringF
18 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
19 // precompiled in headers.h. The problem might be when the pch file goes over
20 // a certain size around 145MB. If we need access to json_spirit outside this
21 // file, we could use the compiled json_spirit option.
23 using namespace boost::asio;
24 using namespace json_spirit;
26 void ThreadRPCServer2(void* parg);
27 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
28 extern map<string, rpcfn_type> mapCallTable;
31 Object JSONRPCError(int code, const string& message)
34 error.push_back(Pair("code", code));
35 error.push_back(Pair("message", message));
40 void PrintConsole(const char* format, ...)
43 int limit = sizeof(buffer);
45 va_start(arg_ptr, format);
46 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
48 if (ret < 0 || ret >= limit)
53 #if defined(__WXMSW__) && defined(GUI)
54 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
56 fprintf(stdout, "%s", buffer);
61 int64 AmountFromValue(const Value& value)
63 double dAmount = value.get_real();
64 if (dAmount <= 0.0 || dAmount > 21000000.0)
65 throw JSONRPCError(-3, "Invalid amount");
66 int64 nAmount = roundint64(dAmount * 100.00) * CENT;
67 if (!MoneyRange(nAmount))
68 throw JSONRPCError(-3, "Invalid amount");
78 /// Note: This interface may still be subject to change.
82 Value help(const Array& params, bool fHelp)
84 if (fHelp || params.size() > 1)
87 "List commands, or get help for a command.");
90 if (params.size() > 0)
91 strCommand = params[0].get_str();
94 set<rpcfn_type> setDone;
95 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
97 string strMethod = (*mi).first;
98 // We already filter duplicates, but these deprecated screw up the sort order
99 if (strMethod == "getamountreceived" ||
100 strMethod == "getallreceived" ||
101 (strMethod.find("label") != string::npos))
103 if (strCommand != "" && strMethod != strCommand)
108 rpcfn_type pfn = (*mi).second;
109 if (setDone.insert(pfn).second)
110 (*pfn)(params, true);
112 catch (std::exception& e)
114 // Help text is returned in an exception
115 string strHelp = string(e.what());
116 if (strCommand == "")
117 if (strHelp.find('\n') != -1)
118 strHelp = strHelp.substr(0, strHelp.find('\n'));
119 strRet += strHelp + "\n";
123 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
124 strRet = strRet.substr(0,strRet.size()-1);
129 Value stop(const Array& params, bool fHelp)
131 if (fHelp || params.size() != 0)
134 "Stop bitcoin server.");
136 // Shutdown will take long enough that the response should get back
137 CreateThread(Shutdown, NULL);
138 return "bitcoin server stopping";
142 Value getblockcount(const Array& params, bool fHelp)
144 if (fHelp || params.size() != 0)
147 "Returns the number of blocks in the longest block chain.");
153 Value getblocknumber(const Array& params, bool fHelp)
155 if (fHelp || params.size() != 0)
158 "Returns the block number of the latest block in the longest block chain.");
164 Value getconnectioncount(const Array& params, bool fHelp)
166 if (fHelp || params.size() != 0)
168 "getconnectioncount\n"
169 "Returns the number of connections to other nodes.");
171 return (int)vNodes.size();
175 double GetDifficulty()
177 // Floating point number that is a multiple of the minimum difficulty,
178 // minimum difficulty = 1.0.
179 if (pindexBest == NULL)
181 int nShift = 256 - 32 - 31; // to fit in a uint
182 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
183 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
184 return dMinimum / dCurrently;
187 Value getdifficulty(const Array& params, bool fHelp)
189 if (fHelp || params.size() != 0)
192 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
194 return GetDifficulty();
198 Value getgenerate(const Array& params, bool fHelp)
200 if (fHelp || params.size() != 0)
203 "Returns true or false.");
205 return (bool)fGenerateBitcoins;
209 Value setgenerate(const Array& params, bool fHelp)
211 if (fHelp || params.size() < 1 || params.size() > 2)
213 "setgenerate <generate> [genproclimit]\n"
214 "<generate> is true or false to turn generation on or off.\n"
215 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
217 bool fGenerate = true;
218 if (params.size() > 0)
219 fGenerate = params[0].get_bool();
221 if (params.size() > 1)
223 int nGenProcLimit = params[1].get_int();
224 fLimitProcessors = (nGenProcLimit != -1);
225 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
226 if (nGenProcLimit != -1)
227 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
230 GenerateBitcoins(fGenerate);
235 Value gethashespersec(const Array& params, bool fHelp)
237 if (fHelp || params.size() != 0)
240 "Returns a recent hashes per second performance measurement while generating.");
242 if (GetTimeMillis() - nHPSTimerStart > 8000)
243 return (boost::int64_t)0;
244 return (boost::int64_t)dHashesPerSec;
248 Value getinfo(const Array& params, bool fHelp)
250 if (fHelp || params.size() != 0)
253 "Returns an object containing various state info.");
256 obj.push_back(Pair("version", (int)VERSION));
257 obj.push_back(Pair("balance", (double)GetBalance() / (double)COIN));
258 obj.push_back(Pair("blocks", (int)nBestHeight));
259 obj.push_back(Pair("connections", (int)vNodes.size()));
260 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
261 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
262 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
263 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
264 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
265 obj.push_back(Pair("testnet", fTestNet));
266 obj.push_back(Pair("keypoololdest", (boost::int64_t)CWalletDB().GetOldestKeyPoolTime()));
267 obj.push_back(Pair("paytxfee", (double)nTransactionFee / (double)COIN));
268 obj.push_back(Pair("errors", GetWarnings("statusbar")));
273 Value getnewaddress(const Array& params, bool fHelp)
275 if (fHelp || params.size() > 1)
277 "getnewaddress [account]\n"
278 "Returns a new bitcoin address for receiving payments. "
279 "If [account] is specified (recommended), it is added to the address book "
280 "so payments received with the address will be credited to [account].");
282 // Parse the account first so we don't generate a key if there's an error
284 if (params.size() > 0)
285 strAccount = params[0].get_str();
287 // Generate a new key that is added to wallet
288 string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());
290 SetAddressBookName(strAddress, strAccount);
295 Value getaccountaddress(const Array& params, bool fHelp)
297 if (fHelp || params.size() != 1)
299 "getaccountaddress <account>\n"
300 "Returns the current bitcoin address for receiving payments to this account.");
302 // Parse the account first so we don't generate a key if there's an error
303 string strAccount = params[0].get_str();
305 CRITICAL_BLOCK(cs_mapWallet)
311 walletdb.ReadAccount(strAccount, account);
313 // Check if the current key has been used
314 if (!account.vchPubKey.empty())
316 CScript scriptPubKey;
317 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
318 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
319 it != mapWallet.end() && !account.vchPubKey.empty();
322 const CWalletTx& wtx = (*it).second;
323 foreach(const CTxOut& txout, wtx.vout)
324 if (txout.scriptPubKey == scriptPubKey)
325 account.vchPubKey.clear();
329 // Generate a new key
330 if (account.vchPubKey.empty())
332 account.vchPubKey = CWalletDB().GetKeyFromKeyPool();
333 string strAddress = PubKeyToAddress(account.vchPubKey);
334 SetAddressBookName(strAddress, strAccount);
335 walletdb.WriteAccount(strAccount, account);
338 walletdb.TxnCommit();
339 return PubKeyToAddress(account.vchPubKey);
344 Value setaccount(const Array& params, bool fHelp)
346 if (fHelp || params.size() < 1 || params.size() > 2)
348 "setaccount <bitcoinaddress> <account>\n"
349 "Sets the account associated with the given address.");
351 string strAddress = params[0].get_str();
353 if (params.size() > 1)
354 strAccount = params[1].get_str();
356 SetAddressBookName(strAddress, strAccount);
361 Value getaccount(const Array& params, bool fHelp)
363 if (fHelp || params.size() != 1)
365 "getaccount <bitcoinaddress>\n"
366 "Returns the account associated with the given address.");
368 string strAddress = params[0].get_str();
371 CRITICAL_BLOCK(cs_mapAddressBook)
373 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
374 if (mi != mapAddressBook.end() && !(*mi).second.empty())
375 strAccount = (*mi).second;
381 Value getaddressesbyaccount(const Array& params, bool fHelp)
383 if (fHelp || params.size() != 1)
385 "getaddressesbyaccount <account>\n"
386 "Returns the list of addresses for the given account.");
388 string strAccount = params[0].get_str();
390 // Find all addresses that have the given account
392 CRITICAL_BLOCK(cs_mapAddressBook)
394 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
396 const string& strAddress = item.first;
397 const string& strName = item.second;
398 if (strName == strAccount)
400 // We're only adding valid bitcoin addresses and not ip addresses
401 CScript scriptPubKey;
402 if (scriptPubKey.SetBitcoinAddress(strAddress))
403 ret.push_back(strAddress);
410 Value sendtoaddress(const Array& params, bool fHelp)
412 if (fHelp || params.size() < 2 || params.size() > 4)
414 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
415 "<amount> is a real and is rounded to the nearest 0.01");
417 string strAddress = params[0].get_str();
420 int64 nAmount = AmountFromValue(params[1]);
424 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
425 wtx.mapValue["message"] = params[2].get_str();
426 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
427 wtx.mapValue["to"] = params[3].get_str();
429 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
431 throw JSONRPCError(-4, strError);
432 return wtx.GetHash().GetHex();
436 Value listtransactions(const Array& params, bool fHelp)
438 if (fHelp || params.size() > 2)
440 "listtransactions [count=10] [includegenerated=false]\n"
441 "Returns up to [count] most recent transactions.");
444 if (params.size() > 0)
445 nCount = params[0].get_int64();
446 bool fGenerated = false;
447 if (params.size() > 1)
448 fGenerated = params[1].get_bool();
452 ret.push_back("not implemented yet");
457 Value getreceivedbyaddress(const Array& params, bool fHelp)
459 if (fHelp || params.size() < 1 || params.size() > 2)
461 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
462 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
465 string strAddress = params[0].get_str();
466 CScript scriptPubKey;
467 if (!scriptPubKey.SetBitcoinAddress(strAddress))
468 throw JSONRPCError(-5, "Invalid bitcoin address");
469 if (!IsMine(scriptPubKey))
472 // Minimum confirmations
474 if (params.size() > 1)
475 nMinDepth = params[1].get_int();
479 CRITICAL_BLOCK(cs_mapWallet)
481 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
483 const CWalletTx& wtx = (*it).second;
484 if (wtx.IsCoinBase() || !wtx.IsFinal())
487 foreach(const CTxOut& txout, wtx.vout)
488 if (txout.scriptPubKey == scriptPubKey)
489 if (wtx.GetDepthInMainChain() >= nMinDepth)
490 nAmount += txout.nValue;
494 return (double)nAmount / (double)COIN;
498 Value getreceivedbyaccount(const Array& params, bool fHelp)
500 if (fHelp || params.size() < 1 || params.size() > 2)
502 "getreceivedbyaccount <account> [minconf=1]\n"
503 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
505 // Minimum confirmations
507 if (params.size() > 1)
508 nMinDepth = params[1].get_int();
510 // Get the set of pub keys that have the label
511 string strAccount = params[0].get_str();
512 set<CScript> setPubKey;
513 CRITICAL_BLOCK(cs_mapAddressBook)
515 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
517 const string& strAddress = item.first;
518 const string& strName = item.second;
519 if (strName == strAccount)
521 // We're only counting our own valid bitcoin addresses and not ip addresses
522 CScript scriptPubKey;
523 if (scriptPubKey.SetBitcoinAddress(strAddress))
524 if (IsMine(scriptPubKey))
525 setPubKey.insert(scriptPubKey);
532 CRITICAL_BLOCK(cs_mapWallet)
534 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
536 const CWalletTx& wtx = (*it).second;
537 if (wtx.IsCoinBase() || !wtx.IsFinal())
540 foreach(const CTxOut& txout, wtx.vout)
541 if (setPubKey.count(txout.scriptPubKey))
542 if (wtx.GetDepthInMainChain() >= nMinDepth)
543 nAmount += txout.nValue;
547 return (double)nAmount / (double)COIN;
551 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
553 // Get the set of pub keys that have the account
554 set<CScript> setPubKey;
555 CRITICAL_BLOCK(cs_mapAddressBook)
557 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
559 const string& strAddress = item.first;
560 const string& strName = item.second;
561 if (strName == strAccount)
563 // We're only counting our own valid bitcoin addresses and not ip addresses
564 CScript scriptPubKey;
565 if (scriptPubKey.SetBitcoinAddress(strAddress))
566 if (IsMine(scriptPubKey))
567 setPubKey.insert(scriptPubKey);
573 CRITICAL_BLOCK(cs_mapWallet)
575 // Tally wallet transactions
576 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
578 const CWalletTx& wtx = (*it).second;
582 // Count generated blocks to account ""
583 if (wtx.IsCoinBase() && strAccount == "" && wtx.GetBlocksToMaturity() == 0)
585 nBalance += wtx.GetCredit();
590 foreach(const CTxOut& txout, wtx.vout)
591 if (setPubKey.count(txout.scriptPubKey))
592 if (wtx.GetDepthInMainChain() >= nMinDepth)
593 nBalance += txout.nValue;
596 if (wtx.strFromAccount == strAccount)
598 int64 nNet = wtx.GetCredit() - wtx.GetDebit();
604 // Tally internal accounting entries
605 nBalance += walletdb.GetAccountCreditDebit(strAccount);
611 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
614 return GetAccountBalance(walletdb, strAccount, nMinDepth);
618 Value getbalance(const Array& params, bool fHelp)
620 if (fHelp || params.size() < 0 || params.size() > 2)
622 "getbalance [account] [minconf=1]\n"
623 "If [account] is not specified, returns the server's total available balance.\n"
624 "If [account] is specified, returns the balance in the account.");
626 if (params.size() == 0)
627 return ((double)GetBalance() / (double)COIN);
629 string strAccount = params[0].get_str();
631 if (params.size() > 1)
632 nMinDepth = params[1].get_int();
634 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
636 return (double)nBalance / (double)COIN;
640 Value movecmd(const Array& params, bool fHelp)
642 if (fHelp || params.size() < 3 || params.size() > 5)
644 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
645 "Move from one account in your wallet to another.");
647 string strFrom = params[0].get_str();
648 string strTo = params[1].get_str();
649 int64 nAmount = AmountFromValue(params[2]);
651 if (params.size() > 3)
652 nMinDepth = params[3].get_int();
654 if (params.size() > 4)
655 strComment = params[4].get_str();
657 CRITICAL_BLOCK(cs_mapWallet)
663 if (!strFrom.empty())
665 int64 nBalance = GetAccountBalance(walletdb, strFrom, nMinDepth);
666 if (nAmount > nBalance)
667 throw JSONRPCError(-6, "Account has insufficient funds");
671 // move from "" account special case
672 int64 nBalance = GetAccountBalance(walletdb, strTo, nMinDepth);
673 if (nAmount > GetBalance() - nBalance)
674 throw JSONRPCError(-6, "Account has insufficient funds");
677 int64 nNow = GetAdjustedTime();
680 CAccountingEntry debit;
681 debit.nCreditDebit = -nAmount;
683 debit.strOtherAccount = strTo;
684 debit.strComment = strComment;
685 walletdb.WriteAccountingEntry(strFrom, debit);
688 CAccountingEntry credit;
689 credit.nCreditDebit = nAmount;
691 credit.strOtherAccount = strFrom;
692 credit.strComment = strComment;
693 walletdb.WriteAccountingEntry(strTo, credit);
695 walletdb.TxnCommit();
701 Value sendfrom(const Array& params, bool fHelp)
703 if (fHelp || params.size() < 3 || params.size() > 6)
705 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
706 "<amount> is a real and is rounded to the nearest 0.01");
708 string strAccount = params[0].get_str();
709 string strAddress = params[1].get_str();
710 int64 nAmount = AmountFromValue(params[2]);
712 if (params.size() > 3)
713 nMinDepth = params[3].get_int();
716 wtx.strFromAccount = strAccount;
717 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
718 wtx.mapValue["message"] = params[4].get_str();
719 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
720 wtx.mapValue["to"] = params[5].get_str();
722 CRITICAL_BLOCK(cs_mapWallet)
725 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
726 if (nAmount > nBalance)
727 throw JSONRPCError(-6, "Account has insufficient funds");
730 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
732 throw JSONRPCError(-4, strError);
735 return wtx.GetHash().GetHex();
751 Value ListReceived(const Array& params, bool fByAccounts)
753 // Minimum confirmations
755 if (params.size() > 0)
756 nMinDepth = params[0].get_int();
758 // Whether to include empty accounts
759 bool fIncludeEmpty = false;
760 if (params.size() > 1)
761 fIncludeEmpty = params[1].get_bool();
764 map<uint160, tallyitem> mapTally;
765 CRITICAL_BLOCK(cs_mapWallet)
767 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
769 const CWalletTx& wtx = (*it).second;
770 if (wtx.IsCoinBase() || !wtx.IsFinal())
773 int nDepth = wtx.GetDepthInMainChain();
774 if (nDepth < nMinDepth)
777 foreach(const CTxOut& txout, wtx.vout)
779 // Only counting our own bitcoin addresses and not ip addresses
780 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
781 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
784 tallyitem& item = mapTally[hash160];
785 item.nAmount += txout.nValue;
786 item.nConf = min(item.nConf, nDepth);
793 map<string, tallyitem> mapAccountTally;
794 CRITICAL_BLOCK(cs_mapAddressBook)
796 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
798 const string& strAddress = item.first;
799 const string& strAccount = item.second;
801 if (!AddressToHash160(strAddress, hash160))
803 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
804 if (it == mapTally.end() && !fIncludeEmpty)
809 if (it != mapTally.end())
811 nAmount = (*it).second.nAmount;
812 nConf = (*it).second.nConf;
817 tallyitem& item = mapAccountTally[strAccount];
818 item.nAmount += nAmount;
819 item.nConf = min(item.nConf, nConf);
824 obj.push_back(Pair("address", strAddress));
825 obj.push_back(Pair("account", strAccount));
826 obj.push_back(Pair("label", strAccount)); // deprecated
827 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
828 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
836 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
838 int64 nAmount = (*it).second.nAmount;
839 int nConf = (*it).second.nConf;
841 obj.push_back(Pair("account", (*it).first));
842 obj.push_back(Pair("label", (*it).first)); // deprecated
843 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
844 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
852 Value listreceivedbyaddress(const Array& params, bool fHelp)
854 if (fHelp || params.size() > 2)
856 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
857 "[minconf] is the minimum number of confirmations before payments are included.\n"
858 "[includeempty] whether to include addresses that haven't received any payments.\n"
859 "Returns an array of objects containing:\n"
860 " \"address\" : receiving address\n"
861 " \"account\" : the account of the receiving address\n"
862 " \"amount\" : total amount received by the address\n"
863 " \"confirmations\" : number of confirmations of the most recent transaction included");
865 return ListReceived(params, false);
868 Value listreceivedbyaccount(const Array& params, bool fHelp)
870 if (fHelp || params.size() > 2)
872 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
873 "[minconf] is the minimum number of confirmations before payments are included.\n"
874 "[includeempty] whether to include accounts that haven't received any payments.\n"
875 "Returns an array of objects containing:\n"
876 " \"account\" : the account of the receiving addresses\n"
877 " \"amount\" : total amount received by addresses with this account\n"
878 " \"confirmations\" : number of confirmations of the most recent transaction included");
880 return ListReceived(params, true);
884 Value backupwallet(const Array& params, bool fHelp)
886 if (fHelp || params.size() != 1)
888 "backupwallet <destination>\n"
889 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
891 string strDest = params[0].get_str();
892 BackupWallet(strDest);
898 Value validateaddress(const Array& params, bool fHelp)
900 if (fHelp || params.size() != 1)
902 "validateaddress <bitcoinaddress>\n"
903 "Return information about <bitcoinaddress>.");
905 string strAddress = params[0].get_str();
907 bool isValid = AddressToHash160(strAddress, hash160);
910 ret.push_back(Pair("isvalid", isValid));
913 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
914 // version of the address:
915 string currentAddress = Hash160ToAddress(hash160);
916 ret.push_back(Pair("address", currentAddress));
917 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
918 CRITICAL_BLOCK(cs_mapAddressBook)
920 if (mapAddressBook.count(currentAddress))
921 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
941 pair<string, rpcfn_type> pCallTable[] =
943 make_pair("help", &help),
944 make_pair("stop", &stop),
945 make_pair("getblockcount", &getblockcount),
946 make_pair("getblocknumber", &getblocknumber),
947 make_pair("getconnectioncount", &getconnectioncount),
948 make_pair("getdifficulty", &getdifficulty),
949 make_pair("getgenerate", &getgenerate),
950 make_pair("setgenerate", &setgenerate),
951 make_pair("gethashespersec", &gethashespersec),
952 make_pair("getinfo", &getinfo),
953 make_pair("getnewaddress", &getnewaddress),
954 make_pair("getaccountaddress", &getaccountaddress),
955 make_pair("setaccount", &setaccount),
956 make_pair("setlabel", &setaccount), // deprecated
957 make_pair("getaccount", &getaccount),
958 make_pair("getlabel", &getaccount), // deprecated
959 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
960 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
961 make_pair("sendtoaddress", &sendtoaddress),
962 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
963 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
964 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
965 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
966 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
967 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
968 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
969 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
970 make_pair("backupwallet", &backupwallet),
971 make_pair("validateaddress", &validateaddress),
972 make_pair("getbalance", &getbalance),
973 make_pair("move", &movecmd),
974 make_pair("sendfrom", &sendfrom),
976 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
978 string pAllowInSafeMode[] =
984 "getconnectioncount",
994 "getlabel", // deprecated
995 "getaddressesbyaccount",
996 "getaddressesbylabel", // deprecated
1000 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1008 // This ain't Apache. We're just using HTTP header for the length field
1009 // and to be compatible with other JSON-RPC implementations.
1012 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1015 s << "POST / HTTP/1.1\r\n"
1016 << "User-Agent: json-rpc/1.0\r\n"
1017 << "Host: 127.0.0.1\r\n"
1018 << "Content-Type: application/json\r\n"
1019 << "Content-Length: " << strMsg.size() << "\r\n"
1020 << "Accept: application/json\r\n";
1021 foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1022 s << item.first << ": " << item.second << "\r\n";
1023 s << "\r\n" << strMsg;
1028 string rfc1123Time()
1033 struct tm* now_gmt = gmtime(&now);
1034 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);
1035 return string(buffer);
1038 string HTTPReply(int nStatus, const string& strMsg)
1041 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1043 "Server: bitcoin-json-rpc\r\n"
1044 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1045 "Content-Type: text/html\r\n"
1046 "Content-Length: 311\r\n"
1048 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1049 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1052 "<TITLE>Error</TITLE>\r\n"
1053 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1055 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1056 "</HTML>\r\n", rfc1123Time().c_str());
1058 if (nStatus == 200) strStatus = "OK";
1059 else if (nStatus == 400) strStatus = "Bad Request";
1060 else if (nStatus == 404) strStatus = "Not Found";
1061 else if (nStatus == 500) strStatus = "Internal Server Error";
1063 "HTTP/1.1 %d %s\r\n"
1065 "Connection: close\r\n"
1066 "Content-Length: %d\r\n"
1067 "Content-Type: application/json\r\n"
1068 "Server: bitcoin-json-rpc/1.0\r\n"
1073 rfc1123Time().c_str(),
1078 int ReadHTTPStatus(std::basic_istream<char>& stream)
1081 getline(stream, str);
1082 vector<string> vWords;
1083 boost::split(vWords, str, boost::is_any_of(" "));
1084 if (vWords.size() < 2)
1086 return atoi(vWords[1].c_str());
1089 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1095 std::getline(stream, str);
1096 if (str.empty() || str == "\r")
1098 string::size_type nColon = str.find(":");
1099 if (nColon != string::npos)
1101 string strHeader = str.substr(0, nColon);
1102 boost::trim(strHeader);
1103 string strValue = str.substr(nColon+1);
1104 boost::trim(strValue);
1105 mapHeadersRet[strHeader] = strValue;
1106 if (strHeader == "Content-Length")
1107 nLen = atoi(strValue.c_str());
1113 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1115 mapHeadersRet.clear();
1119 int nStatus = ReadHTTPStatus(stream);
1122 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1123 if (nLen < 0 || nLen > MAX_SIZE)
1129 vector<char> vch(nLen);
1130 stream.read(&vch[0], nLen);
1131 strMessageRet = string(vch.begin(), vch.end());
1137 string EncodeBase64(string s)
1142 b64 = BIO_new(BIO_f_base64());
1143 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1144 bmem = BIO_new(BIO_s_mem());
1145 b64 = BIO_push(b64, bmem);
1146 BIO_write(b64, s.c_str(), s.size());
1148 BIO_get_mem_ptr(b64, &bptr);
1150 string result(bptr->data, bptr->length);
1156 string DecodeBase64(string s)
1160 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1162 b64 = BIO_new(BIO_f_base64());
1163 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1164 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1165 bmem = BIO_push(b64, bmem);
1166 BIO_read(bmem, buffer, s.size());
1169 string result(buffer);
1174 bool HTTPAuthorized(map<string, string>& mapHeaders)
1176 string strAuth = mapHeaders["Authorization"];
1177 if (strAuth.substr(0,6) != "Basic ")
1179 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1180 string strUserPass = DecodeBase64(strUserPass64);
1181 string::size_type nColon = strUserPass.find(":");
1182 if (nColon == string::npos)
1184 string strUser = strUserPass.substr(0, nColon);
1185 string strPassword = strUserPass.substr(nColon+1);
1186 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1190 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1191 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1192 // unspecified (HTTP errors and contents of 'error').
1194 // 1.0 spec: http://json-rpc.org/wiki/specification
1195 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1196 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1199 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1202 request.push_back(Pair("method", strMethod));
1203 request.push_back(Pair("params", params));
1204 request.push_back(Pair("id", id));
1205 return write_string(Value(request), false) + "\n";
1208 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1211 if (error.type() != null_type)
1212 reply.push_back(Pair("result", Value::null));
1214 reply.push_back(Pair("result", result));
1215 reply.push_back(Pair("error", error));
1216 reply.push_back(Pair("id", id));
1217 return write_string(Value(reply), false) + "\n";
1220 bool ClientAllowed(const string& strAddress)
1222 if (strAddress == asio::ip::address_v4::loopback().to_string())
1224 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1225 foreach(string strAllow, vAllow)
1226 if (WildcardMatch(strAddress, strAllow))
1233 // IOStream device that speaks SSL but can also speak non-SSL
1235 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1237 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1239 fUseSSL = fUseSSLIn;
1240 fNeedHandshake = fUseSSLIn;
1243 void handshake(ssl::stream_base::handshake_type role)
1245 if (!fNeedHandshake) return;
1246 fNeedHandshake = false;
1247 stream.handshake(role);
1249 std::streamsize read(char* s, std::streamsize n)
1251 handshake(ssl::stream_base::server); // HTTPS servers read first
1252 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1253 return stream.next_layer().read_some(asio::buffer(s, n));
1255 std::streamsize write(const char* s, std::streamsize n)
1257 handshake(ssl::stream_base::client); // HTTPS clients write first
1258 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1259 return asio::write(stream.next_layer(), asio::buffer(s, n));
1261 bool connect(const std::string& server, const std::string& port)
1263 ip::tcp::resolver resolver(stream.get_io_service());
1264 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1265 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1266 ip::tcp::resolver::iterator end;
1267 boost::system::error_code error = asio::error::host_not_found;
1268 while (error && endpoint_iterator != end)
1270 stream.lowest_layer().close();
1271 stream.lowest_layer().connect(*endpoint_iterator++, error);
1279 bool fNeedHandshake;
1285 void ThreadRPCServer(void* parg)
1287 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1290 vnThreadsRunning[4]++;
1291 ThreadRPCServer2(parg);
1292 vnThreadsRunning[4]--;
1294 catch (std::exception& e) {
1295 vnThreadsRunning[4]--;
1296 PrintException(&e, "ThreadRPCServer()");
1298 vnThreadsRunning[4]--;
1299 PrintException(NULL, "ThreadRPCServer()");
1301 printf("ThreadRPCServer exiting\n");
1304 void ThreadRPCServer2(void* parg)
1306 printf("ThreadRPCServer started\n");
1308 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1310 string strWhatAmI = "To use bitcoind";
1311 if (mapArgs.count("-server"))
1312 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1313 else if (mapArgs.count("-daemon"))
1314 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1316 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1317 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1319 GetConfigFile().c_str());
1320 CreateThread(Shutdown, NULL);
1324 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1325 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1327 asio::io_service io_service;
1328 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1329 ip::tcp::acceptor acceptor(io_service, endpoint);
1332 ssl::context context(io_service, ssl::context::sslv23);
1335 context.set_options(ssl::context::no_sslv2);
1336 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1337 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1338 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1339 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1340 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1341 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1342 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1343 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1345 string ciphers = GetArg("-rpcsslciphers",
1346 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1347 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1351 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1356 // Accept connection
1358 SSLStream sslStream(io_service, context);
1359 SSLIOStreamDevice d(sslStream, fUseSSL);
1360 iostreams::stream<SSLIOStreamDevice> stream(d);
1362 ip::tcp::iostream stream;
1365 ip::tcp::endpoint peer;
1366 vnThreadsRunning[4]--;
1368 acceptor.accept(sslStream.lowest_layer(), peer);
1370 acceptor.accept(*stream.rdbuf(), peer);
1372 vnThreadsRunning[4]++;
1376 // Restrict callers by IP
1377 if (!ClientAllowed(peer.address().to_string()))
1381 map<string, string> mapHeaders;
1383 ReadHTTP(stream, mapHeaders, strRequest);
1385 // Check authorization
1386 if (mapHeaders.count("Authorization") == 0)
1388 stream << HTTPReply(401, "") << std::flush;
1391 if (!HTTPAuthorized(mapHeaders))
1393 // Deter brute-forcing short passwords
1394 if (mapArgs["-rpcpassword"].size() < 15)
1397 stream << HTTPReply(401, "") << std::flush;
1398 printf("ThreadRPCServer incorrect password attempt\n");
1402 Value id = Value::null;
1407 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1408 throw JSONRPCError(-32700, "Parse error");
1409 const Object& request = valRequest.get_obj();
1411 // Parse id now so errors from here on will have the id
1412 id = find_value(request, "id");
1415 Value valMethod = find_value(request, "method");
1416 if (valMethod.type() == null_type)
1417 throw JSONRPCError(-32600, "Missing method");
1418 if (valMethod.type() != str_type)
1419 throw JSONRPCError(-32600, "Method must be a string");
1420 string strMethod = valMethod.get_str();
1421 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1424 Value valParams = find_value(request, "params");
1426 if (valParams.type() == array_type)
1427 params = valParams.get_array();
1428 else if (valParams.type() == null_type)
1431 throw JSONRPCError(-32600, "Params must be an array");
1434 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1435 if (mi == mapCallTable.end())
1436 throw JSONRPCError(-32601, "Method not found");
1438 // Observe safe mode
1439 string strWarning = GetWarnings("rpc");
1440 if (strWarning != "" && !mapArgs.count("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1441 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1446 Value result = (*(*mi).second)(params, false);
1449 string strReply = JSONRPCReply(result, Value::null, id);
1450 stream << HTTPReply(200, strReply) << std::flush;
1452 catch (std::exception& e)
1454 // Send error reply from method
1455 string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);
1456 stream << HTTPReply(500, strReply) << std::flush;
1459 catch (Object& objError)
1461 // Send error reply from json-rpc error object
1463 int code = find_value(objError, "code").get_int();
1464 if (code == -32600) nStatus = 400;
1465 else if (code == -32601) nStatus = 404;
1466 string strReply = JSONRPCReply(Value::null, objError, id);
1467 stream << HTTPReply(nStatus, strReply) << std::flush;
1469 catch (std::exception& e)
1471 // Send error reply from other json-rpc parsing errors
1472 string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);
1473 stream << HTTPReply(500, strReply) << std::flush;
1481 Object CallRPC(const string& strMethod, const Array& params)
1483 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1484 throw runtime_error(strprintf(
1485 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1486 "If the file does not exist, create it with owner-readable-only file permissions."),
1487 GetConfigFile().c_str()));
1489 // Connect to localhost
1490 bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1492 asio::io_service io_service;
1493 ssl::context context(io_service, ssl::context::sslv23);
1494 context.set_options(ssl::context::no_sslv2);
1495 SSLStream sslStream(io_service, context);
1496 SSLIOStreamDevice d(sslStream, fUseSSL);
1497 iostreams::stream<SSLIOStreamDevice> stream(d);
1498 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1499 throw runtime_error("couldn't connect to server");
1502 throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1504 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1506 throw runtime_error("couldn't connect to server");
1510 // HTTP basic authentication
1511 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1512 map<string, string> mapRequestHeaders;
1513 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1516 string strRequest = JSONRPCRequest(strMethod, params, 1);
1517 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1518 stream << strPost << std::flush;
1521 map<string, string> mapHeaders;
1523 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1525 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1526 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
1527 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1528 else if (strReply.empty())
1529 throw runtime_error("no response from server");
1533 if (!read_string(strReply, valReply))
1534 throw runtime_error("couldn't parse reply from server");
1535 const Object& reply = valReply.get_obj();
1537 throw runtime_error("expected reply to have result, error and id properties");
1545 template<typename T>
1546 void ConvertTo(Value& value)
1548 if (value.type() == str_type)
1550 // reinterpret string as unquoted json value
1552 if (!read_string(value.get_str(), value2))
1553 throw runtime_error("type mismatch");
1554 value = value2.get_value<T>();
1558 value = value.get_value<T>();
1562 int CommandLineRPC(int argc, char *argv[])
1569 while (argc > 1 && IsSwitchChar(argv[1][0]))
1577 throw runtime_error("too few parameters");
1578 string strMethod = argv[1];
1580 // Parameters default to strings
1582 for (int i = 2; i < argc; i++)
1583 params.push_back(argv[i]);
1584 int n = params.size();
1587 // Special case non-string parameter types
1589 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1590 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1591 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1592 if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1593 if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);
1594 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1595 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1596 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1597 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1598 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1599 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
1600 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1601 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1602 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1603 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1604 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1605 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
1606 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1607 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1608 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1609 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1610 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1613 Object reply = CallRPC(strMethod, params);
1616 const Value& result = find_value(reply, "result");
1617 const Value& error = find_value(reply, "error");
1618 const Value& id = find_value(reply, "id");
1620 if (error.type() != null_type)
1623 strPrint = "error: " + write_string(error, false);
1624 int code = find_value(error.get_obj(), "code").get_int();
1630 if (result.type() == null_type)
1632 else if (result.type() == str_type)
1633 strPrint = result.get_str();
1635 strPrint = write_string(result, true);
1638 catch (std::exception& e)
1640 strPrint = string("error: ") + e.what();
1645 PrintException(NULL, "CommandLineRPC()");
1650 #if defined(__WXMSW__) && defined(GUI)
1651 // Windows GUI apps can't print to command line,
1652 // so settle for a message box yuck
1653 MyMessageBox(strPrint, "Bitcoin", wxOK);
1655 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1665 int main(int argc, char *argv[])
1668 // Turn off microsoft heap dump noise
1669 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1670 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1672 setbuf(stdin, NULL);
1673 setbuf(stdout, NULL);
1674 setbuf(stderr, NULL);
1678 if (argc >= 2 && string(argv[1]) == "-server")
1680 printf("server ready\n");
1681 ThreadRPCServer(NULL);
1685 return CommandLineRPC(argc, argv);
1688 catch (std::exception& e) {
1689 PrintException(&e, "main()");
1691 PrintException(NULL, "main()");