LCOV - code coverage report
Current view: top level - src/wallet - rpcwallet.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 645 1137 56.7 %
Date: 2015-10-12 22:39:14 Functions: 42 54 77.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : // Copyright (c) 2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2014 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             : 
       6             : #include "amount.h"
       7             : #include "base58.h"
       8             : #include "chain.h"
       9             : #include "core_io.h"
      10             : #include "init.h"
      11             : #include "main.h"
      12             : #include "net.h"
      13             : #include "netbase.h"
      14             : #include "rpcserver.h"
      15             : #include "timedata.h"
      16             : #include "util.h"
      17             : #include "utilmoneystr.h"
      18             : #include "wallet.h"
      19             : #include "walletdb.h"
      20             : 
      21             : #include <stdint.h>
      22             : 
      23             : #include <boost/assign/list_of.hpp>
      24             : 
      25             : #include <univalue.h>
      26             : 
      27             : using namespace std;
      28             : 
      29             : int64_t nWalletUnlockTime;
      30          96 : static CCriticalSection cs_nWalletUnlockTime;
      31             : 
      32           2 : std::string HelpRequiringPassphrase()
      33             : {
      34           2 :     return pwalletMain && pwalletMain->IsCrypted()
      35             :         ? "\nRequires wallet passphrase to be set with walletpassphrase call."
      36           6 :         : "";
      37             : }
      38             : 
      39         556 : bool EnsureWalletIsAvailable(bool avoidException)
      40             : {
      41         556 :     if (!pwalletMain)
      42             :     {
      43           0 :         if (!avoidException)
      44           0 :             throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
      45             :         else
      46             :             return false;
      47             :     }
      48             :     return true;
      49             : }
      50             : 
      51         165 : void EnsureWalletIsUnlocked()
      52             : {
      53         165 :     if (pwalletMain->IsLocked())
      54           3 :         throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
      55         164 : }
      56             : 
      57         185 : void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
      58             : {
      59         370 :     int confirms = wtx.GetDepthInMainChain();
      60         370 :     entry.push_back(Pair("confirmations", confirms));
      61         185 :     if (wtx.IsCoinBase())
      62         156 :         entry.push_back(Pair("generated", true));
      63         185 :     if (confirms > 0)
      64             :     {
      65         336 :         entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
      66         224 :         entry.push_back(Pair("blockindex", wtx.nIndex));
      67         448 :         entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
      68             :     }
      69         185 :     uint256 hash = wtx.GetHash();
      70         555 :     entry.push_back(Pair("txid", hash.GetHex()));
      71         555 :     UniValue conflicts(UniValue::VARR);
      72        1500 :     BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
      73           8 :         conflicts.push_back(conflict.GetHex());
      74         370 :     entry.push_back(Pair("walletconflicts", conflicts));
      75         370 :     entry.push_back(Pair("time", wtx.GetTxTime()));
      76         370 :     entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
      77         925 :     BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
      78         185 :         entry.push_back(Pair(item.first, item.second));
      79         185 : }
      80             : 
      81          56 : string AccountFromValue(const UniValue& value)
      82             : {
      83          56 :     string strAccount = value.get_str();
      84          56 :     if (strAccount == "*")
      85           0 :         throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
      86          56 :     return strAccount;
      87             : }
      88             : 
      89         178 : UniValue getnewaddress(const UniValue& params, bool fHelp)
      90             : {
      91         178 :     if (!EnsureWalletIsAvailable(fHelp))
      92           0 :         return NullUniValue;
      93             :     
      94         356 :     if (fHelp || params.size() > 1)
      95             :         throw runtime_error(
      96             :             "getnewaddress ( \"account\" )\n"
      97             :             "\nReturns a new Bitcoin address for receiving payments.\n"
      98             :             "If 'account' is specified (DEPRECATED), it is added to the address book \n"
      99             :             "so payments received with the address will be credited to 'account'.\n"
     100             :             "\nArguments:\n"
     101             :             "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"
     102             :             "\nResult:\n"
     103             :             "\"bitcoinaddress\"    (string) The new bitcoin address\n"
     104             :             "\nExamples:\n"
     105           0 :             + HelpExampleCli("getnewaddress", "")
     106           0 :             + HelpExampleRpc("getnewaddress", "")
     107           0 :         );
     108             : 
     109         178 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     110             : 
     111             :     // Parse the account first so we don't generate a key if there's an error
     112             :     string strAccount;
     113         178 :     if (params.size() > 0)
     114          36 :         strAccount = AccountFromValue(params[0]);
     115             : 
     116         178 :     if (!pwalletMain->IsLocked())
     117         178 :         pwalletMain->TopUpKeyPool();
     118             : 
     119             :     // Generate a new key that is added to wallet
     120             :     CPubKey newKey;
     121         178 :     if (!pwalletMain->GetKeyFromPool(newKey))
     122           0 :         throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
     123         178 :     CKeyID keyID = newKey.GetID();
     124             : 
     125         890 :     pwalletMain->SetAddressBook(keyID, strAccount, "receive");
     126             : 
     127         712 :     return CBitcoinAddress(keyID).ToString();
     128             : }
     129             : 
     130             : 
     131           5 : CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
     132             : {
     133           5 :     CWalletDB walletdb(pwalletMain->strWalletFile);
     134             : 
     135             :     CAccount account;
     136           5 :     walletdb.ReadAccount(strAccount, account);
     137             : 
     138           5 :     bool bKeyUsed = false;
     139             : 
     140             :     // Check if the current key has been used
     141           5 :     if (account.vchPubKey.IsValid())
     142             :     {
     143           3 :         CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
     144           3 :         for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
     145           2 :              it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
     146             :              ++it)
     147             :         {
     148           0 :             const CWalletTx& wtx = (*it).second;
     149           0 :             BOOST_FOREACH(const CTxOut& txout, wtx.vout)
     150           0 :                 if (txout.scriptPubKey == scriptPubKey)
     151             :                     bKeyUsed = true;
     152             :         }
     153             :     }
     154             : 
     155             :     // Generate a new key
     156           5 :     if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
     157             :     {
     158           4 :         if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
     159           0 :             throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
     160             : 
     161          20 :         pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
     162           4 :         walletdb.WriteAccount(strAccount, account);
     163             :     }
     164             : 
     165          20 :     return CBitcoinAddress(account.vchPubKey.GetID());
     166             : }
     167             : 
     168           5 : UniValue getaccountaddress(const UniValue& params, bool fHelp)
     169             : {
     170           5 :     if (!EnsureWalletIsAvailable(fHelp))
     171           0 :         return NullUniValue;
     172             :     
     173          10 :     if (fHelp || params.size() != 1)
     174             :         throw runtime_error(
     175             :             "getaccountaddress \"account\"\n"
     176             :             "\nDEPRECATED. Returns the current Bitcoin address for receiving payments to this account.\n"
     177             :             "\nArguments:\n"
     178             :             "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"
     179             :             "\nResult:\n"
     180             :             "\"bitcoinaddress\"   (string) The account bitcoin address\n"
     181             :             "\nExamples:\n"
     182           0 :             + HelpExampleCli("getaccountaddress", "")
     183           0 :             + HelpExampleCli("getaccountaddress", "\"\"")
     184           0 :             + HelpExampleCli("getaccountaddress", "\"myaccount\"")
     185           0 :             + HelpExampleRpc("getaccountaddress", "\"myaccount\"")
     186           0 :         );
     187             : 
     188           5 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     189             : 
     190             :     // Parse the account first so we don't generate a key if there's an error
     191           5 :     string strAccount = AccountFromValue(params[0]);
     192             : 
     193          20 :     UniValue ret(UniValue::VSTR);
     194             : 
     195          20 :     ret = GetAccountAddress(strAccount).ToString();
     196           5 :     return ret;
     197             : }
     198             : 
     199             : 
     200           1 : UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
     201             : {
     202           1 :     if (!EnsureWalletIsAvailable(fHelp))
     203           0 :         return NullUniValue;
     204             :     
     205           2 :     if (fHelp || params.size() > 1)
     206             :         throw runtime_error(
     207             :             "getrawchangeaddress\n"
     208             :             "\nReturns a new Bitcoin address, for receiving change.\n"
     209             :             "This is for use with raw transactions, NOT normal use.\n"
     210             :             "\nResult:\n"
     211             :             "\"address\"    (string) The address\n"
     212             :             "\nExamples:\n"
     213           0 :             + HelpExampleCli("getrawchangeaddress", "")
     214           0 :             + HelpExampleRpc("getrawchangeaddress", "")
     215           0 :        );
     216             : 
     217           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     218             : 
     219           1 :     if (!pwalletMain->IsLocked())
     220           1 :         pwalletMain->TopUpKeyPool();
     221             : 
     222           2 :     CReserveKey reservekey(pwalletMain);
     223             :     CPubKey vchPubKey;
     224           1 :     if (!reservekey.GetReservedKey(vchPubKey))
     225           0 :         throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
     226             : 
     227           1 :     reservekey.KeepKey();
     228             : 
     229           1 :     CKeyID keyID = vchPubKey.GetID();
     230             : 
     231           4 :     return CBitcoinAddress(keyID).ToString();
     232             : }
     233             : 
     234             : 
     235           4 : UniValue setaccount(const UniValue& params, bool fHelp)
     236             : {
     237           4 :     if (!EnsureWalletIsAvailable(fHelp))
     238           0 :         return NullUniValue;
     239             :     
     240          11 :     if (fHelp || params.size() < 1 || params.size() > 2)
     241             :         throw runtime_error(
     242             :             "setaccount \"bitcoinaddress\" \"account\"\n"
     243             :             "\nDEPRECATED. Sets the account associated with the given address.\n"
     244             :             "\nArguments:\n"
     245             :             "1. \"bitcoinaddress\"  (string, required) The bitcoin address to be associated with an account.\n"
     246             :             "2. \"account\"         (string, required) The account to assign the address to.\n"
     247             :             "\nExamples:\n"
     248           7 :             + HelpExampleCli("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"tabby\"")
     249           8 :             + HelpExampleRpc("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"tabby\"")
     250           3 :         );
     251             : 
     252           3 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     253             : 
     254           6 :     CBitcoinAddress address(params[0].get_str());
     255           3 :     if (!address.IsValid())
     256           3 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
     257             : 
     258             :     string strAccount;
     259           2 :     if (params.size() > 1)
     260           4 :         strAccount = AccountFromValue(params[1]);
     261             : 
     262             :     // Only add the account if the address is yours.
     263           4 :     if (IsMine(*pwalletMain, address.Get()))
     264             :     {
     265             :         // Detect when changing the account of an address that is the 'unused current key' of another account:
     266           3 :         if (pwalletMain->mapAddressBook.count(address.Get()))
     267             :         {
     268           0 :             string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
     269           0 :             if (address == GetAccountAddress(strOldAccount))
     270           0 :                 GetAccountAddress(strOldAccount, true);
     271             :         }
     272           5 :         pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
     273             :     }
     274             :     else
     275           3 :         throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
     276             : 
     277           1 :     return NullUniValue;
     278             : }
     279             : 
     280             : 
     281           2 : UniValue getaccount(const UniValue& params, bool fHelp)
     282             : {
     283           2 :     if (!EnsureWalletIsAvailable(fHelp))
     284           0 :         return NullUniValue;
     285             :     
     286           4 :     if (fHelp || params.size() != 1)
     287             :         throw runtime_error(
     288             :             "getaccount \"bitcoinaddress\"\n"
     289             :             "\nDEPRECATED. Returns the account associated with the given address.\n"
     290             :             "\nArguments:\n"
     291             :             "1. \"bitcoinaddress\"  (string, required) The bitcoin address for account lookup.\n"
     292             :             "\nResult:\n"
     293             :             "\"accountname\"        (string) the account address\n"
     294             :             "\nExamples:\n"
     295           7 :             + HelpExampleCli("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"")
     296           8 :             + HelpExampleRpc("getaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"")
     297           3 :         );
     298             : 
     299           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     300             : 
     301           2 :     CBitcoinAddress address(params[0].get_str());
     302           1 :     if (!address.IsValid())
     303           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
     304             : 
     305             :     string strAccount;
     306           3 :     map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
     307           4 :     if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
     308           1 :         strAccount = (*mi).second.name;
     309           1 :     return strAccount;
     310             : }
     311             : 
     312             : 
     313           2 : UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
     314             : {
     315           2 :     if (!EnsureWalletIsAvailable(fHelp))
     316           0 :         return NullUniValue;
     317             :     
     318           4 :     if (fHelp || params.size() != 1)
     319             :         throw runtime_error(
     320             :             "getaddressesbyaccount \"account\"\n"
     321             :             "\nDEPRECATED. Returns the list of addresses for the given account.\n"
     322             :             "\nArguments:\n"
     323             :             "1. \"account\"  (string, required) The account name.\n"
     324             :             "\nResult:\n"
     325             :             "[                     (json array of string)\n"
     326             :             "  \"bitcoinaddress\"  (string) a bitcoin address associated with the given account\n"
     327             :             "  ,...\n"
     328             :             "]\n"
     329             :             "\nExamples:\n"
     330           7 :             + HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
     331           8 :             + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
     332           3 :         );
     333             : 
     334           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     335             : 
     336           1 :     string strAccount = AccountFromValue(params[0]);
     337             : 
     338             :     // Find all addresses that have the given account
     339           4 :     UniValue ret(UniValue::VARR);
     340          48 :     BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
     341             :     {
     342           6 :         const CBitcoinAddress& address = item.first;
     343           6 :         const string& strName = item.second.name;
     344           6 :         if (strName == strAccount)
     345           2 :             ret.push_back(address.ToString());
     346             :     }
     347           1 :     return ret;
     348             : }
     349             : 
     350         119 : static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew)
     351             : {
     352         119 :     CAmount curBalance = pwalletMain->GetBalance();
     353             : 
     354             :     // Check amount
     355         119 :     if (nValue <= 0)
     356           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
     357             : 
     358         119 :     if (nValue > curBalance)
     359           0 :         throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
     360             : 
     361             :     // Parse Bitcoin address
     362         119 :     CScript scriptPubKey = GetScriptForDestination(address);
     363             : 
     364             :     // Create and send the transaction
     365         238 :     CReserveKey reservekey(pwalletMain);
     366             :     CAmount nFeeRequired;
     367             :     std::string strError;
     368         119 :     vector<CRecipient> vecSend;
     369         119 :     int nChangePosRet = -1;
     370         119 :     CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
     371         119 :     vecSend.push_back(recipient);
     372         119 :     if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError)) {
     373           0 :         if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance())
     374           0 :             strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
     375           0 :         throw JSONRPCError(RPC_WALLET_ERROR, strError);
     376             :     }
     377         119 :     if (!pwalletMain->CommitTransaction(wtxNew, reservekey))
     378           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
     379         119 : }
     380             : 
     381         113 : UniValue sendtoaddress(const UniValue& params, bool fHelp)
     382             : {
     383         113 :     if (!EnsureWalletIsAvailable(fHelp))
     384           0 :         return NullUniValue;
     385             :     
     386         339 :     if (fHelp || params.size() < 2 || params.size() > 5)
     387             :         throw runtime_error(
     388             :             "sendtoaddress \"bitcoinaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
     389             :             "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n"
     390           0 :             + HelpRequiringPassphrase() +
     391             :             "\nArguments:\n"
     392             :             "1. \"bitcoinaddress\"  (string, required) The bitcoin address to send to.\n"
     393           0 :             "2. \"amount\"      (numeric, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
     394             :             "3. \"comment\"     (string, optional) A comment used to store what the transaction is for. \n"
     395             :             "                             This is not part of the transaction, just kept in your wallet.\n"
     396             :             "4. \"comment-to\"  (string, optional) A comment to store the name of the person or organization \n"
     397             :             "                             to which you're sending the transaction. This is not part of the \n"
     398             :             "                             transaction, just kept in your wallet.\n"
     399             :             "5. subtractfeefromamount  (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
     400             :             "                             The recipient will receive less bitcoins than you enter in the amount field.\n"
     401             :             "\nResult:\n"
     402             :             "\"transactionid\"  (string) The transaction id.\n"
     403             :             "\nExamples:\n"
     404           0 :             + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1")
     405           0 :             + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"donation\" \"seans outpost\"")
     406           0 :             + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"\" \"\" true")
     407           0 :             + HelpExampleRpc("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.1, \"donation\", \"seans outpost\"")
     408           0 :         );
     409             : 
     410         113 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     411             : 
     412         226 :     CBitcoinAddress address(params[0].get_str());
     413         113 :     if (!address.IsValid())
     414           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
     415             : 
     416             :     // Amount
     417         113 :     CAmount nAmount = AmountFromValue(params[1]);
     418         112 :     if (nAmount <= 0)
     419           0 :         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
     420             : 
     421             :     // Wallet comments
     422         224 :     CWalletTx wtx;
     423         232 :     if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
     424           0 :         wtx.mapValue["comment"] = params[2].get_str();
     425         232 :     if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
     426           0 :         wtx.mapValue["to"]      = params[3].get_str();
     427             : 
     428         112 :     bool fSubtractFeeFromAmount = false;
     429         112 :     if (params.size() > 4)
     430           4 :         fSubtractFeeFromAmount = params[4].get_bool();
     431             : 
     432         112 :     EnsureWalletIsUnlocked();
     433             : 
     434         222 :     SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx);
     435             : 
     436         222 :     return wtx.GetHash().GetHex();
     437             : }
     438             : 
     439           1 : UniValue listaddressgroupings(const UniValue& params, bool fHelp)
     440             : {
     441           1 :     if (!EnsureWalletIsAvailable(fHelp))
     442           0 :         return NullUniValue;
     443             :     
     444           1 :     if (fHelp)
     445             :         throw runtime_error(
     446             :             "listaddressgroupings\n"
     447             :             "\nLists groups of addresses which have had their common ownership\n"
     448             :             "made public by common use as inputs or as the resulting change\n"
     449             :             "in past transactions\n"
     450             :             "\nResult:\n"
     451             :             "[\n"
     452             :             "  [\n"
     453             :             "    [\n"
     454             :             "      \"bitcoinaddress\",     (string) The bitcoin address\n"
     455           0 :             "      amount,                 (numeric) The amount in " + CURRENCY_UNIT + "\n"
     456             :             "      \"account\"             (string, optional) The account (DEPRECATED)\n"
     457             :             "    ]\n"
     458             :             "    ,...\n"
     459             :             "  ]\n"
     460             :             "  ,...\n"
     461             :             "]\n"
     462             :             "\nExamples:\n"
     463           0 :             + HelpExampleCli("listaddressgroupings", "")
     464           0 :             + HelpExampleRpc("listaddressgroupings", "")
     465           0 :         );
     466             : 
     467           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     468             : 
     469           4 :     UniValue jsonGroupings(UniValue::VARR);
     470           1 :     map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
     471           8 :     BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
     472             :     {
     473           0 :         UniValue jsonGrouping(UniValue::VARR);
     474           0 :         BOOST_FOREACH(CTxDestination address, grouping)
     475             :         {
     476           0 :             UniValue addressInfo(UniValue::VARR);
     477           0 :             addressInfo.push_back(CBitcoinAddress(address).ToString());
     478           0 :             addressInfo.push_back(ValueFromAmount(balances[address]));
     479             :             {
     480           0 :                 if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
     481           0 :                     addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
     482             :             }
     483           0 :             jsonGrouping.push_back(addressInfo);
     484           0 :         }
     485           0 :         jsonGroupings.push_back(jsonGrouping);
     486           0 :     }
     487           1 :     return jsonGroupings;
     488             : }
     489             : 
     490           3 : UniValue signmessage(const UniValue& params, bool fHelp)
     491             : {
     492           3 :     if (!EnsureWalletIsAvailable(fHelp))
     493           0 :         return NullUniValue;
     494             :     
     495           6 :     if (fHelp || params.size() != 2)
     496             :         throw runtime_error(
     497             :             "signmessage \"bitcoinaddress\" \"message\"\n"
     498             :             "\nSign a message with the private key of an address"
     499           4 :             + HelpRequiringPassphrase() + "\n"
     500             :             "\nArguments:\n"
     501             :             "1. \"bitcoinaddress\"  (string, required) The bitcoin address to use for the private key.\n"
     502             :             "2. \"message\"         (string, required) The message to create a signature of.\n"
     503             :             "\nResult:\n"
     504             :             "\"signature\"          (string) The signature of the message encoded in base 64\n"
     505             :             "\nExamples:\n"
     506             :             "\nUnlock the wallet for 30 seconds\n"
     507           9 :             + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
     508             :             "\nCreate the signature\n"
     509           9 :             + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
     510             :             "\nVerify the signature\n"
     511           9 :             + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
     512             :             "\nAs json rpc\n"
     513           8 :             + HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"my message\"")
     514           3 :         );
     515             : 
     516           2 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     517             : 
     518           2 :     EnsureWalletIsUnlocked();
     519             : 
     520           2 :     string strAddress = params[0].get_str();
     521           2 :     string strMessage = params[1].get_str();
     522             : 
     523           2 :     CBitcoinAddress addr(strAddress);
     524           2 :     if (!addr.IsValid())
     525           0 :         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
     526             : 
     527             :     CKeyID keyID;
     528           2 :     if (!addr.GetKeyID(keyID))
     529           0 :         throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
     530             : 
     531             :     CKey key;
     532           2 :     if (!pwalletMain->GetKey(keyID, key))
     533           3 :         throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
     534             : 
     535             :     CHashWriter ss(SER_GETHASH, 0);
     536             :     ss << strMessageMagic;
     537             :     ss << strMessage;
     538             : 
     539             :     vector<unsigned char> vchSig;
     540           1 :     if (!key.SignCompact(ss.GetHash(), vchSig))
     541           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
     542             : 
     543           3 :     return EncodeBase64(&vchSig[0], vchSig.size());
     544             : }
     545             : 
     546           0 : UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
     547             : {
     548           0 :     if (!EnsureWalletIsAvailable(fHelp))
     549           0 :         return NullUniValue;
     550             :     
     551           0 :     if (fHelp || params.size() < 1 || params.size() > 2)
     552             :         throw runtime_error(
     553             :             "getreceivedbyaddress \"bitcoinaddress\" ( minconf )\n"
     554             :             "\nReturns the total amount received by the given bitcoinaddress in transactions with at least minconf confirmations.\n"
     555             :             "\nArguments:\n"
     556             :             "1. \"bitcoinaddress\"  (string, required) The bitcoin address for transactions.\n"
     557             :             "2. minconf             (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
     558             :             "\nResult:\n"
     559           0 :             "amount   (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
     560             :             "\nExamples:\n"
     561             :             "\nThe amount from transactions with at least 1 confirmation\n"
     562           0 :             + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"") +
     563             :             "\nThe amount including unconfirmed transactions, zero confirmations\n"
     564           0 :             + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 0") +
     565             :             "\nThe amount with at least 6 confirmation, very safe\n"
     566           0 :             + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 6") +
     567             :             "\nAs a json rpc call\n"
     568           0 :             + HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", 6")
     569           0 :        );
     570             : 
     571           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     572             : 
     573             :     // Bitcoin address
     574           0 :     CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
     575           0 :     if (!address.IsValid())
     576           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
     577           0 :     CScript scriptPubKey = GetScriptForDestination(address.Get());
     578           0 :     if (!IsMine(*pwalletMain,scriptPubKey))
     579           0 :         return (double)0.0;
     580             : 
     581             :     // Minimum confirmations
     582           0 :     int nMinDepth = 1;
     583           0 :     if (params.size() > 1)
     584           0 :         nMinDepth = params[1].get_int();
     585             : 
     586             :     // Tally
     587           0 :     CAmount nAmount = 0;
     588           0 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
     589             :     {
     590           0 :         const CWalletTx& wtx = (*it).second;
     591           0 :         if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
     592             :             continue;
     593             : 
     594           0 :         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
     595           0 :             if (txout.scriptPubKey == scriptPubKey)
     596           0 :                 if (wtx.GetDepthInMainChain() >= nMinDepth)
     597           0 :                     nAmount += txout.nValue;
     598             :     }
     599             : 
     600           0 :     return  ValueFromAmount(nAmount);
     601             : }
     602             : 
     603             : 
     604           0 : UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
     605             : {
     606           0 :     if (!EnsureWalletIsAvailable(fHelp))
     607           0 :         return NullUniValue;
     608             :     
     609           0 :     if (fHelp || params.size() < 1 || params.size() > 2)
     610             :         throw runtime_error(
     611             :             "getreceivedbyaccount \"account\" ( minconf )\n"
     612             :             "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
     613             :             "\nArguments:\n"
     614             :             "1. \"account\"      (string, required) The selected account, may be the default account using \"\".\n"
     615             :             "2. minconf          (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
     616             :             "\nResult:\n"
     617           0 :             "amount              (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
     618             :             "\nExamples:\n"
     619             :             "\nAmount received by the default account with at least 1 confirmation\n"
     620           0 :             + HelpExampleCli("getreceivedbyaccount", "\"\"") +
     621             :             "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
     622           0 :             + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
     623             :             "\nThe amount with at least 6 confirmation, very safe\n"
     624           0 :             + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
     625             :             "\nAs a json rpc call\n"
     626           0 :             + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
     627           0 :         );
     628             : 
     629           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     630             : 
     631             :     // Minimum confirmations
     632           0 :     int nMinDepth = 1;
     633           0 :     if (params.size() > 1)
     634           0 :         nMinDepth = params[1].get_int();
     635             : 
     636             :     // Get the set of pub keys assigned to account
     637           0 :     string strAccount = AccountFromValue(params[0]);
     638           0 :     set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
     639             : 
     640             :     // Tally
     641           0 :     CAmount nAmount = 0;
     642           0 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
     643             :     {
     644           0 :         const CWalletTx& wtx = (*it).second;
     645           0 :         if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
     646             :             continue;
     647             : 
     648           0 :         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
     649             :         {
     650             :             CTxDestination address;
     651           0 :             if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
     652           0 :                 if (wtx.GetDepthInMainChain() >= nMinDepth)
     653           0 :                     nAmount += txout.nValue;
     654             :         }
     655             :     }
     656             : 
     657           0 :     return (double)nAmount / (double)COIN;
     658             : }
     659             : 
     660             : 
     661          30 : CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
     662             : {
     663          30 :     CAmount nBalance = 0;
     664             : 
     665             :     // Tally wallet transactions
     666        3032 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
     667             :     {
     668        1456 :         const CWalletTx& wtx = (*it).second;
     669        2213 :         if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
     670         711 :             continue;
     671             : 
     672             :         CAmount nReceived, nSent, nFee;
     673         745 :         wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
     674             : 
     675        1047 :         if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
     676         302 :             nBalance += nReceived;
     677         745 :         nBalance -= nSent + nFee;
     678             :     }
     679             : 
     680             :     // Tally internal accounting entries
     681          30 :     nBalance += walletdb.GetAccountCreditDebit(strAccount);
     682             : 
     683          30 :     return nBalance;
     684             : }
     685             : 
     686          30 : CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
     687             : {
     688          30 :     CWalletDB walletdb(pwalletMain->strWalletFile);
     689          60 :     return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
     690             : }
     691             : 
     692             : 
     693          90 : UniValue getbalance(const UniValue& params, bool fHelp)
     694             : {
     695          90 :     if (!EnsureWalletIsAvailable(fHelp))
     696           0 :         return NullUniValue;
     697             :     
     698         180 :     if (fHelp || params.size() > 3)
     699             :         throw runtime_error(
     700             :             "getbalance ( \"account\" minconf includeWatchonly )\n"
     701             :             "\nIf account is not specified, returns the server's total available balance.\n"
     702             :             "If account is specified (DEPRECATED), returns the balance in the account.\n"
     703             :             "Note that the account \"\" is not the same as leaving the parameter out.\n"
     704             :             "The server total may be different to the balance in the default \"\" account.\n"
     705             :             "\nArguments:\n"
     706             :             "1. \"account\"      (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
     707             :             "2. minconf          (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
     708             :             "3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
     709             :             "\nResult:\n"
     710           0 :             "amount              (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
     711             :             "\nExamples:\n"
     712             :             "\nThe total amount in the wallet\n"
     713           0 :             + HelpExampleCli("getbalance", "") +
     714             :             "\nThe total amount in the wallet at least 5 blocks confirmed\n"
     715           0 :             + HelpExampleCli("getbalance", "\"*\" 6") +
     716             :             "\nAs a json rpc call\n"
     717           0 :             + HelpExampleRpc("getbalance", "\"*\", 6")
     718           0 :         );
     719             : 
     720          90 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     721             : 
     722          90 :     if (params.size() == 0)
     723          71 :         return  ValueFromAmount(pwalletMain->GetBalance());
     724             : 
     725          19 :     int nMinDepth = 1;
     726          19 :     if (params.size() > 1)
     727           8 :         nMinDepth = params[1].get_int();
     728          19 :     isminefilter filter = ISMINE_SPENDABLE;
     729          19 :     if(params.size() > 2)
     730           0 :         if(params[2].get_bool())
     731           0 :             filter = filter | ISMINE_WATCH_ONLY;
     732             : 
     733          57 :     if (params[0].get_str() == "*") {
     734             :         // Calculate total balance a different way from GetBalance()
     735             :         // (GetBalance() sums up all unspent TxOuts)
     736             :         // getbalance and "getbalance * 1 true" should return the same number
     737           2 :         CAmount nBalance = 0;
     738         230 :         for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
     739             :         {
     740         111 :             const CWalletTx& wtx = (*it).second;
     741         175 :             if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
     742          50 :                 continue;
     743             : 
     744             :             CAmount allFee;
     745             :             string strSentAccount;
     746             :             list<COutputEntry> listReceived;
     747             :             list<COutputEntry> listSent;
     748          61 :             wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
     749         122 :             if (wtx.GetDepthInMainChain() >= nMinDepth)
     750             :             {
     751         661 :                 BOOST_FOREACH(const COutputEntry& r, listReceived)
     752          59 :                     nBalance += r.amount;
     753             :             }
     754         406 :             BOOST_FOREACH(const COutputEntry& s, listSent)
     755           8 :                 nBalance -= s.amount;
     756          61 :             nBalance -= allFee;
     757             :         }
     758           2 :         return  ValueFromAmount(nBalance);
     759             :     }
     760             : 
     761          17 :     string strAccount = AccountFromValue(params[0]);
     762             : 
     763          17 :     CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
     764             : 
     765          17 :     return ValueFromAmount(nBalance);
     766             : }
     767             : 
     768           0 : UniValue getunconfirmedbalance(const UniValue &params, bool fHelp)
     769             : {
     770           0 :     if (!EnsureWalletIsAvailable(fHelp))
     771           0 :         return NullUniValue;
     772             :     
     773           0 :     if (fHelp || params.size() > 0)
     774             :         throw runtime_error(
     775             :                 "getunconfirmedbalance\n"
     776           0 :                 "Returns the server's total unconfirmed balance\n");
     777             : 
     778           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     779             : 
     780           0 :     return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
     781             : }
     782             : 
     783             : 
     784           0 : UniValue movecmd(const UniValue& params, bool fHelp)
     785             : {
     786           0 :     if (!EnsureWalletIsAvailable(fHelp))
     787           0 :         return NullUniValue;
     788             :     
     789           0 :     if (fHelp || params.size() < 3 || params.size() > 5)
     790             :         throw runtime_error(
     791             :             "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
     792             :             "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
     793             :             "\nArguments:\n"
     794             :             "1. \"fromaccount\"   (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
     795             :             "2. \"toaccount\"     (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
     796           0 :             "3. amount            (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
     797             :             "4. minconf           (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
     798             :             "5. \"comment\"       (string, optional) An optional comment, stored in the wallet only.\n"
     799             :             "\nResult:\n"
     800             :             "true|false           (boolean) true if successful.\n"
     801             :             "\nExamples:\n"
     802           0 :             "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
     803           0 :             + HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
     804           0 :             "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n"
     805           0 :             + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
     806             :             "\nAs a json rpc call\n"
     807           0 :             + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"")
     808           0 :         );
     809             : 
     810           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     811             : 
     812           0 :     string strFrom = AccountFromValue(params[0]);
     813           0 :     string strTo = AccountFromValue(params[1]);
     814           0 :     CAmount nAmount = AmountFromValue(params[2]);
     815           0 :     if (nAmount <= 0)
     816           0 :         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
     817           0 :     if (params.size() > 3)
     818             :         // unused parameter, used to be nMinDepth, keep type-checking it though
     819           0 :         (void)params[3].get_int();
     820             :     string strComment;
     821           0 :     if (params.size() > 4)
     822           0 :         strComment = params[4].get_str();
     823             : 
     824           0 :     CWalletDB walletdb(pwalletMain->strWalletFile);
     825           0 :     if (!walletdb.TxnBegin())
     826           0 :         throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
     827             : 
     828           0 :     int64_t nNow = GetAdjustedTime();
     829             : 
     830             :     // Debit
     831           0 :     CAccountingEntry debit;
     832           0 :     debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
     833             :     debit.strAccount = strFrom;
     834           0 :     debit.nCreditDebit = -nAmount;
     835           0 :     debit.nTime = nNow;
     836             :     debit.strOtherAccount = strTo;
     837             :     debit.strComment = strComment;
     838           0 :     walletdb.WriteAccountingEntry(debit);
     839             : 
     840             :     // Credit
     841           0 :     CAccountingEntry credit;
     842           0 :     credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
     843             :     credit.strAccount = strTo;
     844           0 :     credit.nCreditDebit = nAmount;
     845           0 :     credit.nTime = nNow;
     846             :     credit.strOtherAccount = strFrom;
     847             :     credit.strComment = strComment;
     848           0 :     walletdb.WriteAccountingEntry(credit);
     849             : 
     850           0 :     if (!walletdb.TxnCommit())
     851           0 :         throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
     852             : 
     853           0 :     return true;
     854             : }
     855             : 
     856             : 
     857           8 : UniValue sendfrom(const UniValue& params, bool fHelp)
     858             : {
     859           8 :     if (!EnsureWalletIsAvailable(fHelp))
     860           0 :         return NullUniValue;
     861             :     
     862          24 :     if (fHelp || params.size() < 3 || params.size() > 6)
     863             :         throw runtime_error(
     864             :             "sendfrom \"fromaccount\" \"tobitcoinaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
     865             :             "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address.\n"
     866             :             "The amount is a real and is rounded to the nearest 0.00000001."
     867           0 :             + HelpRequiringPassphrase() + "\n"
     868             :             "\nArguments:\n"
     869             :             "1. \"fromaccount\"       (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
     870             :             "2. \"tobitcoinaddress\"  (string, required) The bitcoin address to send funds to.\n"
     871           0 :             "3. amount                (numeric, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
     872             :             "4. minconf               (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
     873             :             "5. \"comment\"           (string, optional) A comment used to store what the transaction is for. \n"
     874             :             "                                     This is not part of the transaction, just kept in your wallet.\n"
     875             :             "6. \"comment-to\"        (string, optional) An optional comment to store the name of the person or organization \n"
     876             :             "                                     to which you're sending the transaction. This is not part of the transaction, \n"
     877             :             "                                     it is just kept in your wallet.\n"
     878             :             "\nResult:\n"
     879             :             "\"transactionid\"        (string) The transaction id.\n"
     880             :             "\nExamples:\n"
     881           0 :             "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
     882           0 :             + HelpExampleCli("sendfrom", "\"\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01") +
     883             :             "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
     884           0 :             + HelpExampleCli("sendfrom", "\"tabby\" \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.01 6 \"donation\" \"seans outpost\"") +
     885             :             "\nAs a json rpc call\n"
     886           0 :             + HelpExampleRpc("sendfrom", "\"tabby\", \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.01, 6, \"donation\", \"seans outpost\"")
     887           0 :         );
     888             : 
     889           8 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     890             : 
     891           8 :     string strAccount = AccountFromValue(params[0]);
     892          16 :     CBitcoinAddress address(params[1].get_str());
     893           8 :     if (!address.IsValid())
     894           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
     895           8 :     CAmount nAmount = AmountFromValue(params[2]);
     896           8 :     if (nAmount <= 0)
     897           0 :         throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
     898           8 :     int nMinDepth = 1;
     899           8 :     if (params.size() > 3)
     900           4 :         nMinDepth = params[3].get_int();
     901             : 
     902          16 :     CWalletTx wtx;
     903             :     wtx.strFromAccount = strAccount;
     904          16 :     if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
     905           0 :         wtx.mapValue["comment"] = params[4].get_str();
     906          16 :     if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
     907           0 :         wtx.mapValue["to"]      = params[5].get_str();
     908             : 
     909           8 :     EnsureWalletIsUnlocked();
     910             : 
     911             :     // Check funds
     912           8 :     CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
     913           8 :     if (nAmount > nBalance)
     914           0 :         throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
     915             : 
     916          16 :     SendMoney(address.Get(), nAmount, false, wtx);
     917             : 
     918          16 :     return wtx.GetHash().GetHex();
     919             : }
     920             : 
     921             : 
     922           5 : UniValue sendmany(const UniValue& params, bool fHelp)
     923             : {
     924           5 :     if (!EnsureWalletIsAvailable(fHelp))
     925           0 :         return NullUniValue;
     926             :     
     927          15 :     if (fHelp || params.size() < 2 || params.size() > 5)
     928             :         throw runtime_error(
     929             :             "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] )\n"
     930             :             "\nSend multiple times. Amounts are double-precision floating point numbers."
     931           0 :             + HelpRequiringPassphrase() + "\n"
     932             :             "\nArguments:\n"
     933             :             "1. \"fromaccount\"         (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
     934             :             "2. \"amounts\"             (string, required) A json object with addresses and amounts\n"
     935             :             "    {\n"
     936           0 :             "      \"address\":amount   (numeric) The bitcoin address is the key, the numeric amount in " + CURRENCY_UNIT + " is the value\n"
     937             :             "      ,...\n"
     938             :             "    }\n"
     939             :             "3. minconf                 (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
     940             :             "4. \"comment\"             (string, optional) A comment\n"
     941             :             "5. subtractfeefromamount   (string, optional) A json array with addresses.\n"
     942             :             "                           The fee will be equally deducted from the amount of each selected address.\n"
     943             :             "                           Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
     944             :             "                           If no addresses are specified here, the sender pays the fee.\n"
     945             :             "    [\n"
     946             :             "      \"address\"            (string) Subtract fee from this address\n"
     947             :             "      ,...\n"
     948             :             "    ]\n"
     949             :             "\nResult:\n"
     950             :             "\"transactionid\"          (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
     951             :             "                                    the number of addresses.\n"
     952             :             "\nExamples:\n"
     953             :             "\nSend two amounts to two different addresses:\n"
     954           0 :             + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
     955             :             "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
     956           0 :             + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
     957             :             "\nSend two amounts to two different addresses, subtract fee from amount:\n"
     958           0 :             + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
     959             :             "\nAs a json rpc call\n"
     960           0 :             + HelpExampleRpc("sendmany", "\"\", \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\", 6, \"testing\"")
     961           0 :         );
     962             : 
     963           5 :     LOCK2(cs_main, pwalletMain->cs_wallet);
     964             : 
     965           5 :     string strAccount = AccountFromValue(params[0]);
     966          10 :     UniValue sendTo = params[1].get_obj();
     967           5 :     int nMinDepth = 1;
     968           5 :     if (params.size() > 2)
     969           2 :         nMinDepth = params[2].get_int();
     970             : 
     971          10 :     CWalletTx wtx;
     972             :     wtx.strFromAccount = strAccount;
     973          14 :     if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
     974           0 :         wtx.mapValue["comment"] = params[3].get_str();
     975             : 
     976          20 :     UniValue subtractFeeFromAmount(UniValue::VARR);
     977           5 :     if (params.size() > 4)
     978           2 :         subtractFeeFromAmount = params[4].get_array();
     979             : 
     980             :     set<CBitcoinAddress> setAddress;
     981           5 :     vector<CRecipient> vecSend;
     982             : 
     983           5 :     CAmount totalAmount = 0;
     984          10 :     vector<string> keys = sendTo.getKeys();
     985         100 :     BOOST_FOREACH(const string& name_, keys)
     986             :     {
     987          14 :         CBitcoinAddress address(name_);
     988          14 :         if (!address.IsValid())
     989           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+name_);
     990             : 
     991          14 :         if (setAddress.count(address))
     992           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
     993             :         setAddress.insert(address);
     994             : 
     995          28 :         CScript scriptPubKey = GetScriptForDestination(address.Get());
     996          14 :         CAmount nAmount = AmountFromValue(sendTo[name_]);
     997          14 :         if (nAmount <= 0)
     998           0 :             throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
     999          14 :         totalAmount += nAmount;
    1000             : 
    1001          14 :         bool fSubtractFeeFromAmount = false;
    1002          30 :         for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
    1003           1 :             const UniValue& addr = subtractFeeFromAmount[idx];
    1004           2 :             if (addr.get_str() == name_)
    1005           1 :                 fSubtractFeeFromAmount = true;
    1006             :         }
    1007             : 
    1008          14 :         CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
    1009          14 :         vecSend.push_back(recipient);
    1010             :     }
    1011             : 
    1012           5 :     EnsureWalletIsUnlocked();
    1013             : 
    1014             :     // Check funds
    1015           5 :     CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
    1016           5 :     if (totalAmount > nBalance)
    1017           0 :         throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
    1018             : 
    1019             :     // Send
    1020          10 :     CReserveKey keyChange(pwalletMain);
    1021           5 :     CAmount nFeeRequired = 0;
    1022           5 :     int nChangePosRet = -1;
    1023             :     string strFailReason;
    1024           5 :     bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason);
    1025           5 :     if (!fCreated)
    1026           0 :         throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
    1027           5 :     if (!pwalletMain->CommitTransaction(wtx, keyChange))
    1028           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
    1029             : 
    1030          10 :     return wtx.GetHash().GetHex();
    1031             : }
    1032             : 
    1033             : // Defined in rpcmisc.cpp
    1034             : extern CScript _createmultisig_redeemScript(const UniValue& params);
    1035             : 
    1036          15 : UniValue addmultisigaddress(const UniValue& params, bool fHelp)
    1037             : {
    1038          15 :     if (!EnsureWalletIsAvailable(fHelp))
    1039           0 :         return NullUniValue;
    1040             :     
    1041          45 :     if (fHelp || params.size() < 2 || params.size() > 3)
    1042             :     {
    1043             :         string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
    1044             :             "\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
    1045             :             "Each key is a Bitcoin address or hex-encoded public key.\n"
    1046             :             "If 'account' is specified (DEPRECATED), assign address to that account.\n"
    1047             : 
    1048             :             "\nArguments:\n"
    1049             :             "1. nrequired        (numeric, required) The number of required signatures out of the n keys or addresses.\n"
    1050             :             "2. \"keysobject\"   (string, required) A json array of bitcoin addresses or hex-encoded public keys\n"
    1051             :             "     [\n"
    1052             :             "       \"address\"  (string) bitcoin address or hex-encoded public key\n"
    1053             :             "       ...,\n"
    1054             :             "     ]\n"
    1055             :             "3. \"account\"      (string, optional) DEPRECATED. An account to assign the addresses to.\n"
    1056             : 
    1057             :             "\nResult:\n"
    1058             :             "\"bitcoinaddress\"  (string) A bitcoin address associated with the keys.\n"
    1059             : 
    1060             :             "\nExamples:\n"
    1061             :             "\nAdd a multisig address from 2 addresses\n"
    1062           0 :             + HelpExampleCli("addmultisigaddress", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
    1063             :             "\nAs json rpc call\n"
    1064           0 :             + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
    1065             :         ;
    1066           0 :         throw runtime_error(msg);
    1067             :     }
    1068             : 
    1069          15 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1070             : 
    1071             :     string strAccount;
    1072          15 :     if (params.size() > 2)
    1073           0 :         strAccount = AccountFromValue(params[2]);
    1074             : 
    1075             :     // Construct using pay-to-script-hash:
    1076          15 :     CScript inner = _createmultisig_redeemScript(params);
    1077           8 :     CScriptID innerID(inner);
    1078           8 :     pwalletMain->AddCScript(inner);
    1079             : 
    1080          40 :     pwalletMain->SetAddressBook(innerID, strAccount, "send");
    1081          32 :     return CBitcoinAddress(innerID).ToString();
    1082             : }
    1083             : 
    1084             : 
    1085          16 : struct tallyitem
    1086             : {
    1087             :     CAmount nAmount;
    1088             :     int nConf;
    1089             :     vector<uint256> txids;
    1090             :     bool fIsWatchonly;
    1091           0 :     tallyitem()
    1092           2 :     {
    1093           2 :         nAmount = 0;
    1094           2 :         nConf = std::numeric_limits<int>::max();
    1095           2 :         fIsWatchonly = false;
    1096           0 :     }
    1097             : };
    1098             : 
    1099           6 : UniValue ListReceived(const UniValue& params, bool fByAccounts)
    1100             : {
    1101             :     // Minimum confirmations
    1102           6 :     int nMinDepth = 1;
    1103           6 :     if (params.size() > 0)
    1104           4 :         nMinDepth = params[0].get_int();
    1105             : 
    1106             :     // Whether to include empty accounts
    1107           6 :     bool fIncludeEmpty = false;
    1108           6 :     if (params.size() > 1)
    1109           2 :         fIncludeEmpty = params[1].get_bool();
    1110             : 
    1111           6 :     isminefilter filter = ISMINE_SPENDABLE;
    1112           6 :     if(params.size() > 2)
    1113           0 :         if(params[2].get_bool())
    1114           0 :             filter = filter | ISMINE_WATCH_ONLY;
    1115             : 
    1116             :     // Tally
    1117             :     map<CBitcoinAddress, tallyitem> mapTally;
    1118          24 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    1119             :     {
    1120           0 :         const CWalletTx& wtx = (*it).second;
    1121             : 
    1122           0 :         if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
    1123           0 :             continue;
    1124             : 
    1125           0 :         int nDepth = wtx.GetDepthInMainChain();
    1126           0 :         if (nDepth < nMinDepth)
    1127             :             continue;
    1128             : 
    1129           0 :         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
    1130             :         {
    1131             :             CTxDestination address;
    1132           0 :             if (!ExtractDestination(txout.scriptPubKey, address))
    1133             :                 continue;
    1134             : 
    1135           0 :             isminefilter mine = IsMine(*pwalletMain, address);
    1136           0 :             if(!(mine & filter))
    1137             :                 continue;
    1138             : 
    1139           0 :             tallyitem& item = mapTally[address];
    1140           0 :             item.nAmount += txout.nValue;
    1141           0 :             item.nConf = min(item.nConf, nDepth);
    1142           0 :             item.txids.push_back(wtx.GetHash());
    1143           0 :             if (mine & ISMINE_WATCH_ONLY)
    1144           0 :                 item.fIsWatchonly = true;
    1145             :         }
    1146             :     }
    1147             : 
    1148             :     // Reply
    1149          18 :     UniValue ret(UniValue::VARR);
    1150             :     map<string, tallyitem> mapAccountTally;
    1151         120 :     BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
    1152             :     {
    1153          12 :         const CBitcoinAddress& address = item.first;
    1154          12 :         const string& strAccount = item.second.name;
    1155          12 :         map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
    1156          24 :         if (it == mapTally.end() && !fIncludeEmpty)
    1157           8 :             continue;
    1158             : 
    1159           4 :         CAmount nAmount = 0;
    1160           4 :         int nConf = std::numeric_limits<int>::max();
    1161           4 :         bool fIsWatchonly = false;
    1162           4 :         if (it != mapTally.end())
    1163             :         {
    1164           0 :             nAmount = (*it).second.nAmount;
    1165           0 :             nConf = (*it).second.nConf;
    1166           0 :             fIsWatchonly = (*it).second.fIsWatchonly;
    1167             :         }
    1168             : 
    1169           4 :         if (fByAccounts)
    1170             :         {
    1171           2 :             tallyitem& item = mapAccountTally[strAccount];
    1172           2 :             item.nAmount += nAmount;
    1173           4 :             item.nConf = min(item.nConf, nConf);
    1174           2 :             item.fIsWatchonly = fIsWatchonly;
    1175             :         }
    1176             :         else
    1177             :         {
    1178           6 :             UniValue obj(UniValue::VOBJ);
    1179           2 :             if(fIsWatchonly)
    1180           0 :                 obj.push_back(Pair("involvesWatchonly", true));
    1181           6 :             obj.push_back(Pair("address",       address.ToString()));
    1182           6 :             obj.push_back(Pair("account",       strAccount));
    1183           4 :             obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
    1184           4 :             obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
    1185           8 :             UniValue transactions(UniValue::VARR);
    1186           2 :             if (it != mapTally.end())
    1187             :             {
    1188           0 :                 BOOST_FOREACH(const uint256& item, (*it).second.txids)
    1189             :                 {
    1190           0 :                     transactions.push_back(item.GetHex());
    1191             :                 }
    1192             :             }
    1193           4 :             obj.push_back(Pair("txids", transactions));
    1194           4 :             ret.push_back(obj);
    1195             :         }
    1196             :     }
    1197             : 
    1198           6 :     if (fByAccounts)
    1199             :     {
    1200           8 :         for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
    1201             :         {
    1202           2 :             CAmount nAmount = (*it).second.nAmount;
    1203           2 :             int nConf = (*it).second.nConf;
    1204           6 :             UniValue obj(UniValue::VOBJ);
    1205           2 :             if((*it).second.fIsWatchonly)
    1206           0 :                 obj.push_back(Pair("involvesWatchonly", true));
    1207           6 :             obj.push_back(Pair("account",       (*it).first));
    1208           4 :             obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
    1209           4 :             obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
    1210           2 :             ret.push_back(obj);
    1211           2 :         }
    1212             :     }
    1213             : 
    1214           6 :     return ret;
    1215             : }
    1216             : 
    1217           3 : UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
    1218             : {
    1219           3 :     if (!EnsureWalletIsAvailable(fHelp))
    1220           0 :         return NullUniValue;
    1221             :     
    1222           6 :     if (fHelp || params.size() > 3)
    1223             :         throw runtime_error(
    1224             :             "listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
    1225             :             "\nList balances by receiving address.\n"
    1226             :             "\nArguments:\n"
    1227             :             "1. minconf       (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
    1228             :             "2. includeempty  (numeric, optional, default=false) Whether to include addresses that haven't received any payments.\n"
    1229             :             "3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
    1230             : 
    1231             :             "\nResult:\n"
    1232             :             "[\n"
    1233             :             "  {\n"
    1234             :             "    \"involvesWatchonly\" : true,        (bool) Only returned if imported addresses were involved in transaction\n"
    1235             :             "    \"address\" : \"receivingaddress\",  (string) The receiving address\n"
    1236             :             "    \"account\" : \"accountname\",       (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
    1237           0 :             "    \"amount\" : x.xxx,                  (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
    1238             :             "    \"confirmations\" : n                (numeric) The number of confirmations of the most recent transaction included\n"
    1239             :             "  }\n"
    1240             :             "  ,...\n"
    1241             :             "]\n"
    1242             : 
    1243             :             "\nExamples:\n"
    1244           0 :             + HelpExampleCli("listreceivedbyaddress", "")
    1245           0 :             + HelpExampleCli("listreceivedbyaddress", "6 true")
    1246           0 :             + HelpExampleRpc("listreceivedbyaddress", "6, true, true")
    1247           0 :         );
    1248             : 
    1249           3 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1250             : 
    1251           3 :     return ListReceived(params, false);
    1252             : }
    1253             : 
    1254           3 : UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
    1255             : {
    1256           3 :     if (!EnsureWalletIsAvailable(fHelp))
    1257           0 :         return NullUniValue;
    1258             :     
    1259           6 :     if (fHelp || params.size() > 3)
    1260             :         throw runtime_error(
    1261             :             "listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
    1262             :             "\nDEPRECATED. List balances by account.\n"
    1263             :             "\nArguments:\n"
    1264             :             "1. minconf      (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
    1265             :             "2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
    1266             :             "3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
    1267             : 
    1268             :             "\nResult:\n"
    1269             :             "[\n"
    1270             :             "  {\n"
    1271             :             "    \"involvesWatchonly\" : true,   (bool) Only returned if imported addresses were involved in transaction\n"
    1272             :             "    \"account\" : \"accountname\",  (string) The account name of the receiving account\n"
    1273             :             "    \"amount\" : x.xxx,             (numeric) The total amount received by addresses with this account\n"
    1274             :             "    \"confirmations\" : n           (numeric) The number of confirmations of the most recent transaction included\n"
    1275             :             "  }\n"
    1276             :             "  ,...\n"
    1277             :             "]\n"
    1278             : 
    1279             :             "\nExamples:\n"
    1280           0 :             + HelpExampleCli("listreceivedbyaccount", "")
    1281           0 :             + HelpExampleCli("listreceivedbyaccount", "6 true")
    1282           0 :             + HelpExampleRpc("listreceivedbyaccount", "6, true, true")
    1283           0 :         );
    1284             : 
    1285           3 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1286             : 
    1287           3 :     return ListReceived(params, true);
    1288             : }
    1289             : 
    1290         207 : static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
    1291             : {
    1292             :     CBitcoinAddress addr;
    1293         207 :     if (addr.Set(dest))
    1294         621 :         entry.push_back(Pair("address", addr.ToString()));
    1295         207 : }
    1296             : 
    1297         258 : void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
    1298             : {
    1299             :     CAmount nFee;
    1300             :     string strSentAccount;
    1301             :     list<COutputEntry> listReceived;
    1302             :     list<COutputEntry> listSent;
    1303             : 
    1304         258 :     wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
    1305             : 
    1306         774 :     bool fAllAccounts = (strAccount == string("*"));
    1307         516 :     bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
    1308             : 
    1309             :     // Sent
    1310         258 :     if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
    1311             :     {
    1312         750 :         BOOST_FOREACH(const COutputEntry& s, listSent)
    1313             :         {
    1314         234 :             UniValue entry(UniValue::VOBJ);
    1315          78 :             if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
    1316           0 :                 entry.push_back(Pair("involvesWatchonly", true));
    1317         234 :             entry.push_back(Pair("account", strSentAccount));
    1318          78 :             MaybePushAddress(entry, s.destination);
    1319         156 :             entry.push_back(Pair("category", "send"));
    1320         156 :             entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
    1321         156 :             entry.push_back(Pair("vout", s.vout));
    1322         156 :             entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
    1323          78 :             if (fLong)
    1324          34 :                 WalletTxToJSON(wtx, entry);
    1325          78 :             ret.push_back(entry);
    1326          78 :         }
    1327             :     }
    1328             : 
    1329             :     // Received
    1330         485 :     if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
    1331             :     {
    1332        2547 :         BOOST_FOREACH(const COutputEntry& r, listReceived)
    1333             :         {
    1334             :             string account;
    1335         474 :             if (pwalletMain->mapAddressBook.count(r.destination))
    1336          57 :                 account = pwalletMain->mapAddressBook[r.destination].name;
    1337         237 :             if (fAllAccounts || (account == strAccount))
    1338             :             {
    1339         387 :                 UniValue entry(UniValue::VOBJ);
    1340         129 :                 if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
    1341           2 :                     entry.push_back(Pair("involvesWatchonly", true));
    1342         387 :                 entry.push_back(Pair("account", account));
    1343         129 :                 MaybePushAddress(entry, r.destination);
    1344         129 :                 if (wtx.IsCoinBase())
    1345             :                 {
    1346         156 :                     if (wtx.GetDepthInMainChain() < 1)
    1347           0 :                         entry.push_back(Pair("category", "orphan"));
    1348          78 :                     else if (wtx.GetBlocksToMaturity() > 0)
    1349         156 :                         entry.push_back(Pair("category", "immature"));
    1350             :                     else
    1351           0 :                         entry.push_back(Pair("category", "generate"));
    1352             :                 }
    1353             :                 else
    1354             :                 {
    1355         102 :                     entry.push_back(Pair("category", "receive"));
    1356             :                 }
    1357         258 :                 entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
    1358         258 :                 entry.push_back(Pair("vout", r.vout));
    1359         129 :                 if (fLong)
    1360         107 :                     WalletTxToJSON(wtx, entry);
    1361         129 :                 ret.push_back(entry);
    1362             :             }
    1363             :         }
    1364             :     }
    1365         258 : }
    1366             : 
    1367           0 : void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
    1368             : {
    1369           0 :     bool fAllAccounts = (strAccount == string("*"));
    1370             : 
    1371           0 :     if (fAllAccounts || acentry.strAccount == strAccount)
    1372             :     {
    1373           0 :         UniValue entry(UniValue::VOBJ);
    1374           0 :         entry.push_back(Pair("account", acentry.strAccount));
    1375           0 :         entry.push_back(Pair("category", "move"));
    1376           0 :         entry.push_back(Pair("time", acentry.nTime));
    1377           0 :         entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
    1378           0 :         entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
    1379           0 :         entry.push_back(Pair("comment", acentry.strComment));
    1380           0 :         ret.push_back(entry);
    1381             :     }
    1382           0 : }
    1383             : 
    1384          20 : UniValue listtransactions(const UniValue& params, bool fHelp)
    1385             : {
    1386          20 :     if (!EnsureWalletIsAvailable(fHelp))
    1387           0 :         return NullUniValue;
    1388             :     
    1389          40 :     if (fHelp || params.size() > 4)
    1390             :         throw runtime_error(
    1391             :             "listtransactions ( \"account\" count from includeWatchonly)\n"
    1392             :             "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
    1393             :             "\nArguments:\n"
    1394             :             "1. \"account\"    (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
    1395             :             "2. count          (numeric, optional, default=10) The number of transactions to return\n"
    1396             :             "3. from           (numeric, optional, default=0) The number of transactions to skip\n"
    1397             :             "4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
    1398             :             "\nResult:\n"
    1399             :             "[\n"
    1400             :             "  {\n"
    1401             :             "    \"account\":\"accountname\",       (string) DEPRECATED. The account name associated with the transaction. \n"
    1402             :             "                                                It will be \"\" for the default account.\n"
    1403             :             "    \"address\":\"bitcoinaddress\",    (string) The bitcoin address of the transaction. Not present for \n"
    1404             :             "                                                move transactions (category = move).\n"
    1405             :             "    \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
    1406             :             "                                                transaction between accounts, and not associated with an address,\n"
    1407             :             "                                                transaction id or block. 'send' and 'receive' transactions are \n"
    1408             :             "                                                associated with an address, transaction id and block details\n"
    1409           0 :             "    \"amount\": x.xxx,          (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
    1410             :             "                                         'move' category for moves outbound. It is positive for the 'receive' category,\n"
    1411             :             "                                         and for the 'move' category for inbound funds.\n"
    1412             :             "    \"vout\" : n,               (numeric) the vout value\n"
    1413           0 :             "    \"fee\": x.xxx,             (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
    1414             :             "                                         'send' category of transactions.\n"
    1415             :             "    \"confirmations\": n,       (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
    1416             :             "                                         'receive' category of transactions.\n"
    1417             :             "    \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
    1418             :             "                                          category of transactions.\n"
    1419             :             "    \"blockindex\": n,          (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
    1420             :             "                                          category of transactions.\n"
    1421             :             "    \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
    1422             :             "    \"time\": xxx,              (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
    1423             :             "    \"timereceived\": xxx,      (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
    1424             :             "                                          for 'send' and 'receive' category of transactions.\n"
    1425             :             "    \"comment\": \"...\",       (string) If a comment is associated with the transaction.\n"
    1426             :             "    \"otheraccount\": \"accountname\",  (string) For the 'move' category of transactions, the account the funds came \n"
    1427             :             "                                          from (for receiving funds, positive amounts), or went to (for sending funds,\n"
    1428             :             "                                          negative amounts).\n"
    1429             :             "  }\n"
    1430             :             "]\n"
    1431             : 
    1432             :             "\nExamples:\n"
    1433             :             "\nList the most recent 10 transactions in the systems\n"
    1434           0 :             + HelpExampleCli("listtransactions", "") +
    1435             :             "\nList transactions 100 to 120\n"
    1436           0 :             + HelpExampleCli("listtransactions", "\"*\" 20 100") +
    1437             :             "\nAs a json rpc call\n"
    1438           0 :             + HelpExampleRpc("listtransactions", "\"*\", 20, 100")
    1439           0 :         );
    1440             : 
    1441          20 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1442             : 
    1443          40 :     string strAccount = "*";
    1444          20 :     if (params.size() > 0)
    1445          10 :         strAccount = params[0].get_str();
    1446          20 :     int nCount = 10;
    1447          20 :     if (params.size() > 1)
    1448           4 :         nCount = params[1].get_int();
    1449          20 :     int nFrom = 0;
    1450          20 :     if (params.size() > 2)
    1451           3 :         nFrom = params[2].get_int();
    1452          20 :     isminefilter filter = ISMINE_SPENDABLE;
    1453          20 :     if(params.size() > 3)
    1454           2 :         if(params[3].get_bool())
    1455           1 :             filter = filter | ISMINE_WATCH_ONLY;
    1456             : 
    1457          20 :     if (nCount < 0)
    1458           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
    1459          20 :     if (nFrom < 0)
    1460           0 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
    1461             : 
    1462          80 :     UniValue ret(UniValue::VARR);
    1463             : 
    1464             :     std::list<CAccountingEntry> acentries;
    1465          40 :     CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
    1466             : 
    1467             :     // iterate backwards until we have nCount items to return:
    1468         220 :     for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
    1469             :     {
    1470         214 :         CWalletTx *const pwtx = (*it).second.first;
    1471         214 :         if (pwtx != 0)
    1472         214 :             ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
    1473         214 :         CAccountingEntry *const pacentry = (*it).second.second;
    1474         214 :         if (pacentry != 0)
    1475           0 :             AcentryToJSON(*pacentry, strAccount, ret);
    1476             : 
    1477         214 :         if ((int)ret.size() >= (nCount+nFrom)) break;
    1478             :     }
    1479             :     // ret is newest to oldest
    1480             : 
    1481          20 :     if (nFrom > (int)ret.size())
    1482           0 :         nFrom = ret.size();
    1483          40 :     if ((nFrom + nCount) > (int)ret.size())
    1484           6 :         nCount = ret.size() - nFrom;
    1485             : 
    1486          40 :     vector<UniValue> arrTmp = ret.getValues();
    1487             : 
    1488          20 :     vector<UniValue>::iterator first = arrTmp.begin();
    1489             :     std::advance(first, nFrom);
    1490          20 :     vector<UniValue>::iterator last = arrTmp.begin();
    1491          20 :     std::advance(last, nFrom+nCount);
    1492             : 
    1493          40 :     if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
    1494          40 :     if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
    1495             : 
    1496             :     std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
    1497             : 
    1498          20 :     ret.clear();
    1499          20 :     ret.setArray();
    1500          20 :     ret.push_backV(arrTmp);
    1501             : 
    1502          20 :     return ret;
    1503             : }
    1504             : 
    1505           1 : UniValue listaccounts(const UniValue& params, bool fHelp)
    1506             : {
    1507           1 :     if (!EnsureWalletIsAvailable(fHelp))
    1508           0 :         return NullUniValue;
    1509             :     
    1510           2 :     if (fHelp || params.size() > 2)
    1511             :         throw runtime_error(
    1512             :             "listaccounts ( minconf includeWatchonly)\n"
    1513             :             "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
    1514             :             "\nArguments:\n"
    1515             :             "1. minconf          (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
    1516             :             "2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
    1517             :             "\nResult:\n"
    1518             :             "{                      (json object where keys are account names, and values are numeric balances\n"
    1519             :             "  \"account\": x.xxx,  (numeric) The property name is the account name, and the value is the total balance for the account.\n"
    1520             :             "  ...\n"
    1521             :             "}\n"
    1522             :             "\nExamples:\n"
    1523             :             "\nList account balances where there at least 1 confirmation\n"
    1524           0 :             + HelpExampleCli("listaccounts", "") +
    1525             :             "\nList account balances including zero confirmation transactions\n"
    1526           0 :             + HelpExampleCli("listaccounts", "0") +
    1527             :             "\nList account balances for 6 or more confirmations\n"
    1528           0 :             + HelpExampleCli("listaccounts", "6") +
    1529             :             "\nAs json rpc call\n"
    1530           0 :             + HelpExampleRpc("listaccounts", "6")
    1531           0 :         );
    1532             : 
    1533           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1534             : 
    1535           1 :     int nMinDepth = 1;
    1536           1 :     if (params.size() > 0)
    1537           0 :         nMinDepth = params[0].get_int();
    1538           1 :     isminefilter includeWatchonly = ISMINE_SPENDABLE;
    1539           1 :     if(params.size() > 1)
    1540           0 :         if(params[1].get_bool())
    1541           0 :             includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
    1542             : 
    1543             :     map<string, CAmount> mapAccountBalances;
    1544          20 :     BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
    1545           2 :         if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
    1546           2 :             mapAccountBalances[entry.second.name] = 0;
    1547             :     }
    1548             : 
    1549           4 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    1550             :     {
    1551           0 :         const CWalletTx& wtx = (*it).second;
    1552             :         CAmount nFee;
    1553             :         string strSentAccount;
    1554             :         list<COutputEntry> listReceived;
    1555             :         list<COutputEntry> listSent;
    1556           0 :         int nDepth = wtx.GetDepthInMainChain();
    1557           0 :         if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
    1558             :             continue;
    1559           0 :         wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
    1560           0 :         mapAccountBalances[strSentAccount] -= nFee;
    1561           0 :         BOOST_FOREACH(const COutputEntry& s, listSent)
    1562           0 :             mapAccountBalances[strSentAccount] -= s.amount;
    1563           0 :         if (nDepth >= nMinDepth)
    1564             :         {
    1565           0 :             BOOST_FOREACH(const COutputEntry& r, listReceived)
    1566           0 :                 if (pwalletMain->mapAddressBook.count(r.destination))
    1567           0 :                     mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
    1568             :                 else
    1569           0 :                     mapAccountBalances[""] += r.amount;
    1570             :         }
    1571             :     }
    1572             : 
    1573             :     list<CAccountingEntry> acentries;
    1574           5 :     CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
    1575           6 :     BOOST_FOREACH(const CAccountingEntry& entry, acentries)
    1576           0 :         mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
    1577             : 
    1578           4 :     UniValue ret(UniValue::VOBJ);
    1579          20 :     BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) {
    1580           6 :         ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
    1581             :     }
    1582           1 :     return ret;
    1583             : }
    1584             : 
    1585           1 : UniValue listsinceblock(const UniValue& params, bool fHelp)
    1586             : {
    1587           1 :     if (!EnsureWalletIsAvailable(fHelp))
    1588           0 :         return NullUniValue;
    1589             :     
    1590           1 :     if (fHelp)
    1591             :         throw runtime_error(
    1592             :             "listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
    1593             :             "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
    1594             :             "\nArguments:\n"
    1595             :             "1. \"blockhash\"   (string, optional) The block hash to list transactions since\n"
    1596             :             "2. target-confirmations:    (numeric, optional) The confirmations required, must be 1 or more\n"
    1597             :             "3. includeWatchonly:        (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
    1598             :             "\nResult:\n"
    1599             :             "{\n"
    1600             :             "  \"transactions\": [\n"
    1601             :             "    \"account\":\"accountname\",       (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
    1602             :             "    \"address\":\"bitcoinaddress\",    (string) The bitcoin address of the transaction. Not present for move transactions (category = move).\n"
    1603             :             "    \"category\":\"send|receive\",     (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
    1604           0 :             "    \"amount\": x.xxx,          (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
    1605             :             "                                          outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
    1606             :             "    \"vout\" : n,               (numeric) the vout value\n"
    1607           0 :             "    \"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"
    1608             :             "    \"confirmations\": n,       (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
    1609             :             "    \"blockhash\": \"hashvalue\",     (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
    1610             :             "    \"blockindex\": n,          (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
    1611             :             "    \"blocktime\": xxx,         (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
    1612             :             "    \"txid\": \"transactionid\",  (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
    1613             :             "    \"time\": xxx,              (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
    1614             :             "    \"timereceived\": xxx,      (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
    1615             :             "    \"comment\": \"...\",       (string) If a comment is associated with the transaction.\n"
    1616             :             "    \"to\": \"...\",            (string) If a comment to is associated with the transaction.\n"
    1617             :              "  ],\n"
    1618             :             "  \"lastblock\": \"lastblockhash\"     (string) The hash of the last block\n"
    1619             :             "}\n"
    1620             :             "\nExamples:\n"
    1621           0 :             + HelpExampleCli("listsinceblock", "")
    1622           0 :             + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
    1623           0 :             + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
    1624           0 :         );
    1625             : 
    1626           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1627             : 
    1628           1 :     CBlockIndex *pindex = NULL;
    1629           1 :     int target_confirms = 1;
    1630           1 :     isminefilter filter = ISMINE_SPENDABLE;
    1631             : 
    1632           1 :     if (params.size() > 0)
    1633             :     {
    1634             :         uint256 blockId;
    1635             : 
    1636           0 :         blockId.SetHex(params[0].get_str());
    1637           0 :         BlockMap::iterator it = mapBlockIndex.find(blockId);
    1638           0 :         if (it != mapBlockIndex.end())
    1639           0 :             pindex = it->second;
    1640             :     }
    1641             : 
    1642           1 :     if (params.size() > 1)
    1643             :     {
    1644           0 :         target_confirms = params[1].get_int();
    1645             : 
    1646           0 :         if (target_confirms < 1)
    1647           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
    1648             :     }
    1649             : 
    1650           1 :     if(params.size() > 2)
    1651           0 :         if(params[2].get_bool())
    1652           0 :             filter = filter | ISMINE_WATCH_ONLY;
    1653             : 
    1654           1 :     int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
    1655             : 
    1656           4 :     UniValue transactions(UniValue::VARR);
    1657             : 
    1658           4 :     for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
    1659             :     {
    1660           0 :         CWalletTx tx = (*it).second;
    1661             : 
    1662           0 :         if (depth == -1 || tx.GetDepthInMainChain() < depth)
    1663           0 :             ListTransactions(tx, "*", 0, true, transactions, filter);
    1664           0 :     }
    1665             : 
    1666           2 :     CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
    1667           1 :     uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
    1668             : 
    1669           4 :     UniValue ret(UniValue::VOBJ);
    1670           2 :     ret.push_back(Pair("transactions", transactions));
    1671           3 :     ret.push_back(Pair("lastblock", lastblock.GetHex()));
    1672             : 
    1673           1 :     return ret;
    1674             : }
    1675             : 
    1676          45 : UniValue gettransaction(const UniValue& params, bool fHelp)
    1677             : {
    1678          45 :     if (!EnsureWalletIsAvailable(fHelp))
    1679           0 :         return NullUniValue;
    1680             :     
    1681         135 :     if (fHelp || params.size() < 1 || params.size() > 2)
    1682             :         throw runtime_error(
    1683             :             "gettransaction \"txid\" ( includeWatchonly )\n"
    1684             :             "\nGet detailed information about in-wallet transaction <txid>\n"
    1685             :             "\nArguments:\n"
    1686             :             "1. \"txid\"    (string, required) The transaction id\n"
    1687             :             "2. \"includeWatchonly\"    (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
    1688             :             "\nResult:\n"
    1689             :             "{\n"
    1690           0 :             "  \"amount\" : x.xxx,        (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
    1691             :             "  \"confirmations\" : n,     (numeric) The number of confirmations\n"
    1692             :             "  \"blockhash\" : \"hash\",  (string) The block hash\n"
    1693             :             "  \"blockindex\" : xx,       (numeric) The block index\n"
    1694             :             "  \"blocktime\" : ttt,       (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
    1695             :             "  \"txid\" : \"transactionid\",   (string) The transaction id.\n"
    1696             :             "  \"time\" : ttt,            (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
    1697             :             "  \"timereceived\" : ttt,    (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
    1698             :             "  \"details\" : [\n"
    1699             :             "    {\n"
    1700             :             "      \"account\" : \"accountname\",  (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
    1701             :             "      \"address\" : \"bitcoinaddress\",   (string) The bitcoin address involved in the transaction\n"
    1702             :             "      \"category\" : \"send|receive\",    (string) The category, either 'send' or 'receive'\n"
    1703           0 :             "      \"amount\" : x.xxx                  (numeric) The amount in " + CURRENCY_UNIT + "\n"
    1704             :             "      \"vout\" : n,                       (numeric) the vout value\n"
    1705             :             "    }\n"
    1706             :             "    ,...\n"
    1707             :             "  ],\n"
    1708             :             "  \"hex\" : \"data\"         (string) Raw data for transaction\n"
    1709             :             "}\n"
    1710             : 
    1711             :             "\nExamples:\n"
    1712           0 :             + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
    1713           0 :             + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
    1714           0 :             + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
    1715           0 :         );
    1716             : 
    1717          45 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1718             : 
    1719             :     uint256 hash;
    1720          90 :     hash.SetHex(params[0].get_str());
    1721             : 
    1722          45 :     isminefilter filter = ISMINE_SPENDABLE;
    1723          45 :     if(params.size() > 1)
    1724           1 :         if(params[1].get_bool())
    1725           1 :             filter = filter | ISMINE_WATCH_ONLY;
    1726             : 
    1727         181 :     UniValue entry(UniValue::VOBJ);
    1728          90 :     if (!pwalletMain->mapWallet.count(hash))
    1729           3 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
    1730          44 :     const CWalletTx& wtx = pwalletMain->mapWallet[hash];
    1731             : 
    1732          44 :     CAmount nCredit = wtx.GetCredit(filter);
    1733          44 :     CAmount nDebit = wtx.GetDebit(filter);
    1734          44 :     CAmount nNet = nCredit - nDebit;
    1735          44 :     CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
    1736             : 
    1737          89 :     entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
    1738          44 :     if (wtx.IsFromMe(filter))
    1739          88 :         entry.push_back(Pair("fee", ValueFromAmount(nFee)));
    1740             : 
    1741          44 :     WalletTxToJSON(wtx, entry);
    1742             : 
    1743         177 :     UniValue details(UniValue::VARR);
    1744         132 :     ListTransactions(wtx, "*", 0, false, details, filter);
    1745          88 :     entry.push_back(Pair("details", details));
    1746             : 
    1747          88 :     string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
    1748         132 :     entry.push_back(Pair("hex", strHex));
    1749             : 
    1750          44 :     return entry;
    1751             : }
    1752             : 
    1753             : 
    1754           3 : UniValue backupwallet(const UniValue& params, bool fHelp)
    1755             : {
    1756           3 :     if (!EnsureWalletIsAvailable(fHelp))
    1757           0 :         return NullUniValue;
    1758             :     
    1759           6 :     if (fHelp || params.size() != 1)
    1760             :         throw runtime_error(
    1761             :             "backupwallet \"destination\"\n"
    1762             :             "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
    1763             :             "\nArguments:\n"
    1764             :             "1. \"destination\"   (string) The destination directory or file\n"
    1765             :             "\nExamples:\n"
    1766           0 :             + HelpExampleCli("backupwallet", "\"backup.dat\"")
    1767           0 :             + HelpExampleRpc("backupwallet", "\"backup.dat\"")
    1768           0 :         );
    1769             : 
    1770           3 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1771             : 
    1772           3 :     string strDest = params[0].get_str();
    1773           3 :     if (!BackupWallet(*pwalletMain, strDest))
    1774           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
    1775             : 
    1776           3 :     return NullUniValue;
    1777             : }
    1778             : 
    1779             : 
    1780           0 : UniValue keypoolrefill(const UniValue& params, bool fHelp)
    1781             : {
    1782           0 :     if (!EnsureWalletIsAvailable(fHelp))
    1783           0 :         return NullUniValue;
    1784             :     
    1785           0 :     if (fHelp || params.size() > 1)
    1786             :         throw runtime_error(
    1787             :             "keypoolrefill ( newsize )\n"
    1788             :             "\nFills the keypool."
    1789           0 :             + HelpRequiringPassphrase() + "\n"
    1790             :             "\nArguments\n"
    1791             :             "1. newsize     (numeric, optional, default=100) The new keypool size\n"
    1792             :             "\nExamples:\n"
    1793           0 :             + HelpExampleCli("keypoolrefill", "")
    1794           0 :             + HelpExampleRpc("keypoolrefill", "")
    1795           0 :         );
    1796             : 
    1797           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1798             : 
    1799             :     // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
    1800           0 :     unsigned int kpSize = 0;
    1801           0 :     if (params.size() > 0) {
    1802           0 :         if (params[0].get_int() < 0)
    1803           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
    1804           0 :         kpSize = (unsigned int)params[0].get_int();
    1805             :     }
    1806             : 
    1807           0 :     EnsureWalletIsUnlocked();
    1808           0 :     pwalletMain->TopUpKeyPool(kpSize);
    1809             : 
    1810           0 :     if (pwalletMain->GetKeyPoolSize() < kpSize)
    1811           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
    1812             : 
    1813           0 :     return NullUniValue;
    1814             : }
    1815             : 
    1816             : 
    1817           0 : static void LockWallet(CWallet* pWallet)
    1818             : {
    1819           0 :     LOCK(cs_nWalletUnlockTime);
    1820           0 :     nWalletUnlockTime = 0;
    1821           0 :     pWallet->Lock();
    1822           0 : }
    1823             : 
    1824           1 : UniValue walletpassphrase(const UniValue& params, bool fHelp)
    1825             : {
    1826           1 :     if (!EnsureWalletIsAvailable(fHelp))
    1827           0 :         return NullUniValue;
    1828             :     
    1829           2 :     if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
    1830             :         throw runtime_error(
    1831             :             "walletpassphrase \"passphrase\" timeout\n"
    1832             :             "\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
    1833             :             "This is needed prior to performing transactions related to private keys such as sending bitcoins\n"
    1834             :             "\nArguments:\n"
    1835             :             "1. \"passphrase\"     (string, required) The wallet passphrase\n"
    1836             :             "2. timeout            (numeric, required) The time to keep the decryption key in seconds.\n"
    1837             :             "\nNote:\n"
    1838             :             "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
    1839             :             "time that overrides the old one.\n"
    1840             :             "\nExamples:\n"
    1841             :             "\nunlock the wallet for 60 seconds\n"
    1842           0 :             + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
    1843             :             "\nLock the wallet again (before 60 seconds)\n"
    1844           0 :             + HelpExampleCli("walletlock", "") +
    1845             :             "\nAs json rpc call\n"
    1846           0 :             + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
    1847           0 :         );
    1848             : 
    1849           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1850             : 
    1851           1 :     if (fHelp)
    1852           0 :         return true;
    1853           1 :     if (!pwalletMain->IsCrypted())
    1854           0 :         throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
    1855             : 
    1856             :     // Note that the walletpassphrase is stored in params[0] which is not mlock()ed
    1857             :     SecureString strWalletPass;
    1858           1 :     strWalletPass.reserve(100);
    1859             :     // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    1860             :     // Alternately, find a way to make params[0] mlock()'d to begin with.
    1861           3 :     strWalletPass = params[0].get_str().c_str();
    1862             : 
    1863           1 :     if (strWalletPass.length() > 0)
    1864             :     {
    1865           1 :         if (!pwalletMain->Unlock(strWalletPass))
    1866           0 :             throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
    1867             :     }
    1868             :     else
    1869             :         throw runtime_error(
    1870             :             "walletpassphrase <passphrase> <timeout>\n"
    1871           0 :             "Stores the wallet decryption key in memory for <timeout> seconds.");
    1872             : 
    1873           1 :     pwalletMain->TopUpKeyPool();
    1874             : 
    1875           1 :     int64_t nSleepTime = params[1].get_int64();
    1876           1 :     LOCK(cs_nWalletUnlockTime);
    1877           1 :     nWalletUnlockTime = GetTime() + nSleepTime;
    1878           5 :     RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
    1879             : 
    1880           1 :     return NullUniValue;
    1881             : }
    1882             : 
    1883             : 
    1884           0 : UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
    1885             : {
    1886           0 :     if (!EnsureWalletIsAvailable(fHelp))
    1887           0 :         return NullUniValue;
    1888             :     
    1889           0 :     if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
    1890             :         throw runtime_error(
    1891             :             "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
    1892             :             "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
    1893             :             "\nArguments:\n"
    1894             :             "1. \"oldpassphrase\"      (string) The current passphrase\n"
    1895             :             "2. \"newpassphrase\"      (string) The new passphrase\n"
    1896             :             "\nExamples:\n"
    1897           0 :             + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
    1898           0 :             + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
    1899           0 :         );
    1900             : 
    1901           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1902             : 
    1903           0 :     if (fHelp)
    1904           0 :         return true;
    1905           0 :     if (!pwalletMain->IsCrypted())
    1906           0 :         throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
    1907             : 
    1908             :     // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
    1909             :     // Alternately, find a way to make params[0] mlock()'d to begin with.
    1910             :     SecureString strOldWalletPass;
    1911           0 :     strOldWalletPass.reserve(100);
    1912           0 :     strOldWalletPass = params[0].get_str().c_str();
    1913             : 
    1914             :     SecureString strNewWalletPass;
    1915           0 :     strNewWalletPass.reserve(100);
    1916           0 :     strNewWalletPass = params[1].get_str().c_str();
    1917             : 
    1918           0 :     if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
    1919             :         throw runtime_error(
    1920             :             "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
    1921           0 :             "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
    1922             : 
    1923           0 :     if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
    1924           0 :         throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
    1925             : 
    1926           0 :     return NullUniValue;
    1927             : }
    1928             : 
    1929             : 
    1930           0 : UniValue walletlock(const UniValue& params, bool fHelp)
    1931             : {
    1932           0 :     if (!EnsureWalletIsAvailable(fHelp))
    1933           0 :         return NullUniValue;
    1934             :     
    1935           0 :     if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
    1936             :         throw runtime_error(
    1937             :             "walletlock\n"
    1938             :             "\nRemoves the wallet encryption key from memory, locking the wallet.\n"
    1939             :             "After calling this method, you will need to call walletpassphrase again\n"
    1940             :             "before being able to call any methods which require the wallet to be unlocked.\n"
    1941             :             "\nExamples:\n"
    1942             :             "\nSet the passphrase for 2 minutes to perform a transaction\n"
    1943           0 :             + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
    1944             :             "\nPerform a send (requires passphrase set)\n"
    1945           0 :             + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 1.0") +
    1946             :             "\nClear the passphrase since we are done before 2 minutes is up\n"
    1947           0 :             + HelpExampleCli("walletlock", "") +
    1948             :             "\nAs json rpc call\n"
    1949           0 :             + HelpExampleRpc("walletlock", "")
    1950           0 :         );
    1951             : 
    1952           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1953             : 
    1954           0 :     if (fHelp)
    1955           0 :         return true;
    1956           0 :     if (!pwalletMain->IsCrypted())
    1957           0 :         throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
    1958             : 
    1959             :     {
    1960           0 :         LOCK(cs_nWalletUnlockTime);
    1961           0 :         pwalletMain->Lock();
    1962           0 :         nWalletUnlockTime = 0;
    1963             :     }
    1964             : 
    1965           0 :     return NullUniValue;
    1966             : }
    1967             : 
    1968             : 
    1969           1 : UniValue encryptwallet(const UniValue& params, bool fHelp)
    1970             : {
    1971           1 :     if (!EnsureWalletIsAvailable(fHelp))
    1972           0 :         return NullUniValue;
    1973             :     
    1974           2 :     if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
    1975             :         throw runtime_error(
    1976             :             "encryptwallet \"passphrase\"\n"
    1977             :             "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
    1978             :             "After this, any calls that interact with private keys such as sending or signing \n"
    1979             :             "will require the passphrase to be set prior the making these calls.\n"
    1980             :             "Use the walletpassphrase call for this, and then walletlock call.\n"
    1981             :             "If the wallet is already encrypted, use the walletpassphrasechange call.\n"
    1982             :             "Note that this will shutdown the server.\n"
    1983             :             "\nArguments:\n"
    1984             :             "1. \"passphrase\"    (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
    1985             :             "\nExamples:\n"
    1986             :             "\nEncrypt you wallet\n"
    1987           0 :             + HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
    1988             :             "\nNow set the passphrase to use the wallet, such as for signing or sending bitcoin\n"
    1989           0 :             + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
    1990             :             "\nNow we can so something like sign\n"
    1991           0 :             + HelpExampleCli("signmessage", "\"bitcoinaddress\" \"test message\"") +
    1992             :             "\nNow lock the wallet again by removing the passphrase\n"
    1993           0 :             + HelpExampleCli("walletlock", "") +
    1994             :             "\nAs a json rpc call\n"
    1995           0 :             + HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
    1996           0 :         );
    1997             : 
    1998           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    1999             : 
    2000           1 :     if (fHelp)
    2001           0 :         return true;
    2002           1 :     if (pwalletMain->IsCrypted())
    2003           0 :         throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
    2004             : 
    2005             :     // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    2006             :     // Alternately, find a way to make params[0] mlock()'d to begin with.
    2007             :     SecureString strWalletPass;
    2008           1 :     strWalletPass.reserve(100);
    2009           3 :     strWalletPass = params[0].get_str().c_str();
    2010             : 
    2011           1 :     if (strWalletPass.length() < 1)
    2012             :         throw runtime_error(
    2013             :             "encryptwallet <passphrase>\n"
    2014           0 :             "Encrypts the wallet with <passphrase>.");
    2015             : 
    2016           1 :     if (!pwalletMain->EncryptWallet(strWalletPass))
    2017           0 :         throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
    2018             : 
    2019             :     // BDB seems to have a bad habit of writing old data into
    2020             :     // slack space in .dat files; that is bad if the old data is
    2021             :     // unencrypted private keys. So:
    2022           1 :     StartShutdown();
    2023           1 :     return "wallet encrypted; Bitcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
    2024             : }
    2025             : 
    2026           0 : UniValue lockunspent(const UniValue& params, bool fHelp)
    2027             : {
    2028           0 :     if (!EnsureWalletIsAvailable(fHelp))
    2029           0 :         return NullUniValue;
    2030             :     
    2031           0 :     if (fHelp || params.size() < 1 || params.size() > 2)
    2032             :         throw runtime_error(
    2033             :             "lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
    2034             :             "\nUpdates list of temporarily unspendable outputs.\n"
    2035             :             "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
    2036             :             "A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n"
    2037             :             "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
    2038             :             "is always cleared (by virtue of process exit) when a node stops or fails.\n"
    2039             :             "Also see the listunspent call\n"
    2040             :             "\nArguments:\n"
    2041             :             "1. unlock            (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
    2042             :             "2. \"transactions\"  (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
    2043             :             "     [           (json array of json objects)\n"
    2044             :             "       {\n"
    2045             :             "         \"txid\":\"id\",    (string) The transaction id\n"
    2046             :             "         \"vout\": n         (numeric) The output number\n"
    2047             :             "       }\n"
    2048             :             "       ,...\n"
    2049             :             "     ]\n"
    2050             : 
    2051             :             "\nResult:\n"
    2052             :             "true|false    (boolean) Whether the command was successful or not\n"
    2053             : 
    2054             :             "\nExamples:\n"
    2055             :             "\nList the unspent transactions\n"
    2056           0 :             + HelpExampleCli("listunspent", "") +
    2057             :             "\nLock an unspent transaction\n"
    2058           0 :             + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
    2059             :             "\nList the locked transactions\n"
    2060           0 :             + HelpExampleCli("listlockunspent", "") +
    2061             :             "\nUnlock the transaction again\n"
    2062           0 :             + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
    2063             :             "\nAs a json rpc call\n"
    2064           0 :             + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
    2065           0 :         );
    2066             : 
    2067           0 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2068             : 
    2069           0 :     if (params.size() == 1)
    2070           0 :         RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
    2071             :     else
    2072           0 :         RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
    2073             : 
    2074           0 :     bool fUnlock = params[0].get_bool();
    2075             : 
    2076           0 :     if (params.size() == 1) {
    2077           0 :         if (fUnlock)
    2078           0 :             pwalletMain->UnlockAllCoins();
    2079           0 :         return true;
    2080             :     }
    2081             : 
    2082           0 :     UniValue outputs = params[1].get_array();
    2083           0 :     for (unsigned int idx = 0; idx < outputs.size(); idx++) {
    2084           0 :         const UniValue& output = outputs[idx];
    2085           0 :         if (!output.isObject())
    2086           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
    2087           0 :         const UniValue& o = output.get_obj();
    2088             : 
    2089           0 :         RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
    2090             : 
    2091           0 :         string txid = find_value(o, "txid").get_str();
    2092           0 :         if (!IsHex(txid))
    2093           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
    2094             : 
    2095           0 :         int nOutput = find_value(o, "vout").get_int();
    2096           0 :         if (nOutput < 0)
    2097           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
    2098             : 
    2099           0 :         COutPoint outpt(uint256S(txid), nOutput);
    2100             : 
    2101           0 :         if (fUnlock)
    2102           0 :             pwalletMain->UnlockCoin(outpt);
    2103             :         else
    2104           0 :             pwalletMain->LockCoin(outpt);
    2105             :     }
    2106             : 
    2107           0 :     return true;
    2108             : }
    2109             : 
    2110           1 : UniValue listlockunspent(const UniValue& params, bool fHelp)
    2111             : {
    2112           1 :     if (!EnsureWalletIsAvailable(fHelp))
    2113           0 :         return NullUniValue;
    2114             :     
    2115           2 :     if (fHelp || params.size() > 0)
    2116             :         throw runtime_error(
    2117             :             "listlockunspent\n"
    2118             :             "\nReturns list of temporarily unspendable outputs.\n"
    2119             :             "See the lockunspent call to lock and unlock transactions for spending.\n"
    2120             :             "\nResult:\n"
    2121             :             "[\n"
    2122             :             "  {\n"
    2123             :             "    \"txid\" : \"transactionid\",     (string) The transaction id locked\n"
    2124             :             "    \"vout\" : n                      (numeric) The vout value\n"
    2125             :             "  }\n"
    2126             :             "  ,...\n"
    2127             :             "]\n"
    2128             :             "\nExamples:\n"
    2129             :             "\nList the unspent transactions\n"
    2130           0 :             + HelpExampleCli("listunspent", "") +
    2131             :             "\nLock an unspent transaction\n"
    2132           0 :             + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
    2133             :             "\nList the locked transactions\n"
    2134           0 :             + HelpExampleCli("listlockunspent", "") +
    2135             :             "\nUnlock the transaction again\n"
    2136           0 :             + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
    2137             :             "\nAs a json rpc call\n"
    2138           0 :             + HelpExampleRpc("listlockunspent", "")
    2139           0 :         );
    2140             : 
    2141           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2142             : 
    2143             :     vector<COutPoint> vOutpts;
    2144           1 :     pwalletMain->ListLockedCoins(vOutpts);
    2145             : 
    2146           4 :     UniValue ret(UniValue::VARR);
    2147             : 
    2148           6 :     BOOST_FOREACH(COutPoint &outpt, vOutpts) {
    2149           0 :         UniValue o(UniValue::VOBJ);
    2150             : 
    2151           0 :         o.push_back(Pair("txid", outpt.hash.GetHex()));
    2152           0 :         o.push_back(Pair("vout", (int)outpt.n));
    2153           0 :         ret.push_back(o);
    2154           0 :     }
    2155             : 
    2156           1 :     return ret;
    2157             : }
    2158             : 
    2159           2 : UniValue settxfee(const UniValue& params, bool fHelp)
    2160             : {
    2161           2 :     if (!EnsureWalletIsAvailable(fHelp))
    2162           0 :         return NullUniValue;
    2163             :     
    2164           6 :     if (fHelp || params.size() < 1 || params.size() > 1)
    2165             :         throw runtime_error(
    2166             :             "settxfee amount\n"
    2167             :             "\nSet the transaction fee per kB.\n"
    2168             :             "\nArguments:\n"
    2169           0 :             "1. amount         (numeric, required) The transaction fee in " + CURRENCY_UNIT + "/kB rounded to the nearest 0.00000001\n"
    2170             :             "\nResult\n"
    2171             :             "true|false        (boolean) Returns true if successful\n"
    2172             :             "\nExamples:\n"
    2173           0 :             + HelpExampleCli("settxfee", "0.00001")
    2174           0 :             + HelpExampleRpc("settxfee", "0.00001")
    2175           0 :         );
    2176             : 
    2177           2 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2178             : 
    2179             :     // Amount
    2180           2 :     CAmount nAmount = AmountFromValue(params[0]);
    2181             : 
    2182           2 :     payTxFee = CFeeRate(nAmount, 1000);
    2183           2 :     return true;
    2184             : }
    2185             : 
    2186           2 : UniValue getwalletinfo(const UniValue& params, bool fHelp)
    2187             : {
    2188           2 :     if (!EnsureWalletIsAvailable(fHelp))
    2189           0 :         return NullUniValue;
    2190             :     
    2191           4 :     if (fHelp || params.size() != 0)
    2192             :         throw runtime_error(
    2193             :             "getwalletinfo\n"
    2194             :             "Returns an object containing various wallet state info.\n"
    2195             :             "\nResult:\n"
    2196             :             "{\n"
    2197             :             "  \"walletversion\": xxxxx,     (numeric) the wallet version\n"
    2198           0 :             "  \"balance\": xxxxxxx,         (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
    2199           0 :             "  \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
    2200           0 :             "  \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
    2201             :             "  \"txcount\": xxxxxxx,         (numeric) the total number of transactions in the wallet\n"
    2202             :             "  \"keypoololdest\": xxxxxx,    (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
    2203             :             "  \"keypoolsize\": xxxx,        (numeric) how many new keys are pre-generated\n"
    2204             :             "  \"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"
    2205           0 :             "  \"paytxfee\": x.xxxx,         (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
    2206             :             "}\n"
    2207             :             "\nExamples:\n"
    2208           0 :             + HelpExampleCli("getwalletinfo", "")
    2209           0 :             + HelpExampleRpc("getwalletinfo", "")
    2210           0 :         );
    2211             : 
    2212           2 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2213             : 
    2214           8 :     UniValue obj(UniValue::VOBJ);
    2215           4 :     obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
    2216           4 :     obj.push_back(Pair("balance",       ValueFromAmount(pwalletMain->GetBalance())));
    2217           4 :     obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
    2218           4 :     obj.push_back(Pair("immature_balance",    ValueFromAmount(pwalletMain->GetImmatureBalance())));
    2219           6 :     obj.push_back(Pair("txcount",       (int)pwalletMain->mapWallet.size()));
    2220           4 :     obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
    2221           6 :     obj.push_back(Pair("keypoolsize",   (int)pwalletMain->GetKeyPoolSize()));
    2222           2 :     if (pwalletMain->IsCrypted())
    2223           0 :         obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
    2224           4 :     obj.push_back(Pair("paytxfee",      ValueFromAmount(payTxFee.GetFeePerK())));
    2225           2 :     return obj;
    2226             : }
    2227             : 
    2228           1 : UniValue resendwallettransactions(const UniValue& params, bool fHelp)
    2229             : {
    2230           1 :     if (!EnsureWalletIsAvailable(fHelp))
    2231           0 :         return NullUniValue;
    2232             :     
    2233           2 :     if (fHelp || params.size() != 0)
    2234             :         throw runtime_error(
    2235             :             "resendwallettransactions\n"
    2236             :             "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
    2237             :             "Intended only for testing; the wallet code periodically re-broadcasts\n"
    2238             :             "automatically.\n"
    2239             :             "Returns array of transaction ids that were re-broadcast.\n"
    2240           0 :             );
    2241             : 
    2242           1 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2243             : 
    2244           1 :     std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime());
    2245           4 :     UniValue result(UniValue::VARR);
    2246          16 :     BOOST_FOREACH(const uint256& txid, txids)
    2247             :     {
    2248           4 :         result.push_back(txid.ToString());
    2249             :     }
    2250           1 :     return result;
    2251             : }
    2252             : 
    2253          14 : UniValue listunspent(const UniValue& params, bool fHelp)
    2254             : {
    2255          14 :     if (!EnsureWalletIsAvailable(fHelp))
    2256           0 :         return NullUniValue;
    2257             :     
    2258          28 :     if (fHelp || params.size() > 3)
    2259             :         throw runtime_error(
    2260             :             "listunspent ( minconf maxconf  [\"address\",...] )\n"
    2261             :             "\nReturns array of unspent transaction outputs\n"
    2262             :             "with between minconf and maxconf (inclusive) confirmations.\n"
    2263             :             "Optionally filter to only include txouts paid to specified addresses.\n"
    2264             :             "Results are an array of Objects, each of which has:\n"
    2265             :             "{txid, vout, scriptPubKey, amount, confirmations}\n"
    2266             :             "\nArguments:\n"
    2267             :             "1. minconf          (numeric, optional, default=1) The minimum confirmations to filter\n"
    2268             :             "2. maxconf          (numeric, optional, default=9999999) The maximum confirmations to filter\n"
    2269             :             "3. \"addresses\"    (string) A json array of bitcoin addresses to filter\n"
    2270             :             "    [\n"
    2271             :             "      \"address\"   (string) bitcoin address\n"
    2272             :             "      ,...\n"
    2273             :             "    ]\n"
    2274             :             "\nResult\n"
    2275             :             "[                   (array of json object)\n"
    2276             :             "  {\n"
    2277             :             "    \"txid\" : \"txid\",        (string) the transaction id \n"
    2278             :             "    \"vout\" : n,               (numeric) the vout value\n"
    2279             :             "    \"address\" : \"address\",  (string) the bitcoin address\n"
    2280             :             "    \"account\" : \"account\",  (string) DEPRECATED. The associated account, or \"\" for the default account\n"
    2281             :             "    \"scriptPubKey\" : \"key\", (string) the script key\n"
    2282           3 :             "    \"amount\" : x.xxx,         (numeric) the transaction amount in " + CURRENCY_UNIT + "\n"
    2283             :             "    \"confirmations\" : n       (numeric) The number of confirmations\n"
    2284             :             "  }\n"
    2285             :             "  ,...\n"
    2286             :             "]\n"
    2287             : 
    2288             :             "\nExamples\n"
    2289           8 :             + HelpExampleCli("listunspent", "")
    2290           8 :             + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
    2291           8 :             + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
    2292           3 :         );
    2293             : 
    2294          78 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
    2295             : 
    2296          13 :     int nMinDepth = 1;
    2297          13 :     if (params.size() > 0)
    2298           4 :         nMinDepth = params[0].get_int();
    2299             : 
    2300          13 :     int nMaxDepth = 9999999;
    2301          13 :     if (params.size() > 1)
    2302           1 :         nMaxDepth = params[1].get_int();
    2303             : 
    2304             :     set<CBitcoinAddress> setAddress;
    2305          13 :     if (params.size() > 2) {
    2306           1 :         UniValue inputs = params[2].get_array();
    2307           1 :         for (unsigned int idx = 0; idx < inputs.size(); idx++) {
    2308           0 :             const UniValue& input = inputs[idx];
    2309           0 :             CBitcoinAddress address(input.get_str());
    2310           0 :             if (!address.IsValid())
    2311           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+input.get_str());
    2312           0 :             if (setAddress.count(address))
    2313           0 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
    2314             :            setAddress.insert(address);
    2315           1 :         }
    2316             :     }
    2317             : 
    2318          52 :     UniValue results(UniValue::VARR);
    2319             :     vector<COutput> vecOutputs;
    2320          13 :     assert(pwalletMain != NULL);
    2321          13 :     LOCK2(cs_main, pwalletMain->cs_wallet);
    2322          13 :     pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
    2323         954 :     BOOST_FOREACH(const COutput& out, vecOutputs) {
    2324         146 :         if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
    2325           2 :             continue;
    2326             : 
    2327         144 :         if (setAddress.size()) {
    2328             :             CTxDestination address;
    2329           0 :             if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
    2330             :                 continue;
    2331             : 
    2332           0 :             if (!setAddress.count(address))
    2333             :                 continue;
    2334             :         }
    2335             : 
    2336         288 :         CAmount nValue = out.tx->vout[out.i].nValue;
    2337         144 :         const CScript& pk = out.tx->vout[out.i].scriptPubKey;
    2338         432 :         UniValue entry(UniValue::VOBJ);
    2339         432 :         entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
    2340         288 :         entry.push_back(Pair("vout", out.i));
    2341             :         CTxDestination address;
    2342         288 :         if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
    2343         576 :             entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
    2344         288 :             if (pwalletMain->mapAddressBook.count(address))
    2345          75 :                 entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
    2346             :         }
    2347         720 :         entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
    2348         144 :         if (pk.IsPayToScriptHash()) {
    2349             :             CTxDestination address;
    2350           0 :             if (ExtractDestination(pk, address)) {
    2351           0 :                 const CScriptID& hash = boost::get<CScriptID>(address);
    2352             :                 CScript redeemScript;
    2353           0 :                 if (pwalletMain->GetCScript(hash, redeemScript))
    2354           0 :                     entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
    2355             :             }
    2356             :         }
    2357         288 :         entry.push_back(Pair("amount",ValueFromAmount(nValue)));
    2358         288 :         entry.push_back(Pair("confirmations",out.nDepth));
    2359         288 :         entry.push_back(Pair("spendable", out.fSpendable));
    2360         144 :         results.push_back(entry);
    2361         144 :     }
    2362             : 
    2363          13 :     return results;
    2364             : }
    2365             : 
    2366          23 : UniValue fundrawtransaction(const UniValue& params, bool fHelp)
    2367             : {
    2368          23 :     if (!EnsureWalletIsAvailable(fHelp))
    2369           0 :         return NullUniValue;
    2370             : 
    2371          69 :     if (fHelp || params.size() < 1 || params.size() > 2)
    2372             :         throw runtime_error(
    2373             :                             "fundrawtransaction \"hexstring\" includeWatching\n"
    2374             :                             "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
    2375             :                             "This will not modify existing inputs, and will add one change output to the outputs.\n"
    2376             :                             "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
    2377             :                             "The inputs added will not be signed, use signrawtransaction for that.\n"
    2378             :                             "Note that all existing inputs must have their previous output transaction be in the wallet.\n"
    2379             :                             "Note that all inputs selected must be of standard form and P2SH scripts must be"
    2380             :                             "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
    2381             :                             "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
    2382             :                             "\nArguments:\n"
    2383             :                             "1. \"hexstring\"     (string, required) The hex string of the raw transaction\n"
    2384             :                             "2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n"
    2385             :                             "\nResult:\n"
    2386             :                             "{\n"
    2387             :                             "  \"hex\":       \"value\", (string)  The resulting raw transaction (hex-encoded string)\n"
    2388             :                             "  \"fee\":       n,         (numeric) The fee added to the transaction\n"
    2389             :                             "  \"changepos\": n          (numeric) The position of the added change output, or -1\n"
    2390             :                             "}\n"
    2391             :                             "\"hex\"             \n"
    2392             :                             "\nExamples:\n"
    2393             :                             "\nCreate a transaction with no inputs\n"
    2394           0 :                             + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
    2395             :                             "\nAdd sufficient unsigned inputs to meet the output value\n"
    2396           0 :                             + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
    2397             :                             "\nSign the transaction\n"
    2398           0 :                             + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
    2399             :                             "\nSend the transaction\n"
    2400           0 :                             + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
    2401           0 :                             );
    2402             : 
    2403         115 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
    2404             : 
    2405             :     // parse hex string from parameter
    2406          23 :     CTransaction origTx;
    2407          46 :     if (!DecodeHexTx(origTx, params[0].get_str()))
    2408           3 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
    2409             : 
    2410          22 :     bool includeWatching = false;
    2411          22 :     if (params.size() > 1)
    2412           2 :         includeWatching = true;
    2413             : 
    2414          22 :     CMutableTransaction tx(origTx);
    2415             :     CAmount nFee;
    2416             :     string strFailReason;
    2417          22 :     int nChangePos = -1;
    2418          22 :     if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching))
    2419           2 :         throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
    2420             : 
    2421          82 :     UniValue result(UniValue::VOBJ);
    2422          80 :     result.push_back(Pair("hex", EncodeHexTx(tx)));
    2423          40 :     result.push_back(Pair("changepos", nChangePos));
    2424          40 :     result.push_back(Pair("fee", ValueFromAmount(nFee)));
    2425             : 
    2426          20 :     return result;
    2427         288 : }

Generated by: LCOV version 1.11