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