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