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