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>
14 #include <boost/algorithm/string.hpp>
16 #include <boost/asio/ssl.hpp>
17 #include <boost/filesystem.hpp>
18 #include <boost/filesystem/fstream.hpp>
19 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
21 #include "json/json_spirit_reader_template.h"
22 #include "json/json_spirit_writer_template.h"
23 #include "json/json_spirit_utils.h"
24 #define printf OutputDebugStringF
25 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
26 // precompiled in headers.h. The problem might be when the pch file goes over
27 // a certain size around 145MB. If we need access to json_spirit outside this
28 // file, we could use the compiled json_spirit option.
31 using namespace boost;
32 using namespace boost::asio;
33 using namespace json_spirit;
35 void ThreadRPCServer2(void* parg);
36 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
37 extern map<string, rpcfn_type> mapCallTable;
40 Object JSONRPCError(int code, const string& message)
43 error.push_back(Pair("code", code));
44 error.push_back(Pair("message", message));
49 void PrintConsole(const char* format, ...)
52 int limit = sizeof(buffer);
54 va_start(arg_ptr, format);
55 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
57 if (ret < 0 || ret >= limit)
63 #if defined(__WXMSW__) && defined(GUI)
64 MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
66 fprintf(stdout, "%s", buffer);
71 int64 AmountFromValue(const Value& value)
73 double dAmount = value.get_real();
74 if (dAmount <= 0.0 || dAmount > 21000000.0)
75 throw JSONRPCError(-3, "Invalid amount");
76 int64 nAmount = roundint64(dAmount * COIN);
77 if (!MoneyRange(nAmount))
78 throw JSONRPCError(-3, "Invalid amount");
82 Value ValueFromAmount(int64 amount)
84 return (double)amount / (double)COIN;
87 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
89 entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
90 entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
91 entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
92 BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
93 entry.push_back(Pair(item.first, item.second));
96 string AccountFromValue(const Value& value)
98 string strAccount = value.get_str();
99 if (strAccount == "*")
100 throw JSONRPCError(-11, "Invalid account name");
107 /// Note: This interface may still be subject to change.
111 Value help(const Array& params, bool fHelp)
113 if (fHelp || params.size() > 1)
116 "List commands, or get help for a command.");
119 if (params.size() > 0)
120 strCommand = params[0].get_str();
123 set<rpcfn_type> setDone;
124 for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
126 string strMethod = (*mi).first;
127 // We already filter duplicates, but these deprecated screw up the sort order
128 if (strMethod == "getamountreceived" ||
129 strMethod == "getallreceived" ||
130 (strMethod.find("label") != string::npos))
132 if (strCommand != "" && strMethod != strCommand)
137 rpcfn_type pfn = (*mi).second;
138 if (setDone.insert(pfn).second)
139 (*pfn)(params, true);
141 catch (std::exception& e)
143 // Help text is returned in an exception
144 string strHelp = string(e.what());
145 if (strCommand == "")
146 if (strHelp.find('\n') != -1)
147 strHelp = strHelp.substr(0, strHelp.find('\n'));
148 strRet += strHelp + "\n";
152 strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
153 strRet = strRet.substr(0,strRet.size()-1);
158 Value stop(const Array& params, bool fHelp)
160 if (fHelp || params.size() != 0)
163 "Stop bitcoin server.");
165 // Shutdown will take long enough that the response should get back
166 CreateThread(Shutdown, NULL);
167 return "bitcoin server stopping";
171 Value getblockcount(const Array& params, bool fHelp)
173 if (fHelp || params.size() != 0)
176 "Returns the number of blocks in the longest block chain.");
182 Value getblocknumber(const Array& params, bool fHelp)
184 if (fHelp || params.size() != 0)
187 "Returns the block number of the latest block in the longest block chain.");
193 Value getconnectioncount(const Array& params, bool fHelp)
195 if (fHelp || params.size() != 0)
197 "getconnectioncount\n"
198 "Returns the number of connections to other nodes.");
200 return (int)vNodes.size();
204 double GetDifficulty()
206 // Floating point number that is a multiple of the minimum difficulty,
207 // minimum difficulty = 1.0.
209 if (pindexBest == NULL)
211 int nShift = (pindexBest->nBits >> 24) & 0xff;
214 (double)0x0000ffff / (double)(pindexBest->nBits & 0x00ffffff);
230 Value getdifficulty(const Array& params, bool fHelp)
232 if (fHelp || params.size() != 0)
235 "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
237 return GetDifficulty();
241 Value getgenerate(const Array& params, bool fHelp)
243 if (fHelp || params.size() != 0)
246 "Returns true or false.");
248 return (bool)fGenerateBitcoins;
252 Value setgenerate(const Array& params, bool fHelp)
254 if (fHelp || params.size() < 1 || params.size() > 2)
256 "setgenerate <generate> [genproclimit]\n"
257 "<generate> is true or false to turn generation on or off.\n"
258 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
260 bool fGenerate = true;
261 if (params.size() > 0)
262 fGenerate = params[0].get_bool();
264 if (params.size() > 1)
266 int nGenProcLimit = params[1].get_int();
267 fLimitProcessors = (nGenProcLimit != -1);
268 WriteSetting("fLimitProcessors", fLimitProcessors);
269 if (nGenProcLimit != -1)
270 WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
271 if (nGenProcLimit == 0)
275 GenerateBitcoins(fGenerate, pwalletMain);
280 Value gethashespersec(const Array& params, bool fHelp)
282 if (fHelp || params.size() != 0)
285 "Returns a recent hashes per second performance measurement while generating.");
287 if (GetTimeMillis() - nHPSTimerStart > 8000)
288 return (boost::int64_t)0;
289 return (boost::int64_t)dHashesPerSec;
293 Value getinfo(const Array& params, bool fHelp)
295 if (fHelp || params.size() != 0)
298 "Returns an object containing various state info.");
301 obj.push_back(Pair("version", (int)VERSION));
302 obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
303 obj.push_back(Pair("blocks", (int)nBestHeight));
304 obj.push_back(Pair("connections", (int)vNodes.size()));
305 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
306 obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
307 obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
308 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
309 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
310 obj.push_back(Pair("testnet", fTestNet));
311 obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
312 obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
313 obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
314 obj.push_back(Pair("errors", GetWarnings("statusbar")));
319 Value getnewaddress(const Array& params, bool fHelp)
321 if (fHelp || params.size() > 1)
323 "getnewaddress [account]\n"
324 "Returns a new bitcoin address for receiving payments. "
325 "If [account] is specified (recommended), it is added to the address book "
326 "so payments received with the address will be credited to [account].");
328 if (!pwalletMain->IsLocked())
329 pwalletMain->TopUpKeyPool();
331 if (pwalletMain->GetKeyPoolSize() < 1)
332 throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
334 // Parse the account first so we don't generate a key if there's an error
336 if (params.size() > 0)
337 strAccount = AccountFromValue(params[0]);
339 // Generate a new key that is added to wallet
340 string strAddress = PubKeyToAddress(pwalletMain->GetOrReuseKeyFromPool());
342 // This could be done in the same main CS as GetKeyFromKeyPool.
343 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
344 pwalletMain->SetAddressBookName(strAddress, strAccount);
350 // requires cs_main, cs_mapWallet, cs_mapAddressBook locks
351 string GetAccountAddress(string strAccount, bool bForceNew=false)
355 CWalletDB walletdb(pwalletMain->strWalletFile);
358 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
360 walletdb.ReadAccount(strAccount, account);
362 bool bKeyUsed = false;
364 // Check if the current key has been used
365 if (!account.vchPubKey.empty())
367 CScript scriptPubKey;
368 scriptPubKey.SetBitcoinAddress(account.vchPubKey);
369 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
370 it != pwalletMain->mapWallet.end() && !account.vchPubKey.empty();
373 const CWalletTx& wtx = (*it).second;
374 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
375 if (txout.scriptPubKey == scriptPubKey)
380 // Generate a new key
381 if (account.vchPubKey.empty() || bForceNew || bKeyUsed)
383 if (pwalletMain->GetKeyPoolSize() < 1)
385 if (bKeyUsed || bForceNew)
386 throw JSONRPCError(-12, "Error: Keypool ran out, please call topupkeypool first");
390 account.vchPubKey = pwalletMain->GetOrReuseKeyFromPool();
391 string strAddress = PubKeyToAddress(account.vchPubKey);
392 pwalletMain->SetAddressBookName(strAddress, strAccount);
393 walletdb.WriteAccount(strAccount, account);
398 strAddress = PubKeyToAddress(account.vchPubKey);
403 Value getaccountaddress(const Array& params, bool fHelp)
405 if (fHelp || params.size() != 1)
407 "getaccountaddress <account>\n"
408 "Returns the current bitcoin address for receiving payments to this account.");
410 // Parse the account first so we don't generate a key if there's an error
411 string strAccount = AccountFromValue(params[0]);
415 CRITICAL_BLOCK(cs_main)
416 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
417 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
419 ret = GetAccountAddress(strAccount);
427 Value setaccount(const Array& params, bool fHelp)
429 if (fHelp || params.size() < 1 || params.size() > 2)
431 "setaccount <bitcoinaddress> <account>\n"
432 "Sets the account associated with the given address.");
434 string strAddress = params[0].get_str();
436 bool isValid = AddressToHash160(strAddress, hash160);
438 throw JSONRPCError(-5, "Invalid bitcoin address");
442 if (params.size() > 1)
443 strAccount = AccountFromValue(params[1]);
445 // Detect when changing the account of an address that is the 'unused current key' of another account:
446 CRITICAL_BLOCK(cs_main)
447 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
448 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
450 if (pwalletMain->mapAddressBook.count(strAddress))
452 string strOldAccount = pwalletMain->mapAddressBook[strAddress];
453 if (strAddress == GetAccountAddress(strOldAccount))
454 GetAccountAddress(strOldAccount, true);
457 pwalletMain->SetAddressBookName(strAddress, strAccount);
464 Value getaccount(const Array& params, bool fHelp)
466 if (fHelp || params.size() != 1)
468 "getaccount <bitcoinaddress>\n"
469 "Returns the account associated with the given address.");
471 string strAddress = params[0].get_str();
474 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
476 map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);
477 if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
478 strAccount = (*mi).second;
484 Value getaddressesbyaccount(const Array& params, bool fHelp)
486 if (fHelp || params.size() != 1)
488 "getaddressesbyaccount <account>\n"
489 "Returns the list of addresses for the given account.");
491 string strAccount = AccountFromValue(params[0]);
493 // Find all addresses that have the given account
495 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
497 BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
499 const string& strAddress = item.first;
500 const string& strName = item.second;
501 if (strName == strAccount)
503 // We're only adding valid bitcoin addresses and not ip addresses
504 CScript scriptPubKey;
505 if (scriptPubKey.SetBitcoinAddress(strAddress))
506 ret.push_back(strAddress);
513 Value settxfee(const Array& params, bool fHelp)
515 if (fHelp || params.size() < 1 || params.size() > 1)
517 "settxfee <amount>\n"
518 "<amount> is a real and is rounded to the nearest 0.00000001");
522 if (params[0].get_real() != 0.0)
523 nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
525 nTransactionFee = nAmount;
529 Value sendtoaddress(const Array& params, bool fHelp)
531 if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
533 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
534 "<amount> is a real and is rounded to the nearest 0.00000001\n"
535 "requires wallet passphrase to be set with walletpassphrase first");
536 if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
538 "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
539 "<amount> is a real and is rounded to the nearest 0.00000001");
541 string strAddress = params[0].get_str();
544 int64 nAmount = AmountFromValue(params[1]);
548 if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
549 wtx.mapValue["comment"] = params[2].get_str();
550 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
551 wtx.mapValue["to"] = params[3].get_str();
553 CRITICAL_BLOCK(cs_main)
554 CRITICAL_BLOCK(pwalletMain->cs_vMasterKey)
556 if(pwalletMain->IsLocked())
557 throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
559 string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
561 throw JSONRPCError(-4, strError);
564 return wtx.GetHash().GetHex();
568 Value getreceivedbyaddress(const Array& params, bool fHelp)
570 if (fHelp || params.size() < 1 || params.size() > 2)
572 "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
573 "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
576 string strAddress = params[0].get_str();
577 CScript scriptPubKey;
578 if (!scriptPubKey.SetBitcoinAddress(strAddress))
579 throw JSONRPCError(-5, "Invalid bitcoin address");
580 if (!IsMine(*pwalletMain,scriptPubKey))
583 // Minimum confirmations
585 if (params.size() > 1)
586 nMinDepth = params[1].get_int();
590 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
592 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
594 const CWalletTx& wtx = (*it).second;
595 if (wtx.IsCoinBase() || !wtx.IsFinal())
598 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
599 if (txout.scriptPubKey == scriptPubKey)
600 if (wtx.GetDepthInMainChain() >= nMinDepth)
601 nAmount += txout.nValue;
605 return ValueFromAmount(nAmount);
609 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
611 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
613 BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
615 const string& strAddress = item.first;
616 const string& strName = item.second;
617 if (strName == strAccount)
619 // We're only counting our own valid bitcoin addresses and not ip addresses
620 CScript scriptPubKey;
621 if (scriptPubKey.SetBitcoinAddress(strAddress))
622 if (IsMine(*pwalletMain,scriptPubKey))
623 setPubKey.insert(scriptPubKey);
630 Value getreceivedbyaccount(const Array& params, bool fHelp)
632 if (fHelp || params.size() < 1 || params.size() > 2)
634 "getreceivedbyaccount <account> [minconf=1]\n"
635 "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
637 // Minimum confirmations
639 if (params.size() > 1)
640 nMinDepth = params[1].get_int();
642 // Get the set of pub keys that have the label
643 string strAccount = AccountFromValue(params[0]);
644 set<CScript> setPubKey;
645 GetAccountPubKeys(strAccount, setPubKey);
649 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
651 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
653 const CWalletTx& wtx = (*it).second;
654 if (wtx.IsCoinBase() || !wtx.IsFinal())
657 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
658 if (setPubKey.count(txout.scriptPubKey))
659 if (wtx.GetDepthInMainChain() >= nMinDepth)
660 nAmount += txout.nValue;
664 return (double)nAmount / (double)COIN;
668 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
671 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
673 // Tally wallet transactions
674 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
676 const CWalletTx& wtx = (*it).second;
680 int64 nGenerated, nReceived, nSent, nFee;
681 wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
683 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
684 nBalance += nReceived;
685 nBalance += nGenerated - nSent - nFee;
688 // Tally internal accounting entries
689 nBalance += walletdb.GetAccountCreditDebit(strAccount);
695 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
697 CWalletDB walletdb(pwalletMain->strWalletFile);
698 return GetAccountBalance(walletdb, strAccount, nMinDepth);
702 Value getbalance(const Array& params, bool fHelp)
704 if (fHelp || params.size() < 0 || params.size() > 2)
706 "getbalance [account] [minconf=1]\n"
707 "If [account] is not specified, returns the server's total available balance.\n"
708 "If [account] is specified, returns the balance in the account.");
710 if (params.size() == 0)
711 return ValueFromAmount(pwalletMain->GetBalance());
714 if (params.size() > 1)
715 nMinDepth = params[1].get_int();
717 if (params[0].get_str() == "*") {
718 // Calculate total balance a different way from GetBalance()
719 // (GetBalance() sums up all unspent TxOuts)
720 // getbalance and getbalance '*' should always return the same number.
722 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
724 const CWalletTx& wtx = (*it).second;
728 int64 allGeneratedImmature, allGeneratedMature, allFee;
729 allGeneratedImmature = allGeneratedMature = allFee = 0;
730 string strSentAccount;
731 list<pair<string, int64> > listReceived;
732 list<pair<string, int64> > listSent;
733 wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
734 if (wtx.GetDepthInMainChain() >= nMinDepth)
735 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
736 nBalance += r.second;
737 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
738 nBalance -= r.second;
740 nBalance += allGeneratedMature;
742 return ValueFromAmount(nBalance);
745 string strAccount = AccountFromValue(params[0]);
747 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
749 return ValueFromAmount(nBalance);
753 Value movecmd(const Array& params, bool fHelp)
755 if (fHelp || params.size() < 3 || params.size() > 5)
757 "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
758 "Move from one account in your wallet to another.");
760 string strFrom = AccountFromValue(params[0]);
761 string strTo = AccountFromValue(params[1]);
762 int64 nAmount = AmountFromValue(params[2]);
764 if (params.size() > 3)
765 nMinDepth = params[3].get_int();
767 if (params.size() > 4)
768 strComment = params[4].get_str();
770 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
772 CWalletDB walletdb(pwalletMain->strWalletFile);
775 int64 nNow = GetAdjustedTime();
778 CAccountingEntry debit;
779 debit.strAccount = strFrom;
780 debit.nCreditDebit = -nAmount;
782 debit.strOtherAccount = strTo;
783 debit.strComment = strComment;
784 walletdb.WriteAccountingEntry(debit);
787 CAccountingEntry credit;
788 credit.strAccount = strTo;
789 credit.nCreditDebit = nAmount;
791 credit.strOtherAccount = strFrom;
792 credit.strComment = strComment;
793 walletdb.WriteAccountingEntry(credit);
795 walletdb.TxnCommit();
801 Value sendfrom(const Array& params, bool fHelp)
803 if (pwalletMain->IsCrypted() && (fHelp || params.size() < 3 || params.size() > 6))
805 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
806 "<amount> is a real and is rounded to the nearest 0.00000001\n"
807 "requires wallet passphrase to be set with walletpassphrase first");
808 if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 3 || params.size() > 6))
810 "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
811 "<amount> is a real and is rounded to the nearest 0.00000001");
813 string strAccount = AccountFromValue(params[0]);
814 string strAddress = params[1].get_str();
815 int64 nAmount = AmountFromValue(params[2]);
817 if (params.size() > 3)
818 nMinDepth = params[3].get_int();
821 wtx.strFromAccount = strAccount;
822 if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
823 wtx.mapValue["comment"] = params[4].get_str();
824 if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
825 wtx.mapValue["to"] = params[5].get_str();
827 CRITICAL_BLOCK(cs_main)
828 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
829 CRITICAL_BLOCK(pwalletMain->cs_vMasterKey)
831 if(pwalletMain->IsLocked())
832 throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
835 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
836 if (nAmount > nBalance)
837 throw JSONRPCError(-6, "Account has insufficient funds");
840 string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
842 throw JSONRPCError(-4, strError);
845 return wtx.GetHash().GetHex();
849 Value sendmany(const Array& params, bool fHelp)
851 if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
853 "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
854 "amounts are double-precision floating point numbers\n"
855 "requires wallet passphrase to be set with walletpassphrase first");
856 if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
858 "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
859 "amounts are double-precision floating point numbers");
861 string strAccount = AccountFromValue(params[0]);
862 Object sendTo = params[1].get_obj();
864 if (params.size() > 2)
865 nMinDepth = params[2].get_int();
868 wtx.strFromAccount = strAccount;
869 if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
870 wtx.mapValue["comment"] = params[3].get_str();
872 set<string> setAddress;
873 vector<pair<CScript, int64> > vecSend;
875 int64 totalAmount = 0;
876 BOOST_FOREACH(const Pair& s, sendTo)
879 string strAddress = s.name_;
881 if (setAddress.count(strAddress))
882 throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
883 setAddress.insert(strAddress);
885 CScript scriptPubKey;
886 if (!scriptPubKey.SetBitcoinAddress(strAddress))
887 throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
888 int64 nAmount = AmountFromValue(s.value_);
889 totalAmount += nAmount;
891 vecSend.push_back(make_pair(scriptPubKey, nAmount));
894 CRITICAL_BLOCK(cs_main)
895 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
896 CRITICAL_BLOCK(pwalletMain->cs_vMasterKey)
898 if(pwalletMain->IsLocked())
899 throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
902 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
903 if (totalAmount > nBalance)
904 throw JSONRPCError(-6, "Account has insufficient funds");
907 CReserveKey keyChange(pwalletMain);
908 int64 nFeeRequired = 0;
909 bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
912 if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
913 throw JSONRPCError(-6, "Insufficient funds");
914 throw JSONRPCError(-4, "Transaction creation failed");
916 if (!pwalletMain->CommitTransaction(wtx, keyChange))
917 throw JSONRPCError(-4, "Transaction commit failed");
920 return wtx.GetHash().GetHex();
935 Value ListReceived(const Array& params, bool fByAccounts)
937 // Minimum confirmations
939 if (params.size() > 0)
940 nMinDepth = params[0].get_int();
942 // Whether to include empty accounts
943 bool fIncludeEmpty = false;
944 if (params.size() > 1)
945 fIncludeEmpty = params[1].get_bool();
948 map<uint160, tallyitem> mapTally;
949 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
951 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
953 const CWalletTx& wtx = (*it).second;
954 if (wtx.IsCoinBase() || !wtx.IsFinal())
957 int nDepth = wtx.GetDepthInMainChain();
958 if (nDepth < nMinDepth)
961 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
963 // Only counting our own bitcoin addresses and not ip addresses
964 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
965 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
968 tallyitem& item = mapTally[hash160];
969 item.nAmount += txout.nValue;
970 item.nConf = min(item.nConf, nDepth);
977 map<string, tallyitem> mapAccountTally;
978 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
980 BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
982 const string& strAddress = item.first;
983 const string& strAccount = item.second;
985 if (!AddressToHash160(strAddress, hash160))
987 map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
988 if (it == mapTally.end() && !fIncludeEmpty)
993 if (it != mapTally.end())
995 nAmount = (*it).second.nAmount;
996 nConf = (*it).second.nConf;
1001 tallyitem& item = mapAccountTally[strAccount];
1002 item.nAmount += nAmount;
1003 item.nConf = min(item.nConf, nConf);
1008 obj.push_back(Pair("address", strAddress));
1009 obj.push_back(Pair("account", strAccount));
1010 obj.push_back(Pair("label", strAccount)); // deprecated
1011 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
1012 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
1020 for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
1022 int64 nAmount = (*it).second.nAmount;
1023 int nConf = (*it).second.nConf;
1025 obj.push_back(Pair("account", (*it).first));
1026 obj.push_back(Pair("label", (*it).first)); // deprecated
1027 obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
1028 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
1036 Value listreceivedbyaddress(const Array& params, bool fHelp)
1038 if (fHelp || params.size() > 2)
1039 throw runtime_error(
1040 "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
1041 "[minconf] is the minimum number of confirmations before payments are included.\n"
1042 "[includeempty] whether to include addresses that haven't received any payments.\n"
1043 "Returns an array of objects containing:\n"
1044 " \"address\" : receiving address\n"
1045 " \"account\" : the account of the receiving address\n"
1046 " \"amount\" : total amount received by the address\n"
1047 " \"confirmations\" : number of confirmations of the most recent transaction included");
1049 return ListReceived(params, false);
1052 Value listreceivedbyaccount(const Array& params, bool fHelp)
1054 if (fHelp || params.size() > 2)
1055 throw runtime_error(
1056 "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
1057 "[minconf] is the minimum number of confirmations before payments are included.\n"
1058 "[includeempty] whether to include accounts that haven't received any payments.\n"
1059 "Returns an array of objects containing:\n"
1060 " \"account\" : the account of the receiving addresses\n"
1061 " \"amount\" : total amount received by addresses with this account\n"
1062 " \"confirmations\" : number of confirmations of the most recent transaction included");
1064 return ListReceived(params, true);
1067 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
1069 int64 nGeneratedImmature, nGeneratedMature, nFee;
1070 string strSentAccount;
1071 list<pair<string, int64> > listReceived;
1072 list<pair<string, int64> > listSent;
1073 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1075 bool fAllAccounts = (strAccount == string("*"));
1077 // Generated blocks assigned to account ""
1078 if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
1081 entry.push_back(Pair("account", string("")));
1082 if (nGeneratedImmature)
1084 entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
1085 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
1089 entry.push_back(Pair("category", "generate"));
1090 entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
1093 WalletTxToJSON(wtx, entry);
1094 ret.push_back(entry);
1098 if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
1100 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1103 entry.push_back(Pair("account", strSentAccount));
1104 entry.push_back(Pair("address", s.first));
1105 entry.push_back(Pair("category", "send"));
1106 entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
1107 entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
1109 WalletTxToJSON(wtx, entry);
1110 ret.push_back(entry);
1115 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1116 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
1118 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1121 if (pwalletMain->mapAddressBook.count(r.first))
1122 account = pwalletMain->mapAddressBook[r.first];
1123 if (fAllAccounts || (account == strAccount))
1126 entry.push_back(Pair("account", account));
1127 entry.push_back(Pair("address", r.first));
1128 entry.push_back(Pair("category", "receive"));
1129 entry.push_back(Pair("amount", ValueFromAmount(r.second)));
1131 WalletTxToJSON(wtx, entry);
1132 ret.push_back(entry);
1139 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
1141 bool fAllAccounts = (strAccount == string("*"));
1143 if (fAllAccounts || acentry.strAccount == strAccount)
1146 entry.push_back(Pair("account", acentry.strAccount));
1147 entry.push_back(Pair("category", "move"));
1148 entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
1149 entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
1150 entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
1151 entry.push_back(Pair("comment", acentry.strComment));
1152 ret.push_back(entry);
1156 Value listtransactions(const Array& params, bool fHelp)
1158 if (fHelp || params.size() > 3)
1159 throw runtime_error(
1160 "listtransactions [account] [count=10] [from=0]\n"
1161 "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
1163 string strAccount = "*";
1164 if (params.size() > 0)
1165 strAccount = params[0].get_str();
1167 if (params.size() > 1)
1168 nCount = params[1].get_int();
1170 if (params.size() > 2)
1171 nFrom = params[2].get_int();
1174 CWalletDB walletdb(pwalletMain->strWalletFile);
1176 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
1178 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
1179 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
1180 typedef multimap<int64, TxPair > TxItems;
1183 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
1185 CWalletTx* wtx = &((*it).second);
1186 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
1188 list<CAccountingEntry> acentries;
1189 walletdb.ListAccountCreditDebit(strAccount, acentries);
1190 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1192 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
1195 // Now: iterate backwards until we have nCount items to return:
1196 TxItems::reverse_iterator it = txByTime.rbegin();
1197 for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
1199 CWalletTx *const pwtx = (*it).second.first;
1201 ListTransactions(*pwtx, strAccount, 0, true, ret);
1202 CAccountingEntry *const pacentry = (*it).second.second;
1204 AcentryToJSON(*pacentry, strAccount, ret);
1206 if (ret.size() >= nCount) break;
1208 // ret is now newest to oldest
1211 // Make sure we return only last nCount items (sends-to-self might give us an extra):
1212 if (ret.size() > nCount)
1214 Array::iterator last = ret.begin();
1215 std::advance(last, nCount);
1216 ret.erase(last, ret.end());
1218 std::reverse(ret.begin(), ret.end()); // oldest to newest
1223 Value listaccounts(const Array& params, bool fHelp)
1225 if (fHelp || params.size() > 1)
1226 throw runtime_error(
1227 "listaccounts [minconf=1]\n"
1228 "Returns Object that has account names as keys, account balances as values.");
1231 if (params.size() > 0)
1232 nMinDepth = params[0].get_int();
1234 map<string, int64> mapAccountBalances;
1235 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
1236 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
1238 BOOST_FOREACH(const PAIRTYPE(string, string)& entry, pwalletMain->mapAddressBook) {
1240 if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
1241 mapAccountBalances[entry.second] = 0;
1244 for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
1246 const CWalletTx& wtx = (*it).second;
1247 int64 nGeneratedImmature, nGeneratedMature, nFee;
1248 string strSentAccount;
1249 list<pair<string, int64> > listReceived;
1250 list<pair<string, int64> > listSent;
1251 wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1252 mapAccountBalances[strSentAccount] -= nFee;
1253 BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1254 mapAccountBalances[strSentAccount] -= s.second;
1255 if (wtx.GetDepthInMainChain() >= nMinDepth)
1257 mapAccountBalances[""] += nGeneratedMature;
1258 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1259 if (pwalletMain->mapAddressBook.count(r.first))
1260 mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
1262 mapAccountBalances[""] += r.second;
1267 list<CAccountingEntry> acentries;
1268 CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
1269 BOOST_FOREACH(const CAccountingEntry& entry, acentries)
1270 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1273 BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1274 ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1279 Value gettransaction(const Array& params, bool fHelp)
1281 if (fHelp || params.size() != 1)
1282 throw runtime_error(
1283 "gettransaction <txid>\n"
1284 "Get detailed information about <txid>");
1287 hash.SetHex(params[0].get_str());
1290 CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
1292 if (!pwalletMain->mapWallet.count(hash))
1293 throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
1294 const CWalletTx& wtx = pwalletMain->mapWallet[hash];
1296 int64 nCredit = wtx.GetCredit();
1297 int64 nDebit = wtx.GetDebit();
1298 int64 nNet = nCredit - nDebit;
1299 int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1301 entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1303 entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1305 WalletTxToJSON(pwalletMain->mapWallet[hash], entry);
1308 ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
1309 entry.push_back(Pair("details", details));
1316 Value backupwallet(const Array& params, bool fHelp)
1318 if (fHelp || params.size() != 1)
1319 throw runtime_error(
1320 "backupwallet <destination>\n"
1321 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1323 string strDest = params[0].get_str();
1324 BackupWallet(*pwalletMain, strDest);
1330 Value keypoolrefill(const Array& params, bool fHelp)
1332 if (pwalletMain->IsCrypted() && (fHelp || params.size() > 0))
1333 throw runtime_error(
1335 "Fills the keypool, requires wallet passphrase to be set.");
1336 if (!pwalletMain->IsCrypted() && (fHelp || params.size() > 0))
1337 throw runtime_error(
1339 "Fills the keypool.");
1341 CRITICAL_BLOCK(pwalletMain->cs_vMasterKey)
1343 if (pwalletMain->IsLocked())
1344 throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
1346 pwalletMain->TopUpKeyPool();
1349 if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
1350 throw JSONRPCError(-4, "Error refreshing keypool.");
1356 void ThreadTopUpKeyPool(void* parg)
1358 pwalletMain->TopUpKeyPool();
1361 void ThreadCleanWalletPassphrase(void* parg)
1363 static int64 nWakeTime;
1364 int64 nMyWakeTime = GetTime() + *((int*)parg);
1365 static CCriticalSection cs_nWakeTime;
1369 CRITICAL_BLOCK(cs_nWakeTime)
1371 nWakeTime = nMyWakeTime;
1374 while (GetTime() < nWakeTime)
1375 Sleep(GetTime() - nWakeTime);
1377 CRITICAL_BLOCK(cs_nWakeTime)
1384 CRITICAL_BLOCK(cs_nWakeTime)
1386 if (nWakeTime < nMyWakeTime)
1387 nWakeTime = nMyWakeTime;
1393 pwalletMain->Lock();
1398 Value walletpassphrase(const Array& params, bool fHelp)
1400 if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
1401 throw runtime_error(
1402 "walletpassphrase <passphrase> <timeout>\n"
1403 "Stores the wallet decryption key in memory for <timeout> seconds.");
1406 if (!pwalletMain->IsCrypted())
1407 throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
1409 if (!pwalletMain->IsLocked())
1410 throw JSONRPCError(-17, "Error: Wallet is already unlocked.");
1412 // Note that the walletpassphrase is stored in params[0] which is not mlock()ed
1413 string strWalletPass;
1414 strWalletPass.reserve(100);
1415 mlock(&strWalletPass[0], strWalletPass.capacity());
1416 strWalletPass = params[0].get_str();
1418 CRITICAL_BLOCK(pwalletMain->cs_vMasterKey)
1420 if (strWalletPass.length() > 0)
1422 if (!pwalletMain->Unlock(strWalletPass))
1424 fill(strWalletPass.begin(), strWalletPass.end(), '\0');
1425 munlock(&strWalletPass[0], strWalletPass.capacity());
1426 throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
1428 fill(strWalletPass.begin(), strWalletPass.end(), '\0');
1429 munlock(&strWalletPass[0], strWalletPass.capacity());
1432 throw runtime_error(
1433 "walletpassphrase <passphrase> <timeout>\n"
1434 "Stores the wallet decryption key in memory for <timeout> seconds.");
1437 CreateThread(ThreadTopUpKeyPool, NULL);
1438 int* pnSleepTime = new int(params[1].get_int());
1439 CreateThread(ThreadCleanWalletPassphrase, pnSleepTime);
1445 Value walletpassphrasechange(const Array& params, bool fHelp)
1447 if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
1448 throw runtime_error(
1449 "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
1450 "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
1453 if (!pwalletMain->IsCrypted())
1454 throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
1456 string strOldWalletPass;
1457 strOldWalletPass.reserve(100);
1458 mlock(&strOldWalletPass[0], strOldWalletPass.capacity());
1459 strOldWalletPass = params[0].get_str();
1461 string strNewWalletPass;
1462 strNewWalletPass.reserve(100);
1463 mlock(&strNewWalletPass[0], strNewWalletPass.capacity());
1464 strNewWalletPass = params[1].get_str();
1466 if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
1467 throw runtime_error(
1468 "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
1469 "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
1471 if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
1473 fill(strOldWalletPass.begin(), strOldWalletPass.end(), '\0');
1474 fill(strNewWalletPass.begin(), strNewWalletPass.end(), '\0');
1475 munlock(&strOldWalletPass[0], strOldWalletPass.capacity());
1476 munlock(&strNewWalletPass[0], strNewWalletPass.capacity());
1477 throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
1479 fill(strNewWalletPass.begin(), strNewWalletPass.end(), '\0');
1480 fill(strOldWalletPass.begin(), strOldWalletPass.end(), '\0');
1481 munlock(&strOldWalletPass[0], strOldWalletPass.capacity());
1482 munlock(&strNewWalletPass[0], strNewWalletPass.capacity());
1488 Value encryptwallet(const Array& params, bool fHelp)
1490 if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
1491 throw runtime_error(
1492 "encryptwallet <passphrase>\n"
1493 "Encrypts the wallet with <passphrase>.");
1496 if (pwalletMain->IsCrypted())
1497 throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called.");
1499 string strWalletPass;
1500 strWalletPass.reserve(100);
1501 mlock(&strWalletPass[0], strWalletPass.capacity());
1502 strWalletPass = params[0].get_str();
1504 if (strWalletPass.length() < 1)
1505 throw runtime_error(
1506 "encryptwallet <passphrase>\n"
1507 "Encrypts the wallet with <passphrase>.");
1509 if (!pwalletMain->EncryptWallet(strWalletPass))
1511 fill(strWalletPass.begin(), strWalletPass.end(), '\0');
1512 munlock(&strWalletPass[0], strWalletPass.capacity());
1513 throw JSONRPCError(-16, "Error: Failed to encrypt the wallet.");
1515 fill(strWalletPass.begin(), strWalletPass.end(), '\0');
1516 munlock(&strWalletPass[0], strWalletPass.capacity());
1522 Value validateaddress(const Array& params, bool fHelp)
1524 if (fHelp || params.size() != 1)
1525 throw runtime_error(
1526 "validateaddress <bitcoinaddress>\n"
1527 "Return information about <bitcoinaddress>.");
1529 string strAddress = params[0].get_str();
1531 bool isValid = AddressToHash160(strAddress, hash160);
1534 ret.push_back(Pair("isvalid", isValid));
1537 // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1538 // version of the address:
1539 string currentAddress = Hash160ToAddress(hash160);
1540 ret.push_back(Pair("address", currentAddress));
1541 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1542 CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
1544 if (pwalletMain->mapAddressBook.count(currentAddress))
1545 ret.push_back(Pair("account", pwalletMain->mapAddressBook[currentAddress]));
1552 Value getwork(const Array& params, bool fHelp)
1554 if (fHelp || params.size() > 1)
1555 throw runtime_error(
1557 "If [data] is not specified, returns formatted hash data to work on:\n"
1558 " \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1559 " \"data\" : block data\n"
1560 " \"hash1\" : formatted hash buffer for second hash\n"
1561 " \"target\" : little endian hash target\n"
1562 "If [data] is specified, tries to solve the block and returns true if it was successful.");
1565 throw JSONRPCError(-9, "Bitcoin is not connected!");
1567 if (IsInitialBlockDownload())
1568 throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1570 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1571 static vector<CBlock*> vNewBlock;
1572 static CReserveKey reservekey(pwalletMain);
1574 if (params.size() == 0)
1577 static unsigned int nTransactionsUpdatedLast;
1578 static CBlockIndex* pindexPrev;
1579 static int64 nStart;
1580 static CBlock* pblock;
1581 if (pindexPrev != pindexBest ||
1582 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1584 if (pindexPrev != pindexBest)
1586 // Deallocate old blocks since they're obsolete now
1587 mapNewBlock.clear();
1588 BOOST_FOREACH(CBlock* pblock, vNewBlock)
1592 nTransactionsUpdatedLast = nTransactionsUpdated;
1593 pindexPrev = pindexBest;
1597 pblock = CreateNewBlock(reservekey);
1599 throw JSONRPCError(-7, "Out of memory");
1600 vNewBlock.push_back(pblock);
1604 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1607 // Update nExtraNonce
1608 static unsigned int nExtraNonce = 0;
1609 static int64 nPrevTime = 0;
1610 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1613 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1615 // Prebuild hash buffers
1619 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1621 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1624 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1625 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
1626 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
1627 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
1633 vector<unsigned char> vchData = ParseHex(params[0].get_str());
1634 if (vchData.size() != 128)
1635 throw JSONRPCError(-8, "Invalid parameter");
1636 CBlock* pdata = (CBlock*)&vchData[0];
1639 for (int i = 0; i < 128/4; i++)
1640 ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1643 if (!mapNewBlock.count(pdata->hashMerkleRoot))
1645 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1646 unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1648 pblock->nTime = pdata->nTime;
1649 pblock->nNonce = pdata->nNonce;
1650 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1651 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1653 return CheckWork(pblock, *pwalletMain, reservekey);
1671 pair<string, rpcfn_type> pCallTable[] =
1673 make_pair("help", &help),
1674 make_pair("stop", &stop),
1675 make_pair("getblockcount", &getblockcount),
1676 make_pair("getblocknumber", &getblocknumber),
1677 make_pair("getconnectioncount", &getconnectioncount),
1678 make_pair("getdifficulty", &getdifficulty),
1679 make_pair("getgenerate", &getgenerate),
1680 make_pair("setgenerate", &setgenerate),
1681 make_pair("gethashespersec", &gethashespersec),
1682 make_pair("getinfo", &getinfo),
1683 make_pair("getnewaddress", &getnewaddress),
1684 make_pair("getaccountaddress", &getaccountaddress),
1685 make_pair("setaccount", &setaccount),
1686 make_pair("setlabel", &setaccount), // deprecated
1687 make_pair("getaccount", &getaccount),
1688 make_pair("getlabel", &getaccount), // deprecated
1689 make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1690 make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
1691 make_pair("sendtoaddress", &sendtoaddress),
1692 make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1693 make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1694 make_pair("getreceivedbyaddress", &getreceivedbyaddress),
1695 make_pair("getreceivedbyaccount", &getreceivedbyaccount),
1696 make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
1697 make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1698 make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1699 make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
1700 make_pair("backupwallet", &backupwallet),
1701 make_pair("keypoolrefill", &keypoolrefill),
1702 make_pair("walletpassphrase", &walletpassphrase),
1703 make_pair("walletpassphrasechange", &walletpassphrasechange),
1704 make_pair("encryptwallet", &encryptwallet),
1705 make_pair("validateaddress", &validateaddress),
1706 make_pair("getbalance", &getbalance),
1707 make_pair("move", &movecmd),
1708 make_pair("sendfrom", &sendfrom),
1709 make_pair("sendmany", &sendmany),
1710 make_pair("gettransaction", &gettransaction),
1711 make_pair("listtransactions", &listtransactions),
1712 make_pair("getwork", &getwork),
1713 make_pair("listaccounts", &listaccounts),
1714 make_pair("settxfee", &settxfee),
1716 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1718 string pAllowInSafeMode[] =
1724 "getconnectioncount",
1731 "getaccountaddress",
1734 "getlabel", // deprecated
1735 "getaddressesbyaccount",
1736 "getaddressesbylabel", // deprecated
1743 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1751 // This ain't Apache. We're just using HTTP header for the length field
1752 // and to be compatible with other JSON-RPC implementations.
1755 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1758 s << "POST / HTTP/1.1\r\n"
1759 << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
1760 << "Host: 127.0.0.1\r\n"
1761 << "Content-Type: application/json\r\n"
1762 << "Content-Length: " << strMsg.size() << "\r\n"
1763 << "Accept: application/json\r\n";
1764 BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1765 s << item.first << ": " << item.second << "\r\n";
1766 s << "\r\n" << strMsg;
1771 string rfc1123Time()
1776 struct tm* now_gmt = gmtime(&now);
1777 string locale(setlocale(LC_TIME, NULL));
1778 setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
1779 strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
1780 setlocale(LC_TIME, locale.c_str());
1781 return string(buffer);
1784 static string HTTPReply(int nStatus, const string& strMsg)
1787 return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1789 "Server: bitcoin-json-rpc/%s\r\n"
1790 "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1791 "Content-Type: text/html\r\n"
1792 "Content-Length: 296\r\n"
1794 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1795 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1798 "<TITLE>Error</TITLE>\r\n"
1799 "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1801 "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1802 "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
1804 if (nStatus == 200) strStatus = "OK";
1805 else if (nStatus == 400) strStatus = "Bad Request";
1806 else if (nStatus == 403) strStatus = "Forbidden";
1807 else if (nStatus == 404) strStatus = "Not Found";
1808 else if (nStatus == 500) strStatus = "Internal Server Error";
1810 "HTTP/1.1 %d %s\r\n"
1812 "Connection: close\r\n"
1813 "Content-Length: %d\r\n"
1814 "Content-Type: application/json\r\n"
1815 "Server: bitcoin-json-rpc/%s\r\n"
1820 rfc1123Time().c_str(),
1822 FormatFullVersion().c_str(),
1826 int ReadHTTPStatus(std::basic_istream<char>& stream)
1829 getline(stream, str);
1830 vector<string> vWords;
1831 boost::split(vWords, str, boost::is_any_of(" "));
1832 if (vWords.size() < 2)
1834 return atoi(vWords[1].c_str());
1837 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1843 std::getline(stream, str);
1844 if (str.empty() || str == "\r")
1846 string::size_type nColon = str.find(":");
1847 if (nColon != string::npos)
1849 string strHeader = str.substr(0, nColon);
1850 boost::trim(strHeader);
1851 boost::to_lower(strHeader);
1852 string strValue = str.substr(nColon+1);
1853 boost::trim(strValue);
1854 mapHeadersRet[strHeader] = strValue;
1855 if (strHeader == "content-length")
1856 nLen = atoi(strValue.c_str());
1862 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1864 mapHeadersRet.clear();
1868 int nStatus = ReadHTTPStatus(stream);
1871 int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1872 if (nLen < 0 || nLen > MAX_SIZE)
1878 vector<char> vch(nLen);
1879 stream.read(&vch[0], nLen);
1880 strMessageRet = string(vch.begin(), vch.end());
1886 string EncodeBase64(string s)
1891 b64 = BIO_new(BIO_f_base64());
1892 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1893 bmem = BIO_new(BIO_s_mem());
1894 b64 = BIO_push(b64, bmem);
1895 BIO_write(b64, s.c_str(), s.size());
1897 BIO_get_mem_ptr(b64, &bptr);
1899 string result(bptr->data, bptr->length);
1905 string DecodeBase64(string s)
1909 char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1911 b64 = BIO_new(BIO_f_base64());
1912 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1913 bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1914 bmem = BIO_push(b64, bmem);
1915 BIO_read(bmem, buffer, s.size());
1918 string result(buffer);
1923 bool HTTPAuthorized(map<string, string>& mapHeaders)
1925 string strAuth = mapHeaders["authorization"];
1926 if (strAuth.substr(0,6) != "Basic ")
1928 string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1929 string strUserPass = DecodeBase64(strUserPass64);
1930 string::size_type nColon = strUserPass.find(":");
1931 if (nColon == string::npos)
1933 string strUser = strUserPass.substr(0, nColon);
1934 string strPassword = strUserPass.substr(nColon+1);
1935 return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1939 // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
1940 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1941 // unspecified (HTTP errors and contents of 'error').
1943 // 1.0 spec: http://json-rpc.org/wiki/specification
1944 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1945 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1948 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1951 request.push_back(Pair("method", strMethod));
1952 request.push_back(Pair("params", params));
1953 request.push_back(Pair("id", id));
1954 return write_string(Value(request), false) + "\n";
1957 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1960 if (error.type() != null_type)
1961 reply.push_back(Pair("result", Value::null));
1963 reply.push_back(Pair("result", result));
1964 reply.push_back(Pair("error", error));
1965 reply.push_back(Pair("id", id));
1966 return write_string(Value(reply), false) + "\n";
1969 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1971 // Send error reply from json-rpc error object
1973 int code = find_value(objError, "code").get_int();
1974 if (code == -32600) nStatus = 400;
1975 else if (code == -32601) nStatus = 404;
1976 string strReply = JSONRPCReply(Value::null, objError, id);
1977 stream << HTTPReply(nStatus, strReply) << std::flush;
1980 bool ClientAllowed(const string& strAddress)
1982 if (strAddress == asio::ip::address_v4::loopback().to_string())
1984 const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1985 BOOST_FOREACH(string strAllow, vAllow)
1986 if (WildcardMatch(strAddress, strAllow))
1993 // IOStream device that speaks SSL but can also speak non-SSL
1995 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1997 SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1999 fUseSSL = fUseSSLIn;
2000 fNeedHandshake = fUseSSLIn;
2003 void handshake(ssl::stream_base::handshake_type role)
2005 if (!fNeedHandshake) return;
2006 fNeedHandshake = false;
2007 stream.handshake(role);
2009 std::streamsize read(char* s, std::streamsize n)
2011 handshake(ssl::stream_base::server); // HTTPS servers read first
2012 if (fUseSSL) return stream.read_some(asio::buffer(s, n));
2013 return stream.next_layer().read_some(asio::buffer(s, n));
2015 std::streamsize write(const char* s, std::streamsize n)
2017 handshake(ssl::stream_base::client); // HTTPS clients write first
2018 if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
2019 return asio::write(stream.next_layer(), asio::buffer(s, n));
2021 bool connect(const std::string& server, const std::string& port)
2023 ip::tcp::resolver resolver(stream.get_io_service());
2024 ip::tcp::resolver::query query(server.c_str(), port.c_str());
2025 ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
2026 ip::tcp::resolver::iterator end;
2027 boost::system::error_code error = asio::error::host_not_found;
2028 while (error && endpoint_iterator != end)
2030 stream.lowest_layer().close();
2031 stream.lowest_layer().connect(*endpoint_iterator++, error);
2039 bool fNeedHandshake;
2045 void ThreadRPCServer(void* parg)
2047 IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
2050 vnThreadsRunning[4]++;
2051 ThreadRPCServer2(parg);
2052 vnThreadsRunning[4]--;
2054 catch (std::exception& e) {
2055 vnThreadsRunning[4]--;
2056 PrintException(&e, "ThreadRPCServer()");
2058 vnThreadsRunning[4]--;
2059 PrintException(NULL, "ThreadRPCServer()");
2061 printf("ThreadRPCServer exiting\n");
2064 void ThreadRPCServer2(void* parg)
2066 printf("ThreadRPCServer started\n");
2068 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
2070 string strWhatAmI = "To use bitcoind";
2071 if (mapArgs.count("-server"))
2072 strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
2073 else if (mapArgs.count("-daemon"))
2074 strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
2076 _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
2077 "If the file does not exist, create it with owner-readable-only file permissions.\n"),
2079 GetConfigFile().c_str());
2080 CreateThread(Shutdown, NULL);
2084 bool fUseSSL = GetBoolArg("-rpcssl");
2085 asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
2087 asio::io_service io_service;
2088 ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
2089 ip::tcp::acceptor acceptor(io_service, endpoint);
2091 acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
2094 ssl::context context(io_service, ssl::context::sslv23);
2097 context.set_options(ssl::context::no_sslv2);
2098 filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
2099 if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
2100 if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
2101 else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
2102 filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
2103 if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
2104 if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
2105 else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
2107 string ciphers = GetArg("-rpcsslciphers",
2108 "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
2109 SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
2113 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
2118 // Accept connection
2120 SSLStream sslStream(io_service, context);
2121 SSLIOStreamDevice d(sslStream, fUseSSL);
2122 iostreams::stream<SSLIOStreamDevice> stream(d);
2124 ip::tcp::iostream stream;
2127 ip::tcp::endpoint peer;
2128 vnThreadsRunning[4]--;
2130 acceptor.accept(sslStream.lowest_layer(), peer);
2132 acceptor.accept(*stream.rdbuf(), peer);
2134 vnThreadsRunning[4]++;
2138 // Restrict callers by IP
2139 if (!ClientAllowed(peer.address().to_string()))
2141 // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
2143 stream << HTTPReply(403, "") << std::flush;
2147 map<string, string> mapHeaders;
2150 boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
2151 if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
2154 printf("ThreadRPCServer ReadHTTP timeout\n");
2158 // Check authorization
2159 if (mapHeaders.count("authorization") == 0)
2161 stream << HTTPReply(401, "") << std::flush;
2164 if (!HTTPAuthorized(mapHeaders))
2166 // Deter brute-forcing short passwords
2167 if (mapArgs["-rpcpassword"].size() < 15)
2170 stream << HTTPReply(401, "") << std::flush;
2171 printf("ThreadRPCServer incorrect password attempt\n");
2175 Value id = Value::null;
2180 if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
2181 throw JSONRPCError(-32700, "Parse error");
2182 const Object& request = valRequest.get_obj();
2184 // Parse id now so errors from here on will have the id
2185 id = find_value(request, "id");
2188 Value valMethod = find_value(request, "method");
2189 if (valMethod.type() == null_type)
2190 throw JSONRPCError(-32600, "Missing method");
2191 if (valMethod.type() != str_type)
2192 throw JSONRPCError(-32600, "Method must be a string");
2193 string strMethod = valMethod.get_str();
2194 if (strMethod != "getwork")
2195 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
2198 Value valParams = find_value(request, "params");
2200 if (valParams.type() == array_type)
2201 params = valParams.get_array();
2202 else if (valParams.type() == null_type)
2205 throw JSONRPCError(-32600, "Params must be an array");
2208 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
2209 if (mi == mapCallTable.end())
2210 throw JSONRPCError(-32601, "Method not found");
2212 // Observe safe mode
2213 string strWarning = GetWarnings("rpc");
2214 if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
2215 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
2220 Value result = (*(*mi).second)(params, false);
2223 string strReply = JSONRPCReply(result, Value::null, id);
2224 stream << HTTPReply(200, strReply) << std::flush;
2226 catch (std::exception& e)
2228 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
2231 catch (Object& objError)
2233 ErrorReply(stream, objError, id);
2235 catch (std::exception& e)
2237 ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
2245 Object CallRPC(const string& strMethod, const Array& params)
2247 if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
2248 throw runtime_error(strprintf(
2249 _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
2250 "If the file does not exist, create it with owner-readable-only file permissions."),
2251 GetConfigFile().c_str()));
2253 // Connect to localhost
2254 bool fUseSSL = GetBoolArg("-rpcssl");
2256 asio::io_service io_service;
2257 ssl::context context(io_service, ssl::context::sslv23);
2258 context.set_options(ssl::context::no_sslv2);
2259 SSLStream sslStream(io_service, context);
2260 SSLIOStreamDevice d(sslStream, fUseSSL);
2261 iostreams::stream<SSLIOStreamDevice> stream(d);
2262 if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
2263 throw runtime_error("couldn't connect to server");
2266 throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
2268 ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
2270 throw runtime_error("couldn't connect to server");
2274 // HTTP basic authentication
2275 string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
2276 map<string, string> mapRequestHeaders;
2277 mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
2280 string strRequest = JSONRPCRequest(strMethod, params, 1);
2281 string strPost = HTTPPost(strRequest, mapRequestHeaders);
2282 stream << strPost << std::flush;
2285 map<string, string> mapHeaders;
2287 int nStatus = ReadHTTP(stream, mapHeaders, strReply);
2289 throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
2290 else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
2291 throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
2292 else if (strReply.empty())
2293 throw runtime_error("no response from server");
2297 if (!read_string(strReply, valReply))
2298 throw runtime_error("couldn't parse reply from server");
2299 const Object& reply = valReply.get_obj();
2301 throw runtime_error("expected reply to have result, error and id properties");
2309 template<typename T>
2310 void ConvertTo(Value& value)
2312 if (value.type() == str_type)
2314 // reinterpret string as unquoted json value
2316 if (!read_string(value.get_str(), value2))
2317 throw runtime_error("type mismatch");
2318 value = value2.get_value<T>();
2322 value = value.get_value<T>();
2326 int CommandLineRPC(int argc, char *argv[])
2333 while (argc > 1 && IsSwitchChar(argv[1][0]))
2341 throw runtime_error("too few parameters");
2342 string strMethod = argv[1];
2344 // Parameters default to strings
2346 for (int i = 2; i < argc; i++)
2347 params.push_back(argv[i]);
2348 int n = params.size();
2351 // Special case non-string parameter types
2353 if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
2354 if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2355 if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
2356 if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
2357 if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2358 if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2359 if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2360 if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2361 if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2362 if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
2363 if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2364 if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
2365 if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2366 if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
2367 if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2368 if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
2369 if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2370 if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
2371 if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2372 if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
2373 if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
2374 if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2375 if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2376 if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
2377 if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
2378 if (strMethod == "sendmany" && n > 1)
2380 string s = params[1].get_str();
2382 if (!read_string(s, v) || v.type() != obj_type)
2383 throw runtime_error("type mismatch");
2384 params[1] = v.get_obj();
2386 if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
2389 Object reply = CallRPC(strMethod, params);
2392 const Value& result = find_value(reply, "result");
2393 const Value& error = find_value(reply, "error");
2394 const Value& id = find_value(reply, "id");
2396 if (error.type() != null_type)
2399 strPrint = "error: " + write_string(error, false);
2400 int code = find_value(error.get_obj(), "code").get_int();
2406 if (result.type() == null_type)
2408 else if (result.type() == str_type)
2409 strPrint = result.get_str();
2411 strPrint = write_string(result, true);
2414 catch (std::exception& e)
2416 strPrint = string("error: ") + e.what();
2421 PrintException(NULL, "CommandLineRPC()");
2426 #if defined(__WXMSW__) && defined(GUI)
2427 // Windows GUI apps can't print to command line,
2428 // so settle for a message box yuck
2429 MyMessageBox(strPrint, "Bitcoin", wxOK);
2431 fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
2441 int main(int argc, char *argv[])
2444 // Turn off microsoft heap dump noise
2445 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2446 _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
2448 setbuf(stdin, NULL);
2449 setbuf(stdout, NULL);
2450 setbuf(stderr, NULL);
2454 if (argc >= 2 && string(argv[1]) == "-server")
2456 printf("server ready\n");
2457 ThreadRPCServer(NULL);
2461 return CommandLineRPC(argc, argv);
2464 catch (std::exception& e) {
2465 PrintException(&e, "main()");
2467 PrintException(NULL, "main()");