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