Only include db.h when we have to.
[novacoin.git] / src / rpc.cpp
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.
4
5 #include "headers.h"
6 #include "cryptopp/sha.h"
7 #include "db.h"
8 #undef printf
9 #include <boost/asio.hpp>
10 #include <boost/iostreams/concepts.hpp>
11 #include <boost/iostreams/stream.hpp>
12 #ifdef USE_SSL
13 #include <boost/asio/ssl.hpp> 
14 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
15 #endif
16 #include "json/json_spirit_reader_template.h"
17 #include "json/json_spirit_writer_template.h"
18 #include "json/json_spirit_utils.h"
19 #define printf OutputDebugStringF
20 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
21 // precompiled in headers.h.  The problem might be when the pch file goes over
22 // a certain size around 145MB.  If we need access to json_spirit outside this
23 // file, we could use the compiled json_spirit option.
24
25 using namespace std;
26 using namespace boost;
27 using namespace boost::asio;
28 using namespace json_spirit;
29
30 void ThreadRPCServer2(void* parg);
31 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
32 extern map<string, rpcfn_type> mapCallTable;
33
34
35 Object JSONRPCError(int code, const string& message)
36 {
37     Object error;
38     error.push_back(Pair("code", code));
39     error.push_back(Pair("message", message));
40     return error;
41 }
42
43
44 void PrintConsole(const char* format, ...)
45 {
46     char buffer[50000];
47     int limit = sizeof(buffer);
48     va_list arg_ptr;
49     va_start(arg_ptr, format);
50     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
51     va_end(arg_ptr);
52     if (ret < 0 || ret >= limit)
53     {
54         ret = limit - 1;
55         buffer[limit-1] = 0;
56     }
57     printf("%s", buffer);
58 #if defined(__WXMSW__) && defined(GUI)
59     MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
60 #else
61     fprintf(stdout, "%s", buffer);
62 #endif
63 }
64
65
66 int64 AmountFromValue(const Value& value)
67 {
68     double dAmount = value.get_real();
69     if (dAmount <= 0.0 || dAmount > 21000000.0)
70         throw JSONRPCError(-3, "Invalid amount");
71     int64 nAmount = roundint64(dAmount * COIN);
72     if (!MoneyRange(nAmount))
73         throw JSONRPCError(-3, "Invalid amount");
74     return nAmount;
75 }
76
77 Value ValueFromAmount(int64 amount)
78 {
79     return (double)amount / (double)COIN;
80 }
81
82 void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
83 {
84     entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
85     entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
86     entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
87     BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
88         entry.push_back(Pair(item.first, item.second));
89 }
90
91 string AccountFromValue(const Value& value)
92 {
93     string strAccount = value.get_str();
94     if (strAccount == "*")
95         throw JSONRPCError(-11, "Invalid account name");
96     return strAccount;
97 }
98
99
100
101 ///
102 /// Note: This interface may still be subject to change.
103 ///
104
105
106 Value help(const Array& params, bool fHelp)
107 {
108     if (fHelp || params.size() > 1)
109         throw runtime_error(
110             "help [command]\n"
111             "List commands, or get help for a command.");
112
113     string strCommand;
114     if (params.size() > 0)
115         strCommand = params[0].get_str();
116
117     string strRet;
118     set<rpcfn_type> setDone;
119     for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
120     {
121         string strMethod = (*mi).first;
122         // We already filter duplicates, but these deprecated screw up the sort order
123         if (strMethod == "getamountreceived" ||
124             strMethod == "getallreceived" ||
125             (strMethod.find("label") != string::npos))
126             continue;
127         if (strCommand != "" && strMethod != strCommand)
128             continue;
129         try
130         {
131             Array params;
132             rpcfn_type pfn = (*mi).second;
133             if (setDone.insert(pfn).second)
134                 (*pfn)(params, true);
135         }
136         catch (std::exception& e)
137         {
138             // Help text is returned in an exception
139             string strHelp = string(e.what());
140             if (strCommand == "")
141                 if (strHelp.find('\n') != -1)
142                     strHelp = strHelp.substr(0, strHelp.find('\n'));
143             strRet += strHelp + "\n";
144         }
145     }
146     if (strRet == "")
147         strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
148     strRet = strRet.substr(0,strRet.size()-1);
149     return strRet;
150 }
151
152
153 Value stop(const Array& params, bool fHelp)
154 {
155     if (fHelp || params.size() != 0)
156         throw runtime_error(
157             "stop\n"
158             "Stop bitcoin server.");
159
160     // Shutdown will take long enough that the response should get back
161     CreateThread(Shutdown, NULL);
162     return "bitcoin server stopping";
163 }
164
165
166 Value getblockcount(const Array& params, bool fHelp)
167 {
168     if (fHelp || params.size() != 0)
169         throw runtime_error(
170             "getblockcount\n"
171             "Returns the number of blocks in the longest block chain.");
172
173     return nBestHeight;
174 }
175
176
177 Value getblocknumber(const Array& params, bool fHelp)
178 {
179     if (fHelp || params.size() != 0)
180         throw runtime_error(
181             "getblocknumber\n"
182             "Returns the block number of the latest block in the longest block chain.");
183
184     return nBestHeight;
185 }
186
187
188 Value getconnectioncount(const Array& params, bool fHelp)
189 {
190     if (fHelp || params.size() != 0)
191         throw runtime_error(
192             "getconnectioncount\n"
193             "Returns the number of connections to other nodes.");
194
195     return (int)vNodes.size();
196 }
197
198
199 double GetDifficulty()
200 {
201     // Floating point number that is a multiple of the minimum difficulty,
202     // minimum difficulty = 1.0.
203     if (pindexBest == NULL)
204         return 1.0;
205     int nShift = 256 - 32 - 31; // to fit in a uint
206     double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
207     double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
208     return dMinimum / dCurrently;
209 }
210
211 Value getdifficulty(const Array& params, bool fHelp)
212 {
213     if (fHelp || params.size() != 0)
214         throw runtime_error(
215             "getdifficulty\n"
216             "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
217
218     return GetDifficulty();
219 }
220
221
222 Value getgenerate(const Array& params, bool fHelp)
223 {
224     if (fHelp || params.size() != 0)
225         throw runtime_error(
226             "getgenerate\n"
227             "Returns true or false.");
228
229     return (bool)fGenerateBitcoins;
230 }
231
232
233 Value setgenerate(const Array& params, bool fHelp)
234 {
235     if (fHelp || params.size() < 1 || params.size() > 2)
236         throw runtime_error(
237             "setgenerate <generate> [genproclimit]\n"
238             "<generate> is true or false to turn generation on or off.\n"
239             "Generation is limited to [genproclimit] processors, -1 is unlimited.");
240
241     bool fGenerate = true;
242     if (params.size() > 0)
243         fGenerate = params[0].get_bool();
244
245     if (params.size() > 1)
246     {
247         int nGenProcLimit = params[1].get_int();
248         fLimitProcessors = (nGenProcLimit != -1);
249         CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
250         if (nGenProcLimit != -1)
251             CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
252         if (nGenProcLimit == 0)
253             fGenerate = false;
254     }
255
256     GenerateBitcoins(fGenerate);
257     return Value::null;
258 }
259
260
261 Value gethashespersec(const Array& params, bool fHelp)
262 {
263     if (fHelp || params.size() != 0)
264         throw runtime_error(
265             "gethashespersec\n"
266             "Returns a recent hashes per second performance measurement while generating.");
267
268     if (GetTimeMillis() - nHPSTimerStart > 8000)
269         return (boost::int64_t)0;
270     return (boost::int64_t)dHashesPerSec;
271 }
272
273
274 Value getinfo(const Array& params, bool fHelp)
275 {
276     if (fHelp || params.size() != 0)
277         throw runtime_error(
278             "getinfo\n"
279             "Returns an object containing various state info.");
280
281     Object obj;
282     obj.push_back(Pair("version",       (int)VERSION));
283     obj.push_back(Pair("balance",       ValueFromAmount(GetBalance())));
284     obj.push_back(Pair("blocks",        (int)nBestHeight));
285     obj.push_back(Pair("connections",   (int)vNodes.size()));
286     obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));
287     obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));
288     obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));
289     obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
290     obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));
291     obj.push_back(Pair("testnet",       fTestNet));
292     obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
293     obj.push_back(Pair("paytxfee",      ValueFromAmount(nTransactionFee)));
294     obj.push_back(Pair("errors",        GetWarnings("statusbar")));
295     return obj;
296 }
297
298
299 Value getnewaddress(const Array& params, bool fHelp)
300 {
301     if (fHelp || params.size() > 1)
302         throw runtime_error(
303             "getnewaddress [account]\n"
304             "Returns a new bitcoin address for receiving payments.  "
305             "If [account] is specified (recommended), it is added to the address book "
306             "so payments received with the address will be credited to [account].");
307
308     // Parse the account first so we don't generate a key if there's an error
309     string strAccount;
310     if (params.size() > 0)
311         strAccount = AccountFromValue(params[0]);
312
313     // Generate a new key that is added to wallet
314     string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
315
316     SetAddressBookName(strAddress, strAccount);
317     return strAddress;
318 }
319
320
321 // requires cs_main, cs_mapWallet locks
322 string GetAccountAddress(string strAccount, bool bForceNew=false)
323 {
324     string strAddress;
325
326     CWalletDB walletdb;
327     walletdb.TxnBegin();
328
329     CAccount account;
330     walletdb.ReadAccount(strAccount, account);
331
332     // Check if the current key has been used
333     if (!account.vchPubKey.empty())
334     {
335         CScript scriptPubKey;
336         scriptPubKey.SetBitcoinAddress(account.vchPubKey);
337         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
338              it != mapWallet.end() && !account.vchPubKey.empty();
339              ++it)
340         {
341             const CWalletTx& wtx = (*it).second;
342             BOOST_FOREACH(const CTxOut& txout, wtx.vout)
343                 if (txout.scriptPubKey == scriptPubKey)
344                     account.vchPubKey.clear();
345         }
346     }
347
348     // Generate a new key
349     if (account.vchPubKey.empty() || bForceNew)
350     {
351         account.vchPubKey = GetKeyFromKeyPool();
352         string strAddress = PubKeyToAddress(account.vchPubKey);
353         SetAddressBookName(strAddress, strAccount);
354         walletdb.WriteAccount(strAccount, account);
355     }
356
357     walletdb.TxnCommit();
358     strAddress = PubKeyToAddress(account.vchPubKey);
359
360     return strAddress;
361 }
362
363 Value getaccountaddress(const Array& params, bool fHelp)
364 {
365     if (fHelp || params.size() != 1)
366         throw runtime_error(
367             "getaccountaddress <account>\n"
368             "Returns the current bitcoin address for receiving payments to this account.");
369
370     // Parse the account first so we don't generate a key if there's an error
371     string strAccount = AccountFromValue(params[0]);
372
373     Value ret;
374
375     CRITICAL_BLOCK(cs_main)
376     CRITICAL_BLOCK(cs_mapWallet)
377     {
378         ret = GetAccountAddress(strAccount);
379     }
380
381     return ret;
382 }
383
384
385
386 Value setaccount(const Array& params, bool fHelp)
387 {
388     if (fHelp || params.size() < 1 || params.size() > 2)
389         throw runtime_error(
390             "setaccount <bitcoinaddress> <account>\n"
391             "Sets the account associated with the given address.");
392
393     string strAddress = params[0].get_str();
394     uint160 hash160;
395     bool isValid = AddressToHash160(strAddress, hash160);
396     if (!isValid)
397         throw JSONRPCError(-5, "Invalid bitcoin address");
398
399
400     string strAccount;
401     if (params.size() > 1)
402         strAccount = AccountFromValue(params[1]);
403
404     // Detect when changing the account of an address that is the 'unused current key' of another account:
405     CRITICAL_BLOCK(cs_main)
406     CRITICAL_BLOCK(cs_mapWallet)
407     CRITICAL_BLOCK(cs_mapAddressBook)
408     {
409         if (mapAddressBook.count(strAddress))
410         {
411             string strOldAccount = mapAddressBook[strAddress];
412             if (strAddress == GetAccountAddress(strOldAccount))
413                 GetAccountAddress(strOldAccount, true);
414         }
415     }
416
417     SetAddressBookName(strAddress, strAccount);
418     return Value::null;
419 }
420
421
422 Value getaccount(const Array& params, bool fHelp)
423 {
424     if (fHelp || params.size() != 1)
425         throw runtime_error(
426             "getaccount <bitcoinaddress>\n"
427             "Returns the account associated with the given address.");
428
429     string strAddress = params[0].get_str();
430
431     string strAccount;
432     CRITICAL_BLOCK(cs_mapAddressBook)
433     {
434         map<string, string>::iterator mi = mapAddressBook.find(strAddress);
435         if (mi != mapAddressBook.end() && !(*mi).second.empty())
436             strAccount = (*mi).second;
437     }
438     return strAccount;
439 }
440
441
442 Value getaddressesbyaccount(const Array& params, bool fHelp)
443 {
444     if (fHelp || params.size() != 1)
445         throw runtime_error(
446             "getaddressesbyaccount <account>\n"
447             "Returns the list of addresses for the given account.");
448
449     string strAccount = AccountFromValue(params[0]);
450
451     // Find all addresses that have the given account
452     Array ret;
453     CRITICAL_BLOCK(cs_mapAddressBook)
454     {
455         BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
456         {
457             const string& strAddress = item.first;
458             const string& strName = item.second;
459             if (strName == strAccount)
460             {
461                 // We're only adding valid bitcoin addresses and not ip addresses
462                 CScript scriptPubKey;
463                 if (scriptPubKey.SetBitcoinAddress(strAddress))
464                     ret.push_back(strAddress);
465             }
466         }
467     }
468     return ret;
469 }
470
471 Value settxfee(const Array& params, bool fHelp)
472 {
473     if (fHelp || params.size() < 1 || params.size() > 1)
474         throw runtime_error(
475             "settxfee <amount>\n"
476             "<amount> is a real and is rounded to the nearest 0.00000001");
477
478     // Amount
479     int64 nAmount = 0;
480     if (params[0].get_real() != 0.0)
481         nAmount = AmountFromValue(params[0]);        // rejects 0.0 amounts
482
483     nTransactionFee = nAmount;
484     return true;
485 }
486
487 Value sendtoaddress(const Array& params, bool fHelp)
488 {
489     if (fHelp || params.size() < 2 || params.size() > 4)
490         throw runtime_error(
491             "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
492             "<amount> is a real and is rounded to the nearest 0.00000001");
493
494     string strAddress = params[0].get_str();
495
496     // Amount
497     int64 nAmount = AmountFromValue(params[1]);
498
499     // Wallet comments
500     CWalletTx wtx;
501     if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
502         wtx.mapValue["comment"] = params[2].get_str();
503     if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
504         wtx.mapValue["to"]      = params[3].get_str();
505
506     CRITICAL_BLOCK(cs_main)
507     {
508         string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
509         if (strError != "")
510             throw JSONRPCError(-4, strError);
511     }
512
513     return wtx.GetHash().GetHex();
514 }
515
516
517 Value getreceivedbyaddress(const Array& params, bool fHelp)
518 {
519     if (fHelp || params.size() < 1 || params.size() > 2)
520         throw runtime_error(
521             "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
522             "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
523
524     // Bitcoin address
525     string strAddress = params[0].get_str();
526     CScript scriptPubKey;
527     if (!scriptPubKey.SetBitcoinAddress(strAddress))
528         throw JSONRPCError(-5, "Invalid bitcoin address");
529     if (!IsMine(scriptPubKey))
530         return (double)0.0;
531
532     // Minimum confirmations
533     int nMinDepth = 1;
534     if (params.size() > 1)
535         nMinDepth = params[1].get_int();
536
537     // Tally
538     int64 nAmount = 0;
539     CRITICAL_BLOCK(cs_mapWallet)
540     {
541         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
542         {
543             const CWalletTx& wtx = (*it).second;
544             if (wtx.IsCoinBase() || !wtx.IsFinal())
545                 continue;
546
547             BOOST_FOREACH(const CTxOut& txout, wtx.vout)
548                 if (txout.scriptPubKey == scriptPubKey)
549                     if (wtx.GetDepthInMainChain() >= nMinDepth)
550                         nAmount += txout.nValue;
551         }
552     }
553
554     return  ValueFromAmount(nAmount);
555 }
556
557
558 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
559 {
560     CRITICAL_BLOCK(cs_mapAddressBook)
561     {
562         BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
563         {
564             const string& strAddress = item.first;
565             const string& strName = item.second;
566             if (strName == strAccount)
567             {
568                 // We're only counting our own valid bitcoin addresses and not ip addresses
569                 CScript scriptPubKey;
570                 if (scriptPubKey.SetBitcoinAddress(strAddress))
571                     if (IsMine(scriptPubKey))
572                         setPubKey.insert(scriptPubKey);
573             }
574         }
575     }
576 }
577
578
579 Value getreceivedbyaccount(const Array& params, bool fHelp)
580 {
581     if (fHelp || params.size() < 1 || params.size() > 2)
582         throw runtime_error(
583             "getreceivedbyaccount <account> [minconf=1]\n"
584             "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
585
586     // Minimum confirmations
587     int nMinDepth = 1;
588     if (params.size() > 1)
589         nMinDepth = params[1].get_int();
590
591     // Get the set of pub keys that have the label
592     string strAccount = AccountFromValue(params[0]);
593     set<CScript> setPubKey;
594     GetAccountPubKeys(strAccount, setPubKey);
595
596     // Tally
597     int64 nAmount = 0;
598     CRITICAL_BLOCK(cs_mapWallet)
599     {
600         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
601         {
602             const CWalletTx& wtx = (*it).second;
603             if (wtx.IsCoinBase() || !wtx.IsFinal())
604                 continue;
605
606             BOOST_FOREACH(const CTxOut& txout, wtx.vout)
607                 if (setPubKey.count(txout.scriptPubKey))
608                     if (wtx.GetDepthInMainChain() >= nMinDepth)
609                         nAmount += txout.nValue;
610         }
611     }
612
613     return (double)nAmount / (double)COIN;
614 }
615
616
617 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
618 {
619     int64 nBalance = 0;
620     CRITICAL_BLOCK(cs_mapWallet)
621     {
622         // Tally wallet transactions
623         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
624         {
625             const CWalletTx& wtx = (*it).second;
626             if (!wtx.IsFinal())
627                 continue;
628
629             int64 nGenerated, nReceived, nSent, nFee;
630             wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
631
632             if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
633                 nBalance += nReceived;
634             nBalance += nGenerated - nSent - nFee;
635         }
636
637         // Tally internal accounting entries
638         nBalance += walletdb.GetAccountCreditDebit(strAccount);
639     }
640
641     return nBalance;
642 }
643
644 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
645 {
646     CWalletDB walletdb;
647     return GetAccountBalance(walletdb, strAccount, nMinDepth);
648 }
649
650
651 Value getbalance(const Array& params, bool fHelp)
652 {
653     if (fHelp || params.size() < 0 || params.size() > 2)
654         throw runtime_error(
655             "getbalance [account] [minconf=1]\n"
656             "If [account] is not specified, returns the server's total available balance.\n"
657             "If [account] is specified, returns the balance in the account.");
658
659     if (params.size() == 0)
660         return  ValueFromAmount(GetBalance());
661
662     int nMinDepth = 1;
663     if (params.size() > 1)
664         nMinDepth = params[1].get_int();
665
666     if (params[0].get_str() == "*") {
667         // Calculate total balance a different way from GetBalance()
668         // (GetBalance() sums up all unspent TxOuts)
669         // getbalance and getbalance '*' should always return the same number.
670         int64 nBalance = 0;
671         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
672         {
673             const CWalletTx& wtx = (*it).second;
674             if (!wtx.IsFinal())
675                 continue;
676
677             int64 allGeneratedImmature, allGeneratedMature, allFee;
678             allGeneratedImmature = allGeneratedMature = allFee = 0;
679             string strSentAccount;
680             list<pair<string, int64> > listReceived;
681             list<pair<string, int64> > listSent;
682             wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
683             if (wtx.GetDepthInMainChain() >= nMinDepth)
684                 BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
685                     nBalance += r.second;
686             BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
687                 nBalance -= r.second;
688             nBalance -= allFee;
689             nBalance += allGeneratedMature;
690         }
691         return  ValueFromAmount(nBalance);
692     }
693
694     string strAccount = AccountFromValue(params[0]);
695
696     int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
697
698     return ValueFromAmount(nBalance);
699 }
700
701
702 Value movecmd(const Array& params, bool fHelp)
703 {
704     if (fHelp || params.size() < 3 || params.size() > 5)
705         throw runtime_error(
706             "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
707             "Move from one account in your wallet to another.");
708
709     string strFrom = AccountFromValue(params[0]);
710     string strTo = AccountFromValue(params[1]);
711     int64 nAmount = AmountFromValue(params[2]);
712     int nMinDepth = 1;
713     if (params.size() > 3)
714         nMinDepth = params[3].get_int();
715     string strComment;
716     if (params.size() > 4)
717         strComment = params[4].get_str();
718
719     CRITICAL_BLOCK(cs_mapWallet)
720     {
721         CWalletDB walletdb;
722         walletdb.TxnBegin();
723
724         int64 nNow = GetAdjustedTime();
725
726         // Debit
727         CAccountingEntry debit;
728         debit.strAccount = strFrom;
729         debit.nCreditDebit = -nAmount;
730         debit.nTime = nNow;
731         debit.strOtherAccount = strTo;
732         debit.strComment = strComment;
733         walletdb.WriteAccountingEntry(debit);
734
735         // Credit
736         CAccountingEntry credit;
737         credit.strAccount = strTo;
738         credit.nCreditDebit = nAmount;
739         credit.nTime = nNow;
740         credit.strOtherAccount = strFrom;
741         credit.strComment = strComment;
742         walletdb.WriteAccountingEntry(credit);
743
744         walletdb.TxnCommit();
745     }
746     return true;
747 }
748
749
750 Value sendfrom(const Array& params, bool fHelp)
751 {
752     if (fHelp || params.size() < 3 || params.size() > 6)
753         throw runtime_error(
754             "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
755             "<amount> is a real and is rounded to the nearest 0.00000001");
756
757     string strAccount = AccountFromValue(params[0]);
758     string strAddress = params[1].get_str();
759     int64 nAmount = AmountFromValue(params[2]);
760     int nMinDepth = 1;
761     if (params.size() > 3)
762         nMinDepth = params[3].get_int();
763
764     CWalletTx wtx;
765     wtx.strFromAccount = strAccount;
766     if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
767         wtx.mapValue["comment"] = params[4].get_str();
768     if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
769         wtx.mapValue["to"]      = params[5].get_str();
770
771     CRITICAL_BLOCK(cs_main)
772     CRITICAL_BLOCK(cs_mapWallet)
773     {
774         // Check funds
775         int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
776         if (nAmount > nBalance)
777             throw JSONRPCError(-6, "Account has insufficient funds");
778
779         // Send
780         string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
781         if (strError != "")
782             throw JSONRPCError(-4, strError);
783     }
784
785     return wtx.GetHash().GetHex();
786 }
787
788 Value sendmany(const Array& params, bool fHelp)
789 {
790     if (fHelp || params.size() < 2 || params.size() > 4)
791         throw runtime_error(
792             "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
793             "amounts are double-precision floating point numbers");
794
795     string strAccount = AccountFromValue(params[0]);
796     Object sendTo = params[1].get_obj();
797     int nMinDepth = 1;
798     if (params.size() > 2)
799         nMinDepth = params[2].get_int();
800
801     CWalletTx wtx;
802     wtx.strFromAccount = strAccount;
803     if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
804         wtx.mapValue["comment"] = params[3].get_str();
805
806     set<string> setAddress;
807     vector<pair<CScript, int64> > vecSend;
808
809     int64 totalAmount = 0;
810     BOOST_FOREACH(const Pair& s, sendTo)
811     {
812         uint160 hash160;
813         string strAddress = s.name_;
814
815         if (setAddress.count(strAddress))
816             throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
817         setAddress.insert(strAddress);
818
819         CScript scriptPubKey;
820         if (!scriptPubKey.SetBitcoinAddress(strAddress))
821             throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
822         int64 nAmount = AmountFromValue(s.value_); 
823         totalAmount += nAmount;
824
825         vecSend.push_back(make_pair(scriptPubKey, nAmount));
826     }
827
828     CRITICAL_BLOCK(cs_main)
829     CRITICAL_BLOCK(cs_mapWallet)
830     {
831         // Check funds
832         int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
833         if (totalAmount > nBalance)
834             throw JSONRPCError(-6, "Account has insufficient funds");
835
836         // Send
837         CReserveKey keyChange;
838         int64 nFeeRequired = 0;
839         bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
840         if (!fCreated)
841         {
842             if (totalAmount + nFeeRequired > GetBalance())
843                 throw JSONRPCError(-6, "Insufficient funds");
844             throw JSONRPCError(-4, "Transaction creation failed");
845         }
846         if (!CommitTransaction(wtx, keyChange))
847             throw JSONRPCError(-4, "Transaction commit failed");
848     }
849
850     return wtx.GetHash().GetHex();
851 }
852
853
854 struct tallyitem
855 {
856     int64 nAmount;
857     int nConf;
858     tallyitem()
859     {
860         nAmount = 0;
861         nConf = INT_MAX;
862     }
863 };
864
865 Value ListReceived(const Array& params, bool fByAccounts)
866 {
867     // Minimum confirmations
868     int nMinDepth = 1;
869     if (params.size() > 0)
870         nMinDepth = params[0].get_int();
871
872     // Whether to include empty accounts
873     bool fIncludeEmpty = false;
874     if (params.size() > 1)
875         fIncludeEmpty = params[1].get_bool();
876
877     // Tally
878     map<uint160, tallyitem> mapTally;
879     CRITICAL_BLOCK(cs_mapWallet)
880     {
881         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
882         {
883             const CWalletTx& wtx = (*it).second;
884             if (wtx.IsCoinBase() || !wtx.IsFinal())
885                 continue;
886
887             int nDepth = wtx.GetDepthInMainChain();
888             if (nDepth < nMinDepth)
889                 continue;
890
891             BOOST_FOREACH(const CTxOut& txout, wtx.vout)
892             {
893                 // Only counting our own bitcoin addresses and not ip addresses
894                 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
895                 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
896                     continue;
897
898                 tallyitem& item = mapTally[hash160];
899                 item.nAmount += txout.nValue;
900                 item.nConf = min(item.nConf, nDepth);
901             }
902         }
903     }
904
905     // Reply
906     Array ret;
907     map<string, tallyitem> mapAccountTally;
908     CRITICAL_BLOCK(cs_mapAddressBook)
909     {
910         BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
911         {
912             const string& strAddress = item.first;
913             const string& strAccount = item.second;
914             uint160 hash160;
915             if (!AddressToHash160(strAddress, hash160))
916                 continue;
917             map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
918             if (it == mapTally.end() && !fIncludeEmpty)
919                 continue;
920
921             int64 nAmount = 0;
922             int nConf = INT_MAX;
923             if (it != mapTally.end())
924             {
925                 nAmount = (*it).second.nAmount;
926                 nConf = (*it).second.nConf;
927             }
928
929             if (fByAccounts)
930             {
931                 tallyitem& item = mapAccountTally[strAccount];
932                 item.nAmount += nAmount;
933                 item.nConf = min(item.nConf, nConf);
934             }
935             else
936             {
937                 Object obj;
938                 obj.push_back(Pair("address",       strAddress));
939                 obj.push_back(Pair("account",       strAccount));
940                 obj.push_back(Pair("label",         strAccount)); // deprecated
941                 obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
942                 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
943                 ret.push_back(obj);
944             }
945         }
946     }
947
948     if (fByAccounts)
949     {
950         for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
951         {
952             int64 nAmount = (*it).second.nAmount;
953             int nConf = (*it).second.nConf;
954             Object obj;
955             obj.push_back(Pair("account",       (*it).first));
956             obj.push_back(Pair("label",         (*it).first)); // deprecated
957             obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
958             obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
959             ret.push_back(obj);
960         }
961     }
962
963     return ret;
964 }
965
966 Value listreceivedbyaddress(const Array& params, bool fHelp)
967 {
968     if (fHelp || params.size() > 2)
969         throw runtime_error(
970             "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
971             "[minconf] is the minimum number of confirmations before payments are included.\n"
972             "[includeempty] whether to include addresses that haven't received any payments.\n"
973             "Returns an array of objects containing:\n"
974             "  \"address\" : receiving address\n"
975             "  \"account\" : the account of the receiving address\n"
976             "  \"amount\" : total amount received by the address\n"
977             "  \"confirmations\" : number of confirmations of the most recent transaction included");
978
979     return ListReceived(params, false);
980 }
981
982 Value listreceivedbyaccount(const Array& params, bool fHelp)
983 {
984     if (fHelp || params.size() > 2)
985         throw runtime_error(
986             "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
987             "[minconf] is the minimum number of confirmations before payments are included.\n"
988             "[includeempty] whether to include accounts that haven't received any payments.\n"
989             "Returns an array of objects containing:\n"
990             "  \"account\" : the account of the receiving addresses\n"
991             "  \"amount\" : total amount received by addresses with this account\n"
992             "  \"confirmations\" : number of confirmations of the most recent transaction included");
993
994     return ListReceived(params, true);
995 }
996
997 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
998 {
999     int64 nGeneratedImmature, nGeneratedMature, nFee;
1000     string strSentAccount;
1001     list<pair<string, int64> > listReceived;
1002     list<pair<string, int64> > listSent;
1003     wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1004
1005     bool fAllAccounts = (strAccount == string("*"));
1006
1007     // Generated blocks assigned to account ""
1008     if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
1009     {
1010         Object entry;
1011         entry.push_back(Pair("account", string("")));
1012         if (nGeneratedImmature)
1013         {
1014             entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
1015             entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
1016         }
1017         else
1018         {
1019             entry.push_back(Pair("category", "generate"));
1020             entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
1021         }
1022         if (fLong)
1023             WalletTxToJSON(wtx, entry);
1024         ret.push_back(entry);
1025     }
1026
1027     // Sent
1028     if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
1029     {
1030         BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1031         {
1032             Object entry;
1033             entry.push_back(Pair("account", strSentAccount));
1034             entry.push_back(Pair("address", s.first));
1035             entry.push_back(Pair("category", "send"));
1036             entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
1037             entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
1038             if (fLong)
1039                 WalletTxToJSON(wtx, entry);
1040             ret.push_back(entry);
1041         }
1042     }
1043
1044     // Received
1045     if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1046         CRITICAL_BLOCK(cs_mapAddressBook)
1047         {
1048             BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1049             {
1050                 string account;
1051                 if (mapAddressBook.count(r.first))
1052                     account = mapAddressBook[r.first];
1053                 if (fAllAccounts || (account == strAccount))
1054                 {
1055                     Object entry;
1056                     entry.push_back(Pair("account", account));
1057                     entry.push_back(Pair("address", r.first));
1058                     entry.push_back(Pair("category", "receive"));
1059                     entry.push_back(Pair("amount", ValueFromAmount(r.second)));
1060                     if (fLong)
1061                         WalletTxToJSON(wtx, entry);
1062                     ret.push_back(entry);
1063                 }
1064             }
1065         }
1066
1067 }
1068
1069 void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
1070 {
1071     bool fAllAccounts = (strAccount == string("*"));
1072
1073     if (fAllAccounts || acentry.strAccount == strAccount)
1074     {
1075         Object entry;
1076         entry.push_back(Pair("account", acentry.strAccount));
1077         entry.push_back(Pair("category", "move"));
1078         entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
1079         entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
1080         entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
1081         entry.push_back(Pair("comment", acentry.strComment));
1082         ret.push_back(entry);
1083     }
1084 }
1085
1086 Value listtransactions(const Array& params, bool fHelp)
1087 {
1088     if (fHelp || params.size() > 3)
1089         throw runtime_error(
1090             "listtransactions [account] [count=10] [from=0]\n"
1091             "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
1092
1093     string strAccount = "*";
1094     if (params.size() > 0)
1095         strAccount = params[0].get_str();
1096     int nCount = 10;
1097     if (params.size() > 1)
1098         nCount = params[1].get_int();
1099     int nFrom = 0;
1100     if (params.size() > 2)
1101         nFrom = params[2].get_int();
1102
1103     Array ret;
1104     CWalletDB walletdb;
1105
1106     CRITICAL_BLOCK(cs_mapWallet)
1107     {
1108         // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
1109         typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
1110         typedef multimap<int64, TxPair > TxItems;
1111         TxItems txByTime;
1112
1113         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1114         {
1115             CWalletTx* wtx = &((*it).second);
1116             txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
1117         }
1118         list<CAccountingEntry> acentries;
1119         walletdb.ListAccountCreditDebit(strAccount, acentries);
1120         BOOST_FOREACH(CAccountingEntry& entry, acentries)
1121         {
1122             txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
1123         }
1124
1125         // Now: iterate backwards until we have nCount items to return:
1126         TxItems::reverse_iterator it = txByTime.rbegin();
1127         for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
1128         {
1129             CWalletTx *const pwtx = (*it).second.first;
1130             if (pwtx != 0)
1131                 ListTransactions(*pwtx, strAccount, 0, true, ret);
1132             CAccountingEntry *const pacentry = (*it).second.second;
1133             if (pacentry != 0)
1134                 AcentryToJSON(*pacentry, strAccount, ret);
1135
1136             if (ret.size() >= nCount) break;
1137         }
1138         // ret is now newest to oldest
1139     }
1140     
1141     // Make sure we return only last nCount items (sends-to-self might give us an extra):
1142     if (ret.size() > nCount)
1143     {
1144         Array::iterator last = ret.begin();
1145         std::advance(last, nCount);
1146         ret.erase(last, ret.end());
1147     }
1148     std::reverse(ret.begin(), ret.end()); // oldest to newest
1149
1150     return ret;
1151 }
1152
1153 Value listaccounts(const Array& params, bool fHelp)
1154 {
1155     if (fHelp || params.size() > 1)
1156         throw runtime_error(
1157             "listaccounts [minconf=1]\n"
1158             "Returns Object that has account names as keys, account balances as values.");
1159
1160     int nMinDepth = 1;
1161     if (params.size() > 0)
1162         nMinDepth = params[0].get_int();
1163
1164     map<string, int64> mapAccountBalances;
1165     CRITICAL_BLOCK(cs_mapWallet)
1166     CRITICAL_BLOCK(cs_mapAddressBook)
1167     {
1168         BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
1169             uint160 hash160;
1170             if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
1171                 mapAccountBalances[entry.second] = 0;
1172         }
1173
1174         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1175         {
1176             const CWalletTx& wtx = (*it).second;
1177             int64 nGeneratedImmature, nGeneratedMature, nFee;
1178             string strSentAccount;
1179             list<pair<string, int64> > listReceived;
1180             list<pair<string, int64> > listSent;
1181             wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
1182             mapAccountBalances[strSentAccount] -= nFee;
1183             BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
1184                 mapAccountBalances[strSentAccount] -= s.second;
1185             if (wtx.GetDepthInMainChain() >= nMinDepth)
1186             {
1187                 mapAccountBalances[""] += nGeneratedMature;
1188                 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
1189                     if (mapAddressBook.count(r.first))
1190                         mapAccountBalances[mapAddressBook[r.first]] += r.second;
1191                     else
1192                         mapAccountBalances[""] += r.second;
1193             }
1194         }
1195     }
1196
1197     list<CAccountingEntry> acentries;
1198     CWalletDB().ListAccountCreditDebit("*", acentries);
1199     BOOST_FOREACH(const CAccountingEntry& entry, acentries)
1200         mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
1201
1202     Object ret;
1203     BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
1204         ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
1205     }
1206     return ret;
1207 }
1208
1209 Value gettransaction(const Array& params, bool fHelp)
1210 {
1211     if (fHelp || params.size() != 1)
1212         throw runtime_error(
1213             "gettransaction <txid>\n"
1214             "Get detailed information about <txid>");
1215
1216     uint256 hash;
1217     hash.SetHex(params[0].get_str());
1218
1219     Object entry;
1220     CRITICAL_BLOCK(cs_mapWallet)
1221     {
1222         if (!mapWallet.count(hash))
1223             throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
1224         const CWalletTx& wtx = mapWallet[hash];
1225
1226         int64 nCredit = wtx.GetCredit();
1227         int64 nDebit = wtx.GetDebit();
1228         int64 nNet = nCredit - nDebit;
1229         int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
1230
1231         entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
1232         if (wtx.IsFromMe())
1233             entry.push_back(Pair("fee", ValueFromAmount(nFee)));
1234
1235         WalletTxToJSON(mapWallet[hash], entry);
1236
1237         Array details;
1238         ListTransactions(mapWallet[hash], "*", 0, false, details);
1239         entry.push_back(Pair("details", details));
1240     }
1241
1242     return entry;
1243 }
1244
1245
1246 Value backupwallet(const Array& params, bool fHelp)
1247 {
1248     if (fHelp || params.size() != 1)
1249         throw runtime_error(
1250             "backupwallet <destination>\n"
1251             "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
1252
1253     string strDest = params[0].get_str();
1254     BackupWallet(strDest);
1255
1256     return Value::null;
1257 }
1258
1259
1260 Value validateaddress(const Array& params, bool fHelp)
1261 {
1262     if (fHelp || params.size() != 1)
1263         throw runtime_error(
1264             "validateaddress <bitcoinaddress>\n"
1265             "Return information about <bitcoinaddress>.");
1266
1267     string strAddress = params[0].get_str();
1268     uint160 hash160;
1269     bool isValid = AddressToHash160(strAddress, hash160);
1270
1271     Object ret;
1272     ret.push_back(Pair("isvalid", isValid));
1273     if (isValid)
1274     {
1275         // Call Hash160ToAddress() so we always return current ADDRESSVERSION
1276         // version of the address:
1277         string currentAddress = Hash160ToAddress(hash160);
1278         ret.push_back(Pair("address", currentAddress));
1279         ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
1280         CRITICAL_BLOCK(cs_mapAddressBook)
1281         {
1282             if (mapAddressBook.count(currentAddress))
1283                 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
1284         }
1285     }
1286     return ret;
1287 }
1288
1289
1290 Value getwork(const Array& params, bool fHelp)
1291 {
1292     if (fHelp || params.size() > 1)
1293         throw runtime_error(
1294             "getwork [data]\n"
1295             "If [data] is not specified, returns formatted hash data to work on:\n"
1296             "  \"midstate\" : precomputed hash state after hashing the first half of the data\n"
1297             "  \"data\" : block data\n"
1298             "  \"hash1\" : formatted hash buffer for second hash\n"
1299             "  \"target\" : little endian hash target\n"
1300             "If [data] is specified, tries to solve the block and returns true if it was successful.");
1301
1302     if (vNodes.empty())
1303         throw JSONRPCError(-9, "Bitcoin is not connected!");
1304
1305     if (IsInitialBlockDownload())
1306         throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
1307
1308     static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
1309     static vector<CBlock*> vNewBlock;
1310     static CReserveKey reservekey;
1311
1312     if (params.size() == 0)
1313     {
1314         // Update block
1315         static unsigned int nTransactionsUpdatedLast;
1316         static CBlockIndex* pindexPrev;
1317         static int64 nStart;
1318         static CBlock* pblock;
1319         if (pindexPrev != pindexBest ||
1320             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
1321         {
1322             if (pindexPrev != pindexBest)
1323             {
1324                 // Deallocate old blocks since they're obsolete now
1325                 mapNewBlock.clear();
1326                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
1327                     delete pblock;
1328                 vNewBlock.clear();
1329             }
1330             nTransactionsUpdatedLast = nTransactionsUpdated;
1331             pindexPrev = pindexBest;
1332             nStart = GetTime();
1333
1334             // Create new block
1335             pblock = CreateNewBlock(reservekey);
1336             if (!pblock)
1337                 throw JSONRPCError(-7, "Out of memory");
1338             vNewBlock.push_back(pblock);
1339         }
1340
1341         // Update nTime
1342         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1343         pblock->nNonce = 0;
1344
1345         // Update nExtraNonce
1346         static unsigned int nExtraNonce = 0;
1347         static int64 nPrevTime = 0;
1348         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
1349
1350         // Save
1351         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
1352
1353         // Prebuild hash buffers
1354         char pmidstate[32];
1355         char pdata[128];
1356         char phash1[64];
1357         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
1358
1359         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
1360
1361         Object result;
1362         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
1363         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
1364         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1))));
1365         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
1366         return result;
1367     }
1368     else
1369     {
1370         // Parse parameters
1371         vector<unsigned char> vchData = ParseHex(params[0].get_str());
1372         if (vchData.size() != 128)
1373             throw JSONRPCError(-8, "Invalid parameter");
1374         CBlock* pdata = (CBlock*)&vchData[0];
1375
1376         // Byte reverse
1377         for (int i = 0; i < 128/4; i++)
1378             ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
1379
1380         // Get saved block
1381         if (!mapNewBlock.count(pdata->hashMerkleRoot))
1382             return false;
1383         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
1384         unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
1385
1386         pblock->nTime = pdata->nTime;
1387         pblock->nNonce = pdata->nNonce;
1388         pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
1389         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1390
1391         return CheckWork(pblock, reservekey);
1392     }
1393 }
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405 //
1406 // Call Table
1407 //
1408
1409 pair<string, rpcfn_type> pCallTable[] =
1410 {
1411     make_pair("help",                  &help),
1412     make_pair("stop",                  &stop),
1413     make_pair("getblockcount",         &getblockcount),
1414     make_pair("getblocknumber",        &getblocknumber),
1415     make_pair("getconnectioncount",    &getconnectioncount),
1416     make_pair("getdifficulty",         &getdifficulty),
1417     make_pair("getgenerate",           &getgenerate),
1418     make_pair("setgenerate",           &setgenerate),
1419     make_pair("gethashespersec",       &gethashespersec),
1420     make_pair("getinfo",               &getinfo),
1421     make_pair("getnewaddress",         &getnewaddress),
1422     make_pair("getaccountaddress",     &getaccountaddress),
1423     make_pair("setaccount",            &setaccount),
1424     make_pair("setlabel",              &setaccount), // deprecated
1425     make_pair("getaccount",            &getaccount),
1426     make_pair("getlabel",              &getaccount), // deprecated
1427     make_pair("getaddressesbyaccount", &getaddressesbyaccount),
1428     make_pair("getaddressesbylabel",   &getaddressesbyaccount), // deprecated
1429     make_pair("sendtoaddress",         &sendtoaddress),
1430     make_pair("getamountreceived",     &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
1431     make_pair("getallreceived",        &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
1432     make_pair("getreceivedbyaddress",  &getreceivedbyaddress),
1433     make_pair("getreceivedbyaccount",  &getreceivedbyaccount),
1434     make_pair("getreceivedbylabel",    &getreceivedbyaccount), // deprecated
1435     make_pair("listreceivedbyaddress", &listreceivedbyaddress),
1436     make_pair("listreceivedbyaccount", &listreceivedbyaccount),
1437     make_pair("listreceivedbylabel",   &listreceivedbyaccount), // deprecated
1438     make_pair("backupwallet",          &backupwallet),
1439     make_pair("validateaddress",       &validateaddress),
1440     make_pair("getbalance",            &getbalance),
1441     make_pair("move",                  &movecmd),
1442     make_pair("sendfrom",              &sendfrom),
1443     make_pair("sendmany",              &sendmany),
1444     make_pair("gettransaction",        &gettransaction),
1445     make_pair("listtransactions",      &listtransactions),
1446     make_pair("getwork",               &getwork),
1447     make_pair("listaccounts",          &listaccounts),
1448     make_pair("settxfee",              &settxfee),
1449 };
1450 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
1451
1452 string pAllowInSafeMode[] =
1453 {
1454     "help",
1455     "stop",
1456     "getblockcount",
1457     "getblocknumber",
1458     "getconnectioncount",
1459     "getdifficulty",
1460     "getgenerate",
1461     "setgenerate",
1462     "gethashespersec",
1463     "getinfo",
1464     "getnewaddress",
1465     "getaccountaddress",
1466     "setlabel",
1467     "getaccount",
1468     "getlabel", // deprecated
1469     "getaddressesbyaccount",
1470     "getaddressesbylabel", // deprecated
1471     "backupwallet",
1472     "validateaddress",
1473     "getwork",
1474 };
1475 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1476
1477
1478
1479
1480 //
1481 // HTTP protocol
1482 //
1483 // This ain't Apache.  We're just using HTTP header for the length field
1484 // and to be compatible with other JSON-RPC implementations.
1485 //
1486
1487 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1488 {
1489     ostringstream s;
1490     s << "POST / HTTP/1.1\r\n"
1491       << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
1492       << "Host: 127.0.0.1\r\n"
1493       << "Content-Type: application/json\r\n"
1494       << "Content-Length: " << strMsg.size() << "\r\n"
1495       << "Accept: application/json\r\n";
1496     BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1497         s << item.first << ": " << item.second << "\r\n";
1498     s << "\r\n" << strMsg;
1499
1500     return s.str();
1501 }
1502
1503 string rfc1123Time()
1504 {
1505     char buffer[64];
1506     time_t now;
1507     time(&now);
1508     struct tm* now_gmt = gmtime(&now);
1509     string locale(setlocale(LC_TIME, NULL));
1510     setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
1511     strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
1512     setlocale(LC_TIME, locale.c_str());
1513     return string(buffer);
1514 }
1515
1516 string HTTPReply(int nStatus, const string& strMsg)
1517 {
1518     if (nStatus == 401)
1519         return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1520             "Date: %s\r\n"
1521             "Server: bitcoin-json-rpc/%s\r\n"
1522             "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1523             "Content-Type: text/html\r\n"
1524             "Content-Length: 296\r\n"
1525             "\r\n"
1526             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1527             "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1528             "<HTML>\r\n"
1529             "<HEAD>\r\n"
1530             "<TITLE>Error</TITLE>\r\n"
1531             "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1532             "</HEAD>\r\n"
1533             "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1534             "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
1535     string strStatus;
1536          if (nStatus == 200) strStatus = "OK";
1537     else if (nStatus == 400) strStatus = "Bad Request";
1538     else if (nStatus == 404) strStatus = "Not Found";
1539     else if (nStatus == 500) strStatus = "Internal Server Error";
1540     return strprintf(
1541             "HTTP/1.1 %d %s\r\n"
1542             "Date: %s\r\n"
1543             "Connection: close\r\n"
1544             "Content-Length: %d\r\n"
1545             "Content-Type: application/json\r\n"
1546             "Server: bitcoin-json-rpc/%s\r\n"
1547             "\r\n"
1548             "%s",
1549         nStatus,
1550         strStatus.c_str(),
1551         rfc1123Time().c_str(),
1552         strMsg.size(),
1553         FormatFullVersion().c_str(),
1554         strMsg.c_str());
1555 }
1556
1557 int ReadHTTPStatus(std::basic_istream<char>& stream)
1558 {
1559     string str;
1560     getline(stream, str);
1561     vector<string> vWords;
1562     boost::split(vWords, str, boost::is_any_of(" "));
1563     if (vWords.size() < 2)
1564         return 500;
1565     return atoi(vWords[1].c_str());
1566 }
1567
1568 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1569 {
1570     int nLen = 0;
1571     loop
1572     {
1573         string str;
1574         std::getline(stream, str);
1575         if (str.empty() || str == "\r")
1576             break;
1577         string::size_type nColon = str.find(":");
1578         if (nColon != string::npos)
1579         {
1580             string strHeader = str.substr(0, nColon);
1581             boost::trim(strHeader);
1582             boost::to_lower(strHeader);
1583             string strValue = str.substr(nColon+1);
1584             boost::trim(strValue);
1585             mapHeadersRet[strHeader] = strValue;
1586             if (strHeader == "content-length")
1587                 nLen = atoi(strValue.c_str());
1588         }
1589     }
1590     return nLen;
1591 }
1592
1593 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1594 {
1595     mapHeadersRet.clear();
1596     strMessageRet = "";
1597
1598     // Read status
1599     int nStatus = ReadHTTPStatus(stream);
1600
1601     // Read header
1602     int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1603     if (nLen < 0 || nLen > MAX_SIZE)
1604         return 500;
1605
1606     // Read message
1607     if (nLen > 0)
1608     {
1609         vector<char> vch(nLen);
1610         stream.read(&vch[0], nLen);
1611         strMessageRet = string(vch.begin(), vch.end());
1612     }
1613
1614     return nStatus;
1615 }
1616
1617 string EncodeBase64(string s)
1618 {
1619     BIO *b64, *bmem;
1620     BUF_MEM *bptr;
1621
1622     b64 = BIO_new(BIO_f_base64());
1623     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1624     bmem = BIO_new(BIO_s_mem());
1625     b64 = BIO_push(b64, bmem);
1626     BIO_write(b64, s.c_str(), s.size());
1627     BIO_flush(b64);
1628     BIO_get_mem_ptr(b64, &bptr);
1629
1630     string result(bptr->data, bptr->length);
1631     BIO_free_all(b64);
1632
1633     return result;
1634 }
1635
1636 string DecodeBase64(string s)
1637 {
1638     BIO *b64, *bmem;
1639
1640     char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1641
1642     b64 = BIO_new(BIO_f_base64());
1643     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1644     bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1645     bmem = BIO_push(b64, bmem);
1646     BIO_read(bmem, buffer, s.size());
1647     BIO_free_all(bmem);
1648
1649     string result(buffer);
1650     free(buffer);
1651     return result;
1652 }
1653
1654 bool HTTPAuthorized(map<string, string>& mapHeaders)
1655 {
1656     string strAuth = mapHeaders["authorization"];
1657     if (strAuth.substr(0,6) != "Basic ")
1658         return false;
1659     string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1660     string strUserPass = DecodeBase64(strUserPass64);
1661     string::size_type nColon = strUserPass.find(":");
1662     if (nColon == string::npos)
1663         return false;
1664     string strUser = strUserPass.substr(0, nColon);
1665     string strPassword = strUserPass.substr(nColon+1);
1666     return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1667 }
1668
1669 //
1670 // JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,
1671 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1672 // unspecified (HTTP errors and contents of 'error').
1673 //
1674 // 1.0 spec: http://json-rpc.org/wiki/specification
1675 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1676 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1677 //
1678
1679 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1680 {
1681     Object request;
1682     request.push_back(Pair("method", strMethod));
1683     request.push_back(Pair("params", params));
1684     request.push_back(Pair("id", id));
1685     return write_string(Value(request), false) + "\n";
1686 }
1687
1688 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1689 {
1690     Object reply;
1691     if (error.type() != null_type)
1692         reply.push_back(Pair("result", Value::null));
1693     else
1694         reply.push_back(Pair("result", result));
1695     reply.push_back(Pair("error", error));
1696     reply.push_back(Pair("id", id));
1697     return write_string(Value(reply), false) + "\n";
1698 }
1699
1700 void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
1701 {
1702     // Send error reply from json-rpc error object
1703     int nStatus = 500;
1704     int code = find_value(objError, "code").get_int();
1705     if (code == -32600) nStatus = 400;
1706     else if (code == -32601) nStatus = 404;
1707     string strReply = JSONRPCReply(Value::null, objError, id);
1708     stream << HTTPReply(nStatus, strReply) << std::flush;
1709 }
1710
1711 bool ClientAllowed(const string& strAddress)
1712 {
1713     if (strAddress == asio::ip::address_v4::loopback().to_string())
1714         return true;
1715     const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1716     BOOST_FOREACH(string strAllow, vAllow)
1717         if (WildcardMatch(strAddress, strAllow))
1718             return true;
1719     return false;
1720 }
1721
1722 #ifdef USE_SSL
1723 //
1724 // IOStream device that speaks SSL but can also speak non-SSL
1725 //
1726 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1727 public:
1728     SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1729     {
1730         fUseSSL = fUseSSLIn;
1731         fNeedHandshake = fUseSSLIn;
1732     }
1733
1734     void handshake(ssl::stream_base::handshake_type role)
1735     {
1736         if (!fNeedHandshake) return;
1737         fNeedHandshake = false;
1738         stream.handshake(role);
1739     }
1740     std::streamsize read(char* s, std::streamsize n)
1741     {
1742         handshake(ssl::stream_base::server); // HTTPS servers read first
1743         if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1744         return stream.next_layer().read_some(asio::buffer(s, n));
1745     }
1746     std::streamsize write(const char* s, std::streamsize n)
1747     {
1748         handshake(ssl::stream_base::client); // HTTPS clients write first
1749         if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1750         return asio::write(stream.next_layer(), asio::buffer(s, n));
1751     }
1752     bool connect(const std::string& server, const std::string& port)
1753     {
1754         ip::tcp::resolver resolver(stream.get_io_service());
1755         ip::tcp::resolver::query query(server.c_str(), port.c_str());
1756         ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1757         ip::tcp::resolver::iterator end;
1758         boost::system::error_code error = asio::error::host_not_found;
1759         while (error && endpoint_iterator != end)
1760         {
1761             stream.lowest_layer().close();
1762             stream.lowest_layer().connect(*endpoint_iterator++, error);
1763         }
1764         if (error)
1765             return false;
1766         return true;
1767     }
1768
1769 private:
1770     bool fNeedHandshake;
1771     bool fUseSSL;
1772     SSLStream& stream;
1773 };
1774 #endif
1775
1776 void ThreadRPCServer(void* parg)
1777 {
1778     IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1779     try
1780     {
1781         vnThreadsRunning[4]++;
1782         ThreadRPCServer2(parg);
1783         vnThreadsRunning[4]--;
1784     }
1785     catch (std::exception& e) {
1786         vnThreadsRunning[4]--;
1787         PrintException(&e, "ThreadRPCServer()");
1788     } catch (...) {
1789         vnThreadsRunning[4]--;
1790         PrintException(NULL, "ThreadRPCServer()");
1791     }
1792     printf("ThreadRPCServer exiting\n");
1793 }
1794
1795 void ThreadRPCServer2(void* parg)
1796 {
1797     printf("ThreadRPCServer started\n");
1798
1799     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1800     {
1801         string strWhatAmI = "To use bitcoind";
1802         if (mapArgs.count("-server"))
1803             strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1804         else if (mapArgs.count("-daemon"))
1805             strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1806         PrintConsole(
1807             _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1808               "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1809                 strWhatAmI.c_str(),
1810                 GetConfigFile().c_str());
1811         CreateThread(Shutdown, NULL);
1812         return;
1813     }
1814
1815     bool fUseSSL = GetBoolArg("-rpcssl");
1816     asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1817
1818     asio::io_service io_service;
1819     ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1820     ip::tcp::acceptor acceptor(io_service, endpoint);
1821
1822     acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1823
1824 #ifdef USE_SSL
1825     ssl::context context(io_service, ssl::context::sslv23);
1826     if (fUseSSL)
1827     {
1828         context.set_options(ssl::context::no_sslv2);
1829         filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1830         if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1831         if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1832         else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1833         filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1834         if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1835         if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1836         else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1837
1838         string ciphers = GetArg("-rpcsslciphers",
1839                                          "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1840         SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1841     }
1842 #else
1843     if (fUseSSL)
1844         throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1845 #endif
1846
1847     loop
1848     {
1849         // Accept connection
1850 #ifdef USE_SSL
1851         SSLStream sslStream(io_service, context);
1852         SSLIOStreamDevice d(sslStream, fUseSSL);
1853         iostreams::stream<SSLIOStreamDevice> stream(d);
1854 #else
1855         ip::tcp::iostream stream;
1856 #endif
1857
1858         ip::tcp::endpoint peer;
1859         vnThreadsRunning[4]--;
1860 #ifdef USE_SSL
1861         acceptor.accept(sslStream.lowest_layer(), peer);
1862 #else
1863         acceptor.accept(*stream.rdbuf(), peer);
1864 #endif
1865         vnThreadsRunning[4]++;
1866         if (fShutdown)
1867             return;
1868
1869         // Restrict callers by IP
1870         if (!ClientAllowed(peer.address().to_string()))
1871             continue;
1872
1873         map<string, string> mapHeaders;
1874         string strRequest;
1875
1876         boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
1877         if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
1878         {   // Timed out:
1879             acceptor.cancel();
1880             printf("ThreadRPCServer ReadHTTP timeout\n");
1881             continue;
1882         }
1883
1884         // Check authorization
1885         if (mapHeaders.count("authorization") == 0)
1886         {
1887             stream << HTTPReply(401, "") << std::flush;
1888             continue;
1889         }
1890         if (!HTTPAuthorized(mapHeaders))
1891         {
1892             // Deter brute-forcing short passwords
1893             if (mapArgs["-rpcpassword"].size() < 15)
1894                 Sleep(50);
1895
1896             stream << HTTPReply(401, "") << std::flush;
1897             printf("ThreadRPCServer incorrect password attempt\n");
1898             continue;
1899         }
1900
1901         Value id = Value::null;
1902         try
1903         {
1904             // Parse request
1905             Value valRequest;
1906             if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1907                 throw JSONRPCError(-32700, "Parse error");
1908             const Object& request = valRequest.get_obj();
1909
1910             // Parse id now so errors from here on will have the id
1911             id = find_value(request, "id");
1912
1913             // Parse method
1914             Value valMethod = find_value(request, "method");
1915             if (valMethod.type() == null_type)
1916                 throw JSONRPCError(-32600, "Missing method");
1917             if (valMethod.type() != str_type)
1918                 throw JSONRPCError(-32600, "Method must be a string");
1919             string strMethod = valMethod.get_str();
1920             if (strMethod != "getwork")
1921                 printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1922
1923             // Parse params
1924             Value valParams = find_value(request, "params");
1925             Array params;
1926             if (valParams.type() == array_type)
1927                 params = valParams.get_array();
1928             else if (valParams.type() == null_type)
1929                 params = Array();
1930             else
1931                 throw JSONRPCError(-32600, "Params must be an array");
1932
1933             // Find method
1934             map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1935             if (mi == mapCallTable.end())
1936                 throw JSONRPCError(-32601, "Method not found");
1937
1938             // Observe safe mode
1939             string strWarning = GetWarnings("rpc");
1940             if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1941                 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1942
1943             try
1944             {
1945                 // Execute
1946                 Value result = (*(*mi).second)(params, false);
1947
1948                 // Send reply
1949                 string strReply = JSONRPCReply(result, Value::null, id);
1950                 stream << HTTPReply(200, strReply) << std::flush;
1951             }
1952             catch (std::exception& e)
1953             {
1954                 ErrorReply(stream, JSONRPCError(-1, e.what()), id);
1955             }
1956         }
1957         catch (Object& objError)
1958         {
1959             ErrorReply(stream, objError, id);
1960         }
1961         catch (std::exception& e)
1962         {
1963             ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
1964         }
1965     }
1966 }
1967
1968
1969
1970
1971 Object CallRPC(const string& strMethod, const Array& params)
1972 {
1973     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1974         throw runtime_error(strprintf(
1975             _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1976               "If the file does not exist, create it with owner-readable-only file permissions."),
1977                 GetConfigFile().c_str()));
1978
1979     // Connect to localhost
1980     bool fUseSSL = GetBoolArg("-rpcssl");
1981 #ifdef USE_SSL
1982     asio::io_service io_service;
1983     ssl::context context(io_service, ssl::context::sslv23);
1984     context.set_options(ssl::context::no_sslv2);
1985     SSLStream sslStream(io_service, context);
1986     SSLIOStreamDevice d(sslStream, fUseSSL);
1987     iostreams::stream<SSLIOStreamDevice> stream(d);
1988     if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1989         throw runtime_error("couldn't connect to server");
1990 #else
1991     if (fUseSSL)
1992         throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
1993
1994     ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1995     if (stream.fail())
1996         throw runtime_error("couldn't connect to server");
1997 #endif
1998
1999
2000     // HTTP basic authentication
2001     string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
2002     map<string, string> mapRequestHeaders;
2003     mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
2004
2005     // Send request
2006     string strRequest = JSONRPCRequest(strMethod, params, 1);
2007     string strPost = HTTPPost(strRequest, mapRequestHeaders);
2008     stream << strPost << std::flush;
2009
2010     // Receive reply
2011     map<string, string> mapHeaders;
2012     string strReply;
2013     int nStatus = ReadHTTP(stream, mapHeaders, strReply);
2014     if (nStatus == 401)
2015         throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
2016     else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
2017         throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
2018     else if (strReply.empty())
2019         throw runtime_error("no response from server");
2020
2021     // Parse reply
2022     Value valReply;
2023     if (!read_string(strReply, valReply))
2024         throw runtime_error("couldn't parse reply from server");
2025     const Object& reply = valReply.get_obj();
2026     if (reply.empty())
2027         throw runtime_error("expected reply to have result, error and id properties");
2028
2029     return reply;
2030 }
2031
2032
2033
2034
2035 template<typename T>
2036 void ConvertTo(Value& value)
2037 {
2038     if (value.type() == str_type)
2039     {
2040         // reinterpret string as unquoted json value
2041         Value value2;
2042         if (!read_string(value.get_str(), value2))
2043             throw runtime_error("type mismatch");
2044         value = value2.get_value<T>();
2045     }
2046     else
2047     {
2048         value = value.get_value<T>();
2049     }
2050 }
2051
2052 int CommandLineRPC(int argc, char *argv[])
2053 {
2054     string strPrint;
2055     int nRet = 0;
2056     try
2057     {
2058         // Skip switches
2059         while (argc > 1 && IsSwitchChar(argv[1][0]))
2060         {
2061             argc--;
2062             argv++;
2063         }
2064
2065         // Method
2066         if (argc < 2)
2067             throw runtime_error("too few parameters");
2068         string strMethod = argv[1];
2069
2070         // Parameters default to strings
2071         Array params;
2072         for (int i = 2; i < argc; i++)
2073             params.push_back(argv[i]);
2074         int n = params.size();
2075
2076         //
2077         // Special case non-string parameter types
2078         //
2079         if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
2080         if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
2081         if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
2082         if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
2083         if (strMethod == "getamountreceived"      && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2084         if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
2085         if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
2086         if (strMethod == "getreceivedbylabel"     && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
2087         if (strMethod == "getallreceived"         && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2088         if (strMethod == "getallreceived"         && n > 1) ConvertTo<bool>(params[1]);
2089         if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
2090         if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
2091         if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
2092         if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
2093         if (strMethod == "listreceivedbylabel"    && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
2094         if (strMethod == "listreceivedbylabel"    && n > 1) ConvertTo<bool>(params[1]); // deprecated
2095         if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
2096         if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
2097         if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
2098         if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
2099         if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
2100         if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
2101         if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
2102         if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
2103         if (strMethod == "sendmany"               && n > 1)
2104         {
2105             string s = params[1].get_str();
2106             Value v;
2107             if (!read_string(s, v) || v.type() != obj_type)
2108                 throw runtime_error("type mismatch");
2109             params[1] = v.get_obj();
2110         }
2111         if (strMethod == "sendmany"                && n > 2) ConvertTo<boost::int64_t>(params[2]);
2112
2113         // Execute
2114         Object reply = CallRPC(strMethod, params);
2115
2116         // Parse reply
2117         const Value& result = find_value(reply, "result");
2118         const Value& error  = find_value(reply, "error");
2119         const Value& id     = find_value(reply, "id");
2120
2121         if (error.type() != null_type)
2122         {
2123             // Error
2124             strPrint = "error: " + write_string(error, false);
2125             int code = find_value(error.get_obj(), "code").get_int();
2126             nRet = abs(code);
2127         }
2128         else
2129         {
2130             // Result
2131             if (result.type() == null_type)
2132                 strPrint = "";
2133             else if (result.type() == str_type)
2134                 strPrint = result.get_str();
2135             else
2136                 strPrint = write_string(result, true);
2137         }
2138     }
2139     catch (std::exception& e)
2140     {
2141         strPrint = string("error: ") + e.what();
2142         nRet = 87;
2143     }
2144     catch (...)
2145     {
2146         PrintException(NULL, "CommandLineRPC()");
2147     }
2148
2149     if (strPrint != "")
2150     {
2151 #if defined(__WXMSW__) && defined(GUI)
2152         // Windows GUI apps can't print to command line,
2153         // so settle for a message box yuck
2154         MyMessageBox(strPrint, "Bitcoin", wxOK);
2155 #else
2156         fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
2157 #endif
2158     }
2159     return nRet;
2160 }
2161
2162
2163
2164
2165 #ifdef TEST
2166 int main(int argc, char *argv[])
2167 {
2168 #ifdef _MSC_VER
2169     // Turn off microsoft heap dump noise
2170     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2171     _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
2172 #endif
2173     setbuf(stdin, NULL);
2174     setbuf(stdout, NULL);
2175     setbuf(stderr, NULL);
2176
2177     try
2178     {
2179         if (argc >= 2 && string(argv[1]) == "-server")
2180         {
2181             printf("server ready\n");
2182             ThreadRPCServer(NULL);
2183         }
2184         else
2185         {
2186             return CommandLineRPC(argc, argv);
2187         }
2188     }
2189     catch (std::exception& e) {
2190         PrintException(&e, "main()");
2191     } catch (...) {
2192         PrintException(NULL, "main()");
2193     }
2194     return 0;
2195 }
2196 #endif