You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rpcwallet.cpp 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include <boost/assign/list_of.hpp>
  6. #include "wallet.h"
  7. #include "walletdb.h"
  8. #include "bitcoinrpc.h"
  9. #include "init.h"
  10. #include "base58.h"
  11. using namespace std;
  12. using namespace boost;
  13. using namespace boost::assign;
  14. using namespace json_spirit;
  15. int64 nWalletUnlockTime;
  16. static CCriticalSection cs_nWalletUnlockTime;
  17. std::string HelpRequiringPassphrase()
  18. {
  19. return pwalletMain->IsCrypted()
  20. ? "\nrequires wallet passphrase to be set with walletpassphrase first"
  21. : "";
  22. }
  23. void EnsureWalletIsUnlocked()
  24. {
  25. if (pwalletMain->IsLocked())
  26. throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
  27. }
  28. void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
  29. {
  30. int confirms = wtx.GetDepthInMainChain();
  31. entry.push_back(Pair("confirmations", confirms));
  32. if (wtx.IsCoinBase())
  33. entry.push_back(Pair("generated", true));
  34. if (confirms)
  35. {
  36. entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
  37. entry.push_back(Pair("blockindex", wtx.nIndex));
  38. entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
  39. }
  40. entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
  41. entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
  42. entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
  43. BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
  44. entry.push_back(Pair(item.first, item.second));
  45. }
  46. string AccountFromValue(const Value& value)
  47. {
  48. string strAccount = value.get_str();
  49. if (strAccount == "*")
  50. throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
  51. return strAccount;
  52. }
  53. Value getinfo(const Array& params, bool fHelp)
  54. {
  55. if (fHelp || params.size() != 0)
  56. throw runtime_error(
  57. "getinfo\n"
  58. "Returns an object containing various state info.");
  59. proxyType proxy;
  60. GetProxy(NET_IPV4, proxy);
  61. Object obj;
  62. obj.push_back(Pair("version", (int)CLIENT_VERSION));
  63. obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
  64. obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
  65. obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
  66. obj.push_back(Pair("blocks", (int)nBestHeight));
  67. obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
  68. obj.push_back(Pair("connections", (int)vNodes.size()));
  69. obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
  70. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  71. obj.push_back(Pair("testnet", TestNet()));
  72. obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
  73. obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
  74. obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
  75. if (pwalletMain->IsCrypted())
  76. obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
  77. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  78. return obj;
  79. }
  80. Value getnewaddress(const Array& params, bool fHelp)
  81. {
  82. if (fHelp || params.size() > 1)
  83. throw runtime_error(
  84. "getnewaddress [account]\n"
  85. "Returns a new Bitcoin address for receiving payments. "
  86. "If [account] is specified (recommended), it is added to the address book "
  87. "so payments received with the address will be credited to [account].");
  88. // Parse the account first so we don't generate a key if there's an error
  89. string strAccount;
  90. if (params.size() > 0)
  91. strAccount = AccountFromValue(params[0]);
  92. if (!pwalletMain->IsLocked())
  93. pwalletMain->TopUpKeyPool();
  94. // Generate a new key that is added to wallet
  95. CPubKey newKey;
  96. if (!pwalletMain->GetKeyFromPool(newKey, false))
  97. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  98. CKeyID keyID = newKey.GetID();
  99. pwalletMain->SetAddressBookName(keyID, strAccount);
  100. return CBitcoinAddress(keyID).ToString();
  101. }
  102. CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
  103. {
  104. CWalletDB walletdb(pwalletMain->strWalletFile);
  105. CAccount account;
  106. walletdb.ReadAccount(strAccount, account);
  107. bool bKeyUsed = false;
  108. // Check if the current key has been used
  109. if (account.vchPubKey.IsValid())
  110. {
  111. CScript scriptPubKey;
  112. scriptPubKey.SetDestination(account.vchPubKey.GetID());
  113. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
  114. it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
  115. ++it)
  116. {
  117. const CWalletTx& wtx = (*it).second;
  118. BOOST_FOREACH(const CTxOut& txout, wtx.vout)
  119. if (txout.scriptPubKey == scriptPubKey)
  120. bKeyUsed = true;
  121. }
  122. }
  123. // Generate a new key
  124. if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
  125. {
  126. if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
  127. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  128. pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
  129. walletdb.WriteAccount(strAccount, account);
  130. }
  131. return CBitcoinAddress(account.vchPubKey.GetID());
  132. }
  133. Value getaccountaddress(const Array& params, bool fHelp)
  134. {
  135. if (fHelp || params.size() != 1)
  136. throw runtime_error(
  137. "getaccountaddress <account>\n"
  138. "Returns the current Bitcoin address for receiving payments to this account.");
  139. // Parse the account first so we don't generate a key if there's an error
  140. string strAccount = AccountFromValue(params[0]);
  141. Value ret;
  142. ret = GetAccountAddress(strAccount).ToString();
  143. return ret;
  144. }
  145. Value setaccount(const Array& params, bool fHelp)
  146. {
  147. if (fHelp || params.size() < 1 || params.size() > 2)
  148. throw runtime_error(
  149. "setaccount <bitcoinaddress> <account>\n"
  150. "Sets the account associated with the given address.");
  151. CBitcoinAddress address(params[0].get_str());
  152. if (!address.IsValid())
  153. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  154. string strAccount;
  155. if (params.size() > 1)
  156. strAccount = AccountFromValue(params[1]);
  157. // Detect when changing the account of an address that is the 'unused current key' of another account:
  158. if (pwalletMain->mapAddressBook.count(address.Get()))
  159. {
  160. string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
  161. if (address == GetAccountAddress(strOldAccount))
  162. GetAccountAddress(strOldAccount, true);
  163. }
  164. pwalletMain->SetAddressBookName(address.Get(), strAccount);
  165. return Value::null;
  166. }
  167. Value getaccount(const Array& params, bool fHelp)
  168. {
  169. if (fHelp || params.size() != 1)
  170. throw runtime_error(
  171. "getaccount <bitcoinaddress>\n"
  172. "Returns the account associated with the given address.");
  173. CBitcoinAddress address(params[0].get_str());
  174. if (!address.IsValid())
  175. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  176. string strAccount;
  177. map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
  178. if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
  179. strAccount = (*mi).second;
  180. return strAccount;
  181. }
  182. Value getaddressesbyaccount(const Array& params, bool fHelp)
  183. {
  184. if (fHelp || params.size() != 1)
  185. throw runtime_error(
  186. "getaddressesbyaccount <account>\n"
  187. "Returns the list of addresses for the given account.");
  188. string strAccount = AccountFromValue(params[0]);
  189. // Find all addresses that have the given account
  190. Array ret;
  191. BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
  192. {
  193. const CBitcoinAddress& address = item.first;
  194. const string& strName = item.second;
  195. if (strName == strAccount)
  196. ret.push_back(address.ToString());
  197. }
  198. return ret;
  199. }
  200. Value sendtoaddress(const Array& params, bool fHelp)
  201. {
  202. if (fHelp || params.size() < 2 || params.size() > 4)
  203. throw runtime_error(
  204. "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
  205. "<amount> is a real and is rounded to the nearest 0.00000001"
  206. + HelpRequiringPassphrase());
  207. CBitcoinAddress address(params[0].get_str());
  208. if (!address.IsValid())
  209. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  210. // Amount
  211. int64 nAmount = AmountFromValue(params[1]);
  212. // Wallet comments
  213. CWalletTx wtx;
  214. if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
  215. wtx.mapValue["comment"] = params[2].get_str();
  216. if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
  217. wtx.mapValue["to"] = params[3].get_str();
  218. if (pwalletMain->IsLocked())
  219. throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
  220. string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
  221. if (strError != "")
  222. throw JSONRPCError(RPC_WALLET_ERROR, strError);
  223. return wtx.GetHash().GetHex();
  224. }
  225. Value listaddressgroupings(const Array& params, bool fHelp)
  226. {
  227. if (fHelp)
  228. throw runtime_error(
  229. "listaddressgroupings\n"
  230. "Lists groups of addresses which have had their common ownership\n"
  231. "made public by common use as inputs or as the resulting change\n"
  232. "in past transactions");
  233. Array jsonGroupings;
  234. map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
  235. BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
  236. {
  237. Array jsonGrouping;
  238. BOOST_FOREACH(CTxDestination address, grouping)
  239. {
  240. Array addressInfo;
  241. addressInfo.push_back(CBitcoinAddress(address).ToString());
  242. addressInfo.push_back(ValueFromAmount(balances[address]));
  243. {
  244. LOCK(pwalletMain->cs_wallet);
  245. if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
  246. addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
  247. }
  248. jsonGrouping.push_back(addressInfo);
  249. }
  250. jsonGroupings.push_back(jsonGrouping);
  251. }
  252. return jsonGroupings;
  253. }
  254. Value signmessage(const Array& params, bool fHelp)
  255. {
  256. if (fHelp || params.size() != 2)
  257. throw runtime_error(
  258. "signmessage <bitcoinaddress> <message>\n"
  259. "Sign a message with the private key of an address");
  260. EnsureWalletIsUnlocked();
  261. string strAddress = params[0].get_str();
  262. string strMessage = params[1].get_str();
  263. CBitcoinAddress addr(strAddress);
  264. if (!addr.IsValid())
  265. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
  266. CKeyID keyID;
  267. if (!addr.GetKeyID(keyID))
  268. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  269. CKey key;
  270. if (!pwalletMain->GetKey(keyID, key))
  271. throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
  272. CHashWriter ss(SER_GETHASH, 0);
  273. ss << strMessageMagic;
  274. ss << strMessage;
  275. vector<unsigned char> vchSig;
  276. if (!key.SignCompact(ss.GetHash(), vchSig))
  277. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
  278. return EncodeBase64(&vchSig[0], vchSig.size());
  279. }
  280. Value verifymessage(const Array& params, bool fHelp)
  281. {
  282. if (fHelp || params.size() != 3)
  283. throw runtime_error(
  284. "verifymessage <bitcoinaddress> <signature> <message>\n"
  285. "Verify a signed message");
  286. string strAddress = params[0].get_str();
  287. string strSign = params[1].get_str();
  288. string strMessage = params[2].get_str();
  289. CBitcoinAddress addr(strAddress);
  290. if (!addr.IsValid())
  291. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
  292. CKeyID keyID;
  293. if (!addr.GetKeyID(keyID))
  294. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  295. bool fInvalid = false;
  296. vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
  297. if (fInvalid)
  298. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
  299. CHashWriter ss(SER_GETHASH, 0);
  300. ss << strMessageMagic;
  301. ss << strMessage;
  302. CPubKey pubkey;
  303. if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
  304. return false;
  305. return (pubkey.GetID() == keyID);
  306. }
  307. Value getreceivedbyaddress(const Array& params, bool fHelp)
  308. {
  309. if (fHelp || params.size() < 1 || params.size() > 2)
  310. throw runtime_error(
  311. "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
  312. "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
  313. // Bitcoin address
  314. CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
  315. CScript scriptPubKey;
  316. if (!address.IsValid())
  317. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  318. scriptPubKey.SetDestination(address.Get());
  319. if (!IsMine(*pwalletMain,scriptPubKey))
  320. return (double)0.0;
  321. // Minimum confirmations
  322. int nMinDepth = 1;
  323. if (params.size() > 1)
  324. nMinDepth = params[1].get_int();
  325. // Tally
  326. int64 nAmount = 0;
  327. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  328. {
  329. const CWalletTx& wtx = (*it).second;
  330. if (wtx.IsCoinBase() || !IsFinalTx(wtx))
  331. continue;
  332. BOOST_FOREACH(const CTxOut& txout, wtx.vout)
  333. if (txout.scriptPubKey == scriptPubKey)
  334. if (wtx.GetDepthInMainChain() >= nMinDepth)
  335. nAmount += txout.nValue;
  336. }
  337. return ValueFromAmount(nAmount);
  338. }
  339. void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
  340. {
  341. BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
  342. {
  343. const CTxDestination& address = item.first;
  344. const string& strName = item.second;
  345. if (strName == strAccount)
  346. setAddress.insert(address);
  347. }
  348. }
  349. Value getreceivedbyaccount(const Array& params, bool fHelp)
  350. {
  351. if (fHelp || params.size() < 1 || params.size() > 2)
  352. throw runtime_error(
  353. "getreceivedbyaccount <account> [minconf=1]\n"
  354. "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
  355. // Minimum confirmations
  356. int nMinDepth = 1;
  357. if (params.size() > 1)
  358. nMinDepth = params[1].get_int();
  359. // Get the set of pub keys assigned to account
  360. string strAccount = AccountFromValue(params[0]);
  361. set<CTxDestination> setAddress;
  362. GetAccountAddresses(strAccount, setAddress);
  363. // Tally
  364. int64 nAmount = 0;
  365. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  366. {
  367. const CWalletTx& wtx = (*it).second;
  368. if (wtx.IsCoinBase() || !IsFinalTx(wtx))
  369. continue;
  370. BOOST_FOREACH(const CTxOut& txout, wtx.vout)
  371. {
  372. CTxDestination address;
  373. if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
  374. if (wtx.GetDepthInMainChain() >= nMinDepth)
  375. nAmount += txout.nValue;
  376. }
  377. }
  378. return (double)nAmount / (double)COIN;
  379. }
  380. int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
  381. {
  382. int64 nBalance = 0;
  383. // Tally wallet transactions
  384. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  385. {
  386. const CWalletTx& wtx = (*it).second;
  387. if (!IsFinalTx(wtx))
  388. continue;
  389. int64 nReceived, nSent, nFee;
  390. wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee);
  391. if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
  392. nBalance += nReceived;
  393. nBalance -= nSent + nFee;
  394. }
  395. // Tally internal accounting entries
  396. nBalance += walletdb.GetAccountCreditDebit(strAccount);
  397. return nBalance;
  398. }
  399. int64 GetAccountBalance(const string& strAccount, int nMinDepth)
  400. {
  401. CWalletDB walletdb(pwalletMain->strWalletFile);
  402. return GetAccountBalance(walletdb, strAccount, nMinDepth);
  403. }
  404. Value getbalance(const Array& params, bool fHelp)
  405. {
  406. if (fHelp || params.size() > 2)
  407. throw runtime_error(
  408. "getbalance [account] [minconf=1]\n"
  409. "If [account] is not specified, returns the server's total available balance.\n"
  410. "If [account] is specified, returns the balance in the account.");
  411. if (params.size() == 0)
  412. return ValueFromAmount(pwalletMain->GetBalance());
  413. int nMinDepth = 1;
  414. if (params.size() > 1)
  415. nMinDepth = params[1].get_int();
  416. if (params[0].get_str() == "*") {
  417. // Calculate total balance a different way from GetBalance()
  418. // (GetBalance() sums up all unspent TxOuts)
  419. // getbalance and getbalance '*' 0 should return the same number
  420. int64 nBalance = 0;
  421. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  422. {
  423. const CWalletTx& wtx = (*it).second;
  424. if (!wtx.IsConfirmed())
  425. continue;
  426. int64 allFee;
  427. string strSentAccount;
  428. list<pair<CTxDestination, int64> > listReceived;
  429. list<pair<CTxDestination, int64> > listSent;
  430. wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount);
  431. if (wtx.GetDepthInMainChain() >= nMinDepth)
  432. {
  433. BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
  434. nBalance += r.second;
  435. }
  436. BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
  437. nBalance -= r.second;
  438. nBalance -= allFee;
  439. }
  440. return ValueFromAmount(nBalance);
  441. }
  442. string strAccount = AccountFromValue(params[0]);
  443. int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
  444. return ValueFromAmount(nBalance);
  445. }
  446. Value movecmd(const Array& params, bool fHelp)
  447. {
  448. if (fHelp || params.size() < 3 || params.size() > 5)
  449. throw runtime_error(
  450. "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
  451. "Move from one account in your wallet to another.");
  452. string strFrom = AccountFromValue(params[0]);
  453. string strTo = AccountFromValue(params[1]);
  454. int64 nAmount = AmountFromValue(params[2]);
  455. if (params.size() > 3)
  456. // unused parameter, used to be nMinDepth, keep type-checking it though
  457. (void)params[3].get_int();
  458. string strComment;
  459. if (params.size() > 4)
  460. strComment = params[4].get_str();
  461. CWalletDB walletdb(pwalletMain->strWalletFile);
  462. if (!walletdb.TxnBegin())
  463. throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
  464. int64 nNow = GetAdjustedTime();
  465. // Debit
  466. CAccountingEntry debit;
  467. debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
  468. debit.strAccount = strFrom;
  469. debit.nCreditDebit = -nAmount;
  470. debit.nTime = nNow;
  471. debit.strOtherAccount = strTo;
  472. debit.strComment = strComment;
  473. walletdb.WriteAccountingEntry(debit);
  474. // Credit
  475. CAccountingEntry credit;
  476. credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
  477. credit.strAccount = strTo;
  478. credit.nCreditDebit = nAmount;
  479. credit.nTime = nNow;
  480. credit.strOtherAccount = strFrom;
  481. credit.strComment = strComment;
  482. walletdb.WriteAccountingEntry(credit);
  483. if (!walletdb.TxnCommit())
  484. throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
  485. return true;
  486. }
  487. Value sendfrom(const Array& params, bool fHelp)
  488. {
  489. if (fHelp || params.size() < 3 || params.size() > 6)
  490. throw runtime_error(
  491. "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
  492. "<amount> is a real and is rounded to the nearest 0.00000001"
  493. + HelpRequiringPassphrase());
  494. string strAccount = AccountFromValue(params[0]);
  495. CBitcoinAddress address(params[1].get_str());
  496. if (!address.IsValid())
  497. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  498. int64 nAmount = AmountFromValue(params[2]);
  499. int nMinDepth = 1;
  500. if (params.size() > 3)
  501. nMinDepth = params[3].get_int();
  502. CWalletTx wtx;
  503. wtx.strFromAccount = strAccount;
  504. if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
  505. wtx.mapValue["comment"] = params[4].get_str();
  506. if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
  507. wtx.mapValue["to"] = params[5].get_str();
  508. EnsureWalletIsUnlocked();
  509. // Check funds
  510. int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
  511. if (nAmount > nBalance)
  512. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  513. // Send
  514. string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
  515. if (strError != "")
  516. throw JSONRPCError(RPC_WALLET_ERROR, strError);
  517. return wtx.GetHash().GetHex();
  518. }
  519. Value sendmany(const Array& params, bool fHelp)
  520. {
  521. if (fHelp || params.size() < 2 || params.size() > 4)
  522. throw runtime_error(
  523. "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
  524. "amounts are double-precision floating point numbers"
  525. + HelpRequiringPassphrase());
  526. string strAccount = AccountFromValue(params[0]);
  527. Object sendTo = params[1].get_obj();
  528. int nMinDepth = 1;
  529. if (params.size() > 2)
  530. nMinDepth = params[2].get_int();
  531. CWalletTx wtx;
  532. wtx.strFromAccount = strAccount;
  533. if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
  534. wtx.mapValue["comment"] = params[3].get_str();
  535. set<CBitcoinAddress> setAddress;
  536. vector<pair<CScript, int64> > vecSend;
  537. int64 totalAmount = 0;
  538. BOOST_FOREACH(const Pair& s, sendTo)
  539. {
  540. CBitcoinAddress address(s.name_);
  541. if (!address.IsValid())
  542. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+s.name_);
  543. if (setAddress.count(address))
  544. throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
  545. setAddress.insert(address);
  546. CScript scriptPubKey;
  547. scriptPubKey.SetDestination(address.Get());
  548. int64 nAmount = AmountFromValue(s.value_);
  549. totalAmount += nAmount;
  550. vecSend.push_back(make_pair(scriptPubKey, nAmount));
  551. }
  552. EnsureWalletIsUnlocked();
  553. // Check funds
  554. int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
  555. if (totalAmount > nBalance)
  556. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  557. // Send
  558. CReserveKey keyChange(pwalletMain);
  559. int64 nFeeRequired = 0;
  560. string strFailReason;
  561. bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
  562. if (!fCreated)
  563. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
  564. if (!pwalletMain->CommitTransaction(wtx, keyChange))
  565. throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
  566. return wtx.GetHash().GetHex();
  567. }
  568. //
  569. // Used by addmultisigaddress / createmultisig:
  570. //
  571. static CScript _createmultisig(const Array& params)
  572. {
  573. int nRequired = params[0].get_int();
  574. const Array& keys = params[1].get_array();
  575. // Gather public keys
  576. if (nRequired < 1)
  577. throw runtime_error("a multisignature address must require at least one key to redeem");
  578. if ((int)keys.size() < nRequired)
  579. throw runtime_error(
  580. strprintf("not enough keys supplied "
  581. "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
  582. std::vector<CPubKey> pubkeys;
  583. pubkeys.resize(keys.size());
  584. for (unsigned int i = 0; i < keys.size(); i++)
  585. {
  586. const std::string& ks = keys[i].get_str();
  587. // Case 1: Bitcoin address and we have full public key:
  588. CBitcoinAddress address(ks);
  589. if (address.IsValid())
  590. {
  591. CKeyID keyID;
  592. if (!address.GetKeyID(keyID))
  593. throw runtime_error(
  594. strprintf("%s does not refer to a key",ks.c_str()));
  595. CPubKey vchPubKey;
  596. if (!pwalletMain->GetPubKey(keyID, vchPubKey))
  597. throw runtime_error(
  598. strprintf("no full public key for address %s",ks.c_str()));
  599. if (!vchPubKey.IsFullyValid())
  600. throw runtime_error(" Invalid public key: "+ks);
  601. pubkeys[i] = vchPubKey;
  602. }
  603. // Case 2: hex public key
  604. else if (IsHex(ks))
  605. {
  606. CPubKey vchPubKey(ParseHex(ks));
  607. if (!vchPubKey.IsFullyValid())
  608. throw runtime_error(" Invalid public key: "+ks);
  609. pubkeys[i] = vchPubKey;
  610. }
  611. else
  612. {
  613. throw runtime_error(" Invalid public key: "+ks);
  614. }
  615. }
  616. CScript result;
  617. result.SetMultisig(nRequired, pubkeys);
  618. return result;
  619. }
  620. Value addmultisigaddress(const Array& params, bool fHelp)
  621. {
  622. if (fHelp || params.size() < 2 || params.size() > 3)
  623. {
  624. string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
  625. "Add a nrequired-to-sign multisignature address to the wallet\"\n"
  626. "each key is a Bitcoin address or hex-encoded public key\n"
  627. "If [account] is specified, assign address to [account].";
  628. throw runtime_error(msg);
  629. }
  630. string strAccount;
  631. if (params.size() > 2)
  632. strAccount = AccountFromValue(params[2]);
  633. // Construct using pay-to-script-hash:
  634. CScript inner = _createmultisig(params);
  635. CScriptID innerID = inner.GetID();
  636. pwalletMain->AddCScript(inner);
  637. pwalletMain->SetAddressBookName(innerID, strAccount);
  638. return CBitcoinAddress(innerID).ToString();
  639. }
  640. Value createmultisig(const Array& params, bool fHelp)
  641. {
  642. if (fHelp || params.size() < 2 || params.size() > 2)
  643. {
  644. string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
  645. "Creates a multi-signature address and returns a json object\n"
  646. "with keys:\n"
  647. "address : bitcoin address\n"
  648. "redeemScript : hex-encoded redemption script";
  649. throw runtime_error(msg);
  650. }
  651. // Construct using pay-to-script-hash:
  652. CScript inner = _createmultisig(params);
  653. CScriptID innerID = inner.GetID();
  654. CBitcoinAddress address(innerID);
  655. Object result;
  656. result.push_back(Pair("address", address.ToString()));
  657. result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
  658. return result;
  659. }
  660. struct tallyitem
  661. {
  662. int64 nAmount;
  663. int nConf;
  664. vector<uint256> txids;
  665. tallyitem()
  666. {
  667. nAmount = 0;
  668. nConf = std::numeric_limits<int>::max();
  669. }
  670. };
  671. Value ListReceived(const Array& params, bool fByAccounts)
  672. {
  673. // Minimum confirmations
  674. int nMinDepth = 1;
  675. if (params.size() > 0)
  676. nMinDepth = params[0].get_int();
  677. // Whether to include empty accounts
  678. bool fIncludeEmpty = false;
  679. if (params.size() > 1)
  680. fIncludeEmpty = params[1].get_bool();
  681. // Tally
  682. map<CBitcoinAddress, tallyitem> mapTally;
  683. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  684. {
  685. const CWalletTx& wtx = (*it).second;
  686. if (wtx.IsCoinBase() || !IsFinalTx(wtx))
  687. continue;
  688. int nDepth = wtx.GetDepthInMainChain();
  689. if (nDepth < nMinDepth)
  690. continue;
  691. BOOST_FOREACH(const CTxOut& txout, wtx.vout)
  692. {
  693. CTxDestination address;
  694. if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
  695. continue;
  696. tallyitem& item = mapTally[address];
  697. item.nAmount += txout.nValue;
  698. item.nConf = min(item.nConf, nDepth);
  699. item.txids.push_back(wtx.GetHash());
  700. }
  701. }
  702. // Reply
  703. Array ret;
  704. map<string, tallyitem> mapAccountTally;
  705. BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
  706. {
  707. const CBitcoinAddress& address = item.first;
  708. const string& strAccount = item.second;
  709. map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
  710. if (it == mapTally.end() && !fIncludeEmpty)
  711. continue;
  712. int64 nAmount = 0;
  713. int nConf = std::numeric_limits<int>::max();
  714. if (it != mapTally.end())
  715. {
  716. nAmount = (*it).second.nAmount;
  717. nConf = (*it).second.nConf;
  718. }
  719. if (fByAccounts)
  720. {
  721. tallyitem& item = mapAccountTally[strAccount];
  722. item.nAmount += nAmount;
  723. item.nConf = min(item.nConf, nConf);
  724. }
  725. else
  726. {
  727. Object obj;
  728. obj.push_back(Pair("address", address.ToString()));
  729. obj.push_back(Pair("account", strAccount));
  730. obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
  731. obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
  732. Array transactions;
  733. if (it != mapTally.end())
  734. {
  735. BOOST_FOREACH(const uint256& item, (*it).second.txids)
  736. {
  737. transactions.push_back(item.GetHex());
  738. }
  739. }
  740. obj.push_back(Pair("txids", transactions));
  741. ret.push_back(obj);
  742. }
  743. }
  744. if (fByAccounts)
  745. {
  746. for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
  747. {
  748. int64 nAmount = (*it).second.nAmount;
  749. int nConf = (*it).second.nConf;
  750. Object obj;
  751. obj.push_back(Pair("account", (*it).first));
  752. obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
  753. obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
  754. ret.push_back(obj);
  755. }
  756. }
  757. return ret;
  758. }
  759. Value listreceivedbyaddress(const Array& params, bool fHelp)
  760. {
  761. if (fHelp || params.size() > 2)
  762. throw runtime_error(
  763. "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
  764. "[minconf] is the minimum number of confirmations before payments are included.\n"
  765. "[includeempty] whether to include addresses that haven't received any payments.\n"
  766. "Returns an array of objects containing:\n"
  767. " \"address\" : receiving address\n"
  768. " \"account\" : the account of the receiving address\n"
  769. " \"amount\" : total amount received by the address\n"
  770. " \"confirmations\" : number of confirmations of the most recent transaction included\n"
  771. " \"txids\" : list of transactions with outputs to the address\n");
  772. return ListReceived(params, false);
  773. }
  774. Value listreceivedbyaccount(const Array& params, bool fHelp)
  775. {
  776. if (fHelp || params.size() > 2)
  777. throw runtime_error(
  778. "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
  779. "[minconf] is the minimum number of confirmations before payments are included.\n"
  780. "[includeempty] whether to include accounts that haven't received any payments.\n"
  781. "Returns an array of objects containing:\n"
  782. " \"account\" : the account of the receiving addresses\n"
  783. " \"amount\" : total amount received by addresses with this account\n"
  784. " \"confirmations\" : number of confirmations of the most recent transaction included");
  785. return ListReceived(params, true);
  786. }
  787. void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
  788. {
  789. int64 nFee;
  790. string strSentAccount;
  791. list<pair<CTxDestination, int64> > listReceived;
  792. list<pair<CTxDestination, int64> > listSent;
  793. wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
  794. bool fAllAccounts = (strAccount == string("*"));
  795. // Sent
  796. if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
  797. {
  798. BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
  799. {
  800. Object entry;
  801. entry.push_back(Pair("account", strSentAccount));
  802. entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
  803. entry.push_back(Pair("category", "send"));
  804. entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
  805. entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
  806. if (fLong)
  807. WalletTxToJSON(wtx, entry);
  808. ret.push_back(entry);
  809. }
  810. }
  811. // Received
  812. if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
  813. {
  814. BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
  815. {
  816. string account;
  817. if (pwalletMain->mapAddressBook.count(r.first))
  818. account = pwalletMain->mapAddressBook[r.first];
  819. if (fAllAccounts || (account == strAccount))
  820. {
  821. Object entry;
  822. entry.push_back(Pair("account", account));
  823. entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
  824. if (wtx.IsCoinBase())
  825. {
  826. if (wtx.GetDepthInMainChain() < 1)
  827. entry.push_back(Pair("category", "orphan"));
  828. else if (wtx.GetBlocksToMaturity() > 0)
  829. entry.push_back(Pair("category", "immature"));
  830. else
  831. entry.push_back(Pair("category", "generate"));
  832. }
  833. else
  834. entry.push_back(Pair("category", "receive"));
  835. entry.push_back(Pair("amount", ValueFromAmount(r.second)));
  836. if (fLong)
  837. WalletTxToJSON(wtx, entry);
  838. ret.push_back(entry);
  839. }
  840. }
  841. }
  842. }
  843. void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
  844. {
  845. bool fAllAccounts = (strAccount == string("*"));
  846. if (fAllAccounts || acentry.strAccount == strAccount)
  847. {
  848. Object entry;
  849. entry.push_back(Pair("account", acentry.strAccount));
  850. entry.push_back(Pair("category", "move"));
  851. entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
  852. entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
  853. entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
  854. entry.push_back(Pair("comment", acentry.strComment));
  855. ret.push_back(entry);
  856. }
  857. }
  858. Value listtransactions(const Array& params, bool fHelp)
  859. {
  860. if (fHelp || params.size() > 3)
  861. throw runtime_error(
  862. "listtransactions [account] [count=10] [from=0]\n"
  863. "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
  864. string strAccount = "*";
  865. if (params.size() > 0)
  866. strAccount = params[0].get_str();
  867. int nCount = 10;
  868. if (params.size() > 1)
  869. nCount = params[1].get_int();
  870. int nFrom = 0;
  871. if (params.size() > 2)
  872. nFrom = params[2].get_int();
  873. if (nCount < 0)
  874. throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
  875. if (nFrom < 0)
  876. throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
  877. Array ret;
  878. std::list<CAccountingEntry> acentries;
  879. CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
  880. // iterate backwards until we have nCount items to return:
  881. for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
  882. {
  883. CWalletTx *const pwtx = (*it).second.first;
  884. if (pwtx != 0)
  885. ListTransactions(*pwtx, strAccount, 0, true, ret);
  886. CAccountingEntry *const pacentry = (*it).second.second;
  887. if (pacentry != 0)
  888. AcentryToJSON(*pacentry, strAccount, ret);
  889. if ((int)ret.size() >= (nCount+nFrom)) break;
  890. }
  891. // ret is newest to oldest
  892. if (nFrom > (int)ret.size())
  893. nFrom = ret.size();
  894. if ((nFrom + nCount) > (int)ret.size())
  895. nCount = ret.size() - nFrom;
  896. Array::iterator first = ret.begin();
  897. std::advance(first, nFrom);
  898. Array::iterator last = ret.begin();
  899. std::advance(last, nFrom+nCount);
  900. if (last != ret.end()) ret.erase(last, ret.end());
  901. if (first != ret.begin()) ret.erase(ret.begin(), first);
  902. std::reverse(ret.begin(), ret.end()); // Return oldest to newest
  903. return ret;
  904. }
  905. Value listaccounts(const Array& params, bool fHelp)
  906. {
  907. if (fHelp || params.size() > 1)
  908. throw runtime_error(
  909. "listaccounts [minconf=1]\n"
  910. "Returns Object that has account names as keys, account balances as values.");
  911. int nMinDepth = 1;
  912. if (params.size() > 0)
  913. nMinDepth = params[0].get_int();
  914. map<string, int64> mapAccountBalances;
  915. BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
  916. if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
  917. mapAccountBalances[entry.second] = 0;
  918. }
  919. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
  920. {
  921. const CWalletTx& wtx = (*it).second;
  922. int64 nFee;
  923. string strSentAccount;
  924. list<pair<CTxDestination, int64> > listReceived;
  925. list<pair<CTxDestination, int64> > listSent;
  926. wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
  927. mapAccountBalances[strSentAccount] -= nFee;
  928. BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
  929. mapAccountBalances[strSentAccount] -= s.second;
  930. if (wtx.GetDepthInMainChain() >= nMinDepth)
  931. {
  932. BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
  933. if (pwalletMain->mapAddressBook.count(r.first))
  934. mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
  935. else
  936. mapAccountBalances[""] += r.second;
  937. }
  938. }
  939. list<CAccountingEntry> acentries;
  940. CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
  941. BOOST_FOREACH(const CAccountingEntry& entry, acentries)
  942. mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
  943. Object ret;
  944. BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
  945. ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
  946. }
  947. return ret;
  948. }
  949. Value listsinceblock(const Array& params, bool fHelp)
  950. {
  951. if (fHelp)
  952. throw runtime_error(
  953. "listsinceblock [blockhash] [target-confirmations]\n"
  954. "Get all transactions in blocks since block [blockhash], or all transactions if omitted");
  955. CBlockIndex *pindex = NULL;
  956. int target_confirms = 1;
  957. if (params.size() > 0)
  958. {
  959. uint256 blockId = 0;
  960. blockId.SetHex(params[0].get_str());
  961. pindex = CBlockLocator(blockId).GetBlockIndex();
  962. }
  963. if (params.size() > 1)
  964. {
  965. target_confirms = params[1].get_int();
  966. if (target_confirms < 1)
  967. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
  968. }
  969. int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
  970. Array transactions;
  971. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
  972. {
  973. CWalletTx tx = (*it).second;
  974. if (depth == -1 || tx.GetDepthInMainChain() < depth)
  975. ListTransactions(tx, "*", 0, true, transactions);
  976. }
  977. uint256 lastblock;
  978. if (target_confirms == 1)
  979. {
  980. lastblock = hashBestChain;
  981. }
  982. else
  983. {
  984. int target_height = pindexBest->nHeight + 1 - target_confirms;
  985. CBlockIndex *block;
  986. for (block = pindexBest;
  987. block && block->nHeight > target_height;
  988. block = block->pprev) { }
  989. lastblock = block ? block->GetBlockHash() : 0;
  990. }
  991. Object ret;
  992. ret.push_back(Pair("transactions", transactions));
  993. ret.push_back(Pair("lastblock", lastblock.GetHex()));
  994. return ret;
  995. }
  996. Value gettransaction(const Array& params, bool fHelp)
  997. {
  998. if (fHelp || params.size() != 1)
  999. throw runtime_error(
  1000. "gettransaction <txid>\n"
  1001. "Get detailed information about in-wallet transaction <txid>");
  1002. uint256 hash;
  1003. hash.SetHex(params[0].get_str());
  1004. Object entry;
  1005. if (!pwalletMain->mapWallet.count(hash))
  1006. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
  1007. const CWalletTx& wtx = pwalletMain->mapWallet[hash];
  1008. int64 nCredit = wtx.GetCredit();
  1009. int64 nDebit = wtx.GetDebit();
  1010. int64 nNet = nCredit - nDebit;
  1011. int64 nFee = (wtx.IsFromMe() ? GetValueOut(wtx) - nDebit : 0);
  1012. entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
  1013. if (wtx.IsFromMe())
  1014. entry.push_back(Pair("fee", ValueFromAmount(nFee)));
  1015. WalletTxToJSON(wtx, entry);
  1016. Array details;
  1017. ListTransactions(wtx, "*", 0, false, details);
  1018. entry.push_back(Pair("details", details));
  1019. return entry;
  1020. }
  1021. Value backupwallet(const Array& params, bool fHelp)
  1022. {
  1023. if (fHelp || params.size() != 1)
  1024. throw runtime_error(
  1025. "backupwallet <destination>\n"
  1026. "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
  1027. string strDest = params[0].get_str();
  1028. if (!BackupWallet(*pwalletMain, strDest))
  1029. throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
  1030. return Value::null;
  1031. }
  1032. Value keypoolrefill(const Array& params, bool fHelp)
  1033. {
  1034. if (fHelp || params.size() > 0)
  1035. throw runtime_error(
  1036. "keypoolrefill\n"
  1037. "Fills the keypool."
  1038. + HelpRequiringPassphrase());
  1039. EnsureWalletIsUnlocked();
  1040. pwalletMain->TopUpKeyPool();
  1041. if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
  1042. throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
  1043. return Value::null;
  1044. }
  1045. static void LockWallet(CWallet* pWallet)
  1046. {
  1047. LOCK(cs_nWalletUnlockTime);
  1048. nWalletUnlockTime = 0;
  1049. pWallet->Lock();
  1050. }
  1051. Value walletpassphrase(const Array& params, bool fHelp)
  1052. {
  1053. if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
  1054. throw runtime_error(
  1055. "walletpassphrase <passphrase> <timeout>\n"
  1056. "Stores the wallet decryption key in memory for <timeout> seconds.");
  1057. if (fHelp)
  1058. return true;
  1059. if (!pwalletMain->IsCrypted())
  1060. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
  1061. // Note that the walletpassphrase is stored in params[0] which is not mlock()ed
  1062. SecureString strWalletPass;
  1063. strWalletPass.reserve(100);
  1064. // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
  1065. // Alternately, find a way to make params[0] mlock()'d to begin with.
  1066. strWalletPass = params[0].get_str().c_str();
  1067. if (strWalletPass.length() > 0)
  1068. {
  1069. if (!pwalletMain->Unlock(strWalletPass))
  1070. throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
  1071. }
  1072. else
  1073. throw runtime_error(
  1074. "walletpassphrase <passphrase> <timeout>\n"
  1075. "Stores the wallet decryption key in memory for <timeout> seconds.");
  1076. pwalletMain->TopUpKeyPool();
  1077. int64 nSleepTime = params[1].get_int64();
  1078. LOCK(cs_nWalletUnlockTime);
  1079. nWalletUnlockTime = GetTime() + nSleepTime;
  1080. RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
  1081. return Value::null;
  1082. }
  1083. Value walletpassphrasechange(const Array& params, bool fHelp)
  1084. {
  1085. if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
  1086. throw runtime_error(
  1087. "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
  1088. "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
  1089. if (fHelp)
  1090. return true;
  1091. if (!pwalletMain->IsCrypted())
  1092. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
  1093. // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
  1094. // Alternately, find a way to make params[0] mlock()'d to begin with.
  1095. SecureString strOldWalletPass;
  1096. strOldWalletPass.reserve(100);
  1097. strOldWalletPass = params[0].get_str().c_str();
  1098. SecureString strNewWalletPass;
  1099. strNewWalletPass.reserve(100);
  1100. strNewWalletPass = params[1].get_str().c_str();
  1101. if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
  1102. throw runtime_error(
  1103. "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
  1104. "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
  1105. if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
  1106. throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
  1107. return Value::null;
  1108. }
  1109. Value walletlock(const Array& params, bool fHelp)
  1110. {
  1111. if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
  1112. throw runtime_error(
  1113. "walletlock\n"
  1114. "Removes the wallet encryption key from memory, locking the wallet.\n"
  1115. "After calling this method, you will need to call walletpassphrase again\n"
  1116. "before being able to call any methods which require the wallet to be unlocked.");
  1117. if (fHelp)
  1118. return true;
  1119. if (!pwalletMain->IsCrypted())
  1120. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
  1121. {
  1122. LOCK(cs_nWalletUnlockTime);
  1123. pwalletMain->Lock();
  1124. nWalletUnlockTime = 0;
  1125. }
  1126. return Value::null;
  1127. }
  1128. Value encryptwallet(const Array& params, bool fHelp)
  1129. {
  1130. if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
  1131. throw runtime_error(
  1132. "encryptwallet <passphrase>\n"
  1133. "Encrypts the wallet with <passphrase>.");
  1134. if (fHelp)
  1135. return true;
  1136. if (pwalletMain->IsCrypted())
  1137. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
  1138. // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
  1139. // Alternately, find a way to make params[0] mlock()'d to begin with.
  1140. SecureString strWalletPass;
  1141. strWalletPass.reserve(100);
  1142. strWalletPass = params[0].get_str().c_str();
  1143. if (strWalletPass.length() < 1)
  1144. throw runtime_error(
  1145. "encryptwallet <passphrase>\n"
  1146. "Encrypts the wallet with <passphrase>.");
  1147. if (!pwalletMain->EncryptWallet(strWalletPass))
  1148. throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
  1149. // BDB seems to have a bad habit of writing old data into
  1150. // slack space in .dat files; that is bad if the old data is
  1151. // unencrypted private keys. So:
  1152. StartShutdown();
  1153. return "wallet encrypted; Bitcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
  1154. }
  1155. class DescribeAddressVisitor : public boost::static_visitor<Object>
  1156. {
  1157. public:
  1158. Object operator()(const CNoDestination &dest) const { return Object(); }
  1159. Object operator()(const CKeyID &keyID) const {
  1160. Object obj;
  1161. CPubKey vchPubKey;
  1162. pwalletMain->GetPubKey(keyID, vchPubKey);
  1163. obj.push_back(Pair("isscript", false));
  1164. obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
  1165. obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
  1166. return obj;
  1167. }
  1168. Object operator()(const CScriptID &scriptID) const {
  1169. Object obj;
  1170. obj.push_back(Pair("isscript", true));
  1171. CScript subscript;
  1172. pwalletMain->GetCScript(scriptID, subscript);
  1173. std::vector<CTxDestination> addresses;
  1174. txnouttype whichType;
  1175. int nRequired;
  1176. ExtractDestinations(subscript, whichType, addresses, nRequired);
  1177. obj.push_back(Pair("script", GetTxnOutputType(whichType)));
  1178. Array a;
  1179. BOOST_FOREACH(const CTxDestination& addr, addresses)
  1180. a.push_back(CBitcoinAddress(addr).ToString());
  1181. obj.push_back(Pair("addresses", a));
  1182. if (whichType == TX_MULTISIG)
  1183. obj.push_back(Pair("sigsrequired", nRequired));
  1184. return obj;
  1185. }
  1186. };
  1187. Value validateaddress(const Array& params, bool fHelp)
  1188. {
  1189. if (fHelp || params.size() != 1)
  1190. throw runtime_error(
  1191. "validateaddress <bitcoinaddress>\n"
  1192. "Return information about <bitcoinaddress>.");
  1193. CBitcoinAddress address(params[0].get_str());
  1194. bool isValid = address.IsValid();
  1195. Object ret;
  1196. ret.push_back(Pair("isvalid", isValid));
  1197. if (isValid)
  1198. {
  1199. CTxDestination dest = address.Get();
  1200. string currentAddress = address.ToString();
  1201. ret.push_back(Pair("address", currentAddress));
  1202. bool fMine = IsMine(*pwalletMain, dest);
  1203. ret.push_back(Pair("ismine", fMine));
  1204. if (fMine) {
  1205. Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
  1206. ret.insert(ret.end(), detail.begin(), detail.end());
  1207. }
  1208. if (pwalletMain->mapAddressBook.count(dest))
  1209. ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
  1210. }
  1211. return ret;
  1212. }
  1213. Value lockunspent(const Array& params, bool fHelp)
  1214. {
  1215. if (fHelp || params.size() < 1 || params.size() > 2)
  1216. throw runtime_error(
  1217. "lockunspent unlock? [array-of-Objects]\n"
  1218. "Updates list of temporarily unspendable outputs.");
  1219. if (params.size() == 1)
  1220. RPCTypeCheck(params, list_of(bool_type));
  1221. else
  1222. RPCTypeCheck(params, list_of(bool_type)(array_type));
  1223. bool fUnlock = params[0].get_bool();
  1224. if (params.size() == 1) {
  1225. if (fUnlock)
  1226. pwalletMain->UnlockAllCoins();
  1227. return true;
  1228. }
  1229. Array outputs = params[1].get_array();
  1230. BOOST_FOREACH(Value& output, outputs)
  1231. {
  1232. if (output.type() != obj_type)
  1233. throw JSONRPCError(-8, "Invalid parameter, expected object");
  1234. const Object& o = output.get_obj();
  1235. RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type));
  1236. string txid = find_value(o, "txid").get_str();
  1237. if (!IsHex(txid))
  1238. throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
  1239. int nOutput = find_value(o, "vout").get_int();
  1240. if (nOutput < 0)
  1241. throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
  1242. COutPoint outpt(uint256(txid), nOutput);
  1243. if (fUnlock)
  1244. pwalletMain->UnlockCoin(outpt);
  1245. else
  1246. pwalletMain->LockCoin(outpt);
  1247. }
  1248. return true;
  1249. }
  1250. Value listlockunspent(const Array& params, bool fHelp)
  1251. {
  1252. if (fHelp || params.size() > 0)
  1253. throw runtime_error(
  1254. "listlockunspent\n"
  1255. "Returns list of temporarily unspendable outputs.");
  1256. vector<COutPoint> vOutpts;
  1257. pwalletMain->ListLockedCoins(vOutpts);
  1258. Array ret;
  1259. BOOST_FOREACH(COutPoint &outpt, vOutpts) {
  1260. Object o;
  1261. o.push_back(Pair("txid", outpt.hash.GetHex()));
  1262. o.push_back(Pair("vout", (int)outpt.n));
  1263. ret.push_back(o);
  1264. }
  1265. return ret;
  1266. }