Depracate "label" API, replacing with account
[novacoin.git] / 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 #undef printf
7 #include <boost/asio.hpp>
8 #include <boost/iostreams/concepts.hpp>
9 #include <boost/iostreams/stream.hpp>
10 #ifdef USE_SSL
11 #include <boost/asio/ssl.hpp> 
12 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
13 #endif
14 #include "json/json_spirit_reader_template.h"
15 #include "json/json_spirit_writer_template.h"
16 #include "json/json_spirit_utils.h"
17 #define printf OutputDebugStringF
18 // MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
19 // precompiled in headers.h.  The problem might be when the pch file goes over
20 // a certain size around 145MB.  If we need access to json_spirit outside this
21 // file, we could use the compiled json_spirit option.
22
23 using namespace boost::asio;
24 using namespace json_spirit;
25
26 void ThreadRPCServer2(void* parg);
27 typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
28 extern map<string, rpcfn_type> mapCallTable;
29
30
31 Object JSONRPCError(int code, const string& message)
32 {
33     Object error;
34     error.push_back(Pair("code", code));
35     error.push_back(Pair("message", message));
36     return error;
37 }
38
39
40 void PrintConsole(const char* format, ...)
41 {
42     char buffer[50000];
43     int limit = sizeof(buffer);
44     va_list arg_ptr;
45     va_start(arg_ptr, format);
46     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
47     va_end(arg_ptr);
48     if (ret < 0 || ret >= limit)
49     {
50         ret = limit - 1;
51         buffer[limit-1] = 0;
52     }
53 #if defined(__WXMSW__) && defined(GUI)
54     MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
55 #else
56     fprintf(stdout, "%s", buffer);
57 #endif
58 }
59
60
61 int64 AmountFromValue(const Value& value)
62 {
63     double dAmount = value.get_real();
64     if (dAmount <= 0.0 || dAmount > 21000000.0)
65         throw JSONRPCError(-3, "Invalid amount");
66     int64 nAmount = roundint64(dAmount * 100.00) * CENT;
67     if (!MoneyRange(nAmount))
68         throw JSONRPCError(-3, "Invalid amount");
69     return nAmount;
70 }
71
72
73
74
75
76
77 ///
78 /// Note: This interface may still be subject to change.
79 ///
80
81
82 Value help(const Array& params, bool fHelp)
83 {
84     if (fHelp || params.size() > 1)
85         throw runtime_error(
86             "help [command]\n"
87             "List commands, or get help for a command.");
88
89     string strCommand;
90     if (params.size() > 0)
91         strCommand = params[0].get_str();
92
93     string strRet;
94     set<rpcfn_type> setDone;
95     for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
96     {
97         string strMethod = (*mi).first;
98         // We already filter duplicates, but these deprecated screw up the sort order
99         if (strMethod == "getamountreceived" ||
100             strMethod == "getallreceived" ||
101             (strMethod.find("label") != string::npos))
102             continue;
103         if (strCommand != "" && strMethod != strCommand)
104             continue;
105         try
106         {
107             Array params;
108             rpcfn_type pfn = (*mi).second;
109             if (setDone.insert(pfn).second)
110                 (*pfn)(params, true);
111         }
112         catch (std::exception& e)
113         {
114             // Help text is returned in an exception
115             string strHelp = string(e.what());
116             if (strCommand == "")
117                 if (strHelp.find('\n') != -1)
118                     strHelp = strHelp.substr(0, strHelp.find('\n'));
119             strRet += strHelp + "\n";
120         }
121     }
122     if (strRet == "")
123         strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
124     strRet = strRet.substr(0,strRet.size()-1);
125     return strRet;
126 }
127
128
129 Value stop(const Array& params, bool fHelp)
130 {
131     if (fHelp || params.size() != 0)
132         throw runtime_error(
133             "stop\n"
134             "Stop bitcoin server.");
135
136     // Shutdown will take long enough that the response should get back
137     CreateThread(Shutdown, NULL);
138     return "bitcoin server stopping";
139 }
140
141
142 Value getblockcount(const Array& params, bool fHelp)
143 {
144     if (fHelp || params.size() != 0)
145         throw runtime_error(
146             "getblockcount\n"
147             "Returns the number of blocks in the longest block chain.");
148
149     return nBestHeight;
150 }
151
152
153 Value getblocknumber(const Array& params, bool fHelp)
154 {
155     if (fHelp || params.size() != 0)
156         throw runtime_error(
157             "getblocknumber\n"
158             "Returns the block number of the latest block in the longest block chain.");
159
160     return nBestHeight;
161 }
162
163
164 Value getconnectioncount(const Array& params, bool fHelp)
165 {
166     if (fHelp || params.size() != 0)
167         throw runtime_error(
168             "getconnectioncount\n"
169             "Returns the number of connections to other nodes.");
170
171     return (int)vNodes.size();
172 }
173
174
175 double GetDifficulty()
176 {
177     // Floating point number that is a multiple of the minimum difficulty,
178     // minimum difficulty = 1.0.
179     if (pindexBest == NULL)
180         return 1.0;
181     int nShift = 256 - 32 - 31; // to fit in a uint
182     double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();
183     double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();
184     return dMinimum / dCurrently;
185 }
186
187 Value getdifficulty(const Array& params, bool fHelp)
188 {
189     if (fHelp || params.size() != 0)
190         throw runtime_error(
191             "getdifficulty\n"
192             "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
193
194     return GetDifficulty();
195 }
196
197
198 Value getgenerate(const Array& params, bool fHelp)
199 {
200     if (fHelp || params.size() != 0)
201         throw runtime_error(
202             "getgenerate\n"
203             "Returns true or false.");
204
205     return (bool)fGenerateBitcoins;
206 }
207
208
209 Value setgenerate(const Array& params, bool fHelp)
210 {
211     if (fHelp || params.size() < 1 || params.size() > 2)
212         throw runtime_error(
213             "setgenerate <generate> [genproclimit]\n"
214             "<generate> is true or false to turn generation on or off.\n"
215             "Generation is limited to [genproclimit] processors, -1 is unlimited.");
216
217     bool fGenerate = true;
218     if (params.size() > 0)
219         fGenerate = params[0].get_bool();
220
221     if (params.size() > 1)
222     {
223         int nGenProcLimit = params[1].get_int();
224         fLimitProcessors = (nGenProcLimit != -1);
225         CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
226         if (nGenProcLimit != -1)
227             CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
228     }
229
230     GenerateBitcoins(fGenerate);
231     return Value::null;
232 }
233
234
235 Value gethashespersec(const Array& params, bool fHelp)
236 {
237     if (fHelp || params.size() != 0)
238         throw runtime_error(
239             "gethashespersec\n"
240             "Returns a recent hashes per second performance measurement while generating.");
241
242     if (GetTimeMillis() - nHPSTimerStart > 8000)
243         return (boost::int64_t)0;
244     return (boost::int64_t)dHashesPerSec;
245 }
246
247
248 Value getinfo(const Array& params, bool fHelp)
249 {
250     if (fHelp || params.size() != 0)
251         throw runtime_error(
252             "getinfo\n"
253             "Returns an object containing various state info.");
254
255     Object obj;
256     obj.push_back(Pair("version",       (int)VERSION));
257     obj.push_back(Pair("balance",       (double)GetBalance() / (double)COIN));
258     obj.push_back(Pair("blocks",        (int)nBestHeight));
259     obj.push_back(Pair("connections",   (int)vNodes.size()));
260     obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));
261     obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));
262     obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));
263     obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
264     obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));
265     obj.push_back(Pair("testnet",       fTestNet));
266     obj.push_back(Pair("keypoololdest", (boost::int64_t)CWalletDB().GetOldestKeyPoolTime()));
267     obj.push_back(Pair("paytxfee",      (double)nTransactionFee / (double)COIN));
268     obj.push_back(Pair("errors",        GetWarnings("statusbar")));
269     return obj;
270 }
271
272
273 Value getnewaddress(const Array& params, bool fHelp)
274 {
275     if (fHelp || params.size() > 1)
276         throw runtime_error(
277             "getnewaddress [account]\n"
278             "Returns a new bitcoin address for receiving payments.  "
279             "If [account] is specified (recommended), it is added to the address book "
280             "so payments received with the address will be credited to [account].");
281
282     // Parse the account first so we don't generate a key if there's an error
283     string strAccount;
284     if (params.size() > 0)
285         strAccount = params[0].get_str();
286
287     // Generate a new key that is added to wallet
288     string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());
289
290     SetAddressBookName(strAddress, strAccount);
291     return strAddress;
292 }
293
294
295 Value getaccountaddress(const Array& params, bool fHelp)
296 {
297     if (fHelp || params.size() != 1)
298         throw runtime_error(
299             "getaccountaddress <account>\n"
300             "Returns the current bitcoin address for receiving payments to this account.");
301
302     // Parse the account first so we don't generate a key if there's an error
303     string strAccount = params[0].get_str();
304
305     CRITICAL_BLOCK(cs_mapWallet)
306     {
307         CWalletDB walletdb;
308         walletdb.TxnBegin();
309
310         CAccount account;
311         walletdb.ReadAccount(strAccount, account);
312
313         // Check if the current key has been used
314         if (!account.vchPubKey.empty())
315         {
316             CScript scriptPubKey;
317             scriptPubKey.SetBitcoinAddress(account.vchPubKey);
318             for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
319                  it != mapWallet.end() && !account.vchPubKey.empty();
320                  ++it)
321             {
322                 const CWalletTx& wtx = (*it).second;
323                 foreach(const CTxOut& txout, wtx.vout)
324                     if (txout.scriptPubKey == scriptPubKey)
325                         account.vchPubKey.clear();
326             }
327         }
328
329         // Generate a new key
330         if (account.vchPubKey.empty())
331         {
332             account.vchPubKey = CWalletDB().GetKeyFromKeyPool();
333             string strAddress = PubKeyToAddress(account.vchPubKey);
334             SetAddressBookName(strAddress, strAccount);
335             walletdb.WriteAccount(strAccount, account);
336         }
337
338         walletdb.TxnCommit();
339         return PubKeyToAddress(account.vchPubKey);
340     }
341 }
342
343
344 Value setaccount(const Array& params, bool fHelp)
345 {
346     if (fHelp || params.size() < 1 || params.size() > 2)
347         throw runtime_error(
348             "setaccount <bitcoinaddress> <account>\n"
349             "Sets the account associated with the given address.");
350
351     string strAddress = params[0].get_str();
352     string strAccount;
353     if (params.size() > 1)
354         strAccount = params[1].get_str();
355
356     SetAddressBookName(strAddress, strAccount);
357     return Value::null;
358 }
359
360
361 Value getaccount(const Array& params, bool fHelp)
362 {
363     if (fHelp || params.size() != 1)
364         throw runtime_error(
365             "getaccount <bitcoinaddress>\n"
366             "Returns the account associated with the given address.");
367
368     string strAddress = params[0].get_str();
369
370     string strAccount;
371     CRITICAL_BLOCK(cs_mapAddressBook)
372     {
373         map<string, string>::iterator mi = mapAddressBook.find(strAddress);
374         if (mi != mapAddressBook.end() && !(*mi).second.empty())
375             strAccount = (*mi).second;
376     }
377     return strAccount;
378 }
379
380
381 Value getaddressesbyaccount(const Array& params, bool fHelp)
382 {
383     if (fHelp || params.size() != 1)
384         throw runtime_error(
385             "getaddressesbyaccount <account>\n"
386             "Returns the list of addresses for the given account.");
387
388     string strAccount = params[0].get_str();
389
390     // Find all addresses that have the given account
391     Array ret;
392     CRITICAL_BLOCK(cs_mapAddressBook)
393     {
394         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
395         {
396             const string& strAddress = item.first;
397             const string& strName = item.second;
398             if (strName == strAccount)
399             {
400                 // We're only adding valid bitcoin addresses and not ip addresses
401                 CScript scriptPubKey;
402                 if (scriptPubKey.SetBitcoinAddress(strAddress))
403                     ret.push_back(strAddress);
404             }
405         }
406     }
407     return ret;
408 }
409
410 Value sendtoaddress(const Array& params, bool fHelp)
411 {
412     if (fHelp || params.size() < 2 || params.size() > 4)
413         throw runtime_error(
414             "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
415             "<amount> is a real and is rounded to the nearest 0.01");
416
417     string strAddress = params[0].get_str();
418
419     // Amount
420     int64 nAmount = AmountFromValue(params[1]);
421
422     // Wallet comments
423     CWalletTx wtx;
424     if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
425         wtx.mapValue["message"] = params[2].get_str();
426     if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
427         wtx.mapValue["to"]      = params[3].get_str();
428
429     string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
430     if (strError != "")
431         throw JSONRPCError(-4, strError);
432     return wtx.GetHash().GetHex();
433 }
434
435
436 Value listtransactions(const Array& params, bool fHelp)
437 {
438     if (fHelp || params.size() > 2)
439         throw runtime_error(
440             "listtransactions [count=10] [includegenerated=false]\n"
441             "Returns up to [count] most recent transactions.");
442
443     int64 nCount = 10;
444     if (params.size() > 0)
445         nCount = params[0].get_int64();
446     bool fGenerated = false;
447     if (params.size() > 1)
448         fGenerated = params[1].get_bool();
449
450     Array ret;
451     //// not finished
452     ret.push_back("not implemented yet");
453     return ret;
454 }
455
456
457 Value getreceivedbyaddress(const Array& params, bool fHelp)
458 {
459     if (fHelp || params.size() < 1 || params.size() > 2)
460         throw runtime_error(
461             "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
462             "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
463
464     // Bitcoin address
465     string strAddress = params[0].get_str();
466     CScript scriptPubKey;
467     if (!scriptPubKey.SetBitcoinAddress(strAddress))
468         throw JSONRPCError(-5, "Invalid bitcoin address");
469     if (!IsMine(scriptPubKey))
470         return (double)0.0;
471
472     // Minimum confirmations
473     int nMinDepth = 1;
474     if (params.size() > 1)
475         nMinDepth = params[1].get_int();
476
477     // Tally
478     int64 nAmount = 0;
479     CRITICAL_BLOCK(cs_mapWallet)
480     {
481         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
482         {
483             const CWalletTx& wtx = (*it).second;
484             if (wtx.IsCoinBase() || !wtx.IsFinal())
485                 continue;
486
487             foreach(const CTxOut& txout, wtx.vout)
488                 if (txout.scriptPubKey == scriptPubKey)
489                     if (wtx.GetDepthInMainChain() >= nMinDepth)
490                         nAmount += txout.nValue;
491         }
492     }
493
494     return (double)nAmount / (double)COIN;
495 }
496
497
498 Value getreceivedbyaccount(const Array& params, bool fHelp)
499 {
500     if (fHelp || params.size() < 1 || params.size() > 2)
501         throw runtime_error(
502             "getreceivedbyaccount <account> [minconf=1]\n"
503             "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
504
505     // Minimum confirmations
506     int nMinDepth = 1;
507     if (params.size() > 1)
508         nMinDepth = params[1].get_int();
509
510     // Get the set of pub keys that have the label
511     string strAccount = params[0].get_str();
512     set<CScript> setPubKey;
513     CRITICAL_BLOCK(cs_mapAddressBook)
514     {
515         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
516         {
517             const string& strAddress = item.first;
518             const string& strName = item.second;
519             if (strName == strAccount)
520             {
521                 // We're only counting our own valid bitcoin addresses and not ip addresses
522                 CScript scriptPubKey;
523                 if (scriptPubKey.SetBitcoinAddress(strAddress))
524                     if (IsMine(scriptPubKey))
525                         setPubKey.insert(scriptPubKey);
526             }
527         }
528     }
529
530     // Tally
531     int64 nAmount = 0;
532     CRITICAL_BLOCK(cs_mapWallet)
533     {
534         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
535         {
536             const CWalletTx& wtx = (*it).second;
537             if (wtx.IsCoinBase() || !wtx.IsFinal())
538                 continue;
539
540             foreach(const CTxOut& txout, wtx.vout)
541                 if (setPubKey.count(txout.scriptPubKey))
542                     if (wtx.GetDepthInMainChain() >= nMinDepth)
543                         nAmount += txout.nValue;
544         }
545     }
546
547     return (double)nAmount / (double)COIN;
548 }
549
550
551 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
552 {
553     // Get the set of pub keys that have the account
554     set<CScript> setPubKey;
555     CRITICAL_BLOCK(cs_mapAddressBook)
556     {
557         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
558         {
559             const string& strAddress = item.first;
560             const string& strName = item.second;
561             if (strName == strAccount)
562             {
563                 // We're only counting our own valid bitcoin addresses and not ip addresses
564                 CScript scriptPubKey;
565                 if (scriptPubKey.SetBitcoinAddress(strAddress))
566                     if (IsMine(scriptPubKey))
567                         setPubKey.insert(scriptPubKey);
568             }
569         }
570     }
571
572     int64 nBalance = 0;
573     CRITICAL_BLOCK(cs_mapWallet)
574     {
575         // Tally wallet transactions
576         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
577         {
578             const CWalletTx& wtx = (*it).second;
579             if (!wtx.IsFinal())
580                 continue;
581
582             // Count generated blocks to account ""
583             if (wtx.IsCoinBase() && strAccount == "" && wtx.GetBlocksToMaturity() == 0)
584             {
585                 nBalance += wtx.GetCredit();
586                 continue;
587             }
588
589             // Tally received
590             foreach(const CTxOut& txout, wtx.vout)
591                 if (setPubKey.count(txout.scriptPubKey))
592                     if (wtx.GetDepthInMainChain() >= nMinDepth)
593                         nBalance += txout.nValue;
594
595             // Tally sent
596             if (wtx.strFromAccount == strAccount)
597             {
598                 int64 nNet = wtx.GetCredit() - wtx.GetDebit();
599                 if (nNet < 0)
600                     nBalance += nNet;
601             }
602         }
603
604         // Tally internal accounting entries
605         nBalance += walletdb.GetAccountCreditDebit(strAccount);
606     }
607
608     return nBalance;
609 }
610
611 int64 GetAccountBalance(const string& strAccount, int nMinDepth)
612 {
613     CWalletDB walletdb;
614     return GetAccountBalance(walletdb, strAccount, nMinDepth);
615 }
616
617
618 Value getbalance(const Array& params, bool fHelp)
619 {
620     if (fHelp || params.size() < 0 || params.size() > 2)
621         throw runtime_error(
622             "getbalance [account] [minconf=1]\n"
623             "If [account] is not specified, returns the server's total available balance.\n"
624             "If [account] is specified, returns the balance in the account.");
625
626     if (params.size() == 0)
627         return ((double)GetBalance() / (double)COIN);
628
629     string strAccount = params[0].get_str();
630     int nMinDepth = 1;
631     if (params.size() > 1)
632         nMinDepth = params[1].get_int();
633
634     int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
635
636     return (double)nBalance / (double)COIN;
637 }
638
639
640 Value movecmd(const Array& params, bool fHelp)
641 {
642     if (fHelp || params.size() < 3 || params.size() > 5)
643         throw runtime_error(
644             "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
645             "Move from one account in your wallet to another.");
646
647     string strFrom = params[0].get_str();
648     string strTo = params[1].get_str();
649     int64 nAmount = AmountFromValue(params[2]);
650     int nMinDepth = 1;
651     if (params.size() > 3)
652         nMinDepth = params[3].get_int();
653     string strComment;
654     if (params.size() > 4)
655         strComment = params[4].get_str();
656
657     CRITICAL_BLOCK(cs_mapWallet)
658     {
659         CWalletDB walletdb;
660         walletdb.TxnBegin();
661
662         // Check funds
663         if (!strFrom.empty())
664         {
665             int64 nBalance = GetAccountBalance(walletdb, strFrom, nMinDepth);
666             if (nAmount > nBalance)
667                 throw JSONRPCError(-6, "Account has insufficient funds");
668         }
669         else
670         {
671             // move from "" account special case
672             int64 nBalance = GetAccountBalance(walletdb, strTo, nMinDepth);
673             if (nAmount > GetBalance() - nBalance)
674                 throw JSONRPCError(-6, "Account has insufficient funds");
675         }
676
677         int64 nNow = GetAdjustedTime();
678
679         // Debit
680         CAccountingEntry debit;
681         debit.nCreditDebit = -nAmount;
682         debit.nTime = nNow;
683         debit.strOtherAccount = strTo;
684         debit.strComment = strComment;
685         walletdb.WriteAccountingEntry(strFrom, debit);
686
687         // Credit
688         CAccountingEntry credit;
689         credit.nCreditDebit = nAmount;
690         credit.nTime = nNow;
691         credit.strOtherAccount = strFrom;
692         credit.strComment = strComment;
693         walletdb.WriteAccountingEntry(strTo, credit);
694
695         walletdb.TxnCommit();
696     }
697     return true;
698 }
699
700
701 Value sendfrom(const Array& params, bool fHelp)
702 {
703     if (fHelp || params.size() < 3 || params.size() > 6)
704         throw runtime_error(
705             "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
706             "<amount> is a real and is rounded to the nearest 0.01");
707
708     string strAccount = params[0].get_str();
709     string strAddress = params[1].get_str();
710     int64 nAmount = AmountFromValue(params[2]);
711     int nMinDepth = 1;
712     if (params.size() > 3)
713         nMinDepth = params[3].get_int();
714
715     CWalletTx wtx;
716     wtx.strFromAccount = strAccount;
717     if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
718         wtx.mapValue["message"] = params[4].get_str();
719     if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
720         wtx.mapValue["to"]      = params[5].get_str();
721
722     CRITICAL_BLOCK(cs_mapWallet)
723     {
724         // Check funds
725         int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
726         if (nAmount > nBalance)
727             throw JSONRPCError(-6, "Account has insufficient funds");
728
729         // Send
730         string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
731         if (strError != "")
732             throw JSONRPCError(-4, strError);
733     }
734
735     return wtx.GetHash().GetHex();
736 }
737
738
739
740 struct tallyitem
741 {
742     int64 nAmount;
743     int nConf;
744     tallyitem()
745     {
746         nAmount = 0;
747         nConf = INT_MAX;
748     }
749 };
750
751 Value ListReceived(const Array& params, bool fByAccounts)
752 {
753     // Minimum confirmations
754     int nMinDepth = 1;
755     if (params.size() > 0)
756         nMinDepth = params[0].get_int();
757
758     // Whether to include empty accounts
759     bool fIncludeEmpty = false;
760     if (params.size() > 1)
761         fIncludeEmpty = params[1].get_bool();
762
763     // Tally
764     map<uint160, tallyitem> mapTally;
765     CRITICAL_BLOCK(cs_mapWallet)
766     {
767         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
768         {
769             const CWalletTx& wtx = (*it).second;
770             if (wtx.IsCoinBase() || !wtx.IsFinal())
771                 continue;
772
773             int nDepth = wtx.GetDepthInMainChain();
774             if (nDepth < nMinDepth)
775                 continue;
776
777             foreach(const CTxOut& txout, wtx.vout)
778             {
779                 // Only counting our own bitcoin addresses and not ip addresses
780                 uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
781                 if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
782                     continue;
783
784                 tallyitem& item = mapTally[hash160];
785                 item.nAmount += txout.nValue;
786                 item.nConf = min(item.nConf, nDepth);
787             }
788         }
789     }
790
791     // Reply
792     Array ret;
793     map<string, tallyitem> mapAccountTally;
794     CRITICAL_BLOCK(cs_mapAddressBook)
795     {
796         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)
797         {
798             const string& strAddress = item.first;
799             const string& strAccount = item.second;
800             uint160 hash160;
801             if (!AddressToHash160(strAddress, hash160))
802                 continue;
803             map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
804             if (it == mapTally.end() && !fIncludeEmpty)
805                 continue;
806
807             int64 nAmount = 0;
808             int nConf = INT_MAX;
809             if (it != mapTally.end())
810             {
811                 nAmount = (*it).second.nAmount;
812                 nConf = (*it).second.nConf;
813             }
814
815             if (fByAccounts)
816             {
817                 tallyitem& item = mapAccountTally[strAccount];
818                 item.nAmount += nAmount;
819                 item.nConf = min(item.nConf, nConf);
820             }
821             else
822             {
823                 Object obj;
824                 obj.push_back(Pair("address",       strAddress));
825                 obj.push_back(Pair("account",       strAccount));
826                 obj.push_back(Pair("label",         strAccount)); // deprecated
827                 obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));
828                 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
829                 ret.push_back(obj);
830             }
831         }
832     }
833
834     if (fByAccounts)
835     {
836         for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
837         {
838             int64 nAmount = (*it).second.nAmount;
839             int nConf = (*it).second.nConf;
840             Object obj;
841             obj.push_back(Pair("account",       (*it).first));
842             obj.push_back(Pair("label",         (*it).first)); // deprecated
843             obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));
844             obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
845             ret.push_back(obj);
846         }
847     }
848
849     return ret;
850 }
851
852 Value listreceivedbyaddress(const Array& params, bool fHelp)
853 {
854     if (fHelp || params.size() > 2)
855         throw runtime_error(
856             "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
857             "[minconf] is the minimum number of confirmations before payments are included.\n"
858             "[includeempty] whether to include addresses that haven't received any payments.\n"
859             "Returns an array of objects containing:\n"
860             "  \"address\" : receiving address\n"
861             "  \"account\" : the account of the receiving address\n"
862             "  \"amount\" : total amount received by the address\n"
863             "  \"confirmations\" : number of confirmations of the most recent transaction included");
864
865     return ListReceived(params, false);
866 }
867
868 Value listreceivedbyaccount(const Array& params, bool fHelp)
869 {
870     if (fHelp || params.size() > 2)
871         throw runtime_error(
872             "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
873             "[minconf] is the minimum number of confirmations before payments are included.\n"
874             "[includeempty] whether to include accounts that haven't received any payments.\n"
875             "Returns an array of objects containing:\n"
876             "  \"account\" : the account of the receiving addresses\n"
877             "  \"amount\" : total amount received by addresses with this account\n"
878             "  \"confirmations\" : number of confirmations of the most recent transaction included");
879
880     return ListReceived(params, true);
881 }
882
883
884 Value backupwallet(const Array& params, bool fHelp)
885 {
886     if (fHelp || params.size() != 1)
887         throw runtime_error(
888             "backupwallet <destination>\n"
889             "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
890
891     string strDest = params[0].get_str();
892     BackupWallet(strDest);
893
894     return Value::null;
895 }
896
897
898 Value validateaddress(const Array& params, bool fHelp)
899 {
900     if (fHelp || params.size() != 1)
901         throw runtime_error(
902             "validateaddress <bitcoinaddress>\n"
903             "Return information about <bitcoinaddress>.");
904
905     string strAddress = params[0].get_str();
906     uint160 hash160;
907     bool isValid = AddressToHash160(strAddress, hash160);
908
909     Object ret;
910     ret.push_back(Pair("isvalid", isValid));
911     if (isValid)
912     {
913         // Call Hash160ToAddress() so we always return current ADDRESSVERSION
914         // version of the address:
915         string currentAddress = Hash160ToAddress(hash160);
916         ret.push_back(Pair("address", currentAddress));
917         ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
918         CRITICAL_BLOCK(cs_mapAddressBook)
919         {
920             if (mapAddressBook.count(currentAddress))
921                 ret.push_back(Pair("account", mapAddressBook[currentAddress]));
922         }
923     }
924     return ret;
925 }
926
927
928
929
930
931
932
933
934
935
936
937 //
938 // Call Table
939 //
940
941 pair<string, rpcfn_type> pCallTable[] =
942 {
943     make_pair("help",                  &help),
944     make_pair("stop",                  &stop),
945     make_pair("getblockcount",         &getblockcount),
946     make_pair("getblocknumber",        &getblocknumber),
947     make_pair("getconnectioncount",    &getconnectioncount),
948     make_pair("getdifficulty",         &getdifficulty),
949     make_pair("getgenerate",           &getgenerate),
950     make_pair("setgenerate",           &setgenerate),
951     make_pair("gethashespersec",       &gethashespersec),
952     make_pair("getinfo",               &getinfo),
953     make_pair("getnewaddress",         &getnewaddress),
954     make_pair("getaccountaddress",     &getaccountaddress),
955     make_pair("setaccount",            &setaccount),
956     make_pair("setlabel",              &setaccount), // deprecated
957     make_pair("getaccount",            &getaccount),
958     make_pair("getlabel",              &getaccount), // deprecated
959     make_pair("getaddressesbyaccount", &getaddressesbyaccount),
960     make_pair("getaddressesbylabel",   &getaddressesbyaccount), // deprecated
961     make_pair("sendtoaddress",         &sendtoaddress),
962     make_pair("getamountreceived",     &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
963     make_pair("getallreceived",        &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
964     make_pair("getreceivedbyaddress",  &getreceivedbyaddress),
965     make_pair("getreceivedbyaccount",  &getreceivedbyaccount),
966     make_pair("getreceivedbylabel",    &getreceivedbyaccount), // deprecated
967     make_pair("listreceivedbyaddress", &listreceivedbyaddress),
968     make_pair("listreceivedbyaccount", &listreceivedbyaccount),
969     make_pair("listreceivedbylabel",   &listreceivedbyaccount), // deprecated
970     make_pair("backupwallet",          &backupwallet),
971     make_pair("validateaddress",       &validateaddress),
972     make_pair("getbalance",            &getbalance),
973     make_pair("move",                  &movecmd),
974     make_pair("sendfrom",              &sendfrom),
975 };
976 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
977
978 string pAllowInSafeMode[] =
979 {
980     "help",
981     "stop",
982     "getblockcount",
983     "getblocknumber",
984     "getconnectioncount",
985     "getdifficulty",
986     "getgenerate",
987     "setgenerate",
988     "gethashespersec",
989     "getinfo",
990     "getnewaddress",
991     "getaccountaddress",
992     "setlabel",
993     "getaccount",
994     "getlabel", // deprecated
995     "getaddressesbyaccount",
996     "getaddressesbylabel", // deprecated
997     "backupwallet",
998     "validateaddress",
999 };
1000 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
1001
1002
1003
1004
1005 //
1006 // HTTP protocol
1007 //
1008 // This ain't Apache.  We're just using HTTP header for the length field
1009 // and to be compatible with other JSON-RPC implementations.
1010 //
1011
1012 string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
1013 {
1014     ostringstream s;
1015     s << "POST / HTTP/1.1\r\n"
1016       << "User-Agent: json-rpc/1.0\r\n"
1017       << "Host: 127.0.0.1\r\n"
1018       << "Content-Type: application/json\r\n"
1019       << "Content-Length: " << strMsg.size() << "\r\n"
1020       << "Accept: application/json\r\n";
1021     foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)
1022         s << item.first << ": " << item.second << "\r\n";
1023     s << "\r\n" << strMsg;
1024
1025     return s.str();
1026 }
1027
1028 string rfc1123Time()
1029 {
1030     char buffer[32];
1031     time_t now;
1032     time(&now);
1033     struct tm* now_gmt = gmtime(&now);
1034     strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);
1035     return string(buffer);
1036 }
1037
1038 string HTTPReply(int nStatus, const string& strMsg)
1039 {
1040     if (nStatus == 401)
1041         return strprintf("HTTP/1.0 401 Authorization Required\r\n"
1042             "Date: %s\r\n"
1043             "Server: bitcoin-json-rpc\r\n"
1044             "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
1045             "Content-Type: text/html\r\n"
1046             "Content-Length: 311\r\n"
1047             "\r\n"
1048             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
1049             "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
1050             "<HTML>\r\n"
1051             "<HEAD>\r\n"
1052             "<TITLE>Error</TITLE>\r\n"
1053             "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
1054             "</HEAD>\r\n"
1055             "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
1056             "</HTML>\r\n", rfc1123Time().c_str());
1057     string strStatus;
1058          if (nStatus == 200) strStatus = "OK";
1059     else if (nStatus == 400) strStatus = "Bad Request";
1060     else if (nStatus == 404) strStatus = "Not Found";
1061     else if (nStatus == 500) strStatus = "Internal Server Error";
1062     return strprintf(
1063             "HTTP/1.1 %d %s\r\n"
1064             "Date: %s\r\n"
1065             "Connection: close\r\n"
1066             "Content-Length: %d\r\n"
1067             "Content-Type: application/json\r\n"
1068             "Server: bitcoin-json-rpc/1.0\r\n"
1069             "\r\n"
1070             "%s",
1071         nStatus,
1072         strStatus.c_str(),
1073         rfc1123Time().c_str(),
1074         strMsg.size(),
1075         strMsg.c_str());
1076 }
1077
1078 int ReadHTTPStatus(std::basic_istream<char>& stream)
1079 {
1080     string str;
1081     getline(stream, str);
1082     vector<string> vWords;
1083     boost::split(vWords, str, boost::is_any_of(" "));
1084     if (vWords.size() < 2)
1085         return 500;
1086     return atoi(vWords[1].c_str());
1087 }
1088
1089 int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
1090 {
1091     int nLen = 0;
1092     loop
1093     {
1094         string str;
1095         std::getline(stream, str);
1096         if (str.empty() || str == "\r")
1097             break;
1098         string::size_type nColon = str.find(":");
1099         if (nColon != string::npos)
1100         {
1101             string strHeader = str.substr(0, nColon);
1102             boost::trim(strHeader);
1103             string strValue = str.substr(nColon+1);
1104             boost::trim(strValue);
1105             mapHeadersRet[strHeader] = strValue;
1106             if (strHeader == "Content-Length")
1107                 nLen = atoi(strValue.c_str());
1108         }
1109     }
1110     return nLen;
1111 }
1112
1113 int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
1114 {
1115     mapHeadersRet.clear();
1116     strMessageRet = "";
1117
1118     // Read status
1119     int nStatus = ReadHTTPStatus(stream);
1120
1121     // Read header
1122     int nLen = ReadHTTPHeader(stream, mapHeadersRet);
1123     if (nLen < 0 || nLen > MAX_SIZE)
1124         return 500;
1125
1126     // Read message
1127     if (nLen > 0)
1128     {
1129         vector<char> vch(nLen);
1130         stream.read(&vch[0], nLen);
1131         strMessageRet = string(vch.begin(), vch.end());
1132     }
1133
1134     return nStatus;
1135 }
1136
1137 string EncodeBase64(string s)
1138 {
1139     BIO *b64, *bmem;
1140     BUF_MEM *bptr;
1141
1142     b64 = BIO_new(BIO_f_base64());
1143     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1144     bmem = BIO_new(BIO_s_mem());
1145     b64 = BIO_push(b64, bmem);
1146     BIO_write(b64, s.c_str(), s.size());
1147     BIO_flush(b64);
1148     BIO_get_mem_ptr(b64, &bptr);
1149
1150     string result(bptr->data, bptr->length);
1151     BIO_free_all(b64);
1152
1153     return result;
1154 }
1155
1156 string DecodeBase64(string s)
1157 {
1158     BIO *b64, *bmem;
1159
1160     char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
1161
1162     b64 = BIO_new(BIO_f_base64());
1163     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1164     bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
1165     bmem = BIO_push(b64, bmem);
1166     BIO_read(bmem, buffer, s.size());
1167     BIO_free_all(bmem);
1168
1169     string result(buffer);
1170     free(buffer);
1171     return result;
1172 }
1173
1174 bool HTTPAuthorized(map<string, string>& mapHeaders)
1175 {
1176     string strAuth = mapHeaders["Authorization"];
1177     if (strAuth.substr(0,6) != "Basic ")
1178         return false;
1179     string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
1180     string strUserPass = DecodeBase64(strUserPass64);
1181     string::size_type nColon = strUserPass.find(":");
1182     if (nColon == string::npos)
1183         return false;
1184     string strUser = strUserPass.substr(0, nColon);
1185     string strPassword = strUserPass.substr(nColon+1);
1186     return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
1187 }
1188
1189 //
1190 // JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,
1191 // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
1192 // unspecified (HTTP errors and contents of 'error').
1193 //
1194 // 1.0 spec: http://json-rpc.org/wiki/specification
1195 // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
1196 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
1197 //
1198
1199 string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
1200 {
1201     Object request;
1202     request.push_back(Pair("method", strMethod));
1203     request.push_back(Pair("params", params));
1204     request.push_back(Pair("id", id));
1205     return write_string(Value(request), false) + "\n";
1206 }
1207
1208 string JSONRPCReply(const Value& result, const Value& error, const Value& id)
1209 {
1210     Object reply;
1211     if (error.type() != null_type)
1212         reply.push_back(Pair("result", Value::null));
1213     else
1214         reply.push_back(Pair("result", result));
1215     reply.push_back(Pair("error", error));
1216     reply.push_back(Pair("id", id));
1217     return write_string(Value(reply), false) + "\n";
1218 }
1219
1220 bool ClientAllowed(const string& strAddress)
1221 {
1222     if (strAddress == asio::ip::address_v4::loopback().to_string())
1223         return true;
1224     const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
1225     foreach(string strAllow, vAllow)
1226         if (WildcardMatch(strAddress, strAllow))
1227             return true;
1228     return false;
1229 }
1230
1231 #ifdef USE_SSL
1232 //
1233 // IOStream device that speaks SSL but can also speak non-SSL
1234 //
1235 class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
1236 public:
1237     SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
1238     {
1239         fUseSSL = fUseSSLIn;
1240         fNeedHandshake = fUseSSLIn;
1241     }
1242
1243     void handshake(ssl::stream_base::handshake_type role)
1244     {
1245         if (!fNeedHandshake) return;
1246         fNeedHandshake = false;
1247         stream.handshake(role);
1248     }
1249     std::streamsize read(char* s, std::streamsize n)
1250     {
1251         handshake(ssl::stream_base::server); // HTTPS servers read first
1252         if (fUseSSL) return stream.read_some(asio::buffer(s, n));
1253         return stream.next_layer().read_some(asio::buffer(s, n));
1254     }
1255     std::streamsize write(const char* s, std::streamsize n)
1256     {
1257         handshake(ssl::stream_base::client); // HTTPS clients write first
1258         if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
1259         return asio::write(stream.next_layer(), asio::buffer(s, n));
1260     }
1261     bool connect(const std::string& server, const std::string& port)
1262     {
1263         ip::tcp::resolver resolver(stream.get_io_service());
1264         ip::tcp::resolver::query query(server.c_str(), port.c_str());
1265         ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
1266         ip::tcp::resolver::iterator end;
1267         boost::system::error_code error = asio::error::host_not_found;
1268         while (error && endpoint_iterator != end)
1269         {
1270             stream.lowest_layer().close();
1271             stream.lowest_layer().connect(*endpoint_iterator++, error);
1272         }
1273         if (error)
1274             return false;
1275         return true;
1276     }
1277
1278 private:
1279     bool fNeedHandshake;
1280     bool fUseSSL;
1281     SSLStream& stream;
1282 };
1283 #endif
1284
1285 void ThreadRPCServer(void* parg)
1286 {
1287     IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
1288     try
1289     {
1290         vnThreadsRunning[4]++;
1291         ThreadRPCServer2(parg);
1292         vnThreadsRunning[4]--;
1293     }
1294     catch (std::exception& e) {
1295         vnThreadsRunning[4]--;
1296         PrintException(&e, "ThreadRPCServer()");
1297     } catch (...) {
1298         vnThreadsRunning[4]--;
1299         PrintException(NULL, "ThreadRPCServer()");
1300     }
1301     printf("ThreadRPCServer exiting\n");
1302 }
1303
1304 void ThreadRPCServer2(void* parg)
1305 {
1306     printf("ThreadRPCServer started\n");
1307
1308     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1309     {
1310         string strWhatAmI = "To use bitcoind";
1311         if (mapArgs.count("-server"))
1312             strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
1313         else if (mapArgs.count("-daemon"))
1314             strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
1315         PrintConsole(
1316             _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
1317               "If the file does not exist, create it with owner-readable-only file permissions.\n"),
1318                 strWhatAmI.c_str(),
1319                 GetConfigFile().c_str());
1320         CreateThread(Shutdown, NULL);
1321         return;
1322     }
1323
1324     bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1325     asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
1326
1327     asio::io_service io_service;
1328     ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
1329     ip::tcp::acceptor acceptor(io_service, endpoint);
1330
1331 #ifdef USE_SSL
1332     ssl::context context(io_service, ssl::context::sslv23);
1333     if (fUseSSL)
1334     {
1335         context.set_options(ssl::context::no_sslv2);
1336         filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
1337         if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
1338         if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
1339         else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
1340         filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
1341         if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
1342         if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
1343         else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
1344
1345         string ciphers = GetArg("-rpcsslciphers",
1346                                          "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
1347         SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
1348     }
1349 #else
1350     if (fUseSSL)
1351         throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1352 #endif
1353
1354     loop
1355     {
1356         // Accept connection
1357 #ifdef USE_SSL
1358         SSLStream sslStream(io_service, context);
1359         SSLIOStreamDevice d(sslStream, fUseSSL);
1360         iostreams::stream<SSLIOStreamDevice> stream(d);
1361 #else
1362         ip::tcp::iostream stream;
1363 #endif
1364
1365         ip::tcp::endpoint peer;
1366         vnThreadsRunning[4]--;
1367 #ifdef USE_SSL
1368         acceptor.accept(sslStream.lowest_layer(), peer);
1369 #else
1370         acceptor.accept(*stream.rdbuf(), peer);
1371 #endif
1372         vnThreadsRunning[4]++;
1373         if (fShutdown)
1374             return;
1375
1376         // Restrict callers by IP
1377         if (!ClientAllowed(peer.address().to_string()))
1378             continue;
1379
1380         // Receive request
1381         map<string, string> mapHeaders;
1382         string strRequest;
1383         ReadHTTP(stream, mapHeaders, strRequest);
1384
1385         // Check authorization
1386         if (mapHeaders.count("Authorization") == 0)
1387         {
1388             stream << HTTPReply(401, "") << std::flush;
1389             continue;
1390         }
1391         if (!HTTPAuthorized(mapHeaders))
1392         {
1393             // Deter brute-forcing short passwords
1394             if (mapArgs["-rpcpassword"].size() < 15)
1395                 Sleep(50);
1396
1397             stream << HTTPReply(401, "") << std::flush;
1398             printf("ThreadRPCServer incorrect password attempt\n");
1399             continue;
1400         }
1401
1402         Value id = Value::null;
1403         try
1404         {
1405             // Parse request
1406             Value valRequest;
1407             if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
1408                 throw JSONRPCError(-32700, "Parse error");
1409             const Object& request = valRequest.get_obj();
1410
1411             // Parse id now so errors from here on will have the id
1412             id = find_value(request, "id");
1413
1414             // Parse method
1415             Value valMethod = find_value(request, "method");
1416             if (valMethod.type() == null_type)
1417                 throw JSONRPCError(-32600, "Missing method");
1418             if (valMethod.type() != str_type)
1419                 throw JSONRPCError(-32600, "Method must be a string");
1420             string strMethod = valMethod.get_str();
1421             printf("ThreadRPCServer method=%s\n", strMethod.c_str());
1422
1423             // Parse params
1424             Value valParams = find_value(request, "params");
1425             Array params;
1426             if (valParams.type() == array_type)
1427                 params = valParams.get_array();
1428             else if (valParams.type() == null_type)
1429                 params = Array();
1430             else
1431                 throw JSONRPCError(-32600, "Params must be an array");
1432
1433             // Find method
1434             map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
1435             if (mi == mapCallTable.end())
1436                 throw JSONRPCError(-32601, "Method not found");
1437
1438             // Observe safe mode
1439             string strWarning = GetWarnings("rpc");
1440             if (strWarning != "" && !mapArgs.count("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
1441                 throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
1442
1443             try
1444             {
1445                 // Execute
1446                 Value result = (*(*mi).second)(params, false);
1447
1448                 // Send reply
1449                 string strReply = JSONRPCReply(result, Value::null, id);
1450                 stream << HTTPReply(200, strReply) << std::flush;
1451             }
1452             catch (std::exception& e)
1453             {
1454                 // Send error reply from method
1455                 string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);
1456                 stream << HTTPReply(500, strReply) << std::flush;
1457             }
1458         }
1459         catch (Object& objError)
1460         {
1461             // Send error reply from json-rpc error object
1462             int nStatus = 500;
1463             int code = find_value(objError, "code").get_int();
1464             if (code == -32600) nStatus = 400;
1465             else if (code == -32601) nStatus = 404;
1466             string strReply = JSONRPCReply(Value::null, objError, id);
1467             stream << HTTPReply(nStatus, strReply) << std::flush;
1468         }
1469         catch (std::exception& e)
1470         {
1471             // Send error reply from other json-rpc parsing errors
1472             string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);
1473             stream << HTTPReply(500, strReply) << std::flush;
1474         }
1475     }
1476 }
1477
1478
1479
1480
1481 Object CallRPC(const string& strMethod, const Array& params)
1482 {
1483     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
1484         throw runtime_error(strprintf(
1485             _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
1486               "If the file does not exist, create it with owner-readable-only file permissions."),
1487                 GetConfigFile().c_str()));
1488
1489     // Connect to localhost
1490     bool fUseSSL = (mapArgs.count("-rpcssl") > 0);
1491 #ifdef USE_SSL
1492     asio::io_service io_service;
1493     ssl::context context(io_service, ssl::context::sslv23);
1494     context.set_options(ssl::context::no_sslv2);
1495     SSLStream sslStream(io_service, context);
1496     SSLIOStreamDevice d(sslStream, fUseSSL);
1497     iostreams::stream<SSLIOStreamDevice> stream(d);
1498     if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
1499         throw runtime_error("couldn't connect to server");
1500 #else
1501     if (fUseSSL)
1502         throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");
1503
1504     ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
1505     if (stream.fail())
1506         throw runtime_error("couldn't connect to server");
1507 #endif
1508
1509
1510     // HTTP basic authentication
1511     string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
1512     map<string, string> mapRequestHeaders;
1513     mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
1514
1515     // Send request
1516     string strRequest = JSONRPCRequest(strMethod, params, 1);
1517     string strPost = HTTPPost(strRequest, mapRequestHeaders);
1518     stream << strPost << std::flush;
1519
1520     // Receive reply
1521     map<string, string> mapHeaders;
1522     string strReply;
1523     int nStatus = ReadHTTP(stream, mapHeaders, strReply);
1524     if (nStatus == 401)
1525         throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
1526     else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
1527         throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
1528     else if (strReply.empty())
1529         throw runtime_error("no response from server");
1530
1531     // Parse reply
1532     Value valReply;
1533     if (!read_string(strReply, valReply))
1534         throw runtime_error("couldn't parse reply from server");
1535     const Object& reply = valReply.get_obj();
1536     if (reply.empty())
1537         throw runtime_error("expected reply to have result, error and id properties");
1538
1539     return reply;
1540 }
1541
1542
1543
1544
1545 template<typename T>
1546 void ConvertTo(Value& value)
1547 {
1548     if (value.type() == str_type)
1549     {
1550         // reinterpret string as unquoted json value
1551         Value value2;
1552         if (!read_string(value.get_str(), value2))
1553             throw runtime_error("type mismatch");
1554         value = value2.get_value<T>();
1555     }
1556     else
1557     {
1558         value = value.get_value<T>();
1559     }
1560 }
1561
1562 int CommandLineRPC(int argc, char *argv[])
1563 {
1564     string strPrint;
1565     int nRet = 0;
1566     try
1567     {
1568         // Skip switches
1569         while (argc > 1 && IsSwitchChar(argv[1][0]))
1570         {
1571             argc--;
1572             argv++;
1573         }
1574
1575         // Method
1576         if (argc < 2)
1577             throw runtime_error("too few parameters");
1578         string strMethod = argv[1];
1579
1580         // Parameters default to strings
1581         Array params;
1582         for (int i = 2; i < argc; i++)
1583             params.push_back(argv[i]);
1584         int n = params.size();
1585
1586         //
1587         // Special case non-string parameter types
1588         //
1589         if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
1590         if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
1591         if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
1592         if (strMethod == "listtransactions"       && n > 0) ConvertTo<boost::int64_t>(params[0]);
1593         if (strMethod == "listtransactions"       && n > 1) ConvertTo<bool>(params[1]);
1594         if (strMethod == "getamountreceived"      && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1595         if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
1596         if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
1597         if (strMethod == "getreceivedbylabel"     && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
1598         if (strMethod == "getallreceived"         && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1599         if (strMethod == "getallreceived"         && n > 1) ConvertTo<bool>(params[1]);
1600         if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
1601         if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
1602         if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
1603         if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
1604         if (strMethod == "listreceivedbylabel"    && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
1605         if (strMethod == "listreceivedbylabel"    && n > 1) ConvertTo<bool>(params[1]); // deprecated
1606         if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
1607         if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
1608         if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
1609         if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
1610         if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
1611
1612         // Execute
1613         Object reply = CallRPC(strMethod, params);
1614
1615         // Parse reply
1616         const Value& result = find_value(reply, "result");
1617         const Value& error  = find_value(reply, "error");
1618         const Value& id     = find_value(reply, "id");
1619
1620         if (error.type() != null_type)
1621         {
1622             // Error
1623             strPrint = "error: " + write_string(error, false);
1624             int code = find_value(error.get_obj(), "code").get_int();
1625             nRet = abs(code);
1626         }
1627         else
1628         {
1629             // Result
1630             if (result.type() == null_type)
1631                 strPrint = "";
1632             else if (result.type() == str_type)
1633                 strPrint = result.get_str();
1634             else
1635                 strPrint = write_string(result, true);
1636         }
1637     }
1638     catch (std::exception& e)
1639     {
1640         strPrint = string("error: ") + e.what();
1641         nRet = 87;
1642     }
1643     catch (...)
1644     {
1645         PrintException(NULL, "CommandLineRPC()");
1646     }
1647
1648     if (strPrint != "")
1649     {
1650 #if defined(__WXMSW__) && defined(GUI)
1651         // Windows GUI apps can't print to command line,
1652         // so settle for a message box yuck
1653         MyMessageBox(strPrint, "Bitcoin", wxOK);
1654 #else
1655         fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
1656 #endif
1657     }
1658     return nRet;
1659 }
1660
1661
1662
1663
1664 #ifdef TEST
1665 int main(int argc, char *argv[])
1666 {
1667 #ifdef _MSC_VER
1668     // Turn off microsoft heap dump noise
1669     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1670     _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
1671 #endif
1672     setbuf(stdin, NULL);
1673     setbuf(stdout, NULL);
1674     setbuf(stderr, NULL);
1675
1676     try
1677     {
1678         if (argc >= 2 && string(argv[1]) == "-server")
1679         {
1680             printf("server ready\n");
1681             ThreadRPCServer(NULL);
1682         }
1683         else
1684         {
1685             return CommandLineRPC(argc, argv);
1686         }
1687     }
1688     catch (std::exception& e) {
1689         PrintException(&e, "main()");
1690     } catch (...) {
1691         PrintException(NULL, "main()");
1692     }
1693     return 0;
1694 }
1695 #endif