[qa] TestNode: Add wait_until_stopped helper method
[bitcoinplatinum.git] / src / rpc / rawtransaction.cpp
blob27daefaf5ad1345f583336db98b8fa7732851b5a
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/safemode.h"
20 #include "rpc/server.h"
21 #include "script/script.h"
22 #include "script/script_error.h"
23 #include "script/sign.h"
24 #include "script/standard.h"
25 #include "txmempool.h"
26 #include "uint256.h"
27 #include "utilstrencodings.h"
28 #ifdef ENABLE_WALLET
29 #include "wallet/rpcwallet.h"
30 #include "wallet/wallet.h"
31 #endif
33 #include <stdint.h>
35 #include <univalue.h>
38 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
40 // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
42 // Blockchain contextual information (confirmations and blocktime) is not
43 // available to code in bitcoin-common, so we query them here and push the
44 // data into the returned UniValue.
45 TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
47 if (!hashBlock.IsNull()) {
48 entry.push_back(Pair("blockhash", hashBlock.GetHex()));
49 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
50 if (mi != mapBlockIndex.end() && (*mi).second) {
51 CBlockIndex* pindex = (*mi).second;
52 if (chainActive.Contains(pindex)) {
53 entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
54 entry.push_back(Pair("time", pindex->GetBlockTime()));
55 entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
57 else
58 entry.push_back(Pair("confirmations", 0));
63 UniValue getrawtransaction(const JSONRPCRequest& request)
65 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
66 throw std::runtime_error(
67 "getrawtransaction \"txid\" ( verbose )\n"
69 "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
70 "enabled, it also works for blockchain transactions.\n"
71 "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
73 "\nReturn the raw transaction data.\n"
74 "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
75 "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
77 "\nArguments:\n"
78 "1. \"txid\" (string, required) The transaction id\n"
79 "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
81 "\nResult (if verbose is not set or set to false):\n"
82 "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
84 "\nResult (if verbose is set to true):\n"
85 "{\n"
86 " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
87 " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
88 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
89 " \"size\" : n, (numeric) The serialized transaction size\n"
90 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
91 " \"version\" : n, (numeric) The version\n"
92 " \"locktime\" : ttt, (numeric) The lock time\n"
93 " \"vin\" : [ (array of json objects)\n"
94 " {\n"
95 " \"txid\": \"id\", (string) The transaction id\n"
96 " \"vout\": n, (numeric) \n"
97 " \"scriptSig\": { (json object) The script\n"
98 " \"asm\": \"asm\", (string) asm\n"
99 " \"hex\": \"hex\" (string) hex\n"
100 " },\n"
101 " \"sequence\": n (numeric) The script sequence number\n"
102 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
103 " }\n"
104 " ,...\n"
105 " ],\n"
106 " \"vout\" : [ (array of json objects)\n"
107 " {\n"
108 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
109 " \"n\" : n, (numeric) index\n"
110 " \"scriptPubKey\" : { (json object)\n"
111 " \"asm\" : \"asm\", (string) the asm\n"
112 " \"hex\" : \"hex\", (string) the hex\n"
113 " \"reqSigs\" : n, (numeric) The required sigs\n"
114 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
115 " \"addresses\" : [ (json array of string)\n"
116 " \"address\" (string) bitcoin address\n"
117 " ,...\n"
118 " ]\n"
119 " }\n"
120 " }\n"
121 " ,...\n"
122 " ],\n"
123 " \"blockhash\" : \"hash\", (string) the block hash\n"
124 " \"confirmations\" : n, (numeric) The confirmations\n"
125 " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
126 " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
127 "}\n"
129 "\nExamples:\n"
130 + HelpExampleCli("getrawtransaction", "\"mytxid\"")
131 + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
132 + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
135 LOCK(cs_main);
137 uint256 hash = ParseHashV(request.params[0], "parameter 1");
139 // Accept either a bool (true) or a num (>=1) to indicate verbose output.
140 bool fVerbose = false;
141 if (!request.params[1].isNull()) {
142 if (request.params[1].isNum()) {
143 if (request.params[1].get_int() != 0) {
144 fVerbose = true;
147 else if(request.params[1].isBool()) {
148 if(request.params[1].isTrue()) {
149 fVerbose = true;
152 else {
153 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean.");
157 CTransactionRef tx;
158 uint256 hashBlock;
159 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
160 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction"
161 : "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
162 ". Use gettransaction for wallet transactions.");
164 if (!fVerbose)
165 return EncodeHexTx(*tx, RPCSerializationFlags());
167 UniValue result(UniValue::VOBJ);
168 TxToJSON(*tx, hashBlock, result);
169 return result;
172 UniValue gettxoutproof(const JSONRPCRequest& request)
174 if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
175 throw std::runtime_error(
176 "gettxoutproof [\"txid\",...] ( blockhash )\n"
177 "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
178 "\nNOTE: By default this function only works sometimes. This is when there is an\n"
179 "unspent output in the utxo for this transaction. To make it always work,\n"
180 "you need to maintain a transaction index, using the -txindex command line option or\n"
181 "specify the block in which the transaction is included manually (by blockhash).\n"
182 "\nArguments:\n"
183 "1. \"txids\" (string) A json array of txids to filter\n"
184 " [\n"
185 " \"txid\" (string) A transaction hash\n"
186 " ,...\n"
187 " ]\n"
188 "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
189 "\nResult:\n"
190 "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
193 std::set<uint256> setTxids;
194 uint256 oneTxid;
195 UniValue txids = request.params[0].get_array();
196 for (unsigned int idx = 0; idx < txids.size(); idx++) {
197 const UniValue& txid = txids[idx];
198 if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
199 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
200 uint256 hash(uint256S(txid.get_str()));
201 if (setTxids.count(hash))
202 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
203 setTxids.insert(hash);
204 oneTxid = hash;
207 LOCK(cs_main);
209 CBlockIndex* pblockindex = nullptr;
211 uint256 hashBlock;
212 if (!request.params[1].isNull())
214 hashBlock = uint256S(request.params[1].get_str());
215 if (!mapBlockIndex.count(hashBlock))
216 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
217 pblockindex = mapBlockIndex[hashBlock];
218 } else {
219 // Loop through txids and try to find which block they're in. Exit loop once a block is found.
220 for (const auto& tx : setTxids) {
221 const Coin& coin = AccessByTxid(*pcoinsTip, tx);
222 if (!coin.IsSpent()) {
223 pblockindex = chainActive[coin.nHeight];
224 break;
229 if (pblockindex == nullptr)
231 CTransactionRef tx;
232 if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
233 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
234 if (!mapBlockIndex.count(hashBlock))
235 throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
236 pblockindex = mapBlockIndex[hashBlock];
239 CBlock block;
240 if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
241 throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
243 unsigned int ntxFound = 0;
244 for (const auto& tx : block.vtx)
245 if (setTxids.count(tx->GetHash()))
246 ntxFound++;
247 if (ntxFound != setTxids.size())
248 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
250 CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
251 CMerkleBlock mb(block, setTxids);
252 ssMB << mb;
253 std::string strHex = HexStr(ssMB.begin(), ssMB.end());
254 return strHex;
257 UniValue verifytxoutproof(const JSONRPCRequest& request)
259 if (request.fHelp || request.params.size() != 1)
260 throw std::runtime_error(
261 "verifytxoutproof \"proof\"\n"
262 "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
263 "and throwing an RPC error if the block is not in our best chain\n"
264 "\nArguments:\n"
265 "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
266 "\nResult:\n"
267 "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
270 CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
271 CMerkleBlock merkleBlock;
272 ssMB >> merkleBlock;
274 UniValue res(UniValue::VARR);
276 std::vector<uint256> vMatch;
277 std::vector<unsigned int> vIndex;
278 if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
279 return res;
281 LOCK(cs_main);
283 if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
284 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
286 for (const uint256& hash : vMatch)
287 res.push_back(hash.GetHex());
288 return res;
291 UniValue createrawtransaction(const JSONRPCRequest& request)
293 if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
294 throw std::runtime_error(
295 "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
296 "\nCreate a transaction spending the given inputs and creating new outputs.\n"
297 "Outputs can be addresses or data.\n"
298 "Returns hex-encoded raw transaction.\n"
299 "Note that the transaction's inputs are not signed, and\n"
300 "it is not stored in the wallet or transmitted to the network.\n"
302 "\nArguments:\n"
303 "1. \"inputs\" (array, required) A json array of json objects\n"
304 " [\n"
305 " {\n"
306 " \"txid\":\"id\", (string, required) The transaction id\n"
307 " \"vout\":n, (numeric, required) The output number\n"
308 " \"sequence\":n (numeric, optional) The sequence number\n"
309 " } \n"
310 " ,...\n"
311 " ]\n"
312 "2. \"outputs\" (object, required) a json object with outputs\n"
313 " {\n"
314 " \"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"
315 " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
316 " ,...\n"
317 " }\n"
318 "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
319 "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
320 " 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"
321 "\nResult:\n"
322 "\"transaction\" (string) hex string of the transaction\n"
324 "\nExamples:\n"
325 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
326 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
327 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
328 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
331 RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM}, true);
332 if (request.params[0].isNull() || request.params[1].isNull())
333 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
335 UniValue inputs = request.params[0].get_array();
336 UniValue sendTo = request.params[1].get_obj();
338 CMutableTransaction rawTx;
340 if (!request.params[2].isNull()) {
341 int64_t nLockTime = request.params[2].get_int64();
342 if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
343 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
344 rawTx.nLockTime = nLockTime;
347 bool rbfOptIn = request.params[3].isTrue();
349 for (unsigned int idx = 0; idx < inputs.size(); idx++) {
350 const UniValue& input = inputs[idx];
351 const UniValue& o = input.get_obj();
353 uint256 txid = ParseHashO(o, "txid");
355 const UniValue& vout_v = find_value(o, "vout");
356 if (!vout_v.isNum())
357 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
358 int nOutput = vout_v.get_int();
359 if (nOutput < 0)
360 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
362 uint32_t nSequence;
363 if (rbfOptIn) {
364 nSequence = MAX_BIP125_RBF_SEQUENCE;
365 } else if (rawTx.nLockTime) {
366 nSequence = std::numeric_limits<uint32_t>::max() - 1;
367 } else {
368 nSequence = std::numeric_limits<uint32_t>::max();
371 // set the sequence number if passed in the parameters object
372 const UniValue& sequenceObj = find_value(o, "sequence");
373 if (sequenceObj.isNum()) {
374 int64_t seqNr64 = sequenceObj.get_int64();
375 if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
376 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
377 } else {
378 nSequence = (uint32_t)seqNr64;
382 CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
384 rawTx.vin.push_back(in);
387 std::set<CBitcoinAddress> setAddress;
388 std::vector<std::string> addrList = sendTo.getKeys();
389 for (const std::string& name_ : addrList) {
391 if (name_ == "data") {
392 std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
394 CTxOut out(0, CScript() << OP_RETURN << data);
395 rawTx.vout.push_back(out);
396 } else {
397 CBitcoinAddress address(name_);
398 if (!address.IsValid())
399 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+name_);
401 if (setAddress.count(address))
402 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
403 setAddress.insert(address);
405 CScript scriptPubKey = GetScriptForDestination(address.Get());
406 CAmount nAmount = AmountFromValue(sendTo[name_]);
408 CTxOut out(nAmount, scriptPubKey);
409 rawTx.vout.push_back(out);
413 if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {
414 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
417 return EncodeHexTx(rawTx);
420 UniValue decoderawtransaction(const JSONRPCRequest& request)
422 if (request.fHelp || request.params.size() != 1)
423 throw std::runtime_error(
424 "decoderawtransaction \"hexstring\"\n"
425 "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
427 "\nArguments:\n"
428 "1. \"hexstring\" (string, required) The transaction hex string\n"
430 "\nResult:\n"
431 "{\n"
432 " \"txid\" : \"id\", (string) The transaction id\n"
433 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
434 " \"size\" : n, (numeric) The transaction size\n"
435 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
436 " \"version\" : n, (numeric) The version\n"
437 " \"locktime\" : ttt, (numeric) The lock time\n"
438 " \"vin\" : [ (array of json objects)\n"
439 " {\n"
440 " \"txid\": \"id\", (string) The transaction id\n"
441 " \"vout\": n, (numeric) The output number\n"
442 " \"scriptSig\": { (json object) The script\n"
443 " \"asm\": \"asm\", (string) asm\n"
444 " \"hex\": \"hex\" (string) hex\n"
445 " },\n"
446 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
447 " \"sequence\": n (numeric) The script sequence number\n"
448 " }\n"
449 " ,...\n"
450 " ],\n"
451 " \"vout\" : [ (array of json objects)\n"
452 " {\n"
453 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
454 " \"n\" : n, (numeric) index\n"
455 " \"scriptPubKey\" : { (json object)\n"
456 " \"asm\" : \"asm\", (string) the asm\n"
457 " \"hex\" : \"hex\", (string) the hex\n"
458 " \"reqSigs\" : n, (numeric) The required sigs\n"
459 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
460 " \"addresses\" : [ (json array of string)\n"
461 " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n"
462 " ,...\n"
463 " ]\n"
464 " }\n"
465 " }\n"
466 " ,...\n"
467 " ],\n"
468 "}\n"
470 "\nExamples:\n"
471 + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
472 + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
475 LOCK(cs_main);
476 RPCTypeCheck(request.params, {UniValue::VSTR});
478 CMutableTransaction mtx;
480 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
481 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
483 UniValue result(UniValue::VOBJ);
484 TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
486 return result;
489 UniValue decodescript(const JSONRPCRequest& request)
491 if (request.fHelp || request.params.size() != 1)
492 throw std::runtime_error(
493 "decodescript \"hexstring\"\n"
494 "\nDecode a hex-encoded script.\n"
495 "\nArguments:\n"
496 "1. \"hexstring\" (string) the hex encoded script\n"
497 "\nResult:\n"
498 "{\n"
499 " \"asm\":\"asm\", (string) Script public key\n"
500 " \"hex\":\"hex\", (string) hex encoded public key\n"
501 " \"type\":\"type\", (string) The output type\n"
502 " \"reqSigs\": n, (numeric) The required signatures\n"
503 " \"addresses\": [ (json array of string)\n"
504 " \"address\" (string) bitcoin address\n"
505 " ,...\n"
506 " ],\n"
507 " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
508 "}\n"
509 "\nExamples:\n"
510 + HelpExampleCli("decodescript", "\"hexstring\"")
511 + HelpExampleRpc("decodescript", "\"hexstring\"")
514 RPCTypeCheck(request.params, {UniValue::VSTR});
516 UniValue r(UniValue::VOBJ);
517 CScript script;
518 if (request.params[0].get_str().size() > 0){
519 std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
520 script = CScript(scriptData.begin(), scriptData.end());
521 } else {
522 // Empty scripts are valid
524 ScriptPubKeyToUniv(script, r, false);
526 UniValue type;
527 type = find_value(r, "type");
529 if (type.isStr() && type.get_str() != "scripthash") {
530 // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
531 // don't return the address for a P2SH of the P2SH.
532 r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
535 return r;
538 /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
539 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
541 UniValue entry(UniValue::VOBJ);
542 entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
543 entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
544 UniValue witness(UniValue::VARR);
545 for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
546 witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
548 entry.push_back(Pair("witness", witness));
549 entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
550 entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
551 entry.push_back(Pair("error", strMessage));
552 vErrorsRet.push_back(entry);
555 UniValue combinerawtransaction(const JSONRPCRequest& request)
558 if (request.fHelp || request.params.size() != 1)
559 throw std::runtime_error(
560 "combinerawtransaction [\"hexstring\",...]\n"
561 "\nCombine multiple partially signed transactions into one transaction.\n"
562 "The combined transaction may be another partially signed transaction or a \n"
563 "fully signed transaction."
565 "\nArguments:\n"
566 "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
567 " [\n"
568 " \"hexstring\" (string) A transaction hash\n"
569 " ,...\n"
570 " ]\n"
572 "\nResult:\n"
573 "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
575 "\nExamples:\n"
576 + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
580 UniValue txs = request.params[0].get_array();
581 std::vector<CMutableTransaction> txVariants(txs.size());
583 for (unsigned int idx = 0; idx < txs.size(); idx++) {
584 if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
585 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
589 if (txVariants.empty()) {
590 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
593 // mergedTx will end up with all the signatures; it
594 // starts as a clone of the rawtx:
595 CMutableTransaction mergedTx(txVariants[0]);
597 // Fetch previous transactions (inputs):
598 CCoinsView viewDummy;
599 CCoinsViewCache view(&viewDummy);
601 LOCK(cs_main);
602 LOCK(mempool.cs);
603 CCoinsViewCache &viewChain = *pcoinsTip;
604 CCoinsViewMemPool viewMempool(&viewChain, mempool);
605 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
607 for (const CTxIn& txin : mergedTx.vin) {
608 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
611 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
614 // Use CTransaction for the constant parts of the
615 // transaction to avoid rehashing.
616 const CTransaction txConst(mergedTx);
617 // Sign what we can:
618 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
619 CTxIn& txin = mergedTx.vin[i];
620 const Coin& coin = view.AccessCoin(txin.prevout);
621 if (coin.IsSpent()) {
622 throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
624 const CScript& prevPubKey = coin.out.scriptPubKey;
625 const CAmount& amount = coin.out.nValue;
627 SignatureData sigdata;
629 // ... and merge in other signatures:
630 for (const CMutableTransaction& txv : txVariants) {
631 if (txv.vin.size() > i) {
632 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
636 UpdateTransaction(mergedTx, i, sigdata);
639 return EncodeHexTx(mergedTx);
642 UniValue signrawtransaction(const JSONRPCRequest& request)
644 #ifdef ENABLE_WALLET
645 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
646 #endif
648 if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
649 throw std::runtime_error(
650 "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
651 "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
652 "The second optional argument (may be null) is an array of previous transaction outputs that\n"
653 "this transaction depends on but may not yet be in the block chain.\n"
654 "The third optional argument (may be null) is an array of base58-encoded private\n"
655 "keys that, if given, will be the only keys used to sign the transaction.\n"
656 #ifdef ENABLE_WALLET
657 + HelpRequiringPassphrase(pwallet) + "\n"
658 #endif
660 "\nArguments:\n"
661 "1. \"hexstring\" (string, required) The transaction hex string\n"
662 "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
663 " [ (json array of json objects, or 'null' if none provided)\n"
664 " {\n"
665 " \"txid\":\"id\", (string, required) The transaction id\n"
666 " \"vout\":n, (numeric, required) The output number\n"
667 " \"scriptPubKey\": \"hex\", (string, required) script key\n"
668 " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
669 " \"amount\": value (numeric, required) The amount spent\n"
670 " }\n"
671 " ,...\n"
672 " ]\n"
673 "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
674 " [ (json array of strings, or 'null' if none provided)\n"
675 " \"privatekey\" (string) private key in base58-encoding\n"
676 " ,...\n"
677 " ]\n"
678 "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
679 " \"ALL\"\n"
680 " \"NONE\"\n"
681 " \"SINGLE\"\n"
682 " \"ALL|ANYONECANPAY\"\n"
683 " \"NONE|ANYONECANPAY\"\n"
684 " \"SINGLE|ANYONECANPAY\"\n"
686 "\nResult:\n"
687 "{\n"
688 " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
689 " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
690 " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
691 " {\n"
692 " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
693 " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
694 " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
695 " \"sequence\" : n, (numeric) Script sequence number\n"
696 " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
697 " }\n"
698 " ,...\n"
699 " ]\n"
700 "}\n"
702 "\nExamples:\n"
703 + HelpExampleCli("signrawtransaction", "\"myhex\"")
704 + HelpExampleRpc("signrawtransaction", "\"myhex\"")
707 ObserveSafeMode();
708 #ifdef ENABLE_WALLET
709 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
710 #else
711 LOCK(cs_main);
712 #endif
713 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
715 CMutableTransaction mtx;
716 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
717 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
719 // Fetch previous transactions (inputs):
720 CCoinsView viewDummy;
721 CCoinsViewCache view(&viewDummy);
723 LOCK(mempool.cs);
724 CCoinsViewCache &viewChain = *pcoinsTip;
725 CCoinsViewMemPool viewMempool(&viewChain, mempool);
726 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
728 for (const CTxIn& txin : mtx.vin) {
729 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
732 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
735 bool fGivenKeys = false;
736 CBasicKeyStore tempKeystore;
737 if (!request.params[2].isNull()) {
738 fGivenKeys = true;
739 UniValue keys = request.params[2].get_array();
740 for (unsigned int idx = 0; idx < keys.size(); idx++) {
741 UniValue k = keys[idx];
742 CBitcoinSecret vchSecret;
743 bool fGood = vchSecret.SetString(k.get_str());
744 if (!fGood)
745 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
746 CKey key = vchSecret.GetKey();
747 if (!key.IsValid())
748 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
749 tempKeystore.AddKey(key);
752 #ifdef ENABLE_WALLET
753 else if (pwallet) {
754 EnsureWalletIsUnlocked(pwallet);
756 #endif
758 // Add previous txouts given in the RPC call:
759 if (!request.params[1].isNull()) {
760 UniValue prevTxs = request.params[1].get_array();
761 for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
762 const UniValue& p = prevTxs[idx];
763 if (!p.isObject())
764 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
766 UniValue prevOut = p.get_obj();
768 RPCTypeCheckObj(prevOut,
770 {"txid", UniValueType(UniValue::VSTR)},
771 {"vout", UniValueType(UniValue::VNUM)},
772 {"scriptPubKey", UniValueType(UniValue::VSTR)},
775 uint256 txid = ParseHashO(prevOut, "txid");
777 int nOut = find_value(prevOut, "vout").get_int();
778 if (nOut < 0)
779 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
781 COutPoint out(txid, nOut);
782 std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
783 CScript scriptPubKey(pkData.begin(), pkData.end());
786 const Coin& coin = view.AccessCoin(out);
787 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
788 std::string err("Previous output scriptPubKey mismatch:\n");
789 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
790 ScriptToAsmStr(scriptPubKey);
791 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
793 Coin newcoin;
794 newcoin.out.scriptPubKey = scriptPubKey;
795 newcoin.out.nValue = 0;
796 if (prevOut.exists("amount")) {
797 newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
799 newcoin.nHeight = 1;
800 view.AddCoin(out, std::move(newcoin), true);
803 // if redeemScript given and not using the local wallet (private keys
804 // given), add redeemScript to the tempKeystore so it can be signed:
805 if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
806 RPCTypeCheckObj(prevOut,
808 {"txid", UniValueType(UniValue::VSTR)},
809 {"vout", UniValueType(UniValue::VNUM)},
810 {"scriptPubKey", UniValueType(UniValue::VSTR)},
811 {"redeemScript", UniValueType(UniValue::VSTR)},
813 UniValue v = find_value(prevOut, "redeemScript");
814 if (!v.isNull()) {
815 std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
816 CScript redeemScript(rsData.begin(), rsData.end());
817 tempKeystore.AddCScript(redeemScript);
823 #ifdef ENABLE_WALLET
824 const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
825 #else
826 const CKeyStore& keystore = tempKeystore;
827 #endif
829 int nHashType = SIGHASH_ALL;
830 if (!request.params[3].isNull()) {
831 static std::map<std::string, int> mapSigHashValues = {
832 {std::string("ALL"), int(SIGHASH_ALL)},
833 {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
834 {std::string("NONE"), int(SIGHASH_NONE)},
835 {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
836 {std::string("SINGLE"), int(SIGHASH_SINGLE)},
837 {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
839 std::string strHashType = request.params[3].get_str();
840 if (mapSigHashValues.count(strHashType))
841 nHashType = mapSigHashValues[strHashType];
842 else
843 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
846 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
848 // Script verification errors
849 UniValue vErrors(UniValue::VARR);
851 // Use CTransaction for the constant parts of the
852 // transaction to avoid rehashing.
853 const CTransaction txConst(mtx);
854 // Sign what we can:
855 for (unsigned int i = 0; i < mtx.vin.size(); i++) {
856 CTxIn& txin = mtx.vin[i];
857 const Coin& coin = view.AccessCoin(txin.prevout);
858 if (coin.IsSpent()) {
859 TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
860 continue;
862 const CScript& prevPubKey = coin.out.scriptPubKey;
863 const CAmount& amount = coin.out.nValue;
865 SignatureData sigdata;
866 // Only sign SIGHASH_SINGLE if there's a corresponding output:
867 if (!fHashSingle || (i < mtx.vout.size()))
868 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
869 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
871 UpdateTransaction(mtx, i, sigdata);
873 ScriptError serror = SCRIPT_ERR_OK;
874 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
875 TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
878 bool fComplete = vErrors.empty();
880 UniValue result(UniValue::VOBJ);
881 result.push_back(Pair("hex", EncodeHexTx(mtx)));
882 result.push_back(Pair("complete", fComplete));
883 if (!vErrors.empty()) {
884 result.push_back(Pair("errors", vErrors));
887 return result;
890 UniValue sendrawtransaction(const JSONRPCRequest& request)
892 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
893 throw std::runtime_error(
894 "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
895 "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
896 "\nAlso see createrawtransaction and signrawtransaction calls.\n"
897 "\nArguments:\n"
898 "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
899 "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
900 "\nResult:\n"
901 "\"hex\" (string) The transaction hash in hex\n"
902 "\nExamples:\n"
903 "\nCreate a transaction\n"
904 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
905 "Sign the transaction, and get back the hex\n"
906 + HelpExampleCli("signrawtransaction", "\"myhex\"") +
907 "\nSend the transaction (signed hex)\n"
908 + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
909 "\nAs a json rpc call\n"
910 + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
913 ObserveSafeMode();
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[1].isNull() && 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) argNames
966 // --------------------- ------------------------ ----------------------- ----------
967 { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose"} },
968 { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} },
969 { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring"} },
970 { "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
971 { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees"} },
972 { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
973 { "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
975 { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
976 { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
979 void RegisterRawTransactionRPCCommands(CRPCTable &t)
981 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
982 t.appendCommand(commands[vcidx].name, &commands[vcidx]);