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