rpcwallet.cpp 61 KB

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