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

rpcwallet.cpp 151KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "amount.h"
  6. #include "base58.h"
  7. #include "chain.h"
  8. #include "consensus/validation.h"
  9. #include "core_io.h"
  10. #include "init.h"
  11. #include "httpserver.h"
  12. #include "validation.h"
  13. #include "net.h"
  14. #include "policy/feerate.h"
  15. #include "policy/fees.h"
  16. #include "policy/policy.h"
  17. #include "policy/rbf.h"
  18. #include "rpc/mining.h"
  19. #include "rpc/server.h"
  20. #include "script/sign.h"
  21. #include "timedata.h"
  22. #include "util.h"
  23. #include "utilmoneystr.h"
  24. #include "wallet/coincontrol.h"
  25. #include "wallet/feebumper.h"
  26. #include "wallet/wallet.h"
  27. #include "wallet/walletdb.h"
  28. #include <stdint.h>
  29. #include <univalue.h>
  30. static const std::string WALLET_ENDPOINT_BASE = "/wallet/";
  31. CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request)
  32. {
  33. if (request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) == WALLET_ENDPOINT_BASE) {
  34. // wallet endpoint was used
  35. std::string requestedWallet = urlDecode(request.URI.substr(WALLET_ENDPOINT_BASE.size()));
  36. for (CWalletRef pwallet : ::vpwallets) {
  37. if (pwallet->GetName() == requestedWallet) {
  38. return pwallet;
  39. }
  40. }
  41. throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
  42. }
  43. return ::vpwallets.size() == 1 || (request.fHelp && ::vpwallets.size() > 0) ? ::vpwallets[0] : nullptr;
  44. }
  45. std::string HelpRequiringPassphrase(CWallet * const pwallet)
  46. {
  47. return pwallet && pwallet->IsCrypted()
  48. ? "\nRequires wallet passphrase to be set with walletpassphrase call."
  49. : "";
  50. }
  51. bool EnsureWalletIsAvailable(CWallet * const pwallet, bool avoidException)
  52. {
  53. if (pwallet) return true;
  54. if (avoidException) return false;
  55. if (::vpwallets.empty()) {
  56. // Note: It isn't currently possible to trigger this error because
  57. // wallet RPC methods aren't registered unless a wallet is loaded. But
  58. // this error is being kept as a precaution, because it's possible in
  59. // the future that wallet RPC methods might get or remain registered
  60. // when no wallets are loaded.
  61. throw JSONRPCError(
  62. RPC_METHOD_NOT_FOUND, "Method not found (wallet method is disabled because no wallet is loaded)");
  63. }
  64. throw JSONRPCError(RPC_WALLET_NOT_SPECIFIED,
  65. "Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).");
  66. }
  67. void EnsureWalletIsUnlocked(CWallet * const pwallet)
  68. {
  69. if (pwallet->IsLocked()) {
  70. throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
  71. }
  72. }
  73. void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
  74. {
  75. int confirms = wtx.GetDepthInMainChain();
  76. entry.push_back(Pair("confirmations", confirms));
  77. if (wtx.IsCoinBase())
  78. entry.push_back(Pair("generated", true));
  79. if (confirms > 0)
  80. {
  81. entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
  82. entry.push_back(Pair("blockindex", wtx.nIndex));
  83. entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
  84. } else {
  85. entry.push_back(Pair("trusted", wtx.IsTrusted()));
  86. }
  87. uint256 hash = wtx.GetHash();
  88. entry.push_back(Pair("txid", hash.GetHex()));
  89. UniValue conflicts(UniValue::VARR);
  90. for (const uint256& conflict : wtx.GetConflicts())
  91. conflicts.push_back(conflict.GetHex());
  92. entry.push_back(Pair("walletconflicts", conflicts));
  93. entry.push_back(Pair("time", wtx.GetTxTime()));
  94. entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
  95. // Add opt-in RBF status
  96. std::string rbfStatus = "no";
  97. if (confirms <= 0) {
  98. LOCK(mempool.cs);
  99. RBFTransactionState rbfState = IsRBFOptIn(wtx, mempool);
  100. if (rbfState == RBF_TRANSACTIONSTATE_UNKNOWN)
  101. rbfStatus = "unknown";
  102. else if (rbfState == RBF_TRANSACTIONSTATE_REPLACEABLE_BIP125)
  103. rbfStatus = "yes";
  104. }
  105. entry.push_back(Pair("bip125-replaceable", rbfStatus));
  106. for (const std::pair<std::string, std::string>& item : wtx.mapValue)
  107. entry.push_back(Pair(item.first, item.second));
  108. }
  109. std::string AccountFromValue(const UniValue& value)
  110. {
  111. std::string strAccount = value.get_str();
  112. if (strAccount == "*")
  113. throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
  114. return strAccount;
  115. }
  116. UniValue getnewaddress(const JSONRPCRequest& request)
  117. {
  118. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  119. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  120. return NullUniValue;
  121. }
  122. if (request.fHelp || request.params.size() > 1)
  123. throw std::runtime_error(
  124. "getnewaddress ( \"account\" )\n"
  125. "\nReturns a new Bitcoin address for receiving payments.\n"
  126. "If 'account' is specified (DEPRECATED), it is added to the address book \n"
  127. "so payments received with the address will be credited to 'account'.\n"
  128. "\nArguments:\n"
  129. "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
  130. "\nResult:\n"
  131. "\"address\" (string) The new bitcoin address\n"
  132. "\nExamples:\n"
  133. + HelpExampleCli("getnewaddress", "")
  134. + HelpExampleRpc("getnewaddress", "")
  135. );
  136. LOCK2(cs_main, pwallet->cs_wallet);
  137. // Parse the account first so we don't generate a key if there's an error
  138. std::string strAccount;
  139. if (!request.params[0].isNull())
  140. strAccount = AccountFromValue(request.params[0]);
  141. if (!pwallet->IsLocked()) {
  142. pwallet->TopUpKeyPool();
  143. }
  144. // Generate a new key that is added to wallet
  145. CPubKey newKey;
  146. if (!pwallet->GetKeyFromPool(newKey)) {
  147. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  148. }
  149. CKeyID keyID = newKey.GetID();
  150. pwallet->SetAddressBook(keyID, strAccount, "receive");
  151. return CBitcoinAddress(keyID).ToString();
  152. }
  153. CBitcoinAddress GetAccountAddress(CWallet* const pwallet, std::string strAccount, bool bForceNew=false)
  154. {
  155. CPubKey pubKey;
  156. if (!pwallet->GetAccountPubkey(pubKey, strAccount, bForceNew)) {
  157. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  158. }
  159. return CBitcoinAddress(pubKey.GetID());
  160. }
  161. UniValue getaccountaddress(const JSONRPCRequest& request)
  162. {
  163. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  164. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  165. return NullUniValue;
  166. }
  167. if (request.fHelp || request.params.size() != 1)
  168. throw std::runtime_error(
  169. "getaccountaddress \"account\"\n"
  170. "\nDEPRECATED. Returns the current Bitcoin address for receiving payments to this account.\n"
  171. "\nArguments:\n"
  172. "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
  173. "\nResult:\n"
  174. "\"address\" (string) The account bitcoin address\n"
  175. "\nExamples:\n"
  176. + HelpExampleCli("getaccountaddress", "")
  177. + HelpExampleCli("getaccountaddress", "\"\"")
  178. + HelpExampleCli("getaccountaddress", "\"myaccount\"")
  179. + HelpExampleRpc("getaccountaddress", "\"myaccount\"")
  180. );
  181. LOCK2(cs_main, pwallet->cs_wallet);
  182. // Parse the account first so we don't generate a key if there's an error
  183. std::string strAccount = AccountFromValue(request.params[0]);
  184. UniValue ret(UniValue::VSTR);
  185. ret = GetAccountAddress(pwallet, strAccount).ToString();
  186. return ret;
  187. }
  188. UniValue getrawchangeaddress(const JSONRPCRequest& request)
  189. {
  190. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  191. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  192. return NullUniValue;
  193. }
  194. if (request.fHelp || request.params.size() > 0)
  195. throw std::runtime_error(
  196. "getrawchangeaddress\n"
  197. "\nReturns a new Bitcoin address, for receiving change.\n"
  198. "This is for use with raw transactions, NOT normal use.\n"
  199. "\nResult:\n"
  200. "\"address\" (string) The address\n"
  201. "\nExamples:\n"
  202. + HelpExampleCli("getrawchangeaddress", "")
  203. + HelpExampleRpc("getrawchangeaddress", "")
  204. );
  205. LOCK2(cs_main, pwallet->cs_wallet);
  206. if (!pwallet->IsLocked()) {
  207. pwallet->TopUpKeyPool();
  208. }
  209. CReserveKey reservekey(pwallet);
  210. CPubKey vchPubKey;
  211. if (!reservekey.GetReservedKey(vchPubKey, true))
  212. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  213. reservekey.KeepKey();
  214. CKeyID keyID = vchPubKey.GetID();
  215. return CBitcoinAddress(keyID).ToString();
  216. }
  217. UniValue setaccount(const JSONRPCRequest& request)
  218. {
  219. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  220. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  221. return NullUniValue;
  222. }
  223. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  224. throw std::runtime_error(
  225. "setaccount \"address\" \"account\"\n"
  226. "\nDEPRECATED. Sets the account associated with the given address.\n"
  227. "\nArguments:\n"
  228. "1. \"address\" (string, required) The bitcoin address to be associated with an account.\n"
  229. "2. \"account\" (string, required) The account to assign the address to.\n"
  230. "\nExamples:\n"
  231. + HelpExampleCli("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"tabby\"")
  232. + HelpExampleRpc("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"tabby\"")
  233. );
  234. LOCK2(cs_main, pwallet->cs_wallet);
  235. CBitcoinAddress address(request.params[0].get_str());
  236. if (!address.IsValid())
  237. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  238. std::string strAccount;
  239. if (request.params.size() > 1)
  240. strAccount = AccountFromValue(request.params[1]);
  241. // Only add the account if the address is yours.
  242. if (IsMine(*pwallet, address.Get())) {
  243. // Detect when changing the account of an address that is the 'unused current key' of another account:
  244. if (pwallet->mapAddressBook.count(address.Get())) {
  245. std::string strOldAccount = pwallet->mapAddressBook[address.Get()].name;
  246. if (address == GetAccountAddress(pwallet, strOldAccount)) {
  247. GetAccountAddress(pwallet, strOldAccount, true);
  248. }
  249. }
  250. pwallet->SetAddressBook(address.Get(), strAccount, "receive");
  251. }
  252. else
  253. throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
  254. return NullUniValue;
  255. }
  256. UniValue getaccount(const JSONRPCRequest& request)
  257. {
  258. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  259. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  260. return NullUniValue;
  261. }
  262. if (request.fHelp || request.params.size() != 1)
  263. throw std::runtime_error(
  264. "getaccount \"address\"\n"
  265. "\nDEPRECATED. Returns the account associated with the given address.\n"
  266. "\nArguments:\n"
  267. "1. \"address\" (string, required) The bitcoin address for account lookup.\n"
  268. "\nResult:\n"
  269. "\"accountname\" (string) the account address\n"
  270. "\nExamples:\n"
  271. + HelpExampleCli("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\"")
  272. + HelpExampleRpc("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\"")
  273. );
  274. LOCK2(cs_main, pwallet->cs_wallet);
  275. CBitcoinAddress address(request.params[0].get_str());
  276. if (!address.IsValid())
  277. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  278. std::string strAccount;
  279. std::map<CTxDestination, CAddressBookData>::iterator mi = pwallet->mapAddressBook.find(address.Get());
  280. if (mi != pwallet->mapAddressBook.end() && !(*mi).second.name.empty()) {
  281. strAccount = (*mi).second.name;
  282. }
  283. return strAccount;
  284. }
  285. UniValue getaddressesbyaccount(const JSONRPCRequest& request)
  286. {
  287. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  288. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  289. return NullUniValue;
  290. }
  291. if (request.fHelp || request.params.size() != 1)
  292. throw std::runtime_error(
  293. "getaddressesbyaccount \"account\"\n"
  294. "\nDEPRECATED. Returns the list of addresses for the given account.\n"
  295. "\nArguments:\n"
  296. "1. \"account\" (string, required) The account name.\n"
  297. "\nResult:\n"
  298. "[ (json array of string)\n"
  299. " \"address\" (string) a bitcoin address associated with the given account\n"
  300. " ,...\n"
  301. "]\n"
  302. "\nExamples:\n"
  303. + HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
  304. + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
  305. );
  306. LOCK2(cs_main, pwallet->cs_wallet);
  307. std::string strAccount = AccountFromValue(request.params[0]);
  308. // Find all addresses that have the given account
  309. UniValue ret(UniValue::VARR);
  310. for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) {
  311. const CBitcoinAddress& address = item.first;
  312. const std::string& strName = item.second.name;
  313. if (strName == strAccount)
  314. ret.push_back(address.ToString());
  315. }
  316. return ret;
  317. }
  318. static void SendMoney(CWallet * const pwallet, const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, const CCoinControl& coin_control)
  319. {
  320. CAmount curBalance = pwallet->GetBalance();
  321. // Check amount
  322. if (nValue <= 0)
  323. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
  324. if (nValue > curBalance)
  325. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
  326. if (pwallet->GetBroadcastTransactions() && !g_connman) {
  327. throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
  328. }
  329. // Parse Bitcoin address
  330. CScript scriptPubKey = GetScriptForDestination(address);
  331. // Create and send the transaction
  332. CReserveKey reservekey(pwallet);
  333. CAmount nFeeRequired;
  334. std::string strError;
  335. std::vector<CRecipient> vecSend;
  336. int nChangePosRet = -1;
  337. CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
  338. vecSend.push_back(recipient);
  339. if (!pwallet->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError, coin_control)) {
  340. if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance)
  341. strError = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired));
  342. throw JSONRPCError(RPC_WALLET_ERROR, strError);
  343. }
  344. CValidationState state;
  345. if (!pwallet->CommitTransaction(wtxNew, reservekey, g_connman.get(), state)) {
  346. strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason());
  347. throw JSONRPCError(RPC_WALLET_ERROR, strError);
  348. }
  349. }
  350. UniValue sendtoaddress(const JSONRPCRequest& request)
  351. {
  352. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  353. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  354. return NullUniValue;
  355. }
  356. if (request.fHelp || request.params.size() < 2 || request.params.size() > 8)
  357. throw std::runtime_error(
  358. "sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" subtractfeefromamount replaceable conf_target \"estimate_mode\")\n"
  359. "\nSend an amount to a given address.\n"
  360. + HelpRequiringPassphrase(pwallet) +
  361. "\nArguments:\n"
  362. "1. \"address\" (string, required) The bitcoin address to send to.\n"
  363. "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
  364. "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
  365. " This is not part of the transaction, just kept in your wallet.\n"
  366. "4. \"comment_to\" (string, optional) A comment to store the name of the person or organization \n"
  367. " to which you're sending the transaction. This is not part of the \n"
  368. " transaction, just kept in your wallet.\n"
  369. "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
  370. " The recipient will receive less bitcoins than you enter in the amount field.\n"
  371. "6. replaceable (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
  372. "7. conf_target (numeric, optional) Confirmation target (in blocks)\n"
  373. "8. \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
  374. " \"UNSET\"\n"
  375. " \"ECONOMICAL\"\n"
  376. " \"CONSERVATIVE\"\n"
  377. "\nResult:\n"
  378. "\"txid\" (string) The transaction id.\n"
  379. "\nExamples:\n"
  380. + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1")
  381. + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"donation\" \"seans outpost\"")
  382. + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"\" \"\" true")
  383. + HelpExampleRpc("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.1, \"donation\", \"seans outpost\"")
  384. );
  385. LOCK2(cs_main, pwallet->cs_wallet);
  386. CBitcoinAddress address(request.params[0].get_str());
  387. if (!address.IsValid())
  388. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  389. // Amount
  390. CAmount nAmount = AmountFromValue(request.params[1]);
  391. if (nAmount <= 0)
  392. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
  393. // Wallet comments
  394. CWalletTx wtx;
  395. if (request.params.size() > 2 && !request.params[2].isNull() && !request.params[2].get_str().empty())
  396. wtx.mapValue["comment"] = request.params[2].get_str();
  397. if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty())
  398. wtx.mapValue["to"] = request.params[3].get_str();
  399. bool fSubtractFeeFromAmount = false;
  400. if (request.params.size() > 4 && !request.params[4].isNull()) {
  401. fSubtractFeeFromAmount = request.params[4].get_bool();
  402. }
  403. CCoinControl coin_control;
  404. if (request.params.size() > 5 && !request.params[5].isNull()) {
  405. coin_control.signalRbf = request.params[5].get_bool();
  406. }
  407. if (request.params.size() > 6 && !request.params[6].isNull()) {
  408. coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
  409. }
  410. if (request.params.size() > 7 && !request.params[7].isNull()) {
  411. if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
  412. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
  413. }
  414. }
  415. EnsureWalletIsUnlocked(pwallet);
  416. SendMoney(pwallet, address.Get(), nAmount, fSubtractFeeFromAmount, wtx, coin_control);
  417. return wtx.GetHash().GetHex();
  418. }
  419. UniValue listaddressgroupings(const JSONRPCRequest& request)
  420. {
  421. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  422. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  423. return NullUniValue;
  424. }
  425. if (request.fHelp || request.params.size() != 0)
  426. throw std::runtime_error(
  427. "listaddressgroupings\n"
  428. "\nLists groups of addresses which have had their common ownership\n"
  429. "made public by common use as inputs or as the resulting change\n"
  430. "in past transactions\n"
  431. "\nResult:\n"
  432. "[\n"
  433. " [\n"
  434. " [\n"
  435. " \"address\", (string) The bitcoin address\n"
  436. " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
  437. " \"account\" (string, optional) DEPRECATED. The account\n"
  438. " ]\n"
  439. " ,...\n"
  440. " ]\n"
  441. " ,...\n"
  442. "]\n"
  443. "\nExamples:\n"
  444. + HelpExampleCli("listaddressgroupings", "")
  445. + HelpExampleRpc("listaddressgroupings", "")
  446. );
  447. LOCK2(cs_main, pwallet->cs_wallet);
  448. UniValue jsonGroupings(UniValue::VARR);
  449. std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances();
  450. for (std::set<CTxDestination> grouping : pwallet->GetAddressGroupings()) {
  451. UniValue jsonGrouping(UniValue::VARR);
  452. for (CTxDestination address : grouping)
  453. {
  454. UniValue addressInfo(UniValue::VARR);
  455. addressInfo.push_back(CBitcoinAddress(address).ToString());
  456. addressInfo.push_back(ValueFromAmount(balances[address]));
  457. {
  458. if (pwallet->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwallet->mapAddressBook.end()) {
  459. addressInfo.push_back(pwallet->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
  460. }
  461. }
  462. jsonGrouping.push_back(addressInfo);
  463. }
  464. jsonGroupings.push_back(jsonGrouping);
  465. }
  466. return jsonGroupings;
  467. }
  468. UniValue signmessage(const JSONRPCRequest& request)
  469. {
  470. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  471. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  472. return NullUniValue;
  473. }
  474. if (request.fHelp || request.params.size() != 2)
  475. throw std::runtime_error(
  476. "signmessage \"address\" \"message\"\n"
  477. "\nSign a message with the private key of an address"
  478. + HelpRequiringPassphrase(pwallet) + "\n"
  479. "\nArguments:\n"
  480. "1. \"address\" (string, required) The bitcoin address to use for the private key.\n"
  481. "2. \"message\" (string, required) The message to create a signature of.\n"
  482. "\nResult:\n"
  483. "\"signature\" (string) The signature of the message encoded in base 64\n"
  484. "\nExamples:\n"
  485. "\nUnlock the wallet for 30 seconds\n"
  486. + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
  487. "\nCreate the signature\n"
  488. + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
  489. "\nVerify the signature\n"
  490. + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
  491. "\nAs json rpc\n"
  492. + HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"my message\"")
  493. );
  494. LOCK2(cs_main, pwallet->cs_wallet);
  495. EnsureWalletIsUnlocked(pwallet);
  496. std::string strAddress = request.params[0].get_str();
  497. std::string strMessage = request.params[1].get_str();
  498. CBitcoinAddress addr(strAddress);
  499. if (!addr.IsValid())
  500. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
  501. CKeyID keyID;
  502. if (!addr.GetKeyID(keyID))
  503. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  504. CKey key;
  505. if (!pwallet->GetKey(keyID, key)) {
  506. throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
  507. }
  508. CHashWriter ss(SER_GETHASH, 0);
  509. ss << strMessageMagic;
  510. ss << strMessage;
  511. std::vector<unsigned char> vchSig;
  512. if (!key.SignCompact(ss.GetHash(), vchSig))
  513. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
  514. return EncodeBase64(&vchSig[0], vchSig.size());
  515. }
  516. UniValue getreceivedbyaddress(const JSONRPCRequest& request)
  517. {
  518. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  519. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  520. return NullUniValue;
  521. }
  522. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  523. throw std::runtime_error(
  524. "getreceivedbyaddress \"address\" ( minconf )\n"
  525. "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n"
  526. "\nArguments:\n"
  527. "1. \"address\" (string, required) The bitcoin address for transactions.\n"
  528. "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
  529. "\nResult:\n"
  530. "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
  531. "\nExamples:\n"
  532. "\nThe amount from transactions with at least 1 confirmation\n"
  533. + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\"") +
  534. "\nThe amount including unconfirmed transactions, zero confirmations\n"
  535. + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 0") +
  536. "\nThe amount with at least 6 confirmations\n"
  537. + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 6") +
  538. "\nAs a json rpc call\n"
  539. + HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", 6")
  540. );
  541. LOCK2(cs_main, pwallet->cs_wallet);
  542. // Bitcoin address
  543. CBitcoinAddress address = CBitcoinAddress(request.params[0].get_str());
  544. if (!address.IsValid())
  545. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  546. CScript scriptPubKey = GetScriptForDestination(address.Get());
  547. if (!IsMine(*pwallet, scriptPubKey)) {
  548. return ValueFromAmount(0);
  549. }
  550. // Minimum confirmations
  551. int nMinDepth = 1;
  552. if (!request.params[1].isNull())
  553. nMinDepth = request.params[1].get_int();
  554. // Tally
  555. CAmount nAmount = 0;
  556. for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
  557. const CWalletTx& wtx = pairWtx.second;
  558. if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
  559. continue;
  560. for (const CTxOut& txout : wtx.tx->vout)
  561. if (txout.scriptPubKey == scriptPubKey)
  562. if (wtx.GetDepthInMainChain() >= nMinDepth)
  563. nAmount += txout.nValue;
  564. }
  565. return ValueFromAmount(nAmount);
  566. }
  567. UniValue getreceivedbyaccount(const JSONRPCRequest& request)
  568. {
  569. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  570. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  571. return NullUniValue;
  572. }
  573. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  574. throw std::runtime_error(
  575. "getreceivedbyaccount \"account\" ( minconf )\n"
  576. "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
  577. "\nArguments:\n"
  578. "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
  579. "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
  580. "\nResult:\n"
  581. "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
  582. "\nExamples:\n"
  583. "\nAmount received by the default account with at least 1 confirmation\n"
  584. + HelpExampleCli("getreceivedbyaccount", "\"\"") +
  585. "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
  586. + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
  587. "\nThe amount with at least 6 confirmations\n"
  588. + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
  589. "\nAs a json rpc call\n"
  590. + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
  591. );
  592. LOCK2(cs_main, pwallet->cs_wallet);
  593. // Minimum confirmations
  594. int nMinDepth = 1;
  595. if (!request.params[1].isNull())
  596. nMinDepth = request.params[1].get_int();
  597. // Get the set of pub keys assigned to account
  598. std::string strAccount = AccountFromValue(request.params[0]);
  599. std::set<CTxDestination> setAddress = pwallet->GetAccountAddresses(strAccount);
  600. // Tally
  601. CAmount nAmount = 0;
  602. for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
  603. const CWalletTx& wtx = pairWtx.second;
  604. if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
  605. continue;
  606. for (const CTxOut& txout : wtx.tx->vout)
  607. {
  608. CTxDestination address;
  609. if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwallet, address) && setAddress.count(address)) {
  610. if (wtx.GetDepthInMainChain() >= nMinDepth)
  611. nAmount += txout.nValue;
  612. }
  613. }
  614. }
  615. return ValueFromAmount(nAmount);
  616. }
  617. UniValue getbalance(const JSONRPCRequest& request)
  618. {
  619. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  620. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  621. return NullUniValue;
  622. }
  623. if (request.fHelp || request.params.size() > 3)
  624. throw std::runtime_error(
  625. "getbalance ( \"account\" minconf include_watchonly )\n"
  626. "\nIf account is not specified, returns the server's total available balance.\n"
  627. "If account is specified (DEPRECATED), returns the balance in the account.\n"
  628. "Note that the account \"\" is not the same as leaving the parameter out.\n"
  629. "The server total may be different to the balance in the default \"\" account.\n"
  630. "\nArguments:\n"
  631. "1. \"account\" (string, optional) DEPRECATED. The account string may be given as a\n"
  632. " specific account name to find the balance associated with wallet keys in\n"
  633. " a named account, or as the empty string (\"\") to find the balance\n"
  634. " associated with wallet keys not in any named account, or as \"*\" to find\n"
  635. " the balance associated with all wallet keys regardless of account.\n"
  636. " When this option is specified, it calculates the balance in a different\n"
  637. " way than when it is not specified, and which can count spends twice when\n"
  638. " there are conflicting pending transactions (such as those created by\n"
  639. " the bumpfee command), temporarily resulting in low or even negative\n"
  640. " balances. In general, account balance calculation is not considered\n"
  641. " reliable and has resulted in confusing outcomes, so it is recommended to\n"
  642. " avoid passing this argument.\n"
  643. "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
  644. "3. include_watchonly (bool, optional, default=false) Also include balance in watch-only addresses (see 'importaddress')\n"
  645. "\nResult:\n"
  646. "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
  647. "\nExamples:\n"
  648. "\nThe total amount in the wallet with 1 or more confirmations\n"
  649. + HelpExampleCli("getbalance", "") +
  650. "\nThe total amount in the wallet at least 6 blocks confirmed\n"
  651. + HelpExampleCli("getbalance", "\"*\" 6") +
  652. "\nAs a json rpc call\n"
  653. + HelpExampleRpc("getbalance", "\"*\", 6")
  654. );
  655. LOCK2(cs_main, pwallet->cs_wallet);
  656. if (request.params.size() == 0)
  657. return ValueFromAmount(pwallet->GetBalance());
  658. const std::string& account_param = request.params[0].get_str();
  659. const std::string* account = account_param != "*" ? &account_param : nullptr;
  660. int nMinDepth = 1;
  661. if (!request.params[1].isNull())
  662. nMinDepth = request.params[1].get_int();
  663. isminefilter filter = ISMINE_SPENDABLE;
  664. if(!request.params[2].isNull())
  665. if(request.params[2].get_bool())
  666. filter = filter | ISMINE_WATCH_ONLY;
  667. return ValueFromAmount(pwallet->GetLegacyBalance(filter, nMinDepth, account));
  668. }
  669. UniValue getunconfirmedbalance(const JSONRPCRequest &request)
  670. {
  671. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  672. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  673. return NullUniValue;
  674. }
  675. if (request.fHelp || request.params.size() > 0)
  676. throw std::runtime_error(
  677. "getunconfirmedbalance\n"
  678. "Returns the server's total unconfirmed balance\n");
  679. LOCK2(cs_main, pwallet->cs_wallet);
  680. return ValueFromAmount(pwallet->GetUnconfirmedBalance());
  681. }
  682. UniValue movecmd(const JSONRPCRequest& request)
  683. {
  684. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  685. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  686. return NullUniValue;
  687. }
  688. if (request.fHelp || request.params.size() < 3 || request.params.size() > 5)
  689. throw std::runtime_error(
  690. "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
  691. "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
  692. "\nArguments:\n"
  693. "1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
  694. "2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
  695. "3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
  696. "4. (dummy) (numeric, optional) Ignored. Remains for backward compatibility.\n"
  697. "5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
  698. "\nResult:\n"
  699. "true|false (boolean) true if successful.\n"
  700. "\nExamples:\n"
  701. "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
  702. + HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
  703. "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n"
  704. + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
  705. "\nAs a json rpc call\n"
  706. + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
  707. );
  708. LOCK2(cs_main, pwallet->cs_wallet);
  709. std::string strFrom = AccountFromValue(request.params[0]);
  710. std::string strTo = AccountFromValue(request.params[1]);
  711. CAmount nAmount = AmountFromValue(request.params[2]);
  712. if (nAmount <= 0)
  713. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
  714. if (request.params.size() > 3)
  715. // unused parameter, used to be nMinDepth, keep type-checking it though
  716. (void)request.params[3].get_int();
  717. std::string strComment;
  718. if (request.params.size() > 4)
  719. strComment = request.params[4].get_str();
  720. if (!pwallet->AccountMove(strFrom, strTo, nAmount, strComment)) {
  721. throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
  722. }
  723. return true;
  724. }
  725. UniValue sendfrom(const JSONRPCRequest& request)
  726. {
  727. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  728. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  729. return NullUniValue;
  730. }
  731. if (request.fHelp || request.params.size() < 3 || request.params.size() > 6)
  732. throw std::runtime_error(
  733. "sendfrom \"fromaccount\" \"toaddress\" amount ( minconf \"comment\" \"comment_to\" )\n"
  734. "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address."
  735. + HelpRequiringPassphrase(pwallet) + "\n"
  736. "\nArguments:\n"
  737. "1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
  738. " Specifying an account does not influence coin selection, but it does associate the newly created\n"
  739. " transaction with the account, so the account's balance computation and transaction history can reflect\n"
  740. " the spend.\n"
  741. "2. \"toaddress\" (string, required) The bitcoin address to send funds to.\n"
  742. "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
  743. "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
  744. "5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
  745. " This is not part of the transaction, just kept in your wallet.\n"
  746. "6. \"comment_to\" (string, optional) An optional comment to store the name of the person or organization \n"
  747. " to which you're sending the transaction. This is not part of the transaction, \n"
  748. " it is just kept in your wallet.\n"
  749. "\nResult:\n"
  750. "\"txid\" (string) The transaction id.\n"
  751. "\nExamples:\n"
  752. "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
  753. + HelpExampleCli("sendfrom", "\"\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01") +
  754. "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
  755. + HelpExampleCli("sendfrom", "\"tabby\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01 6 \"donation\" \"seans outpost\"") +
  756. "\nAs a json rpc call\n"
  757. + HelpExampleRpc("sendfrom", "\"tabby\", \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.01, 6, \"donation\", \"seans outpost\"")
  758. );
  759. LOCK2(cs_main, pwallet->cs_wallet);
  760. std::string strAccount = AccountFromValue(request.params[0]);
  761. CBitcoinAddress address(request.params[1].get_str());
  762. if (!address.IsValid())
  763. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  764. CAmount nAmount = AmountFromValue(request.params[2]);
  765. if (nAmount <= 0)
  766. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
  767. int nMinDepth = 1;
  768. if (request.params.size() > 3)
  769. nMinDepth = request.params[3].get_int();
  770. CWalletTx wtx;
  771. wtx.strFromAccount = strAccount;
  772. if (request.params.size() > 4 && !request.params[4].isNull() && !request.params[4].get_str().empty())
  773. wtx.mapValue["comment"] = request.params[4].get_str();
  774. if (request.params.size() > 5 && !request.params[5].isNull() && !request.params[5].get_str().empty())
  775. wtx.mapValue["to"] = request.params[5].get_str();
  776. EnsureWalletIsUnlocked(pwallet);
  777. // Check funds
  778. CAmount nBalance = pwallet->GetLegacyBalance(ISMINE_SPENDABLE, nMinDepth, &strAccount);
  779. if (nAmount > nBalance)
  780. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  781. CCoinControl no_coin_control; // This is a deprecated API
  782. SendMoney(pwallet, address.Get(), nAmount, false, wtx, no_coin_control);
  783. return wtx.GetHash().GetHex();
  784. }
  785. UniValue sendmany(const JSONRPCRequest& request)
  786. {
  787. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  788. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  789. return NullUniValue;
  790. }
  791. if (request.fHelp || request.params.size() < 2 || request.params.size() > 8)
  792. throw std::runtime_error(
  793. "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] replaceable conf_target \"estimate_mode\")\n"
  794. "\nSend multiple times. Amounts are double-precision floating point numbers."
  795. + HelpRequiringPassphrase(pwallet) + "\n"
  796. "\nArguments:\n"
  797. "1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
  798. "2. \"amounts\" (string, required) A json object with addresses and amounts\n"
  799. " {\n"
  800. " \"address\":amount (numeric or string) The bitcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
  801. " ,...\n"
  802. " }\n"
  803. "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
  804. "4. \"comment\" (string, optional) A comment\n"
  805. "5. subtractfeefrom (array, optional) A json array with addresses.\n"
  806. " The fee will be equally deducted from the amount of each selected address.\n"
  807. " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
  808. " If no addresses are specified here, the sender pays the fee.\n"
  809. " [\n"
  810. " \"address\" (string) Subtract fee from this address\n"
  811. " ,...\n"
  812. " ]\n"
  813. "6. replaceable (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
  814. "7. conf_target (numeric, optional) Confirmation target (in blocks)\n"
  815. "8. \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
  816. " \"UNSET\"\n"
  817. " \"ECONOMICAL\"\n"
  818. " \"CONSERVATIVE\"\n"
  819. "\nResult:\n"
  820. "\"txid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
  821. " the number of addresses.\n"
  822. "\nExamples:\n"
  823. "\nSend two amounts to two different addresses:\n"
  824. + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
  825. "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
  826. + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
  827. "\nSend two amounts to two different addresses, subtract fee from amount:\n"
  828. + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
  829. "\nAs a json rpc call\n"
  830. + HelpExampleRpc("sendmany", "\"\", \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\", 6, \"testing\"")
  831. );
  832. LOCK2(cs_main, pwallet->cs_wallet);
  833. if (pwallet->GetBroadcastTransactions() && !g_connman) {
  834. throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
  835. }
  836. std::string strAccount = AccountFromValue(request.params[0]);
  837. UniValue sendTo = request.params[1].get_obj();
  838. int nMinDepth = 1;
  839. if (!request.params[2].isNull())
  840. nMinDepth = request.params[2].get_int();
  841. CWalletTx wtx;
  842. wtx.strFromAccount = strAccount;
  843. if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty())
  844. wtx.mapValue["comment"] = request.params[3].get_str();
  845. UniValue subtractFeeFromAmount(UniValue::VARR);
  846. if (request.params.size() > 4 && !request.params[4].isNull())
  847. subtractFeeFromAmount = request.params[4].get_array();
  848. CCoinControl coin_control;
  849. if (request.params.size() > 5 && !request.params[5].isNull()) {
  850. coin_control.signalRbf = request.params[5].get_bool();
  851. }
  852. if (request.params.size() > 6 && !request.params[6].isNull()) {
  853. coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
  854. }
  855. if (request.params.size() > 7 && !request.params[7].isNull()) {
  856. if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
  857. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
  858. }
  859. }
  860. std::set<CBitcoinAddress> setAddress;
  861. std::vector<CRecipient> vecSend;
  862. CAmount totalAmount = 0;
  863. std::vector<std::string> keys = sendTo.getKeys();
  864. for (const std::string& name_ : keys)
  865. {
  866. CBitcoinAddress address(name_);
  867. if (!address.IsValid())
  868. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+name_);
  869. if (setAddress.count(address))
  870. throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
  871. setAddress.insert(address);
  872. CScript scriptPubKey = GetScriptForDestination(address.Get());
  873. CAmount nAmount = AmountFromValue(sendTo[name_]);
  874. if (nAmount <= 0)
  875. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
  876. totalAmount += nAmount;
  877. bool fSubtractFeeFromAmount = false;
  878. for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
  879. const UniValue& addr = subtractFeeFromAmount[idx];
  880. if (addr.get_str() == name_)
  881. fSubtractFeeFromAmount = true;
  882. }
  883. CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
  884. vecSend.push_back(recipient);
  885. }
  886. EnsureWalletIsUnlocked(pwallet);
  887. // Check funds
  888. CAmount nBalance = pwallet->GetLegacyBalance(ISMINE_SPENDABLE, nMinDepth, &strAccount);
  889. if (totalAmount > nBalance)
  890. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  891. // Send
  892. CReserveKey keyChange(pwallet);
  893. CAmount nFeeRequired = 0;
  894. int nChangePosRet = -1;
  895. std::string strFailReason;
  896. bool fCreated = pwallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
  897. if (!fCreated)
  898. throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
  899. CValidationState state;
  900. if (!pwallet->CommitTransaction(wtx, keyChange, g_connman.get(), state)) {
  901. strFailReason = strprintf("Transaction commit failed:: %s", state.GetRejectReason());
  902. throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
  903. }
  904. return wtx.GetHash().GetHex();
  905. }
  906. // Defined in rpc/misc.cpp
  907. extern CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params);
  908. UniValue addmultisigaddress(const JSONRPCRequest& request)
  909. {
  910. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  911. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  912. return NullUniValue;
  913. }
  914. if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
  915. {
  916. std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
  917. "\nAdd a nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
  918. "Each key is a Bitcoin address or hex-encoded public key.\n"
  919. "If 'account' is specified (DEPRECATED), assign address to that account.\n"
  920. "\nArguments:\n"
  921. "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
  922. "2. \"keys\" (string, required) A json array of bitcoin addresses or hex-encoded public keys\n"
  923. " [\n"
  924. " \"address\" (string) bitcoin address or hex-encoded public key\n"
  925. " ...,\n"
  926. " ]\n"
  927. "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
  928. "\nResult:\n"
  929. "\"address\" (string) A bitcoin address associated with the keys.\n"
  930. "\nExamples:\n"
  931. "\nAdd a multisig address from 2 addresses\n"
  932. + HelpExampleCli("addmultisigaddress", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
  933. "\nAs json rpc call\n"
  934. + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
  935. ;
  936. throw std::runtime_error(msg);
  937. }
  938. LOCK2(cs_main, pwallet->cs_wallet);
  939. std::string strAccount;
  940. if (request.params.size() > 2)
  941. strAccount = AccountFromValue(request.params[2]);
  942. // Construct using pay-to-script-hash:
  943. CScript inner = _createmultisig_redeemScript(pwallet, request.params);
  944. CScriptID innerID(inner);
  945. pwallet->AddCScript(inner);
  946. pwallet->SetAddressBook(innerID, strAccount, "send");
  947. return CBitcoinAddress(innerID).ToString();
  948. }
  949. class Witnessifier : public boost::static_visitor<bool>
  950. {
  951. public:
  952. CWallet * const pwallet;
  953. CScriptID result;
  954. Witnessifier(CWallet *_pwallet) : pwallet(_pwallet) {}
  955. bool operator()(const CNoDestination &dest) const { return false; }
  956. bool operator()(const CKeyID &keyID) {
  957. if (pwallet) {
  958. CScript basescript = GetScriptForDestination(keyID);
  959. CScript witscript = GetScriptForWitness(basescript);
  960. SignatureData sigs;
  961. // This check is to make sure that the script we created can actually be solved for and signed by us
  962. // if we were to have the private keys. This is just to make sure that the script is valid and that,
  963. // if found in a transaction, we would still accept and relay that transcation.
  964. if (!ProduceSignature(DummySignatureCreator(pwallet), witscript, sigs) ||
  965. !VerifyScript(sigs.scriptSig, witscript, &sigs.scriptWitness, MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, DummySignatureCreator(pwallet).Checker())) {
  966. return false;
  967. }
  968. pwallet->AddCScript(witscript);
  969. result = CScriptID(witscript);
  970. return true;
  971. }
  972. return false;
  973. }
  974. bool operator()(const CScriptID &scriptID) {
  975. CScript subscript;
  976. if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
  977. int witnessversion;
  978. std::vector<unsigned char> witprog;
  979. if (subscript.IsWitnessProgram(witnessversion, witprog)) {
  980. result = scriptID;
  981. return true;
  982. }
  983. CScript witscript = GetScriptForWitness(subscript);
  984. SignatureData sigs;
  985. // This check is to make sure that the script we created can actually be solved for and signed by us
  986. // if we were to have the private keys. This is just to make sure that the script is valid and that,
  987. // if found in a transaction, we would still accept and relay that transcation.
  988. if (!ProduceSignature(DummySignatureCreator(pwallet), witscript, sigs) ||
  989. !VerifyScript(sigs.scriptSig, witscript, &sigs.scriptWitness, MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, DummySignatureCreator(pwallet).Checker())) {
  990. return false;
  991. }
  992. pwallet->AddCScript(witscript);
  993. result = CScriptID(witscript);
  994. return true;
  995. }
  996. return false;
  997. }
  998. };
  999. UniValue addwitnessaddress(const JSONRPCRequest& request)
  1000. {
  1001. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1002. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1003. return NullUniValue;
  1004. }
  1005. if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
  1006. {
  1007. std::string msg = "addwitnessaddress \"address\"\n"
  1008. "\nAdd a witness address for a script (with pubkey or redeemscript known). Requires a new wallet backup.\n"
  1009. "It returns the witness script.\n"
  1010. "\nArguments:\n"
  1011. "1. \"address\" (string, required) An address known to the wallet\n"
  1012. "\nResult:\n"
  1013. "\"witnessaddress\", (string) The value of the new address (P2SH of witness script).\n"
  1014. "}\n"
  1015. ;
  1016. throw std::runtime_error(msg);
  1017. }
  1018. {
  1019. LOCK(cs_main);
  1020. if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()) && !gArgs.GetBoolArg("-walletprematurewitness", false)) {
  1021. throw JSONRPCError(RPC_WALLET_ERROR, "Segregated witness not enabled on network");
  1022. }
  1023. }
  1024. CBitcoinAddress address(request.params[0].get_str());
  1025. if (!address.IsValid())
  1026. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  1027. Witnessifier w(pwallet);
  1028. CTxDestination dest = address.Get();
  1029. bool ret = boost::apply_visitor(w, dest);
  1030. if (!ret) {
  1031. throw JSONRPCError(RPC_WALLET_ERROR, "Public key or redeemscript not known to wallet, or the key is uncompressed");
  1032. }
  1033. pwallet->SetAddressBook(w.result, "", "receive");
  1034. return CBitcoinAddress(w.result).ToString();
  1035. }
  1036. struct tallyitem
  1037. {
  1038. CAmount nAmount;
  1039. int nConf;
  1040. std::vector<uint256> txids;
  1041. bool fIsWatchonly;
  1042. tallyitem()
  1043. {
  1044. nAmount = 0;
  1045. nConf = std::numeric_limits<int>::max();
  1046. fIsWatchonly = false;
  1047. }
  1048. };
  1049. UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByAccounts)
  1050. {
  1051. // Minimum confirmations
  1052. int nMinDepth = 1;
  1053. if (!params[0].isNull())
  1054. nMinDepth = params[0].get_int();
  1055. // Whether to include empty accounts
  1056. bool fIncludeEmpty = false;
  1057. if (!params[1].isNull())
  1058. fIncludeEmpty = params[1].get_bool();
  1059. isminefilter filter = ISMINE_SPENDABLE;
  1060. if(!params[2].isNull())
  1061. if(params[2].get_bool())
  1062. filter = filter | ISMINE_WATCH_ONLY;
  1063. // Tally
  1064. std::map<CBitcoinAddress, tallyitem> mapTally;
  1065. for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
  1066. const CWalletTx& wtx = pairWtx.second;
  1067. if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
  1068. continue;
  1069. int nDepth = wtx.GetDepthInMainChain();
  1070. if (nDepth < nMinDepth)
  1071. continue;
  1072. for (const CTxOut& txout : wtx.tx->vout)
  1073. {
  1074. CTxDestination address;
  1075. if (!ExtractDestination(txout.scriptPubKey, address))
  1076. continue;
  1077. isminefilter mine = IsMine(*pwallet, address);
  1078. if(!(mine & filter))
  1079. continue;
  1080. tallyitem& item = mapTally[address];
  1081. item.nAmount += txout.nValue;
  1082. item.nConf = std::min(item.nConf, nDepth);
  1083. item.txids.push_back(wtx.GetHash());
  1084. if (mine & ISMINE_WATCH_ONLY)
  1085. item.fIsWatchonly = true;
  1086. }
  1087. }
  1088. // Reply
  1089. UniValue ret(UniValue::VARR);
  1090. std::map<std::string, tallyitem> mapAccountTally;
  1091. for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) {
  1092. const CBitcoinAddress& address = item.first;
  1093. const std::string& strAccount = item.second.name;
  1094. std::map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
  1095. if (it == mapTally.end() && !fIncludeEmpty)
  1096. continue;
  1097. CAmount nAmount = 0;
  1098. int nConf = std::numeric_limits<int>::max();
  1099. bool fIsWatchonly = false;
  1100. if (it != mapTally.end())
  1101. {
  1102. nAmount = (*it).second.nAmount;
  1103. nConf = (*it).second.nConf;
  1104. fIsWatchonly = (*it).second.fIsWatchonly;
  1105. }
  1106. if (fByAccounts)
  1107. {
  1108. tallyitem& _item = mapAccountTally[strAccount];
  1109. _item.nAmount += nAmount;
  1110. _item.nConf = std::min(_item.nConf, nConf);
  1111. _item.fIsWatchonly = fIsWatchonly;
  1112. }
  1113. else
  1114. {
  1115. UniValue obj(UniValue::VOBJ);
  1116. if(fIsWatchonly)
  1117. obj.push_back(Pair("involvesWatchonly", true));
  1118. obj.push_back(Pair("address", address.ToString()));
  1119. obj.push_back(Pair("account", strAccount));
  1120. obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
  1121. obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
  1122. if (!fByAccounts)
  1123. obj.push_back(Pair("label", strAccount));
  1124. UniValue transactions(UniValue::VARR);
  1125. if (it != mapTally.end())
  1126. {
  1127. for (const uint256& _item : (*it).second.txids)
  1128. {
  1129. transactions.push_back(_item.GetHex());
  1130. }
  1131. }
  1132. obj.push_back(Pair("txids", transactions));
  1133. ret.push_back(obj);
  1134. }
  1135. }
  1136. if (fByAccounts)
  1137. {
  1138. for (std::map<std::string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
  1139. {
  1140. CAmount nAmount = (*it).second.nAmount;
  1141. int nConf = (*it).second.nConf;
  1142. UniValue obj(UniValue::VOBJ);
  1143. if((*it).second.fIsWatchonly)
  1144. obj.push_back(Pair("involvesWatchonly", true));
  1145. obj.push_back(Pair("account", (*it).first));
  1146. obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
  1147. obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
  1148. ret.push_back(obj);
  1149. }
  1150. }
  1151. return ret;
  1152. }
  1153. UniValue listreceivedbyaddress(const JSONRPCRequest& request)
  1154. {
  1155. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1156. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1157. return NullUniValue;
  1158. }
  1159. if (request.fHelp || request.params.size() > 3)
  1160. throw std::runtime_error(
  1161. "listreceivedbyaddress ( minconf include_empty include_watchonly)\n"
  1162. "\nList balances by receiving address.\n"
  1163. "\nArguments:\n"
  1164. "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
  1165. "2. include_empty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n"
  1166. "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n"
  1167. "\nResult:\n"
  1168. "[\n"
  1169. " {\n"
  1170. " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
  1171. " \"address\" : \"receivingaddress\", (string) The receiving address\n"
  1172. " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
  1173. " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
  1174. " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
  1175. " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
  1176. " \"txids\": [\n"
  1177. " n, (numeric) The ids of transactions received with the address \n"
  1178. " ...\n"
  1179. " ]\n"
  1180. " }\n"
  1181. " ,...\n"
  1182. "]\n"
  1183. "\nExamples:\n"
  1184. + HelpExampleCli("listreceivedbyaddress", "")
  1185. + HelpExampleCli("listreceivedbyaddress", "6 true")
  1186. + HelpExampleRpc("listreceivedbyaddress", "6, true, true")
  1187. );
  1188. LOCK2(cs_main, pwallet->cs_wallet);
  1189. return ListReceived(pwallet, request.params, false);
  1190. }
  1191. UniValue listreceivedbyaccount(const JSONRPCRequest& request)
  1192. {
  1193. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1194. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1195. return NullUniValue;
  1196. }
  1197. if (request.fHelp || request.params.size() > 3)
  1198. throw std::runtime_error(
  1199. "listreceivedbyaccount ( minconf include_empty include_watchonly)\n"
  1200. "\nDEPRECATED. List balances by account.\n"
  1201. "\nArguments:\n"
  1202. "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
  1203. "2. include_empty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n"
  1204. "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n"
  1205. "\nResult:\n"
  1206. "[\n"
  1207. " {\n"
  1208. " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
  1209. " \"account\" : \"accountname\", (string) The account name of the receiving account\n"
  1210. " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
  1211. " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
  1212. " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
  1213. " }\n"
  1214. " ,...\n"
  1215. "]\n"
  1216. "\nExamples:\n"
  1217. + HelpExampleCli("listreceivedbyaccount", "")
  1218. + HelpExampleCli("listreceivedbyaccount", "6 true")
  1219. + HelpExampleRpc("listreceivedbyaccount", "6, true, true")
  1220. );
  1221. LOCK2(cs_main, pwallet->cs_wallet);
  1222. return ListReceived(pwallet, request.params, true);
  1223. }
  1224. static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
  1225. {
  1226. CBitcoinAddress addr;
  1227. if (addr.Set(dest))
  1228. entry.push_back(Pair("address", addr.ToString()));
  1229. }
  1230. /**
  1231. * List transactions based on the given criteria.
  1232. *
  1233. * @param pwallet The wallet.
  1234. * @param wtx The wallet transaction.
  1235. * @param strAccount The account, if any, or "*" for all.
  1236. * @param nMinDepth The minimum confirmation depth.
  1237. * @param fLong Whether to include the JSON version of the transaction.
  1238. * @param ret The UniValue into which the result is stored.
  1239. * @param filter The "is mine" filter bool.
  1240. */
  1241. void ListTransactions(CWallet* const pwallet, const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
  1242. {
  1243. CAmount nFee;
  1244. std::string strSentAccount;
  1245. std::list<COutputEntry> listReceived;
  1246. std::list<COutputEntry> listSent;
  1247. wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
  1248. bool fAllAccounts = (strAccount == std::string("*"));
  1249. bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
  1250. // Sent
  1251. if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
  1252. {
  1253. for (const COutputEntry& s : listSent)
  1254. {
  1255. UniValue entry(UniValue::VOBJ);
  1256. if (involvesWatchonly || (::IsMine(*pwallet, s.destination) & ISMINE_WATCH_ONLY)) {
  1257. entry.push_back(Pair("involvesWatchonly", true));
  1258. }
  1259. entry.push_back(Pair("account", strSentAccount));
  1260. MaybePushAddress(entry, s.destination);
  1261. entry.push_back(Pair("category", "send"));
  1262. entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
  1263. if (pwallet->mapAddressBook.count(s.destination)) {
  1264. entry.push_back(Pair("label", pwallet->mapAddressBook[s.destination].name));
  1265. }
  1266. entry.push_back(Pair("vout", s.vout));
  1267. entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
  1268. if (fLong)
  1269. WalletTxToJSON(wtx, entry);
  1270. entry.push_back(Pair("abandoned", wtx.isAbandoned()));
  1271. ret.push_back(entry);
  1272. }
  1273. }
  1274. // Received
  1275. if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
  1276. {
  1277. for (const COutputEntry& r : listReceived)
  1278. {
  1279. std::string account;
  1280. if (pwallet->mapAddressBook.count(r.destination)) {
  1281. account = pwallet->mapAddressBook[r.destination].name;
  1282. }
  1283. if (fAllAccounts || (account == strAccount))
  1284. {
  1285. UniValue entry(UniValue::VOBJ);
  1286. if (involvesWatchonly || (::IsMine(*pwallet, r.destination) & ISMINE_WATCH_ONLY)) {
  1287. entry.push_back(Pair("involvesWatchonly", true));
  1288. }
  1289. entry.push_back(Pair("account", account));
  1290. MaybePushAddress(entry, r.destination);
  1291. if (wtx.IsCoinBase())
  1292. {
  1293. if (wtx.GetDepthInMainChain() < 1)
  1294. entry.push_back(Pair("category", "orphan"));
  1295. else if (wtx.GetBlocksToMaturity() > 0)
  1296. entry.push_back(Pair("category", "immature"));
  1297. else
  1298. entry.push_back(Pair("category", "generate"));
  1299. }
  1300. else
  1301. {
  1302. entry.push_back(Pair("category", "receive"));
  1303. }
  1304. entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
  1305. if (pwallet->mapAddressBook.count(r.destination)) {
  1306. entry.push_back(Pair("label", account));
  1307. }
  1308. entry.push_back(Pair("vout", r.vout));
  1309. if (fLong)
  1310. WalletTxToJSON(wtx, entry);
  1311. ret.push_back(entry);
  1312. }
  1313. }
  1314. }
  1315. }
  1316. void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, UniValue& ret)
  1317. {
  1318. bool fAllAccounts = (strAccount == std::string("*"));
  1319. if (fAllAccounts || acentry.strAccount == strAccount)
  1320. {
  1321. UniValue entry(UniValue::VOBJ);
  1322. entry.push_back(Pair("account", acentry.strAccount));
  1323. entry.push_back(Pair("category", "move"));
  1324. entry.push_back(Pair("time", acentry.nTime));
  1325. entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
  1326. entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
  1327. entry.push_back(Pair("comment", acentry.strComment));
  1328. ret.push_back(entry);
  1329. }
  1330. }
  1331. UniValue listtransactions(const JSONRPCRequest& request)
  1332. {
  1333. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1334. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1335. return NullUniValue;
  1336. }
  1337. if (request.fHelp || request.params.size() > 4)
  1338. throw std::runtime_error(
  1339. "listtransactions ( \"account\" count skip include_watchonly)\n"
  1340. "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
  1341. "\nArguments:\n"
  1342. "1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
  1343. "2. count (numeric, optional, default=10) The number of transactions to return\n"
  1344. "3. skip (numeric, optional, default=0) The number of transactions to skip\n"
  1345. "4. include_watchonly (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')\n"
  1346. "\nResult:\n"
  1347. "[\n"
  1348. " {\n"
  1349. " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n"
  1350. " It will be \"\" for the default account.\n"
  1351. " \"address\":\"address\", (string) The bitcoin address of the transaction. Not present for \n"
  1352. " move transactions (category = move).\n"
  1353. " \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
  1354. " transaction between accounts, and not associated with an address,\n"
  1355. " transaction id or block. 'send' and 'receive' transactions are \n"
  1356. " associated with an address, transaction id and block details\n"
  1357. " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
  1358. " 'move' category for moves outbound. It is positive for the 'receive' category,\n"
  1359. " and for the 'move' category for inbound funds.\n"
  1360. " \"label\": \"label\", (string) A comment for the address/transaction, if any\n"
  1361. " \"vout\": n, (numeric) the vout value\n"
  1362. " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
  1363. " 'send' category of transactions.\n"
  1364. " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
  1365. " 'receive' category of transactions. Negative confirmations indicate the\n"
  1366. " transaction conflicts with the block chain\n"
  1367. " \"trusted\": xxx, (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
  1368. " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
  1369. " category of transactions.\n"
  1370. " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n"
  1371. " category of transactions.\n"
  1372. " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
  1373. " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
  1374. " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
  1375. " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
  1376. " for 'send' and 'receive' category of transactions.\n"
  1377. " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
  1378. " \"otheraccount\": \"accountname\", (string) DEPRECATED. For the 'move' category of transactions, the account the funds came \n"
  1379. " from (for receiving funds, positive amounts), or went to (for sending funds,\n"
  1380. " negative amounts).\n"
  1381. " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
  1382. " may be unknown for unconfirmed transactions not in the mempool\n"
  1383. " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
  1384. " 'send' category of transactions.\n"
  1385. " }\n"
  1386. "]\n"
  1387. "\nExamples:\n"
  1388. "\nList the most recent 10 transactions in the systems\n"
  1389. + HelpExampleCli("listtransactions", "") +
  1390. "\nList transactions 100 to 120\n"
  1391. + HelpExampleCli("listtransactions", "\"*\" 20 100") +
  1392. "\nAs a json rpc call\n"
  1393. + HelpExampleRpc("listtransactions", "\"*\", 20, 100")
  1394. );
  1395. LOCK2(cs_main, pwallet->cs_wallet);
  1396. std::string strAccount = "*";
  1397. if (!request.params[0].isNull())
  1398. strAccount = request.params[0].get_str();
  1399. int nCount = 10;
  1400. if (!request.params[1].isNull())
  1401. nCount = request.params[1].get_int();
  1402. int nFrom = 0;
  1403. if (!request.params[2].isNull())
  1404. nFrom = request.params[2].get_int();
  1405. isminefilter filter = ISMINE_SPENDABLE;
  1406. if(!request.params[3].isNull())
  1407. if(request.params[3].get_bool())
  1408. filter = filter | ISMINE_WATCH_ONLY;
  1409. if (nCount < 0)
  1410. throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
  1411. if (nFrom < 0)
  1412. throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
  1413. UniValue ret(UniValue::VARR);
  1414. const CWallet::TxItems & txOrdered = pwallet->wtxOrdered;
  1415. // iterate backwards until we have nCount items to return:
  1416. for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
  1417. {
  1418. CWalletTx *const pwtx = (*it).second.first;
  1419. if (pwtx != 0)
  1420. ListTransactions(pwallet, *pwtx, strAccount, 0, true, ret, filter);
  1421. CAccountingEntry *const pacentry = (*it).second.second;
  1422. if (pacentry != 0)
  1423. AcentryToJSON(*pacentry, strAccount, ret);
  1424. if ((int)ret.size() >= (nCount+nFrom)) break;
  1425. }
  1426. // ret is newest to oldest
  1427. if (nFrom > (int)ret.size())
  1428. nFrom = ret.size();
  1429. if ((nFrom + nCount) > (int)ret.size())
  1430. nCount = ret.size() - nFrom;
  1431. std::vector<UniValue> arrTmp = ret.getValues();
  1432. std::vector<UniValue>::iterator first = arrTmp.begin();
  1433. std::advance(first, nFrom);
  1434. std::vector<UniValue>::iterator last = arrTmp.begin();
  1435. std::advance(last, nFrom+nCount);
  1436. if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
  1437. if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
  1438. std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
  1439. ret.clear();
  1440. ret.setArray();
  1441. ret.push_backV(arrTmp);
  1442. return ret;
  1443. }
  1444. UniValue listaccounts(const JSONRPCRequest& request)
  1445. {
  1446. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1447. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1448. return NullUniValue;
  1449. }
  1450. if (request.fHelp || request.params.size() > 2)
  1451. throw std::runtime_error(
  1452. "listaccounts ( minconf include_watchonly)\n"
  1453. "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
  1454. "\nArguments:\n"
  1455. "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
  1456. "2. include_watchonly (bool, optional, default=false) Include balances in watch-only addresses (see 'importaddress')\n"
  1457. "\nResult:\n"
  1458. "{ (json object where keys are account names, and values are numeric balances\n"
  1459. " \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
  1460. " ...\n"
  1461. "}\n"
  1462. "\nExamples:\n"
  1463. "\nList account balances where there at least 1 confirmation\n"
  1464. + HelpExampleCli("listaccounts", "") +
  1465. "\nList account balances including zero confirmation transactions\n"
  1466. + HelpExampleCli("listaccounts", "0") +
  1467. "\nList account balances for 6 or more confirmations\n"
  1468. + HelpExampleCli("listaccounts", "6") +
  1469. "\nAs json rpc call\n"
  1470. + HelpExampleRpc("listaccounts", "6")
  1471. );
  1472. LOCK2(cs_main, pwallet->cs_wallet);
  1473. int nMinDepth = 1;
  1474. if (request.params.size() > 0)
  1475. nMinDepth = request.params[0].get_int();
  1476. isminefilter includeWatchonly = ISMINE_SPENDABLE;
  1477. if(request.params.size() > 1)
  1478. if(request.params[1].get_bool())
  1479. includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
  1480. std::map<std::string, CAmount> mapAccountBalances;
  1481. for (const std::pair<CTxDestination, CAddressBookData>& entry : pwallet->mapAddressBook) {
  1482. if (IsMine(*pwallet, entry.first) & includeWatchonly) { // This address belongs to me
  1483. mapAccountBalances[entry.second.name] = 0;
  1484. }
  1485. }
  1486. for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
  1487. const CWalletTx& wtx = pairWtx.second;
  1488. CAmount nFee;
  1489. std::string strSentAccount;
  1490. std::list<COutputEntry> listReceived;
  1491. std::list<COutputEntry> listSent;
  1492. int nDepth = wtx.GetDepthInMainChain();
  1493. if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
  1494. continue;
  1495. wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
  1496. mapAccountBalances[strSentAccount] -= nFee;
  1497. for (const COutputEntry& s : listSent)
  1498. mapAccountBalances[strSentAccount] -= s.amount;
  1499. if (nDepth >= nMinDepth)
  1500. {
  1501. for (const COutputEntry& r : listReceived)
  1502. if (pwallet->mapAddressBook.count(r.destination)) {
  1503. mapAccountBalances[pwallet->mapAddressBook[r.destination].name] += r.amount;
  1504. }
  1505. else
  1506. mapAccountBalances[""] += r.amount;
  1507. }
  1508. }
  1509. const std::list<CAccountingEntry>& acentries = pwallet->laccentries;
  1510. for (const CAccountingEntry& entry : acentries)
  1511. mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
  1512. UniValue ret(UniValue::VOBJ);
  1513. for (const std::pair<std::string, CAmount>& accountBalance : mapAccountBalances) {
  1514. ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
  1515. }
  1516. return ret;
  1517. }
  1518. UniValue listsinceblock(const JSONRPCRequest& request)
  1519. {
  1520. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1521. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1522. return NullUniValue;
  1523. }
  1524. if (request.fHelp || request.params.size() > 4)
  1525. throw std::runtime_error(
  1526. "listsinceblock ( \"blockhash\" target_confirmations include_watchonly include_removed )\n"
  1527. "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted.\n"
  1528. "If \"blockhash\" is no longer a part of the main chain, transactions from the fork point onward are included.\n"
  1529. "Additionally, if include_removed is set, transactions affecting the wallet which were removed are returned in the \"removed\" array.\n"
  1530. "\nArguments:\n"
  1531. "1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
  1532. "2. target_confirmations: (numeric, optional, default=1) Return the nth block hash from the main chain. e.g. 1 would mean the best block hash. Note: this is not used as a filter, but only affects [lastblock] in the return value\n"
  1533. "3. include_watchonly: (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')\n"
  1534. "4. include_removed: (bool, optional, default=true) Show transactions that were removed due to a reorg in the \"removed\" array\n"
  1535. " (not guaranteed to work on pruned nodes)\n"
  1536. "\nResult:\n"
  1537. "{\n"
  1538. " \"transactions\": [\n"
  1539. " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
  1540. " \"address\":\"address\", (string) The bitcoin address of the transaction. Not present for move transactions (category = move).\n"
  1541. " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
  1542. " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
  1543. " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
  1544. " \"vout\" : n, (numeric) the vout value\n"
  1545. " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
  1546. " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
  1547. " When it's < 0, it means the transaction conflicted that many blocks ago.\n"
  1548. " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
  1549. " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n"
  1550. " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
  1551. " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
  1552. " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
  1553. " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
  1554. " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
  1555. " may be unknown for unconfirmed transactions not in the mempool\n"
  1556. " \"abandoned\": xxx, (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the 'send' category of transactions.\n"
  1557. " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
  1558. " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
  1559. " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
  1560. " ],\n"
  1561. " \"removed\": [\n"
  1562. " <structure is the same as \"transactions\" above, only present if include_removed=true>\n"
  1563. " Note: transactions that were readded in the active chain will appear as-is in this array, and may thus have a positive confirmation count.\n"
  1564. " ],\n"
  1565. " \"lastblock\": \"lastblockhash\" (string) The hash of the block (target_confirmations-1) from the best block on the main chain. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones\n"
  1566. "}\n"
  1567. "\nExamples:\n"
  1568. + HelpExampleCli("listsinceblock", "")
  1569. + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
  1570. + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
  1571. );
  1572. LOCK2(cs_main, pwallet->cs_wallet);
  1573. const CBlockIndex* pindex = nullptr; // Block index of the specified block or the common ancestor, if the block provided was in a deactivated chain.
  1574. const CBlockIndex* paltindex = nullptr; // Block index of the specified block, even if it's in a deactivated chain.
  1575. int target_confirms = 1;
  1576. isminefilter filter = ISMINE_SPENDABLE;
  1577. if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
  1578. uint256 blockId;
  1579. blockId.SetHex(request.params[0].get_str());
  1580. BlockMap::iterator it = mapBlockIndex.find(blockId);
  1581. if (it == mapBlockIndex.end()) {
  1582. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  1583. }
  1584. paltindex = pindex = it->second;
  1585. if (chainActive[pindex->nHeight] != pindex) {
  1586. // the block being asked for is a part of a deactivated chain;
  1587. // we don't want to depend on its perceived height in the block
  1588. // chain, we want to instead use the last common ancestor
  1589. pindex = chainActive.FindFork(pindex);
  1590. }
  1591. }
  1592. if (!request.params[1].isNull()) {
  1593. target_confirms = request.params[1].get_int();
  1594. if (target_confirms < 1) {
  1595. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
  1596. }
  1597. }
  1598. if (!request.params[2].isNull() && request.params[2].get_bool()) {
  1599. filter = filter | ISMINE_WATCH_ONLY;
  1600. }
  1601. bool include_removed = (request.params[3].isNull() || request.params[3].get_bool());
  1602. int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
  1603. UniValue transactions(UniValue::VARR);
  1604. for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
  1605. CWalletTx tx = pairWtx.second;
  1606. if (depth == -1 || tx.GetDepthInMainChain() < depth) {
  1607. ListTransactions(pwallet, tx, "*", 0, true, transactions, filter);
  1608. }
  1609. }
  1610. // when a reorg'd block is requested, we also list any relevant transactions
  1611. // in the blocks of the chain that was detached
  1612. UniValue removed(UniValue::VARR);
  1613. while (include_removed && paltindex && paltindex != pindex) {
  1614. CBlock block;
  1615. if (!ReadBlockFromDisk(block, paltindex, Params().GetConsensus())) {
  1616. throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
  1617. }
  1618. for (const CTransactionRef& tx : block.vtx) {
  1619. if (pwallet->mapWallet.count(tx->GetHash()) > 0) {
  1620. // We want all transactions regardless of confirmation count to appear here,
  1621. // even negative confirmation ones, hence the big negative.
  1622. ListTransactions(pwallet, pwallet->mapWallet[tx->GetHash()], "*", -100000000, true, removed, filter);
  1623. }
  1624. }
  1625. paltindex = paltindex->pprev;
  1626. }
  1627. CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
  1628. uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
  1629. UniValue ret(UniValue::VOBJ);
  1630. ret.push_back(Pair("transactions", transactions));
  1631. if (include_removed) ret.push_back(Pair("removed", removed));
  1632. ret.push_back(Pair("lastblock", lastblock.GetHex()));
  1633. return ret;
  1634. }
  1635. UniValue gettransaction(const JSONRPCRequest& request)
  1636. {
  1637. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1638. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1639. return NullUniValue;
  1640. }
  1641. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  1642. throw std::runtime_error(
  1643. "gettransaction \"txid\" ( include_watchonly )\n"
  1644. "\nGet detailed information about in-wallet transaction <txid>\n"
  1645. "\nArguments:\n"
  1646. "1. \"txid\" (string, required) The transaction id\n"
  1647. "2. \"include_watchonly\" (bool, optional, default=false) Whether to include watch-only addresses in balance calculation and details[]\n"
  1648. "\nResult:\n"
  1649. "{\n"
  1650. " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
  1651. " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
  1652. " 'send' category of transactions.\n"
  1653. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  1654. " \"blockhash\" : \"hash\", (string) The block hash\n"
  1655. " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
  1656. " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
  1657. " \"txid\" : \"transactionid\", (string) The transaction id.\n"
  1658. " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
  1659. " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
  1660. " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
  1661. " may be unknown for unconfirmed transactions not in the mempool\n"
  1662. " \"details\" : [\n"
  1663. " {\n"
  1664. " \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
  1665. " \"address\" : \"address\", (string) The bitcoin address involved in the transaction\n"
  1666. " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
  1667. " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
  1668. " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
  1669. " \"vout\" : n, (numeric) the vout value\n"
  1670. " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
  1671. " 'send' category of transactions.\n"
  1672. " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
  1673. " 'send' category of transactions.\n"
  1674. " }\n"
  1675. " ,...\n"
  1676. " ],\n"
  1677. " \"hex\" : \"data\" (string) Raw data for transaction\n"
  1678. "}\n"
  1679. "\nExamples:\n"
  1680. + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
  1681. + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
  1682. + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
  1683. );
  1684. LOCK2(cs_main, pwallet->cs_wallet);
  1685. uint256 hash;
  1686. hash.SetHex(request.params[0].get_str());
  1687. isminefilter filter = ISMINE_SPENDABLE;
  1688. if(!request.params[1].isNull())
  1689. if(request.params[1].get_bool())
  1690. filter = filter | ISMINE_WATCH_ONLY;
  1691. UniValue entry(UniValue::VOBJ);
  1692. if (!pwallet->mapWallet.count(hash)) {
  1693. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
  1694. }
  1695. const CWalletTx& wtx = pwallet->mapWallet[hash];
  1696. CAmount nCredit = wtx.GetCredit(filter);
  1697. CAmount nDebit = wtx.GetDebit(filter);
  1698. CAmount nNet = nCredit - nDebit;
  1699. CAmount nFee = (wtx.IsFromMe(filter) ? wtx.tx->GetValueOut() - nDebit : 0);
  1700. entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
  1701. if (wtx.IsFromMe(filter))
  1702. entry.push_back(Pair("fee", ValueFromAmount(nFee)));
  1703. WalletTxToJSON(wtx, entry);
  1704. UniValue details(UniValue::VARR);
  1705. ListTransactions(pwallet, wtx, "*", 0, false, details, filter);
  1706. entry.push_back(Pair("details", details));
  1707. std::string strHex = EncodeHexTx(static_cast<CTransaction>(wtx), RPCSerializationFlags());
  1708. entry.push_back(Pair("hex", strHex));
  1709. return entry;
  1710. }
  1711. UniValue abandontransaction(const JSONRPCRequest& request)
  1712. {
  1713. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1714. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1715. return NullUniValue;
  1716. }
  1717. if (request.fHelp || request.params.size() != 1)
  1718. throw std::runtime_error(
  1719. "abandontransaction \"txid\"\n"
  1720. "\nMark in-wallet transaction <txid> as abandoned\n"
  1721. "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
  1722. "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
  1723. "It only works on transactions which are not included in a block and are not currently in the mempool.\n"
  1724. "It has no effect on transactions which are already conflicted or abandoned.\n"
  1725. "\nArguments:\n"
  1726. "1. \"txid\" (string, required) The transaction id\n"
  1727. "\nResult:\n"
  1728. "\nExamples:\n"
  1729. + HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
  1730. + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
  1731. );
  1732. LOCK2(cs_main, pwallet->cs_wallet);
  1733. uint256 hash;
  1734. hash.SetHex(request.params[0].get_str());
  1735. if (!pwallet->mapWallet.count(hash)) {
  1736. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
  1737. }
  1738. if (!pwallet->AbandonTransaction(hash)) {
  1739. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
  1740. }
  1741. return NullUniValue;
  1742. }
  1743. UniValue backupwallet(const JSONRPCRequest& request)
  1744. {
  1745. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1746. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1747. return NullUniValue;
  1748. }
  1749. if (request.fHelp || request.params.size() != 1)
  1750. throw std::runtime_error(
  1751. "backupwallet \"destination\"\n"
  1752. "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n"
  1753. "\nArguments:\n"
  1754. "1. \"destination\" (string) The destination directory or file\n"
  1755. "\nExamples:\n"
  1756. + HelpExampleCli("backupwallet", "\"backup.dat\"")
  1757. + HelpExampleRpc("backupwallet", "\"backup.dat\"")
  1758. );
  1759. LOCK2(cs_main, pwallet->cs_wallet);
  1760. std::string strDest = request.params[0].get_str();
  1761. if (!pwallet->BackupWallet(strDest)) {
  1762. throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
  1763. }
  1764. return NullUniValue;
  1765. }
  1766. UniValue keypoolrefill(const JSONRPCRequest& request)
  1767. {
  1768. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1769. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1770. return NullUniValue;
  1771. }
  1772. if (request.fHelp || request.params.size() > 1)
  1773. throw std::runtime_error(
  1774. "keypoolrefill ( newsize )\n"
  1775. "\nFills the keypool."
  1776. + HelpRequiringPassphrase(pwallet) + "\n"
  1777. "\nArguments\n"
  1778. "1. newsize (numeric, optional, default=100) The new keypool size\n"
  1779. "\nExamples:\n"
  1780. + HelpExampleCli("keypoolrefill", "")
  1781. + HelpExampleRpc("keypoolrefill", "")
  1782. );
  1783. LOCK2(cs_main, pwallet->cs_wallet);
  1784. // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
  1785. unsigned int kpSize = 0;
  1786. if (!request.params[0].isNull()) {
  1787. if (request.params[0].get_int() < 0)
  1788. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
  1789. kpSize = (unsigned int)request.params[0].get_int();
  1790. }
  1791. EnsureWalletIsUnlocked(pwallet);
  1792. pwallet->TopUpKeyPool(kpSize);
  1793. if (pwallet->GetKeyPoolSize() < kpSize) {
  1794. throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
  1795. }
  1796. return NullUniValue;
  1797. }
  1798. static void LockWallet(CWallet* pWallet)
  1799. {
  1800. LOCK(pWallet->cs_wallet);
  1801. pWallet->nRelockTime = 0;
  1802. pWallet->Lock();
  1803. }
  1804. UniValue walletpassphrase(const JSONRPCRequest& request)
  1805. {
  1806. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1807. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1808. return NullUniValue;
  1809. }
  1810. if (request.fHelp || request.params.size() != 2) {
  1811. throw std::runtime_error(
  1812. "walletpassphrase \"passphrase\" timeout\n"
  1813. "\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
  1814. "This is needed prior to performing transactions related to private keys such as sending bitcoins\n"
  1815. "\nArguments:\n"
  1816. "1. \"passphrase\" (string, required) The wallet passphrase\n"
  1817. "2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
  1818. "\nNote:\n"
  1819. "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
  1820. "time that overrides the old one.\n"
  1821. "\nExamples:\n"
  1822. "\nUnlock the wallet for 60 seconds\n"
  1823. + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
  1824. "\nLock the wallet again (before 60 seconds)\n"
  1825. + HelpExampleCli("walletlock", "") +
  1826. "\nAs json rpc call\n"
  1827. + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
  1828. );
  1829. }
  1830. LOCK2(cs_main, pwallet->cs_wallet);
  1831. if (request.fHelp)
  1832. return true;
  1833. if (!pwallet->IsCrypted()) {
  1834. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
  1835. }
  1836. // Note that the walletpassphrase is stored in request.params[0] which is not mlock()ed
  1837. SecureString strWalletPass;
  1838. strWalletPass.reserve(100);
  1839. // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
  1840. // Alternately, find a way to make request.params[0] mlock()'d to begin with.
  1841. strWalletPass = request.params[0].get_str().c_str();
  1842. if (strWalletPass.length() > 0)
  1843. {
  1844. if (!pwallet->Unlock(strWalletPass)) {
  1845. throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
  1846. }
  1847. }
  1848. else
  1849. throw std::runtime_error(
  1850. "walletpassphrase <passphrase> <timeout>\n"
  1851. "Stores the wallet decryption key in memory for <timeout> seconds.");
  1852. pwallet->TopUpKeyPool();
  1853. int64_t nSleepTime = request.params[1].get_int64();
  1854. pwallet->nRelockTime = GetTime() + nSleepTime;
  1855. RPCRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), boost::bind(LockWallet, pwallet), nSleepTime);
  1856. return NullUniValue;
  1857. }
  1858. UniValue walletpassphrasechange(const JSONRPCRequest& request)
  1859. {
  1860. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1861. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1862. return NullUniValue;
  1863. }
  1864. if (request.fHelp || request.params.size() != 2) {
  1865. throw std::runtime_error(
  1866. "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
  1867. "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
  1868. "\nArguments:\n"
  1869. "1. \"oldpassphrase\" (string) The current passphrase\n"
  1870. "2. \"newpassphrase\" (string) The new passphrase\n"
  1871. "\nExamples:\n"
  1872. + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
  1873. + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
  1874. );
  1875. }
  1876. LOCK2(cs_main, pwallet->cs_wallet);
  1877. if (request.fHelp)
  1878. return true;
  1879. if (!pwallet->IsCrypted()) {
  1880. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
  1881. }
  1882. // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
  1883. // Alternately, find a way to make request.params[0] mlock()'d to begin with.
  1884. SecureString strOldWalletPass;
  1885. strOldWalletPass.reserve(100);
  1886. strOldWalletPass = request.params[0].get_str().c_str();
  1887. SecureString strNewWalletPass;
  1888. strNewWalletPass.reserve(100);
  1889. strNewWalletPass = request.params[1].get_str().c_str();
  1890. if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
  1891. throw std::runtime_error(
  1892. "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
  1893. "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
  1894. if (!pwallet->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) {
  1895. throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
  1896. }
  1897. return NullUniValue;
  1898. }
  1899. UniValue walletlock(const JSONRPCRequest& request)
  1900. {
  1901. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1902. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1903. return NullUniValue;
  1904. }
  1905. if (request.fHelp || request.params.size() != 0) {
  1906. throw std::runtime_error(
  1907. "walletlock\n"
  1908. "\nRemoves the wallet encryption key from memory, locking the wallet.\n"
  1909. "After calling this method, you will need to call walletpassphrase again\n"
  1910. "before being able to call any methods which require the wallet to be unlocked.\n"
  1911. "\nExamples:\n"
  1912. "\nSet the passphrase for 2 minutes to perform a transaction\n"
  1913. + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
  1914. "\nPerform a send (requires passphrase set)\n"
  1915. + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 1.0") +
  1916. "\nClear the passphrase since we are done before 2 minutes is up\n"
  1917. + HelpExampleCli("walletlock", "") +
  1918. "\nAs json rpc call\n"
  1919. + HelpExampleRpc("walletlock", "")
  1920. );
  1921. }
  1922. LOCK2(cs_main, pwallet->cs_wallet);
  1923. if (request.fHelp)
  1924. return true;
  1925. if (!pwallet->IsCrypted()) {
  1926. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
  1927. }
  1928. pwallet->Lock();
  1929. pwallet->nRelockTime = 0;
  1930. return NullUniValue;
  1931. }
  1932. UniValue encryptwallet(const JSONRPCRequest& request)
  1933. {
  1934. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1935. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1936. return NullUniValue;
  1937. }
  1938. if (request.fHelp || request.params.size() != 1) {
  1939. throw std::runtime_error(
  1940. "encryptwallet \"passphrase\"\n"
  1941. "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
  1942. "After this, any calls that interact with private keys such as sending or signing \n"
  1943. "will require the passphrase to be set prior the making these calls.\n"
  1944. "Use the walletpassphrase call for this, and then walletlock call.\n"
  1945. "If the wallet is already encrypted, use the walletpassphrasechange call.\n"
  1946. "Note that this will shutdown the server.\n"
  1947. "\nArguments:\n"
  1948. "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
  1949. "\nExamples:\n"
  1950. "\nEncrypt your wallet\n"
  1951. + HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
  1952. "\nNow set the passphrase to use the wallet, such as for signing or sending bitcoin\n"
  1953. + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
  1954. "\nNow we can do something like sign\n"
  1955. + HelpExampleCli("signmessage", "\"address\" \"test message\"") +
  1956. "\nNow lock the wallet again by removing the passphrase\n"
  1957. + HelpExampleCli("walletlock", "") +
  1958. "\nAs a json rpc call\n"
  1959. + HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
  1960. );
  1961. }
  1962. LOCK2(cs_main, pwallet->cs_wallet);
  1963. if (request.fHelp)
  1964. return true;
  1965. if (pwallet->IsCrypted()) {
  1966. throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
  1967. }
  1968. // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
  1969. // Alternately, find a way to make request.params[0] mlock()'d to begin with.
  1970. SecureString strWalletPass;
  1971. strWalletPass.reserve(100);
  1972. strWalletPass = request.params[0].get_str().c_str();
  1973. if (strWalletPass.length() < 1)
  1974. throw std::runtime_error(
  1975. "encryptwallet <passphrase>\n"
  1976. "Encrypts the wallet with <passphrase>.");
  1977. if (!pwallet->EncryptWallet(strWalletPass)) {
  1978. throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
  1979. }
  1980. // BDB seems to have a bad habit of writing old data into
  1981. // slack space in .dat files; that is bad if the old data is
  1982. // unencrypted private keys. So:
  1983. StartShutdown();
  1984. return "wallet encrypted; Bitcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup.";
  1985. }
  1986. UniValue lockunspent(const JSONRPCRequest& request)
  1987. {
  1988. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  1989. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  1990. return NullUniValue;
  1991. }
  1992. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  1993. throw std::runtime_error(
  1994. "lockunspent unlock ([{\"txid\":\"txid\",\"vout\":n},...])\n"
  1995. "\nUpdates list of temporarily unspendable outputs.\n"
  1996. "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
  1997. "If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n"
  1998. "A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n"
  1999. "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
  2000. "is always cleared (by virtue of process exit) when a node stops or fails.\n"
  2001. "Also see the listunspent call\n"
  2002. "\nArguments:\n"
  2003. "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
  2004. "2. \"transactions\" (string, optional) A json array of objects. Each object the txid (string) vout (numeric)\n"
  2005. " [ (json array of json objects)\n"
  2006. " {\n"
  2007. " \"txid\":\"id\", (string) The transaction id\n"
  2008. " \"vout\": n (numeric) The output number\n"
  2009. " }\n"
  2010. " ,...\n"
  2011. " ]\n"
  2012. "\nResult:\n"
  2013. "true|false (boolean) Whether the command was successful or not\n"
  2014. "\nExamples:\n"
  2015. "\nList the unspent transactions\n"
  2016. + HelpExampleCli("listunspent", "") +
  2017. "\nLock an unspent transaction\n"
  2018. + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
  2019. "\nList the locked transactions\n"
  2020. + HelpExampleCli("listlockunspent", "") +
  2021. "\nUnlock the transaction again\n"
  2022. + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
  2023. "\nAs a json rpc call\n"
  2024. + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
  2025. );
  2026. LOCK2(cs_main, pwallet->cs_wallet);
  2027. if (request.params.size() == 1)
  2028. RPCTypeCheck(request.params, {UniValue::VBOOL});
  2029. else
  2030. RPCTypeCheck(request.params, {UniValue::VBOOL, UniValue::VARR});
  2031. bool fUnlock = request.params[0].get_bool();
  2032. if (request.params.size() == 1) {
  2033. if (fUnlock)
  2034. pwallet->UnlockAllCoins();
  2035. return true;
  2036. }
  2037. UniValue outputs = request.params[1].get_array();
  2038. for (unsigned int idx = 0; idx < outputs.size(); idx++) {
  2039. const UniValue& output = outputs[idx];
  2040. if (!output.isObject())
  2041. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
  2042. const UniValue& o = output.get_obj();
  2043. RPCTypeCheckObj(o,
  2044. {
  2045. {"txid", UniValueType(UniValue::VSTR)},
  2046. {"vout", UniValueType(UniValue::VNUM)},
  2047. });
  2048. std::string txid = find_value(o, "txid").get_str();
  2049. if (!IsHex(txid))
  2050. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
  2051. int nOutput = find_value(o, "vout").get_int();
  2052. if (nOutput < 0)
  2053. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
  2054. COutPoint outpt(uint256S(txid), nOutput);
  2055. if (fUnlock)
  2056. pwallet->UnlockCoin(outpt);
  2057. else
  2058. pwallet->LockCoin(outpt);
  2059. }
  2060. return true;
  2061. }
  2062. UniValue listlockunspent(const JSONRPCRequest& request)
  2063. {
  2064. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2065. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2066. return NullUniValue;
  2067. }
  2068. if (request.fHelp || request.params.size() > 0)
  2069. throw std::runtime_error(
  2070. "listlockunspent\n"
  2071. "\nReturns list of temporarily unspendable outputs.\n"
  2072. "See the lockunspent call to lock and unlock transactions for spending.\n"
  2073. "\nResult:\n"
  2074. "[\n"
  2075. " {\n"
  2076. " \"txid\" : \"transactionid\", (string) The transaction id locked\n"
  2077. " \"vout\" : n (numeric) The vout value\n"
  2078. " }\n"
  2079. " ,...\n"
  2080. "]\n"
  2081. "\nExamples:\n"
  2082. "\nList the unspent transactions\n"
  2083. + HelpExampleCli("listunspent", "") +
  2084. "\nLock an unspent transaction\n"
  2085. + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
  2086. "\nList the locked transactions\n"
  2087. + HelpExampleCli("listlockunspent", "") +
  2088. "\nUnlock the transaction again\n"
  2089. + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
  2090. "\nAs a json rpc call\n"
  2091. + HelpExampleRpc("listlockunspent", "")
  2092. );
  2093. LOCK2(cs_main, pwallet->cs_wallet);
  2094. std::vector<COutPoint> vOutpts;
  2095. pwallet->ListLockedCoins(vOutpts);
  2096. UniValue ret(UniValue::VARR);
  2097. for (COutPoint &outpt : vOutpts) {
  2098. UniValue o(UniValue::VOBJ);
  2099. o.push_back(Pair("txid", outpt.hash.GetHex()));
  2100. o.push_back(Pair("vout", (int)outpt.n));
  2101. ret.push_back(o);
  2102. }
  2103. return ret;
  2104. }
  2105. UniValue settxfee(const JSONRPCRequest& request)
  2106. {
  2107. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2108. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2109. return NullUniValue;
  2110. }
  2111. if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
  2112. throw std::runtime_error(
  2113. "settxfee amount\n"
  2114. "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
  2115. "\nArguments:\n"
  2116. "1. amount (numeric or string, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
  2117. "\nResult\n"
  2118. "true|false (boolean) Returns true if successful\n"
  2119. "\nExamples:\n"
  2120. + HelpExampleCli("settxfee", "0.00001")
  2121. + HelpExampleRpc("settxfee", "0.00001")
  2122. );
  2123. LOCK2(cs_main, pwallet->cs_wallet);
  2124. // Amount
  2125. CAmount nAmount = AmountFromValue(request.params[0]);
  2126. payTxFee = CFeeRate(nAmount, 1000);
  2127. return true;
  2128. }
  2129. UniValue getwalletinfo(const JSONRPCRequest& request)
  2130. {
  2131. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2132. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2133. return NullUniValue;
  2134. }
  2135. if (request.fHelp || request.params.size() != 0)
  2136. throw std::runtime_error(
  2137. "getwalletinfo\n"
  2138. "Returns an object containing various wallet state info.\n"
  2139. "\nResult:\n"
  2140. "{\n"
  2141. " \"walletname\": xxxxx, (string) the wallet name\n"
  2142. " \"walletversion\": xxxxx, (numeric) the wallet version\n"
  2143. " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
  2144. " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
  2145. " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
  2146. " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
  2147. " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
  2148. " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n"
  2149. " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n"
  2150. " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
  2151. " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
  2152. " \"hdmasterkeyid\": \"<hash160>\" (string) the Hash160 of the HD master pubkey\n"
  2153. "}\n"
  2154. "\nExamples:\n"
  2155. + HelpExampleCli("getwalletinfo", "")
  2156. + HelpExampleRpc("getwalletinfo", "")
  2157. );
  2158. LOCK2(cs_main, pwallet->cs_wallet);
  2159. UniValue obj(UniValue::VOBJ);
  2160. size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
  2161. obj.push_back(Pair("walletname", pwallet->GetName()));
  2162. obj.push_back(Pair("walletversion", pwallet->GetVersion()));
  2163. obj.push_back(Pair("balance", ValueFromAmount(pwallet->GetBalance())));
  2164. obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwallet->GetUnconfirmedBalance())));
  2165. obj.push_back(Pair("immature_balance", ValueFromAmount(pwallet->GetImmatureBalance())));
  2166. obj.push_back(Pair("txcount", (int)pwallet->mapWallet.size()));
  2167. obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
  2168. obj.push_back(Pair("keypoolsize", (int64_t)kpExternalSize));
  2169. CKeyID masterKeyID = pwallet->GetHDChain().masterKeyID;
  2170. if (!masterKeyID.IsNull() && pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) {
  2171. obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwallet->GetKeyPoolSize() - kpExternalSize)));
  2172. }
  2173. if (pwallet->IsCrypted()) {
  2174. obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
  2175. }
  2176. obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
  2177. if (!masterKeyID.IsNull())
  2178. obj.push_back(Pair("hdmasterkeyid", masterKeyID.GetHex()));
  2179. return obj;
  2180. }
  2181. UniValue listwallets(const JSONRPCRequest& request)
  2182. {
  2183. if (request.fHelp || request.params.size() != 0)
  2184. throw std::runtime_error(
  2185. "listwallets\n"
  2186. "Returns a list of currently loaded wallets.\n"
  2187. "For full information on the wallet, use \"getwalletinfo\"\n"
  2188. "\nResult:\n"
  2189. "[ (json array of strings)\n"
  2190. " \"walletname\" (string) the wallet name\n"
  2191. " ...\n"
  2192. "]\n"
  2193. "\nExamples:\n"
  2194. + HelpExampleCli("listwallets", "")
  2195. + HelpExampleRpc("listwallets", "")
  2196. );
  2197. UniValue obj(UniValue::VARR);
  2198. for (CWalletRef pwallet : vpwallets) {
  2199. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2200. return NullUniValue;
  2201. }
  2202. LOCK(pwallet->cs_wallet);
  2203. obj.push_back(pwallet->GetName());
  2204. }
  2205. return obj;
  2206. }
  2207. UniValue resendwallettransactions(const JSONRPCRequest& request)
  2208. {
  2209. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2210. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2211. return NullUniValue;
  2212. }
  2213. if (request.fHelp || request.params.size() != 0)
  2214. throw std::runtime_error(
  2215. "resendwallettransactions\n"
  2216. "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
  2217. "Intended only for testing; the wallet code periodically re-broadcasts\n"
  2218. "automatically.\n"
  2219. "Returns an RPC error if -walletbroadcast is set to false.\n"
  2220. "Returns array of transaction ids that were re-broadcast.\n"
  2221. );
  2222. if (!g_connman)
  2223. throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
  2224. LOCK2(cs_main, pwallet->cs_wallet);
  2225. if (!pwallet->GetBroadcastTransactions()) {
  2226. throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet transaction broadcasting is disabled with -walletbroadcast");
  2227. }
  2228. std::vector<uint256> txids = pwallet->ResendWalletTransactionsBefore(GetTime(), g_connman.get());
  2229. UniValue result(UniValue::VARR);
  2230. for (const uint256& txid : txids)
  2231. {
  2232. result.push_back(txid.ToString());
  2233. }
  2234. return result;
  2235. }
  2236. UniValue listunspent(const JSONRPCRequest& request)
  2237. {
  2238. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2239. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2240. return NullUniValue;
  2241. }
  2242. if (request.fHelp || request.params.size() > 5)
  2243. throw std::runtime_error(
  2244. "listunspent ( minconf maxconf [\"addresses\",...] [include_unsafe] [query_options])\n"
  2245. "\nReturns array of unspent transaction outputs\n"
  2246. "with between minconf and maxconf (inclusive) confirmations.\n"
  2247. "Optionally filter to only include txouts paid to specified addresses.\n"
  2248. "\nArguments:\n"
  2249. "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
  2250. "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
  2251. "3. \"addresses\" (string) A json array of bitcoin addresses to filter\n"
  2252. " [\n"
  2253. " \"address\" (string) bitcoin address\n"
  2254. " ,...\n"
  2255. " ]\n"
  2256. "4. include_unsafe (bool, optional, default=true) Include outputs that are not safe to spend\n"
  2257. " See description of \"safe\" attribute below.\n"
  2258. "5. query_options (json, optional) JSON with query options\n"
  2259. " {\n"
  2260. " \"minimumAmount\" (numeric or string, default=0) Minimum value of each UTXO in " + CURRENCY_UNIT + "\n"
  2261. " \"maximumAmount\" (numeric or string, default=unlimited) Maximum value of each UTXO in " + CURRENCY_UNIT + "\n"
  2262. " \"maximumCount\" (numeric or string, default=unlimited) Maximum number of UTXOs\n"
  2263. " \"minimumSumAmount\" (numeric or string, default=unlimited) Minimum sum value of all UTXOs in " + CURRENCY_UNIT + "\n"
  2264. " }\n"
  2265. "\nResult\n"
  2266. "[ (array of json object)\n"
  2267. " {\n"
  2268. " \"txid\" : \"txid\", (string) the transaction id \n"
  2269. " \"vout\" : n, (numeric) the vout value\n"
  2270. " \"address\" : \"address\", (string) the bitcoin address\n"
  2271. " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
  2272. " \"scriptPubKey\" : \"key\", (string) the script key\n"
  2273. " \"amount\" : x.xxx, (numeric) the transaction output amount in " + CURRENCY_UNIT + "\n"
  2274. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  2275. " \"redeemScript\" : n (string) The redeemScript if scriptPubKey is P2SH\n"
  2276. " \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n"
  2277. " \"solvable\" : xxx, (bool) Whether we know how to spend this output, ignoring the lack of keys\n"
  2278. " \"safe\" : xxx (bool) Whether this output is considered safe to spend. Unconfirmed transactions\n"
  2279. " from outside keys and unconfirmed replacement transactions are considered unsafe\n"
  2280. " and are not eligible for spending by fundrawtransaction and sendtoaddress.\n"
  2281. " }\n"
  2282. " ,...\n"
  2283. "]\n"
  2284. "\nExamples\n"
  2285. + HelpExampleCli("listunspent", "")
  2286. + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
  2287. + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
  2288. + HelpExampleCli("listunspent", "6 9999999 '[]' true '{ \"minimumAmount\": 0.005 }'")
  2289. + HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ")
  2290. );
  2291. int nMinDepth = 1;
  2292. if (request.params.size() > 0 && !request.params[0].isNull()) {
  2293. RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
  2294. nMinDepth = request.params[0].get_int();
  2295. }
  2296. int nMaxDepth = 9999999;
  2297. if (request.params.size() > 1 && !request.params[1].isNull()) {
  2298. RPCTypeCheckArgument(request.params[1], UniValue::VNUM);
  2299. nMaxDepth = request.params[1].get_int();
  2300. }
  2301. std::set<CBitcoinAddress> setAddress;
  2302. if (request.params.size() > 2 && !request.params[2].isNull()) {
  2303. RPCTypeCheckArgument(request.params[2], UniValue::VARR);
  2304. UniValue inputs = request.params[2].get_array();
  2305. for (unsigned int idx = 0; idx < inputs.size(); idx++) {
  2306. const UniValue& input = inputs[idx];
  2307. CBitcoinAddress address(input.get_str());
  2308. if (!address.IsValid())
  2309. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+input.get_str());
  2310. if (setAddress.count(address))
  2311. throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+input.get_str());
  2312. setAddress.insert(address);
  2313. }
  2314. }
  2315. bool include_unsafe = true;
  2316. if (request.params.size() > 3 && !request.params[3].isNull()) {
  2317. RPCTypeCheckArgument(request.params[3], UniValue::VBOOL);
  2318. include_unsafe = request.params[3].get_bool();
  2319. }
  2320. CAmount nMinimumAmount = 0;
  2321. CAmount nMaximumAmount = MAX_MONEY;
  2322. CAmount nMinimumSumAmount = MAX_MONEY;
  2323. uint64_t nMaximumCount = 0;
  2324. if (!request.params[4].isNull()) {
  2325. const UniValue& options = request.params[4].get_obj();
  2326. if (options.exists("minimumAmount"))
  2327. nMinimumAmount = AmountFromValue(options["minimumAmount"]);
  2328. if (options.exists("maximumAmount"))
  2329. nMaximumAmount = AmountFromValue(options["maximumAmount"]);
  2330. if (options.exists("minimumSumAmount"))
  2331. nMinimumSumAmount = AmountFromValue(options["minimumSumAmount"]);
  2332. if (options.exists("maximumCount"))
  2333. nMaximumCount = options["maximumCount"].get_int64();
  2334. }
  2335. UniValue results(UniValue::VARR);
  2336. std::vector<COutput> vecOutputs;
  2337. assert(pwallet != nullptr);
  2338. LOCK2(cs_main, pwallet->cs_wallet);
  2339. pwallet->AvailableCoins(vecOutputs, !include_unsafe, nullptr, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
  2340. for (const COutput& out : vecOutputs) {
  2341. CTxDestination address;
  2342. const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
  2343. bool fValidAddress = ExtractDestination(scriptPubKey, address);
  2344. if (setAddress.size() && (!fValidAddress || !setAddress.count(address)))
  2345. continue;
  2346. UniValue entry(UniValue::VOBJ);
  2347. entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
  2348. entry.push_back(Pair("vout", out.i));
  2349. if (fValidAddress) {
  2350. entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
  2351. if (pwallet->mapAddressBook.count(address)) {
  2352. entry.push_back(Pair("account", pwallet->mapAddressBook[address].name));
  2353. }
  2354. if (scriptPubKey.IsPayToScriptHash()) {
  2355. const CScriptID& hash = boost::get<CScriptID>(address);
  2356. CScript redeemScript;
  2357. if (pwallet->GetCScript(hash, redeemScript)) {
  2358. entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
  2359. }
  2360. }
  2361. }
  2362. entry.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
  2363. entry.push_back(Pair("amount", ValueFromAmount(out.tx->tx->vout[out.i].nValue)));
  2364. entry.push_back(Pair("confirmations", out.nDepth));
  2365. entry.push_back(Pair("spendable", out.fSpendable));
  2366. entry.push_back(Pair("solvable", out.fSolvable));
  2367. entry.push_back(Pair("safe", out.fSafe));
  2368. results.push_back(entry);
  2369. }
  2370. return results;
  2371. }
  2372. UniValue fundrawtransaction(const JSONRPCRequest& request)
  2373. {
  2374. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2375. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2376. return NullUniValue;
  2377. }
  2378. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  2379. throw std::runtime_error(
  2380. "fundrawtransaction \"hexstring\" ( options )\n"
  2381. "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
  2382. "This will not modify existing inputs, and will add at most one change output to the outputs.\n"
  2383. "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n"
  2384. "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
  2385. "The inputs added will not be signed, use signrawtransaction for that.\n"
  2386. "Note that all existing inputs must have their previous output transaction be in the wallet.\n"
  2387. "Note that all inputs selected must be of standard form and P2SH scripts must be\n"
  2388. "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
  2389. "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
  2390. "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
  2391. "\nArguments:\n"
  2392. "1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
  2393. "2. options (object, optional)\n"
  2394. " {\n"
  2395. " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n"
  2396. " \"changePosition\" (numeric, optional, default random) The index of the change output\n"
  2397. " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n"
  2398. " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n"
  2399. " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific feerate (" + CURRENCY_UNIT + " per KB)\n"
  2400. " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n"
  2401. " The fee will be equally deducted from the amount of each specified output.\n"
  2402. " The outputs are specified by their zero-based index, before any change output is added.\n"
  2403. " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
  2404. " If no outputs are specified here, the sender pays the fee.\n"
  2405. " [vout_index,...]\n"
  2406. " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n"
  2407. " Allows this transaction to be replaced by a transaction with higher fees\n"
  2408. " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n"
  2409. " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
  2410. " \"UNSET\"\n"
  2411. " \"ECONOMICAL\"\n"
  2412. " \"CONSERVATIVE\"\n"
  2413. " }\n"
  2414. " for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}\n"
  2415. "\nResult:\n"
  2416. "{\n"
  2417. " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
  2418. " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n"
  2419. " \"changepos\": n (numeric) The position of the added change output, or -1\n"
  2420. "}\n"
  2421. "\nExamples:\n"
  2422. "\nCreate a transaction with no inputs\n"
  2423. + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
  2424. "\nAdd sufficient unsigned inputs to meet the output value\n"
  2425. + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
  2426. "\nSign the transaction\n"
  2427. + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
  2428. "\nSend the transaction\n"
  2429. + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
  2430. );
  2431. RPCTypeCheck(request.params, {UniValue::VSTR});
  2432. CCoinControl coinControl;
  2433. int changePosition = -1;
  2434. bool lockUnspents = false;
  2435. UniValue subtractFeeFromOutputs;
  2436. std::set<int> setSubtractFeeFromOutputs;
  2437. if (!request.params[1].isNull()) {
  2438. if (request.params[1].type() == UniValue::VBOOL) {
  2439. // backward compatibility bool only fallback
  2440. coinControl.fAllowWatchOnly = request.params[1].get_bool();
  2441. }
  2442. else {
  2443. RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
  2444. UniValue options = request.params[1];
  2445. RPCTypeCheckObj(options,
  2446. {
  2447. {"changeAddress", UniValueType(UniValue::VSTR)},
  2448. {"changePosition", UniValueType(UniValue::VNUM)},
  2449. {"includeWatching", UniValueType(UniValue::VBOOL)},
  2450. {"lockUnspents", UniValueType(UniValue::VBOOL)},
  2451. {"reserveChangeKey", UniValueType(UniValue::VBOOL)}, // DEPRECATED (and ignored), should be removed in 0.16 or so.
  2452. {"feeRate", UniValueType()}, // will be checked below
  2453. {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
  2454. {"replaceable", UniValueType(UniValue::VBOOL)},
  2455. {"conf_target", UniValueType(UniValue::VNUM)},
  2456. {"estimate_mode", UniValueType(UniValue::VSTR)},
  2457. },
  2458. true, true);
  2459. if (options.exists("changeAddress")) {
  2460. CBitcoinAddress address(options["changeAddress"].get_str());
  2461. if (!address.IsValid())
  2462. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "changeAddress must be a valid bitcoin address");
  2463. coinControl.destChange = address.Get();
  2464. }
  2465. if (options.exists("changePosition"))
  2466. changePosition = options["changePosition"].get_int();
  2467. if (options.exists("includeWatching"))
  2468. coinControl.fAllowWatchOnly = options["includeWatching"].get_bool();
  2469. if (options.exists("lockUnspents"))
  2470. lockUnspents = options["lockUnspents"].get_bool();
  2471. if (options.exists("feeRate"))
  2472. {
  2473. coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
  2474. coinControl.fOverrideFeeRate = true;
  2475. }
  2476. if (options.exists("subtractFeeFromOutputs"))
  2477. subtractFeeFromOutputs = options["subtractFeeFromOutputs"].get_array();
  2478. if (options.exists("replaceable")) {
  2479. coinControl.signalRbf = options["replaceable"].get_bool();
  2480. }
  2481. if (options.exists("conf_target")) {
  2482. if (options.exists("feeRate")) {
  2483. throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and feeRate");
  2484. }
  2485. coinControl.m_confirm_target = ParseConfirmTarget(options["conf_target"]);
  2486. }
  2487. if (options.exists("estimate_mode")) {
  2488. if (options.exists("feeRate")) {
  2489. throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
  2490. }
  2491. if (!FeeModeFromString(options["estimate_mode"].get_str(), coinControl.m_fee_mode)) {
  2492. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
  2493. }
  2494. }
  2495. }
  2496. }
  2497. // parse hex string from parameter
  2498. CMutableTransaction tx;
  2499. if (!DecodeHexTx(tx, request.params[0].get_str(), true))
  2500. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
  2501. if (tx.vout.size() == 0)
  2502. throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
  2503. if (changePosition != -1 && (changePosition < 0 || (unsigned int)changePosition > tx.vout.size()))
  2504. throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
  2505. for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
  2506. int pos = subtractFeeFromOutputs[idx].get_int();
  2507. if (setSubtractFeeFromOutputs.count(pos))
  2508. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos));
  2509. if (pos < 0)
  2510. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos));
  2511. if (pos >= int(tx.vout.size()))
  2512. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos));
  2513. setSubtractFeeFromOutputs.insert(pos);
  2514. }
  2515. CAmount nFeeOut;
  2516. std::string strFailReason;
  2517. if (!pwallet->FundTransaction(tx, nFeeOut, changePosition, strFailReason, lockUnspents, setSubtractFeeFromOutputs, coinControl)) {
  2518. throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
  2519. }
  2520. UniValue result(UniValue::VOBJ);
  2521. result.push_back(Pair("hex", EncodeHexTx(tx)));
  2522. result.push_back(Pair("changepos", changePosition));
  2523. result.push_back(Pair("fee", ValueFromAmount(nFeeOut)));
  2524. return result;
  2525. }
  2526. UniValue bumpfee(const JSONRPCRequest& request)
  2527. {
  2528. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2529. if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
  2530. return NullUniValue;
  2531. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
  2532. throw std::runtime_error(
  2533. "bumpfee \"txid\" ( options ) \n"
  2534. "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n"
  2535. "An opt-in RBF transaction with the given txid must be in the wallet.\n"
  2536. "The command will pay the additional fee by decreasing (or perhaps removing) its change output.\n"
  2537. "If the change output is not big enough to cover the increased fee, the command will currently fail\n"
  2538. "instead of adding new inputs to compensate. (A future implementation could improve this.)\n"
  2539. "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
  2540. "By default, the new fee will be calculated automatically using estimatefee.\n"
  2541. "The user can specify a confirmation target for estimatefee.\n"
  2542. "Alternatively, the user can specify totalFee, or use RPC settxfee to set a higher fee rate.\n"
  2543. "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
  2544. "returned by getnetworkinfo) to enter the node's mempool.\n"
  2545. "\nArguments:\n"
  2546. "1. txid (string, required) The txid to be bumped\n"
  2547. "2. options (object, optional)\n"
  2548. " {\n"
  2549. " \"confTarget\" (numeric, optional) Confirmation target (in blocks)\n"
  2550. " \"totalFee\" (numeric, optional) Total fee (NOT feerate) to pay, in satoshis.\n"
  2551. " In rare cases, the actual fee paid might be slightly higher than the specified\n"
  2552. " totalFee if the tx change output has to be removed because it is too close to\n"
  2553. " the dust threshold.\n"
  2554. " \"replaceable\" (boolean, optional, default true) Whether the new transaction should still be\n"
  2555. " marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
  2556. " be left unchanged from the original. If false, any input sequence numbers in the\n"
  2557. " original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n"
  2558. " so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
  2559. " still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
  2560. " are replaceable).\n"
  2561. " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
  2562. " \"UNSET\"\n"
  2563. " \"ECONOMICAL\"\n"
  2564. " \"CONSERVATIVE\"\n"
  2565. " }\n"
  2566. "\nResult:\n"
  2567. "{\n"
  2568. " \"txid\": \"value\", (string) The id of the new transaction\n"
  2569. " \"origfee\": n, (numeric) Fee of the replaced transaction\n"
  2570. " \"fee\": n, (numeric) Fee of the new transaction\n"
  2571. " \"errors\": [ str... ] (json array of strings) Errors encountered during processing (may be empty)\n"
  2572. "}\n"
  2573. "\nExamples:\n"
  2574. "\nBump the fee, get the new transaction\'s txid\n" +
  2575. HelpExampleCli("bumpfee", "<txid>"));
  2576. }
  2577. RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
  2578. uint256 hash;
  2579. hash.SetHex(request.params[0].get_str());
  2580. // optional parameters
  2581. CAmount totalFee = 0;
  2582. CCoinControl coin_control;
  2583. coin_control.signalRbf = true;
  2584. if (!request.params[1].isNull()) {
  2585. UniValue options = request.params[1];
  2586. RPCTypeCheckObj(options,
  2587. {
  2588. {"confTarget", UniValueType(UniValue::VNUM)},
  2589. {"totalFee", UniValueType(UniValue::VNUM)},
  2590. {"replaceable", UniValueType(UniValue::VBOOL)},
  2591. {"estimate_mode", UniValueType(UniValue::VSTR)},
  2592. },
  2593. true, true);
  2594. if (options.exists("confTarget") && options.exists("totalFee")) {
  2595. throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and totalFee options should not both be set. Please provide either a confirmation target for fee estimation or an explicit total fee for the transaction.");
  2596. } else if (options.exists("confTarget")) { // TODO: alias this to conf_target
  2597. coin_control.m_confirm_target = ParseConfirmTarget(options["confTarget"]);
  2598. } else if (options.exists("totalFee")) {
  2599. totalFee = options["totalFee"].get_int64();
  2600. if (totalFee <= 0) {
  2601. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid totalFee %s (must be greater than 0)", FormatMoney(totalFee)));
  2602. }
  2603. }
  2604. if (options.exists("replaceable")) {
  2605. coin_control.signalRbf = options["replaceable"].get_bool();
  2606. }
  2607. if (options.exists("estimate_mode")) {
  2608. if (!FeeModeFromString(options["estimate_mode"].get_str(), coin_control.m_fee_mode)) {
  2609. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
  2610. }
  2611. }
  2612. }
  2613. LOCK2(cs_main, pwallet->cs_wallet);
  2614. EnsureWalletIsUnlocked(pwallet);
  2615. CFeeBumper feeBump(pwallet, hash, coin_control, totalFee);
  2616. BumpFeeResult res = feeBump.getResult();
  2617. if (res != BumpFeeResult::OK)
  2618. {
  2619. switch(res) {
  2620. case BumpFeeResult::INVALID_ADDRESS_OR_KEY:
  2621. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, feeBump.getErrors()[0]);
  2622. break;
  2623. case BumpFeeResult::INVALID_REQUEST:
  2624. throw JSONRPCError(RPC_INVALID_REQUEST, feeBump.getErrors()[0]);
  2625. break;
  2626. case BumpFeeResult::INVALID_PARAMETER:
  2627. throw JSONRPCError(RPC_INVALID_PARAMETER, feeBump.getErrors()[0]);
  2628. break;
  2629. case BumpFeeResult::WALLET_ERROR:
  2630. throw JSONRPCError(RPC_WALLET_ERROR, feeBump.getErrors()[0]);
  2631. break;
  2632. default:
  2633. throw JSONRPCError(RPC_MISC_ERROR, feeBump.getErrors()[0]);
  2634. break;
  2635. }
  2636. }
  2637. // sign bumped transaction
  2638. if (!feeBump.signTransaction(pwallet)) {
  2639. throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
  2640. }
  2641. // commit the bumped transaction
  2642. if(!feeBump.commit(pwallet)) {
  2643. throw JSONRPCError(RPC_WALLET_ERROR, feeBump.getErrors()[0]);
  2644. }
  2645. UniValue result(UniValue::VOBJ);
  2646. result.push_back(Pair("txid", feeBump.getBumpedTxId().GetHex()));
  2647. result.push_back(Pair("origfee", ValueFromAmount(feeBump.getOldFee())));
  2648. result.push_back(Pair("fee", ValueFromAmount(feeBump.getNewFee())));
  2649. UniValue errors(UniValue::VARR);
  2650. for (const std::string& err: feeBump.getErrors())
  2651. errors.push_back(err);
  2652. result.push_back(Pair("errors", errors));
  2653. return result;
  2654. }
  2655. UniValue generate(const JSONRPCRequest& request)
  2656. {
  2657. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  2658. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  2659. return NullUniValue;
  2660. }
  2661. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
  2662. throw std::runtime_error(
  2663. "generate nblocks ( maxtries )\n"
  2664. "\nMine up to nblocks blocks immediately (before the RPC call returns) to an address in the wallet.\n"
  2665. "\nArguments:\n"
  2666. "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
  2667. "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
  2668. "\nResult:\n"
  2669. "[ blockhashes ] (array) hashes of blocks generated\n"
  2670. "\nExamples:\n"
  2671. "\nGenerate 11 blocks\n"
  2672. + HelpExampleCli("generate", "11")
  2673. );
  2674. }
  2675. int num_generate = request.params[0].get_int();
  2676. uint64_t max_tries = 1000000;
  2677. if (request.params.size() > 1 && !request.params[1].isNull()) {
  2678. max_tries = request.params[1].get_int();
  2679. }
  2680. std::shared_ptr<CReserveScript> coinbase_script;
  2681. pwallet->GetScriptForMining(coinbase_script);
  2682. // If the keypool is exhausted, no script is returned at all. Catch this.
  2683. if (!coinbase_script) {
  2684. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  2685. }
  2686. //throw an error if no script was provided
  2687. if (coinbase_script->reserveScript.empty()) {
  2688. throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available");
  2689. }
  2690. return generateBlocks(coinbase_script, num_generate, max_tries, true);
  2691. }
  2692. extern UniValue abortrescan(const JSONRPCRequest& request); // in rpcdump.cpp
  2693. extern UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp
  2694. extern UniValue importprivkey(const JSONRPCRequest& request);
  2695. extern UniValue importaddress(const JSONRPCRequest& request);
  2696. extern UniValue importpubkey(const JSONRPCRequest& request);
  2697. extern UniValue dumpwallet(const JSONRPCRequest& request);
  2698. extern UniValue importwallet(const JSONRPCRequest& request);
  2699. extern UniValue importprunedfunds(const JSONRPCRequest& request);
  2700. extern UniValue removeprunedfunds(const JSONRPCRequest& request);
  2701. extern UniValue importmulti(const JSONRPCRequest& request);
  2702. static const CRPCCommand commands[] =
  2703. { // category name actor (function) okSafeMode
  2704. // --------------------- ------------------------ ----------------------- ----------
  2705. { "rawtransactions", "fundrawtransaction", &fundrawtransaction, false, {"hexstring","options"} },
  2706. { "hidden", "resendwallettransactions", &resendwallettransactions, true, {} },
  2707. { "wallet", "abandontransaction", &abandontransaction, false, {"txid"} },
  2708. { "wallet", "abortrescan", &abortrescan, false, {} },
  2709. { "wallet", "addmultisigaddress", &addmultisigaddress, true, {"nrequired","keys","account"} },
  2710. { "wallet", "addwitnessaddress", &addwitnessaddress, true, {"address"} },
  2711. { "wallet", "backupwallet", &backupwallet, true, {"destination"} },
  2712. { "wallet", "bumpfee", &bumpfee, true, {"txid", "options"} },
  2713. { "wallet", "dumpprivkey", &dumpprivkey, true, {"address"} },
  2714. { "wallet", "dumpwallet", &dumpwallet, true, {"filename"} },
  2715. { "wallet", "encryptwallet", &encryptwallet, true, {"passphrase"} },
  2716. { "wallet", "getaccountaddress", &getaccountaddress, true, {"account"} },
  2717. { "wallet", "getaccount", &getaccount, true, {"address"} },
  2718. { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, {"account"} },
  2719. { "wallet", "getbalance", &getbalance, false, {"account","minconf","include_watchonly"} },
  2720. { "wallet", "getnewaddress", &getnewaddress, true, {"account"} },
  2721. { "wallet", "getrawchangeaddress", &getrawchangeaddress, true, {} },
  2722. { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, {"account","minconf"} },
  2723. { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, {"address","minconf"} },
  2724. { "wallet", "gettransaction", &gettransaction, false, {"txid","include_watchonly"} },
  2725. { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, {} },
  2726. { "wallet", "getwalletinfo", &getwalletinfo, false, {} },
  2727. { "wallet", "importmulti", &importmulti, true, {"requests","options"} },
  2728. { "wallet", "importprivkey", &importprivkey, true, {"privkey","label","rescan"} },
  2729. { "wallet", "importwallet", &importwallet, true, {"filename"} },
  2730. { "wallet", "importaddress", &importaddress, true, {"address","label","rescan","p2sh"} },
  2731. { "wallet", "importprunedfunds", &importprunedfunds, true, {"rawtransaction","txoutproof"} },
  2732. { "wallet", "importpubkey", &importpubkey, true, {"pubkey","label","rescan"} },
  2733. { "wallet", "keypoolrefill", &keypoolrefill, true, {"newsize"} },
  2734. { "wallet", "listaccounts", &listaccounts, false, {"minconf","include_watchonly"} },
  2735. { "wallet", "listaddressgroupings", &listaddressgroupings, false, {} },
  2736. { "wallet", "listlockunspent", &listlockunspent, false, {} },
  2737. { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, {"minconf","include_empty","include_watchonly"} },
  2738. { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, {"minconf","include_empty","include_watchonly"} },
  2739. { "wallet", "listsinceblock", &listsinceblock, false, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
  2740. { "wallet", "listtransactions", &listtransactions, false, {"account","count","skip","include_watchonly"} },
  2741. { "wallet", "listunspent", &listunspent, false, {"minconf","maxconf","addresses","include_unsafe","query_options"} },
  2742. { "wallet", "listwallets", &listwallets, true, {} },
  2743. { "wallet", "lockunspent", &lockunspent, true, {"unlock","transactions"} },
  2744. { "wallet", "move", &movecmd, false, {"fromaccount","toaccount","amount","minconf","comment"} },
  2745. { "wallet", "sendfrom", &sendfrom, false, {"fromaccount","toaddress","amount","minconf","comment","comment_to"} },
  2746. { "wallet", "sendmany", &sendmany, false, {"fromaccount","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
  2747. { "wallet", "sendtoaddress", &sendtoaddress, false, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode"} },
  2748. { "wallet", "setaccount", &setaccount, true, {"address","account"} },
  2749. { "wallet", "settxfee", &settxfee, true, {"amount"} },
  2750. { "wallet", "signmessage", &signmessage, true, {"address","message"} },
  2751. { "wallet", "walletlock", &walletlock, true, {} },
  2752. { "wallet", "walletpassphrasechange", &walletpassphrasechange, true, {"oldpassphrase","newpassphrase"} },
  2753. { "wallet", "walletpassphrase", &walletpassphrase, true, {"passphrase","timeout"} },
  2754. { "wallet", "removeprunedfunds", &removeprunedfunds, true, {"txid"} },
  2755. { "generating", "generate", &generate, true, {"nblocks","maxtries"} },
  2756. };
  2757. void RegisterWalletRPCCommands(CRPCTable &t)
  2758. {
  2759. if (gArgs.GetBoolArg("-disablewallet", false))
  2760. return;
  2761. for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
  2762. t.appendCommand(commands[vcidx].name, &commands[vcidx]);
  2763. }