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"
9 #include <boost/asio.hpp>
10 #include <boost/iostreams/concepts.hpp>
11 #include <boost/iostreams/stream.hpp>
13 #include <boost/asio/ssl.hpp>
14 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
16 #include "json/json_spirit_reader_template.h"
17 #include "json/json_spirit_writer_template.h"
18 #include "json/json_spirit_utils.h"
19 #define printf OutputDebugStringF
20 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
21 // precompiled in headers.h. The problem might be when the pch file goes over
22 // a certain size around 145MB. If we need access to json_spirit outside this
23 // file, we could use the compiled json_spirit option.
26 using namespace boost;
27 using namespace boost::asio;
28 using namespace json_spirit;
30 void ThreadRPCServer2(void* parg);
31 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
32 extern map<string, rpcfn_type> mapCallTable;
35 Object JSONRPCError(int code, const string& message)
38 error.push_back(Pair("code", code));
39 error.push_back(Pair("message", message));
44 void PrintConsole(const char* format, ...)
47 int limit = sizeof(buffer);
49 va_start(arg_ptr, format);
50 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
52 if (ret < 0 || ret >= limit)
58 #if defined(__WXMSW__) && defined(GUI)
59 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
61 fprintf(stdout, "%s", buffer);
66 int64 AmountFromValue(const Value& value)
68 double dAmount = value.get_real();
69 if (dAmount <= 0.0 || dAmount > 21000000.0)
70 throw JSONRPCError(-3, "Invalid amount");
71 int64 nAmount = roundint64(dAmount * COIN);
72 if (!MoneyRange(nAmount))
73 throw JSONRPCError(-3, "Invalid amount");
77 Value ValueFromAmount(int64 amount)
79 return (double)amount / (double)COIN;
82 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
84 entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
85 entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
86 entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
87 BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
88 entry.push_back(Pair(item.first, item.second));
91 string AccountFromValue(const Value& value)
93 string strAccount = value.get_str();
94 if (strAccount == "*")
95 throw JSONRPCError(-11, "Invalid account name");
102 /// Note: This interface may still be subject to change.
106 Value help(const Array& params, bool fHelp)
108 if (fHelp || params.size() > 1)
111 "List commands, or get help for a command.");
114 if (params.size() > 0)
115 strCommand = params[0].get_str();
118 set<rpcfn_type> setDone;
119 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
121 string strMethod = (*mi).first;
122 // We already filter duplicates, but these deprecated screw up the sort order
123 if (strMethod == "getamountreceived" ||
124 strMethod == "getallreceived" ||
125 (strMethod.find("label") != string::npos))
127 if (strCommand != "" && strMethod != strCommand)
132 rpcfn_type pfn = (*mi).second;
133 if (setDone.insert(pfn).second)
134 (*pfn)(params, true);
136 catch (std::exception& e)
138 // Help text is returned in an exception
139 string strHelp = string(e.what());
140 if (strCommand == "")
141 if (strHelp.find('\n') != -1)
142 strHelp = strHelp.substr(0, strHelp.find('\n'));
143 strRet += strHelp + "\n";
147 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
148 strRet = strRet.substr(0,strRet.size()-1);
153 Value stop(const Array& params, bool fHelp)
155 if (fHelp || params.size() != 0)
158 "Stop bitcoin server.");
160 // Shutdown will take long enough that the response should get back
161 CreateThread(Shutdown, NULL);
162 return "bitcoin server stopping";
166 Value getblockcount(const Array& params, bool fHelp)
168 if (fHelp || params.size() != 0)
171 "Returns the number of blocks in the longest block chain.");
177 Value getblocknumber(const Array& params, bool fHelp)
179 if (fHelp || params.size() != 0)
182 "Returns the block number of the latest block in the longest block chain.");
188 Value getconnectioncount(const Array& params, bool fHelp)
190 if (fHelp || params.size() != 0)
192 "getconnectioncount\n"
193 "Returns the number of connections to other nodes.");
195 return (int)vNodes.size();
199 double GetDifficulty()
201 // Floating point number that is a multiple of the minimum difficulty,
202 // minimum difficulty = 1.0.
203 if (pindexBest == NULL)
205 int nShift = 256 - 32 - 31; // to fit in a uint
206 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
207 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
208 return dMinimum / dCurrently;
211 Value getdifficulty(const Array& params, bool fHelp)
213 if (fHelp || params.size() != 0)
216 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
218 return GetDifficulty();
222 Value getgenerate(const Array& params, bool fHelp)
224 if (fHelp || params.size() != 0)
227 "Returns true or false.");
229 return (bool)fGenerateBitcoins;
233 Value setgenerate(const Array& params, bool fHelp)
235 if (fHelp || params.size() < 1 || params.size() > 2)
237 "setgenerate <generate> [genproclimit]\n"
238 "<generate> is true or false to turn generation on or off.\n"
239 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
241 bool fGenerate = true;
242 if (params.size() > 0)
243 fGenerate = params[0].get_bool();
245 if (params.size() > 1)
247 int nGenProcLimit = params[1].get_int();
248 fLimitProcessors = (nGenProcLimit != -1);
249 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
250 if (nGenProcLimit != -1)
251 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
252 if (nGenProcLimit == 0)
256 GenerateBitcoins(fGenerate);
261 Value gethashespersec(const Array& params, bool fHelp)
263 if (fHelp || params.size() != 0)
266 "Returns a recent hashes per second performance measurement while generating.");
268 if (GetTimeMillis() - nHPSTimerStart > 8000)
269 return (boost::int64_t)0;
270 return (boost::int64_t)dHashesPerSec;
274 Value getinfo(const Array& params, bool fHelp)
276 if (fHelp || params.size() != 0)
279 "Returns an object containing various state info.");
282 obj.push_back(Pair("version", (int)VERSION));
283 obj.push_back(Pair("balance", ValueFromAmount(GetBalance())));
284 obj.push_back(Pair("blocks", (int)nBestHeight));
285 obj.push_back(Pair("connections", (int)vNodes.size()));
286 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
287 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
288 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
289 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
290 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
291 obj.push_back(Pair("testnet", fTestNet));
292 obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
293 obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
294 obj.push_back(Pair("errors", GetWarnings("statusbar")));
299 Value getnewaddress(const Array& params, bool fHelp)
301 if (fHelp || params.size() > 1)
303 "getnewaddress [account]\n"
304 "Returns a new bitcoin address for receiving payments. "
305 "If [account] is specified (recommended), it is added to the address book "
306 "so payments received with the address will be credited to [account].");
308 // Parse the account first so we don't generate a key if there's an error
310 if (params.size() > 0)
311 strAccount = AccountFromValue(params[0]);
313 // Generate a new key that is added to wallet
314 string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
316 SetAddressBookName(strAddress, strAccount);
321 // requires cs_main, cs_mapWallet locks
322 string GetAccountAddress(string strAccount, bool bForceNew=false)
330 walletdb.ReadAccount(strAccount, account);
332 // Check if the current key has been used
333 if (!account.vchPubKey.empty())
335 CScript scriptPubKey;
336 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
337 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
338 it != mapWallet.end() && !account.vchPubKey.empty();
341 const CWalletTx& wtx = (*it).second;
342 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
343 if (txout.scriptPubKey == scriptPubKey)
344 account.vchPubKey.clear();
348 // Generate a new key
349 if (account.vchPubKey.empty() || bForceNew)
351 account.vchPubKey = GetKeyFromKeyPool();
352 string strAddress = PubKeyToAddress(account.vchPubKey);
353 SetAddressBookName(strAddress, strAccount);
354 walletdb.WriteAccount(strAccount, account);
357 walletdb.TxnCommit();
358 strAddress = PubKeyToAddress(account.vchPubKey);
363 Value getaccountaddress(const Array& params, bool fHelp)
365 if (fHelp || params.size() != 1)
367 "getaccountaddress <account>\n"
368 "Returns the current bitcoin address for receiving payments to this account.");
370 // Parse the account first so we don't generate a key if there's an error
371 string strAccount = AccountFromValue(params[0]);
375 CRITICAL_BLOCK(cs_main)
376 CRITICAL_BLOCK(cs_mapWallet)
378 ret = GetAccountAddress(strAccount);
386 Value setaccount(const Array& params, bool fHelp)
388 if (fHelp || params.size() < 1 || params.size() > 2)
390 "setaccount <bitcoinaddress> <account>\n"
391 "Sets the account associated with the given address.");
393 string strAddress = params[0].get_str();
395 bool isValid = AddressToHash160(strAddress, hash160);
397 throw JSONRPCError(-5, "Invalid bitcoin address");
401 if (params.size() > 1)
402 strAccount = AccountFromValue(params[1]);
404 // Detect when changing the account of an address that is the 'unused current key' of another account:
405 CRITICAL_BLOCK(cs_main)
406 CRITICAL_BLOCK(cs_mapWallet)
407 CRITICAL_BLOCK(cs_mapAddressBook)
409 if (mapAddressBook.count(strAddress))
411 string strOldAccount = mapAddressBook[strAddress];
412 if (strAddress == GetAccountAddress(strOldAccount))
413 GetAccountAddress(strOldAccount, true);
417 SetAddressBookName(strAddress, strAccount);
422 Value getaccount(const Array& params, bool fHelp)
424 if (fHelp || params.size() != 1)
426 "getaccount <bitcoinaddress>\n"
427 "Returns the account associated with the given address.");
429 string strAddress = params[0].get_str();
432 CRITICAL_BLOCK(cs_mapAddressBook)
434 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
435 if (mi != mapAddressBook.end() && !(*mi).second.empty())
436 strAccount = (*mi).second;
442 Value getaddressesbyaccount(const Array& params, bool fHelp)
444 if (fHelp || params.size() != 1)
446 "getaddressesbyaccount <account>\n"
447 "Returns the list of addresses for the given account.");
449 string strAccount = AccountFromValue(params[0]);
451 // Find all addresses that have the given account
453 CRITICAL_BLOCK(cs_mapAddressBook)
455 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
457 const string& strAddress = item.first;
458 const string& strName = item.second;
459 if (strName == strAccount)
461 // We're only adding valid bitcoin addresses and not ip addresses
462 CScript scriptPubKey;
463 if (scriptPubKey.SetBitcoinAddress(strAddress))
464 ret.push_back(strAddress);
471 Value settxfee(const Array& params, bool fHelp)
473 if (fHelp || params.size() < 1 || params.size() > 1)
475 "settxfee <amount>\n"
476 "<amount> is a real and is rounded to the nearest 0.00000001");
480 if (params[0].get_real() != 0.0)
481 nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
483 nTransactionFee = nAmount;
487 Value sendtoaddress(const Array& params, bool fHelp)
489 if (fHelp || params.size() < 2 || params.size() > 4)
491 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
492 "<amount> is a real and is rounded to the nearest 0.00000001");
494 string strAddress = params[0].get_str();
497 int64 nAmount = AmountFromValue(params[1]);
501 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
502 wtx.mapValue["comment"] = params[2].get_str();
503 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
504 wtx.mapValue["to"] = params[3].get_str();
506 CRITICAL_BLOCK(cs_main)
508 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
510 throw JSONRPCError(-4, strError);
513 return wtx.GetHash().GetHex();
517 Value getreceivedbyaddress(const Array& params, bool fHelp)
519 if (fHelp || params.size() < 1 || params.size() > 2)
521 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
522 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
525 string strAddress = params[0].get_str();
526 CScript scriptPubKey;
527 if (!scriptPubKey.SetBitcoinAddress(strAddress))
528 throw JSONRPCError(-5, "Invalid bitcoin address");
529 if (!IsMine(scriptPubKey))
532 // Minimum confirmations
534 if (params.size() > 1)
535 nMinDepth = params[1].get_int();
539 CRITICAL_BLOCK(cs_mapWallet)
541 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
543 const CWalletTx& wtx = (*it).second;
544 if (wtx.IsCoinBase() || !wtx.IsFinal())
547 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
548 if (txout.scriptPubKey == scriptPubKey)
549 if (wtx.GetDepthInMainChain() >= nMinDepth)
550 nAmount += txout.nValue;
554 return ValueFromAmount(nAmount);
558 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
560 CRITICAL_BLOCK(cs_mapAddressBook)
562 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
564 const string& strAddress = item.first;
565 const string& strName = item.second;
566 if (strName == strAccount)
568 // We're only counting our own valid bitcoin addresses and not ip addresses
569 CScript scriptPubKey;
570 if (scriptPubKey.SetBitcoinAddress(strAddress))
571 if (IsMine(scriptPubKey))
572 setPubKey.insert(scriptPubKey);
579 Value getreceivedbyaccount(const Array& params, bool fHelp)
581 if (fHelp || params.size() < 1 || params.size() > 2)
583 "getreceivedbyaccount <account> [minconf=1]\n"
584 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
586 // Minimum confirmations
588 if (params.size() > 1)
589 nMinDepth = params[1].get_int();
591 // Get the set of pub keys that have the label
592 string strAccount = AccountFromValue(params[0]);
593 set<CScript> setPubKey;
594 GetAccountPubKeys(strAccount, setPubKey);
598 CRITICAL_BLOCK(cs_mapWallet)
600 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
602 const CWalletTx& wtx = (*it).second;
603 if (wtx.IsCoinBase() || !wtx.IsFinal())
606 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
607 if (setPubKey.count(txout.scriptPubKey))
608 if (wtx.GetDepthInMainChain() >= nMinDepth)
609 nAmount += txout.nValue;
613 return (double)nAmount / (double)COIN;
617 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
620 CRITICAL_BLOCK(cs_mapWallet)
622 // Tally wallet transactions
623 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
625 const CWalletTx& wtx = (*it).second;
629 int64 nGenerated, nReceived, nSent, nFee;
630 wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
632 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
633 nBalance += nReceived;
634 nBalance += nGenerated - nSent - nFee;
637 // Tally internal accounting entries
638 nBalance += walletdb.GetAccountCreditDebit(strAccount);
644 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
647 return GetAccountBalance(walletdb, strAccount, nMinDepth);
651 Value getbalance(const Array& params, bool fHelp)
653 if (fHelp || params.size() < 0 || params.size() > 2)
655 "getbalance [account] [minconf=1]\n"
656 "If [account] is not specified, returns the server's total available balance.\n"
657 "If [account] is specified, returns the balance in the account.");
659 if (params.size() == 0)
660 return ValueFromAmount(GetBalance());
663 if (params.size() > 1)
664 nMinDepth = params[1].get_int();
666 if (params[0].get_str() == "*") {
667 // Calculate total balance a different way from GetBalance()
668 // (GetBalance() sums up all unspent TxOuts)
669 // getbalance and getbalance '*' should always return the same number.
671 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
673 const CWalletTx& wtx = (*it).second;
677 int64 allGeneratedImmature, allGeneratedMature, allFee;
678 allGeneratedImmature = allGeneratedMature = allFee = 0;
679 string strSentAccount;
680 list<pair<string, int64> > listReceived;
681 list<pair<string, int64> > listSent;
682 wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
683 if (wtx.GetDepthInMainChain() >= nMinDepth)
684 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
685 nBalance += r.second;
686 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
687 nBalance -= r.second;
689 nBalance += allGeneratedMature;
691 return ValueFromAmount(nBalance);
694 string strAccount = AccountFromValue(params[0]);
696 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
698 return ValueFromAmount(nBalance);
702 Value movecmd(const Array& params, bool fHelp)
704 if (fHelp || params.size() < 3 || params.size() > 5)
706 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
707 "Move from one account in your wallet to another.");
709 string strFrom = AccountFromValue(params[0]);
710 string strTo = AccountFromValue(params[1]);
711 int64 nAmount = AmountFromValue(params[2]);
713 if (params.size() > 3)
714 nMinDepth = params[3].get_int();
716 if (params.size() > 4)
717 strComment = params[4].get_str();
719 CRITICAL_BLOCK(cs_mapWallet)
724 int64 nNow = GetAdjustedTime();
727 CAccountingEntry debit;
728 debit.strAccount = strFrom;
729 debit.nCreditDebit = -nAmount;
731 debit.strOtherAccount = strTo;
732 debit.strComment = strComment;
733 walletdb.WriteAccountingEntry(debit);
736 CAccountingEntry credit;
737 credit.strAccount = strTo;
738 credit.nCreditDebit = nAmount;
740 credit.strOtherAccount = strFrom;
741 credit.strComment = strComment;
742 walletdb.WriteAccountingEntry(credit);
744 walletdb.TxnCommit();
750 Value sendfrom(const Array& params, bool fHelp)
752 if (fHelp || params.size() < 3 || params.size() > 6)
754 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
755 "<amount> is a real and is rounded to the nearest 0.00000001");
757 string strAccount = AccountFromValue(params[0]);
758 string strAddress = params[1].get_str();
759 int64 nAmount = AmountFromValue(params[2]);
761 if (params.size() > 3)
762 nMinDepth = params[3].get_int();
765 wtx.strFromAccount = strAccount;
766 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
767 wtx.mapValue["comment"] = params[4].get_str();
768 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
769 wtx.mapValue["to"] = params[5].get_str();
771 CRITICAL_BLOCK(cs_main)
772 CRITICAL_BLOCK(cs_mapWallet)
775 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
776 if (nAmount > nBalance)
777 throw JSONRPCError(-6, "Account has insufficient funds");
780 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
782 throw JSONRPCError(-4, strError);
785 return wtx.GetHash().GetHex();
788 Value sendmany(const Array& params, bool fHelp)
790 if (fHelp || params.size() < 2 || params.size() > 4)
792 "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
793 "amounts are double-precision floating point numbers");
795 string strAccount = AccountFromValue(params[0]);
796 Object sendTo = params[1].get_obj();
798 if (params.size() > 2)
799 nMinDepth = params[2].get_int();
802 wtx.strFromAccount = strAccount;
803 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
804 wtx.mapValue["comment"] = params[3].get_str();
806 set<string> setAddress;
807 vector<pair<CScript, int64> > vecSend;
809 int64 totalAmount = 0;
810 BOOST_FOREACH(const Pair& s, sendTo)
813 string strAddress = s.name_;
815 if (setAddress.count(strAddress))
816 throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
817 setAddress.insert(strAddress);
819 CScript scriptPubKey;
820 if (!scriptPubKey.SetBitcoinAddress(strAddress))
821 throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
822 int64 nAmount = AmountFromValue(s.value_);
823 totalAmount += nAmount;
825 vecSend.push_back(make_pair(scriptPubKey, nAmount));
828 CRITICAL_BLOCK(cs_main)
829 CRITICAL_BLOCK(cs_mapWallet)
832 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
833 if (totalAmount > nBalance)
834 throw JSONRPCError(-6, "Account has insufficient funds");
837 CReserveKey keyChange;
838 int64 nFeeRequired = 0;
839 bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
842 if (totalAmount + nFeeRequired > GetBalance())
843 throw JSONRPCError(-6, "Insufficient funds");
844 throw JSONRPCError(-4, "Transaction creation failed");
846 if (!CommitTransaction(wtx, keyChange))
847 throw JSONRPCError(-4, "Transaction commit failed");
850 return wtx.GetHash().GetHex();
865 Value ListReceived(const Array& params, bool fByAccounts)
867 // Minimum confirmations
869 if (params.size() > 0)
870 nMinDepth = params[0].get_int();
872 // Whether to include empty accounts
873 bool fIncludeEmpty = false;
874 if (params.size() > 1)
875 fIncludeEmpty = params[1].get_bool();
878 map<uint160, tallyitem> mapTally;
879 CRITICAL_BLOCK(cs_mapWallet)
881 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
883 const CWalletTx& wtx = (*it).second;
884 if (wtx.IsCoinBase() || !wtx.IsFinal())
887 int nDepth = wtx.GetDepthInMainChain();
888 if (nDepth < nMinDepth)
891 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
893 // Only counting our own bitcoin addresses and not ip addresses
894 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
895 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
898 tallyitem& item = mapTally[hash160];
899 item.nAmount += txout.nValue;
900 item.nConf = min(item.nConf, nDepth);
907 map<string, tallyitem> mapAccountTally;
908 CRITICAL_BLOCK(cs_mapAddressBook)
910 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
912 const string& strAddress = item.first;
913 const string& strAccount = item.second;
915 if (!AddressToHash160(strAddress, hash160))
917 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
918 if (it == mapTally.end() && !fIncludeEmpty)
923 if (it != mapTally.end())
925 nAmount = (*it).second.nAmount;
926 nConf = (*it).second.nConf;
931 tallyitem& item = mapAccountTally[strAccount];
932 item.nAmount += nAmount;
933 item.nConf = min(item.nConf, nConf);
938 obj.push_back(Pair("address", strAddress));
939 obj.push_back(Pair("account", strAccount));
940 obj.push_back(Pair("label", strAccount)); // deprecated
941 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
942 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
950 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
952 int64 nAmount = (*it).second.nAmount;
953 int nConf = (*it).second.nConf;
955 obj.push_back(Pair("account", (*it).first));
956 obj.push_back(Pair("label", (*it).first)); // deprecated
957 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
958 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
966 Value listreceivedbyaddress(const Array& params, bool fHelp)
968 if (fHelp || params.size() > 2)
970 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
971 "[minconf] is the minimum number of confirmations before payments are included.\n"
972 "[includeempty] whether to include addresses that haven't received any payments.\n"
973 "Returns an array of objects containing:\n"
974 " \"address\" : receiving address\n"
975 " \"account\" : the account of the receiving address\n"
976 " \"amount\" : total amount received by the address\n"
977 " \"confirmations\" : number of confirmations of the most recent transaction included");
979 return ListReceived(params, false);
982 Value listreceivedbyaccount(const Array& params, bool fHelp)
984 if (fHelp || params.size() > 2)
986 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
987 "[minconf] is the minimum number of confirmations before payments are included.\n"
988 "[includeempty] whether to include accounts that haven't received any payments.\n"
989 "Returns an array of objects containing:\n"
990 " \"account\" : the account of the receiving addresses\n"
991 " \"amount\" : total amount received by addresses with this account\n"
992 " \"confirmations\" : number of confirmations of the most recent transaction included");
994 return ListReceived(params, true);
997 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
999 int64 nGeneratedImmature, nGeneratedMature, nFee;
1000 string strSentAccount;
1001 list<pair<string, int64> > listReceived;
1002 list<pair<string, int64> > listSent;
1003 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1005 bool fAllAccounts = (strAccount == string("*"));
1007 // Generated blocks assigned to account ""
1008 if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
1011 entry.push_back(Pair("account", string("")));
1012 if (nGeneratedImmature)
1014 entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
1015 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
1019 entry.push_back(Pair("category", "generate"));
1020 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
1023 WalletTxToJSON(wtx, entry);
1024 ret.push_back(entry);
1028 if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
1030 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1033 entry.push_back(Pair("account", strSentAccount));
1034 entry.push_back(Pair("address", s.first));
1035 entry.push_back(Pair("category", "send"));
1036 entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
1037 entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
1039 WalletTxToJSON(wtx, entry);
1040 ret.push_back(entry);
1045 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1046 CRITICAL_BLOCK(cs_mapAddressBook)
1048 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1051 if (mapAddressBook.count(r.first))
1052 account = mapAddressBook[r.first];
1053 if (fAllAccounts || (account == strAccount))
1056 entry.push_back(Pair("account", account));
1057 entry.push_back(Pair("address", r.first));
1058 entry.push_back(Pair("category", "receive"));
1059 entry.push_back(Pair("amount", ValueFromAmount(r.second)));
1061 WalletTxToJSON(wtx, entry);
1062 ret.push_back(entry);
1069 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
1071 bool fAllAccounts = (strAccount == string("*"));
1073 if (fAllAccounts || acentry.strAccount == strAccount)
1076 entry.push_back(Pair("account", acentry.strAccount));
1077 entry.push_back(Pair("category", "move"));
1078 entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
1079 entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
1080 entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
1081 entry.push_back(Pair("comment", acentry.strComment));
1082 ret.push_back(entry);
1086 Value listtransactions(const Array& params, bool fHelp)
1088 if (fHelp || params.size() > 3)
1089 throw runtime_error(
1090 "listtransactions [account] [count=10] [from=0]\n"
1091 "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
1093 string strAccount = "*";
1094 if (params.size() > 0)
1095 strAccount = params[0].get_str();
1097 if (params.size() > 1)
1098 nCount = params[1].get_int();
1100 if (params.size() > 2)
1101 nFrom = params[2].get_int();
1106 CRITICAL_BLOCK(cs_mapWallet)
1108 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
1109 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
1110 typedef multimap<int64, TxPair > TxItems;
1113 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1115 CWalletTx* wtx = &((*it).second);
1116 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
1118 list<CAccountingEntry> acentries;
1119 walletdb.ListAccountCreditDebit(strAccount, acentries);
1120 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1122 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
1125 // Now: iterate backwards until we have nCount items to return:
1126 TxItems::reverse_iterator it = txByTime.rbegin();
1127 for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
1129 CWalletTx *const pwtx = (*it).second.first;
1131 ListTransactions(*pwtx, strAccount, 0, true, ret);
1132 CAccountingEntry *const pacentry = (*it).second.second;
1134 AcentryToJSON(*pacentry, strAccount, ret);
1136 if (ret.size() >= nCount) break;
1138 // ret is now newest to oldest
1141 // Make sure we return only last nCount items (sends-to-self might give us an extra):
1142 if (ret.size() > nCount)
1144 Array::iterator last = ret.begin();
1145 std::advance(last, nCount);
1146 ret.erase(last, ret.end());
1148 std::reverse(ret.begin(), ret.end()); // oldest to newest
1153 Value listaccounts(const Array& params, bool fHelp)
1155 if (fHelp || params.size() > 1)
1156 throw runtime_error(
1157 "listaccounts [minconf=1]\n"
1158 "Returns Object that has account names as keys, account balances as values.");
1161 if (params.size() > 0)
1162 nMinDepth = params[0].get_int();
1164 map<string, int64> mapAccountBalances;
1165 CRITICAL_BLOCK(cs_mapWallet)
1166 CRITICAL_BLOCK(cs_mapAddressBook)
1168 BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
1170 if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
1171 mapAccountBalances[entry.second] = 0;
1174 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1176 const CWalletTx& wtx = (*it).second;
1177 int64 nGeneratedImmature, nGeneratedMature, nFee;
1178 string strSentAccount;
1179 list<pair<string, int64> > listReceived;
1180 list<pair<string, int64> > listSent;
1181 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1182 mapAccountBalances[strSentAccount] -= nFee;
1183 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1184 mapAccountBalances[strSentAccount] -= s.second;
1185 if (wtx.GetDepthInMainChain() >= nMinDepth)
1187 mapAccountBalances[""] += nGeneratedMature;
1188 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1189 if (mapAddressBook.count(r.first))
1190 mapAccountBalances[mapAddressBook[r.first]] += r.second;
1192 mapAccountBalances[""] += r.second;
1197 list<CAccountingEntry> acentries;
1198 CWalletDB().ListAccountCreditDebit("*", acentries);
1199 BOOST_FOREACH(const CAccountingEntry& entry, acentries)
1200 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1203 BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1204 ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1209 Value gettransaction(const Array& params, bool fHelp)
1211 if (fHelp || params.size() != 1)
1212 throw runtime_error(
1213 "gettransaction <txid>\n"
1214 "Get detailed information about <txid>");
1217 hash.SetHex(params[0].get_str());
1220 CRITICAL_BLOCK(cs_mapWallet)
1222 if (!mapWallet.count(hash))
1223 throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
1224 const CWalletTx& wtx = mapWallet[hash];
1226 int64 nCredit = wtx.GetCredit();
1227 int64 nDebit = wtx.GetDebit();
1228 int64 nNet = nCredit - nDebit;
1229 int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1231 entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1233 entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1235 WalletTxToJSON(mapWallet[hash], entry);
1238 ListTransactions(mapWallet[hash], "*", 0, false, details);
1239 entry.push_back(Pair("details", details));
1246 Value backupwallet(const Array& params, bool fHelp)
1248 if (fHelp || params.size() != 1)
1249 throw runtime_error(
1250 "backupwallet <destination>\n"
1251 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1253 string strDest = params[0].get_str();
1254 BackupWallet(strDest);
1260 Value validateaddress(const Array& params, bool fHelp)
1262 if (fHelp || params.size() != 1)
1263 throw runtime_error(
1264 "validateaddress <bitcoinaddress>\n"
1265 "Return information about <bitcoinaddress>.");
1267 string strAddress = params[0].get_str();
1269 bool isValid = AddressToHash160(strAddress, hash160);
1272 ret.push_back(Pair("isvalid", isValid));
1275 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1276 // version of the address:
1277 string currentAddress = Hash160ToAddress(hash160);
1278 ret.push_back(Pair("address", currentAddress));
1279 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1280 CRITICAL_BLOCK(cs_mapAddressBook)
1282 if (mapAddressBook.count(currentAddress))
1283 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
1290 Value getwork(const Array& params, bool fHelp)
1292 if (fHelp || params.size() > 1)
1293 throw runtime_error(
1295 "If [data] is not specified, returns formatted hash data to work on:\n"
1296 " \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1297 " \"data\" : block data\n"
1298 " \"hash1\" : formatted hash buffer for second hash\n"
1299 " \"target\" : little endian hash target\n"
1300 "If [data] is specified, tries to solve the block and returns true if it was successful.");
1303 throw JSONRPCError(-9, "Bitcoin is not connected!");
1305 if (IsInitialBlockDownload())
1306 throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1308 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1309 static vector<CBlock*> vNewBlock;
1310 static CReserveKey reservekey;
1312 if (params.size() == 0)
1315 static unsigned int nTransactionsUpdatedLast;
1316 static CBlockIndex* pindexPrev;
1317 static int64 nStart;
1318 static CBlock* pblock;
1319 if (pindexPrev != pindexBest ||
1320 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1322 if (pindexPrev != pindexBest)
1324 // Deallocate old blocks since they're obsolete now
1325 mapNewBlock.clear();
1326 BOOST_FOREACH(CBlock* pblock, vNewBlock)
1330 nTransactionsUpdatedLast = nTransactionsUpdated;
1331 pindexPrev = pindexBest;
1335 pblock = CreateNewBlock(reservekey);
1337 throw JSONRPCError(-7, "Out of memory");
1338 vNewBlock.push_back(pblock);
1342 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1345 // Update nExtraNonce
1346 static unsigned int nExtraNonce = 0;
1347 static int64 nPrevTime = 0;
1348 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1351 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1353 // Prebuild hash buffers
1357 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1359 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1362 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1363 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
1364 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
1365 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
1371 vector<unsigned char> vchData = ParseHex(params[0].get_str());
1372 if (vchData.size() != 128)
1373 throw JSONRPCError(-8, "Invalid parameter");
1374 CBlock* pdata = (CBlock*)&vchData[0];
1377 for (int i = 0; i < 128/4; i++)
1378 ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1381 if (!mapNewBlock.count(pdata->hashMerkleRoot))
1383 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1384 unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1386 pblock->nTime = pdata->nTime;
1387 pblock->nNonce = pdata->nNonce;
1388 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1389 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1391 return CheckWork(pblock, reservekey);
1409 pair<string, rpcfn_type> pCallTable[] =
1411 make_pair("help", &help),
1412 make_pair("stop", &stop),
1413 make_pair("getblockcount", &getblockcount),
1414 make_pair("getblocknumber", &getblocknumber),
1415 make_pair("getconnectioncount", &getconnectioncount),
1416 make_pair("getdifficulty", &getdifficulty),
1417 make_pair("getgenerate", &getgenerate),
1418 make_pair("setgenerate", &setgenerate),
1419 make_pair("gethashespersec", &gethashespersec),
1420 make_pair("getinfo", &getinfo),
1421 make_pair("getnewaddress", &getnewaddress),
1422 make_pair("getaccountaddress", &getaccountaddress),
1423 make_pair("setaccount", &setaccount),
1424 make_pair("setlabel", &setaccount), // deprecated
1425 make_pair("getaccount", &getaccount),
1426 make_pair("getlabel", &getaccount), // deprecated
1427 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1428 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
1429 make_pair("sendtoaddress", &sendtoaddress),
1430 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1431 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1432 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
1433 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
1434 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
1435 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1436 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1437 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
1438 make_pair("backupwallet", &backupwallet),
1439 make_pair("validateaddress", &validateaddress),
1440 make_pair("getbalance", &getbalance),
1441 make_pair("move", &movecmd),
1442 make_pair("sendfrom", &sendfrom),
1443 make_pair("sendmany", &sendmany),
1444 make_pair("gettransaction", &gettransaction),
1445 make_pair("listtransactions", &listtransactions),
1446 make_pair("getwork", &getwork),
1447 make_pair("listaccounts", &listaccounts),
1448 make_pair("settxfee", &settxfee),
1450 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1452 string pAllowInSafeMode[] =
1458 "getconnectioncount",
1465 "getaccountaddress",
1468 "getlabel", // deprecated
1469 "getaddressesbyaccount",
1470 "getaddressesbylabel", // deprecated
1475 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1483 // This ain't Apache. We're just using HTTP header for the length field
1484 // and to be compatible with other JSON-RPC implementations.
1487 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1490 s << "POST / HTTP/1.1\r\n"
1491 << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
1492 << "Host: 127.0.0.1\r\n"
1493 << "Content-Type: application/json\r\n"
1494 << "Content-Length: " << strMsg.size() << "\r\n"
1495 << "Accept: application/json\r\n";
1496 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1497 s << item.first << ": " << item.second << "\r\n";
1498 s << "\r\n" << strMsg;
1503 string rfc1123Time()
1508 struct tm* now_gmt = gmtime(&now);
1509 string locale(setlocale(LC_TIME, NULL));
1510 setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
1511 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
1512 setlocale(LC_TIME, locale.c_str());
1513 return string(buffer);
1516 string HTTPReply(int nStatus, const string& strMsg)
1519 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1521 "Server: bitcoin-json-rpc/%s\r\n"
1522 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1523 "Content-Type: text/html\r\n"
1524 "Content-Length: 296\r\n"
1526 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1527 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1530 "<TITLE>Error</TITLE>\r\n"
1531 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1533 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1534 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
1536 if (nStatus == 200) strStatus = "OK";
1537 else if (nStatus == 400) strStatus = "Bad Request";
1538 else if (nStatus == 404) strStatus = "Not Found";
1539 else if (nStatus == 500) strStatus = "Internal Server Error";
1541 "HTTP/1.1 %d %s\r\n"
1543 "Connection: close\r\n"
1544 "Content-Length: %d\r\n"
1545 "Content-Type: application/json\r\n"
1546 "Server: bitcoin-json-rpc/%s\r\n"
1551 rfc1123Time().c_str(),
1553 FormatFullVersion().c_str(),
1557 int ReadHTTPStatus(std::basic_istream<char>& stream)
1560 getline(stream, str);
1561 vector<string> vWords;
1562 boost::split(vWords, str, boost::is_any_of(" "));
1563 if (vWords.size() < 2)
1565 return atoi(vWords[1].c_str());
1568 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1574 std::getline(stream, str);
1575 if (str.empty() || str == "\r")
1577 string::size_type nColon = str.find(":");
1578 if (nColon != string::npos)
1580 string strHeader = str.substr(0, nColon);
1581 boost::trim(strHeader);
1582 boost::to_lower(strHeader);
1583 string strValue = str.substr(nColon+1);
1584 boost::trim(strValue);
1585 mapHeadersRet[strHeader] = strValue;
1586 if (strHeader == "content-length")
1587 nLen = atoi(strValue.c_str());
1593 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1595 mapHeadersRet.clear();
1599 int nStatus = ReadHTTPStatus(stream);
1602 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1603 if (nLen < 0 || nLen > MAX_SIZE)
1609 vector<char> vch(nLen);
1610 stream.read(&vch[0], nLen);
1611 strMessageRet = string(vch.begin(), vch.end());
1617 string EncodeBase64(string s)
1622 b64 = BIO_new(BIO_f_base64());
1623 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1624 bmem = BIO_new(BIO_s_mem());
1625 b64 = BIO_push(b64, bmem);
1626 BIO_write(b64, s.c_str(), s.size());
1628 BIO_get_mem_ptr(b64, &bptr);
1630 string result(bptr->data, bptr->length);
1636 string DecodeBase64(string s)
1640 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1642 b64 = BIO_new(BIO_f_base64());
1643 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1644 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1645 bmem = BIO_push(b64, bmem);
1646 BIO_read(bmem, buffer, s.size());
1649 string result(buffer);
1654 bool HTTPAuthorized(map<string, string>& mapHeaders)
1656 string strAuth = mapHeaders["authorization"];
1657 if (strAuth.substr(0,6) != "Basic ")
1659 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1660 string strUserPass = DecodeBase64(strUserPass64);
1661 string::size_type nColon = strUserPass.find(":");
1662 if (nColon == string::npos)
1664 string strUser = strUserPass.substr(0, nColon);
1665 string strPassword = strUserPass.substr(nColon+1);
1666 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1670 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1671 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1672 // unspecified (HTTP errors and contents of 'error').
1674 // 1.0 spec: http://json-rpc.org/wiki/specification
1675 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1676 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1679 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1682 request.push_back(Pair("method", strMethod));
1683 request.push_back(Pair("params", params));
1684 request.push_back(Pair("id", id));
1685 return write_string(Value(request), false) + "\n";
1688 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1691 if (error.type() != null_type)
1692 reply.push_back(Pair("result", Value::null));
1694 reply.push_back(Pair("result", result));
1695 reply.push_back(Pair("error", error));
1696 reply.push_back(Pair("id", id));
1697 return write_string(Value(reply), false) + "\n";
1700 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1702 // Send error reply from json-rpc error object
1704 int code = find_value(objError, "code").get_int();
1705 if (code == -32600) nStatus = 400;
1706 else if (code == -32601) nStatus = 404;
1707 string strReply = JSONRPCReply(Value::null, objError, id);
1708 stream << HTTPReply(nStatus, strReply) << std::flush;
1711 bool ClientAllowed(const string& strAddress)
1713 if (strAddress == asio::ip::address_v4::loopback().to_string())
1715 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1716 BOOST_FOREACH(string strAllow, vAllow)
1717 if (WildcardMatch(strAddress, strAllow))
1724 // IOStream device that speaks SSL but can also speak non-SSL
1726 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1728 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1730 fUseSSL = fUseSSLIn;
1731 fNeedHandshake = fUseSSLIn;
1734 void handshake(ssl::stream_base::handshake_type role)
1736 if (!fNeedHandshake) return;
1737 fNeedHandshake = false;
1738 stream.handshake(role);
1740 std::streamsize read(char* s, std::streamsize n)
1742 handshake(ssl::stream_base::server); // HTTPS servers read first
1743 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1744 return stream.next_layer().read_some(asio::buffer(s, n));
1746 std::streamsize write(const char* s, std::streamsize n)
1748 handshake(ssl::stream_base::client); // HTTPS clients write first
1749 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1750 return asio::write(stream.next_layer(), asio::buffer(s, n));
1752 bool connect(const std::string& server, const std::string& port)
1754 ip::tcp::resolver resolver(stream.get_io_service());
1755 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1756 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1757 ip::tcp::resolver::iterator end;
1758 boost::system::error_code error = asio::error::host_not_found;
1759 while (error && endpoint_iterator != end)
1761 stream.lowest_layer().close();
1762 stream.lowest_layer().connect(*endpoint_iterator++, error);
1770 bool fNeedHandshake;
1776 void ThreadRPCServer(void* parg)
1778 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1781 vnThreadsRunning[4]++;
1782 ThreadRPCServer2(parg);
1783 vnThreadsRunning[4]--;
1785 catch (std::exception& e) {
1786 vnThreadsRunning[4]--;
1787 PrintException(&e, "ThreadRPCServer()");
1789 vnThreadsRunning[4]--;
1790 PrintException(NULL, "ThreadRPCServer()");
1792 printf("ThreadRPCServer exiting\n");
1795 void ThreadRPCServer2(void* parg)
1797 printf("ThreadRPCServer started\n");
1799 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1801 string strWhatAmI = "To use bitcoind";
1802 if (mapArgs.count("-server"))
1803 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1804 else if (mapArgs.count("-daemon"))
1805 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1807 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1808 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1810 GetConfigFile().c_str());
1811 CreateThread(Shutdown, NULL);
1815 bool fUseSSL = GetBoolArg("-rpcssl");
1816 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1818 asio::io_service io_service;
1819 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1820 ip::tcp::acceptor acceptor(io_service, endpoint);
1822 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1825 ssl::context context(io_service, ssl::context::sslv23);
1828 context.set_options(ssl::context::no_sslv2);
1829 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1830 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1831 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1832 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1833 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1834 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1835 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1836 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1838 string ciphers = GetArg("-rpcsslciphers",
1839 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1840 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1844 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1849 // Accept connection
1851 SSLStream sslStream(io_service, context);
1852 SSLIOStreamDevice d(sslStream, fUseSSL);
1853 iostreams::stream<SSLIOStreamDevice> stream(d);
1855 ip::tcp::iostream stream;
1858 ip::tcp::endpoint peer;
1859 vnThreadsRunning[4]--;
1861 acceptor.accept(sslStream.lowest_layer(), peer);
1863 acceptor.accept(*stream.rdbuf(), peer);
1865 vnThreadsRunning[4]++;
1869 // Restrict callers by IP
1870 if (!ClientAllowed(peer.address().to_string()))
1873 map<string, string> mapHeaders;
1876 boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
1877 if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
1880 printf("ThreadRPCServer ReadHTTP timeout\n");
1884 // Check authorization
1885 if (mapHeaders.count("authorization") == 0)
1887 stream << HTTPReply(401, "") << std::flush;
1890 if (!HTTPAuthorized(mapHeaders))
1892 // Deter brute-forcing short passwords
1893 if (mapArgs["-rpcpassword"].size() < 15)
1896 stream << HTTPReply(401, "") << std::flush;
1897 printf("ThreadRPCServer incorrect password attempt\n");
1901 Value id = Value::null;
1906 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1907 throw JSONRPCError(-32700, "Parse error");
1908 const Object& request = valRequest.get_obj();
1910 // Parse id now so errors from here on will have the id
1911 id = find_value(request, "id");
1914 Value valMethod = find_value(request, "method");
1915 if (valMethod.type() == null_type)
1916 throw JSONRPCError(-32600, "Missing method");
1917 if (valMethod.type() != str_type)
1918 throw JSONRPCError(-32600, "Method must be a string");
1919 string strMethod = valMethod.get_str();
1920 if (strMethod != "getwork")
1921 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1924 Value valParams = find_value(request, "params");
1926 if (valParams.type() == array_type)
1927 params = valParams.get_array();
1928 else if (valParams.type() == null_type)
1931 throw JSONRPCError(-32600, "Params must be an array");
1934 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1935 if (mi == mapCallTable.end())
1936 throw JSONRPCError(-32601, "Method not found");
1938 // Observe safe mode
1939 string strWarning = GetWarnings("rpc");
1940 if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1941 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1946 Value result = (*(*mi).second)(params, false);
1949 string strReply = JSONRPCReply(result, Value::null, id);
1950 stream << HTTPReply(200, strReply) << std::flush;
1952 catch (std::exception& e)
1954 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
1957 catch (Object& objError)
1959 ErrorReply(stream, objError, id);
1961 catch (std::exception& e)
1963 ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
1971 Object CallRPC(const string& strMethod, const Array& params)
1973 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1974 throw runtime_error(strprintf(
1975 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1976 "If the file does not exist, create it with owner-readable-only file permissions."),
1977 GetConfigFile().c_str()));
1979 // Connect to localhost
1980 bool fUseSSL = GetBoolArg("-rpcssl");
1982 asio::io_service io_service;
1983 ssl::context context(io_service, ssl::context::sslv23);
1984 context.set_options(ssl::context::no_sslv2);
1985 SSLStream sslStream(io_service, context);
1986 SSLIOStreamDevice d(sslStream, fUseSSL);
1987 iostreams::stream<SSLIOStreamDevice> stream(d);
1988 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1989 throw runtime_error("couldn't connect to server");
1992 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1994 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1996 throw runtime_error("couldn't connect to server");
2000 // HTTP basic authentication
2001 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
2002 map<string, string> mapRequestHeaders;
2003 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
2006 string strRequest = JSONRPCRequest(strMethod, params, 1);
2007 string strPost = HTTPPost(strRequest, mapRequestHeaders);
2008 stream << strPost << std::flush;
2011 map<string, string> mapHeaders;
2013 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
2015 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
2016 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
2017 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
2018 else if (strReply.empty())
2019 throw runtime_error("no response from server");
2023 if (!read_string(strReply, valReply))
2024 throw runtime_error("couldn't parse reply from server");
2025 const Object& reply = valReply.get_obj();
2027 throw runtime_error("expected reply to have result, error and id properties");
2035 template<typename T>
2036 void ConvertTo(Value& value)
2038 if (value.type() == str_type)
2040 // reinterpret string as unquoted json value
2042 if (!read_string(value.get_str(), value2))
2043 throw runtime_error("type mismatch");
2044 value = value2.get_value<T>();
2048 value = value.get_value<T>();
2052 int CommandLineRPC(int argc, char *argv[])
2059 while (argc > 1 && IsSwitchChar(argv[1][0]))
2067 throw runtime_error("too few parameters");
2068 string strMethod = argv[1];
2070 // Parameters default to strings
2072 for (int i = 2; i < argc; i++)
2073 params.push_back(argv[i]);
2074 int n = params.size();
2077 // Special case non-string parameter types
2079 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
2080 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2081 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
2082 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
2083 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2084 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2085 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2086 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2087 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2088 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
2089 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2090 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
2091 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2092 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
2093 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2094 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
2095 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2096 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
2097 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2098 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
2099 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2100 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2101 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2102 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2103 if (strMethod == "sendmany" && n > 1)
2105 string s = params[1].get_str();
2107 if (!read_string(s, v) || v.type() != obj_type)
2108 throw runtime_error("type mismatch");
2109 params[1] = v.get_obj();
2111 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2114 Object reply = CallRPC(strMethod, params);
2117 const Value& result = find_value(reply, "result");
2118 const Value& error = find_value(reply, "error");
2119 const Value& id = find_value(reply, "id");
2121 if (error.type() != null_type)
2124 strPrint = "error: " + write_string(error, false);
2125 int code = find_value(error.get_obj(), "code").get_int();
2131 if (result.type() == null_type)
2133 else if (result.type() == str_type)
2134 strPrint = result.get_str();
2136 strPrint = write_string(result, true);
2139 catch (std::exception& e)
2141 strPrint = string("error: ") + e.what();
2146 PrintException(NULL, "CommandLineRPC()");
2151 #if defined(__WXMSW__) && defined(GUI)
2152 // Windows GUI apps can't print to command line,
2153 // so settle for a message box yuck
2154 MyMessageBox(strPrint, "Bitcoin", wxOK);
2156 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
2166 int main(int argc, char *argv[])
2169 // Turn off microsoft heap dump noise
2170 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2171 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
2173 setbuf(stdin, NULL);
2174 setbuf(stdout, NULL);
2175 setbuf(stderr, NULL);
2179 if (argc >= 2 && string(argv[1]) == "-server")
2181 printf("server ready\n");
2182 ThreadRPCServer(NULL);
2186 return CommandLineRPC(argc, argv);
2189 catch (std::exception& e) {
2190 PrintException(&e, "main()");
2192 PrintException(NULL, "main()");