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

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