1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "cryptopp/sha.h"
8 #include <boost/asio.hpp>
9 #include <boost/iostreams/concepts.hpp>
10 #include <boost/iostreams/stream.hpp>
12 #include <boost/asio/ssl.hpp>
13 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
15 #include "json/json_spirit_reader_template.h"
16 #include "json/json_spirit_writer_template.h"
17 #include "json/json_spirit_utils.h"
18 #define printf OutputDebugStringF
19 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
20 // precompiled in headers.h. The problem might be when the pch file goes over
21 // a certain size around 145MB. If we need access to json_spirit outside this
22 // file, we could use the compiled json_spirit option.
25 using namespace boost;
26 using namespace boost::asio;
27 using namespace json_spirit;
29 void ThreadRPCServer2(void* parg);
30 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
31 extern map<string, rpcfn_type> mapCallTable;
34 Object JSONRPCError(int code, const string& message)
37 error.push_back(Pair("code", code));
38 error.push_back(Pair("message", message));
43 void PrintConsole(const char* format, ...)
46 int limit = sizeof(buffer);
48 va_start(arg_ptr, format);
49 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
51 if (ret < 0 || ret >= limit)
57 #if defined(__WXMSW__) && defined(GUI)
58 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
60 fprintf(stdout, "%s", buffer);
65 int64 AmountFromValue(const Value& value)
67 double dAmount = value.get_real();
68 if (dAmount <= 0.0 || dAmount > 21000000.0)
69 throw JSONRPCError(-3, "Invalid amount");
70 int64 nAmount = roundint64(dAmount * COIN);
71 if (!MoneyRange(nAmount))
72 throw JSONRPCError(-3, "Invalid amount");
76 Value ValueFromAmount(int64 amount)
78 return (double)amount / (double)COIN;
81 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
83 entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
84 entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
85 entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
86 BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
87 entry.push_back(Pair(item.first, item.second));
90 string AccountFromValue(const Value& value)
92 string strAccount = value.get_str();
93 if (strAccount == "*")
94 throw JSONRPCError(-11, "Invalid account name");
101 /// Note: This interface may still be subject to change.
105 Value help(const Array& params, bool fHelp)
107 if (fHelp || params.size() > 1)
110 "List commands, or get help for a command.");
113 if (params.size() > 0)
114 strCommand = params[0].get_str();
117 set<rpcfn_type> setDone;
118 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
120 string strMethod = (*mi).first;
121 // We already filter duplicates, but these deprecated screw up the sort order
122 if (strMethod == "getamountreceived" ||
123 strMethod == "getallreceived" ||
124 (strMethod.find("label") != string::npos))
126 if (strCommand != "" && strMethod != strCommand)
131 rpcfn_type pfn = (*mi).second;
132 if (setDone.insert(pfn).second)
133 (*pfn)(params, true);
135 catch (std::exception& e)
137 // Help text is returned in an exception
138 string strHelp = string(e.what());
139 if (strCommand == "")
140 if (strHelp.find('\n') != -1)
141 strHelp = strHelp.substr(0, strHelp.find('\n'));
142 strRet += strHelp + "\n";
146 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
147 strRet = strRet.substr(0,strRet.size()-1);
152 Value stop(const Array& params, bool fHelp)
154 if (fHelp || params.size() != 0)
157 "Stop bitcoin server.");
159 // Shutdown will take long enough that the response should get back
160 CreateThread(Shutdown, NULL);
161 return "bitcoin server stopping";
165 Value getblockcount(const Array& params, bool fHelp)
167 if (fHelp || params.size() != 0)
170 "Returns the number of blocks in the longest block chain.");
176 Value getblocknumber(const Array& params, bool fHelp)
178 if (fHelp || params.size() != 0)
181 "Returns the block number of the latest block in the longest block chain.");
187 Value getconnectioncount(const Array& params, bool fHelp)
189 if (fHelp || params.size() != 0)
191 "getconnectioncount\n"
192 "Returns the number of connections to other nodes.");
194 return (int)vNodes.size();
198 double GetDifficulty()
200 // Floating point number that is a multiple of the minimum difficulty,
201 // minimum difficulty = 1.0.
202 if (pindexBest == NULL)
204 int nShift = 256 - 32 - 31; // to fit in a uint
205 double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
206 double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
207 return dMinimum / dCurrently;
210 Value getdifficulty(const Array& params, bool fHelp)
212 if (fHelp || params.size() != 0)
215 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
217 return GetDifficulty();
221 Value getgenerate(const Array& params, bool fHelp)
223 if (fHelp || params.size() != 0)
226 "Returns true or false.");
228 return (bool)fGenerateBitcoins;
232 Value setgenerate(const Array& params, bool fHelp)
234 if (fHelp || params.size() < 1 || params.size() > 2)
236 "setgenerate <generate> [genproclimit]\n"
237 "<generate> is true or false to turn generation on or off.\n"
238 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
240 bool fGenerate = true;
241 if (params.size() > 0)
242 fGenerate = params[0].get_bool();
244 if (params.size() > 1)
246 int nGenProcLimit = params[1].get_int();
247 fLimitProcessors = (nGenProcLimit != -1);
248 CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
249 if (nGenProcLimit != -1)
250 CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
251 if (nGenProcLimit == 0)
255 GenerateBitcoins(fGenerate);
260 Value gethashespersec(const Array& params, bool fHelp)
262 if (fHelp || params.size() != 0)
265 "Returns a recent hashes per second performance measurement while generating.");
267 if (GetTimeMillis() - nHPSTimerStart > 8000)
268 return (boost::int64_t)0;
269 return (boost::int64_t)dHashesPerSec;
273 Value getinfo(const Array& params, bool fHelp)
275 if (fHelp || params.size() != 0)
278 "Returns an object containing various state info.");
281 obj.push_back(Pair("version", (int)VERSION));
282 obj.push_back(Pair("balance", ValueFromAmount(GetBalance())));
283 obj.push_back(Pair("blocks", (int)nBestHeight));
284 obj.push_back(Pair("connections", (int)vNodes.size()));
285 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
286 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
287 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
288 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
289 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
290 obj.push_back(Pair("testnet", fTestNet));
291 obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
292 obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
293 obj.push_back(Pair("errors", GetWarnings("statusbar")));
298 Value getnewaddress(const Array& params, bool fHelp)
300 if (fHelp || params.size() > 1)
302 "getnewaddress [account]\n"
303 "Returns a new bitcoin address for receiving payments. "
304 "If [account] is specified (recommended), it is added to the address book "
305 "so payments received with the address will be credited to [account].");
307 // Parse the account first so we don't generate a key if there's an error
309 if (params.size() > 0)
310 strAccount = AccountFromValue(params[0]);
312 // Generate a new key that is added to wallet
313 string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
315 SetAddressBookName(strAddress, strAccount);
320 // requires cs_main, cs_mapWallet locks
321 string GetAccountAddress(string strAccount, bool bForceNew=false)
329 walletdb.ReadAccount(strAccount, account);
331 // Check if the current key has been used
332 if (!account.vchPubKey.empty())
334 CScript scriptPubKey;
335 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
336 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
337 it != mapWallet.end() && !account.vchPubKey.empty();
340 const CWalletTx& wtx = (*it).second;
341 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
342 if (txout.scriptPubKey == scriptPubKey)
343 account.vchPubKey.clear();
347 // Generate a new key
348 if (account.vchPubKey.empty() || bForceNew)
350 account.vchPubKey = GetKeyFromKeyPool();
351 string strAddress = PubKeyToAddress(account.vchPubKey);
352 SetAddressBookName(strAddress, strAccount);
353 walletdb.WriteAccount(strAccount, account);
356 walletdb.TxnCommit();
357 strAddress = PubKeyToAddress(account.vchPubKey);
362 Value getaccountaddress(const Array& params, bool fHelp)
364 if (fHelp || params.size() != 1)
366 "getaccountaddress <account>\n"
367 "Returns the current bitcoin address for receiving payments to this account.");
369 // Parse the account first so we don't generate a key if there's an error
370 string strAccount = AccountFromValue(params[0]);
374 CRITICAL_BLOCK(cs_main)
375 CRITICAL_BLOCK(cs_mapWallet)
377 ret = GetAccountAddress(strAccount);
385 Value setaccount(const Array& params, bool fHelp)
387 if (fHelp || params.size() < 1 || params.size() > 2)
389 "setaccount <bitcoinaddress> <account>\n"
390 "Sets the account associated with the given address.");
392 string strAddress = params[0].get_str();
394 bool isValid = AddressToHash160(strAddress, hash160);
396 throw JSONRPCError(-5, "Invalid bitcoin address");
400 if (params.size() > 1)
401 strAccount = AccountFromValue(params[1]);
403 // Detect when changing the account of an address that is the 'unused current key' of another account:
404 CRITICAL_BLOCK(cs_main)
405 CRITICAL_BLOCK(cs_mapWallet)
406 CRITICAL_BLOCK(cs_mapAddressBook)
408 if (mapAddressBook.count(strAddress))
410 string strOldAccount = mapAddressBook[strAddress];
411 if (strAddress == GetAccountAddress(strOldAccount))
412 GetAccountAddress(strOldAccount, true);
416 SetAddressBookName(strAddress, strAccount);
421 Value getaccount(const Array& params, bool fHelp)
423 if (fHelp || params.size() != 1)
425 "getaccount <bitcoinaddress>\n"
426 "Returns the account associated with the given address.");
428 string strAddress = params[0].get_str();
431 CRITICAL_BLOCK(cs_mapAddressBook)
433 map<string, string>::iterator mi = mapAddressBook.find(strAddress);
434 if (mi != mapAddressBook.end() && !(*mi).second.empty())
435 strAccount = (*mi).second;
441 Value getaddressesbyaccount(const Array& params, bool fHelp)
443 if (fHelp || params.size() != 1)
445 "getaddressesbyaccount <account>\n"
446 "Returns the list of addresses for the given account.");
448 string strAccount = AccountFromValue(params[0]);
450 // Find all addresses that have the given account
452 CRITICAL_BLOCK(cs_mapAddressBook)
454 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
456 const string& strAddress = item.first;
457 const string& strName = item.second;
458 if (strName == strAccount)
460 // We're only adding valid bitcoin addresses and not ip addresses
461 CScript scriptPubKey;
462 if (scriptPubKey.SetBitcoinAddress(strAddress))
463 ret.push_back(strAddress);
470 Value settxfee(const Array& params, bool fHelp)
472 if (fHelp || params.size() < 1 || params.size() > 1)
474 "settxfee <amount>\n"
475 "<amount> is a real and is rounded to the nearest 0.00000001");
479 if (params[0].get_real() != 0.0)
480 nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
482 nTransactionFee = nAmount;
486 Value sendtoaddress(const Array& params, bool fHelp)
488 if (fHelp || params.size() < 2 || params.size() > 4)
490 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
491 "<amount> is a real and is rounded to the nearest 0.00000001");
493 string strAddress = params[0].get_str();
496 int64 nAmount = AmountFromValue(params[1]);
500 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
501 wtx.mapValue["comment"] = params[2].get_str();
502 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
503 wtx.mapValue["to"] = params[3].get_str();
505 CRITICAL_BLOCK(cs_main)
507 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
509 throw JSONRPCError(-4, strError);
512 return wtx.GetHash().GetHex();
516 Value getreceivedbyaddress(const Array& params, bool fHelp)
518 if (fHelp || params.size() < 1 || params.size() > 2)
520 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
521 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
524 string strAddress = params[0].get_str();
525 CScript scriptPubKey;
526 if (!scriptPubKey.SetBitcoinAddress(strAddress))
527 throw JSONRPCError(-5, "Invalid bitcoin address");
528 if (!IsMine(scriptPubKey))
531 // Minimum confirmations
533 if (params.size() > 1)
534 nMinDepth = params[1].get_int();
538 CRITICAL_BLOCK(cs_mapWallet)
540 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
542 const CWalletTx& wtx = (*it).second;
543 if (wtx.IsCoinBase() || !wtx.IsFinal())
546 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
547 if (txout.scriptPubKey == scriptPubKey)
548 if (wtx.GetDepthInMainChain() >= nMinDepth)
549 nAmount += txout.nValue;
553 return ValueFromAmount(nAmount);
557 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
559 CRITICAL_BLOCK(cs_mapAddressBook)
561 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
563 const string& strAddress = item.first;
564 const string& strName = item.second;
565 if (strName == strAccount)
567 // We're only counting our own valid bitcoin addresses and not ip addresses
568 CScript scriptPubKey;
569 if (scriptPubKey.SetBitcoinAddress(strAddress))
570 if (IsMine(scriptPubKey))
571 setPubKey.insert(scriptPubKey);
578 Value getreceivedbyaccount(const Array& params, bool fHelp)
580 if (fHelp || params.size() < 1 || params.size() > 2)
582 "getreceivedbyaccount <account> [minconf=1]\n"
583 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
585 // Minimum confirmations
587 if (params.size() > 1)
588 nMinDepth = params[1].get_int();
590 // Get the set of pub keys that have the label
591 string strAccount = AccountFromValue(params[0]);
592 set<CScript> setPubKey;
593 GetAccountPubKeys(strAccount, setPubKey);
597 CRITICAL_BLOCK(cs_mapWallet)
599 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
601 const CWalletTx& wtx = (*it).second;
602 if (wtx.IsCoinBase() || !wtx.IsFinal())
605 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
606 if (setPubKey.count(txout.scriptPubKey))
607 if (wtx.GetDepthInMainChain() >= nMinDepth)
608 nAmount += txout.nValue;
612 return (double)nAmount / (double)COIN;
616 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
619 CRITICAL_BLOCK(cs_mapWallet)
621 // Tally wallet transactions
622 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
624 const CWalletTx& wtx = (*it).second;
628 int64 nGenerated, nReceived, nSent, nFee;
629 wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
631 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
632 nBalance += nReceived;
633 nBalance += nGenerated - nSent - nFee;
636 // Tally internal accounting entries
637 nBalance += walletdb.GetAccountCreditDebit(strAccount);
643 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
646 return GetAccountBalance(walletdb, strAccount, nMinDepth);
650 Value getbalance(const Array& params, bool fHelp)
652 if (fHelp || params.size() < 0 || params.size() > 2)
654 "getbalance [account] [minconf=1]\n"
655 "If [account] is not specified, returns the server's total available balance.\n"
656 "If [account] is specified, returns the balance in the account.");
658 if (params.size() == 0)
659 return ValueFromAmount(GetBalance());
662 if (params.size() > 1)
663 nMinDepth = params[1].get_int();
665 if (params[0].get_str() == "*") {
666 // Calculate total balance a different way from GetBalance()
667 // (GetBalance() sums up all unspent TxOuts)
668 // getbalance and getbalance '*' should always return the same number.
670 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
672 const CWalletTx& wtx = (*it).second;
676 int64 allGeneratedImmature, allGeneratedMature, allFee;
677 allGeneratedImmature = allGeneratedMature = allFee = 0;
678 string strSentAccount;
679 list<pair<string, int64> > listReceived;
680 list<pair<string, int64> > listSent;
681 wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
682 if (wtx.GetDepthInMainChain() >= nMinDepth)
683 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
684 nBalance += r.second;
685 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
686 nBalance -= r.second;
688 nBalance += allGeneratedMature;
690 return ValueFromAmount(nBalance);
693 string strAccount = AccountFromValue(params[0]);
695 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
697 return ValueFromAmount(nBalance);
701 Value movecmd(const Array& params, bool fHelp)
703 if (fHelp || params.size() < 3 || params.size() > 5)
705 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
706 "Move from one account in your wallet to another.");
708 string strFrom = AccountFromValue(params[0]);
709 string strTo = AccountFromValue(params[1]);
710 int64 nAmount = AmountFromValue(params[2]);
712 if (params.size() > 3)
713 nMinDepth = params[3].get_int();
715 if (params.size() > 4)
716 strComment = params[4].get_str();
718 CRITICAL_BLOCK(cs_mapWallet)
723 int64 nNow = GetAdjustedTime();
726 CAccountingEntry debit;
727 debit.strAccount = strFrom;
728 debit.nCreditDebit = -nAmount;
730 debit.strOtherAccount = strTo;
731 debit.strComment = strComment;
732 walletdb.WriteAccountingEntry(debit);
735 CAccountingEntry credit;
736 credit.strAccount = strTo;
737 credit.nCreditDebit = nAmount;
739 credit.strOtherAccount = strFrom;
740 credit.strComment = strComment;
741 walletdb.WriteAccountingEntry(credit);
743 walletdb.TxnCommit();
749 Value sendfrom(const Array& params, bool fHelp)
751 if (fHelp || params.size() < 3 || params.size() > 6)
753 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
754 "<amount> is a real and is rounded to the nearest 0.00000001");
756 string strAccount = AccountFromValue(params[0]);
757 string strAddress = params[1].get_str();
758 int64 nAmount = AmountFromValue(params[2]);
760 if (params.size() > 3)
761 nMinDepth = params[3].get_int();
764 wtx.strFromAccount = strAccount;
765 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
766 wtx.mapValue["comment"] = params[4].get_str();
767 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
768 wtx.mapValue["to"] = params[5].get_str();
770 CRITICAL_BLOCK(cs_main)
771 CRITICAL_BLOCK(cs_mapWallet)
774 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
775 if (nAmount > nBalance)
776 throw JSONRPCError(-6, "Account has insufficient funds");
779 string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
781 throw JSONRPCError(-4, strError);
784 return wtx.GetHash().GetHex();
787 Value sendmany(const Array& params, bool fHelp)
789 if (fHelp || params.size() < 2 || params.size() > 4)
791 "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
792 "amounts are double-precision floating point numbers");
794 string strAccount = AccountFromValue(params[0]);
795 Object sendTo = params[1].get_obj();
797 if (params.size() > 2)
798 nMinDepth = params[2].get_int();
801 wtx.strFromAccount = strAccount;
802 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
803 wtx.mapValue["comment"] = params[3].get_str();
805 set<string> setAddress;
806 vector<pair<CScript, int64> > vecSend;
808 int64 totalAmount = 0;
809 BOOST_FOREACH(const Pair& s, sendTo)
812 string strAddress = s.name_;
814 if (setAddress.count(strAddress))
815 throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
816 setAddress.insert(strAddress);
818 CScript scriptPubKey;
819 if (!scriptPubKey.SetBitcoinAddress(strAddress))
820 throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
821 int64 nAmount = AmountFromValue(s.value_);
822 totalAmount += nAmount;
824 vecSend.push_back(make_pair(scriptPubKey, nAmount));
827 CRITICAL_BLOCK(cs_main)
828 CRITICAL_BLOCK(cs_mapWallet)
831 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
832 if (totalAmount > nBalance)
833 throw JSONRPCError(-6, "Account has insufficient funds");
836 CReserveKey keyChange;
837 int64 nFeeRequired = 0;
838 bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
841 if (totalAmount + nFeeRequired > GetBalance())
842 throw JSONRPCError(-6, "Insufficient funds");
843 throw JSONRPCError(-4, "Transaction creation failed");
845 if (!CommitTransaction(wtx, keyChange))
846 throw JSONRPCError(-4, "Transaction commit failed");
849 return wtx.GetHash().GetHex();
864 Value ListReceived(const Array& params, bool fByAccounts)
866 // Minimum confirmations
868 if (params.size() > 0)
869 nMinDepth = params[0].get_int();
871 // Whether to include empty accounts
872 bool fIncludeEmpty = false;
873 if (params.size() > 1)
874 fIncludeEmpty = params[1].get_bool();
877 map<uint160, tallyitem> mapTally;
878 CRITICAL_BLOCK(cs_mapWallet)
880 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
882 const CWalletTx& wtx = (*it).second;
883 if (wtx.IsCoinBase() || !wtx.IsFinal())
886 int nDepth = wtx.GetDepthInMainChain();
887 if (nDepth < nMinDepth)
890 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
892 // Only counting our own bitcoin addresses and not ip addresses
893 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
894 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
897 tallyitem& item = mapTally[hash160];
898 item.nAmount += txout.nValue;
899 item.nConf = min(item.nConf, nDepth);
906 map<string, tallyitem> mapAccountTally;
907 CRITICAL_BLOCK(cs_mapAddressBook)
909 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
911 const string& strAddress = item.first;
912 const string& strAccount = item.second;
914 if (!AddressToHash160(strAddress, hash160))
916 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
917 if (it == mapTally.end() && !fIncludeEmpty)
922 if (it != mapTally.end())
924 nAmount = (*it).second.nAmount;
925 nConf = (*it).second.nConf;
930 tallyitem& item = mapAccountTally[strAccount];
931 item.nAmount += nAmount;
932 item.nConf = min(item.nConf, nConf);
937 obj.push_back(Pair("address", strAddress));
938 obj.push_back(Pair("account", strAccount));
939 obj.push_back(Pair("label", strAccount)); // deprecated
940 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
941 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
949 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
951 int64 nAmount = (*it).second.nAmount;
952 int nConf = (*it).second.nConf;
954 obj.push_back(Pair("account", (*it).first));
955 obj.push_back(Pair("label", (*it).first)); // deprecated
956 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
957 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
965 Value listreceivedbyaddress(const Array& params, bool fHelp)
967 if (fHelp || params.size() > 2)
969 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
970 "[minconf] is the minimum number of confirmations before payments are included.\n"
971 "[includeempty] whether to include addresses that haven't received any payments.\n"
972 "Returns an array of objects containing:\n"
973 " \"address\" : receiving address\n"
974 " \"account\" : the account of the receiving address\n"
975 " \"amount\" : total amount received by the address\n"
976 " \"confirmations\" : number of confirmations of the most recent transaction included");
978 return ListReceived(params, false);
981 Value listreceivedbyaccount(const Array& params, bool fHelp)
983 if (fHelp || params.size() > 2)
985 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
986 "[minconf] is the minimum number of confirmations before payments are included.\n"
987 "[includeempty] whether to include accounts that haven't received any payments.\n"
988 "Returns an array of objects containing:\n"
989 " \"account\" : the account of the receiving addresses\n"
990 " \"amount\" : total amount received by addresses with this account\n"
991 " \"confirmations\" : number of confirmations of the most recent transaction included");
993 return ListReceived(params, true);
996 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
998 int64 nGeneratedImmature, nGeneratedMature, nFee;
999 string strSentAccount;
1000 list<pair<string, int64> > listReceived;
1001 list<pair<string, int64> > listSent;
1002 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1004 bool fAllAccounts = (strAccount == string("*"));
1006 // Generated blocks assigned to account ""
1007 if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
1010 entry.push_back(Pair("account", string("")));
1011 if (nGeneratedImmature)
1013 entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
1014 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
1018 entry.push_back(Pair("category", "generate"));
1019 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
1022 WalletTxToJSON(wtx, entry);
1023 ret.push_back(entry);
1027 if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
1029 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1032 entry.push_back(Pair("account", strSentAccount));
1033 entry.push_back(Pair("address", s.first));
1034 entry.push_back(Pair("category", "send"));
1035 entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
1036 entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
1038 WalletTxToJSON(wtx, entry);
1039 ret.push_back(entry);
1044 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1045 CRITICAL_BLOCK(cs_mapAddressBook)
1047 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1050 if (mapAddressBook.count(r.first))
1051 account = mapAddressBook[r.first];
1052 if (fAllAccounts || (account == strAccount))
1055 entry.push_back(Pair("account", account));
1056 entry.push_back(Pair("address", r.first));
1057 entry.push_back(Pair("category", "receive"));
1058 entry.push_back(Pair("amount", ValueFromAmount(r.second)));
1060 WalletTxToJSON(wtx, entry);
1061 ret.push_back(entry);
1068 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
1070 bool fAllAccounts = (strAccount == string("*"));
1072 if (fAllAccounts || acentry.strAccount == strAccount)
1075 entry.push_back(Pair("account", acentry.strAccount));
1076 entry.push_back(Pair("category", "move"));
1077 entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
1078 entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
1079 entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
1080 entry.push_back(Pair("comment", acentry.strComment));
1081 ret.push_back(entry);
1085 Value listtransactions(const Array& params, bool fHelp)
1087 if (fHelp || params.size() > 3)
1088 throw runtime_error(
1089 "listtransactions [account] [count=10] [from=0]\n"
1090 "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
1092 string strAccount = "*";
1093 if (params.size() > 0)
1094 strAccount = params[0].get_str();
1096 if (params.size() > 1)
1097 nCount = params[1].get_int();
1099 if (params.size() > 2)
1100 nFrom = params[2].get_int();
1105 CRITICAL_BLOCK(cs_mapWallet)
1107 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
1108 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
1109 typedef multimap<int64, TxPair > TxItems;
1112 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1114 CWalletTx* wtx = &((*it).second);
1115 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
1117 list<CAccountingEntry> acentries;
1118 walletdb.ListAccountCreditDebit(strAccount, acentries);
1119 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1121 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
1124 // Now: iterate backwards until we have nCount items to return:
1125 TxItems::reverse_iterator it = txByTime.rbegin();
1126 for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
1128 CWalletTx *const pwtx = (*it).second.first;
1130 ListTransactions(*pwtx, strAccount, 0, true, ret);
1131 CAccountingEntry *const pacentry = (*it).second.second;
1133 AcentryToJSON(*pacentry, strAccount, ret);
1135 if (ret.size() >= nCount) break;
1137 // ret is now newest to oldest
1140 // Make sure we return only last nCount items (sends-to-self might give us an extra):
1141 if (ret.size() > nCount)
1143 Array::iterator last = ret.begin();
1144 std::advance(last, nCount);
1145 ret.erase(last, ret.end());
1147 std::reverse(ret.begin(), ret.end()); // oldest to newest
1152 Value listaccounts(const Array& params, bool fHelp)
1154 if (fHelp || params.size() > 1)
1155 throw runtime_error(
1156 "listaccounts [minconf=1]\n"
1157 "Returns Object that has account names as keys, account balances as values.");
1160 if (params.size() > 0)
1161 nMinDepth = params[0].get_int();
1163 map<string, int64> mapAccountBalances;
1164 CRITICAL_BLOCK(cs_mapWallet)
1165 CRITICAL_BLOCK(cs_mapAddressBook)
1167 BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
1169 if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
1170 mapAccountBalances[entry.second] = 0;
1173 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1175 const CWalletTx& wtx = (*it).second;
1176 int64 nGeneratedImmature, nGeneratedMature, nFee;
1177 string strSentAccount;
1178 list<pair<string, int64> > listReceived;
1179 list<pair<string, int64> > listSent;
1180 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1181 mapAccountBalances[strSentAccount] -= nFee;
1182 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1183 mapAccountBalances[strSentAccount] -= s.second;
1184 if (wtx.GetDepthInMainChain() >= nMinDepth)
1186 mapAccountBalances[""] += nGeneratedMature;
1187 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1188 if (mapAddressBook.count(r.first))
1189 mapAccountBalances[mapAddressBook[r.first]] += r.second;
1191 mapAccountBalances[""] += r.second;
1196 list<CAccountingEntry> acentries;
1197 CWalletDB().ListAccountCreditDebit("*", acentries);
1198 BOOST_FOREACH(const CAccountingEntry& entry, acentries)
1199 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1202 BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1203 ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1208 Value gettransaction(const Array& params, bool fHelp)
1210 if (fHelp || params.size() != 1)
1211 throw runtime_error(
1212 "gettransaction <txid>\n"
1213 "Get detailed information about <txid>");
1216 hash.SetHex(params[0].get_str());
1219 CRITICAL_BLOCK(cs_mapWallet)
1221 if (!mapWallet.count(hash))
1222 throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
1223 const CWalletTx& wtx = mapWallet[hash];
1225 int64 nCredit = wtx.GetCredit();
1226 int64 nDebit = wtx.GetDebit();
1227 int64 nNet = nCredit - nDebit;
1228 int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1230 entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1232 entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1234 WalletTxToJSON(mapWallet[hash], entry);
1237 ListTransactions(mapWallet[hash], "*", 0, false, details);
1238 entry.push_back(Pair("details", details));
1245 Value backupwallet(const Array& params, bool fHelp)
1247 if (fHelp || params.size() != 1)
1248 throw runtime_error(
1249 "backupwallet <destination>\n"
1250 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1252 string strDest = params[0].get_str();
1253 BackupWallet(strDest);
1259 Value validateaddress(const Array& params, bool fHelp)
1261 if (fHelp || params.size() != 1)
1262 throw runtime_error(
1263 "validateaddress <bitcoinaddress>\n"
1264 "Return information about <bitcoinaddress>.");
1266 string strAddress = params[0].get_str();
1268 bool isValid = AddressToHash160(strAddress, hash160);
1271 ret.push_back(Pair("isvalid", isValid));
1274 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1275 // version of the address:
1276 string currentAddress = Hash160ToAddress(hash160);
1277 ret.push_back(Pair("address", currentAddress));
1278 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1279 CRITICAL_BLOCK(cs_mapAddressBook)
1281 if (mapAddressBook.count(currentAddress))
1282 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
1289 Value getwork(const Array& params, bool fHelp)
1291 if (fHelp || params.size() > 1)
1292 throw runtime_error(
1294 "If [data] is not specified, returns formatted hash data to work on:\n"
1295 " \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1296 " \"data\" : block data\n"
1297 " \"hash1\" : formatted hash buffer for second hash\n"
1298 " \"target\" : little endian hash target\n"
1299 "If [data] is specified, tries to solve the block and returns true if it was successful.");
1302 throw JSONRPCError(-9, "Bitcoin is not connected!");
1304 if (IsInitialBlockDownload())
1305 throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1307 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1308 static vector<CBlock*> vNewBlock;
1309 static CReserveKey reservekey;
1311 if (params.size() == 0)
1314 static unsigned int nTransactionsUpdatedLast;
1315 static CBlockIndex* pindexPrev;
1316 static int64 nStart;
1317 static CBlock* pblock;
1318 if (pindexPrev != pindexBest ||
1319 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1321 if (pindexPrev != pindexBest)
1323 // Deallocate old blocks since they're obsolete now
1324 mapNewBlock.clear();
1325 BOOST_FOREACH(CBlock* pblock, vNewBlock)
1329 nTransactionsUpdatedLast = nTransactionsUpdated;
1330 pindexPrev = pindexBest;
1334 pblock = CreateNewBlock(reservekey);
1336 throw JSONRPCError(-7, "Out of memory");
1337 vNewBlock.push_back(pblock);
1341 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1344 // Update nExtraNonce
1345 static unsigned int nExtraNonce = 0;
1346 static int64 nPrevTime = 0;
1347 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1350 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1352 // Prebuild hash buffers
1356 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1358 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1361 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1362 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
1363 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
1364 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
1370 vector<unsigned char> vchData = ParseHex(params[0].get_str());
1371 if (vchData.size() != 128)
1372 throw JSONRPCError(-8, "Invalid parameter");
1373 CBlock* pdata = (CBlock*)&vchData[0];
1376 for (int i = 0; i < 128/4; i++)
1377 ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1380 if (!mapNewBlock.count(pdata->hashMerkleRoot))
1382 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1383 unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1385 pblock->nTime = pdata->nTime;
1386 pblock->nNonce = pdata->nNonce;
1387 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1388 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1390 return CheckWork(pblock, reservekey);
1408 pair<string, rpcfn_type> pCallTable[] =
1410 make_pair("help", &help),
1411 make_pair("stop", &stop),
1412 make_pair("getblockcount", &getblockcount),
1413 make_pair("getblocknumber", &getblocknumber),
1414 make_pair("getconnectioncount", &getconnectioncount),
1415 make_pair("getdifficulty", &getdifficulty),
1416 make_pair("getgenerate", &getgenerate),
1417 make_pair("setgenerate", &setgenerate),
1418 make_pair("gethashespersec", &gethashespersec),
1419 make_pair("getinfo", &getinfo),
1420 make_pair("getnewaddress", &getnewaddress),
1421 make_pair("getaccountaddress", &getaccountaddress),
1422 make_pair("setaccount", &setaccount),
1423 make_pair("setlabel", &setaccount), // deprecated
1424 make_pair("getaccount", &getaccount),
1425 make_pair("getlabel", &getaccount), // deprecated
1426 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1427 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
1428 make_pair("sendtoaddress", &sendtoaddress),
1429 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1430 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1431 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
1432 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
1433 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
1434 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1435 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1436 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
1437 make_pair("backupwallet", &backupwallet),
1438 make_pair("validateaddress", &validateaddress),
1439 make_pair("getbalance", &getbalance),
1440 make_pair("move", &movecmd),
1441 make_pair("sendfrom", &sendfrom),
1442 make_pair("sendmany", &sendmany),
1443 make_pair("gettransaction", &gettransaction),
1444 make_pair("listtransactions", &listtransactions),
1445 make_pair("getwork", &getwork),
1446 make_pair("listaccounts", &listaccounts),
1447 make_pair("settxfee", &settxfee),
1449 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1451 string pAllowInSafeMode[] =
1457 "getconnectioncount",
1464 "getaccountaddress",
1467 "getlabel", // deprecated
1468 "getaddressesbyaccount",
1469 "getaddressesbylabel", // deprecated
1474 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1482 // This ain't Apache. We're just using HTTP header for the length field
1483 // and to be compatible with other JSON-RPC implementations.
1486 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1489 s << "POST / HTTP/1.1\r\n"
1490 << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
1491 << "Host: 127.0.0.1\r\n"
1492 << "Content-Type: application/json\r\n"
1493 << "Content-Length: " << strMsg.size() << "\r\n"
1494 << "Accept: application/json\r\n";
1495 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1496 s << item.first << ": " << item.second << "\r\n";
1497 s << "\r\n" << strMsg;
1502 string rfc1123Time()
1507 struct tm* now_gmt = gmtime(&now);
1508 string locale(setlocale(LC_TIME, NULL));
1509 setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
1510 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
1511 setlocale(LC_TIME, locale.c_str());
1512 return string(buffer);
1515 string HTTPReply(int nStatus, const string& strMsg)
1518 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1520 "Server: bitcoin-json-rpc/%s\r\n"
1521 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1522 "Content-Type: text/html\r\n"
1523 "Content-Length: 296\r\n"
1525 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1526 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1529 "<TITLE>Error</TITLE>\r\n"
1530 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1532 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1533 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
1535 if (nStatus == 200) strStatus = "OK";
1536 else if (nStatus == 400) strStatus = "Bad Request";
1537 else if (nStatus == 404) strStatus = "Not Found";
1538 else if (nStatus == 500) strStatus = "Internal Server Error";
1540 "HTTP/1.1 %d %s\r\n"
1542 "Connection: close\r\n"
1543 "Content-Length: %d\r\n"
1544 "Content-Type: application/json\r\n"
1545 "Server: bitcoin-json-rpc/%s\r\n"
1550 rfc1123Time().c_str(),
1552 FormatFullVersion().c_str(),
1556 int ReadHTTPStatus(std::basic_istream<char>& stream)
1559 getline(stream, str);
1560 vector<string> vWords;
1561 boost::split(vWords, str, boost::is_any_of(" "));
1562 if (vWords.size() < 2)
1564 return atoi(vWords[1].c_str());
1567 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1573 std::getline(stream, str);
1574 if (str.empty() || str == "\r")
1576 string::size_type nColon = str.find(":");
1577 if (nColon != string::npos)
1579 string strHeader = str.substr(0, nColon);
1580 boost::trim(strHeader);
1581 boost::to_lower(strHeader);
1582 string strValue = str.substr(nColon+1);
1583 boost::trim(strValue);
1584 mapHeadersRet[strHeader] = strValue;
1585 if (strHeader == "content-length")
1586 nLen = atoi(strValue.c_str());
1592 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1594 mapHeadersRet.clear();
1598 int nStatus = ReadHTTPStatus(stream);
1601 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1602 if (nLen < 0 || nLen > MAX_SIZE)
1608 vector<char> vch(nLen);
1609 stream.read(&vch[0], nLen);
1610 strMessageRet = string(vch.begin(), vch.end());
1616 string EncodeBase64(string s)
1621 b64 = BIO_new(BIO_f_base64());
1622 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1623 bmem = BIO_new(BIO_s_mem());
1624 b64 = BIO_push(b64, bmem);
1625 BIO_write(b64, s.c_str(), s.size());
1627 BIO_get_mem_ptr(b64, &bptr);
1629 string result(bptr->data, bptr->length);
1635 string DecodeBase64(string s)
1639 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1641 b64 = BIO_new(BIO_f_base64());
1642 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1643 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1644 bmem = BIO_push(b64, bmem);
1645 BIO_read(bmem, buffer, s.size());
1648 string result(buffer);
1653 bool HTTPAuthorized(map<string, string>& mapHeaders)
1655 string strAuth = mapHeaders["authorization"];
1656 if (strAuth.substr(0,6) != "Basic ")
1658 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1659 string strUserPass = DecodeBase64(strUserPass64);
1660 string::size_type nColon = strUserPass.find(":");
1661 if (nColon == string::npos)
1663 string strUser = strUserPass.substr(0, nColon);
1664 string strPassword = strUserPass.substr(nColon+1);
1665 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1669 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1670 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1671 // unspecified (HTTP errors and contents of 'error').
1673 // 1.0 spec: http://json-rpc.org/wiki/specification
1674 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1675 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1678 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1681 request.push_back(Pair("method", strMethod));
1682 request.push_back(Pair("params", params));
1683 request.push_back(Pair("id", id));
1684 return write_string(Value(request), false) + "\n";
1687 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1690 if (error.type() != null_type)
1691 reply.push_back(Pair("result", Value::null));
1693 reply.push_back(Pair("result", result));
1694 reply.push_back(Pair("error", error));
1695 reply.push_back(Pair("id", id));
1696 return write_string(Value(reply), false) + "\n";
1699 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1701 // Send error reply from json-rpc error object
1703 int code = find_value(objError, "code").get_int();
1704 if (code == -32600) nStatus = 400;
1705 else if (code == -32601) nStatus = 404;
1706 string strReply = JSONRPCReply(Value::null, objError, id);
1707 stream << HTTPReply(nStatus, strReply) << std::flush;
1710 bool ClientAllowed(const string& strAddress)
1712 if (strAddress == asio::ip::address_v4::loopback().to_string())
1714 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1715 BOOST_FOREACH(string strAllow, vAllow)
1716 if (WildcardMatch(strAddress, strAllow))
1723 // IOStream device that speaks SSL but can also speak non-SSL
1725 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1727 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1729 fUseSSL = fUseSSLIn;
1730 fNeedHandshake = fUseSSLIn;
1733 void handshake(ssl::stream_base::handshake_type role)
1735 if (!fNeedHandshake) return;
1736 fNeedHandshake = false;
1737 stream.handshake(role);
1739 std::streamsize read(char* s, std::streamsize n)
1741 handshake(ssl::stream_base::server); // HTTPS servers read first
1742 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1743 return stream.next_layer().read_some(asio::buffer(s, n));
1745 std::streamsize write(const char* s, std::streamsize n)
1747 handshake(ssl::stream_base::client); // HTTPS clients write first
1748 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1749 return asio::write(stream.next_layer(), asio::buffer(s, n));
1751 bool connect(const std::string& server, const std::string& port)
1753 ip::tcp::resolver resolver(stream.get_io_service());
1754 ip::tcp::resolver::query query(server.c_str(), port.c_str());
1755 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1756 ip::tcp::resolver::iterator end;
1757 boost::system::error_code error = asio::error::host_not_found;
1758 while (error && endpoint_iterator != end)
1760 stream.lowest_layer().close();
1761 stream.lowest_layer().connect(*endpoint_iterator++, error);
1769 bool fNeedHandshake;
1775 void ThreadRPCServer(void* parg)
1777 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1780 vnThreadsRunning[4]++;
1781 ThreadRPCServer2(parg);
1782 vnThreadsRunning[4]--;
1784 catch (std::exception& e) {
1785 vnThreadsRunning[4]--;
1786 PrintException(&e, "ThreadRPCServer()");
1788 vnThreadsRunning[4]--;
1789 PrintException(NULL, "ThreadRPCServer()");
1791 printf("ThreadRPCServer exiting\n");
1794 void ThreadRPCServer2(void* parg)
1796 printf("ThreadRPCServer started\n");
1798 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1800 string strWhatAmI = "To use bitcoind";
1801 if (mapArgs.count("-server"))
1802 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1803 else if (mapArgs.count("-daemon"))
1804 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1806 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1807 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1809 GetConfigFile().c_str());
1810 CreateThread(Shutdown, NULL);
1814 bool fUseSSL = GetBoolArg("-rpcssl");
1815 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1817 asio::io_service io_service;
1818 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1819 ip::tcp::acceptor acceptor(io_service, endpoint);
1821 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1824 ssl::context context(io_service, ssl::context::sslv23);
1827 context.set_options(ssl::context::no_sslv2);
1828 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1829 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1830 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1831 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1832 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1833 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1834 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1835 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1837 string ciphers = GetArg("-rpcsslciphers",
1838 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1839 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1843 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1848 // Accept connection
1850 SSLStream sslStream(io_service, context);
1851 SSLIOStreamDevice d(sslStream, fUseSSL);
1852 iostreams::stream<SSLIOStreamDevice> stream(d);
1854 ip::tcp::iostream stream;
1857 ip::tcp::endpoint peer;
1858 vnThreadsRunning[4]--;
1860 acceptor.accept(sslStream.lowest_layer(), peer);
1862 acceptor.accept(*stream.rdbuf(), peer);
1864 vnThreadsRunning[4]++;
1868 // Restrict callers by IP
1869 if (!ClientAllowed(peer.address().to_string()))
1872 map<string, string> mapHeaders;
1875 boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
1876 if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
1879 printf("ThreadRPCServer ReadHTTP timeout\n");
1883 // Check authorization
1884 if (mapHeaders.count("authorization") == 0)
1886 stream << HTTPReply(401, "") << std::flush;
1889 if (!HTTPAuthorized(mapHeaders))
1891 // Deter brute-forcing short passwords
1892 if (mapArgs["-rpcpassword"].size() < 15)
1895 stream << HTTPReply(401, "") << std::flush;
1896 printf("ThreadRPCServer incorrect password attempt\n");
1900 Value id = Value::null;
1905 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1906 throw JSONRPCError(-32700, "Parse error");
1907 const Object& request = valRequest.get_obj();
1909 // Parse id now so errors from here on will have the id
1910 id = find_value(request, "id");
1913 Value valMethod = find_value(request, "method");
1914 if (valMethod.type() == null_type)
1915 throw JSONRPCError(-32600, "Missing method");
1916 if (valMethod.type() != str_type)
1917 throw JSONRPCError(-32600, "Method must be a string");
1918 string strMethod = valMethod.get_str();
1919 if (strMethod != "getwork")
1920 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1923 Value valParams = find_value(request, "params");
1925 if (valParams.type() == array_type)
1926 params = valParams.get_array();
1927 else if (valParams.type() == null_type)
1930 throw JSONRPCError(-32600, "Params must be an array");
1933 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1934 if (mi == mapCallTable.end())
1935 throw JSONRPCError(-32601, "Method not found");
1937 // Observe safe mode
1938 string strWarning = GetWarnings("rpc");
1939 if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1940 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1945 Value result = (*(*mi).second)(params, false);
1948 string strReply = JSONRPCReply(result, Value::null, id);
1949 stream << HTTPReply(200, strReply) << std::flush;
1951 catch (std::exception& e)
1953 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
1956 catch (Object& objError)
1958 ErrorReply(stream, objError, id);
1960 catch (std::exception& e)
1962 ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
1970 Object CallRPC(const string& strMethod, const Array& params)
1972 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1973 throw runtime_error(strprintf(
1974 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1975 "If the file does not exist, create it with owner-readable-only file permissions."),
1976 GetConfigFile().c_str()));
1978 // Connect to localhost
1979 bool fUseSSL = GetBoolArg("-rpcssl");
1981 asio::io_service io_service;
1982 ssl::context context(io_service, ssl::context::sslv23);
1983 context.set_options(ssl::context::no_sslv2);
1984 SSLStream sslStream(io_service, context);
1985 SSLIOStreamDevice d(sslStream, fUseSSL);
1986 iostreams::stream<SSLIOStreamDevice> stream(d);
1987 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1988 throw runtime_error("couldn't connect to server");
1991 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1993 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1995 throw runtime_error("couldn't connect to server");
1999 // HTTP basic authentication
2000 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
2001 map<string, string> mapRequestHeaders;
2002 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
2005 string strRequest = JSONRPCRequest(strMethod, params, 1);
2006 string strPost = HTTPPost(strRequest, mapRequestHeaders);
2007 stream << strPost << std::flush;
2010 map<string, string> mapHeaders;
2012 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
2014 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
2015 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
2016 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
2017 else if (strReply.empty())
2018 throw runtime_error("no response from server");
2022 if (!read_string(strReply, valReply))
2023 throw runtime_error("couldn't parse reply from server");
2024 const Object& reply = valReply.get_obj();
2026 throw runtime_error("expected reply to have result, error and id properties");
2034 template<typename T>
2035 void ConvertTo(Value& value)
2037 if (value.type() == str_type)
2039 // reinterpret string as unquoted json value
2041 if (!read_string(value.get_str(), value2))
2042 throw runtime_error("type mismatch");
2043 value = value2.get_value<T>();
2047 value = value.get_value<T>();
2051 int CommandLineRPC(int argc, char *argv[])
2058 while (argc > 1 && IsSwitchChar(argv[1][0]))
2066 throw runtime_error("too few parameters");
2067 string strMethod = argv[1];
2069 // Parameters default to strings
2071 for (int i = 2; i < argc; i++)
2072 params.push_back(argv[i]);
2073 int n = params.size();
2076 // Special case non-string parameter types
2078 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
2079 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2080 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
2081 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
2082 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2083 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2084 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2085 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2086 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2087 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
2088 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2089 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
2090 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2091 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
2092 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2093 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
2094 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2095 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
2096 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2097 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
2098 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2099 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2100 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2101 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2102 if (strMethod == "sendmany" && n > 1)
2104 string s = params[1].get_str();
2106 if (!read_string(s, v) || v.type() != obj_type)
2107 throw runtime_error("type mismatch");
2108 params[1] = v.get_obj();
2110 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2113 Object reply = CallRPC(strMethod, params);
2116 const Value& result = find_value(reply, "result");
2117 const Value& error = find_value(reply, "error");
2118 const Value& id = find_value(reply, "id");
2120 if (error.type() != null_type)
2123 strPrint = "error: " + write_string(error, false);
2124 int code = find_value(error.get_obj(), "code").get_int();
2130 if (result.type() == null_type)
2132 else if (result.type() == str_type)
2133 strPrint = result.get_str();
2135 strPrint = write_string(result, true);
2138 catch (std::exception& e)
2140 strPrint = string("error: ") + e.what();
2145 PrintException(NULL, "CommandLineRPC()");
2150 #if defined(__WXMSW__) && defined(GUI)
2151 // Windows GUI apps can't print to command line,
2152 // so settle for a message box yuck
2153 MyMessageBox(strPrint, "Bitcoin", wxOK);
2155 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
2165 int main(int argc, char *argv[])
2168 // Turn off microsoft heap dump noise
2169 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2170 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
2172 setbuf(stdin, NULL);
2173 setbuf(stdout, NULL);
2174 setbuf(stderr, NULL);
2178 if (argc >= 2 && string(argv[1]) == "-server")
2180 printf("server ready\n");
2181 ThreadRPCServer(NULL);
2185 return CommandLineRPC(argc, argv);
2188 catch (std::exception& e) {
2189 PrintException(&e, "main()");
2191 PrintException(NULL, "main()");