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

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