LCOV - code coverage report
Current view: top level - src - rpcrawtransaction.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 326 354 92.1 %
Date: 2015-10-12 22:39:14 Functions: 13 13 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : // Copyright (c) 2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2015 The Bitcoin Core developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #include "base58.h"
       7             : #include "chain.h"
       8             : #include "coins.h"
       9             : #include "consensus/validation.h"
      10             : #include "core_io.h"
      11             : #include "init.h"
      12             : #include "keystore.h"
      13             : #include "main.h"
      14             : #include "merkleblock.h"
      15             : #include "net.h"
      16             : #include "policy/policy.h"
      17             : #include "primitives/transaction.h"
      18             : #include "rpcserver.h"
      19             : #include "script/script.h"
      20             : #include "script/script_error.h"
      21             : #include "script/sign.h"
      22             : #include "script/standard.h"
      23             : #include "txmempool.h"
      24             : #include "uint256.h"
      25             : #include "utilstrencodings.h"
      26             : #ifdef ENABLE_WALLET
      27             : #include "wallet/wallet.h"
      28             : #endif
      29             : 
      30             : #include <stdint.h>
      31             : 
      32             : #include <boost/assign/list_of.hpp>
      33             : 
      34             : #include <univalue.h>
      35             : 
      36             : using namespace std;
      37             : 
      38         112 : void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
      39             : {
      40             :     txnouttype type;
      41             :     vector<CTxDestination> addresses;
      42             :     int nRequired;
      43             : 
      44         336 :     out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
      45         112 :     if (fIncludeHex)
      46         510 :         out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
      47             : 
      48         112 :     if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
      49          18 :         out.push_back(Pair("type", GetTxnOutputType(type)));
      50         121 :         return;
      51             :     }
      52             : 
      53         206 :     out.push_back(Pair("reqSigs", nRequired));
      54         206 :     out.push_back(Pair("type", GetTxnOutputType(type)));
      55             : 
      56         412 :     UniValue a(UniValue::VARR);
      57        1143 :     BOOST_FOREACH(const CTxDestination& addr, addresses)
      58         315 :         a.push_back(CBitcoinAddress(addr).ToString());
      59         309 :     out.push_back(Pair("addresses", a));
      60             : }
      61             : 
      62          49 : void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
      63             : {
      64         147 :     entry.push_back(Pair("txid", tx.GetHash().GetHex()));
      65          98 :     entry.push_back(Pair("version", tx.nVersion));
      66          98 :     entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
      67         147 :     UniValue vin(UniValue::VARR);
      68         625 :     BOOST_FOREACH(const CTxIn& txin, tx.vin) {
      69         228 :         UniValue in(UniValue::VOBJ);
      70          76 :         if (tx.IsCoinBase())
      71          15 :             in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
      72             :         else {
      73         219 :             in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
      74         146 :             in.push_back(Pair("vout", (int64_t)txin.prevout.n));
      75         219 :             UniValue o(UniValue::VOBJ);
      76         219 :             o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
      77         365 :             o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
      78         146 :             in.push_back(Pair("scriptSig", o));
      79             :         }
      80         152 :         in.push_back(Pair("sequence", (int64_t)txin.nSequence));
      81          76 :         vin.push_back(in);
      82          76 :     }
      83          98 :     entry.push_back(Pair("vin", vin));
      84         196 :     UniValue vout(UniValue::VARR);
      85         266 :     for (unsigned int i = 0; i < tx.vout.size(); i++) {
      86         168 :         const CTxOut& txout = tx.vout[i];
      87         252 :         UniValue out(UniValue::VOBJ);
      88         168 :         out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
      89         168 :         out.push_back(Pair("n", (int64_t)i));
      90         336 :         UniValue o(UniValue::VOBJ);
      91          84 :         ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
      92         168 :         out.push_back(Pair("scriptPubKey", o));
      93          84 :         vout.push_back(out);
      94          84 :     }
      95          98 :     entry.push_back(Pair("vout", vout));
      96             : 
      97          49 :     if (!hashBlock.IsNull()) {
      98           6 :         entry.push_back(Pair("blockhash", hashBlock.GetHex()));
      99           2 :         BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
     100           4 :         if (mi != mapBlockIndex.end() && (*mi).second) {
     101           2 :             CBlockIndex* pindex = (*mi).second;
     102           2 :             if (chainActive.Contains(pindex)) {
     103           4 :                 entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
     104           6 :                 entry.push_back(Pair("time", pindex->GetBlockTime()));
     105           6 :                 entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
     106             :             }
     107             :             else
     108           0 :                 entry.push_back(Pair("confirmations", 0));
     109             :         }
     110          49 :     }
     111          49 : }
     112             : 
     113           5 : UniValue getrawtransaction(const UniValue& params, bool fHelp)
     114             : {
     115          14 :     if (fHelp || params.size() < 1 || params.size() > 2)
     116             :         throw runtime_error(
     117             :             "getrawtransaction \"txid\" ( verbose )\n"
     118             :             "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
     119             :             "or there is an unspent output in the utxo for this transaction. To make it always work,\n"
     120             :             "you need to maintain a transaction index, using the -txindex command line option.\n"
     121             :             "\nReturn the raw transaction data.\n"
     122             :             "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
     123             :             "If verbose is non-zero, returns an Object with information about 'txid'.\n"
     124             : 
     125             :             "\nArguments:\n"
     126             :             "1. \"txid\"      (string, required) The transaction id\n"
     127             :             "2. verbose       (numeric, optional, default=0) If 0, return a string, other return a json object\n"
     128             : 
     129             :             "\nResult (if verbose is not set or set to 0):\n"
     130             :             "\"data\"      (string) The serialized, hex-encoded data for 'txid'\n"
     131             : 
     132             :             "\nResult (if verbose > 0):\n"
     133             :             "{\n"
     134             :             "  \"hex\" : \"data\",       (string) The serialized, hex-encoded data for 'txid'\n"
     135             :             "  \"txid\" : \"id\",        (string) The transaction id (same as provided)\n"
     136             :             "  \"version\" : n,          (numeric) The version\n"
     137             :             "  \"locktime\" : ttt,       (numeric) The lock time\n"
     138             :             "  \"vin\" : [               (array of json objects)\n"
     139             :             "     {\n"
     140             :             "       \"txid\": \"id\",    (string) The transaction id\n"
     141             :             "       \"vout\": n,         (numeric) \n"
     142             :             "       \"scriptSig\": {     (json object) The script\n"
     143             :             "         \"asm\": \"asm\",  (string) asm\n"
     144             :             "         \"hex\": \"hex\"   (string) hex\n"
     145             :             "       },\n"
     146             :             "       \"sequence\": n      (numeric) The script sequence number\n"
     147             :             "     }\n"
     148             :             "     ,...\n"
     149             :             "  ],\n"
     150             :             "  \"vout\" : [              (array of json objects)\n"
     151             :             "     {\n"
     152           3 :             "       \"value\" : x.xxx,            (numeric) The value in " + CURRENCY_UNIT + "\n"
     153             :             "       \"n\" : n,                    (numeric) index\n"
     154             :             "       \"scriptPubKey\" : {          (json object)\n"
     155             :             "         \"asm\" : \"asm\",          (string) the asm\n"
     156             :             "         \"hex\" : \"hex\",          (string) the hex\n"
     157             :             "         \"reqSigs\" : n,            (numeric) The required sigs\n"
     158             :             "         \"type\" : \"pubkeyhash\",  (string) The type, eg 'pubkeyhash'\n"
     159             :             "         \"addresses\" : [           (json array of string)\n"
     160             :             "           \"bitcoinaddress\"        (string) bitcoin address\n"
     161             :             "           ,...\n"
     162             :             "         ]\n"
     163             :             "       }\n"
     164             :             "     }\n"
     165             :             "     ,...\n"
     166             :             "  ],\n"
     167             :             "  \"blockhash\" : \"hash\",   (string) the block hash\n"
     168             :             "  \"confirmations\" : n,      (numeric) The confirmations\n"
     169             :             "  \"time\" : ttt,             (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
     170             :             "  \"blocktime\" : ttt         (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
     171             :             "}\n"
     172             : 
     173             :             "\nExamples:\n"
     174           8 :             + HelpExampleCli("getrawtransaction", "\"mytxid\"")
     175           8 :             + HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
     176           8 :             + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
     177           3 :         );
     178             : 
     179           4 :     LOCK(cs_main);
     180             : 
     181          12 :     uint256 hash = ParseHashV(params[0], "parameter 1");
     182             : 
     183           3 :     bool fVerbose = false;
     184           3 :     if (params.size() > 1)
     185           3 :         fVerbose = (params[1].get_int() != 0);
     186             : 
     187           3 :     CTransaction tx;
     188             :     uint256 hashBlock;
     189           3 :     if (!GetTransaction(hash, tx, hashBlock, true))
     190           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
     191             : 
     192           3 :     string strHex = EncodeHexTx(tx);
     193             : 
     194           3 :     if (!fVerbose)
     195           0 :         return strHex;
     196             : 
     197          12 :     UniValue result(UniValue::VOBJ);
     198           9 :     result.push_back(Pair("hex", strHex));
     199           3 :     TxToJSON(tx, hashBlock, result);
     200           3 :     return result;
     201             : }
     202             : 
     203           9 : UniValue gettxoutproof(const UniValue& params, bool fHelp)
     204             : {
     205          20 :     if (fHelp || (params.size() != 1 && params.size() != 2))
     206             :         throw runtime_error(
     207             :             "gettxoutproof [\"txid\",...] ( blockhash )\n"
     208             :             "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
     209             :             "\nNOTE: By default this function only works sometimes. This is when there is an\n"
     210             :             "unspent output in the utxo for this transaction. To make it always work,\n"
     211             :             "you need to maintain a transaction index, using the -txindex command line option or\n"
     212             :             "specify the block in which the transaction is included in manually (by blockhash).\n"
     213             :             "\nReturn the raw transaction data.\n"
     214             :             "\nArguments:\n"
     215             :             "1. \"txids\"       (string) A json array of txids to filter\n"
     216             :             "    [\n"
     217             :             "      \"txid\"     (string) A transaction hash\n"
     218             :             "      ,...\n"
     219             :             "    ]\n"
     220             :             "2. \"block hash\"  (string, optional) If specified, looks for txid in the block with this hash\n"
     221             :             "\nResult:\n"
     222             :             "\"data\"           (string) A string that is a serialized, hex-encoded data for the proof.\n"
     223           0 :         );
     224             : 
     225             :     set<uint256> setTxids;
     226             :     uint256 oneTxid;
     227          18 :     UniValue txids = params[0].get_array();
     228          33 :     for (unsigned int idx = 0; idx < txids.size(); idx++) {
     229          12 :         const UniValue& txid = txids[idx];
     230          48 :         if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
     231           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
     232          24 :         uint256 hash(uint256S(txid.get_str()));
     233          12 :         if (setTxids.count(hash))
     234           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
     235             :        setTxids.insert(hash);
     236          12 :        oneTxid = hash;
     237             :     }
     238             : 
     239           9 :     LOCK(cs_main);
     240             : 
     241           9 :     CBlockIndex* pblockindex = NULL;
     242             : 
     243             :     uint256 hashBlock;
     244           9 :     if (params.size() > 1)
     245             :     {
     246           6 :         hashBlock = uint256S(params[1].get_str());
     247           2 :         if (!mapBlockIndex.count(hashBlock))
     248           0 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
     249           2 :         pblockindex = mapBlockIndex[hashBlock];
     250             :     } else {
     251           7 :         CCoins coins;
     252          11 :         if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())
     253           8 :             pblockindex = chainActive[coins.nHeight];
     254             :     }
     255             : 
     256           9 :     if (pblockindex == NULL)
     257             :     {
     258           3 :         CTransaction tx;
     259           5 :         if (!GetTransaction(oneTxid, tx, hashBlock, false) || hashBlock.IsNull())
     260           6 :             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
     261           1 :         if (!mapBlockIndex.count(hashBlock))
     262           0 :             throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
     263           1 :         pblockindex = mapBlockIndex[hashBlock];
     264             :     }
     265             : 
     266           7 :     CBlock block;
     267           7 :     if(!ReadBlockFromDisk(block, pblockindex))
     268           0 :         throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
     269             : 
     270           7 :     unsigned int ntxFound = 0;
     271         168 :     BOOST_FOREACH(const CTransaction&tx, block.vtx)
     272          42 :         if (setTxids.count(tx.GetHash()))
     273          10 :             ntxFound++;
     274          14 :     if (ntxFound != setTxids.size())
     275           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
     276             : 
     277             :     CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
     278          14 :     CMerkleBlock mb(block, setTxids);
     279             :     ssMB << mb;
     280           7 :     std::string strHex = HexStr(ssMB.begin(), ssMB.end());
     281          14 :     return strHex;
     282             : }
     283             : 
     284           7 : UniValue verifytxoutproof(const UniValue& params, bool fHelp)
     285             : {
     286          14 :     if (fHelp || params.size() != 1)
     287             :         throw runtime_error(
     288             :             "verifytxoutproof \"proof\"\n"
     289             :             "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
     290             :             "and throwing an RPC error if the block is not in our best chain\n"
     291             :             "\nArguments:\n"
     292             :             "1. \"proof\"    (string, required) The hex-encoded proof generated by gettxoutproof\n"
     293             :             "\nResult:\n"
     294             :             "[\"txid\"]      (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
     295           0 :         );
     296             : 
     297          28 :     CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
     298          14 :     CMerkleBlock merkleBlock;
     299             :     ssMB >> merkleBlock;
     300             : 
     301          21 :     UniValue res(UniValue::VARR);
     302             : 
     303             :     vector<uint256> vMatch;
     304          14 :     if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot)
     305             :         return res;
     306             : 
     307           7 :     LOCK(cs_main);
     308             : 
     309          28 :     if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
     310           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
     311             : 
     312          92 :     BOOST_FOREACH(const uint256& hash, vMatch)
     313          20 :         res.push_back(hash.GetHex());
     314             :     return res;
     315             : }
     316             : 
     317          58 : UniValue createrawtransaction(const UniValue& params, bool fHelp)
     318             : {
     319         116 :     if (fHelp || params.size() != 2)
     320             :         throw runtime_error(
     321             :             "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...}\n"
     322             :             "\nCreate a transaction spending the given inputs and creating new outputs.\n"
     323             :             "Outputs can be addresses or data.\n"
     324             :             "Returns hex-encoded raw transaction.\n"
     325             :             "Note that the transaction's inputs are not signed, and\n"
     326             :             "it is not stored in the wallet or transmitted to the network.\n"
     327             : 
     328             :             "\nArguments:\n"
     329             :             "1. \"transactions\"        (string, required) A json array of json objects\n"
     330             :             "     [\n"
     331             :             "       {\n"
     332             :             "         \"txid\":\"id\",    (string, required) The transaction id\n"
     333             :             "         \"vout\":n        (numeric, required) The output number\n"
     334             :             "       }\n"
     335             :             "       ,...\n"
     336             :             "     ]\n"
     337             :             "2. \"outputs\"             (string, required) a json object with outputs\n"
     338             :             "    {\n"
     339           6 :             "      \"address\": x.xxx   (numeric, required) The key is the bitcoin address, the value is the " + CURRENCY_UNIT + " amount\n"
     340             :             "      \"data\": \"hex\",     (string, required) The key is \"data\", the value is hex encoded data\n"
     341             :             "      ...\n"
     342             :             "    }\n"
     343             :             "\nResult:\n"
     344             :             "\"transaction\"            (string) hex string of the transaction\n"
     345             : 
     346             :             "\nExamples\n"
     347          16 :             + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
     348          16 :             + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
     349          16 :             + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
     350          16 :             + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
     351           6 :         );
     352             : 
     353          56 :     LOCK(cs_main);
     354         280 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ));
     355             : 
     356         106 :     UniValue inputs = params[0].get_array();
     357         106 :     UniValue sendTo = params[1].get_obj();
     358             : 
     359          53 :     CMutableTransaction rawTx;
     360             : 
     361         139 :     for (unsigned int idx = 0; idx < inputs.size(); idx++) {
     362          43 :         const UniValue& input = inputs[idx];
     363          43 :         const UniValue& o = input.get_obj();
     364             : 
     365         132 :         uint256 txid = ParseHashO(o, "txid");
     366             : 
     367         132 :         const UniValue& vout_v = find_value(o, "vout");
     368          43 :         if (!vout_v.isNum())
     369           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
     370          43 :         int nOutput = vout_v.get_int();
     371          43 :         if (nOutput < 0)
     372           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
     373             : 
     374         172 :         CTxIn in(COutPoint(txid, nOutput));
     375          43 :         rawTx.vin.push_back(in);
     376             :     }
     377             : 
     378             :     set<CBitcoinAddress> setAddress;
     379         106 :     vector<string> addrList = sendTo.getKeys();
     380         699 :     BOOST_FOREACH(const string& name_, addrList) {
     381             : 
     382          65 :         if (name_ == "data") {
     383          27 :             std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
     384             : 
     385          16 :             CTxOut out(0, CScript() << OP_RETURN << data);
     386           4 :             rawTx.vout.push_back(out);
     387             :         } else {
     388          59 :             CBitcoinAddress address(name_);
     389          59 :             if (!address.IsValid())
     390           4 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+name_);
     391             : 
     392          58 :             if (setAddress.count(address))
     393           0 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
     394             :             setAddress.insert(address);
     395             : 
     396         116 :             CScript scriptPubKey = GetScriptForDestination(address.Get());
     397          58 :             CAmount nAmount = AmountFromValue(sendTo[name_]);
     398             : 
     399         116 :             CTxOut out(nAmount, scriptPubKey);
     400          58 :             rawTx.vout.push_back(out);
     401             :         }
     402             :     }
     403             : 
     404         200 :     return EncodeHexTx(rawTx);
     405             : }
     406             : 
     407          41 : UniValue decoderawtransaction(const UniValue& params, bool fHelp)
     408             : {
     409          82 :     if (fHelp || params.size() != 1)
     410             :         throw runtime_error(
     411             :             "decoderawtransaction \"hexstring\"\n"
     412             :             "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
     413             : 
     414             :             "\nArguments:\n"
     415             :             "1. \"hex\"      (string, required) The transaction hex string\n"
     416             : 
     417             :             "\nResult:\n"
     418             :             "{\n"
     419             :             "  \"txid\" : \"id\",        (string) The transaction id\n"
     420             :             "  \"version\" : n,          (numeric) The version\n"
     421             :             "  \"locktime\" : ttt,       (numeric) The lock time\n"
     422             :             "  \"vin\" : [               (array of json objects)\n"
     423             :             "     {\n"
     424             :             "       \"txid\": \"id\",    (string) The transaction id\n"
     425             :             "       \"vout\": n,         (numeric) The output number\n"
     426             :             "       \"scriptSig\": {     (json object) The script\n"
     427             :             "         \"asm\": \"asm\",  (string) asm\n"
     428             :             "         \"hex\": \"hex\"   (string) hex\n"
     429             :             "       },\n"
     430             :             "       \"sequence\": n     (numeric) The script sequence number\n"
     431             :             "     }\n"
     432             :             "     ,...\n"
     433             :             "  ],\n"
     434             :             "  \"vout\" : [             (array of json objects)\n"
     435             :             "     {\n"
     436           6 :             "       \"value\" : x.xxx,            (numeric) The value in " + CURRENCY_UNIT + "\n"
     437             :             "       \"n\" : n,                    (numeric) index\n"
     438             :             "       \"scriptPubKey\" : {          (json object)\n"
     439             :             "         \"asm\" : \"asm\",          (string) the asm\n"
     440             :             "         \"hex\" : \"hex\",          (string) the hex\n"
     441             :             "         \"reqSigs\" : n,            (numeric) The required sigs\n"
     442             :             "         \"type\" : \"pubkeyhash\",  (string) The type, eg 'pubkeyhash'\n"
     443             :             "         \"addresses\" : [           (json array of string)\n"
     444             :             "           \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\"   (string) bitcoin address\n"
     445             :             "           ,...\n"
     446             :             "         ]\n"
     447             :             "       }\n"
     448             :             "     }\n"
     449             :             "     ,...\n"
     450             :             "  ],\n"
     451             :             "}\n"
     452             : 
     453             :             "\nExamples:\n"
     454          16 :             + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
     455          16 :             + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
     456           6 :         );
     457             : 
     458          39 :     LOCK(cs_main);
     459         158 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
     460             : 
     461          39 :     CTransaction tx;
     462             : 
     463          78 :     if (!DecodeHexTx(tx, params[0].get_str()))
     464           6 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
     465             : 
     466         113 :     UniValue result(UniValue::VOBJ);
     467          37 :     TxToJSON(tx, uint256(), result);
     468             : 
     469          37 :     return result;
     470             : }
     471             : 
     472          10 : UniValue decodescript(const UniValue& params, bool fHelp)
     473             : {
     474          20 :     if (fHelp || params.size() != 1)
     475             :         throw runtime_error(
     476             :             "decodescript \"hex\"\n"
     477             :             "\nDecode a hex-encoded script.\n"
     478             :             "\nArguments:\n"
     479             :             "1. \"hex\"     (string) the hex encoded script\n"
     480             :             "\nResult:\n"
     481             :             "{\n"
     482             :             "  \"asm\":\"asm\",   (string) Script public key\n"
     483             :             "  \"hex\":\"hex\",   (string) hex encoded public key\n"
     484             :             "  \"type\":\"type\", (string) The output type\n"
     485             :             "  \"reqSigs\": n,    (numeric) The required signatures\n"
     486             :             "  \"addresses\": [   (json array of string)\n"
     487             :             "     \"address\"     (string) bitcoin address\n"
     488             :             "     ,...\n"
     489             :             "  ],\n"
     490             :             "  \"p2sh\",\"address\" (string) script address\n"
     491             :             "}\n"
     492             :             "\nExamples:\n"
     493           0 :             + HelpExampleCli("decodescript", "\"hexstring\"")
     494           0 :             + HelpExampleRpc("decodescript", "\"hexstring\"")
     495           0 :         );
     496             : 
     497          10 :     LOCK(cs_main);
     498          40 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
     499             : 
     500          30 :     UniValue r(UniValue::VOBJ);
     501             :     CScript script;
     502          30 :     if (params[0].get_str().size() > 0){
     503          30 :         vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
     504          30 :         script = CScript(scriptData.begin(), scriptData.end());
     505             :     } else {
     506             :         // Empty scripts are valid
     507             :     }
     508          10 :     ScriptPubKeyToJSON(script, r, false);
     509             : 
     510          60 :     r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
     511          10 :     return r;
     512             : }
     513             : 
     514             : /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
     515           9 : static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
     516             : {
     517          27 :     UniValue entry(UniValue::VOBJ);
     518          27 :     entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
     519          18 :     entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
     520          45 :     entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
     521          18 :     entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
     522          27 :     entry.push_back(Pair("error", strMessage));
     523           9 :     vErrorsRet.push_back(entry);
     524           9 : }
     525             : 
     526          40 : UniValue signrawtransaction(const UniValue& params, bool fHelp)
     527             : {
     528         119 :     if (fHelp || params.size() < 1 || params.size() > 4)
     529             :         throw runtime_error(
     530             :             "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
     531             :             "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
     532             :             "The second optional argument (may be null) is an array of previous transaction outputs that\n"
     533             :             "this transaction depends on but may not yet be in the block chain.\n"
     534             :             "The third optional argument (may be null) is an array of base58-encoded private\n"
     535             :             "keys that, if given, will be the only keys used to sign the transaction.\n"
     536             : #ifdef ENABLE_WALLET
     537           4 :             + HelpRequiringPassphrase() + "\n"
     538             : #endif
     539             : 
     540             :             "\nArguments:\n"
     541             :             "1. \"hexstring\"     (string, required) The transaction hex string\n"
     542             :             "2. \"prevtxs\"       (string, optional) An json array of previous dependent transaction outputs\n"
     543             :             "     [               (json array of json objects, or 'null' if none provided)\n"
     544             :             "       {\n"
     545             :             "         \"txid\":\"id\",             (string, required) The transaction id\n"
     546             :             "         \"vout\":n,                  (numeric, required) The output number\n"
     547             :             "         \"scriptPubKey\": \"hex\",   (string, required) script key\n"
     548             :             "         \"redeemScript\": \"hex\"    (string, required for P2SH) redeem script\n"
     549             :             "       }\n"
     550             :             "       ,...\n"
     551             :             "    ]\n"
     552             :             "3. \"privatekeys\"     (string, optional) A json array of base58-encoded private keys for signing\n"
     553             :             "    [                  (json array of strings, or 'null' if none provided)\n"
     554             :             "      \"privatekey\"   (string) private key in base58-encoding\n"
     555             :             "      ,...\n"
     556             :             "    ]\n"
     557             :             "4. \"sighashtype\"     (string, optional, default=ALL) The signature hash type. Must be one of\n"
     558             :             "       \"ALL\"\n"
     559             :             "       \"NONE\"\n"
     560             :             "       \"SINGLE\"\n"
     561             :             "       \"ALL|ANYONECANPAY\"\n"
     562             :             "       \"NONE|ANYONECANPAY\"\n"
     563             :             "       \"SINGLE|ANYONECANPAY\"\n"
     564             : 
     565             :             "\nResult:\n"
     566             :             "{\n"
     567             :             "  \"hex\" : \"value\",           (string) The hex-encoded raw transaction with signature(s)\n"
     568             :             "  \"complete\" : true|false,   (boolean) If the transaction has a complete set of signatures\n"
     569             :             "  \"errors\" : [                 (json array of objects) Script verification errors (if there are any)\n"
     570             :             "    {\n"
     571             :             "      \"txid\" : \"hash\",           (string) The hash of the referenced, previous transaction\n"
     572             :             "      \"vout\" : n,                (numeric) The index of the output to spent and used as input\n"
     573             :             "      \"scriptSig\" : \"hex\",       (string) The hex-encoded signature script\n"
     574             :             "      \"sequence\" : n,            (numeric) Script sequence number\n"
     575             :             "      \"error\" : \"text\"           (string) Verification or signing error related to the input\n"
     576             :             "    }\n"
     577             :             "    ,...\n"
     578             :             "  ]\n"
     579             :             "}\n"
     580             : 
     581             :             "\nExamples:\n"
     582           8 :             + HelpExampleCli("signrawtransaction", "\"myhex\"")
     583           8 :             + HelpExampleRpc("signrawtransaction", "\"myhex\"")
     584           3 :         );
     585             : 
     586             : #ifdef ENABLE_WALLET
     587          39 :     LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
     588             : #else
     589             :     LOCK(cs_main);
     590             : #endif
     591         273 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
     592             : 
     593         119 :     vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
     594             :     CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
     595          38 :     vector<CMutableTransaction> txVariants;
     596          75 :     while (!ssData.empty()) {
     597             :         try {
     598          38 :             CMutableTransaction tx;
     599             :             ssData >> tx;
     600          37 :             txVariants.push_back(tx);
     601             :         }
     602           1 :         catch (const std::exception&) {
     603           3 :             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
     604             :         }
     605             :     }
     606             : 
     607          37 :     if (txVariants.empty())
     608           0 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
     609             : 
     610             :     // mergedTx will end up with all the signatures; it
     611             :     // starts as a clone of the rawtx:
     612          37 :     CMutableTransaction mergedTx(txVariants[0]);
     613             : 
     614             :     // Fetch previous transactions (inputs):
     615             :     CCoinsView viewDummy;
     616          74 :     CCoinsViewCache view(&viewDummy);
     617             :     {
     618          37 :         LOCK(mempool.cs);
     619          37 :         CCoinsViewCache &viewChain = *pcoinsTip;
     620          37 :         CCoinsViewMemPool viewMempool(&viewChain, mempool);
     621          37 :         view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
     622             : 
     623         527 :         BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
     624          61 :             const uint256& prevHash = txin.prevout.hash;
     625          61 :             CCoins coins;
     626          61 :             view.AccessCoins(prevHash); // this is certainly allowed to fail
     627             :         }
     628             : 
     629          37 :         view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
     630             :     }
     631             : 
     632          37 :     bool fGivenKeys = false;
     633          74 :     CBasicKeyStore tempKeystore;
     634          37 :     if (params.size() > 2 && !params[2].isNull()) {
     635           5 :         fGivenKeys = true;
     636           5 :         UniValue keys = params[2].get_array();
     637          13 :         for (unsigned int idx = 0; idx < keys.size(); idx++) {
     638           4 :             UniValue k = keys[idx];
     639             :             CBitcoinSecret vchSecret;
     640           8 :             bool fGood = vchSecret.SetString(k.get_str());
     641           4 :             if (!fGood)
     642           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
     643           4 :             CKey key = vchSecret.GetKey();
     644           4 :             if (!key.IsValid())
     645           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
     646           4 :             tempKeystore.AddKey(key);
     647           9 :         }
     648             :     }
     649             : #ifdef ENABLE_WALLET
     650          32 :     else if (pwalletMain)
     651          32 :         EnsureWalletIsUnlocked();
     652             : #endif
     653             : 
     654             :     // Add previous txouts given in the RPC call:
     655             :     if (params.size() > 1 && !params[1].isNull()) {
     656           7 :         UniValue prevTxs = params[1].get_array();
     657          21 :         for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
     658           7 :             const UniValue& p = prevTxs[idx];
     659           7 :             if (!p.isObject())
     660           0 :                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
     661             : 
     662           7 :             UniValue prevOut = p.get_obj();
     663             : 
     664          42 :             RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
     665             : 
     666          21 :             uint256 txid = ParseHashO(prevOut, "txid");
     667             : 
     668          21 :             int nOut = find_value(prevOut, "vout").get_int();
     669           7 :             if (nOut < 0)
     670           0 :                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
     671             : 
     672          21 :             vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
     673          14 :             CScript scriptPubKey(pkData.begin(), pkData.end());
     674             : 
     675             :             {
     676           7 :                 CCoinsModifier coins = view.ModifyCoins(txid);
     677          27 :                 if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
     678           0 :                     string err("Previous output scriptPubKey mismatch:\n");
     679           0 :                     err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
     680             :                         ScriptToAsmStr(scriptPubKey);
     681           0 :                     throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
     682             :                 }
     683          14 :                 if ((unsigned int)nOut >= coins->vout.size())
     684          15 :                     coins->vout.resize(nOut+1);
     685          21 :                 coins->vout[nOut].scriptPubKey = scriptPubKey;
     686          21 :                 coins->vout[nOut].nValue = 0; // we don't know the actual output value
     687             :             }
     688             : 
     689             :             // if redeemScript given and not using the local wallet (private keys
     690             :             // given), add redeemScript to the tempKeystore so it can be signed:
     691           7 :             if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
     692          14 :                 RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
     693           6 :                 UniValue v = find_value(prevOut, "redeemScript");
     694           2 :                 if (!v.isNull()) {
     695           6 :                     vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
     696           4 :                     CScript redeemScript(rsData.begin(), rsData.end());
     697           2 :                     tempKeystore.AddCScript(redeemScript);
     698           2 :                 }
     699             :             }
     700          14 :         }
     701             :     }
     702             : 
     703             : #ifdef ENABLE_WALLET
     704          37 :     const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
     705             : #else
     706             :     const CKeyStore& keystore = tempKeystore;
     707             : #endif
     708             : 
     709          37 :     int nHashType = SIGHASH_ALL;
     710          37 :     if (params.size() > 3 && !params[3].isNull()) {
     711             :         static map<string, int> mapSigHashValues =
     712             :             boost::assign::map_list_of
     713             :             (string("ALL"), int(SIGHASH_ALL))
     714          12 :             (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
     715           8 :             (string("NONE"), int(SIGHASH_NONE))
     716           8 :             (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
     717           8 :             (string("SINGLE"), int(SIGHASH_SINGLE))
     718          12 :             (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
     719             :             ;
     720           4 :         string strHashType = params[3].get_str();
     721           4 :         if (mapSigHashValues.count(strHashType))
     722           3 :             nHashType = mapSigHashValues[strHashType];
     723             :         else
     724           3 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
     725             :     }
     726             : 
     727          36 :     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
     728             : 
     729             :     // Script verification errors
     730         145 :     UniValue vErrors(UniValue::VARR);
     731             : 
     732             :     // Sign what we can:
     733         192 :     for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
     734         120 :         CTxIn& txin = mergedTx.vin[i];
     735          60 :         const CCoins* coins = view.AccessCoins(txin.prevout.hash);
     736         116 :         if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
     737          15 :             TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
     738           5 :             continue;
     739             :         }
     740         110 :         const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
     741             : 
     742          55 :         txin.scriptSig.clear();
     743             :         // Only sign SIGHASH_SINGLE if there's a corresponding output:
     744          55 :         if (!fHashSingle || (i < mergedTx.vout.size()))
     745          55 :             SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
     746             : 
     747             :         // ... and merge in other signatures:
     748         605 :         BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
     749         220 :             txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
     750             :         }
     751          55 :         ScriptError serror = SCRIPT_ERR_OK;
     752          55 :         if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
     753          12 :             TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
     754             :         }
     755             :     }
     756          36 :     bool fComplete = vErrors.empty();
     757             : 
     758         108 :     UniValue result(UniValue::VOBJ);
     759         144 :     result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
     760          72 :     result.push_back(Pair("complete", fComplete));
     761          36 :     if (!vErrors.empty()) {
     762          16 :         result.push_back(Pair("errors", vErrors));
     763             :     }
     764             : 
     765          36 :     return result;
     766             : }
     767             : 
     768          37 : UniValue sendrawtransaction(const UniValue& params, bool fHelp)
     769             : {
     770         110 :     if (fHelp || params.size() < 1 || params.size() > 2)
     771             :         throw runtime_error(
     772             :             "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
     773             :             "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
     774             :             "\nAlso see createrawtransaction and signrawtransaction calls.\n"
     775             :             "\nArguments:\n"
     776             :             "1. \"hexstring\"    (string, required) The hex string of the raw transaction)\n"
     777             :             "2. allowhighfees    (boolean, optional, default=false) Allow high fees\n"
     778             :             "\nResult:\n"
     779             :             "\"hex\"             (string) The transaction hash in hex\n"
     780             :             "\nExamples:\n"
     781             :             "\nCreate a transaction\n"
     782           8 :             + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
     783             :             "Sign the transaction, and get back the hex\n"
     784           9 :             + HelpExampleCli("signrawtransaction", "\"myhex\"") +
     785             :             "\nSend the transaction (signed hex)\n"
     786           9 :             + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
     787             :             "\nAs a json rpc call\n"
     788           8 :             + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
     789           3 :         );
     790             : 
     791          36 :     LOCK(cs_main);
     792         180 :     RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
     793             : 
     794             :     // parse hex string from parameter
     795          36 :     CTransaction tx;
     796          72 :     if (!DecodeHexTx(tx, params[0].get_str()))
     797           6 :         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
     798          34 :     uint256 hashTx = tx.GetHash();
     799             : 
     800          34 :     bool fOverrideFees = false;
     801          34 :     if (params.size() > 1)
     802           2 :         fOverrideFees = params[1].get_bool();
     803             : 
     804          34 :     CCoinsViewCache &view = *pcoinsTip;
     805          34 :     const CCoins* existingCoins = view.AccessCoins(hashTx);
     806          34 :     bool fHaveMempool = mempool.exists(hashTx);
     807          34 :     bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
     808          34 :     if (!fHaveMempool && !fHaveChain) {
     809             :         // push to local node and sync with wallets
     810             :         CValidationState state;
     811             :         bool fMissingInputs;
     812          32 :         if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, !fOverrideFees)) {
     813           2 :             if (state.IsInvalid()) {
     814           4 :                 throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
     815             :             } else {
     816           1 :                 if (fMissingInputs) {
     817           3 :                     throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
     818             :                 }
     819           0 :                 throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
     820             :             }
     821          32 :         }
     822           2 :     } else if (fHaveChain) {
     823           0 :         throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
     824             :     }
     825          32 :     RelayTransaction(tx);
     826             : 
     827          96 :     return hashTx.GetHex();
     828         288 : }

Generated by: LCOV version 1.11