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.
6 #include "cryptopp/sha.h"
8 #include <boost/asio.hpp>
9 #include <boost/iostreams/concepts.hpp>
10 #include <boost/iostreams/stream.hpp>
12 #include <boost/asio/ssl.hpp>
13 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
15 #include "json/json_spirit_reader_template.h"
16 #include "json/json_spirit_writer_template.h"
17 #include "json/json_spirit_utils.h"
18 #define printf OutputDebugStringF
19 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
20 // precompiled in headers.h. The problem might be when the pch file goes over
21 // a certain size around 145MB. If we need access to json_spirit outside this
22 // file, we could use the compiled json_spirit option.
24 using namespace boost::asio;
25 using namespace json_spirit;
27 void ThreadRPCServer2(void* parg);
28 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
29 extern map<string, rpcfn_type> mapCallTable;
32 Object JSONRPCError(int code, const string& message)
35 error.push_back(Pair("code", code));
36 error.push_back(Pair("message", message));
41 void PrintConsole(const char* format, ...)
44 int limit = sizeof(buffer);
46 va_start(arg_ptr, format);
47 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
49 if (ret < 0 || ret >= limit)
55 #if defined(__WXMSW__) && defined(GUI)
56 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
58 fprintf(stdout, "%s", buffer);
63 int64 AmountFromValue(const Value& value)
65 double dAmount = value.get_real();
66 if (dAmount <= 0.0 || dAmount > 21000000.0)
67 throw JSONRPCError(-3, "Invalid amount");
68 int64 nAmount = roundint64(dAmount * 100.00) * CENT;
69 if (!MoneyRange(nAmount))
70 throw JSONRPCError(-3, "Invalid amount");
74 Value ValueFromAmount(int64 amount)
76 return (double)amount / (double)COIN;
79 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
81 entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
82 entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
83 entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
84 foreach(const PAIRTYPE(string,string)& item, wtx.mapValue)
85 entry.push_back(Pair(item.first, item.second));
88 string AccountFromValue(const Value& value)
90 string strAccount = value.get_str();
91 if (strAccount == "*")
92 throw JSONRPCError(-11, "Invalid account name");
99 /// Note: This interface may still be subject to change.
103 Value help(const Array& params, bool fHelp)
105 if (fHelp || params.size() > 1)
108 "List commands, or get help for a command.");
111 if (params.size() > 0)
112 strCommand = params[0].get_str();
115 set<rpcfn_type> setDone;
116 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
118 string strMethod = (*mi).first;
119 // We already filter duplicates, but these deprecated screw up the sort order
120 if (strMethod == "getamountreceived" ||
121 strMethod == "getallreceived" ||
122 (strMethod.find("label") != string::npos))
124 if (strCommand != "" && strMethod != strCommand)
129 rpcfn_type pfn = (*mi).second;
130 if (setDone.insert(pfn).second)
131 (*pfn)(params, true);
133 catch (std::exception& e)
135 // Help text is returned in an exception
136 string strHelp = string(e.what());
137 if (strCommand == "")
138 if (strHelp.find('\n') != -1)
139 strHelp = strHelp.substr(0, strHelp.find('\n'));
140 strRet += strHelp + "\n";
144 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
145 strRet = strRet.substr(0,strRet.size()-1);
150 Value stop(const Array& params, bool fHelp)
152 if (fHelp || params.size() != 0)
155 "Stop bitcoin server.");
157 // Shutdown will take long enough that the response should get back
158 CreateThread(Shutdown, NULL);
159 return "bitcoin server stopping";
163 Value getblockcount(const Array& params, bool fHelp)
165 if (fHelp || params.size() != 0)
168 "Returns the number of blocks in the longest block chain.");
174 Value getblocknumber(const Array& params, bool fHelp)
176 if (fHelp || params.size() != 0)
179 "Returns the block number of the latest block in the longest block chain.");
185 Value getconnectioncount(const Array& params, bool fHelp)
187 if (fHelp || params.size() != 0)
189 "getconnectioncount\n"
190 "Returns the number of connections to other nodes.");
192 return (int)vNodes.size();
196 double GetDifficulty()
198 // Floating point number that is a multiple of the minimum difficulty,
199 // minimum difficulty = 1.0.
200 if (pindexBest == NULL)
202 int nShift = 256 - 32 - 31; // to fit in a uint
203 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
204 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
205 return dMinimum / dCurrently;
208 Value getdifficulty(const Array& params, bool fHelp)
210 if (fHelp || params.size() != 0)
213 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
215 return GetDifficulty();
219 Value getgenerate(const Array& params, bool fHelp)
221 if (fHelp || params.size() != 0)
224 "Returns true or false.");
226 return (bool)fGenerateBitcoins;
230 Value setgenerate(const Array& params, bool fHelp)
232 if (fHelp || params.size() < 1 || params.size() > 2)
234 "setgenerate <generate> [genproclimit]\n"
235 "<generate> is true or false to turn generation on or off.\n"
236 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
238 bool fGenerate = true;
239 if (params.size() > 0)
240 fGenerate = params[0].get_bool();
242 if (params.size() > 1)
244 int nGenProcLimit = params[1].get_int();
245 fLimitProcessors = (nGenProcLimit != -1);
246 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
247 if (nGenProcLimit != -1)
248 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
249 if (nGenProcLimit == 0)
253 GenerateBitcoins(fGenerate);
258 Value gethashespersec(const Array& params, bool fHelp)
260 if (fHelp || params.size() != 0)
263 "Returns a recent hashes per second performance measurement while generating.");
265 if (GetTimeMillis() - nHPSTimerStart > 8000)
266 return (boost::int64_t)0;
267 return (boost::int64_t)dHashesPerSec;
271 Value getinfo(const Array& params, bool fHelp)
273 if (fHelp || params.size() != 0)
276 "Returns an object containing various state info.");
279 obj.push_back(Pair("version", (int)VERSION));
280 obj.push_back(Pair("balance", (double)GetBalance() / (double)COIN));
281 obj.push_back(Pair("blocks", (int)nBestHeight));
282 obj.push_back(Pair("connections", (int)vNodes.size()));
283 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
284 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
285 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
286 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
287 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
288 obj.push_back(Pair("testnet", fTestNet));
289 obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
290 obj.push_back(Pair("paytxfee", (double)nTransactionFee / (double)COIN));
291 obj.push_back(Pair("errors", GetWarnings("statusbar")));
296 Value getnewaddress(const Array& params, bool fHelp)
298 if (fHelp || params.size() > 1)
300 "getnewaddress [account]\n"
301 "Returns a new bitcoin address for receiving payments. "
302 "If [account] is specified (recommended), it is added to the address book "
303 "so payments received with the address will be credited to [account].");
305 // Parse the account first so we don't generate a key if there's an error
307 if (params.size() > 0)
308 strAccount = AccountFromValue(params[0]);
310 // Generate a new key that is added to wallet
311 string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
313 SetAddressBookName(strAddress, strAccount);
318 Value getaccountaddress(const Array& params, bool fHelp)
320 if (fHelp || params.size() != 1)
322 "getaccountaddress <account>\n"
323 "Returns the current bitcoin address for receiving payments to this account.");
325 // Parse the account first so we don't generate a key if there's an error
326 string strAccount = AccountFromValue(params[0]);
328 CRITICAL_BLOCK(cs_mapWallet)
334 walletdb.ReadAccount(strAccount, account);
336 // Check if the current key has been used
337 if (!account.vchPubKey.empty())
339 CScript scriptPubKey;
340 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
341 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
342 it != mapWallet.end() && !account.vchPubKey.empty();
345 const CWalletTx& wtx = (*it).second;
346 foreach(const CTxOut& txout, wtx.vout)
347 if (txout.scriptPubKey == scriptPubKey)
348 account.vchPubKey.clear();
352 // Generate a new key
353 if (account.vchPubKey.empty())
355 account.vchPubKey = GetKeyFromKeyPool();
356 string strAddress = PubKeyToAddress(account.vchPubKey);
357 SetAddressBookName(strAddress, strAccount);
358 walletdb.WriteAccount(strAccount, account);
361 walletdb.TxnCommit();
362 return PubKeyToAddress(account.vchPubKey);
367 Value setaccount(const Array& params, bool fHelp)
369 if (fHelp || params.size() < 1 || params.size() > 2)
371 "setaccount <bitcoinaddress> <account>\n"
372 "Sets the account associated with the given address.");
374 string strAddress = params[0].get_str();
376 if (params.size() > 1)
377 strAccount = AccountFromValue(params[1]);
379 SetAddressBookName(strAddress, strAccount);
384 Value getaccount(const Array& params, bool fHelp)
386 if (fHelp || params.size() != 1)
388 "getaccount <bitcoinaddress>\n"
389 "Returns the account associated with the given address.");
391 string strAddress = params[0].get_str();
394 CRITICAL_BLOCK(cs_mapAddressBook)
396 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
397 if (mi != mapAddressBook.end() && !(*mi).second.empty())
398 strAccount = (*mi).second;
404 Value getaddressesbyaccount(const Array& params, bool fHelp)
406 if (fHelp || params.size() != 1)
408 "getaddressesbyaccount <account>\n"
409 "Returns the list of addresses for the given account.");
411 string strAccount = AccountFromValue(params[0]);
413 // Find all addresses that have the given account
415 CRITICAL_BLOCK(cs_mapAddressBook)
417 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
419 const string& strAddress = item.first;
420 const string& strName = item.second;
421 if (strName == strAccount)
423 // We're only adding valid bitcoin addresses and not ip addresses
424 CScript scriptPubKey;
425 if (scriptPubKey.SetBitcoinAddress(strAddress))
426 ret.push_back(strAddress);
433 Value sendtoaddress(const Array& params, bool fHelp)
435 if (fHelp || params.size() < 2 || params.size() > 4)
437 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
438 "<amount> is a real and is rounded to the nearest 0.01");
440 string strAddress = params[0].get_str();
443 int64 nAmount = AmountFromValue(params[1]);
447 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
448 wtx.mapValue["comment"] = params[2].get_str();
449 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
450 wtx.mapValue["to"] = params[3].get_str();
452 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
454 throw JSONRPCError(-4, strError);
455 return wtx.GetHash().GetHex();
459 Value getreceivedbyaddress(const Array& params, bool fHelp)
461 if (fHelp || params.size() < 1 || params.size() > 2)
463 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
464 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
467 string strAddress = params[0].get_str();
468 CScript scriptPubKey;
469 if (!scriptPubKey.SetBitcoinAddress(strAddress))
470 throw JSONRPCError(-5, "Invalid bitcoin address");
471 if (!IsMine(scriptPubKey))
474 // Minimum confirmations
476 if (params.size() > 1)
477 nMinDepth = params[1].get_int();
481 CRITICAL_BLOCK(cs_mapWallet)
483 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
485 const CWalletTx& wtx = (*it).second;
486 if (wtx.IsCoinBase() || !wtx.IsFinal())
489 foreach(const CTxOut& txout, wtx.vout)
490 if (txout.scriptPubKey == scriptPubKey)
491 if (wtx.GetDepthInMainChain() >= nMinDepth)
492 nAmount += txout.nValue;
496 return (double)nAmount / (double)COIN;
500 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
502 CRITICAL_BLOCK(cs_mapAddressBook)
504 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
506 const string& strAddress = item.first;
507 const string& strName = item.second;
508 if (strName == strAccount)
510 // We're only counting our own valid bitcoin addresses and not ip addresses
511 CScript scriptPubKey;
512 if (scriptPubKey.SetBitcoinAddress(strAddress))
513 if (IsMine(scriptPubKey))
514 setPubKey.insert(scriptPubKey);
521 Value getreceivedbyaccount(const Array& params, bool fHelp)
523 if (fHelp || params.size() < 1 || params.size() > 2)
525 "getreceivedbyaccount <account> [minconf=1]\n"
526 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
528 // Minimum confirmations
530 if (params.size() > 1)
531 nMinDepth = params[1].get_int();
533 // Get the set of pub keys that have the label
534 string strAccount = AccountFromValue(params[0]);
535 set<CScript> setPubKey;
536 GetAccountPubKeys(strAccount, setPubKey);
540 CRITICAL_BLOCK(cs_mapWallet)
542 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
544 const CWalletTx& wtx = (*it).second;
545 if (wtx.IsCoinBase() || !wtx.IsFinal())
548 foreach(const CTxOut& txout, wtx.vout)
549 if (setPubKey.count(txout.scriptPubKey))
550 if (wtx.GetDepthInMainChain() >= nMinDepth)
551 nAmount += txout.nValue;
555 return (double)nAmount / (double)COIN;
559 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
562 CRITICAL_BLOCK(cs_mapWallet)
564 // Tally wallet transactions
565 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
567 const CWalletTx& wtx = (*it).second;
571 int64 nGenerated, nReceived, nSent, nFee;
572 wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
574 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
575 nBalance += nReceived;
576 nBalance += nGenerated - nSent - nFee;
579 // Tally internal accounting entries
580 nBalance += walletdb.GetAccountCreditDebit(strAccount);
586 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
589 return GetAccountBalance(walletdb, strAccount, nMinDepth);
593 Value getbalance(const Array& params, bool fHelp)
595 if (fHelp || params.size() < 0 || params.size() > 2)
597 "getbalance [account] [minconf=1]\n"
598 "If [account] is not specified, returns the server's total available balance.\n"
599 "If [account] is specified, returns the balance in the account.");
601 if (params.size() == 0)
602 return ((double)GetBalance() / (double)COIN);
604 string strAccount = AccountFromValue(params[0]);
606 if (params.size() > 1)
607 nMinDepth = params[1].get_int();
609 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
611 return (double)nBalance / (double)COIN;
615 Value movecmd(const Array& params, bool fHelp)
617 if (fHelp || params.size() < 3 || params.size() > 5)
619 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
620 "Move from one account in your wallet to another.");
622 string strFrom = AccountFromValue(params[0]);
623 string strTo = AccountFromValue(params[1]);
624 int64 nAmount = AmountFromValue(params[2]);
626 if (params.size() > 3)
627 nMinDepth = params[3].get_int();
629 if (params.size() > 4)
630 strComment = params[4].get_str();
632 CRITICAL_BLOCK(cs_mapWallet)
638 if (!strFrom.empty())
640 int64 nBalance = GetAccountBalance(walletdb, strFrom, nMinDepth);
641 if (nAmount > nBalance)
642 throw JSONRPCError(-6, "Account has insufficient funds");
646 // move from "" account special case
647 int64 nBalance = GetAccountBalance(walletdb, strTo, nMinDepth);
648 if (nAmount > GetBalance() - nBalance)
649 throw JSONRPCError(-6, "Account has insufficient funds");
652 int64 nNow = GetAdjustedTime();
655 CAccountingEntry debit;
656 debit.strAccount = strFrom;
657 debit.nCreditDebit = -nAmount;
659 debit.strOtherAccount = strTo;
660 debit.strComment = strComment;
661 walletdb.WriteAccountingEntry(debit);
664 CAccountingEntry credit;
665 credit.strAccount = strTo;
666 credit.nCreditDebit = nAmount;
668 credit.strOtherAccount = strFrom;
669 credit.strComment = strComment;
670 walletdb.WriteAccountingEntry(credit);
672 walletdb.TxnCommit();
678 Value sendfrom(const Array& params, bool fHelp)
680 if (fHelp || params.size() < 3 || params.size() > 6)
682 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
683 "<amount> is a real and is rounded to the nearest 0.01");
685 string strAccount = AccountFromValue(params[0]);
686 string strAddress = params[1].get_str();
687 int64 nAmount = AmountFromValue(params[2]);
689 if (params.size() > 3)
690 nMinDepth = params[3].get_int();
693 wtx.strFromAccount = strAccount;
694 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
695 wtx.mapValue["comment"] = params[4].get_str();
696 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
697 wtx.mapValue["to"] = params[5].get_str();
699 CRITICAL_BLOCK(cs_mapWallet)
702 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
703 if (nAmount > nBalance)
704 throw JSONRPCError(-6, "Account has insufficient funds");
707 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
709 throw JSONRPCError(-4, strError);
712 return wtx.GetHash().GetHex();
728 Value ListReceived(const Array& params, bool fByAccounts)
730 // Minimum confirmations
732 if (params.size() > 0)
733 nMinDepth = params[0].get_int();
735 // Whether to include empty accounts
736 bool fIncludeEmpty = false;
737 if (params.size() > 1)
738 fIncludeEmpty = params[1].get_bool();
741 map<uint160, tallyitem> mapTally;
742 CRITICAL_BLOCK(cs_mapWallet)
744 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
746 const CWalletTx& wtx = (*it).second;
747 if (wtx.IsCoinBase() || !wtx.IsFinal())
750 int nDepth = wtx.GetDepthInMainChain();
751 if (nDepth < nMinDepth)
754 foreach(const CTxOut& txout, wtx.vout)
756 // Only counting our own bitcoin addresses and not ip addresses
757 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
758 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
761 tallyitem& item = mapTally[hash160];
762 item.nAmount += txout.nValue;
763 item.nConf = min(item.nConf, nDepth);
770 map<string, tallyitem> mapAccountTally;
771 CRITICAL_BLOCK(cs_mapAddressBook)
773 foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
775 const string& strAddress = item.first;
776 const string& strAccount = item.second;
778 if (!AddressToHash160(strAddress, hash160))
780 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
781 if (it == mapTally.end() && !fIncludeEmpty)
786 if (it != mapTally.end())
788 nAmount = (*it).second.nAmount;
789 nConf = (*it).second.nConf;
794 tallyitem& item = mapAccountTally[strAccount];
795 item.nAmount += nAmount;
796 item.nConf = min(item.nConf, nConf);
801 obj.push_back(Pair("address", strAddress));
802 obj.push_back(Pair("account", strAccount));
803 obj.push_back(Pair("label", strAccount)); // deprecated
804 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
805 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
813 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
815 int64 nAmount = (*it).second.nAmount;
816 int nConf = (*it).second.nConf;
818 obj.push_back(Pair("account", (*it).first));
819 obj.push_back(Pair("label", (*it).first)); // deprecated
820 obj.push_back(Pair("amount", (double)nAmount / (double)COIN));
821 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
829 Value listreceivedbyaddress(const Array& params, bool fHelp)
831 if (fHelp || params.size() > 2)
833 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
834 "[minconf] is the minimum number of confirmations before payments are included.\n"
835 "[includeempty] whether to include addresses that haven't received any payments.\n"
836 "Returns an array of objects containing:\n"
837 " \"address\" : receiving address\n"
838 " \"account\" : the account of the receiving address\n"
839 " \"amount\" : total amount received by the address\n"
840 " \"confirmations\" : number of confirmations of the most recent transaction included");
842 return ListReceived(params, false);
845 Value listreceivedbyaccount(const Array& params, bool fHelp)
847 if (fHelp || params.size() > 2)
849 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
850 "[minconf] is the minimum number of confirmations before payments are included.\n"
851 "[includeempty] whether to include accounts that haven't received any payments.\n"
852 "Returns an array of objects containing:\n"
853 " \"account\" : the account of the receiving addresses\n"
854 " \"amount\" : total amount received by addresses with this account\n"
855 " \"confirmations\" : number of confirmations of the most recent transaction included");
857 return ListReceived(params, true);
860 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, Array& ret)
862 int64 nGenerated, nSent, nFee;
863 string strSentAccount;
864 list<pair<string, int64> > listReceived;
865 wtx.GetAmounts(nGenerated, listReceived, nSent, nFee, strSentAccount);
867 bool fAllAccounts = (strAccount == string("*"));
869 // Generated blocks assigned to account ""
870 if (nGenerated != 0 && (fAllAccounts || strAccount == ""))
873 entry.push_back(Pair("account", string("")));
874 entry.push_back(Pair("category", "generate"));
875 entry.push_back(Pair("amount", ValueFromAmount(nGenerated)));
876 WalletTxToJSON(wtx, entry);
877 ret.push_back(entry);
881 if ((nSent != 0 || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
884 entry.push_back(Pair("account", strSentAccount));
885 entry.push_back(Pair("category", "send"));
886 entry.push_back(Pair("amount", ValueFromAmount(-nSent)));
887 entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
888 WalletTxToJSON(wtx, entry);
889 ret.push_back(entry);
893 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
894 CRITICAL_BLOCK(cs_mapAddressBook)
896 foreach(const PAIRTYPE(string, int64)& r, listReceived)
897 if (mapAddressBook.count(r.first) && (fAllAccounts || mapAddressBook[r.first] == strAccount))
900 entry.push_back(Pair("account", mapAddressBook[r.first]));
901 entry.push_back(Pair("category", "receive"));
902 entry.push_back(Pair("amount", ValueFromAmount(r.second)));
903 WalletTxToJSON(wtx, entry);
904 ret.push_back(entry);
910 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
912 bool fAllAccounts = (strAccount == string("*"));
914 if (fAllAccounts || acentry.strAccount == strAccount)
917 entry.push_back(Pair("account", acentry.strAccount));
918 entry.push_back(Pair("category", "move"));
919 entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
920 entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
921 entry.push_back(Pair("comment", acentry.strComment));
922 ret.push_back(entry);
926 Value listtransactions(const Array& params, bool fHelp)
928 if (fHelp || params.size() > 2)
930 "listtransactions [account] [count=10]\n"
931 "Returns up to [count] most recent transactions for account <account>.");
933 string strAccount = "*";
934 if (params.size() > 0)
935 strAccount = params[0].get_str();
937 if (params.size() > 1)
938 nCount = params[1].get_int();
943 CRITICAL_BLOCK(cs_mapWallet)
945 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
946 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
947 typedef multimap<int64, TxPair > TxItems;
950 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
952 CWalletTx* wtx = &((*it).second);
953 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, 0)));
955 list<CAccountingEntry> acentries;
956 walletdb.ListAccountCreditDebit(strAccount, acentries);
957 foreach(CAccountingEntry& entry, acentries)
959 txByTime.insert(make_pair(entry.nTime, TxPair(0, &entry)));
962 // Now: iterate backwards until we have nCount items to return:
963 for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it)
965 CWalletTx *const pwtx = (*it).second.first;
967 ListTransactions(*pwtx, strAccount, 0, ret);
968 CAccountingEntry *const pacentry = (*it).second.second;
970 AcentryToJSON(*pacentry, strAccount, ret);
972 if (ret.size() >= nCount) break;
974 // ret is now newest to oldest
977 // Make sure we return only last nCount items (sends-to-self might give us an extra):
978 if (ret.size() > nCount)
980 Array::iterator last = ret.begin();
981 std::advance(last, nCount);
982 ret.erase(last, ret.end());
984 std::reverse(ret.begin(), ret.end()); // oldest to newest
989 Value listaccounts(const Array& params, bool fHelp)
991 if (fHelp || params.size() > 1)
993 "listaccounts [minconf=1]\n"
994 "Returns Object that has account names as keys, account balances as values.");
997 if (params.size() > 1)
998 nMinDepth = params[1].get_int();
1000 map<string, int64> mapAccountBalances;
1001 CRITICAL_BLOCK(cs_mapWallet)
1002 CRITICAL_BLOCK(cs_mapAddressBook)
1004 foreach(const PAIRTYPE(string, string)& entry, mapAddressBook)
1005 mapAccountBalances[entry.second] = 0;
1007 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1009 const CWalletTx& wtx = (*it).second;
1010 int64 nGenerated, nSent, nFee;
1011 string strSentAccount;
1012 list<pair<string, int64> > listReceived;
1013 wtx.GetAmounts(nGenerated, listReceived, nSent, nFee, strSentAccount);
1014 mapAccountBalances[strSentAccount] -= nSent+nFee;
1015 if (wtx.GetDepthInMainChain() >= nMinDepth)
1017 mapAccountBalances[""] += nGenerated;
1018 foreach(const PAIRTYPE(string, int64)& r, listReceived)
1019 if (mapAddressBook.count(r.first))
1020 mapAccountBalances[mapAddressBook[r.first]] += r.second;
1025 list<CAccountingEntry> acentries;
1026 CWalletDB().ListAccountCreditDebit("*", acentries);
1027 foreach(const CAccountingEntry& entry, acentries)
1028 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1031 foreach(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1032 ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1037 Value gettransaction(const Array& params, bool fHelp)
1039 if (fHelp || params.size() != 1)
1040 throw runtime_error(
1041 "gettransaction <txid>\n"
1042 "Get detailed information about <txid>");
1045 hash.SetHex(params[0].get_str());
1048 CRITICAL_BLOCK(cs_mapWallet)
1050 if (!mapWallet.count(hash))
1051 throw JSONRPCError(-5, "Invalid transaction id");
1052 const CWalletTx& wtx = mapWallet[hash];
1054 int64 nCredit = wtx.GetCredit();
1055 int64 nDebit = wtx.GetDebit();
1056 int64 nNet = nCredit - nDebit;
1057 int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1059 entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1061 entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1062 WalletTxToJSON(mapWallet[hash], entry);
1069 Value backupwallet(const Array& params, bool fHelp)
1071 if (fHelp || params.size() != 1)
1072 throw runtime_error(
1073 "backupwallet <destination>\n"
1074 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1076 string strDest = params[0].get_str();
1077 BackupWallet(strDest);
1083 Value validateaddress(const Array& params, bool fHelp)
1085 if (fHelp || params.size() != 1)
1086 throw runtime_error(
1087 "validateaddress <bitcoinaddress>\n"
1088 "Return information about <bitcoinaddress>.");
1090 string strAddress = params[0].get_str();
1092 bool isValid = AddressToHash160(strAddress, hash160);
1095 ret.push_back(Pair("isvalid", isValid));
1098 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1099 // version of the address:
1100 string currentAddress = Hash160ToAddress(hash160);
1101 ret.push_back(Pair("address", currentAddress));
1102 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1103 CRITICAL_BLOCK(cs_mapAddressBook)
1105 if (mapAddressBook.count(currentAddress))
1106 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
1113 Value getwork(const Array& params, bool fHelp)
1115 if (fHelp || params.size() > 1)
1116 throw runtime_error(
1118 "If [data] is not specified, returns formatted hash data to work on:\n"
1119 " \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1120 " \"data\" : block data\n"
1121 " \"hash1\" : formatted hash buffer for second hash\n"
1122 " \"target\" : little endian hash target\n"
1123 "If [data] is specified, tries to solve the block and returns true if it was successful.");
1126 throw JSONRPCError(-9, "Bitcoin is not connected!");
1128 if (IsInitialBlockDownload())
1129 throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1131 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1132 static vector<CBlock*> vNewBlock;
1133 static CReserveKey reservekey;
1135 if (params.size() == 0)
1138 static unsigned int nTransactionsUpdatedLast;
1139 static CBlockIndex* pindexPrev;
1140 static int64 nStart;
1141 static CBlock* pblock;
1142 if (pindexPrev != pindexBest ||
1143 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1145 if (pindexPrev != pindexBest)
1147 // Deallocate old blocks since they're obsolete now
1148 mapNewBlock.clear();
1149 foreach(CBlock* pblock, vNewBlock)
1153 nTransactionsUpdatedLast = nTransactionsUpdated;
1154 pindexPrev = pindexBest;
1158 pblock = CreateNewBlock(reservekey);
1160 throw JSONRPCError(-7, "Out of memory");
1161 vNewBlock.push_back(pblock);
1165 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1168 // Update nExtraNonce
1169 static unsigned int nExtraNonce = 0;
1170 static int64 nPrevTime = 0;
1171 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1174 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1176 // Prebuild hash buffers
1180 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1182 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1185 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1186 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
1187 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
1188 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
1194 vector<unsigned char> vchData = ParseHex(params[0].get_str());
1195 if (vchData.size() != 128)
1196 throw JSONRPCError(-8, "Invalid parameter");
1197 CBlock* pdata = (CBlock*)&vchData[0];
1200 for (int i = 0; i < 128/4; i++)
1201 ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1204 if (!mapNewBlock.count(pdata->hashMerkleRoot))
1206 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1207 unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1209 pblock->nTime = pdata->nTime;
1210 pblock->nNonce = pdata->nNonce;
1211 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1212 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1214 return CheckWork(pblock, reservekey);
1232 pair<string, rpcfn_type> pCallTable[] =
1234 make_pair("help", &help),
1235 make_pair("stop", &stop),
1236 make_pair("getblockcount", &getblockcount),
1237 make_pair("getblocknumber", &getblocknumber),
1238 make_pair("getconnectioncount", &getconnectioncount),
1239 make_pair("getdifficulty", &getdifficulty),
1240 make_pair("getgenerate", &getgenerate),
1241 make_pair("setgenerate", &setgenerate),
1242 make_pair("gethashespersec", &gethashespersec),
1243 make_pair("getinfo", &getinfo),
1244 make_pair("getnewaddress", &getnewaddress),
1245 make_pair("getaccountaddress", &getaccountaddress),
1246 make_pair("setaccount", &setaccount),
1247 make_pair("setlabel", &setaccount), // deprecated
1248 make_pair("getaccount", &getaccount),
1249 make_pair("getlabel", &getaccount), // deprecated
1250 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1251 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
1252 make_pair("sendtoaddress", &sendtoaddress),
1253 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1254 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1255 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
1256 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
1257 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
1258 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1259 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1260 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
1261 make_pair("backupwallet", &backupwallet),
1262 make_pair("validateaddress", &validateaddress),
1263 make_pair("getbalance", &getbalance),
1264 make_pair("move", &movecmd),
1265 make_pair("sendfrom", &sendfrom),
1266 make_pair("gettransaction", &gettransaction),
1267 make_pair("listtransactions", &listtransactions),
1268 make_pair("getwork", &getwork),
1269 make_pair("listaccounts", &listaccounts),
1271 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1273 string pAllowInSafeMode[] =
1279 "getconnectioncount",
1286 "getaccountaddress",
1289 "getlabel", // deprecated
1290 "getaddressesbyaccount",
1291 "getaddressesbylabel", // deprecated
1296 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1304 // This ain't Apache. We're just using HTTP header for the length field
1305 // and to be compatible with other JSON-RPC implementations.
1308 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1311 s << "POST / HTTP/1.1\r\n"
1312 << "User-Agent: json-rpc/1.0\r\n"
1313 << "Host: 127.0.0.1\r\n"
1314 << "Content-Type: application/json\r\n"
1315 << "Content-Length: " << strMsg.size() << "\r\n"
1316 << "Accept: application/json\r\n";
1317 foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1318 s << item.first << ": " << item.second << "\r\n";
1319 s << "\r\n" << strMsg;
1324 string rfc1123Time()
1329 struct tm* now_gmt = gmtime(&now);
1330 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);
1331 return string(buffer);
1334 string HTTPReply(int nStatus, const string& strMsg)
1337 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1339 "Server: bitcoin-json-rpc\r\n"
1340 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1341 "Content-Type: text/html\r\n"
1342 "Content-Length: 296\r\n"
1344 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1345 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1348 "<TITLE>Error</TITLE>\r\n"
1349 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1351 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1352 "</HTML>\r\n", rfc1123Time().c_str());
1354 if (nStatus == 200) strStatus = "OK";
1355 else if (nStatus == 400) strStatus = "Bad Request";
1356 else if (nStatus == 404) strStatus = "Not Found";
1357 else if (nStatus == 500) strStatus = "Internal Server Error";
1359 "HTTP/1.1 %d %s\r\n"
1361 "Connection: close\r\n"
1362 "Content-Length: %d\r\n"
1363 "Content-Type: application/json\r\n"
1364 "Server: bitcoin-json-rpc/1.0\r\n"
1369 rfc1123Time().c_str(),
1374 int ReadHTTPStatus(std::basic_istream<char>& stream)
1377 getline(stream, str);
1378 vector<string> vWords;
1379 boost::split(vWords, str, boost::is_any_of(" "));
1380 if (vWords.size() < 2)
1382 return atoi(vWords[1].c_str());
1385 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1391 std::getline(stream, str);
1392 if (str.empty() || str == "\r")
1394 string::size_type nColon = str.find(":");
1395 if (nColon != string::npos)
1397 string strHeader = str.substr(0, nColon);
1398 boost::trim(strHeader);
1399 string strValue = str.substr(nColon+1);
1400 boost::trim(strValue);
1401 mapHeadersRet[strHeader] = strValue;
1402 if (strHeader == "Content-Length")
1403 nLen = atoi(strValue.c_str());
1409 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1411 mapHeadersRet.clear();
1415 int nStatus = ReadHTTPStatus(stream);
1418 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1419 if (nLen < 0 || nLen > MAX_SIZE)
1425 vector<char> vch(nLen);
1426 stream.read(&vch[0], nLen);
1427 strMessageRet = string(vch.begin(), vch.end());
1433 string EncodeBase64(string s)
1438 b64 = BIO_new(BIO_f_base64());
1439 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1440 bmem = BIO_new(BIO_s_mem());
1441 b64 = BIO_push(b64, bmem);
1442 BIO_write(b64, s.c_str(), s.size());
1444 BIO_get_mem_ptr(b64, &bptr);
1446 string result(bptr->data, bptr->length);
1452 string DecodeBase64(string s)
1456 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1458 b64 = BIO_new(BIO_f_base64());
1459 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1460 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1461 bmem = BIO_push(b64, bmem);
1462 BIO_read(bmem, buffer, s.size());
1465 string result(buffer);
1470 bool HTTPAuthorized(map<string, string>& mapHeaders)
1472 string strAuth = mapHeaders["Authorization"];
1473 if (strAuth.substr(0,6) != "Basic ")
1475 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1476 string strUserPass = DecodeBase64(strUserPass64);
1477 string::size_type nColon = strUserPass.find(":");
1478 if (nColon == string::npos)
1480 string strUser = strUserPass.substr(0, nColon);
1481 string strPassword = strUserPass.substr(nColon+1);
1482 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1486 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1487 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1488 // unspecified (HTTP errors and contents of 'error').
1490 // 1.0 spec: http://json-rpc.org/wiki/specification
1491 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1492 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1495 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1498 request.push_back(Pair("method", strMethod));
1499 request.push_back(Pair("params", params));
1500 request.push_back(Pair("id", id));
1501 return write_string(Value(request), false) + "\n";
1504 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1507 if (error.type() != null_type)
1508 reply.push_back(Pair("result", Value::null));
1510 reply.push_back(Pair("result", result));
1511 reply.push_back(Pair("error", error));
1512 reply.push_back(Pair("id", id));
1513 return write_string(Value(reply), false) + "\n";
1516 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1518 // Send error reply from json-rpc error object
1520 int code = find_value(objError, "code").get_int();
1521 if (code == -32600) nStatus = 400;
1522 else if (code == -32601) nStatus = 404;
1523 string strReply = JSONRPCReply(Value::null, objError, id);
1524 stream << HTTPReply(nStatus, strReply) << std::flush;
1527 bool ClientAllowed(const string& strAddress)
1529 if (strAddress == asio::ip::address_v4::loopback().to_string())
1531 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1532 foreach(string strAllow, vAllow)
1533 if (WildcardMatch(strAddress, strAllow))
1540 // IOStream device that speaks SSL but can also speak non-SSL
1542 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1544 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1546 fUseSSL = fUseSSLIn;
1547 fNeedHandshake = fUseSSLIn;
1550 void handshake(ssl::stream_base::handshake_type role)
1552 if (!fNeedHandshake) return;
1553 fNeedHandshake = false;
1554 stream.handshake(role);
1556 std::streamsize read(char* s, std::streamsize n)
1558 handshake(ssl::stream_base::server); // HTTPS servers read first
1559 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1560 return stream.next_layer().read_some(asio::buffer(s, n));
1562 std::streamsize write(const char* s, std::streamsize n)
1564 handshake(ssl::stream_base::client); // HTTPS clients write first
1565 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1566 return asio::write(stream.next_layer(), asio::buffer(s, n));
1568 bool connect(const std::string& server, const std::string& port)
1570 ip::tcp::resolver resolver(stream.get_io_service());
1571 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1572 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1573 ip::tcp::resolver::iterator end;
1574 boost::system::error_code error = asio::error::host_not_found;
1575 while (error && endpoint_iterator != end)
1577 stream.lowest_layer().close();
1578 stream.lowest_layer().connect(*endpoint_iterator++, error);
1586 bool fNeedHandshake;
1592 void ThreadRPCServer(void* parg)
1594 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1597 vnThreadsRunning[4]++;
1598 ThreadRPCServer2(parg);
1599 vnThreadsRunning[4]--;
1601 catch (std::exception& e) {
1602 vnThreadsRunning[4]--;
1603 PrintException(&e, "ThreadRPCServer()");
1605 vnThreadsRunning[4]--;
1606 PrintException(NULL, "ThreadRPCServer()");
1608 printf("ThreadRPCServer exiting\n");
1611 void ThreadRPCServer2(void* parg)
1613 printf("ThreadRPCServer started\n");
1615 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1617 string strWhatAmI = "To use bitcoind";
1618 if (mapArgs.count("-server"))
1619 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1620 else if (mapArgs.count("-daemon"))
1621 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1623 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1624 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1626 GetConfigFile().c_str());
1627 CreateThread(Shutdown, NULL);
1631 bool fUseSSL = GetBoolArg("-rpcssl");
1632 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1634 asio::io_service io_service;
1635 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1636 ip::tcp::acceptor acceptor(io_service, endpoint);
1639 ssl::context context(io_service, ssl::context::sslv23);
1642 context.set_options(ssl::context::no_sslv2);
1643 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1644 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1645 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1646 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1647 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1648 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1649 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1650 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1652 string ciphers = GetArg("-rpcsslciphers",
1653 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1654 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1658 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1663 // Accept connection
1665 SSLStream sslStream(io_service, context);
1666 SSLIOStreamDevice d(sslStream, fUseSSL);
1667 iostreams::stream<SSLIOStreamDevice> stream(d);
1669 ip::tcp::iostream stream;
1672 ip::tcp::endpoint peer;
1673 vnThreadsRunning[4]--;
1675 acceptor.accept(sslStream.lowest_layer(), peer);
1677 acceptor.accept(*stream.rdbuf(), peer);
1679 vnThreadsRunning[4]++;
1683 // Restrict callers by IP
1684 if (!ClientAllowed(peer.address().to_string()))
1687 map<string, string> mapHeaders;
1690 boost::thread api_caller(ReadHTTP, ref(stream), ref(mapHeaders), ref(strRequest));
1691 if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
1694 printf("ThreadRPCServer ReadHTTP timeout\n");
1698 // Check authorization
1699 if (mapHeaders.count("Authorization") == 0)
1701 stream << HTTPReply(401, "") << std::flush;
1704 if (!HTTPAuthorized(mapHeaders))
1706 // Deter brute-forcing short passwords
1707 if (mapArgs["-rpcpassword"].size() < 15)
1710 stream << HTTPReply(401, "") << std::flush;
1711 printf("ThreadRPCServer incorrect password attempt\n");
1715 Value id = Value::null;
1720 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1721 throw JSONRPCError(-32700, "Parse error");
1722 const Object& request = valRequest.get_obj();
1724 // Parse id now so errors from here on will have the id
1725 id = find_value(request, "id");
1728 Value valMethod = find_value(request, "method");
1729 if (valMethod.type() == null_type)
1730 throw JSONRPCError(-32600, "Missing method");
1731 if (valMethod.type() != str_type)
1732 throw JSONRPCError(-32600, "Method must be a string");
1733 string strMethod = valMethod.get_str();
1734 if (strMethod != "getwork")
1735 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1738 Value valParams = find_value(request, "params");
1740 if (valParams.type() == array_type)
1741 params = valParams.get_array();
1742 else if (valParams.type() == null_type)
1745 throw JSONRPCError(-32600, "Params must be an array");
1748 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1749 if (mi == mapCallTable.end())
1750 throw JSONRPCError(-32601, "Method not found");
1752 // Observe safe mode
1753 string strWarning = GetWarnings("rpc");
1754 if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1755 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1760 Value result = (*(*mi).second)(params, false);
1763 string strReply = JSONRPCReply(result, Value::null, id);
1764 stream << HTTPReply(200, strReply) << std::flush;
1766 catch (std::exception& e)
1768 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
1771 catch (Object& objError)
1773 ErrorReply(stream, objError, id);
1775 catch (std::exception& e)
1777 ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
1785 Object CallRPC(const string& strMethod, const Array& params)
1787 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1788 throw runtime_error(strprintf(
1789 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1790 "If the file does not exist, create it with owner-readable-only file permissions."),
1791 GetConfigFile().c_str()));
1793 // Connect to localhost
1794 bool fUseSSL = GetBoolArg("-rpcssl");
1796 asio::io_service io_service;
1797 ssl::context context(io_service, ssl::context::sslv23);
1798 context.set_options(ssl::context::no_sslv2);
1799 SSLStream sslStream(io_service, context);
1800 SSLIOStreamDevice d(sslStream, fUseSSL);
1801 iostreams::stream<SSLIOStreamDevice> stream(d);
1802 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1803 throw runtime_error("couldn't connect to server");
1806 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1808 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1810 throw runtime_error("couldn't connect to server");
1814 // HTTP basic authentication
1815 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1816 map<string, string> mapRequestHeaders;
1817 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1820 string strRequest = JSONRPCRequest(strMethod, params, 1);
1821 string strPost = HTTPPost(strRequest, mapRequestHeaders);
1822 stream << strPost << std::flush;
1825 map<string, string> mapHeaders;
1827 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1829 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1830 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
1831 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1832 else if (strReply.empty())
1833 throw runtime_error("no response from server");
1837 if (!read_string(strReply, valReply))
1838 throw runtime_error("couldn't parse reply from server");
1839 const Object& reply = valReply.get_obj();
1841 throw runtime_error("expected reply to have result, error and id properties");
1849 template<typename T>
1850 void ConvertTo(Value& value)
1852 if (value.type() == str_type)
1854 // reinterpret string as unquoted json value
1856 if (!read_string(value.get_str(), value2))
1857 throw runtime_error("type mismatch");
1858 value = value2.get_value<T>();
1862 value = value.get_value<T>();
1866 int CommandLineRPC(int argc, char *argv[])
1873 while (argc > 1 && IsSwitchChar(argv[1][0]))
1881 throw runtime_error("too few parameters");
1882 string strMethod = argv[1];
1884 // Parameters default to strings
1886 for (int i = 2; i < argc; i++)
1887 params.push_back(argv[i]);
1888 int n = params.size();
1891 // Special case non-string parameter types
1893 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
1894 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1895 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
1896 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1897 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1898 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1899 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1900 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1901 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
1902 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1903 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
1904 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
1905 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
1906 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1907 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
1908 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1909 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
1910 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1911 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
1912 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
1913 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1914 if (strMethod == "listaccounts" && n > 1) ConvertTo<boost::int64_t>(params[1]);
1917 Object reply = CallRPC(strMethod, params);
1920 const Value& result = find_value(reply, "result");
1921 const Value& error = find_value(reply, "error");
1922 const Value& id = find_value(reply, "id");
1924 if (error.type() != null_type)
1927 strPrint = "error: " + write_string(error, false);
1928 int code = find_value(error.get_obj(), "code").get_int();
1934 if (result.type() == null_type)
1936 else if (result.type() == str_type)
1937 strPrint = result.get_str();
1939 strPrint = write_string(result, true);
1942 catch (std::exception& e)
1944 strPrint = string("error: ") + e.what();
1949 PrintException(NULL, "CommandLineRPC()");
1954 #if defined(__WXMSW__) && defined(GUI)
1955 // Windows GUI apps can't print to command line,
1956 // so settle for a message box yuck
1957 MyMessageBox(strPrint, "Bitcoin", wxOK);
1959 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1969 int main(int argc, char *argv[])
1972 // Turn off microsoft heap dump noise
1973 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1974 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1976 setbuf(stdin, NULL);
1977 setbuf(stdout, NULL);
1978 setbuf(stderr, NULL);
1982 if (argc >= 2 && string(argv[1]) == "-server")
1984 printf("server ready\n");
1985 ThreadRPCServer(NULL);
1989 return CommandLineRPC(argc, argv);
1992 catch (std::exception& e) {
1993 PrintException(&e, "main()");
1995 PrintException(NULL, "main()");