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