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