Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin r202 (last Satoshi commit) · 2010-12-15

rpc.cpp

1,899 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#include "cryptopp/sha.h"7#undef printf8#include <boost/asio.hpp>9#include <boost/iostreams/concepts.hpp>10#include <boost/iostreams/stream.hpp>11#ifdef USE_SSL12#include <boost/asio/ssl.hpp> 13typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;14#endif15#include "json/json_spirit_reader_template.h"16#include "json/json_spirit_writer_template.h"17#include "json/json_spirit_utils.h"18#define printf OutputDebugStringF19// MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are20// precompiled in headers.h.  The problem might be when the pch file goes over21// a certain size around 145MB.  If we need access to json_spirit outside this22// file, we could use the compiled json_spirit option.2324using namespace boost::asio;25using namespace json_spirit;2627void ThreadRPCServer2(void* parg);28typedef Value(*rpcfn_type)(const Array& params, bool fHelp);29extern map<string, rpcfn_type> mapCallTable;303132Object JSONRPCError(int code, const string& message)33{34    Object error;35    error.push_back(Pair("code", code));36    error.push_back(Pair("message", message));37    return error;38}394041void PrintConsole(const char* format, ...)42{43    char buffer[50000];44    int limit = sizeof(buffer);45    va_list arg_ptr;46    va_start(arg_ptr, format);47    int ret = _vsnprintf(buffer, limit, format, arg_ptr);48    va_end(arg_ptr);49    if (ret < 0 || ret >= limit)50    {51        ret = limit - 1;52        buffer[limit-1] = 0;53    }54    printf("%s", buffer);55#if defined(__WXMSW__) && defined(GUI)56    MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);57#else58    fprintf(stdout, "%s", buffer);59#endif60}616263int64 AmountFromValue(const Value& value)64{65    double dAmount = value.get_real();66    if (dAmount <= 0.0 || dAmount > 21000000.0)67        throw JSONRPCError(-3, "Invalid amount");68    int64 nAmount = roundint64(dAmount * 100.00) * CENT;69    if (!MoneyRange(nAmount))70        throw JSONRPCError(-3, "Invalid amount");71    return nAmount;72}7374Value ValueFromAmount(int64 amount)75{76    return (double)amount / (double)COIN;77}7879void WalletTxToJSON(const CWalletTx& wtx, Object& entry)80{81    entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));82    entry.push_back(Pair("txid", wtx.GetHash().GetHex()));83    foreach(const PAIRTYPE(string,string)& item, wtx.mapValue)84        entry.push_back(Pair(item.first, item.second));85}868788899091///92/// Note: This interface may still be subject to change.93///949596Value help(const Array& params, bool fHelp)97{98    if (fHelp || params.size() > 1)99        throw runtime_error(100            "help [command]\n"101            "List commands, or get help for a command.");102103    string strCommand;104    if (params.size() > 0)105        strCommand = params[0].get_str();106107    string strRet;108    set<rpcfn_type> setDone;109    for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)110    {111        string strMethod = (*mi).first;112        // We already filter duplicates, but these deprecated screw up the sort order113        if (strMethod == "getamountreceived" ||114            strMethod == "getallreceived" ||115            (strMethod.find("label") != string::npos))116            continue;117        if (strCommand != "" && strMethod != strCommand)118            continue;119        try120        {121            Array params;122            rpcfn_type pfn = (*mi).second;123            if (setDone.insert(pfn).second)124                (*pfn)(params, true);125        }126        catch (std::exception& e)127        {128            // Help text is returned in an exception129            string strHelp = string(e.what());130            if (strCommand == "")131                if (strHelp.find('\n') != -1)132                    strHelp = strHelp.substr(0, strHelp.find('\n'));133            strRet += strHelp + "\n";134        }135    }136    if (strRet == "")137        strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());138    strRet = strRet.substr(0,strRet.size()-1);139    return strRet;140}141142143Value stop(const Array& params, bool fHelp)144{145    if (fHelp || params.size() != 0)146        throw runtime_error(147            "stop\n"148            "Stop bitcoin server.");149150    // Shutdown will take long enough that the response should get back151    CreateThread(Shutdown, NULL);152    return "bitcoin server stopping";153}154155156Value getblockcount(const Array& params, bool fHelp)157{158    if (fHelp || params.size() != 0)159        throw runtime_error(160            "getblockcount\n"161            "Returns the number of blocks in the longest block chain.");162163    return nBestHeight;164}165166167Value getblocknumber(const Array& params, bool fHelp)168{169    if (fHelp || params.size() != 0)170        throw runtime_error(171            "getblocknumber\n"172            "Returns the block number of the latest block in the longest block chain.");173174    return nBestHeight;175}176177178Value getconnectioncount(const Array& params, bool fHelp)179{180    if (fHelp || params.size() != 0)181        throw runtime_error(182            "getconnectioncount\n"183            "Returns the number of connections to other nodes.");184185    return (int)vNodes.size();186}187188189double GetDifficulty()190{191    // Floating point number that is a multiple of the minimum difficulty,192    // minimum difficulty = 1.0.193    if (pindexBest == NULL)194        return 1.0;195    int nShift = 256 - 32 - 31; // to fit in a uint196    double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();197    double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();198    return dMinimum / dCurrently;199}200201Value getdifficulty(const Array& params, bool fHelp)202{203    if (fHelp || params.size() != 0)204        throw runtime_error(205            "getdifficulty\n"206            "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");207208    return GetDifficulty();209}210211212Value getgenerate(const Array& params, bool fHelp)213{214    if (fHelp || params.size() != 0)215        throw runtime_error(216            "getgenerate\n"217            "Returns true or false.");218219    return (bool)fGenerateBitcoins;220}221222223Value setgenerate(const Array& params, bool fHelp)224{225    if (fHelp || params.size() < 1 || params.size() > 2)226        throw runtime_error(227            "setgenerate <generate> [genproclimit]\n"228            "<generate> is true or false to turn generation on or off.\n"229            "Generation is limited to [genproclimit] processors, -1 is unlimited.");230231    bool fGenerate = true;232    if (params.size() > 0)233        fGenerate = params[0].get_bool();234235    if (params.size() > 1)236    {237        int nGenProcLimit = params[1].get_int();238        fLimitProcessors = (nGenProcLimit != -1);239        CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);240        if (nGenProcLimit != -1)241            CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);242    }243244    GenerateBitcoins(fGenerate);245    return Value::null;246}247248249Value gethashespersec(const Array& params, bool fHelp)250{251    if (fHelp || params.size() != 0)252        throw runtime_error(253            "gethashespersec\n"254            "Returns a recent hashes per second performance measurement while generating.");255256    if (GetTimeMillis() - nHPSTimerStart > 8000)257        return (boost::int64_t)0;258    return (boost::int64_t)dHashesPerSec;259}260261262Value getinfo(const Array& params, bool fHelp)263{264    if (fHelp || params.size() != 0)265        throw runtime_error(266            "getinfo\n"267            "Returns an object containing various state info.");268269    Object obj;270    obj.push_back(Pair("version",       (int)VERSION));271    obj.push_back(Pair("balance",       (double)GetBalance() / (double)COIN));272    obj.push_back(Pair("blocks",        (int)nBestHeight));273    obj.push_back(Pair("connections",   (int)vNodes.size()));274    obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));275    obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));276    obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));277    obj.push_back(Pair("difficulty",    (double)GetDifficulty()));278    obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));279    obj.push_back(Pair("testnet",       fTestNet));280    obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));281    obj.push_back(Pair("paytxfee",      (double)nTransactionFee / (double)COIN));282    obj.push_back(Pair("errors",        GetWarnings("statusbar")));283    return obj;284}285286287Value getnewaddress(const Array& params, bool fHelp)288{289    if (fHelp || params.size() > 1)290        throw runtime_error(291            "getnewaddress [account]\n"292            "Returns a new bitcoin address for receiving payments.  "293            "If [account] is specified (recommended), it is added to the address book "294            "so payments received with the address will be credited to [account].");295296    // Parse the account first so we don't generate a key if there's an error297    string strAccount;298    if (params.size() > 0)299        strAccount = params[0].get_str();300301    // Generate a new key that is added to wallet302    string strAddress = PubKeyToAddress(GetKeyFromKeyPool());303304    SetAddressBookName(strAddress, strAccount);305    return strAddress;306}307308309Value getaccountaddress(const Array& params, bool fHelp)310{311    if (fHelp || params.size() != 1)312        throw runtime_error(313            "getaccountaddress <account>\n"314            "Returns the current bitcoin address for receiving payments to this account.");315316    // Parse the account first so we don't generate a key if there's an error317    string strAccount = params[0].get_str();318319    CRITICAL_BLOCK(cs_mapWallet)320    {321        CWalletDB walletdb;322        walletdb.TxnBegin();323324        CAccount account;325        walletdb.ReadAccount(strAccount, account);326327        // Check if the current key has been used328        if (!account.vchPubKey.empty())329        {330            CScript scriptPubKey;331            scriptPubKey.SetBitcoinAddress(account.vchPubKey);332            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();333                 it != mapWallet.end() && !account.vchPubKey.empty();334                 ++it)335            {336                const CWalletTx& wtx = (*it).second;337                foreach(const CTxOut& txout, wtx.vout)338                    if (txout.scriptPubKey == scriptPubKey)339                        account.vchPubKey.clear();340            }341        }342343        // Generate a new key344        if (account.vchPubKey.empty())345        {346            account.vchPubKey = GetKeyFromKeyPool();347            string strAddress = PubKeyToAddress(account.vchPubKey);348            SetAddressBookName(strAddress, strAccount);349            walletdb.WriteAccount(strAccount, account);350        }351352        walletdb.TxnCommit();353        return PubKeyToAddress(account.vchPubKey);354    }355}356357358Value setaccount(const Array& params, bool fHelp)359{360    if (fHelp || params.size() < 1 || params.size() > 2)361        throw runtime_error(362            "setaccount <bitcoinaddress> <account>\n"363            "Sets the account associated with the given address.");364365    string strAddress = params[0].get_str();366    string strAccount;367    if (params.size() > 1)368        strAccount = params[1].get_str();369370    SetAddressBookName(strAddress, strAccount);371    return Value::null;372}373374375Value getaccount(const Array& params, bool fHelp)376{377    if (fHelp || params.size() != 1)378        throw runtime_error(379            "getaccount <bitcoinaddress>\n"380            "Returns the account associated with the given address.");381382    string strAddress = params[0].get_str();383384    string strAccount;385    CRITICAL_BLOCK(cs_mapAddressBook)386    {387        map<string, string>::iterator mi = mapAddressBook.find(strAddress);388        if (mi != mapAddressBook.end() && !(*mi).second.empty())389            strAccount = (*mi).second;390    }391    return strAccount;392}393394395Value getaddressesbyaccount(const Array& params, bool fHelp)396{397    if (fHelp || params.size() != 1)398        throw runtime_error(399            "getaddressesbyaccount <account>\n"400            "Returns the list of addresses for the given account.");401402    string strAccount = params[0].get_str();403404    // Find all addresses that have the given account405    Array ret;406    CRITICAL_BLOCK(cs_mapAddressBook)407    {408        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)409        {410            const string& strAddress = item.first;411            const string& strName = item.second;412            if (strName == strAccount)413            {414                // We're only adding valid bitcoin addresses and not ip addresses415                CScript scriptPubKey;416                if (scriptPubKey.SetBitcoinAddress(strAddress))417                    ret.push_back(strAddress);418            }419        }420    }421    return ret;422}423424Value sendtoaddress(const Array& params, bool fHelp)425{426    if (fHelp || params.size() < 2 || params.size() > 4)427        throw runtime_error(428            "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"429            "<amount> is a real and is rounded to the nearest 0.01");430431    string strAddress = params[0].get_str();432433    // Amount434    int64 nAmount = AmountFromValue(params[1]);435436    // Wallet comments437    CWalletTx wtx;438    if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())439        wtx.mapValue["message"] = params[2].get_str();440    if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())441        wtx.mapValue["to"]      = params[3].get_str();442443    string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);444    if (strError != "")445        throw JSONRPCError(-4, strError);446    return wtx.GetHash().GetHex();447}448449450Value getreceivedbyaddress(const Array& params, bool fHelp)451{452    if (fHelp || params.size() < 1 || params.size() > 2)453        throw runtime_error(454            "getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"455            "Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");456457    // Bitcoin address458    string strAddress = params[0].get_str();459    CScript scriptPubKey;460    if (!scriptPubKey.SetBitcoinAddress(strAddress))461        throw JSONRPCError(-5, "Invalid bitcoin address");462    if (!IsMine(scriptPubKey))463        return (double)0.0;464465    // Minimum confirmations466    int nMinDepth = 1;467    if (params.size() > 1)468        nMinDepth = params[1].get_int();469470    // Tally471    int64 nAmount = 0;472    CRITICAL_BLOCK(cs_mapWallet)473    {474        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)475        {476            const CWalletTx& wtx = (*it).second;477            if (wtx.IsCoinBase() || !wtx.IsFinal())478                continue;479480            foreach(const CTxOut& txout, wtx.vout)481                if (txout.scriptPubKey == scriptPubKey)482                    if (wtx.GetDepthInMainChain() >= nMinDepth)483                        nAmount += txout.nValue;484        }485    }486487    return (double)nAmount / (double)COIN;488}489490491void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)492{493    CRITICAL_BLOCK(cs_mapAddressBook)494    {495        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)496        {497            const string& strAddress = item.first;498            const string& strName = item.second;499            if (strName == strAccount)500            {501                // We're only counting our own valid bitcoin addresses and not ip addresses502                CScript scriptPubKey;503                if (scriptPubKey.SetBitcoinAddress(strAddress))504                    if (IsMine(scriptPubKey))505                        setPubKey.insert(scriptPubKey);506            }507        }508    }509}510511512Value getreceivedbyaccount(const Array& params, bool fHelp)513{514    if (fHelp || params.size() < 1 || params.size() > 2)515        throw runtime_error(516            "getreceivedbyaccount <account> [minconf=1]\n"517            "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");518519    // Minimum confirmations520    int nMinDepth = 1;521    if (params.size() > 1)522        nMinDepth = params[1].get_int();523524    // Get the set of pub keys that have the label525    string strAccount = params[0].get_str();526    set<CScript> setPubKey;527    GetAccountPubKeys(strAccount, setPubKey);528529    // Tally530    int64 nAmount = 0;531    CRITICAL_BLOCK(cs_mapWallet)532    {533        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)534        {535            const CWalletTx& wtx = (*it).second;536            if (wtx.IsCoinBase() || !wtx.IsFinal())537                continue;538539            foreach(const CTxOut& txout, wtx.vout)540                if (setPubKey.count(txout.scriptPubKey))541                    if (wtx.GetDepthInMainChain() >= nMinDepth)542                        nAmount += txout.nValue;543        }544    }545546    return (double)nAmount / (double)COIN;547}548549550int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)551{552    set<CScript> setPubKey;553    GetAccountPubKeys(strAccount, setPubKey);554555    int64 nBalance = 0;556    CRITICAL_BLOCK(cs_mapWallet)557    {558        // Tally wallet transactions559        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)560        {561            const CWalletTx& wtx = (*it).second;562            if (!wtx.IsFinal())563                continue;564565            int64 nGenerated, nReceived, nSent, nFee;566            wtx.GetAccountAmounts(strAccount, setPubKey, nGenerated, nReceived, nSent, nFee);567568            if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)569                nBalance += nReceived;570            nBalance += nGenerated - nSent - nFee;571        }572573        // Tally internal accounting entries574        nBalance += walletdb.GetAccountCreditDebit(strAccount);575    }576577    return nBalance;578}579580int64 GetAccountBalance(const string& strAccount, int nMinDepth)581{582    CWalletDB walletdb;583    return GetAccountBalance(walletdb, strAccount, nMinDepth);584}585586587Value getbalance(const Array& params, bool fHelp)588{589    if (fHelp || params.size() < 0 || params.size() > 2)590        throw runtime_error(591            "getbalance [account] [minconf=1]\n"592            "If [account] is not specified, returns the server's total available balance.\n"593            "If [account] is specified, returns the balance in the account.");594595    if (params.size() == 0)596        return ((double)GetBalance() / (double)COIN);597598    string strAccount = params[0].get_str();599    int nMinDepth = 1;600    if (params.size() > 1)601        nMinDepth = params[1].get_int();602603    int64 nBalance = GetAccountBalance(strAccount, nMinDepth);604605    return (double)nBalance / (double)COIN;606}607608609Value movecmd(const Array& params, bool fHelp)610{611    if (fHelp || params.size() < 3 || params.size() > 5)612        throw runtime_error(613            "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"614            "Move from one account in your wallet to another.");615616    string strFrom = params[0].get_str();617    string strTo = params[1].get_str();618    int64 nAmount = AmountFromValue(params[2]);619    int nMinDepth = 1;620    if (params.size() > 3)621        nMinDepth = params[3].get_int();622    string strComment;623    if (params.size() > 4)624        strComment = params[4].get_str();625626    CRITICAL_BLOCK(cs_mapWallet)627    {628        CWalletDB walletdb;629        walletdb.TxnBegin();630631        // Check funds632        if (!strFrom.empty())633        {634            int64 nBalance = GetAccountBalance(walletdb, strFrom, nMinDepth);635            if (nAmount > nBalance)636                throw JSONRPCError(-6, "Account has insufficient funds");637        }638        else639        {640            // move from "" account special case641            int64 nBalance = GetAccountBalance(walletdb, strTo, nMinDepth);642            if (nAmount > GetBalance() - nBalance)643                throw JSONRPCError(-6, "Account has insufficient funds");644        }645646        int64 nNow = GetAdjustedTime();647648        // Debit649        CAccountingEntry debit;650        debit.nCreditDebit = -nAmount;651        debit.nTime = nNow;652        debit.strOtherAccount = strTo;653        debit.strComment = strComment;654        walletdb.WriteAccountingEntry(strFrom, debit);655656        // Credit657        CAccountingEntry credit;658        credit.nCreditDebit = nAmount;659        credit.nTime = nNow;660        credit.strOtherAccount = strFrom;661        credit.strComment = strComment;662        walletdb.WriteAccountingEntry(strTo, credit);663664        walletdb.TxnCommit();665    }666    return true;667}668669670Value sendfrom(const Array& params, bool fHelp)671{672    if (fHelp || params.size() < 3 || params.size() > 6)673        throw runtime_error(674            "sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"675            "<amount> is a real and is rounded to the nearest 0.01");676677    string strAccount = params[0].get_str();678    string strAddress = params[1].get_str();679    int64 nAmount = AmountFromValue(params[2]);680    int nMinDepth = 1;681    if (params.size() > 3)682        nMinDepth = params[3].get_int();683684    CWalletTx wtx;685    wtx.strFromAccount = strAccount;686    if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())687        wtx.mapValue["message"] = params[4].get_str();688    if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())689        wtx.mapValue["to"]      = params[5].get_str();690691    CRITICAL_BLOCK(cs_mapWallet)692    {693        // Check funds694        int64 nBalance = GetAccountBalance(strAccount, nMinDepth);695        if (nAmount > nBalance)696            throw JSONRPCError(-6, "Account has insufficient funds");697698        // Send699        string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);700        if (strError != "")701            throw JSONRPCError(-4, strError);702    }703704    return wtx.GetHash().GetHex();705}706707708709struct tallyitem710{711    int64 nAmount;712    int nConf;713    tallyitem()714    {715        nAmount = 0;716        nConf = INT_MAX;717    }718};719720Value ListReceived(const Array& params, bool fByAccounts)721{722    // Minimum confirmations723    int nMinDepth = 1;724    if (params.size() > 0)725        nMinDepth = params[0].get_int();726727    // Whether to include empty accounts728    bool fIncludeEmpty = false;729    if (params.size() > 1)730        fIncludeEmpty = params[1].get_bool();731732    // Tally733    map<uint160, tallyitem> mapTally;734    CRITICAL_BLOCK(cs_mapWallet)735    {736        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)737        {738            const CWalletTx& wtx = (*it).second;739            if (wtx.IsCoinBase() || !wtx.IsFinal())740                continue;741742            int nDepth = wtx.GetDepthInMainChain();743            if (nDepth < nMinDepth)744                continue;745746            foreach(const CTxOut& txout, wtx.vout)747            {748                // Only counting our own bitcoin addresses and not ip addresses749                uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();750                if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine751                    continue;752753                tallyitem& item = mapTally[hash160];754                item.nAmount += txout.nValue;755                item.nConf = min(item.nConf, nDepth);756            }757        }758    }759760    // Reply761    Array ret;762    map<string, tallyitem> mapAccountTally;763    CRITICAL_BLOCK(cs_mapAddressBook)764    {765        foreach(const PAIRTYPE(string, string)& item, mapAddressBook)766        {767            const string& strAddress = item.first;768            const string& strAccount = item.second;769            uint160 hash160;770            if (!AddressToHash160(strAddress, hash160))771                continue;772            map<uint160, tallyitem>::iterator it = mapTally.find(hash160);773            if (it == mapTally.end() && !fIncludeEmpty)774                continue;775776            int64 nAmount = 0;777            int nConf = INT_MAX;778            if (it != mapTally.end())779            {780                nAmount = (*it).second.nAmount;781                nConf = (*it).second.nConf;782            }783784            if (fByAccounts)785            {786                tallyitem& item = mapAccountTally[strAccount];787                item.nAmount += nAmount;788                item.nConf = min(item.nConf, nConf);789            }790            else791            {792                Object obj;793                obj.push_back(Pair("address",       strAddress));794                obj.push_back(Pair("account",       strAccount));795                obj.push_back(Pair("label",         strAccount)); // deprecated796                obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));797                obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));798                ret.push_back(obj);799            }800        }801    }802803    if (fByAccounts)804    {805        for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)806        {807            int64 nAmount = (*it).second.nAmount;808            int nConf = (*it).second.nConf;809            Object obj;810            obj.push_back(Pair("account",       (*it).first));811            obj.push_back(Pair("label",         (*it).first)); // deprecated812            obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));813            obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));814            ret.push_back(obj);815        }816    }817818    return ret;819}820821Value listreceivedbyaddress(const Array& params, bool fHelp)822{823    if (fHelp || params.size() > 2)824        throw runtime_error(825            "listreceivedbyaddress [minconf=1] [includeempty=false]\n"826            "[minconf] is the minimum number of confirmations before payments are included.\n"827            "[includeempty] whether to include addresses that haven't received any payments.\n"828            "Returns an array of objects containing:\n"829            "  \"address\" : receiving address\n"830            "  \"account\" : the account of the receiving address\n"831            "  \"amount\" : total amount received by the address\n"832            "  \"confirmations\" : number of confirmations of the most recent transaction included");833834    return ListReceived(params, false);835}836837Value listreceivedbyaccount(const Array& params, bool fHelp)838{839    if (fHelp || params.size() > 2)840        throw runtime_error(841            "listreceivedbyaccount [minconf=1] [includeempty=false]\n"842            "[minconf] is the minimum number of confirmations before payments are included.\n"843            "[includeempty] whether to include accounts that haven't received any payments.\n"844            "Returns an array of objects containing:\n"845            "  \"account\" : the account of the receiving addresses\n"846            "  \"amount\" : total amount received by addresses with this account\n"847            "  \"confirmations\" : number of confirmations of the most recent transaction included");848849    return ListReceived(params, true);850}851852void ListAccountTransactions(CWalletDB& walletdb, const string& strAccount, int nMinDepth, multimap<int64, Object>& ret)853{854    set<CScript> setPubKey;855    GetAccountPubKeys(strAccount, setPubKey);856857    CRITICAL_BLOCK(cs_mapWallet)858    {859        // Wallet: generate/send/receive transactions860        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)861        {862            const CWalletTx& wtx = (*it).second;863            if (!wtx.IsFinal())864                continue;865866            int64 nGenerated, nReceived, nSent, nFee;867            wtx.GetAccountAmounts(strAccount, setPubKey, nGenerated, nReceived, nSent, nFee);868869            // Generated blocks count to account ""870            if (nGenerated != 0)871            {872                Object entry;873                entry.push_back(Pair("category", "generate"));874                entry.push_back(Pair("amount", ValueFromAmount(nGenerated)));875                WalletTxToJSON(wtx, entry);876                ret.insert(make_pair(wtx.GetTxTime(), entry));877            }878879            // Sent880            if (nSent != 0 || nFee != 0)881            {882                Object entry;883                entry.push_back(Pair("category", "send"));884                entry.push_back(Pair("amount", ValueFromAmount(-nSent)));885                entry.push_back(Pair("fee", ValueFromAmount(-nFee)));886                WalletTxToJSON(wtx, entry);887                ret.insert(make_pair(wtx.GetTxTime(), entry));888            }889890            // Received891            if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)892            {893                Object entry;894                entry.push_back(Pair("category", "receive"));895                entry.push_back(Pair("amount", ValueFromAmount(nReceived)));896                WalletTxToJSON(wtx, entry);897                ret.insert(make_pair(wtx.GetTxTime(), entry));898            }899        }900901        // Internal accounting entries902        list<CAccountingEntry> acentries;903        walletdb.ListAccountCreditDebit(strAccount, acentries);904        foreach (const CAccountingEntry& acentry, acentries)905        {906            Object entry;907            entry.push_back(Pair("category", "move"));908            entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));909            entry.push_back(Pair("otheraccount", acentry.strOtherAccount));910            ret.insert(make_pair(acentry.nTime, entry));911        }912    }913}914915Value listtransactions(const Array& params, bool fHelp)916{917    if (fHelp || params.size() < 1 || params.size() > 2)918        throw runtime_error(919            "listtransactions <account> [count=10]\n"920            "Returns up to [count] most recent transactions for account <account>.");921922    string strAccount = params[0].get_str();923    int nCount = 10;924    if (params.size() > 1)925        nCount = params[1].get_int();926927    CWalletDB walletdb;928    multimap<int64, Object> mapByTime;  // keys are transaction time929    ListAccountTransactions(walletdb, strAccount, 0, mapByTime);930931    // Return only last nCount items:932    int nToErase = mapByTime.size()-nCount;933    if (nToErase > 0)934    {935        multimap<int64, Object>::iterator end = mapByTime.begin();936        std::advance(end, nToErase);937        mapByTime.erase(mapByTime.begin(), end);938    }939940    Array ret;941    foreach(const PAIRTYPE(int64, Object)& item, mapByTime)942        ret.push_back(item.second);943    return ret;944}945946Value gettransaction(const Array& params, bool fHelp)947{948    if (fHelp || params.size() != 1)949        throw runtime_error(950            "gettransaction <txid>\n"951            "Get detailed information about <txid>");952953    uint256 hash;954    hash.SetHex(params[0].get_str());955956    Object entry;957    CRITICAL_BLOCK(cs_mapWallet)958    {959        if (!mapWallet.count(hash))960            throw JSONRPCError(-5, "Invalid transaction id");961        const CWalletTx& wtx = mapWallet[hash];962963        int64 nCredit = wtx.GetCredit();964        int64 nDebit = wtx.GetDebit();965        int64 nNet = nCredit - nDebit;966        int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);967968        entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));969        if (wtx.IsFromMe())970            entry.push_back(Pair("fee", ValueFromAmount(nFee)));971        WalletTxToJSON(mapWallet[hash], entry);972    }973974    return entry;975}976977978Value backupwallet(const Array& params, bool fHelp)979{980    if (fHelp || params.size() != 1)981        throw runtime_error(982            "backupwallet <destination>\n"983            "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");984985    string strDest = params[0].get_str();986    BackupWallet(strDest);987988    return Value::null;989}990991992Value validateaddress(const Array& params, bool fHelp)993{994    if (fHelp || params.size() != 1)995        throw runtime_error(996            "validateaddress <bitcoinaddress>\n"997            "Return information about <bitcoinaddress>.");998999    string strAddress = params[0].get_str();1000    uint160 hash160;1001    bool isValid = AddressToHash160(strAddress, hash160);10021003    Object ret;1004    ret.push_back(Pair("isvalid", isValid));1005    if (isValid)1006    {1007        // Call Hash160ToAddress() so we always return current ADDRESSVERSION1008        // version of the address:1009        string currentAddress = Hash160ToAddress(hash160);1010        ret.push_back(Pair("address", currentAddress));1011        ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));1012        CRITICAL_BLOCK(cs_mapAddressBook)1013        {1014            if (mapAddressBook.count(currentAddress))1015                ret.push_back(Pair("account", mapAddressBook[currentAddress]));1016        }1017    }1018    return ret;1019}102010211022Value getwork(const Array& params, bool fHelp)1023{1024    if (fHelp || params.size() > 1)1025        throw runtime_error(1026            "getwork [data]\n"1027            "If [data] is not specified, returns formatted hash data to work on:\n"1028            "  \"midstate\" : precomputed hash state after hashing the first half of the data\n"1029            "  \"data\" : block data\n"1030            "  \"hash1\" : formatted hash buffer for second hash\n"1031            "  \"target\" : little endian hash target\n"1032            "If [data] is specified, tries to solve the block and returns true if it was successful.");10331034    if (vNodes.empty())1035        throw JSONRPCError(-9, "Bitcoin is not connected!");10361037    if (IsInitialBlockDownload())1038        throw JSONRPCError(-10, "Bitcoin is downloading blocks...");10391040    static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;1041    static vector<CBlock*> vNewBlock;1042    static CReserveKey reservekey;10431044    if (params.size() == 0)1045    {1046        // Update block1047        static unsigned int nTransactionsUpdatedLast;1048        static CBlockIndex* pindexPrev;1049        static int64 nStart;1050        static CBlock* pblock;1051        if (pindexPrev != pindexBest ||1052            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))1053        {1054            if (pindexPrev != pindexBest)1055            {1056                // Deallocate old blocks since they're obsolete now1057                mapNewBlock.clear();1058                foreach(CBlock* pblock, vNewBlock)1059                    delete pblock;1060                vNewBlock.clear();1061            }1062            nTransactionsUpdatedLast = nTransactionsUpdated;1063            pindexPrev = pindexBest;1064            nStart = GetTime();10651066            // Create new block1067            pblock = CreateNewBlock(reservekey);1068            if (!pblock)1069                throw JSONRPCError(-7, "Out of memory");1070            vNewBlock.push_back(pblock);1071        }10721073        // Update nTime1074        pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());1075        pblock->nNonce = 0;10761077        // Update nExtraNonce1078        static unsigned int nExtraNonce = 0;1079        static int64 nPrevTime = 0;1080        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);10811082        // Save1083        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);10841085        // Prebuild hash buffers1086        char pmidstate[32];1087        char pdata[128];1088        char phash1[64];1089        FormatHashBuffers(pblock, pmidstate, pdata, phash1);10901091        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();10921093        Object result;1094        result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));1095        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));1096        result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1))));1097        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));1098        return result;1099    }1100    else1101    {1102        // Parse parameters1103        vector<unsigned char> vchData = ParseHex(params[0].get_str());1104        if (vchData.size() != 128)1105            throw JSONRPCError(-8, "Invalid parameter");1106        CBlock* pdata = (CBlock*)&vchData[0];11071108        // Byte reverse1109        for (int i = 0; i < 128/4; i++)1110            ((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);11111112        // Get saved block1113        if (!mapNewBlock.count(pdata->hashMerkleRoot))1114            return false;1115        CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;1116        unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;11171118        pblock->nTime = pdata->nTime;1119        pblock->nNonce = pdata->nNonce;1120        pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);1121        pblock->hashMerkleRoot = pblock->BuildMerkleTree();11221123        return CheckWork(pblock, reservekey);1124    }1125}112611271128112911301131113211331134113511361137//1138// Call Table1139//11401141pair<string, rpcfn_type> pCallTable[] =1142{1143    make_pair("help",                  &help),1144    make_pair("stop",                  &stop),1145    make_pair("getblockcount",         &getblockcount),1146    make_pair("getblocknumber",        &getblocknumber),1147    make_pair("getconnectioncount",    &getconnectioncount),1148    make_pair("getdifficulty",         &getdifficulty),1149    make_pair("getgenerate",           &getgenerate),1150    make_pair("setgenerate",           &setgenerate),1151    make_pair("gethashespersec",       &gethashespersec),1152    make_pair("getinfo",               &getinfo),1153    make_pair("getnewaddress",         &getnewaddress),1154    make_pair("getaccountaddress",     &getaccountaddress),1155    make_pair("setaccount",            &setaccount),1156    make_pair("setlabel",              &setaccount), // deprecated1157    make_pair("getaccount",            &getaccount),1158    make_pair("getlabel",              &getaccount), // deprecated1159    make_pair("getaddressesbyaccount", &getaddressesbyaccount),1160    make_pair("getaddressesbylabel",   &getaddressesbyaccount), // deprecated1161    make_pair("sendtoaddress",         &sendtoaddress),1162    make_pair("getamountreceived",     &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress1163    make_pair("getallreceived",        &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress1164    make_pair("getreceivedbyaddress",  &getreceivedbyaddress),1165    make_pair("getreceivedbyaccount",  &getreceivedbyaccount),1166    make_pair("getreceivedbylabel",    &getreceivedbyaccount), // deprecated1167    make_pair("listreceivedbyaddress", &listreceivedbyaddress),1168    make_pair("listreceivedbyaccount", &listreceivedbyaccount),1169    make_pair("listreceivedbylabel",   &listreceivedbyaccount), // deprecated1170    make_pair("backupwallet",          &backupwallet),1171    make_pair("validateaddress",       &validateaddress),1172    make_pair("getbalance",            &getbalance),1173    make_pair("move",                  &movecmd),1174    make_pair("sendfrom",              &sendfrom),1175    make_pair("gettransaction",        &gettransaction),1176    make_pair("listtransactions",      &listtransactions),1177    make_pair("getwork",               &getwork),1178};1179map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));11801181string pAllowInSafeMode[] =1182{1183    "help",1184    "stop",1185    "getblockcount",1186    "getblocknumber",1187    "getconnectioncount",1188    "getdifficulty",1189    "getgenerate",1190    "setgenerate",1191    "gethashespersec",1192    "getinfo",1193    "getnewaddress",1194    "getaccountaddress",1195    "setlabel",1196    "getaccount",1197    "getlabel", // deprecated1198    "getaddressesbyaccount",1199    "getaddressesbylabel", // deprecated1200    "backupwallet",1201    "validateaddress",1202    "getwork",1203};1204set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));12051206120712081209//1210// HTTP protocol1211//1212// This ain't Apache.  We're just using HTTP header for the length field1213// and to be compatible with other JSON-RPC implementations.1214//12151216string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)1217{1218    ostringstream s;1219    s << "POST / HTTP/1.1\r\n"1220      << "User-Agent: json-rpc/1.0\r\n"1221      << "Host: 127.0.0.1\r\n"1222      << "Content-Type: application/json\r\n"1223      << "Content-Length: " << strMsg.size() << "\r\n"1224      << "Accept: application/json\r\n";1225    foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)1226        s << item.first << ": " << item.second << "\r\n";1227    s << "\r\n" << strMsg;12281229    return s.str();1230}12311232string rfc1123Time()1233{1234    char buffer[32];1235    time_t now;1236    time(&now);1237    struct tm* now_gmt = gmtime(&now);1238    strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);1239    return string(buffer);1240}12411242string HTTPReply(int nStatus, const string& strMsg)1243{1244    if (nStatus == 401)1245        return strprintf("HTTP/1.0 401 Authorization Required\r\n"1246            "Date: %s\r\n"1247            "Server: bitcoin-json-rpc\r\n"1248            "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"1249            "Content-Type: text/html\r\n"1250            "Content-Length: 311\r\n"1251            "\r\n"1252            "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"1253            "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"1254            "<HTML>\r\n"1255            "<HEAD>\r\n"1256            "<TITLE>Error</TITLE>\r\n"1257            "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"1258            "</HEAD>\r\n"1259            "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"1260            "</HTML>\r\n", rfc1123Time().c_str());1261    string strStatus;1262         if (nStatus == 200) strStatus = "OK";1263    else if (nStatus == 400) strStatus = "Bad Request";1264    else if (nStatus == 404) strStatus = "Not Found";1265    else if (nStatus == 500) strStatus = "Internal Server Error";1266    return strprintf(1267            "HTTP/1.1 %d %s\r\n"1268            "Date: %s\r\n"1269            "Connection: close\r\n"1270            "Content-Length: %d\r\n"1271            "Content-Type: application/json\r\n"1272            "Server: bitcoin-json-rpc/1.0\r\n"1273            "\r\n"1274            "%s",1275        nStatus,1276        strStatus.c_str(),1277        rfc1123Time().c_str(),1278        strMsg.size(),1279        strMsg.c_str());1280}12811282int ReadHTTPStatus(std::basic_istream<char>& stream)1283{1284    string str;1285    getline(stream, str);1286    vector<string> vWords;1287    boost::split(vWords, str, boost::is_any_of(" "));1288    if (vWords.size() < 2)1289        return 500;1290    return atoi(vWords[1].c_str());1291}12921293int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)1294{1295    int nLen = 0;1296    loop1297    {1298        string str;1299        std::getline(stream, str);1300        if (str.empty() || str == "\r")1301            break;1302        string::size_type nColon = str.find(":");1303        if (nColon != string::npos)1304        {1305            string strHeader = str.substr(0, nColon);1306            boost::trim(strHeader);1307            string strValue = str.substr(nColon+1);1308            boost::trim(strValue);1309            mapHeadersRet[strHeader] = strValue;1310            if (strHeader == "Content-Length")1311                nLen = atoi(strValue.c_str());1312        }1313    }1314    return nLen;1315}13161317int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)1318{1319    mapHeadersRet.clear();1320    strMessageRet = "";13211322    // Read status1323    int nStatus = ReadHTTPStatus(stream);13241325    // Read header1326    int nLen = ReadHTTPHeader(stream, mapHeadersRet);1327    if (nLen < 0 || nLen > MAX_SIZE)1328        return 500;13291330    // Read message1331    if (nLen > 0)1332    {1333        vector<char> vch(nLen);1334        stream.read(&vch[0], nLen);1335        strMessageRet = string(vch.begin(), vch.end());1336    }13371338    return nStatus;1339}13401341string EncodeBase64(string s)1342{1343    BIO *b64, *bmem;1344    BUF_MEM *bptr;13451346    b64 = BIO_new(BIO_f_base64());1347    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);1348    bmem = BIO_new(BIO_s_mem());1349    b64 = BIO_push(b64, bmem);1350    BIO_write(b64, s.c_str(), s.size());1351    BIO_flush(b64);1352    BIO_get_mem_ptr(b64, &bptr);13531354    string result(bptr->data, bptr->length);1355    BIO_free_all(b64);13561357    return result;1358}13591360string DecodeBase64(string s)1361{1362    BIO *b64, *bmem;13631364    char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));13651366    b64 = BIO_new(BIO_f_base64());1367    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);1368    bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());1369    bmem = BIO_push(b64, bmem);1370    BIO_read(bmem, buffer, s.size());1371    BIO_free_all(bmem);13721373    string result(buffer);1374    free(buffer);1375    return result;1376}13771378bool HTTPAuthorized(map<string, string>& mapHeaders)1379{1380    string strAuth = mapHeaders["Authorization"];1381    if (strAuth.substr(0,6) != "Basic ")1382        return false;1383    string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);1384    string strUserPass = DecodeBase64(strUserPass64);1385    string::size_type nColon = strUserPass.find(":");1386    if (nColon == string::npos)1387        return false;1388    string strUser = strUserPass.substr(0, nColon);1389    string strPassword = strUserPass.substr(nColon+1);1390    return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);1391}13921393//1394// JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,1395// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were1396// unspecified (HTTP errors and contents of 'error').1397//1398// 1.0 spec: http://json-rpc.org/wiki/specification1399// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http1400// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx1401//14021403string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)1404{1405    Object request;1406    request.push_back(Pair("method", strMethod));1407    request.push_back(Pair("params", params));1408    request.push_back(Pair("id", id));1409    return write_string(Value(request), false) + "\n";1410}14111412string JSONRPCReply(const Value& result, const Value& error, const Value& id)1413{1414    Object reply;1415    if (error.type() != null_type)1416        reply.push_back(Pair("result", Value::null));1417    else1418        reply.push_back(Pair("result", result));1419    reply.push_back(Pair("error", error));1420    reply.push_back(Pair("id", id));1421    return write_string(Value(reply), false) + "\n";1422}14231424bool ClientAllowed(const string& strAddress)1425{1426    if (strAddress == asio::ip::address_v4::loopback().to_string())1427        return true;1428    const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];1429    foreach(string strAllow, vAllow)1430        if (WildcardMatch(strAddress, strAllow))1431            return true;1432    return false;1433}14341435#ifdef USE_SSL1436//1437// IOStream device that speaks SSL but can also speak non-SSL1438//1439class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {1440public:1441    SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)1442    {1443        fUseSSL = fUseSSLIn;1444        fNeedHandshake = fUseSSLIn;1445    }14461447    void handshake(ssl::stream_base::handshake_type role)1448    {1449        if (!fNeedHandshake) return;1450        fNeedHandshake = false;1451        stream.handshake(role);1452    }1453    std::streamsize read(char* s, std::streamsize n)1454    {1455        handshake(ssl::stream_base::server); // HTTPS servers read first1456        if (fUseSSL) return stream.read_some(asio::buffer(s, n));1457        return stream.next_layer().read_some(asio::buffer(s, n));1458    }1459    std::streamsize write(const char* s, std::streamsize n)1460    {1461        handshake(ssl::stream_base::client); // HTTPS clients write first1462        if (fUseSSL) return asio::write(stream, asio::buffer(s, n));1463        return asio::write(stream.next_layer(), asio::buffer(s, n));1464    }1465    bool connect(const std::string& server, const std::string& port)1466    {1467        ip::tcp::resolver resolver(stream.get_io_service());1468        ip::tcp::resolver::query query(server.c_str(), port.c_str());1469        ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);1470        ip::tcp::resolver::iterator end;1471        boost::system::error_code error = asio::error::host_not_found;1472        while (error && endpoint_iterator != end)1473        {1474            stream.lowest_layer().close();1475            stream.lowest_layer().connect(*endpoint_iterator++, error);1476        }1477        if (error)1478            return false;1479        return true;1480    }14811482private:1483    bool fNeedHandshake;1484    bool fUseSSL;1485    SSLStream& stream;1486};1487#endif14881489void ThreadRPCServer(void* parg)1490{1491    IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));1492    try1493    {1494        vnThreadsRunning[4]++;1495        ThreadRPCServer2(parg);1496        vnThreadsRunning[4]--;1497    }1498    catch (std::exception& e) {1499        vnThreadsRunning[4]--;1500        PrintException(&e, "ThreadRPCServer()");1501    } catch (...) {1502        vnThreadsRunning[4]--;1503        PrintException(NULL, "ThreadRPCServer()");1504    }1505    printf("ThreadRPCServer exiting\n");1506}15071508void ThreadRPCServer2(void* parg)1509{1510    printf("ThreadRPCServer started\n");15111512    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")1513    {1514        string strWhatAmI = "To use bitcoind";1515        if (mapArgs.count("-server"))1516            strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");1517        else if (mapArgs.count("-daemon"))1518            strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");1519        PrintConsole(1520            _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"1521              "If the file does not exist, create it with owner-readable-only file permissions.\n"),1522                strWhatAmI.c_str(),1523                GetConfigFile().c_str());1524        CreateThread(Shutdown, NULL);1525        return;1526    }15271528    bool fUseSSL = GetBoolArg("-rpcssl");1529    asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();15301531    asio::io_service io_service;1532    ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));1533    ip::tcp::acceptor acceptor(io_service, endpoint);15341535#ifdef USE_SSL1536    ssl::context context(io_service, ssl::context::sslv23);1537    if (fUseSSL)1538    {1539        context.set_options(ssl::context::no_sslv2);1540        filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");1541        if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;1542        if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());1543        else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());1544        filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");1545        if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;1546        if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);1547        else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());15481549        string ciphers = GetArg("-rpcsslciphers",1550                                         "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");1551        SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());1552    }1553#else1554    if (fUseSSL)1555        throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");1556#endif15571558    loop1559    {1560        // Accept connection1561#ifdef USE_SSL1562        SSLStream sslStream(io_service, context);1563        SSLIOStreamDevice d(sslStream, fUseSSL);1564        iostreams::stream<SSLIOStreamDevice> stream(d);1565#else1566        ip::tcp::iostream stream;1567#endif15681569        ip::tcp::endpoint peer;1570        vnThreadsRunning[4]--;1571#ifdef USE_SSL1572        acceptor.accept(sslStream.lowest_layer(), peer);1573#else1574        acceptor.accept(*stream.rdbuf(), peer);1575#endif1576        vnThreadsRunning[4]++;1577        if (fShutdown)1578            return;15791580        // Restrict callers by IP1581        if (!ClientAllowed(peer.address().to_string()))1582            continue;15831584        // Receive request1585        map<string, string> mapHeaders;1586        string strRequest;1587        ReadHTTP(stream, mapHeaders, strRequest);15881589        // Check authorization1590        if (mapHeaders.count("Authorization") == 0)1591        {1592            stream << HTTPReply(401, "") << std::flush;1593            continue;1594        }1595        if (!HTTPAuthorized(mapHeaders))1596        {1597            // Deter brute-forcing short passwords1598            if (mapArgs["-rpcpassword"].size() < 15)1599                Sleep(50);16001601            stream << HTTPReply(401, "") << std::flush;1602            printf("ThreadRPCServer incorrect password attempt\n");1603            continue;1604        }16051606        Value id = Value::null;1607        try1608        {1609            // Parse request1610            Value valRequest;1611            if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)1612                throw JSONRPCError(-32700, "Parse error");1613            const Object& request = valRequest.get_obj();16141615            // Parse id now so errors from here on will have the id1616            id = find_value(request, "id");16171618            // Parse method1619            Value valMethod = find_value(request, "method");1620            if (valMethod.type() == null_type)1621                throw JSONRPCError(-32600, "Missing method");1622            if (valMethod.type() != str_type)1623                throw JSONRPCError(-32600, "Method must be a string");1624            string strMethod = valMethod.get_str();1625            if (strMethod != "getwork")1626                printf("ThreadRPCServer method=%s\n", strMethod.c_str());16271628            // Parse params1629            Value valParams = find_value(request, "params");1630            Array params;1631            if (valParams.type() == array_type)1632                params = valParams.get_array();1633            else if (valParams.type() == null_type)1634                params = Array();1635            else1636                throw JSONRPCError(-32600, "Params must be an array");16371638            // Find method1639            map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);1640            if (mi == mapCallTable.end())1641                throw JSONRPCError(-32601, "Method not found");16421643            // Observe safe mode1644            string strWarning = GetWarnings("rpc");1645            if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))1646                throw JSONRPCError(-2, string("Safe mode: ") + strWarning);16471648            try1649            {1650                // Execute1651                Value result = (*(*mi).second)(params, false);16521653                // Send reply1654                string strReply = JSONRPCReply(result, Value::null, id);1655                stream << HTTPReply(200, strReply) << std::flush;1656            }1657            catch (std::exception& e)1658            {1659                // Send error reply from method1660                string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);1661                stream << HTTPReply(500, strReply) << std::flush;1662            }1663        }1664        catch (Object& objError)1665        {1666            // Send error reply from json-rpc error object1667            int nStatus = 500;1668            int code = find_value(objError, "code").get_int();1669            if (code == -32600) nStatus = 400;1670            else if (code == -32601) nStatus = 404;1671            string strReply = JSONRPCReply(Value::null, objError, id);1672            stream << HTTPReply(nStatus, strReply) << std::flush;1673        }1674        catch (std::exception& e)1675        {1676            // Send error reply from other json-rpc parsing errors1677            string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);1678            stream << HTTPReply(500, strReply) << std::flush;1679        }1680    }1681}16821683168416851686Object CallRPC(const string& strMethod, const Array& params)1687{1688    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")1689        throw runtime_error(strprintf(1690            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"1691              "If the file does not exist, create it with owner-readable-only file permissions."),1692                GetConfigFile().c_str()));16931694    // Connect to localhost1695    bool fUseSSL = GetBoolArg("-rpcssl");1696#ifdef USE_SSL1697    asio::io_service io_service;1698    ssl::context context(io_service, ssl::context::sslv23);1699    context.set_options(ssl::context::no_sslv2);1700    SSLStream sslStream(io_service, context);1701    SSLIOStreamDevice d(sslStream, fUseSSL);1702    iostreams::stream<SSLIOStreamDevice> stream(d);1703    if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))1704        throw runtime_error("couldn't connect to server");1705#else1706    if (fUseSSL)1707        throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");17081709    ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));1710    if (stream.fail())1711        throw runtime_error("couldn't connect to server");1712#endif171317141715    // HTTP basic authentication1716    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);1717    map<string, string> mapRequestHeaders;1718    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;17191720    // Send request1721    string strRequest = JSONRPCRequest(strMethod, params, 1);1722    string strPost = HTTPPost(strRequest, mapRequestHeaders);1723    stream << strPost << std::flush;17241725    // Receive reply1726    map<string, string> mapHeaders;1727    string strReply;1728    int nStatus = ReadHTTP(stream, mapHeaders, strReply);1729    if (nStatus == 401)1730        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");1731    else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)1732        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));1733    else if (strReply.empty())1734        throw runtime_error("no response from server");17351736    // Parse reply1737    Value valReply;1738    if (!read_string(strReply, valReply))1739        throw runtime_error("couldn't parse reply from server");1740    const Object& reply = valReply.get_obj();1741    if (reply.empty())1742        throw runtime_error("expected reply to have result, error and id properties");17431744    return reply;1745}17461747174817491750template<typename T>1751void ConvertTo(Value& value)1752{1753    if (value.type() == str_type)1754    {1755        // reinterpret string as unquoted json value1756        Value value2;1757        if (!read_string(value.get_str(), value2))1758            throw runtime_error("type mismatch");1759        value = value2.get_value<T>();1760    }1761    else1762    {1763        value = value.get_value<T>();1764    }1765}17661767int CommandLineRPC(int argc, char *argv[])1768{1769    string strPrint;1770    int nRet = 0;1771    try1772    {1773        // Skip switches1774        while (argc > 1 && IsSwitchChar(argv[1][0]))1775        {1776            argc--;1777            argv++;1778        }17791780        // Method1781        if (argc < 2)1782            throw runtime_error("too few parameters");1783        string strMethod = argv[1];17841785        // Parameters default to strings1786        Array params;1787        for (int i = 2; i < argc; i++)1788            params.push_back(argv[i]);1789        int n = params.size();17901791        //1792        // Special case non-string parameter types1793        //1794        if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);1795        if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);1796        if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);1797        if (strMethod == "getamountreceived"      && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated1798        if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);1799        if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);1800        if (strMethod == "getreceivedbylabel"     && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated1801        if (strMethod == "getallreceived"         && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated1802        if (strMethod == "getallreceived"         && n > 1) ConvertTo<bool>(params[1]);1803        if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);1804        if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);1805        if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);1806        if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);1807        if (strMethod == "listreceivedbylabel"    && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated1808        if (strMethod == "listreceivedbylabel"    && n > 1) ConvertTo<bool>(params[1]); // deprecated1809        if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);1810        if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);1811        if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);1812        if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);1813        if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);1814        if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);18151816        // Execute1817        Object reply = CallRPC(strMethod, params);18181819        // Parse reply1820        const Value& result = find_value(reply, "result");1821        const Value& error  = find_value(reply, "error");1822        const Value& id     = find_value(reply, "id");18231824        if (error.type() != null_type)1825        {1826            // Error1827            strPrint = "error: " + write_string(error, false);1828            int code = find_value(error.get_obj(), "code").get_int();1829            nRet = abs(code);1830        }1831        else1832        {1833            // Result1834            if (result.type() == null_type)1835                strPrint = "";1836            else if (result.type() == str_type)1837                strPrint = result.get_str();1838            else1839                strPrint = write_string(result, true);1840        }1841    }1842    catch (std::exception& e)1843    {1844        strPrint = string("error: ") + e.what();1845        nRet = 87;1846    }1847    catch (...)1848    {1849        PrintException(NULL, "CommandLineRPC()");1850    }18511852    if (strPrint != "")1853    {1854#if defined(__WXMSW__) && defined(GUI)1855        // Windows GUI apps can't print to command line,1856        // so settle for a message box yuck1857        MyMessageBox(strPrint, "Bitcoin", wxOK);1858#else1859        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());1860#endif1861    }1862    return nRet;1863}18641865186618671868#ifdef TEST1869int main(int argc, char *argv[])1870{1871#ifdef _MSC_VER1872    // Turn off microsoft heap dump noise1873    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);1874    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));1875#endif1876    setbuf(stdin, NULL);1877    setbuf(stdout, NULL);1878    setbuf(stderr, NULL);18791880    try1881    {1882        if (argc >= 2 && string(argv[1]) == "-server")1883        {1884            printf("server ready\n");1885            ThreadRPCServer(NULL);1886        }1887        else1888        {1889            return CommandLineRPC(argc, argv);1890        }1891    }1892    catch (std::exception& e) {1893        PrintException(&e, "main()");1894    } catch (...) {1895        PrintException(NULL, "main()");1896    }1897    return 0;1898}1899#endif

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00