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 102KB

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