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.

bitcoinrpc.cpp 92KB

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