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"
11 #include <boost/asio.hpp>
12 #include <boost/iostreams/concepts.hpp>
13 #include <boost/iostreams/stream.hpp>
15 #include <boost/asio/ssl.hpp>
16 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
18 #include "json/json_spirit_reader_template.h"
19 #include "json/json_spirit_writer_template.h"
20 #include "json/json_spirit_utils.h"
21 #define printf OutputDebugStringF
22 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
23 // precompiled in headers.h. The problem might be when the pch file goes over
24 // a certain size around 145MB. If we need access to json_spirit outside this
25 // file, we could use the compiled json_spirit option.
28 using namespace boost;
29 using namespace boost::asio;
30 using namespace json_spirit;
32 void ThreadRPCServer2(void* parg);
33 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
34 extern map<string, rpcfn_type> mapCallTable;
37 Object JSONRPCError(int code, const string& message)
40 error.push_back(Pair("code", code));
41 error.push_back(Pair("message", message));
46 void PrintConsole(const char* format, ...)
49 int limit = sizeof(buffer);
51 va_start(arg_ptr, format);
52 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
54 if (ret < 0 || ret >= limit)
60 #if defined(__WXMSW__) && defined(GUI)
61 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
63 fprintf(stdout, "%s", buffer);
68 int64 AmountFromValue(const Value& value)
70 double dAmount = value.get_real();
71 if (dAmount <= 0.0 || dAmount > 21000000.0)
72 throw JSONRPCError(-3, "Invalid amount");
73 int64 nAmount = roundint64(dAmount * COIN);
74 if (!MoneyRange(nAmount))
75 throw JSONRPCError(-3, "Invalid amount");
79 Value ValueFromAmount(int64 amount)
81 return (double)amount / (double)COIN;
84 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
86 entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
87 entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
88 entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
89 BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
90 entry.push_back(Pair(item.first, item.second));
93 string AccountFromValue(const Value& value)
95 string strAccount = value.get_str();
96 if (strAccount == "*")
97 throw JSONRPCError(-11, "Invalid account name");
104 /// Note: This interface may still be subject to change.
108 Value help(const Array& params, bool fHelp)
110 if (fHelp || params.size() > 1)
113 "List commands, or get help for a command.");
116 if (params.size() > 0)
117 strCommand = params[0].get_str();
120 set<rpcfn_type> setDone;
121 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
123 string strMethod = (*mi).first;
124 // We already filter duplicates, but these deprecated screw up the sort order
125 if (strMethod == "getamountreceived" ||
126 strMethod == "getallreceived" ||
127 (strMethod.find("label") != string::npos))
129 if (strCommand != "" && strMethod != strCommand)
134 rpcfn_type pfn = (*mi).second;
135 if (setDone.insert(pfn).second)
136 (*pfn)(params, true);
138 catch (std::exception& e)
140 // Help text is returned in an exception
141 string strHelp = string(e.what());
142 if (strCommand == "")
143 if (strHelp.find('\n') != -1)
144 strHelp = strHelp.substr(0, strHelp.find('\n'));
145 strRet += strHelp + "\n";
149 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
150 strRet = strRet.substr(0,strRet.size()-1);
155 Value stop(const Array& params, bool fHelp)
157 if (fHelp || params.size() != 0)
160 "Stop bitcoin server.");
162 // Shutdown will take long enough that the response should get back
163 CreateThread(Shutdown, NULL);
164 return "bitcoin server stopping";
168 Value getblockcount(const Array& params, bool fHelp)
170 if (fHelp || params.size() != 0)
173 "Returns the number of blocks in the longest block chain.");
179 Value getblocknumber(const Array& params, bool fHelp)
181 if (fHelp || params.size() != 0)
184 "Returns the block number of the latest block in the longest block chain.");
190 Value getconnectioncount(const Array& params, bool fHelp)
192 if (fHelp || params.size() != 0)
194 "getconnectioncount\n"
195 "Returns the number of connections to other nodes.");
197 return (int)vNodes.size();
201 double GetDifficulty()
203 // Floating point number that is a multiple of the minimum difficulty,
204 // minimum difficulty = 1.0.
205 if (pindexBest == NULL)
207 int nShift = 256 - 32 - 31; // to fit in a uint
208 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
209 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
210 return dMinimum / dCurrently;
213 Value getdifficulty(const Array& params, bool fHelp)
215 if (fHelp || params.size() != 0)
218 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
220 return GetDifficulty();
224 Value getgenerate(const Array& params, bool fHelp)
226 if (fHelp || params.size() != 0)
229 "Returns true or false.");
231 return (bool)fGenerateBitcoins;
235 Value setgenerate(const Array& params, bool fHelp)
237 if (fHelp || params.size() < 1 || params.size() > 2)
239 "setgenerate <generate> [genproclimit]\n"
240 "<generate> is true or false to turn generation on or off.\n"
241 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
243 bool fGenerate = true;
244 if (params.size() > 0)
245 fGenerate = params[0].get_bool();
247 if (params.size() > 1)
249 int nGenProcLimit = params[1].get_int();
250 fLimitProcessors = (nGenProcLimit != -1);
251 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
252 if (nGenProcLimit != -1)
253 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
254 if (nGenProcLimit == 0)
258 GenerateBitcoins(fGenerate);
263 Value gethashespersec(const Array& params, bool fHelp)
265 if (fHelp || params.size() != 0)
268 "Returns a recent hashes per second performance measurement while generating.");
270 if (GetTimeMillis() - nHPSTimerStart > 8000)
271 return (boost::int64_t)0;
272 return (boost::int64_t)dHashesPerSec;
276 Value getinfo(const Array& params, bool fHelp)
278 if (fHelp || params.size() != 0)
281 "Returns an object containing various state info.");
284 obj.push_back(Pair("version", (int)VERSION));
285 obj.push_back(Pair("balance", ValueFromAmount(GetBalance())));
286 obj.push_back(Pair("blocks", (int)nBestHeight));
287 obj.push_back(Pair("connections", (int)vNodes.size()));
288 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
289 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
290 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
291 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
292 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
293 obj.push_back(Pair("testnet", fTestNet));
294 obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
295 obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
296 obj.push_back(Pair("errors", GetWarnings("statusbar")));
301 Value getnewaddress(const Array& params, bool fHelp)
303 if (fHelp || params.size() > 1)
305 "getnewaddress [account]\n"
306 "Returns a new bitcoin address for receiving payments. "
307 "If [account] is specified (recommended), it is added to the address book "
308 "so payments received with the address will be credited to [account].");
310 // Parse the account first so we don't generate a key if there's an error
312 if (params.size() > 0)
313 strAccount = AccountFromValue(params[0]);
315 // Generate a new key that is added to wallet
316 string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
318 SetAddressBookName(strAddress, strAccount);
323 // requires cs_main, cs_mapWallet locks
324 string GetAccountAddress(string strAccount, bool bForceNew=false)
332 walletdb.ReadAccount(strAccount, account);
334 // Check if the current key has been used
335 if (!account.vchPubKey.empty())
337 CScript scriptPubKey;
338 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
339 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
340 it != mapWallet.end() && !account.vchPubKey.empty();
343 const CWalletTx& wtx = (*it).second;
344 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
345 if (txout.scriptPubKey == scriptPubKey)
346 account.vchPubKey.clear();
350 // Generate a new key
351 if (account.vchPubKey.empty() || bForceNew)
353 account.vchPubKey = GetKeyFromKeyPool();
354 string strAddress = PubKeyToAddress(account.vchPubKey);
355 SetAddressBookName(strAddress, strAccount);
356 walletdb.WriteAccount(strAccount, account);
359 walletdb.TxnCommit();
360 strAddress = PubKeyToAddress(account.vchPubKey);
365 Value getaccountaddress(const Array& params, bool fHelp)
367 if (fHelp || params.size() != 1)
369 "getaccountaddress <account>\n"
370 "Returns the current bitcoin address for receiving payments to this account.");
372 // Parse the account first so we don't generate a key if there's an error
373 string strAccount = AccountFromValue(params[0]);
377 CRITICAL_BLOCK(cs_main)
378 CRITICAL_BLOCK(cs_mapWallet)
380 ret = GetAccountAddress(strAccount);
388 Value setaccount(const Array& params, bool fHelp)
390 if (fHelp || params.size() < 1 || params.size() > 2)
392 "setaccount <bitcoinaddress> <account>\n"
393 "Sets the account associated with the given address.");
395 string strAddress = params[0].get_str();
397 bool isValid = AddressToHash160(strAddress, hash160);
399 throw JSONRPCError(-5, "Invalid bitcoin address");
403 if (params.size() > 1)
404 strAccount = AccountFromValue(params[1]);
406 // Detect when changing the account of an address that is the 'unused current key' of another account:
407 CRITICAL_BLOCK(cs_main)
408 CRITICAL_BLOCK(cs_mapWallet)
409 CRITICAL_BLOCK(cs_mapAddressBook)
411 if (mapAddressBook.count(strAddress))
413 string strOldAccount = mapAddressBook[strAddress];
414 if (strAddress == GetAccountAddress(strOldAccount))
415 GetAccountAddress(strOldAccount, true);
419 SetAddressBookName(strAddress, strAccount);
424 Value getaccount(const Array& params, bool fHelp)
426 if (fHelp || params.size() != 1)
428 "getaccount <bitcoinaddress>\n"
429 "Returns the account associated with the given address.");
431 string strAddress = params[0].get_str();
434 CRITICAL_BLOCK(cs_mapAddressBook)
436 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
437 if (mi != mapAddressBook.end() && !(*mi).second.empty())
438 strAccount = (*mi).second;
444 Value getaddressesbyaccount(const Array& params, bool fHelp)
446 if (fHelp || params.size() != 1)
448 "getaddressesbyaccount <account>\n"
449 "Returns the list of addresses for the given account.");
451 string strAccount = AccountFromValue(params[0]);
453 // Find all addresses that have the given account
455 CRITICAL_BLOCK(cs_mapAddressBook)
457 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
459 const string& strAddress = item.first;
460 const string& strName = item.second;
461 if (strName == strAccount)
463 // We're only adding valid bitcoin addresses and not ip addresses
464 CScript scriptPubKey;
465 if (scriptPubKey.SetBitcoinAddress(strAddress))
466 ret.push_back(strAddress);
473 Value settxfee(const Array& params, bool fHelp)
475 if (fHelp || params.size() < 1 || params.size() > 1)
477 "settxfee <amount>\n"
478 "<amount> is a real and is rounded to the nearest 0.00000001");
482 if (params[0].get_real() != 0.0)
483 nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
485 nTransactionFee = nAmount;
489 Value sendtoaddress(const Array& params, bool fHelp)
491 if (fHelp || params.size() < 2 || params.size() > 4)
493 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
494 "<amount> is a real and is rounded to the nearest 0.00000001");
496 string strAddress = params[0].get_str();
499 int64 nAmount = AmountFromValue(params[1]);
503 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
504 wtx.mapValue["comment"] = params[2].get_str();
505 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
506 wtx.mapValue["to"] = params[3].get_str();
508 CRITICAL_BLOCK(cs_main)
510 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
512 throw JSONRPCError(-4, strError);
515 return wtx.GetHash().GetHex();
519 Value getreceivedbyaddress(const Array& params, bool fHelp)
521 if (fHelp || params.size() < 1 || params.size() > 2)
523 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
524 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
527 string strAddress = params[0].get_str();
528 CScript scriptPubKey;
529 if (!scriptPubKey.SetBitcoinAddress(strAddress))
530 throw JSONRPCError(-5, "Invalid bitcoin address");
531 if (!IsMine(scriptPubKey))
534 // Minimum confirmations
536 if (params.size() > 1)
537 nMinDepth = params[1].get_int();
541 CRITICAL_BLOCK(cs_mapWallet)
543 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
545 const CWalletTx& wtx = (*it).second;
546 if (wtx.IsCoinBase() || !wtx.IsFinal())
549 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
550 if (txout.scriptPubKey == scriptPubKey)
551 if (wtx.GetDepthInMainChain() >= nMinDepth)
552 nAmount += txout.nValue;
556 return ValueFromAmount(nAmount);
560 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
562 CRITICAL_BLOCK(cs_mapAddressBook)
564 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
566 const string& strAddress = item.first;
567 const string& strName = item.second;
568 if (strName == strAccount)
570 // We're only counting our own valid bitcoin addresses and not ip addresses
571 CScript scriptPubKey;
572 if (scriptPubKey.SetBitcoinAddress(strAddress))
573 if (IsMine(scriptPubKey))
574 setPubKey.insert(scriptPubKey);
581 Value getreceivedbyaccount(const Array& params, bool fHelp)
583 if (fHelp || params.size() < 1 || params.size() > 2)
585 "getreceivedbyaccount <account> [minconf=1]\n"
586 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
588 // Minimum confirmations
590 if (params.size() > 1)
591 nMinDepth = params[1].get_int();
593 // Get the set of pub keys that have the label
594 string strAccount = AccountFromValue(params[0]);
595 set<CScript> setPubKey;
596 GetAccountPubKeys(strAccount, setPubKey);
600 CRITICAL_BLOCK(cs_mapWallet)
602 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
604 const CWalletTx& wtx = (*it).second;
605 if (wtx.IsCoinBase() || !wtx.IsFinal())
608 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
609 if (setPubKey.count(txout.scriptPubKey))
610 if (wtx.GetDepthInMainChain() >= nMinDepth)
611 nAmount += txout.nValue;
615 return (double)nAmount / (double)COIN;
619 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
622 CRITICAL_BLOCK(cs_mapWallet)
624 // Tally wallet transactions
625 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
627 const CWalletTx& wtx = (*it).second;
631 int64 nGenerated, nReceived, nSent, nFee;
632 wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
634 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
635 nBalance += nReceived;
636 nBalance += nGenerated - nSent - nFee;
639 // Tally internal accounting entries
640 nBalance += walletdb.GetAccountCreditDebit(strAccount);
646 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
649 return GetAccountBalance(walletdb, strAccount, nMinDepth);
653 Value getbalance(const Array& params, bool fHelp)
655 if (fHelp || params.size() < 0 || params.size() > 2)
657 "getbalance [account] [minconf=1]\n"
658 "If [account] is not specified, returns the server's total available balance.\n"
659 "If [account] is specified, returns the balance in the account.");
661 if (params.size() == 0)
662 return ValueFromAmount(GetBalance());
665 if (params.size() > 1)
666 nMinDepth = params[1].get_int();
668 if (params[0].get_str() == "*") {
669 // Calculate total balance a different way from GetBalance()
670 // (GetBalance() sums up all unspent TxOuts)
671 // getbalance and getbalance '*' should always return the same number.
673 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
675 const CWalletTx& wtx = (*it).second;
679 int64 allGeneratedImmature, allGeneratedMature, allFee;
680 allGeneratedImmature = allGeneratedMature = allFee = 0;
681 string strSentAccount;
682 list<pair<string, int64> > listReceived;
683 list<pair<string, int64> > listSent;
684 wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
685 if (wtx.GetDepthInMainChain() >= nMinDepth)
686 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
687 nBalance += r.second;
688 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
689 nBalance -= r.second;
691 nBalance += allGeneratedMature;
693 return ValueFromAmount(nBalance);
696 string strAccount = AccountFromValue(params[0]);
698 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
700 return ValueFromAmount(nBalance);
704 Value movecmd(const Array& params, bool fHelp)
706 if (fHelp || params.size() < 3 || params.size() > 5)
708 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
709 "Move from one account in your wallet to another.");
711 string strFrom = AccountFromValue(params[0]);
712 string strTo = AccountFromValue(params[1]);
713 int64 nAmount = AmountFromValue(params[2]);
715 if (params.size() > 3)
716 nMinDepth = params[3].get_int();
718 if (params.size() > 4)
719 strComment = params[4].get_str();
721 CRITICAL_BLOCK(cs_mapWallet)
726 int64 nNow = GetAdjustedTime();
729 CAccountingEntry debit;
730 debit.strAccount = strFrom;
731 debit.nCreditDebit = -nAmount;
733 debit.strOtherAccount = strTo;
734 debit.strComment = strComment;
735 walletdb.WriteAccountingEntry(debit);
738 CAccountingEntry credit;
739 credit.strAccount = strTo;
740 credit.nCreditDebit = nAmount;
742 credit.strOtherAccount = strFrom;
743 credit.strComment = strComment;
744 walletdb.WriteAccountingEntry(credit);
746 walletdb.TxnCommit();
752 Value sendfrom(const Array& params, bool fHelp)
754 if (fHelp || params.size() < 3 || params.size() > 6)
756 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
757 "<amount> is a real and is rounded to the nearest 0.00000001");
759 string strAccount = AccountFromValue(params[0]);
760 string strAddress = params[1].get_str();
761 int64 nAmount = AmountFromValue(params[2]);
763 if (params.size() > 3)
764 nMinDepth = params[3].get_int();
767 wtx.strFromAccount = strAccount;
768 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
769 wtx.mapValue["comment"] = params[4].get_str();
770 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
771 wtx.mapValue["to"] = params[5].get_str();
773 CRITICAL_BLOCK(cs_main)
774 CRITICAL_BLOCK(cs_mapWallet)
777 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
778 if (nAmount > nBalance)
779 throw JSONRPCError(-6, "Account has insufficient funds");
782 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
784 throw JSONRPCError(-4, strError);
787 return wtx.GetHash().GetHex();
790 Value sendmany(const Array& params, bool fHelp)
792 if (fHelp || params.size() < 2 || params.size() > 4)
794 "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
795 "amounts are double-precision floating point numbers");
797 string strAccount = AccountFromValue(params[0]);
798 Object sendTo = params[1].get_obj();
800 if (params.size() > 2)
801 nMinDepth = params[2].get_int();
804 wtx.strFromAccount = strAccount;
805 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
806 wtx.mapValue["comment"] = params[3].get_str();
808 set<string> setAddress;
809 vector<pair<CScript, int64> > vecSend;
811 int64 totalAmount = 0;
812 BOOST_FOREACH(const Pair& s, sendTo)
815 string strAddress = s.name_;
817 if (setAddress.count(strAddress))
818 throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
819 setAddress.insert(strAddress);
821 CScript scriptPubKey;
822 if (!scriptPubKey.SetBitcoinAddress(strAddress))
823 throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
824 int64 nAmount = AmountFromValue(s.value_);
825 totalAmount += nAmount;
827 vecSend.push_back(make_pair(scriptPubKey, nAmount));
830 CRITICAL_BLOCK(cs_main)
831 CRITICAL_BLOCK(cs_mapWallet)
834 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
835 if (totalAmount > nBalance)
836 throw JSONRPCError(-6, "Account has insufficient funds");
839 CReserveKey keyChange;
840 int64 nFeeRequired = 0;
841 bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
844 if (totalAmount + nFeeRequired > GetBalance())
845 throw JSONRPCError(-6, "Insufficient funds");
846 throw JSONRPCError(-4, "Transaction creation failed");
848 if (!CommitTransaction(wtx, keyChange))
849 throw JSONRPCError(-4, "Transaction commit failed");
852 return wtx.GetHash().GetHex();
867 Value ListReceived(const Array& params, bool fByAccounts)
869 // Minimum confirmations
871 if (params.size() > 0)
872 nMinDepth = params[0].get_int();
874 // Whether to include empty accounts
875 bool fIncludeEmpty = false;
876 if (params.size() > 1)
877 fIncludeEmpty = params[1].get_bool();
880 map<uint160, tallyitem> mapTally;
881 CRITICAL_BLOCK(cs_mapWallet)
883 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
885 const CWalletTx& wtx = (*it).second;
886 if (wtx.IsCoinBase() || !wtx.IsFinal())
889 int nDepth = wtx.GetDepthInMainChain();
890 if (nDepth < nMinDepth)
893 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
895 // Only counting our own bitcoin addresses and not ip addresses
896 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
897 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
900 tallyitem& item = mapTally[hash160];
901 item.nAmount += txout.nValue;
902 item.nConf = min(item.nConf, nDepth);
909 map<string, tallyitem> mapAccountTally;
910 CRITICAL_BLOCK(cs_mapAddressBook)
912 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
914 const string& strAddress = item.first;
915 const string& strAccount = item.second;
917 if (!AddressToHash160(strAddress, hash160))
919 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
920 if (it == mapTally.end() && !fIncludeEmpty)
925 if (it != mapTally.end())
927 nAmount = (*it).second.nAmount;
928 nConf = (*it).second.nConf;
933 tallyitem& item = mapAccountTally[strAccount];
934 item.nAmount += nAmount;
935 item.nConf = min(item.nConf, nConf);
940 obj.push_back(Pair("address", strAddress));
941 obj.push_back(Pair("account", strAccount));
942 obj.push_back(Pair("label", strAccount)); // deprecated
943 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
944 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
952 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
954 int64 nAmount = (*it).second.nAmount;
955 int nConf = (*it).second.nConf;
957 obj.push_back(Pair("account", (*it).first));
958 obj.push_back(Pair("label", (*it).first)); // deprecated
959 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
960 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
968 Value listreceivedbyaddress(const Array& params, bool fHelp)
970 if (fHelp || params.size() > 2)
972 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
973 "[minconf] is the minimum number of confirmations before payments are included.\n"
974 "[includeempty] whether to include addresses that haven't received any payments.\n"
975 "Returns an array of objects containing:\n"
976 " \"address\" : receiving address\n"
977 " \"account\" : the account of the receiving address\n"
978 " \"amount\" : total amount received by the address\n"
979 " \"confirmations\" : number of confirmations of the most recent transaction included");
981 return ListReceived(params, false);
984 Value listreceivedbyaccount(const Array& params, bool fHelp)
986 if (fHelp || params.size() > 2)
988 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
989 "[minconf] is the minimum number of confirmations before payments are included.\n"
990 "[includeempty] whether to include accounts that haven't received any payments.\n"
991 "Returns an array of objects containing:\n"
992 " \"account\" : the account of the receiving addresses\n"
993 " \"amount\" : total amount received by addresses with this account\n"
994 " \"confirmations\" : number of confirmations of the most recent transaction included");
996 return ListReceived(params, true);
999 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
1001 int64 nGeneratedImmature, nGeneratedMature, nFee;
1002 string strSentAccount;
1003 list<pair<string, int64> > listReceived;
1004 list<pair<string, int64> > listSent;
1005 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1007 bool fAllAccounts = (strAccount == string("*"));
1009 // Generated blocks assigned to account ""
1010 if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
1013 entry.push_back(Pair("account", string("")));
1014 if (nGeneratedImmature)
1016 entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
1017 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
1021 entry.push_back(Pair("category", "generate"));
1022 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
1025 WalletTxToJSON(wtx, entry);
1026 ret.push_back(entry);
1030 if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
1032 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1035 entry.push_back(Pair("account", strSentAccount));
1036 entry.push_back(Pair("address", s.first));
1037 entry.push_back(Pair("category", "send"));
1038 entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
1039 entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
1041 WalletTxToJSON(wtx, entry);
1042 ret.push_back(entry);
1047 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1048 CRITICAL_BLOCK(cs_mapAddressBook)
1050 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1053 if (mapAddressBook.count(r.first))
1054 account = mapAddressBook[r.first];
1055 if (fAllAccounts || (account == strAccount))
1058 entry.push_back(Pair("account", account));
1059 entry.push_back(Pair("address", r.first));
1060 entry.push_back(Pair("category", "receive"));
1061 entry.push_back(Pair("amount", ValueFromAmount(r.second)));
1063 WalletTxToJSON(wtx, entry);
1064 ret.push_back(entry);
1071 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
1073 bool fAllAccounts = (strAccount == string("*"));
1075 if (fAllAccounts || acentry.strAccount == strAccount)
1078 entry.push_back(Pair("account", acentry.strAccount));
1079 entry.push_back(Pair("category", "move"));
1080 entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
1081 entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
1082 entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
1083 entry.push_back(Pair("comment", acentry.strComment));
1084 ret.push_back(entry);
1088 Value listtransactions(const Array& params, bool fHelp)
1090 if (fHelp || params.size() > 3)
1091 throw runtime_error(
1092 "listtransactions [account] [count=10] [from=0]\n"
1093 "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
1095 string strAccount = "*";
1096 if (params.size() > 0)
1097 strAccount = params[0].get_str();
1099 if (params.size() > 1)
1100 nCount = params[1].get_int();
1102 if (params.size() > 2)
1103 nFrom = params[2].get_int();
1108 CRITICAL_BLOCK(cs_mapWallet)
1110 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
1111 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
1112 typedef multimap<int64, TxPair > TxItems;
1115 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1117 CWalletTx* wtx = &((*it).second);
1118 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
1120 list<CAccountingEntry> acentries;
1121 walletdb.ListAccountCreditDebit(strAccount, acentries);
1122 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1124 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
1127 // Now: iterate backwards until we have nCount items to return:
1128 TxItems::reverse_iterator it = txByTime.rbegin();
1129 for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
1131 CWalletTx *const pwtx = (*it).second.first;
1133 ListTransactions(*pwtx, strAccount, 0, true, ret);
1134 CAccountingEntry *const pacentry = (*it).second.second;
1136 AcentryToJSON(*pacentry, strAccount, ret);
1138 if (ret.size() >= nCount) break;
1140 // ret is now newest to oldest
1143 // Make sure we return only last nCount items (sends-to-self might give us an extra):
1144 if (ret.size() > nCount)
1146 Array::iterator last = ret.begin();
1147 std::advance(last, nCount);
1148 ret.erase(last, ret.end());
1150 std::reverse(ret.begin(), ret.end()); // oldest to newest
1155 Value listaccounts(const Array& params, bool fHelp)
1157 if (fHelp || params.size() > 1)
1158 throw runtime_error(
1159 "listaccounts [minconf=1]\n"
1160 "Returns Object that has account names as keys, account balances as values.");
1163 if (params.size() > 0)
1164 nMinDepth = params[0].get_int();
1166 map<string, int64> mapAccountBalances;
1167 CRITICAL_BLOCK(cs_mapWallet)
1168 CRITICAL_BLOCK(cs_mapAddressBook)
1170 BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
1172 if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
1173 mapAccountBalances[entry.second] = 0;
1176 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1178 const CWalletTx& wtx = (*it).second;
1179 int64 nGeneratedImmature, nGeneratedMature, nFee;
1180 string strSentAccount;
1181 list<pair<string, int64> > listReceived;
1182 list<pair<string, int64> > listSent;
1183 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1184 mapAccountBalances[strSentAccount] -= nFee;
1185 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1186 mapAccountBalances[strSentAccount] -= s.second;
1187 if (wtx.GetDepthInMainChain() >= nMinDepth)
1189 mapAccountBalances[""] += nGeneratedMature;
1190 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1191 if (mapAddressBook.count(r.first))
1192 mapAccountBalances[mapAddressBook[r.first]] += r.second;
1194 mapAccountBalances[""] += r.second;
1199 list<CAccountingEntry> acentries;
1200 CWalletDB().ListAccountCreditDebit("*", acentries);
1201 BOOST_FOREACH(const CAccountingEntry& entry, acentries)
1202 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1205 BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1206 ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1211 Value gettransaction(const Array& params, bool fHelp)
1213 if (fHelp || params.size() != 1)
1214 throw runtime_error(
1215 "gettransaction <txid>\n"
1216 "Get detailed information about <txid>");
1219 hash.SetHex(params[0].get_str());
1222 CRITICAL_BLOCK(cs_mapWallet)
1224 if (!mapWallet.count(hash))
1225 throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
1226 const CWalletTx& wtx = mapWallet[hash];
1228 int64 nCredit = wtx.GetCredit();
1229 int64 nDebit = wtx.GetDebit();
1230 int64 nNet = nCredit - nDebit;
1231 int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1233 entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1235 entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1237 WalletTxToJSON(mapWallet[hash], entry);
1240 ListTransactions(mapWallet[hash], "*", 0, false, details);
1241 entry.push_back(Pair("details", details));
1248 Value backupwallet(const Array& params, bool fHelp)
1250 if (fHelp || params.size() != 1)
1251 throw runtime_error(
1252 "backupwallet <destination>\n"
1253 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1255 string strDest = params[0].get_str();
1256 BackupWallet(strDest);
1262 Value validateaddress(const Array& params, bool fHelp)
1264 if (fHelp || params.size() != 1)
1265 throw runtime_error(
1266 "validateaddress <bitcoinaddress>\n"
1267 "Return information about <bitcoinaddress>.");
1269 string strAddress = params[0].get_str();
1271 bool isValid = AddressToHash160(strAddress, hash160);
1274 ret.push_back(Pair("isvalid", isValid));
1277 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1278 // version of the address:
1279 string currentAddress = Hash160ToAddress(hash160);
1280 ret.push_back(Pair("address", currentAddress));
1281 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1282 CRITICAL_BLOCK(cs_mapAddressBook)
1284 if (mapAddressBook.count(currentAddress))
1285 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
1292 Value getwork(const Array& params, bool fHelp)
1294 if (fHelp || params.size() > 1)
1295 throw runtime_error(
1297 "If [data] is not specified, returns formatted hash data to work on:\n"
1298 " \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1299 " \"data\" : block data\n"
1300 " \"hash1\" : formatted hash buffer for second hash\n"
1301 " \"target\" : little endian hash target\n"
1302 "If [data] is specified, tries to solve the block and returns true if it was successful.");
1305 throw JSONRPCError(-9, "Bitcoin is not connected!");
1307 if (IsInitialBlockDownload())
1308 throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1310 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1311 static vector<CBlock*> vNewBlock;
1312 static CReserveKey reservekey;
1314 if (params.size() == 0)
1317 static unsigned int nTransactionsUpdatedLast;
1318 static CBlockIndex* pindexPrev;
1319 static int64 nStart;
1320 static CBlock* pblock;
1321 if (pindexPrev != pindexBest ||
1322 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1324 if (pindexPrev != pindexBest)
1326 // Deallocate old blocks since they're obsolete now
1327 mapNewBlock.clear();
1328 BOOST_FOREACH(CBlock* pblock, vNewBlock)
1332 nTransactionsUpdatedLast = nTransactionsUpdated;
1333 pindexPrev = pindexBest;
1337 pblock = CreateNewBlock(reservekey);
1339 throw JSONRPCError(-7, "Out of memory");
1340 vNewBlock.push_back(pblock);
1344 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1347 // Update nExtraNonce
1348 static unsigned int nExtraNonce = 0;
1349 static int64 nPrevTime = 0;
1350 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1353 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1355 // Prebuild hash buffers
1359 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1361 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1364 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1365 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
1366 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
1367 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
1373 vector<unsigned char> vchData = ParseHex(params[0].get_str());
1374 if (vchData.size() != 128)
1375 throw JSONRPCError(-8, "Invalid parameter");
1376 CBlock* pdata = (CBlock*)&vchData[0];
1379 for (int i = 0; i < 128/4; i++)
1380 ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1383 if (!mapNewBlock.count(pdata->hashMerkleRoot))
1385 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1386 unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1388 pblock->nTime = pdata->nTime;
1389 pblock->nNonce = pdata->nNonce;
1390 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1391 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1393 return CheckWork(pblock, reservekey);
1411 pair<string, rpcfn_type> pCallTable[] =
1413 make_pair("help", &help),
1414 make_pair("stop", &stop),
1415 make_pair("getblockcount", &getblockcount),
1416 make_pair("getblocknumber", &getblocknumber),
1417 make_pair("getconnectioncount", &getconnectioncount),
1418 make_pair("getdifficulty", &getdifficulty),
1419 make_pair("getgenerate", &getgenerate),
1420 make_pair("setgenerate", &setgenerate),
1421 make_pair("gethashespersec", &gethashespersec),
1422 make_pair("getinfo", &getinfo),
1423 make_pair("getnewaddress", &getnewaddress),
1424 make_pair("getaccountaddress", &getaccountaddress),
1425 make_pair("setaccount", &setaccount),
1426 make_pair("setlabel", &setaccount), // deprecated
1427 make_pair("getaccount", &getaccount),
1428 make_pair("getlabel", &getaccount), // deprecated
1429 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1430 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
1431 make_pair("sendtoaddress", &sendtoaddress),
1432 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1433 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1434 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
1435 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
1436 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
1437 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1438 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1439 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
1440 make_pair("backupwallet", &backupwallet),
1441 make_pair("validateaddress", &validateaddress),
1442 make_pair("getbalance", &getbalance),
1443 make_pair("move", &movecmd),
1444 make_pair("sendfrom", &sendfrom),
1445 make_pair("sendmany", &sendmany),
1446 make_pair("gettransaction", &gettransaction),
1447 make_pair("listtransactions", &listtransactions),
1448 make_pair("getwork", &getwork),
1449 make_pair("listaccounts", &listaccounts),
1450 make_pair("settxfee", &settxfee),
1452 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1454 string pAllowInSafeMode[] =
1460 "getconnectioncount",
1467 "getaccountaddress",
1470 "getlabel", // deprecated
1471 "getaddressesbyaccount",
1472 "getaddressesbylabel", // deprecated
1477 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1485 // This ain't Apache. We're just using HTTP header for the length field
1486 // and to be compatible with other JSON-RPC implementations.
1489 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1492 s << "POST / HTTP/1.1\r\n"
1493 << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
1494 << "Host: 127.0.0.1\r\n"
1495 << "Content-Type: application/json\r\n"
1496 << "Content-Length: " << strMsg.size() << "\r\n"
1497 << "Accept: application/json\r\n";
1498 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1499 s << item.first << ": " << item.second << "\r\n";
1500 s << "\r\n" << strMsg;
1505 string rfc1123Time()
1510 struct tm* now_gmt = gmtime(&now);
1511 string locale(setlocale(LC_TIME, NULL));
1512 setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
1513 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
1514 setlocale(LC_TIME, locale.c_str());
1515 return string(buffer);
1518 string HTTPReply(int nStatus, const string& strMsg)
1521 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1523 "Server: bitcoin-json-rpc/%s\r\n"
1524 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1525 "Content-Type: text/html\r\n"
1526 "Content-Length: 296\r\n"
1528 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1529 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1532 "<TITLE>Error</TITLE>\r\n"
1533 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1535 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1536 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
1538 if (nStatus == 200) strStatus = "OK";
1539 else if (nStatus == 400) strStatus = "Bad Request";
1540 else if (nStatus == 404) strStatus = "Not Found";
1541 else if (nStatus == 500) strStatus = "Internal Server Error";
1543 "HTTP/1.1 %d %s\r\n"
1545 "Connection: close\r\n"
1546 "Content-Length: %d\r\n"
1547 "Content-Type: application/json\r\n"
1548 "Server: bitcoin-json-rpc/%s\r\n"
1553 rfc1123Time().c_str(),
1555 FormatFullVersion().c_str(),
1559 int ReadHTTPStatus(std::basic_istream<char>& stream)
1562 getline(stream, str);
1563 vector<string> vWords;
1564 boost::split(vWords, str, boost::is_any_of(" "));
1565 if (vWords.size() < 2)
1567 return atoi(vWords[1].c_str());
1570 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1576 std::getline(stream, str);
1577 if (str.empty() || str == "\r")
1579 string::size_type nColon = str.find(":");
1580 if (nColon != string::npos)
1582 string strHeader = str.substr(0, nColon);
1583 boost::trim(strHeader);
1584 boost::to_lower(strHeader);
1585 string strValue = str.substr(nColon+1);
1586 boost::trim(strValue);
1587 mapHeadersRet[strHeader] = strValue;
1588 if (strHeader == "content-length")
1589 nLen = atoi(strValue.c_str());
1595 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1597 mapHeadersRet.clear();
1601 int nStatus = ReadHTTPStatus(stream);
1604 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1605 if (nLen < 0 || nLen > MAX_SIZE)
1611 vector<char> vch(nLen);
1612 stream.read(&vch[0], nLen);
1613 strMessageRet = string(vch.begin(), vch.end());
1619 string EncodeBase64(string s)
1624 b64 = BIO_new(BIO_f_base64());
1625 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1626 bmem = BIO_new(BIO_s_mem());
1627 b64 = BIO_push(b64, bmem);
1628 BIO_write(b64, s.c_str(), s.size());
1630 BIO_get_mem_ptr(b64, &bptr);
1632 string result(bptr->data, bptr->length);
1638 string DecodeBase64(string s)
1642 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1644 b64 = BIO_new(BIO_f_base64());
1645 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1646 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1647 bmem = BIO_push(b64, bmem);
1648 BIO_read(bmem, buffer, s.size());
1651 string result(buffer);
1656 bool HTTPAuthorized(map<string, string>& mapHeaders)
1658 string strAuth = mapHeaders["authorization"];
1659 if (strAuth.substr(0,6) != "Basic ")
1661 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1662 string strUserPass = DecodeBase64(strUserPass64);
1663 string::size_type nColon = strUserPass.find(":");
1664 if (nColon == string::npos)
1666 string strUser = strUserPass.substr(0, nColon);
1667 string strPassword = strUserPass.substr(nColon+1);
1668 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1672 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1673 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1674 // unspecified (HTTP errors and contents of 'error').
1676 // 1.0 spec: http://json-rpc.org/wiki/specification
1677 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1678 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1681 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1684 request.push_back(Pair("method", strMethod));
1685 request.push_back(Pair("params", params));
1686 request.push_back(Pair("id", id));
1687 return write_string(Value(request), false) + "\n";
1690 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1693 if (error.type() != null_type)
1694 reply.push_back(Pair("result", Value::null));
1696 reply.push_back(Pair("result", result));
1697 reply.push_back(Pair("error", error));
1698 reply.push_back(Pair("id", id));
1699 return write_string(Value(reply), false) + "\n";
1702 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1704 // Send error reply from json-rpc error object
1706 int code = find_value(objError, "code").get_int();
1707 if (code == -32600) nStatus = 400;
1708 else if (code == -32601) nStatus = 404;
1709 string strReply = JSONRPCReply(Value::null, objError, id);
1710 stream << HTTPReply(nStatus, strReply) << std::flush;
1713 bool ClientAllowed(const string& strAddress)
1715 if (strAddress == asio::ip::address_v4::loopback().to_string())
1717 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1718 BOOST_FOREACH(string strAllow, vAllow)
1719 if (WildcardMatch(strAddress, strAllow))
1726 // IOStream device that speaks SSL but can also speak non-SSL
1728 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1730 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1732 fUseSSL = fUseSSLIn;
1733 fNeedHandshake = fUseSSLIn;
1736 void handshake(ssl::stream_base::handshake_type role)
1738 if (!fNeedHandshake) return;
1739 fNeedHandshake = false;
1740 stream.handshake(role);
1742 std::streamsize read(char* s, std::streamsize n)
1744 handshake(ssl::stream_base::server); // HTTPS servers read first
1745 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1746 return stream.next_layer().read_some(asio::buffer(s, n));
1748 std::streamsize write(const char* s, std::streamsize n)
1750 handshake(ssl::stream_base::client); // HTTPS clients write first
1751 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1752 return asio::write(stream.next_layer(), asio::buffer(s, n));
1754 bool connect(const std::string& server, const std::string& port)
1756 ip::tcp::resolver resolver(stream.get_io_service());
1757 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1758 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1759 ip::tcp::resolver::iterator end;
1760 boost::system::error_code error = asio::error::host_not_found;
1761 while (error && endpoint_iterator != end)
1763 stream.lowest_layer().close();
1764 stream.lowest_layer().connect(*endpoint_iterator++, error);
1772 bool fNeedHandshake;
1778 void ThreadRPCServer(void* parg)
1780 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1783 vnThreadsRunning[4]++;
1784 ThreadRPCServer2(parg);
1785 vnThreadsRunning[4]--;
1787 catch (std::exception& e) {
1788 vnThreadsRunning[4]--;
1789 PrintException(&e, "ThreadRPCServer()");
1791 vnThreadsRunning[4]--;
1792 PrintException(NULL, "ThreadRPCServer()");
1794 printf("ThreadRPCServer exiting\n");
1797 void ThreadRPCServer2(void* parg)
1799 printf("ThreadRPCServer started\n");
1801 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1803 string strWhatAmI = "To use bitcoind";
1804 if (mapArgs.count("-server"))
1805 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1806 else if (mapArgs.count("-daemon"))
1807 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1809 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1810 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1812 GetConfigFile().c_str());
1813 CreateThread(Shutdown, NULL);
1817 bool fUseSSL = GetBoolArg("-rpcssl");
1818 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1820 asio::io_service io_service;
1821 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1822 ip::tcp::acceptor acceptor(io_service, endpoint);
1824 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1827 ssl::context context(io_service, ssl::context::sslv23);
1830 context.set_options(ssl::context::no_sslv2);
1831 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1832 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1833 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1834 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1835 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1836 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1837 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1838 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1840 string ciphers = GetArg("-rpcsslciphers",
1841 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1842 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1846 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1851 // Accept connection
1853 SSLStream sslStream(io_service, context);
1854 SSLIOStreamDevice d(sslStream, fUseSSL);
1855 iostreams::stream<SSLIOStreamDevice> stream(d);
1857 ip::tcp::iostream stream;
1860 ip::tcp::endpoint peer;
1861 vnThreadsRunning[4]--;
1863 acceptor.accept(sslStream.lowest_layer(), peer);
1865 acceptor.accept(*stream.rdbuf(), peer);
1867 vnThreadsRunning[4]++;
1871 // Restrict callers by IP
1872 if (!ClientAllowed(peer.address().to_string()))
1875 map<string, string> mapHeaders;
1878 boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
1879 if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
1882 printf("ThreadRPCServer ReadHTTP timeout\n");
1886 // Check authorization
1887 if (mapHeaders.count("authorization") == 0)
1889 stream << HTTPReply(401, "") << std::flush;
1892 if (!HTTPAuthorized(mapHeaders))
1894 // Deter brute-forcing short passwords
1895 if (mapArgs["-rpcpassword"].size() < 15)
1898 stream << HTTPReply(401, "") << std::flush;
1899 printf("ThreadRPCServer incorrect password attempt\n");
1903 Value id = Value::null;
1908 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1909 throw JSONRPCError(-32700, "Parse error");
1910 const Object& request = valRequest.get_obj();
1912 // Parse id now so errors from here on will have the id
1913 id = find_value(request, "id");
1916 Value valMethod = find_value(request, "method");
1917 if (valMethod.type() == null_type)
1918 throw JSONRPCError(-32600, "Missing method");
1919 if (valMethod.type() != str_type)
1920 throw JSONRPCError(-32600, "Method must be a string");
1921 string strMethod = valMethod.get_str();
1922 if (strMethod != "getwork")
1923 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1926 Value valParams = find_value(request, "params");
1928 if (valParams.type() == array_type)
1929 params = valParams.get_array();
1930 else if (valParams.type() == null_type)
1933 throw JSONRPCError(-32600, "Params must be an array");
1936 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1937 if (mi == mapCallTable.end())
1938 throw JSONRPCError(-32601, "Method not found");
1940 // Observe safe mode
1941 string strWarning = GetWarnings("rpc");
1942 if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1943 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1948 Value result = (*(*mi).second)(params, false);
1951 string strReply = JSONRPCReply(result, Value::null, id);
1952 stream << HTTPReply(200, strReply) << std::flush;
1954 catch (std::exception& e)
1956 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
1959 catch (Object& objError)
1961 ErrorReply(stream, objError, id);
1963 catch (std::exception& e)
1965 ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
1973 Object CallRPC(const string& strMethod, const Array& params)
1975 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1976 throw runtime_error(strprintf(
1977 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1978 "If the file does not exist, create it with owner-readable-only file permissions."),
1979 GetConfigFile().c_str()));
1981 // Connect to localhost
1982 bool fUseSSL = GetBoolArg("-rpcssl");
1984 asio::io_service io_service;
1985 ssl::context context(io_service, ssl::context::sslv23);
1986 context.set_options(ssl::context::no_sslv2);
1987 SSLStream sslStream(io_service, context);
1988 SSLIOStreamDevice d(sslStream, fUseSSL);
1989 iostreams::stream<SSLIOStreamDevice> stream(d);
1990 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1991 throw runtime_error("couldn't connect to server");
1994 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1996 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1998 throw runtime_error("couldn't connect to server");
2002 // HTTP basic authentication
2003 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
2004 map<string, string> mapRequestHeaders;
2005 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
2008 string strRequest = JSONRPCRequest(strMethod, params, 1);
2009 string strPost = HTTPPost(strRequest, mapRequestHeaders);
2010 stream << strPost << std::flush;
2013 map<string, string> mapHeaders;
2015 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
2017 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
2018 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
2019 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
2020 else if (strReply.empty())
2021 throw runtime_error("no response from server");
2025 if (!read_string(strReply, valReply))
2026 throw runtime_error("couldn't parse reply from server");
2027 const Object& reply = valReply.get_obj();
2029 throw runtime_error("expected reply to have result, error and id properties");
2037 template<typename T>
2038 void ConvertTo(Value& value)
2040 if (value.type() == str_type)
2042 // reinterpret string as unquoted json value
2044 if (!read_string(value.get_str(), value2))
2045 throw runtime_error("type mismatch");
2046 value = value2.get_value<T>();
2050 value = value.get_value<T>();
2054 int CommandLineRPC(int argc, char *argv[])
2061 while (argc > 1 && IsSwitchChar(argv[1][0]))
2069 throw runtime_error("too few parameters");
2070 string strMethod = argv[1];
2072 // Parameters default to strings
2074 for (int i = 2; i < argc; i++)
2075 params.push_back(argv[i]);
2076 int n = params.size();
2079 // Special case non-string parameter types
2081 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
2082 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2083 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
2084 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
2085 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2086 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2087 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2088 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2089 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2090 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
2091 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2092 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
2093 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2094 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
2095 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2096 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
2097 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2098 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
2099 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2100 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
2101 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2102 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2103 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2104 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2105 if (strMethod == "sendmany" && n > 1)
2107 string s = params[1].get_str();
2109 if (!read_string(s, v) || v.type() != obj_type)
2110 throw runtime_error("type mismatch");
2111 params[1] = v.get_obj();
2113 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2116 Object reply = CallRPC(strMethod, params);
2119 const Value& result = find_value(reply, "result");
2120 const Value& error = find_value(reply, "error");
2121 const Value& id = find_value(reply, "id");
2123 if (error.type() != null_type)
2126 strPrint = "error: " + write_string(error, false);
2127 int code = find_value(error.get_obj(), "code").get_int();
2133 if (result.type() == null_type)
2135 else if (result.type() == str_type)
2136 strPrint = result.get_str();
2138 strPrint = write_string(result, true);
2141 catch (std::exception& e)
2143 strPrint = string("error: ") + e.what();
2148 PrintException(NULL, "CommandLineRPC()");
2153 #if defined(__WXMSW__) && defined(GUI)
2154 // Windows GUI apps can't print to command line,
2155 // so settle for a message box yuck
2156 MyMessageBox(strPrint, "Bitcoin", wxOK);
2158 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
2168 int main(int argc, char *argv[])
2171 // Turn off microsoft heap dump noise
2172 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2173 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
2175 setbuf(stdin, NULL);
2176 setbuf(stdout, NULL);
2177 setbuf(stderr, NULL);
2181 if (argc >= 2 && string(argv[1]) == "-server")
2183 printf("server ready\n");
2184 ThreadRPCServer(NULL);
2188 return CommandLineRPC(argc, argv);
2191 catch (std::exception& e) {
2192 PrintException(&e, "main()");
2194 PrintException(NULL, "main()");