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