scripted-diff: Use the C++11 keyword nullptr to denote the pointer literal instead...
[bitcoinplatinum.git] / src / rpc / rawtransaction.cpp
blob81005118541a8bda2412bed4bc7491453fd45543
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
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 "validation.h"
14 #include "merkleblock.h"
15 #include "net.h"
16 #include "policy/policy.h"
17 #include "policy/rbf.h"
18 #include "primitives/transaction.h"
19 #include "rpc/server.h"
20 #include "script/script.h"
21 #include "script/script_error.h"
22 #include "script/sign.h"
23 #include "script/standard.h"
24 #include "txmempool.h"
25 #include "uint256.h"
26 #include "utilstrencodings.h"
27 #ifdef ENABLE_WALLET
28 #include "wallet/rpcwallet.h"
29 #include "wallet/wallet.h"
30 #endif
32 #include <stdint.h>
34 #include <univalue.h>
37 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
39 // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
41 // Blockchain contextual information (confirmations and blocktime) is not
42 // available to code in bitcoin-common, so we query them here and push the
43 // data into the returned UniValue.
44 TxToUniv(tx, uint256(), entry);
46 if (!hashBlock.IsNull()) {
47 entry.push_back(Pair("blockhash", hashBlock.GetHex()));
48 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
49 if (mi != mapBlockIndex.end() && (*mi).second) {
50 CBlockIndex* pindex = (*mi).second;
51 if (chainActive.Contains(pindex)) {
52 entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
53 entry.push_back(Pair("time", pindex->GetBlockTime()));
54 entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
56 else
57 entry.push_back(Pair("confirmations", 0));
62 UniValue getrawtransaction(const JSONRPCRequest& request)
64 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
65 throw std::runtime_error(
66 "getrawtransaction \"txid\" ( verbose )\n"
68 "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
69 "enabled, it also works for blockchain transactions.\n"
70 "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
72 "\nReturn the raw transaction data.\n"
73 "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
74 "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
76 "\nArguments:\n"
77 "1. \"txid\" (string, required) The transaction id\n"
78 "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
80 "\nResult (if verbose is not set or set to false):\n"
81 "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
83 "\nResult (if verbose is set to true):\n"
84 "{\n"
85 " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
86 " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
87 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
88 " \"size\" : n, (numeric) The serialized transaction size\n"
89 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
90 " \"version\" : n, (numeric) The version\n"
91 " \"locktime\" : ttt, (numeric) The lock time\n"
92 " \"vin\" : [ (array of json objects)\n"
93 " {\n"
94 " \"txid\": \"id\", (string) The transaction id\n"
95 " \"vout\": n, (numeric) \n"
96 " \"scriptSig\": { (json object) The script\n"
97 " \"asm\": \"asm\", (string) asm\n"
98 " \"hex\": \"hex\" (string) hex\n"
99 " },\n"
100 " \"sequence\": n (numeric) The script sequence number\n"
101 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
102 " }\n"
103 " ,...\n"
104 " ],\n"
105 " \"vout\" : [ (array of json objects)\n"
106 " {\n"
107 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
108 " \"n\" : n, (numeric) index\n"
109 " \"scriptPubKey\" : { (json object)\n"
110 " \"asm\" : \"asm\", (string) the asm\n"
111 " \"hex\" : \"hex\", (string) the hex\n"
112 " \"reqSigs\" : n, (numeric) The required sigs\n"
113 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
114 " \"addresses\" : [ (json array of string)\n"
115 " \"address\" (string) bitcoin address\n"
116 " ,...\n"
117 " ]\n"
118 " }\n"
119 " }\n"
120 " ,...\n"
121 " ],\n"
122 " \"blockhash\" : \"hash\", (string) the block hash\n"
123 " \"confirmations\" : n, (numeric) The confirmations\n"
124 " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
125 " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
126 "}\n"
128 "\nExamples:\n"
129 + HelpExampleCli("getrawtransaction", "\"mytxid\"")
130 + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
131 + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
134 LOCK(cs_main);
136 uint256 hash = ParseHashV(request.params[0], "parameter 1");
138 // Accept either a bool (true) or a num (>=1) to indicate verbose output.
139 bool fVerbose = false;
140 if (!request.params[1].isNull()) {
141 if (request.params[1].isNum()) {
142 if (request.params[1].get_int() != 0) {
143 fVerbose = true;
146 else if(request.params[1].isBool()) {
147 if(request.params[1].isTrue()) {
148 fVerbose = true;
151 else {
152 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean.");
156 CTransactionRef tx;
157 uint256 hashBlock;
158 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
159 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction"
160 : "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
161 ". Use gettransaction for wallet transactions.");
163 std::string strHex = EncodeHexTx(*tx, RPCSerializationFlags());
165 if (!fVerbose)
166 return strHex;
168 UniValue result(UniValue::VOBJ);
169 result.push_back(Pair("hex", strHex));
170 TxToJSON(*tx, hashBlock, result);
171 return result;
174 UniValue gettxoutproof(const JSONRPCRequest& request)
176 if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
177 throw std::runtime_error(
178 "gettxoutproof [\"txid\",...] ( blockhash )\n"
179 "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
180 "\nNOTE: By default this function only works sometimes. This is when there is an\n"
181 "unspent output in the utxo for this transaction. To make it always work,\n"
182 "you need to maintain a transaction index, using the -txindex command line option or\n"
183 "specify the block in which the transaction is included manually (by blockhash).\n"
184 "\nArguments:\n"
185 "1. \"txids\" (string) A json array of txids to filter\n"
186 " [\n"
187 " \"txid\" (string) A transaction hash\n"
188 " ,...\n"
189 " ]\n"
190 "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
191 "\nResult:\n"
192 "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
195 std::set<uint256> setTxids;
196 uint256 oneTxid;
197 UniValue txids = request.params[0].get_array();
198 for (unsigned int idx = 0; idx < txids.size(); idx++) {
199 const UniValue& txid = txids[idx];
200 if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
201 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
202 uint256 hash(uint256S(txid.get_str()));
203 if (setTxids.count(hash))
204 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
205 setTxids.insert(hash);
206 oneTxid = hash;
209 LOCK(cs_main);
211 CBlockIndex* pblockindex = nullptr;
213 uint256 hashBlock;
214 if (!request.params[1].isNull())
216 hashBlock = uint256S(request.params[1].get_str());
217 if (!mapBlockIndex.count(hashBlock))
218 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
219 pblockindex = mapBlockIndex[hashBlock];
220 } else {
221 // Loop through txids and try to find which block they're in. Exit loop once a block is found.
222 for (const auto& tx : setTxids) {
223 const Coin& coin = AccessByTxid(*pcoinsTip, tx);
224 if (!coin.IsSpent()) {
225 pblockindex = chainActive[coin.nHeight];
226 break;
231 if (pblockindex == nullptr)
233 CTransactionRef tx;
234 if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
235 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
236 if (!mapBlockIndex.count(hashBlock))
237 throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
238 pblockindex = mapBlockIndex[hashBlock];
241 CBlock block;
242 if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
243 throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
245 unsigned int ntxFound = 0;
246 for (const auto& tx : block.vtx)
247 if (setTxids.count(tx->GetHash()))
248 ntxFound++;
249 if (ntxFound != setTxids.size())
250 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
252 CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
253 CMerkleBlock mb(block, setTxids);
254 ssMB << mb;
255 std::string strHex = HexStr(ssMB.begin(), ssMB.end());
256 return strHex;
259 UniValue verifytxoutproof(const JSONRPCRequest& request)
261 if (request.fHelp || request.params.size() != 1)
262 throw std::runtime_error(
263 "verifytxoutproof \"proof\"\n"
264 "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
265 "and throwing an RPC error if the block is not in our best chain\n"
266 "\nArguments:\n"
267 "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
268 "\nResult:\n"
269 "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
272 CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
273 CMerkleBlock merkleBlock;
274 ssMB >> merkleBlock;
276 UniValue res(UniValue::VARR);
278 std::vector<uint256> vMatch;
279 std::vector<unsigned int> vIndex;
280 if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
281 return res;
283 LOCK(cs_main);
285 if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
286 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
288 for (const uint256& hash : vMatch)
289 res.push_back(hash.GetHex());
290 return res;
293 UniValue createrawtransaction(const JSONRPCRequest& request)
295 if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
296 throw std::runtime_error(
297 "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
298 "\nCreate a transaction spending the given inputs and creating new outputs.\n"
299 "Outputs can be addresses or data.\n"
300 "Returns hex-encoded raw transaction.\n"
301 "Note that the transaction's inputs are not signed, and\n"
302 "it is not stored in the wallet or transmitted to the network.\n"
304 "\nArguments:\n"
305 "1. \"inputs\" (array, required) A json array of json objects\n"
306 " [\n"
307 " {\n"
308 " \"txid\":\"id\", (string, required) The transaction id\n"
309 " \"vout\":n, (numeric, required) The output number\n"
310 " \"sequence\":n (numeric, optional) The sequence number\n"
311 " } \n"
312 " ,...\n"
313 " ]\n"
314 "2. \"outputs\" (object, required) a json object with outputs\n"
315 " {\n"
316 " \"address\": x.xxx, (numeric or string, required) The key is the bitcoin address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
317 " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
318 " ,...\n"
319 " }\n"
320 "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
321 "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
322 " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"
323 "\nResult:\n"
324 "\"transaction\" (string) hex string of the transaction\n"
326 "\nExamples:\n"
327 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
328 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
329 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
330 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
333 RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM}, true);
334 if (request.params[0].isNull() || request.params[1].isNull())
335 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
337 UniValue inputs = request.params[0].get_array();
338 UniValue sendTo = request.params[1].get_obj();
340 CMutableTransaction rawTx;
342 if (request.params.size() > 2 && !request.params[2].isNull()) {
343 int64_t nLockTime = request.params[2].get_int64();
344 if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
345 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
346 rawTx.nLockTime = nLockTime;
349 bool rbfOptIn = request.params.size() > 3 ? request.params[3].isTrue() : false;
351 for (unsigned int idx = 0; idx < inputs.size(); idx++) {
352 const UniValue& input = inputs[idx];
353 const UniValue& o = input.get_obj();
355 uint256 txid = ParseHashO(o, "txid");
357 const UniValue& vout_v = find_value(o, "vout");
358 if (!vout_v.isNum())
359 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
360 int nOutput = vout_v.get_int();
361 if (nOutput < 0)
362 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
364 uint32_t nSequence;
365 if (rbfOptIn) {
366 nSequence = MAX_BIP125_RBF_SEQUENCE;
367 } else if (rawTx.nLockTime) {
368 nSequence = std::numeric_limits<uint32_t>::max() - 1;
369 } else {
370 nSequence = std::numeric_limits<uint32_t>::max();
373 // set the sequence number if passed in the parameters object
374 const UniValue& sequenceObj = find_value(o, "sequence");
375 if (sequenceObj.isNum()) {
376 int64_t seqNr64 = sequenceObj.get_int64();
377 if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
378 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
379 } else {
380 nSequence = (uint32_t)seqNr64;
384 CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
386 rawTx.vin.push_back(in);
389 std::set<CBitcoinAddress> setAddress;
390 std::vector<std::string> addrList = sendTo.getKeys();
391 for (const std::string& name_ : addrList) {
393 if (name_ == "data") {
394 std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
396 CTxOut out(0, CScript() << OP_RETURN << data);
397 rawTx.vout.push_back(out);
398 } else {
399 CBitcoinAddress address(name_);
400 if (!address.IsValid())
401 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+name_);
403 if (setAddress.count(address))
404 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
405 setAddress.insert(address);
407 CScript scriptPubKey = GetScriptForDestination(address.Get());
408 CAmount nAmount = AmountFromValue(sendTo[name_]);
410 CTxOut out(nAmount, scriptPubKey);
411 rawTx.vout.push_back(out);
415 if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {
416 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
419 return EncodeHexTx(rawTx);
422 UniValue decoderawtransaction(const JSONRPCRequest& request)
424 if (request.fHelp || request.params.size() != 1)
425 throw std::runtime_error(
426 "decoderawtransaction \"hexstring\"\n"
427 "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
429 "\nArguments:\n"
430 "1. \"hexstring\" (string, required) The transaction hex string\n"
432 "\nResult:\n"
433 "{\n"
434 " \"txid\" : \"id\", (string) The transaction id\n"
435 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
436 " \"size\" : n, (numeric) The transaction size\n"
437 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
438 " \"version\" : n, (numeric) The version\n"
439 " \"locktime\" : ttt, (numeric) The lock time\n"
440 " \"vin\" : [ (array of json objects)\n"
441 " {\n"
442 " \"txid\": \"id\", (string) The transaction id\n"
443 " \"vout\": n, (numeric) The output number\n"
444 " \"scriptSig\": { (json object) The script\n"
445 " \"asm\": \"asm\", (string) asm\n"
446 " \"hex\": \"hex\" (string) hex\n"
447 " },\n"
448 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
449 " \"sequence\": n (numeric) The script sequence number\n"
450 " }\n"
451 " ,...\n"
452 " ],\n"
453 " \"vout\" : [ (array of json objects)\n"
454 " {\n"
455 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
456 " \"n\" : n, (numeric) index\n"
457 " \"scriptPubKey\" : { (json object)\n"
458 " \"asm\" : \"asm\", (string) the asm\n"
459 " \"hex\" : \"hex\", (string) the hex\n"
460 " \"reqSigs\" : n, (numeric) The required sigs\n"
461 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
462 " \"addresses\" : [ (json array of string)\n"
463 " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n"
464 " ,...\n"
465 " ]\n"
466 " }\n"
467 " }\n"
468 " ,...\n"
469 " ],\n"
470 "}\n"
472 "\nExamples:\n"
473 + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
474 + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
477 LOCK(cs_main);
478 RPCTypeCheck(request.params, {UniValue::VSTR});
480 CMutableTransaction mtx;
482 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
483 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
485 UniValue result(UniValue::VOBJ);
486 TxToUniv(CTransaction(std::move(mtx)), uint256(), result);
488 return result;
491 UniValue decodescript(const JSONRPCRequest& request)
493 if (request.fHelp || request.params.size() != 1)
494 throw std::runtime_error(
495 "decodescript \"hexstring\"\n"
496 "\nDecode a hex-encoded script.\n"
497 "\nArguments:\n"
498 "1. \"hexstring\" (string) the hex encoded script\n"
499 "\nResult:\n"
500 "{\n"
501 " \"asm\":\"asm\", (string) Script public key\n"
502 " \"hex\":\"hex\", (string) hex encoded public key\n"
503 " \"type\":\"type\", (string) The output type\n"
504 " \"reqSigs\": n, (numeric) The required signatures\n"
505 " \"addresses\": [ (json array of string)\n"
506 " \"address\" (string) bitcoin address\n"
507 " ,...\n"
508 " ],\n"
509 " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
510 "}\n"
511 "\nExamples:\n"
512 + HelpExampleCli("decodescript", "\"hexstring\"")
513 + HelpExampleRpc("decodescript", "\"hexstring\"")
516 RPCTypeCheck(request.params, {UniValue::VSTR});
518 UniValue r(UniValue::VOBJ);
519 CScript script;
520 if (request.params[0].get_str().size() > 0){
521 std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
522 script = CScript(scriptData.begin(), scriptData.end());
523 } else {
524 // Empty scripts are valid
526 ScriptPubKeyToUniv(script, r, false);
528 UniValue type;
529 type = find_value(r, "type");
531 if (type.isStr() && type.get_str() != "scripthash") {
532 // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
533 // don't return the address for a P2SH of the P2SH.
534 r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
537 return r;
540 /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
541 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
543 UniValue entry(UniValue::VOBJ);
544 entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
545 entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
546 UniValue witness(UniValue::VARR);
547 for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
548 witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
550 entry.push_back(Pair("witness", witness));
551 entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
552 entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
553 entry.push_back(Pair("error", strMessage));
554 vErrorsRet.push_back(entry);
557 UniValue combinerawtransaction(const JSONRPCRequest& request)
560 if (request.fHelp || request.params.size() != 1)
561 throw std::runtime_error(
562 "combinerawtransaction [\"hexstring\",...]\n"
563 "\nCombine multiple partially signed transactions into one transaction.\n"
564 "The combined transaction may be another partially signed transaction or a \n"
565 "fully signed transaction."
567 "\nArguments:\n"
568 "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
569 " [\n"
570 " \"hexstring\" (string) A transaction hash\n"
571 " ,...\n"
572 " ]\n"
574 "\nResult:\n"
575 "\"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
577 "\nExamples:\n"
578 + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
582 UniValue txs = request.params[0].get_array();
583 std::vector<CMutableTransaction> txVariants(txs.size());
585 for (unsigned int idx = 0; idx < txs.size(); idx++) {
586 if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
587 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
591 if (txVariants.empty()) {
592 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
595 // mergedTx will end up with all the signatures; it
596 // starts as a clone of the rawtx:
597 CMutableTransaction mergedTx(txVariants[0]);
599 // Fetch previous transactions (inputs):
600 CCoinsView viewDummy;
601 CCoinsViewCache view(&viewDummy);
603 LOCK(cs_main);
604 LOCK(mempool.cs);
605 CCoinsViewCache &viewChain = *pcoinsTip;
606 CCoinsViewMemPool viewMempool(&viewChain, mempool);
607 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
609 for (const CTxIn& txin : mergedTx.vin) {
610 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
613 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
616 // Use CTransaction for the constant parts of the
617 // transaction to avoid rehashing.
618 const CTransaction txConst(mergedTx);
619 // Sign what we can:
620 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
621 CTxIn& txin = mergedTx.vin[i];
622 const Coin& coin = view.AccessCoin(txin.prevout);
623 if (coin.IsSpent()) {
624 throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
626 const CScript& prevPubKey = coin.out.scriptPubKey;
627 const CAmount& amount = coin.out.nValue;
629 SignatureData sigdata;
631 // ... and merge in other signatures:
632 for (const CMutableTransaction& txv : txVariants) {
633 if (txv.vin.size() > i) {
634 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
638 UpdateTransaction(mergedTx, i, sigdata);
641 return EncodeHexTx(mergedTx);
644 UniValue signrawtransaction(const JSONRPCRequest& request)
646 #ifdef ENABLE_WALLET
647 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
648 #endif
650 if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
651 throw std::runtime_error(
652 "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
653 "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
654 "The second optional argument (may be null) is an array of previous transaction outputs that\n"
655 "this transaction depends on but may not yet be in the block chain.\n"
656 "The third optional argument (may be null) is an array of base58-encoded private\n"
657 "keys that, if given, will be the only keys used to sign the transaction.\n"
658 #ifdef ENABLE_WALLET
659 + HelpRequiringPassphrase(pwallet) + "\n"
660 #endif
662 "\nArguments:\n"
663 "1. \"hexstring\" (string, required) The transaction hex string\n"
664 "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
665 " [ (json array of json objects, or 'null' if none provided)\n"
666 " {\n"
667 " \"txid\":\"id\", (string, required) The transaction id\n"
668 " \"vout\":n, (numeric, required) The output number\n"
669 " \"scriptPubKey\": \"hex\", (string, required) script key\n"
670 " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
671 " \"amount\": value (numeric, required) The amount spent\n"
672 " }\n"
673 " ,...\n"
674 " ]\n"
675 "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
676 " [ (json array of strings, or 'null' if none provided)\n"
677 " \"privatekey\" (string) private key in base58-encoding\n"
678 " ,...\n"
679 " ]\n"
680 "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
681 " \"ALL\"\n"
682 " \"NONE\"\n"
683 " \"SINGLE\"\n"
684 " \"ALL|ANYONECANPAY\"\n"
685 " \"NONE|ANYONECANPAY\"\n"
686 " \"SINGLE|ANYONECANPAY\"\n"
688 "\nResult:\n"
689 "{\n"
690 " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
691 " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
692 " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
693 " {\n"
694 " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
695 " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
696 " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
697 " \"sequence\" : n, (numeric) Script sequence number\n"
698 " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
699 " }\n"
700 " ,...\n"
701 " ]\n"
702 "}\n"
704 "\nExamples:\n"
705 + HelpExampleCli("signrawtransaction", "\"myhex\"")
706 + HelpExampleRpc("signrawtransaction", "\"myhex\"")
709 #ifdef ENABLE_WALLET
710 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
711 #else
712 LOCK(cs_main);
713 #endif
714 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
716 CMutableTransaction mtx;
717 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
718 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
720 // Fetch previous transactions (inputs):
721 CCoinsView viewDummy;
722 CCoinsViewCache view(&viewDummy);
724 LOCK(mempool.cs);
725 CCoinsViewCache &viewChain = *pcoinsTip;
726 CCoinsViewMemPool viewMempool(&viewChain, mempool);
727 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
729 for (const CTxIn& txin : mtx.vin) {
730 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
733 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
736 bool fGivenKeys = false;
737 CBasicKeyStore tempKeystore;
738 if (request.params.size() > 2 && !request.params[2].isNull()) {
739 fGivenKeys = true;
740 UniValue keys = request.params[2].get_array();
741 for (unsigned int idx = 0; idx < keys.size(); idx++) {
742 UniValue k = keys[idx];
743 CBitcoinSecret vchSecret;
744 bool fGood = vchSecret.SetString(k.get_str());
745 if (!fGood)
746 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
747 CKey key = vchSecret.GetKey();
748 if (!key.IsValid())
749 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
750 tempKeystore.AddKey(key);
753 #ifdef ENABLE_WALLET
754 else if (pwallet) {
755 EnsureWalletIsUnlocked(pwallet);
757 #endif
759 // Add previous txouts given in the RPC call:
760 if (request.params.size() > 1 && !request.params[1].isNull()) {
761 UniValue prevTxs = request.params[1].get_array();
762 for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
763 const UniValue& p = prevTxs[idx];
764 if (!p.isObject())
765 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
767 UniValue prevOut = p.get_obj();
769 RPCTypeCheckObj(prevOut,
771 {"txid", UniValueType(UniValue::VSTR)},
772 {"vout", UniValueType(UniValue::VNUM)},
773 {"scriptPubKey", UniValueType(UniValue::VSTR)},
776 uint256 txid = ParseHashO(prevOut, "txid");
778 int nOut = find_value(prevOut, "vout").get_int();
779 if (nOut < 0)
780 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
782 COutPoint out(txid, nOut);
783 std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
784 CScript scriptPubKey(pkData.begin(), pkData.end());
787 const Coin& coin = view.AccessCoin(out);
788 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
789 std::string err("Previous output scriptPubKey mismatch:\n");
790 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
791 ScriptToAsmStr(scriptPubKey);
792 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
794 Coin newcoin;
795 newcoin.out.scriptPubKey = scriptPubKey;
796 newcoin.out.nValue = 0;
797 if (prevOut.exists("amount")) {
798 newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
800 newcoin.nHeight = 1;
801 view.AddCoin(out, std::move(newcoin), true);
804 // if redeemScript given and not using the local wallet (private keys
805 // given), add redeemScript to the tempKeystore so it can be signed:
806 if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
807 RPCTypeCheckObj(prevOut,
809 {"txid", UniValueType(UniValue::VSTR)},
810 {"vout", UniValueType(UniValue::VNUM)},
811 {"scriptPubKey", UniValueType(UniValue::VSTR)},
812 {"redeemScript", UniValueType(UniValue::VSTR)},
814 UniValue v = find_value(prevOut, "redeemScript");
815 if (!v.isNull()) {
816 std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
817 CScript redeemScript(rsData.begin(), rsData.end());
818 tempKeystore.AddCScript(redeemScript);
824 #ifdef ENABLE_WALLET
825 const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
826 #else
827 const CKeyStore& keystore = tempKeystore;
828 #endif
830 int nHashType = SIGHASH_ALL;
831 if (request.params.size() > 3 && !request.params[3].isNull()) {
832 static std::map<std::string, int> mapSigHashValues = {
833 {std::string("ALL"), int(SIGHASH_ALL)},
834 {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
835 {std::string("NONE"), int(SIGHASH_NONE)},
836 {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
837 {std::string("SINGLE"), int(SIGHASH_SINGLE)},
838 {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
840 std::string strHashType = request.params[3].get_str();
841 if (mapSigHashValues.count(strHashType))
842 nHashType = mapSigHashValues[strHashType];
843 else
844 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
847 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
849 // Script verification errors
850 UniValue vErrors(UniValue::VARR);
852 // Use CTransaction for the constant parts of the
853 // transaction to avoid rehashing.
854 const CTransaction txConst(mtx);
855 // Sign what we can:
856 for (unsigned int i = 0; i < mtx.vin.size(); i++) {
857 CTxIn& txin = mtx.vin[i];
858 const Coin& coin = view.AccessCoin(txin.prevout);
859 if (coin.IsSpent()) {
860 TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
861 continue;
863 const CScript& prevPubKey = coin.out.scriptPubKey;
864 const CAmount& amount = coin.out.nValue;
866 SignatureData sigdata;
867 // Only sign SIGHASH_SINGLE if there's a corresponding output:
868 if (!fHashSingle || (i < mtx.vout.size()))
869 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
870 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
872 UpdateTransaction(mtx, i, sigdata);
874 ScriptError serror = SCRIPT_ERR_OK;
875 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
876 TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
879 bool fComplete = vErrors.empty();
881 UniValue result(UniValue::VOBJ);
882 result.push_back(Pair("hex", EncodeHexTx(mtx)));
883 result.push_back(Pair("complete", fComplete));
884 if (!vErrors.empty()) {
885 result.push_back(Pair("errors", vErrors));
888 return result;
891 UniValue sendrawtransaction(const JSONRPCRequest& request)
893 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
894 throw std::runtime_error(
895 "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
896 "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
897 "\nAlso see createrawtransaction and signrawtransaction calls.\n"
898 "\nArguments:\n"
899 "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
900 "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
901 "\nResult:\n"
902 "\"hex\" (string) The transaction hash in hex\n"
903 "\nExamples:\n"
904 "\nCreate a transaction\n"
905 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
906 "Sign the transaction, and get back the hex\n"
907 + HelpExampleCli("signrawtransaction", "\"myhex\"") +
908 "\nSend the transaction (signed hex)\n"
909 + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
910 "\nAs a json rpc call\n"
911 + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
914 LOCK(cs_main);
915 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
917 // parse hex string from parameter
918 CMutableTransaction mtx;
919 if (!DecodeHexTx(mtx, request.params[0].get_str()))
920 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
921 CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
922 const uint256& hashTx = tx->GetHash();
924 CAmount nMaxRawTxFee = maxTxFee;
925 if (request.params.size() > 1 && request.params[1].get_bool())
926 nMaxRawTxFee = 0;
928 CCoinsViewCache &view = *pcoinsTip;
929 bool fHaveChain = false;
930 for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
931 const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
932 fHaveChain = !existingCoin.IsSpent();
934 bool fHaveMempool = mempool.exists(hashTx);
935 if (!fHaveMempool && !fHaveChain) {
936 // push to local node and sync with wallets
937 CValidationState state;
938 bool fMissingInputs;
939 bool fLimitFree = true;
940 if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, nullptr, false, nMaxRawTxFee)) {
941 if (state.IsInvalid()) {
942 throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
943 } else {
944 if (fMissingInputs) {
945 throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
947 throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
950 } else if (fHaveChain) {
951 throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
953 if(!g_connman)
954 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
956 CInv inv(MSG_TX, hashTx);
957 g_connman->ForEachNode([&inv](CNode* pnode)
959 pnode->PushInventory(inv);
961 return hashTx.GetHex();
964 static const CRPCCommand commands[] =
965 { // category name actor (function) okSafeMode
966 // --------------------- ------------------------ ----------------------- ----------
967 { "rawtransactions", "getrawtransaction", &getrawtransaction, true, {"txid","verbose"} },
968 { "rawtransactions", "createrawtransaction", &createrawtransaction, true, {"inputs","outputs","locktime","replaceable"} },
969 { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, {"hexstring"} },
970 { "rawtransactions", "decodescript", &decodescript, true, {"hexstring"} },
971 { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, {"hexstring","allowhighfees"} },
972 { "rawtransactions", "combinerawtransaction", &combinerawtransaction, true, {"txs"} },
973 { "rawtransactions", "signrawtransaction", &signrawtransaction, false, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
975 { "blockchain", "gettxoutproof", &gettxoutproof, true, {"txids", "blockhash"} },
976 { "blockchain", "verifytxoutproof", &verifytxoutproof, true, {"proof"} },
979 void RegisterRawTransactionRPCCommands(CRPCTable &t)
981 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
982 t.appendCommand(commands[vcidx].name, &commands[vcidx]);