text: // Copyright (c) 2010 Satoshi Nakamoto
  // Copyright (c) 2009-2014 The Bitcoin developers
  // Copyright (c) 2014 The Mini-Blockchain Project
  // Distributed under the MIT/X11 software license, see the accompanying
  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  
  #include "base58.h"
  #include "rpcserver.h"
  #include "init.h"
  #include "net.h"
  #include "netbase.h"
  #include "util.h"
  #include "wallet.h"
  #include "walletdb.h"
  
  #include <stdint.h>
  #include <string.h>
  
  #include <boost/assign/list_of.hpp>
  #include "json/json_spirit_utils.h"
  #include "json/json_spirit_value.h"
  
  using namespace std;
  using namespace boost;
  using namespace boost::assign;
  using namespace json_spirit;
  
  int64_t nWalletUnlockTime;
  static CCriticalSection cs_nWalletUnlockTime;
  
  std::string HelpRequiringPassphrase()
  {
      return pwalletMain && pwalletMain->IsCrypted()
          ? "\nRequires wallet passphrase to be set with walletpassphrase call."
          : "";
  }
  
  void EnsureWalletIsUnlocked()
  {
      if (pwalletMain->IsLocked())
          throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
  }
  
  void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
  {
      int confirms = GetDepthInMainChain(wtx.GetTxID());
      entry.push_back(Pair("confirmations", confirms));
      if (wtx.IsCoinBase())
          entry.push_back(Pair("generated", true));
      if (confirms > 0)
      {
          entry.push_back(Pair("blockhash", GetTxBlock(wtx.GetTxID())->GetBlockHash().GetHex()));
  	//printf("hashblock: %s\n", wtx.hashBlock.GetHex().c_str());
          entry.push_back(Pair("blocktime", (boost::int64_t)(GetTxBlock(wtx.GetTxID())->nTime)));
      }
      uint256 hash = wtx.GetTxID();
      entry.push_back(Pair("txid", hash.GetHex()));
      entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
      entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
      entry.push_back(Pair("lockheight", wtx.nLockHeight));
      entry.push_back(Pair("msg", string(wtx.msg.begin(),wtx.msg.end())));
      for (const std::pair<string,string>& item : wtx.mapValue)
          entry.push_back(Pair(item.first, item.second));
  }
  
  string AccountFromValue(const Value& value)
  {
      string strAccount = value.get_str();
      if (strAccount == "*")
          throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
      return strAccount;
  }
  
  Value getnewaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 1)
          throw runtime_error(
              "getnewaddress ( \"account\" )\n"
              "\nReturns a new Cryptonite address for receiving payments.\n"
              "If 'account' is specified (recommended), it is added to the address book \n"
              "so payments received with the address will be credited to 'account'.\n"
              "\nArguments:\n"
              "1. \"account\"        (string, optional) 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"
              "\nResult:\n"
              "\"cryptoniteaddress\"    (string) The new cryptonite address\n"
              "\nExamples:\n"
              + HelpExampleCli("getnewaddress", "")
              + HelpExampleCli("getnewaddress", "\"\"")
              + HelpExampleCli("getnewaddress", "\"myaccount\"")
              + HelpExampleRpc("getnewaddress", "\"myaccount\"")
          );
  
      // Parse the account first so we don't generate a key if there's an error
      string strAccount;
      if (params.size() > 0)
          strAccount = AccountFromValue(params[0]);
  
      if (!pwalletMain->IsLocked())
          pwalletMain->TopUpKeyPool();
  
      // Generate a new key that is added to wallet
      CPubKey newKey;
      if (!pwalletMain->GetKeyFromPool(newKey))
          throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
      CKeyID keyID = newKey.GetID();
  
      pwalletMain->SetAddressBook(keyID, strAccount, "receive");
  
      return CBitcoinAddress(keyID).ToString();
  }
  
  
  CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
  {
      CWalletDB walletdb(pwalletMain->strWalletFile);
  
      CAccount account;
      walletdb.ReadAccount(strAccount, account);
  
      // Generate a new key
      if (!account.vchPubKey.IsValid() || bForceNew)
      {
          if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
              throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  
          pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
          walletdb.WriteAccount(strAccount, account);
      }
  
      return CBitcoinAddress(account.vchPubKey.GetID());
  }
  
  Value getaccountaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 1)
          throw runtime_error(
              "getaccountaddress \"account\"\n"
              "\nReturns the current Cryptonite address for receiving payments to this account.\n"
              "\nArguments:\n"
              "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"
              "\nResult:\n"
              "\"cryptoniteaddress\"   (string) The account cryptonite address\n"
              "\nExamples:\n"
              + HelpExampleCli("getaccountaddress", "")
              + HelpExampleCli("getaccountaddress", "\"\"")
              + HelpExampleCli("getaccountaddress", "\"myaccount\"")
              + HelpExampleRpc("getaccountaddress", "\"myaccount\"")
          );
  
      // Parse the account first so we don't generate a key if there's an error
      string strAccount = AccountFromValue(params[0]);
  
      Value ret;
  
      ret = GetAccountAddress(strAccount).ToString();
  
      return ret;
  }
  
  Value setaccount(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 1 || params.size() > 3)
          throw runtime_error(
              "setaccount \"cryptoniteaddress\" \"account\"\n"
              "\nSets the account associated with the given address.\n"
              "\nArguments:\n"
              "1. \"cryptoniteaddress\"  (string, required) The cryptonite address to be associated with an account.\n"
              "2. \"account\"         (string, required) The account to assign the address to.\n"
  	    "3. \"create\"	    (bool, optional) Set if want to disable address creation on source.\n"
              "\nExamples:\n"
              + HelpExampleCli("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"tabby\"")
              + HelpExampleRpc("setaccount", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"tabby\"")
          );
  
      CBitcoinAddress address(params[0].get_str());
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
  
      string strAccount;
      if (params.size() > 1)
          strAccount = AccountFromValue(params[1]);
  
      // Detect when changing the account of an address that is the 'unused current key' of another account:
      if (pwalletMain->mapAddressBook.count(address.Get()) && params.size() < 3)
      {
          string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
          if (address == GetAccountAddress(strOldAccount))
              GetAccountAddress(strOldAccount, true);
      }
  
      pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
  
      return Value::null;
  }
  
  
  Value getaccount(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 1)
          throw runtime_error(
              "getaccount \"cryptoniteaddress\"\n"
              "\nReturns the account associated with the given address.\n"
              "\nArguments:\n"
              "1. \"cryptoniteaddress\"  (string, required) The cryptonite address for account lookup.\n"
              "\nResult:\n"
              "\"accountname\"        (string) the account address\n"
              "\nExamples:\n"
              + HelpExampleCli("getaccount", "\"address\"")
              + HelpExampleRpc("getaccount", "\"address\"")
          );
  
      CBitcoinAddress address(params[0].get_str());
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
      string strAccount;
      map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
      if (mi != pwalletMain->mapAddressBook.end())
          strAccount = (*mi).second.name;
      else
  	return Value::null;
      return strAccount;
  }
  
  
  Value getaddressesbyaccount(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 1)
          throw runtime_error(
              "getaddressesbyaccount \"account\"\n"
              "\nReturns the list of addresses for the given account.\n"
              "\nArguments:\n"
              "1. \"account\"  (string, required) The account name.\n"
              "\nResult:\n"
              "[                     (json array of string)\n"
              "  \"cryptoniteaddress\"  (string) a cryptonite address associated with the given account\n"
              "  ,...\n"
              "]\n"
              "\nExamples:\n"
              + HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
              + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
          );
  
      string strAccount = AccountFromValue(params[0]);
  
      // Find all addresses that have the given account
      Array ret;
      for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwalletMain->mapAddressBook)
      {
          const CBitcoinAddress& address = item.first;
          const string& strName = item.second.name;
          if (strName == strAccount)
              ret.push_back(address.ToString());
      }
      return ret;
  }
  
  Value sendtoaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 2 || params.size() > 3)
          throw runtime_error(
              "sendtoaddress \"cryptoniteaddress\" amount ( \"msg\" )\n"
              "\nSent an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n"
              + HelpRequiringPassphrase() +
              "\nArguments:\n"
              "1. \"cryptoniteaddress\"  (string, required) The cryptonite address to send to.\n"
              "2. \"amount\"      (ep, required) The amount in XCN to send. eg 0.1\n"
              "3. \"msg\"     (string, optional) A comment used to store what the transaction is for. \n"
              "\nResult:\n"
              "\"transactionid\"  (string) The transaction id. (view at https://blockchain.info/tx/[transactionid])\n"
              "\nExamples:\n"
              + HelpExampleCli("sendtoaddress", "\"address\" \"0.10000000ep\"")
              + HelpExampleCli("sendtoaddress", "\"address\" \"0.10000000ep\" \"donation\" ")
              + HelpExampleRpc("sendtoaddress", "\"address\", \"0.10000000ep\", \"donation\"")
          );
  
      CBitcoinAddress address(params[0].get_str());
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
      // Amount
      int64_t nAmount = AmountFromValue(params[1]);
  
      // Wallet comments
      CWalletTx wtx;
      if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()){
  	string msg = params[2].get_str();
          wtx.msg = vector<char>(msg.begin(),msg.end());
      }
  
      EnsureWalletIsUnlocked();
  
      string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
      if (strError != "")
          throw JSONRPCError(RPC_WALLET_ERROR, strError);
  
      return wtx.GetTxID().GetHex();
  }
  
  Value resendwallet(const Array& params, bool fHelp)
  {
      if (fHelp)
          throw runtime_error(
              "resendwallet\n"
              "\nCause all unconfirmed transactions in wallet to be resent\n"
              "\nExamples:\n"
              + HelpExampleCli("resendwallet", "")
              + HelpExampleRpc("resendwallet", "")
          );
  
      pwalletMain->ReacceptWalletTransactions();
  
      return Value::null;
  }
  
  Value setlimit(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 2)
          throw runtime_error(
              "setlimit\n"
              "\nUpdate the transaction limit field on an address\n"
              "\nArguments:\n"
              "1. \"limit\"         (ep, required) The new limit for the address\n"
              "2. \"cryptoniteaddress\"  (string, required) The cryptonite address to update.\n"
  	    "\nResult:\n"
              "\"transactionid\"          (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
              "                                    the number of addresses. See https://blockchain.info/tx/[transactionid]\n"
              "\nExamples:\n"
              + HelpExampleCli("setlimit", "\"1.00000000ep\" \"address\"")
              + HelpExampleRpc("setlimit", "\"1.00000000ep\", \"address\"")
          );
  
      CBitcoinAddress address(params[1].get_str());
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
      // Amount
      int64_t nLimit = AmountFromValue(params[0]);
  
      CWalletTx wtx;
  
      EnsureWalletIsUnlocked();
  
      string strError = pwalletMain->SetLimit(address.Get(), nLimit, wtx);
      if (strError != "")
          throw JSONRPCError(RPC_WALLET_ERROR, strError);
  
      return wtx.GetTxID().GetHex();
  }
  
  Value listaddressgroupings(const Array& params, bool fHelp)
  {
      if (fHelp)
          throw runtime_error(
              "listaddressgroupings\n"
              "\nLists groups of addresses which have had their common ownership\n"
              "made public by common use as inputs or as the resulting change\n"
              "in past transactions\n"
              "\nResult:\n"
              "[\n"
              "  [\n"
              "    [\n"
              "      \"cryptoniteaddress\",     (string) The cryptonite address\n"
              "      amount,                 (ep) The amount in XCN\n"
              "      \"account\"             (string, optional) The account\n"
              "    ]\n"
              "    ,...\n"
              "  ]\n"
              "  ,...\n"
              "]\n"
              "\nExamples:\n"
              + HelpExampleCli("listaddressgroupings", "")
              + HelpExampleRpc("listaddressgroupings", "")
          );
  
      Array jsonGroupings;
      map<CTxDestination, uint64_t> balances = pwalletMain->GetAddressBalances();
      for (set<CTxDestination> grouping : pwalletMain->GetAddressGroupings())
      {
          Array jsonGrouping;
          for (CTxDestination address : grouping)
          {
              Array addressInfo;
              addressInfo.push_back(CBitcoinAddress(address).ToString());
              addressInfo.push_back(ValueFromAmount(balances[address]));
              {
                  LOCK(pwalletMain->cs_wallet);
                  if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
                      addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
              }
              jsonGrouping.push_back(addressInfo);
          }
          jsonGroupings.push_back(jsonGrouping);
      }
      return jsonGroupings;
  }
  
  Value signmessage(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 2)
          throw runtime_error(
              "signmessage \"cryptoniteaddress\" \"message\"\n"
              "\nSign a message with the private key of an address"
              + HelpRequiringPassphrase() + "\n"
              "\nArguments:\n"
              "1. \"cryptoniteaddress\"  (string, required) The cryptonite address to use for the private key.\n"
              "2. \"message\"         (string, required) The message to create a signature of.\n"
              "\nResult:\n"
              "\"signature\"          (string) The signature of the message encoded in base 64\n"
              "\nExamples:\n"
              "\nUnlock the wallet for 30 seconds\n"
              + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
              "\nCreate the signature\n"
              + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
              "\nVerify the signature\n"
              + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
              "\nAs json rpc\n"
              + HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"my message\"")
          );
  
      EnsureWalletIsUnlocked();
  
      string strAddress = params[0].get_str();
      string strMessage = params[1].get_str();
  
      CBitcoinAddress addr(strAddress);
      if (!addr.IsValid())
          throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
  
      CKeyID keyID;
      if (!addr.GetKeyID(keyID))
          throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
  
      CKey key;
      if (!pwalletMain->GetKey(keyID, key))
          throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
  
      CHashWriter ss(SER_GETHASH, 0);
      ss << strMessageMagic;
      ss << strMessage;
  
      vector<unsigned char> vchSig;
      if (!key.SignCompact(ss.GetHash(), vchSig))
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
  
      return EncodeBase64(&vchSig[0], vchSig.size());
  }
  
  Value getreceivedbyaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 1 || params.size() > 2)
          throw runtime_error(
              "getreceivedbyaddress \"cryptoniteaddress\" ( minconf )\n"
              "\nReturns the total amount received by the given cryptoniteaddress in transactions with at least minconf confirmations.\n"
              "\nArguments:\n"
              "1. \"cryptoniteaddress\"  (string, required) The cryptonite address for transactions.\n"
              "2. minconf             (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
              "\nResult:\n"
              "amount   (ep) The total amount in XCN received at this address.\n"
              "\nExamples:\n"
              "\nThe amount from transactions with at least 1 confirmation\n"
              + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\"") +
              "\nThe amount including unconfirmed transactions, zero confirmations\n"
              + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 0") +
              "\nThe amount with at least 6 confirmation, very safe\n"
              + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" 6") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", 6")
         );
  
      // Bitcoin address
      CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
  
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
      CKeyID keyID;
      address.GetKeyID(keyID);
  
      if (!pwalletMain->IsMine(keyID))
          return (double)0.0;
  
      // Minimum confirmations
      int nMinDepth = 1;
      if (params.size() > 1)
          nMinDepth = params[1].get_int();
  
      // Tally
      int64_t nAmount = 0;
      for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
      {
          const CWalletTx& wtx = (*it).second;
          //if (wtx.IsCoinBase() || !IsFinalTx(wtx))
          //    continue;
  
          int nDepth = GetDepthInMainChain(wtx.GetTxID());
  		if (nDepth < nMinDepth)
  			continue;
  
          for (const CTxOut& txout : wtx.vout)
          {
              if (keyID == CKeyID(txout.pubKey))
              	nAmount += txout.nValue;
          }
      }
  
      return  ValueFromAmount(nAmount);
  }
  
  
  Value getreceivedbyaccount(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 1 || params.size() > 2)
          throw runtime_error(
              "getreceivedbyaccount \"account\" ( minconf )\n"
              "\nReturns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
              "\nArguments:\n"
              "1. \"account\"      (string, required) The selected account, may be the default account using \"\".\n"
              "2. minconf          (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
              "\nResult:\n"
              "amount              (ep) The total amount in XCN received for this account.\n"
              "\nExamples:\n"
              "\nAmount received by the default account with at least 1 confirmation\n"
              + HelpExampleCli("getreceivedbyaccount", "\"\"") +
              "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
              + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
              "\nThe amount with at least 6 confirmation, very safe\n"
              + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6")
          );
  
      // Minimum confirmations
      int nMinDepth = 1;
      if (params.size() > 1)
          nMinDepth = params[1].get_int();
  
      // Get the set of pub keys assigned to account
      string strAccount = AccountFromValue(params[0]);
      set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
  
      // Tally
      int64_t nAmount = 0;
      for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
      {
          const CWalletTx& wtx = (*it).second;
          //if (wtx.IsCoinBase() || !IsFinalTx(wtx))
          //    continue;
  
          int nDepth = GetDepthInMainChain(wtx.GetTxID());
  		if (nDepth < nMinDepth)
  			continue;
  
          for (const CTxOut& txout : wtx.vout)
          {
          	CTxDestination address = CKeyID(txout.pubKey);
  
              if (pwalletMain->IsMine(txout.pubKey) && setAddress.count(address))
                  nAmount += txout.nValue;
          }
      }
  
      return (double)nAmount / (double)COIN;
  }
  
  uint64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
  {
      vector<uint160> keys;
      pwalletMain->GetAllKeys(keys, strAccount);
      vector<CActInfo> balances;
      pviewTip->ConservativeBalances(nMinDepth, keys, balances);
  
      uint64_t nBalance=0;
      for (CActInfo v : balances)
  	nBalance += v.balance;
      return nBalance;
  }
  
  uint64_t GetAccountBalance(const string& strAccount, int nMinDepth)
  {
      CWalletDB walletdb(pwalletMain->strWalletFile);
      return GetAccountBalance(walletdb, strAccount, nMinDepth);
  }
  
  Value getbalance(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 2)
          throw runtime_error(
              "getbalance ( \"account\" minconf )\n"
              "\nIf account is not specified, returns the server's total available balance.\n"
              "If account is specified, returns the balance in the account.\n"
              "Note that the account \"\" is not the same as leaving the parameter out.\n"
              "The server total may be different to the balance in the default \"\" account.\n"
              "\nArguments:\n"
              "1. \"account\"      (string, optional) The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
              "2. minconf          (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
              "\nResult:\n"
              "amount              (ep) The total amount in XCN received for this account.\n"
              "\nExamples:\n"
              "\nThe total amount in the server across all accounts\n"
              + HelpExampleCli("getbalance", "") +
              "\nThe total amount in the server across all accounts, with at least 6 confirmations\n"
              + HelpExampleCli("getbalance", "\"*\" 6") +
              "\nThe total amount in the default account with at least 1 confirmation\n"
              + HelpExampleCli("getbalance", "\"\"") +
              "\nThe total amount in the account named tabby with at least 6 confirmations\n"
              + HelpExampleCli("getbalance", "\"tabby\" 6") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("getbalance", "\"tabby\", 6")
          );
  
      if (params.size() == 0)
          return  ValueFromAmount(pwalletMain->GetBalance());
  
      int nMinDepth = 1;
      if (params.size() > 1)
          nMinDepth = params[1].get_int();
      if(nMinDepth > (int64_t)MIN_HISTORY || nMinDepth > (int64_t)chainActive.Height()+1)
          throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, minconf cannot exceed min history"));
      if(nMinDepth <= 0)
  	throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, minconf cannot be <= 0"));
  
  
      if (params[0].get_str() == "*") {
  	vector<uint160> keys;
  	pwalletMain->GetAllKeys(keys);
      	vector<CActInfo> balances;
  	pviewTip->ConservativeBalances(nMinDepth, keys, balances);
  
  	uint64_t nBalance=0;
  	for (CActInfo v : balances)
              nBalance += v.balance;
          return  ValueFromAmount(nBalance);
      }
  
      string strAccount = AccountFromValue(params[0]);
  
      uint64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
  
      return ValueFromAmount(nBalance);
  }
  
  Value getunconfirmedbalance(const Array &params, bool fHelp)
  {
      if (fHelp || params.size() > 0)
          throw runtime_error(
                  "getunconfirmedbalance\n"
                  "Returns the server's total unconfirmed balance\n");
      return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
  }
  
  
  Value movecmd(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 3 || params.size() > 5)
          throw runtime_error(
              "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
              "\nMove a specified amount from one account in your wallet to another.\n"
              "\nArguments:\n"
              "1. \"fromaccount\"   (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
              "2. \"toaccount\"     (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
              "3. minconf           (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
              "4. \"comment\"       (string, optional) An optional comment, stored in the wallet only.\n"
              "\nResult:\n"
              "true|false           (boolean) true if successfull.\n"
              "\nExamples:\n"
              "\nMove 0.01 XCN from the default account to the account named tabby\n"
              + HelpExampleCli("move", "\"\" \"tabby\" \"0.01000000ep\"") +
              "\nMove 0.01 XCN timotei to akiko with a comment and funds have 6 confirmations\n"
              + HelpExampleCli("move", "\"timotei\" \"akiko\" \"0.01000000ep\" 6 \"happy birthday!\"") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("move", "\"timotei\", \"akiko\", \"0.01000000ep\", 6, \"happy birthday!\"")
          );
  
      string strFrom = AccountFromValue(params[0]);
      string strTo = AccountFromValue(params[1]);
      int64_t nAmount = AmountFromValue(params[2]);
  
      if (params.size() > 3)
          // unused parameter, used to be nMinDepth, keep type-checking it though
          (void)params[3].get_int();
      string strComment;
      if (params.size() > 4)
          strComment = params[4].get_str();
  
      CWalletDB walletdb(pwalletMain->strWalletFile);
      if (!walletdb.TxnBegin())
          throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
  
      int64_t nNow = GetAdjustedTime();
  
      // Debit
      CAccountingEntry debit;
      debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
      debit.strAccount = strFrom;
      debit.nCreditDebit = -nAmount;
      debit.nTime = nNow;
      debit.strOtherAccount = strTo;
      debit.strComment = strComment;
      walletdb.WriteAccountingEntry(debit);
  
      // Credit
      CAccountingEntry credit;
      credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
      credit.strAccount = strTo;
      credit.nCreditDebit = nAmount;
      credit.nTime = nNow;
      credit.strOtherAccount = strFrom;
      credit.strComment = strComment;
      walletdb.WriteAccountingEntry(credit);
  
      if (!walletdb.TxnCommit())
          throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
  
      return true;
  }
  
  
  Value sendfrom(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 3 || params.size() > 5)
          throw runtime_error(
              "sendfrom \"fromaccount\" \"tocryptoniteaddress\" amount ( minconf \"msg\" )\n"
              "\nSent an amount from an account to a cryptonite address.\n"
              "The amount is a real and is rounded to the nearest 0.00000001."
              + HelpRequiringPassphrase() + "\n"
              "\nArguments:\n"
              "1. \"fromaccount\"         (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
              "2. \"tocryptoniteaddress\" (string, required) The cryptonite address to send funds to.\n"
              "3. amount                  (ep, required) The amount in XCN. (transaction fee is added on top).\n"
              "4. minconf                 (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
              "5. \"msg\"                 (string, optional) A comment used to store what the transaction is for. \n"
              "\nResult:\n"
              "\"transactionid\"          (string) The transaction id. (view at https://blockchain.info/tx/[transactionid])\n"
              "\nExamples:\n"
              "\nSend 0.01 XCN from the default account to the address, must have at least 1 confirmation\n"
              + HelpExampleCli("sendfrom", "\"\" \"address\" \"0.01000000ep\"") +
              "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n"
              + HelpExampleCli("sendfrom", "\"tabby\" \"address\" \"0.01000000ep\" 6 \"donation\" ") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("sendfrom", "\"tabby\", \"address\", \"0.01000000ep\", 6, \"donation\"")
          );
  
      string strAccount = AccountFromValue(params[0]);
      CBitcoinAddress address(params[1].get_str());
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
      uint64_t nAmount = AmountFromValue(params[2]);
      int nMinDepth = 1;
      if (params.size() > 3)
          nMinDepth = params[3].get_int();
  
      CWalletTx wtx;
      wtx.strFromAccount = strAccount;
      if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()){
  	string msg = params[4].get_str();
          wtx.msg = vector<char>(msg.begin(),msg.end());
      }
  
      EnsureWalletIsUnlocked();
  
      // Check funds
      uint64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
      if (nAmount > nBalance)
          throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  
      // Send
      string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
      if (strError != "")
          throw JSONRPCError(RPC_WALLET_ERROR, strError);
  
      return wtx.GetTxID().GetHex();
  }
  
  
  Value sendmany(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 2 || params.size() > 4)
          throw runtime_error(
              "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"msg\" )\n"
              "\nSend multiple times. Amounts are ep numbers."
              + HelpRequiringPassphrase() + "\n"
              "\nArguments:\n"
              "1. \"fromaccount\"            (string, required) The account to send the funds from, can be \"\" for the default account\n"
              "2. \"amounts\"                (string, required) A json object with addresses and amounts\n"
              "    {\n"
              "      \"address\":\"amount\"  (ep) The cryptonite address is the key, the numeric amount in XCN is the value\n"
              "      ,...\n"
              "    }\n"
              "3. minconf                    (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
              "4. \"msg\"                    (string, optional) A message to include in transaction\n"
              "\nResult:\n"
              "\"transactionid\"             (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
              "                                    the number of addresses. See https://blockchain.info/tx/[transactionid]\n"
              "\nExamples:\n"
              "\nSend two amounts to two different addresses:\n"
              + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":\"0.01000000ep\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":\"0.02000000ep\"}\"") +
              "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
              + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":\"0.01000000ep\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":\"0.02000000ep\"}\" 6 \"testing\"") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\":\"0.01000000ep\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":\"0.02000000ep\"}\", 6, \"testing\"")
          );
  
      string strAccount = AccountFromValue(params[0]);
      Object sendTo = params[1].get_obj();
      int nMinDepth = 1;
      if (params.size() > 2)
          nMinDepth = params[2].get_int();
  
      CWalletTx wtx;
      wtx.strFromAccount = strAccount;
      if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()){
  	string msg = params[3].get_str();
          wtx.msg = vector<char>(msg.begin(),msg.end());
      }
  
      set<CBitcoinAddress> setAddress;
      map<CKeyID, int64_t> mapSend;
  
      uint64_t totalAmount = 0;
      for (const Pair& s : sendTo)
      {
          CBitcoinAddress address(s.name_);
          if (!address.IsValid())
              throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Cryptonite address: ")+s.name_);
  
          if (setAddress.count(address))
              throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
          setAddress.insert(address);
  
          uint64_t nAmount = AmountFromValue(s.value_);
          totalAmount += nAmount;
  
          mapSend[boost::get<CKeyID>(address.Get())] = nAmount;
      }
  
      EnsureWalletIsUnlocked();
  
      // Check funds
      uint64_t nBalance = GetAccountBalance(strAccount, nMinDepth);
      if (totalAmount > nBalance)
          throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
  
      // Send
      int64_t nFeeRequired = 0;
      string strFailReason;
      bool fCreated = pwalletMain->CreateTransaction(mapSend, wtx, nFeeRequired, strFailReason);
      if (!fCreated)
          throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
      if (!pwalletMain->CommitTransaction(wtx,strFailReason))
          throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
  
      return wtx.GetTxID().GetHex();
  }
  
  // Defined in rpcmisc.cpp
  extern CKeyID _createmultisig(const Array& params);
  
  Value addmultisigaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 2 || params.size() > 3)
      {
          string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
              "\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
              "Each key is a Cryptonite address or hex-encoded public key.\n"
              "If 'account' is specified, assign address to that account.\n"
  
              "\nArguments:\n"
              "1. nrequired        (numeric, required) The number of required signatures out of the n keys or addresses.\n"
              "2. \"keysobject\"   (string, required) A json array of cryptonite addresses or hex-encoded public keys\n"
              "     [\n"
              "       \"address\"  (string) cryptonite address or hex-encoded public key\n"
              "       ...,\n"
              "     ]\n"
              "3. \"account\"      (string, optional) An account to assign the addresses to.\n"
  
              "\nResult:\n"
              "\"cryptoniteaddress\"  (string) A cryptonite address associated with the keys.\n"
  
              "\nExamples:\n"
              "\nAdd a multisig address from 2 addresses\n"
              + HelpExampleCli("addmultisigaddress", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
              "\nAs json rpc call\n"
              + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
          ;
          throw runtime_error(msg);
      }
  
      string strAccount;
      if (params.size() > 2)
          strAccount = AccountFromValue(params[2]);
  
      // Construct using pay-to-script-hash:
      CKeyID inner = _createmultisig(params);
  
      pwalletMain->SetAddressBook(inner, strAccount, "send");
      return CBitcoinAddress(inner).ToString();
  }
  
  
  struct tallyitem
  {
      int64_t nAmount;
      int nConf;
      vector<uint256> txids;
      tallyitem()
      {
          nAmount = 0;
          nConf = std::numeric_limits<int>::max();
      }
  };
  
  Value ListReceived(const Array& params, bool fByAccounts)
  {
      // Minimum confirmations
      int nMinDepth = 1;
      if (params.size() > 0)
          nMinDepth = params[0].get_int();
  
      // Whether to include empty accounts
      bool fIncludeEmpty = false;
      if (params.size() > 1)
          fIncludeEmpty = params[1].get_bool();
  
      // Tally
      map<CBitcoinAddress, tallyitem> mapTally;
      for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
      {
          const CWalletTx& wtx = (*it).second;
  
          int nDepth = GetDepthInMainChain(wtx.GetTxID());
          if (nDepth < nMinDepth)
              continue;
  
          for (const CTxOut& txout : wtx.vout)
          {
              CTxDestination address = CKeyID(txout.pubKey);
              if (!pwalletMain->IsMine(txout.pubKey))
                  continue;
  
              tallyitem& item = mapTally[address];
              item.nAmount += txout.nValue;
              item.nConf = min(item.nConf, nDepth);
              item.txids.push_back(wtx.GetTxID());
          }
      }
  
      // Reply
      Array ret;
      map<string, tallyitem> mapAccountTally;
      for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwalletMain->mapAddressBook)
      {
          const CBitcoinAddress& address = item.first;
          const string& strAccount = item.second.name;
          map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
          if (it == mapTally.end() && !fIncludeEmpty)
              continue;
  
          int64_t nAmount = 0;
          int nConf = std::numeric_limits<int>::max();
          if (it != mapTally.end())
          {
              nAmount = (*it).second.nAmount;
              nConf = (*it).second.nConf;
          }
  
          if (fByAccounts)
          {
              tallyitem& item = mapAccountTally[strAccount];
              item.nAmount += nAmount;
              item.nConf = min(item.nConf, nConf);
          }
          else
          {
              Object obj;
              obj.push_back(Pair("address",       address.ToString()));
              obj.push_back(Pair("account",       strAccount));
              obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
              obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
              Array transactions;
              if (it != mapTally.end())
              {
                  for (const uint256& item : (*it).second.txids)
                  {
                      transactions.push_back(item.GetHex());
                  }
              }
              obj.push_back(Pair("txids", transactions));
              ret.push_back(obj);
          }
      }
  
      if (fByAccounts)
      {
          for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
          {
              int64_t nAmount = (*it).second.nAmount;
              int nConf = (*it).second.nConf;
              Object obj;
              obj.push_back(Pair("account",       (*it).first));
              obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
              obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
              ret.push_back(obj);
          }
      }
  
      return ret;
  }
  
  Value listreceivedbyaddress(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 2)
          throw runtime_error(
              "listreceivedbyaddress ( minconf includeempty )\n"
              "\nList balances by receiving address.\n"
              "\nArguments:\n"
              "1. minconf       (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
              "2. includeempty  (numeric, optional, dafault=false) Whether to include addresses that haven't received any payments.\n"
  
              "\nResult:\n"
              "[\n"
              "  {\n"
              "    \"address\" : \"receivingaddress\",  (string) The receiving address\n"
              "    \"account\" : \"accountname\",       (string) The account of the receiving address. The default account is \"\".\n"
              "    \"amount\" : x.xxx,                  (ep) The total amount in XCN received by the address\n"
              "    \"confirmations\" : n                (numeric) The number of confirmations of the most recent transaction included\n"
              "  }\n"
              "  ,...\n"
              "]\n"
  
              "\nExamples:\n"
              + HelpExampleCli("listreceivedbyaddress", "")
              + HelpExampleCli("listreceivedbyaddress", "6 true")
              + HelpExampleRpc("listreceivedbyaddress", "6, true")
          );
  
      return ListReceived(params, false);
  }
  
  Value listreceivedbyaccount(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 2)
          throw runtime_error(
              "listreceivedbyaccount ( minconf includeempty )\n"
              "\nList balances by account.\n"
              "\nArguments:\n"
              "1. minconf      (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
              "2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
  
              "\nResult:\n"
              "[\n"
              "  {\n"
              "    \"account\" : \"accountname\",  (string) The account name of the receiving account\n"
              "    \"amount\" : x.xxx,             (numeric) The total amount received by addresses with this account\n"
              "    \"confirmations\" : n           (numeric) The number of confirmations of the most recent transaction included\n"
              "  }\n"
              "  ,...\n"
              "]\n"
  
              "\nExamples:\n"
              + HelpExampleCli("listreceivedbyaccount", "")
              + HelpExampleCli("listreceivedbyaccount", "6 true")
              + HelpExampleRpc("listreceivedbyaccount", "6, true")
          );
  
      return ListReceived(params, true);
  }
  
  static void MaybePushAddress(Object & entry, const CTxDestination &dest)
  {
      CBitcoinAddress addr;
      if (addr.Set(dest))
          entry.push_back(Pair("address", addr.ToString()));
  }
  
  void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
  {
      int64_t nFee;
      string strSentAccount;
      list<pair<CTxDestination, int64_t> > listReceived;
      list<pair<CTxDestination, int64_t> > listSent;
  
      wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
  
      bool fAllAccounts = (strAccount == string("*"));
  
      // Sent
      if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
      {
          for (const std::pair<CTxDestination, int64_t>& s : listSent)
          {
              Object entry;
              entry.push_back(Pair("account", strSentAccount));
              MaybePushAddress(entry, s.first);
              entry.push_back(Pair("category", "send"));
              entry.push_back(Pair("amount", fStandardAmounts ? ValueFromAmount_signed(-1 * s.second) : ValueFromAmount(s.second + nFee)));
              entry.push_back(Pair("fee", fStandardAmounts ? ValueFromAmount_signed(-1 * nFee) : ValueFromAmount(nFee)));
              if (fLong)
                  WalletTxToJSON(wtx, entry);
              ret.push_back(entry);
          }
      }
  
      // Received
      if (listReceived.size() > 0 && GetDepthInMainChain(wtx.GetTxID()) >= nMinDepth)
      {
          for (const std::pair<CTxDestination, int64_t>& r : listReceived)
          {
              string account;
              if (pwalletMain->mapAddressBook.count(r.first))
                  account = pwalletMain->mapAddressBook[r.first].name;
              if (fAllAccounts || (account == strAccount))
              {
                  Object entry;
                  entry.push_back(Pair("account", account));
                  MaybePushAddress(entry, r.first);
                  if (wtx.IsCoinBase())
                  {
                      if (GetDepthInMainChain(wtx.GetTxID()) < 1)
                          entry.push_back(Pair("category", "orphan"));
                      else
                          entry.push_back(Pair("category", "generate"));
                  }
                  else
                  {
                      entry.push_back(Pair("category", "receive"));
                  }
                  entry.push_back(Pair("amount", ValueFromAmount(r.second)));
                  if (fLong)
                      WalletTxToJSON(wtx, entry);
                  ret.push_back(entry);
              }
          }
      }
  }
  
  void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
  {
      bool fAllAccounts = (strAccount == string("*"));
  
      if (fAllAccounts || acentry.strAccount == strAccount)
      {
          Object entry;
          entry.push_back(Pair("account", acentry.strAccount));
          entry.push_back(Pair("category", "move"));
          entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
          entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
          entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
          entry.push_back(Pair("comment", acentry.strComment));
          ret.push_back(entry);
      }
  }
  
  Value listtransactions(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 3)
          throw runtime_error(
              "listtransactions ( \"account\" count from )\n"
              "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
              "\nArguments:\n"
              "1. \"account\"    (string, optional) The account name. If not included, it will list all transactions for all accounts.\n"
              "                                     If \"\" is set, it will list transactions for the default account.\n"
              "2. count          (numeric, optional, default=10) The number of transactions to return\n"
              "3. from           (numeric, optional, default=0) The number of transactions to skip\n"
  
              "\nResult:\n"
              "[\n"
              "  {\n"
              "    \"account\":\"accountname\",       (string) The account name associated with the transaction. \n"
              "                                                It will be \"\" for the default account.\n"
              "    \"address\":\"cryptoniteaddress\",    (string) The cryptonite address of the transaction. Not present for \n"
              "                                                move transactions (category = move).\n"
              "    \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
              "                                                transaction between accounts, and not associated with an address,\n"
              "                                                transaction id or block. 'send' and 'receive' transactions are \n"
              "                                                associated with an address, transaction id and block details\n"
              "    \"amount\": x.xxx,          (ep) The amount in XCN. This is negative for the 'send' category, and for the\n"
              "                                         'move' category for moves outbound. It is positive for the 'receive' category,\n"
              "                                         and for the 'move' category for inbound funds.\n"
              "    \"fee\": x.xxx,             (ep) The amount of the fee in XCN. This is negative and only available for the \n"
              "                                         'send' category of transactions.\n"
              "    \"confirmations\": n,       (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
              "                                         'receive' category of transactions.\n"
              "    \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
              "                                          category of transactions.\n"
              "    \"blockindex\": n,          (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
              "                                          category of transactions.\n"
              "    \"txid\": \"transactionid\", (string) The transaction id (see https://blockchain.info/tx/[transactionid]. Available \n"
              "                                          for 'send' and 'receive' category of transactions.\n"
              "    \"time\": xxx,              (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
              "    \"timereceived\": xxx,      (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
              "                                          for 'send' and 'receive' category of transactions.\n"
              "    \"comment\": \"...\",       (string) If a comment is associated with the transaction.\n"
              "    \"otheraccount\": \"accountname\",  (string) For the 'move' category of transactions, the account the funds came \n"
              "                                          from (for receiving funds, positive amounts), or went to (for sending funds,\n"
              "                                          negative amounts).\n"
              "  }\n"
              "]\n"
  
              "\nExamples:\n"
              "\nList the most recent 10 transactions in the systems\n"
              + HelpExampleCli("listtransactions", "") +
              "\nList the most recent 10 transactions for the tabby account\n"
              + HelpExampleCli("listtransactions", "\"tabby\"") +
              "\nList transactions 100 to 120 from the tabby account\n"
              + HelpExampleCli("listtransactions", "\"tabby\" 20 100") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("listtransactions", "\"tabby\", 20, 100")
          );
  
      string strAccount = "*";
      if (params.size() > 0)
          strAccount = params[0].get_str();
      int nCount = 10;
      if (params.size() > 1)
          nCount = params[1].get_int();
      int nFrom = 0;
      if (params.size() > 2)
          nFrom = params[2].get_int();
  
      if (nCount < 0)
          throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
      if (nFrom < 0)
          throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
  
      Array ret;
  
      std::list<CAccountingEntry> acentries;
      CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
  
      // iterate backwards until we have nCount items to return:
      for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
      {
          CWalletTx *const pwtx = (*it).second.first;
          if (pwtx != 0)
              ListTransactions(*pwtx, strAccount, -1, true, ret);
          CAccountingEntry *const pacentry = (*it).second.second;
          if (pacentry != 0)
              AcentryToJSON(*pacentry, strAccount, ret);
  
          if ((int)ret.size() >= (nCount+nFrom)) break;
      }
      // ret is newest to oldest
  
      if (nFrom > (int)ret.size())
          nFrom = ret.size();
      if ((nFrom + nCount) > (int)ret.size())
          nCount = ret.size() - nFrom;
      Array::iterator first = ret.begin();
      std::advance(first, nFrom);
      Array::iterator last = ret.begin();
      std::advance(last, nFrom+nCount);
  
      if (last != ret.end()) ret.erase(last, ret.end());
      if (first != ret.begin()) ret.erase(ret.begin(), first);
  
      std::reverse(ret.begin(), ret.end()); // Return oldest to newest
  
      return ret;
  }
  
  Value listaccounts(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 1)
          throw runtime_error(
              "listaccounts ( minconf )\n"
              "\nReturns Object that has account names as keys, account balances as values.\n"
              "\nArguments:\n"
              "1. minconf     (numeric, optional, default=1) Only onclude transactions with at least this many confirmations\n"
              "\nResult:\n"
              "{                      (json object where keys are account names, and values are numeric balances\n"
              "  \"account\": x.xxx,  (numeric) The property name is the account name, and the value is the total balance for the account.\n"
              "  ...\n"
              "}\n"
              "\nExamples:\n"
              "\nList account balances where there at least 1 confirmation\n"
              + HelpExampleCli("listaccounts", "") +
              "\nList account balances including zero confirmation transactions\n"
              + HelpExampleCli("listaccounts", "0") +
              "\nList account balances for 6 or more confirmations\n"
              + HelpExampleCli("listaccounts", "6") +
              "\nAs json rpc call\n"
              + HelpExampleRpc("listaccounts", "6")
          );
  
      int nMinDepth = 1;
      if (params.size() > 0)
          nMinDepth = params[0].get_int();
  
      map<string, int64_t> mapAccountBalances;
      for (const std::pair<CTxDestination, CAddressBookData>& entry : pwalletMain->mapAddressBook) {
          if (pwalletMain->IsMine(boost::get<CKeyID>(entry.first))) // This address belongs to me
              mapAccountBalances[entry.second.name] = 0;
      }
  
      for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
      {
          const CWalletTx& wtx = (*it).second;
          int64_t nFee;
          string strSentAccount;
          list<pair<CTxDestination, int64_t> > listReceived;
          list<pair<CTxDestination, int64_t> > listSent;
  
          int nDepth = GetDepthInMainChain(wtx.GetTxID());
          if (nDepth < 0)
              continue;
          wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
          mapAccountBalances[strSentAccount] -= nFee;
          for (const std::pair<CTxDestination, int64_t>& s : listSent)
              mapAccountBalances[strSentAccount] -= s.second;
          if (nDepth >= nMinDepth)
          {
              for (const std::pair<CTxDestination, int64_t>& r : listReceived)
                  if (pwalletMain->mapAddressBook.count(r.first))
                      mapAccountBalances[pwalletMain->mapAddressBook[r.first].name] += r.second;
                  else
                      mapAccountBalances[""] += r.second;
          }
      }
  
      list<CAccountingEntry> acentries;
      CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
      for (const CAccountingEntry& entry : acentries)
          mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
  
      Object ret;
      for (const std::pair<string, int64_t>& accountBalance : mapAccountBalances) {
          ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
      }
      return ret;
  }
  
  Value listsinceblock(const Array& params, bool fHelp)
  {
      if (fHelp)
          throw runtime_error(
              "listsinceblock ( \"blockhash\" target-confirmations )\n"
              "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
              "\nArguments:\n"
              "1. \"blockhash\"   (string, optional) The block hash to list transactions since\n"
              "2. target-confirmations:    (numeric, optional) The confirmations required, must be 1 or more\n"
              "\nResult:\n"
              "{\n"
              "  \"transactions\": [\n"
              "    \"account\":\"accountname\",       (string) The account name associated with the transaction. Will be \"\" for the default account.\n"
              "    \"address\":\"cryptoniteaddress\",    (string) The cryptonite address of the transaction. Not present for move transactions (category = move).\n"
              "    \"category\":\"send|receive\",     (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
              "    \"amount\": x.xxx,          (ep) The amount in XCN. This is negative for the 'send' category, and for the 'move' category for moves \n"
              "                                          outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
              "    \"fee\": x.xxx,             (ep) The amount of the fee in XCN. This is negative and only available for the 'send' category of transactions.\n"
              "    \"confirmations\": n,       (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
              "    \"blockhash\": \"hashvalue\",     (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
              "    \"blockindex\": n,          (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
              "    \"blocktime\": xxx,         (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
              "    \"txid\": \"transactionid\",  (string) The transaction id (see https://blockchain.info/tx/[transactionid]. Available for 'send' and 'receive' category of transactions.\n"
              "    \"time\": xxx,              (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
              "    \"timereceived\": xxx,      (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
              "    \"comment\": \"...\",       (string) If a comment is associated with the transaction.\n"
              "    \"to\": \"...\",            (string) If a comment to is associated with the transaction.\n"
               "  ],\n"
              "  \"lastblock\": \"lastblockhash\"     (string) The hash of the last block\n"
              "}\n"
              "\nExamples:\n"
              + HelpExampleCli("listsinceblock", "")
              + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
              + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
          );
  
      CBlockIndex *pindex = nullptr;
      int target_confirms = 1;
  
      if (params.size() > 0)
      {
          uint256 blockId = 0;
  
          blockId.SetHex(params[0].get_str());
          std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(blockId);
          if (it != mapBlockIndex.end())
              pindex = it->second;
      }
  
      if (params.size() > 1)
      {
          target_confirms = params[1].get_int();
  
          if (target_confirms < 1)
              throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
      }
  
      int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
  
      Array transactions;
  
      for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
      {
          CWalletTx tx = (*it).second;
  
          if (depth == -1 || GetDepthInMainChain(tx.GetTxID()) < depth)
              ListTransactions(tx, "*", -1, true, transactions);
      }
  
      CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
      uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : 0;
  
      Object ret;
      ret.push_back(Pair("transactions", transactions));
      ret.push_back(Pair("lastblock", lastblock.GetHex()));
  
      return ret;
  }
  
  Value gettransaction(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 1)
          throw runtime_error(
              "gettransaction \"txid\"\n"
              "\nGet detailed information about in-wallet transaction <txid>\n"
              "\nArguments:\n"
              "1. \"txid\"    (string, required) The transaction id\n"
              "\nResult:\n"
              "{\n"
              "  \"amount\" : x.xxx,        (ep) The transaction amount in XCN\n"
              "  \"confirmations\" : n,     (numeric) The number of confirmations\n"
              "  \"blockhash\" : \"hash\",  (string) The block hash\n"
              "  \"blockindex\" : xx,       (numeric) The block index\n"
              "  \"blocktime\" : ttt,       (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
              "  \"txid\" : \"transactionid\",   (string) The transaction id, see also https://blockchain.info/tx/[transactionid]\n"
              "  \"time\" : ttt,            (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
              "  \"timereceived\" : ttt,    (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
              "  \"details\" : [\n"
              "    {\n"
              "      \"account\" : \"accountname\",  (string) The account name involved in the transaction, can be \"\" for the default account.\n"
              "      \"address\" : \"cryptoniteaddress\",   (string) The cryptonite address involved in the transaction\n"
              "      \"category\" : \"send|receive\",    (string) The category, either 'send' or 'receive'\n"
              "      \"amount\" : x.xxx                  (ep) The amount in XCN\n"
              "    }\n"
              "    ,...\n"
              "  ],\n"
              "  \"hex\" : \"data\"         (string) Raw data for transaction\n"
              "}\n"
  
              "\nbExamples\n"
              + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
              + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
          );
  
      uint256 hash;
      hash.SetHex(params[0].get_str());
  
      Object entry;
      if (!pwalletMain->mapWallet.count(hash))
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
      const CWalletTx& wtx = pwalletMain->mapWallet[hash];
  
      int64_t nCredit = wtx.GetCredit();
      int64_t nDebit = wtx.GetDebit();
      int64_t nFee = (wtx.IsFromMe() ? nDebit - wtx.GetValueOut(): 0);
  
      //printf("C: %ld, V: %ld, D: %ld\n", nFee, wtx.GetValueOut(), nDebit);
  
      if (wtx.IsFromMe()){
          entry.push_back(Pair("amount", fStandardAmounts ? ValueFromAmount_signed(-1 * (nDebit - nFee)) : ValueFromAmount(nDebit)));
          entry.push_back(Pair("fee", fStandardAmounts ? ValueFromAmount_signed(-1 * nFee) : ValueFromAmount(nFee)));
      }else
          entry.push_back(Pair("amount", ValueFromAmount(nCredit)));
  
  
      WalletTxToJSON(wtx, entry);
  
      Array details;
      ListTransactions(wtx, "*", -1, false, details);
      entry.push_back(Pair("details", details));
  
      CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
      ssTx << static_cast<CTransaction>(wtx);
      string strHex = HexStr(ssTx.begin(), ssTx.end());
      entry.push_back(Pair("hex", strHex));
  
      return entry;
  }
  
  
  Value backupwallet(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 1)
          throw runtime_error(
              "backupwallet \"destination\"\n"
              "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
              "\nArguments:\n"
              "1. \"destination\"   (string) The destination directory or file\n"
              "\nExamples:\n"
              + HelpExampleCli("backupwallet", "\"backup.dat\"")
              + HelpExampleRpc("backupwallet", "\"backup.dat\"")
          );
  
      string strDest = params[0].get_str();
      if (!BackupWallet(*pwalletMain, strDest))
          throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
  
      return Value::null;
  }
  
  
  Value keypoolrefill(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() > 1)
          throw runtime_error(
              "keypoolrefill ( newsize )\n"
              "\nFills the keypool."
              + HelpRequiringPassphrase() + "\n"
              "\nArguments\n"
              "1. newsize     (numeric, optional, default=100) The new keypool size\n"
              "\nExamples:\n"
              + HelpExampleCli("keypoolrefill", "")
              + HelpExampleRpc("keypoolrefill", "")
          );
  
      // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
      unsigned int kpSize = 0;
      if (params.size() > 0) {
          if (params[0].get_int() < 0)
              throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
          kpSize = (unsigned int)params[0].get_int();
      }
  
      EnsureWalletIsUnlocked();
      pwalletMain->TopUpKeyPool(kpSize);
  
      if (pwalletMain->GetKeyPoolSize() < kpSize)
          throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
  
      return Value::null;
  }
  
  
  static void LockWallet(CWallet* pWallet)
  {
      LOCK(cs_nWalletUnlockTime);
      nWalletUnlockTime = 0;
      pWallet->Lock();
  }
  
  Value walletpassphrase(const Array& params, bool fHelp)
  {
      if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
          throw runtime_error(
              "walletpassphrase \"passphrase\" timeout\n"
              "\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
              "This is needed prior to performing transactions related to private keys such as sending XCN\n"
              "\nArguments:\n"
              "1. \"passphrase\"     (string, required) The wallet passphrase\n"
              "2. timeout            (numeric, required) The time to keep the decryption key in seconds.\n"
              "\nNote:\n"
              "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
              "time that overrides the old one.\n"
              "\nExamples:\n"
              "\nunlock the wallet for 60 seconds\n"
              + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
              "\nLock the wallet again (before 60 seconds)\n"
              + HelpExampleCli("walletlock", "") +
              "\nAs json rpc call\n"
              + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
          );
  
      if (fHelp)
          return true;
      if (!pwalletMain->IsCrypted())
          throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
  
      // Note that the walletpassphrase is stored in params[0] which is not mlock()ed
      SecureString strWalletPass;
      strWalletPass.reserve(100);
      // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
      // Alternately, find a way to make params[0] mlock()'d to begin with.
      strWalletPass = params[0].get_str().c_str();
  
      if (strWalletPass.length() > 0)
      {
          if (!pwalletMain->Unlock(strWalletPass))
              throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
      }
      else
          throw runtime_error(
              "walletpassphrase <passphrase> <timeout>\n"
              "Stores the wallet decryption key in memory for <timeout> seconds.");
  
      pwalletMain->TopUpKeyPool();
  
      int64_t nSleepTime = params[1].get_int64();
      LOCK(cs_nWalletUnlockTime);
      nWalletUnlockTime = GetTime() + nSleepTime;
      RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
  
      return Value::null;
  }
  
  
  Value walletpassphrasechange(const Array& params, bool fHelp)
  {
      if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
          throw runtime_error(
              "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
              "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
              "\nArguments:\n"
              "1. \"oldpassphrase\"      (string) The current passphrase\n"
              "2. \"newpassphrase\"      (string) The new passphrase\n"
              "\nExamples:\n"
              + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
              + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
          );
  
      if (fHelp)
          return true;
      if (!pwalletMain->IsCrypted())
          throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
  
      // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
      // Alternately, find a way to make params[0] mlock()'d to begin with.
      SecureString strOldWalletPass;
      strOldWalletPass.reserve(100);
      strOldWalletPass = params[0].get_str().c_str();
  
      SecureString strNewWalletPass;
      strNewWalletPass.reserve(100);
      strNewWalletPass = params[1].get_str().c_str();
  
      if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
          throw runtime_error(
              "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
              "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
  
      if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
          throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
  
      return Value::null;
  }
  
  
  Value walletlock(const Array& params, bool fHelp)
  {
      if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
          throw runtime_error(
              "walletlock\n"
              "\nRemoves the wallet encryption key from memory, locking the wallet.\n"
              "After calling this method, you will need to call walletpassphrase again\n"
              "before being able to call any methods which require the wallet to be unlocked.\n"
              "\nExamples:\n"
              "\nSet the passphrase for 2 minutes to perform a transaction\n"
              + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
              "\nPerform a send (requires passphrase set)\n"
              + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 1.0") +
              "\nClear the passphrase since we are done before 2 minutes is up\n"
              + HelpExampleCli("walletlock", "") +
              "\nAs json rpc call\n"
              + HelpExampleRpc("walletlock", "")
          );
  
      if (fHelp)
          return true;
      if (!pwalletMain->IsCrypted())
          throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
  
      {
          LOCK(cs_nWalletUnlockTime);
          pwalletMain->Lock();
          nWalletUnlockTime = 0;
      }
  
      return Value::null;
  }
  
  
  Value encryptwallet(const Array& params, bool fHelp)
  {
      if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
          throw runtime_error(
              "encryptwallet \"passphrase\"\n"
              "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
              "After this, any calls that interact with private keys such as sending or signing \n"
              "will require the passphrase to be set prior the making these calls.\n"
              "Use the walletpassphrase call for this, and then walletlock call.\n"
              "If the wallet is already encrypted, use the walletpassphrasechange call.\n"
              "Note that this will shutdown the server.\n"
              "\nArguments:\n"
              "1. \"passphrase\"    (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
              "\nExamples:\n"
              "\nEncrypt you wallet\n"
              + HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
              "\nNow set the passphrase to use the wallet, such as for signing or sending XCN\n"
              + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
              "\nNow we can so something like sign\n"
              + HelpExampleCli("signmessage", "\"cryptoniteaddress\" \"test message\"") +
              "\nNow lock the wallet again by removing the passphrase\n"
              + HelpExampleCli("walletlock", "") +
              "\nAs a json rpc call\n"
              + HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
          );
  
      if (fHelp)
          return true;
      if (pwalletMain->IsCrypted())
          throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
  
      // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
      // Alternately, find a way to make params[0] mlock()'d to begin with.
      SecureString strWalletPass;
      strWalletPass.reserve(100);
      strWalletPass = params[0].get_str().c_str();
  
      if (strWalletPass.length() < 1)
          throw runtime_error(
              "encryptwallet <passphrase>\n"
              "Encrypts the wallet with <passphrase>.");
  
      if (!pwalletMain->EncryptWallet(strWalletPass))
          throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
  
      // BDB seems to have a bad habit of writing old data into
      // slack space in .dat files; that is bad if the old data is
      // unencrypted private keys. So:
      StartShutdown();
      return "wallet encrypted; Cryptonite server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
  }
  
  
  Value settxfee(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 1 || params.size() > 1)
          throw runtime_error(
              "settxfee amount\n"
              "\nSet the transaction fee per kB.\n"
              "\nArguments:\n"
              "1. amount         (ep, required) The transaction fee in XCN/kB rounded to the nearest 0.00000001\n"
              "\nResult\n"
              "true|false        (boolean) Returns true if successful\n"
              "\nExamples:\n"
              + HelpExampleCli("settxfee", "0.000010000ep")
              + HelpExampleRpc("settxfee", "0.000010000ep")
          );
  
      // Amount
      uint64_t nAmount = AmountFromValue(params[0]);        // rejects 0.0 amounts
  
      nTransactionFee = nAmount;
      return true;
  }
  
  Value getwalletinfo(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 0)
          throw runtime_error(
              "getwalletinfo\n"
              "Returns an object containing various wallet state info.\n"
              "\nResult:\n"
              "{\n"
              "  \"walletversion\": xxxxx,     (numeric) the wallet version\n"
              "  \"balance\": xxxxxxx,         (ep) the total XCN balance of the wallet\n"
              "  \"txcount\": xxxxxxx,         (numeric) the total number of transactions in the wallet\n"
              "  \"keypoololdest\": xxxxxx,    (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
              "  \"keypoolsize\": xxxx,        (numeric) how many new keys are pre-generated\n"
              "  \"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"
              "}\n"
              "\nExamples:\n"
              + HelpExampleCli("getwalletinfo", "")
              + HelpExampleRpc("getwalletinfo", "")
          );
  
      Object obj;
      obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
      obj.push_back(Pair("balance",       ValueFromAmount(pwalletMain->GetBalance())));
      obj.push_back(Pair("txcount",       (int)pwalletMain->mapWallet.size()));
      obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
      obj.push_back(Pair("keypoolsize",   (int)pwalletMain->GetKeyPoolSize()));
      if (pwalletMain->IsCrypted())
          obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
      return obj;
  }
  
  
  /***************************** Agregado por Tesis de Carlos Sanguña***************************************************************************/
  Value contractdeploy(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() != 4)
          throw runtime_error(
              "contractdeploy \"fromaccount\" \"bin-bytecode\" \"abi\" \"solidity version\"\n" 
              "Create a contract address with associated bytecode that can be executed and has a persistent storage space.\n"
              "Returns contract address.\n"
              "\nExamples:\n"
              + HelpExampleCli("contractdeploy", " \"608060405234801561001057600080fd5b506...\"  \"abi\"  \"0.5.1+commit.c8a2cb62.Linux.g++\"")
          );
      string strAccount = AccountFromValue(params[0]);
      uint64_t nAmount = 0;
      CWalletTx wtx;
      wtx.strFromAccount = strAccount;
      int64_t nFeeRequired;
      string strFailReason;
  
      CBitcoinAddress address; /////////////////// Importanteeeeee esta es la direccion que deberá retornar la funcion ya que a su vez es la direccion que sera enviada a la transacción.
  
      /*El despliegue del contrato deberá ir aqui*/
  
  
  
      bool fCreated = pwalletMain->CreateTransaction(boost::get<CKeyID>(address.Get()), nAmount, wtx, nFeeRequired, strFailReason);
      if (!fCreated)
          throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
      if (!pwalletMain->CommitTransaction(wtx,strFailReason))
          throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
      
     return CBitcoinAddress(address).ToString();
  }
  
  Value contractexec(const Array& params, bool fHelp)
  {
      if (fHelp || params.size() < 4 || params.size() > 5)
          throw runtime_error(
              "contractexec \"fromaccount\" \"contract-address\" \"hash-method\" \"input\" (\"amount\") \n"
              "execute the method associated with the contract address\n"
              "Returns the method result.\n"
              "\nExamples:\n"
              + HelpExampleCli("contractexec", " \"tabby\" \"1F2A98889594024BFFDA3311CBE69728D392C06D\"\"a5f3c23b\" \"{x:4 y:5}\" ")
          );
      
      string strAccount = AccountFromValue(params[0]);
  
      CBitcoinAddress address(params[1].get_str()); /// Direccion de la cuenta que se va a ejecutar
      if (!address.IsValid())
          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Cryptonite address");
  
      uint64_t nAmount = 0;
      if (params.size()==5)
          nAmount=AmountFromValue(params[4]);
  
      CWalletTx wtx;
      wtx.strFromAccount = strAccount;
      int64_t nFeeRequired;
      string strFailReason;
      wtx.sResult = "Este es el resultado";
      wtx.bContract=true;
  
      EnsureWalletIsUnlocked();
  
      /*La ejecucion del copntrato puede ir aquí*/
  
      bool fCreated = pwalletMain->CreateTransaction(boost::get<CKeyID>(address.Get()), nAmount, wtx, nFeeRequired, strFailReason);
      if (!fCreated)
          throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
      if (!pwalletMain->CommitTransaction(wtx,strFailReason))
          throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
      
  
      return wtx.GetTxID().GetHex(); /// Aqui lo que hay que colocar es el resultado de la ejecución
  }
  
      
  
  