Merge #11683: tests: Remove unused mininode functions {ser,deser}_int_vector(......
[bitcoinplatinum.git] / src / rpc / rawtransaction.cpp
blob3aff1e9fbff31e63518e09f9cd79311e022f5ffc
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 <validationinterface.h>
15 #include <merkleblock.h>
16 #include <net.h>
17 #include <policy/policy.h>
18 #include <policy/rbf.h>
19 #include <primitives/transaction.h>
20 #include <rpc/safemode.h>
21 #include <rpc/server.h>
22 #include <script/script.h>
23 #include <script/script_error.h>
24 #include <script/sign.h>
25 #include <script/standard.h>
26 #include <txmempool.h>
27 #include <uint256.h>
28 #include <utilstrencodings.h>
29 #ifdef ENABLE_WALLET
30 #include <wallet/rpcwallet.h>
31 #include <wallet/wallet.h>
32 #endif
34 #include <future>
35 #include <stdint.h>
37 #include <univalue.h>
40 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
42 // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
44 // Blockchain contextual information (confirmations and blocktime) is not
45 // available to code in bitcoin-common, so we query them here and push the
46 // data into the returned UniValue.
47 TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
49 if (!hashBlock.IsNull()) {
50 entry.push_back(Pair("blockhash", hashBlock.GetHex()));
51 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
52 if (mi != mapBlockIndex.end() && (*mi).second) {
53 CBlockIndex* pindex = (*mi).second;
54 if (chainActive.Contains(pindex)) {
55 entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
56 entry.push_back(Pair("time", pindex->GetBlockTime()));
57 entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
59 else
60 entry.push_back(Pair("confirmations", 0));
65 UniValue getrawtransaction(const JSONRPCRequest& request)
67 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
68 throw std::runtime_error(
69 "getrawtransaction \"txid\" ( verbose )\n"
71 "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
72 "enabled, it also works for blockchain transactions.\n"
73 "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
75 "\nReturn the raw transaction data.\n"
76 "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
77 "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
79 "\nArguments:\n"
80 "1. \"txid\" (string, required) The transaction id\n"
81 "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
83 "\nResult (if verbose is not set or set to false):\n"
84 "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
86 "\nResult (if verbose is set to true):\n"
87 "{\n"
88 " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
89 " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
90 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
91 " \"size\" : n, (numeric) The serialized transaction size\n"
92 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
93 " \"version\" : n, (numeric) The version\n"
94 " \"locktime\" : ttt, (numeric) The lock time\n"
95 " \"vin\" : [ (array of json objects)\n"
96 " {\n"
97 " \"txid\": \"id\", (string) The transaction id\n"
98 " \"vout\": n, (numeric) \n"
99 " \"scriptSig\": { (json object) The script\n"
100 " \"asm\": \"asm\", (string) asm\n"
101 " \"hex\": \"hex\" (string) hex\n"
102 " },\n"
103 " \"sequence\": n (numeric) The script sequence number\n"
104 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
105 " }\n"
106 " ,...\n"
107 " ],\n"
108 " \"vout\" : [ (array of json objects)\n"
109 " {\n"
110 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
111 " \"n\" : n, (numeric) index\n"
112 " \"scriptPubKey\" : { (json object)\n"
113 " \"asm\" : \"asm\", (string) the asm\n"
114 " \"hex\" : \"hex\", (string) the hex\n"
115 " \"reqSigs\" : n, (numeric) The required sigs\n"
116 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
117 " \"addresses\" : [ (json array of string)\n"
118 " \"address\" (string) bitcoin address\n"
119 " ,...\n"
120 " ]\n"
121 " }\n"
122 " }\n"
123 " ,...\n"
124 " ],\n"
125 " \"blockhash\" : \"hash\", (string) the block hash\n"
126 " \"confirmations\" : n, (numeric) The confirmations\n"
127 " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
128 " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
129 "}\n"
131 "\nExamples:\n"
132 + HelpExampleCli("getrawtransaction", "\"mytxid\"")
133 + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
134 + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
137 LOCK(cs_main);
139 uint256 hash = ParseHashV(request.params[0], "parameter 1");
141 // Accept either a bool (true) or a num (>=1) to indicate verbose output.
142 bool fVerbose = false;
143 if (!request.params[1].isNull()) {
144 if (request.params[1].isNum()) {
145 if (request.params[1].get_int() != 0) {
146 fVerbose = true;
149 else if(request.params[1].isBool()) {
150 if(request.params[1].isTrue()) {
151 fVerbose = true;
154 else {
155 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean.");
159 CTransactionRef tx;
160 uint256 hashBlock;
161 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
162 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction"
163 : "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
164 ". Use gettransaction for wallet transactions.");
166 if (!fVerbose)
167 return EncodeHexTx(*tx, RPCSerializationFlags());
169 UniValue result(UniValue::VOBJ);
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[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[3].isTrue();
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<CTxDestination> destinations;
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 CTxDestination destination = DecodeDestination(name_);
400 if (!IsValidDestination(destination)) {
401 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);
404 if (!destinations.insert(destination).second) {
405 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
408 CScript scriptPubKey = GetScriptForDestination(destination);
409 CAmount nAmount = AmountFromValue(sendTo[name_]);
411 CTxOut out(nAmount, scriptPubKey);
412 rawTx.vout.push_back(out);
416 if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {
417 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
420 return EncodeHexTx(rawTx);
423 UniValue decoderawtransaction(const JSONRPCRequest& request)
425 if (request.fHelp || request.params.size() != 1)
426 throw std::runtime_error(
427 "decoderawtransaction \"hexstring\"\n"
428 "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
430 "\nArguments:\n"
431 "1. \"hexstring\" (string, required) The transaction hex string\n"
433 "\nResult:\n"
434 "{\n"
435 " \"txid\" : \"id\", (string) The transaction id\n"
436 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
437 " \"size\" : n, (numeric) The transaction size\n"
438 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
439 " \"version\" : n, (numeric) The version\n"
440 " \"locktime\" : ttt, (numeric) The lock time\n"
441 " \"vin\" : [ (array of json objects)\n"
442 " {\n"
443 " \"txid\": \"id\", (string) The transaction id\n"
444 " \"vout\": n, (numeric) The output number\n"
445 " \"scriptSig\": { (json object) The script\n"
446 " \"asm\": \"asm\", (string) asm\n"
447 " \"hex\": \"hex\" (string) hex\n"
448 " },\n"
449 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
450 " \"sequence\": n (numeric) The script sequence number\n"
451 " }\n"
452 " ,...\n"
453 " ],\n"
454 " \"vout\" : [ (array of json objects)\n"
455 " {\n"
456 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
457 " \"n\" : n, (numeric) index\n"
458 " \"scriptPubKey\" : { (json object)\n"
459 " \"asm\" : \"asm\", (string) the asm\n"
460 " \"hex\" : \"hex\", (string) the hex\n"
461 " \"reqSigs\" : n, (numeric) The required sigs\n"
462 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
463 " \"addresses\" : [ (json array of string)\n"
464 " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n"
465 " ,...\n"
466 " ]\n"
467 " }\n"
468 " }\n"
469 " ,...\n"
470 " ],\n"
471 "}\n"
473 "\nExamples:\n"
474 + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
475 + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
478 LOCK(cs_main);
479 RPCTypeCheck(request.params, {UniValue::VSTR});
481 CMutableTransaction mtx;
483 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
484 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
486 UniValue result(UniValue::VOBJ);
487 TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
489 return result;
492 UniValue decodescript(const JSONRPCRequest& request)
494 if (request.fHelp || request.params.size() != 1)
495 throw std::runtime_error(
496 "decodescript \"hexstring\"\n"
497 "\nDecode a hex-encoded script.\n"
498 "\nArguments:\n"
499 "1. \"hexstring\" (string) the hex encoded script\n"
500 "\nResult:\n"
501 "{\n"
502 " \"asm\":\"asm\", (string) Script public key\n"
503 " \"hex\":\"hex\", (string) hex encoded public key\n"
504 " \"type\":\"type\", (string) The output type\n"
505 " \"reqSigs\": n, (numeric) The required signatures\n"
506 " \"addresses\": [ (json array of string)\n"
507 " \"address\" (string) bitcoin address\n"
508 " ,...\n"
509 " ],\n"
510 " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
511 "}\n"
512 "\nExamples:\n"
513 + HelpExampleCli("decodescript", "\"hexstring\"")
514 + HelpExampleRpc("decodescript", "\"hexstring\"")
517 RPCTypeCheck(request.params, {UniValue::VSTR});
519 UniValue r(UniValue::VOBJ);
520 CScript script;
521 if (request.params[0].get_str().size() > 0){
522 std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
523 script = CScript(scriptData.begin(), scriptData.end());
524 } else {
525 // Empty scripts are valid
527 ScriptPubKeyToUniv(script, r, false);
529 UniValue type;
530 type = find_value(r, "type");
532 if (type.isStr() && type.get_str() != "scripthash") {
533 // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
534 // don't return the address for a P2SH of the P2SH.
535 r.push_back(Pair("p2sh", EncodeDestination(CScriptID(script))));
538 return r;
541 /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
542 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
544 UniValue entry(UniValue::VOBJ);
545 entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
546 entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
547 UniValue witness(UniValue::VARR);
548 for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
549 witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
551 entry.push_back(Pair("witness", witness));
552 entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
553 entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
554 entry.push_back(Pair("error", strMessage));
555 vErrorsRet.push_back(entry);
558 UniValue combinerawtransaction(const JSONRPCRequest& request)
561 if (request.fHelp || request.params.size() != 1)
562 throw std::runtime_error(
563 "combinerawtransaction [\"hexstring\",...]\n"
564 "\nCombine multiple partially signed transactions into one transaction.\n"
565 "The combined transaction may be another partially signed transaction or a \n"
566 "fully signed transaction."
568 "\nArguments:\n"
569 "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
570 " [\n"
571 " \"hexstring\" (string) A transaction hash\n"
572 " ,...\n"
573 " ]\n"
575 "\nResult:\n"
576 "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
578 "\nExamples:\n"
579 + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
583 UniValue txs = request.params[0].get_array();
584 std::vector<CMutableTransaction> txVariants(txs.size());
586 for (unsigned int idx = 0; idx < txs.size(); idx++) {
587 if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
588 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
592 if (txVariants.empty()) {
593 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
596 // mergedTx will end up with all the signatures; it
597 // starts as a clone of the rawtx:
598 CMutableTransaction mergedTx(txVariants[0]);
600 // Fetch previous transactions (inputs):
601 CCoinsView viewDummy;
602 CCoinsViewCache view(&viewDummy);
604 LOCK(cs_main);
605 LOCK(mempool.cs);
606 CCoinsViewCache &viewChain = *pcoinsTip;
607 CCoinsViewMemPool viewMempool(&viewChain, mempool);
608 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
610 for (const CTxIn& txin : mergedTx.vin) {
611 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
614 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
617 // Use CTransaction for the constant parts of the
618 // transaction to avoid rehashing.
619 const CTransaction txConst(mergedTx);
620 // Sign what we can:
621 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
622 CTxIn& txin = mergedTx.vin[i];
623 const Coin& coin = view.AccessCoin(txin.prevout);
624 if (coin.IsSpent()) {
625 throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
627 const CScript& prevPubKey = coin.out.scriptPubKey;
628 const CAmount& amount = coin.out.nValue;
630 SignatureData sigdata;
632 // ... and merge in other signatures:
633 for (const CMutableTransaction& txv : txVariants) {
634 if (txv.vin.size() > i) {
635 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
639 UpdateTransaction(mergedTx, i, sigdata);
642 return EncodeHexTx(mergedTx);
645 UniValue signrawtransaction(const JSONRPCRequest& request)
647 #ifdef ENABLE_WALLET
648 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
649 #endif
651 if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
652 throw std::runtime_error(
653 "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
654 "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
655 "The second optional argument (may be null) is an array of previous transaction outputs that\n"
656 "this transaction depends on but may not yet be in the block chain.\n"
657 "The third optional argument (may be null) is an array of base58-encoded private\n"
658 "keys that, if given, will be the only keys used to sign the transaction.\n"
659 #ifdef ENABLE_WALLET
660 + HelpRequiringPassphrase(pwallet) + "\n"
661 #endif
663 "\nArguments:\n"
664 "1. \"hexstring\" (string, required) The transaction hex string\n"
665 "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
666 " [ (json array of json objects, or 'null' if none provided)\n"
667 " {\n"
668 " \"txid\":\"id\", (string, required) The transaction id\n"
669 " \"vout\":n, (numeric, required) The output number\n"
670 " \"scriptPubKey\": \"hex\", (string, required) script key\n"
671 " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
672 " \"amount\": value (numeric, required) The amount spent\n"
673 " }\n"
674 " ,...\n"
675 " ]\n"
676 "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
677 " [ (json array of strings, or 'null' if none provided)\n"
678 " \"privatekey\" (string) private key in base58-encoding\n"
679 " ,...\n"
680 " ]\n"
681 "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
682 " \"ALL\"\n"
683 " \"NONE\"\n"
684 " \"SINGLE\"\n"
685 " \"ALL|ANYONECANPAY\"\n"
686 " \"NONE|ANYONECANPAY\"\n"
687 " \"SINGLE|ANYONECANPAY\"\n"
689 "\nResult:\n"
690 "{\n"
691 " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
692 " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
693 " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
694 " {\n"
695 " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
696 " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
697 " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
698 " \"sequence\" : n, (numeric) Script sequence number\n"
699 " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
700 " }\n"
701 " ,...\n"
702 " ]\n"
703 "}\n"
705 "\nExamples:\n"
706 + HelpExampleCli("signrawtransaction", "\"myhex\"")
707 + HelpExampleRpc("signrawtransaction", "\"myhex\"")
710 ObserveSafeMode();
711 #ifdef ENABLE_WALLET
712 LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
713 #else
714 LOCK(cs_main);
715 #endif
716 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
718 CMutableTransaction mtx;
719 if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
720 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
722 // Fetch previous transactions (inputs):
723 CCoinsView viewDummy;
724 CCoinsViewCache view(&viewDummy);
726 LOCK(mempool.cs);
727 CCoinsViewCache &viewChain = *pcoinsTip;
728 CCoinsViewMemPool viewMempool(&viewChain, mempool);
729 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
731 for (const CTxIn& txin : mtx.vin) {
732 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
735 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
738 bool fGivenKeys = false;
739 CBasicKeyStore tempKeystore;
740 if (!request.params[2].isNull()) {
741 fGivenKeys = true;
742 UniValue keys = request.params[2].get_array();
743 for (unsigned int idx = 0; idx < keys.size(); idx++) {
744 UniValue k = keys[idx];
745 CBitcoinSecret vchSecret;
746 bool fGood = vchSecret.SetString(k.get_str());
747 if (!fGood)
748 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
749 CKey key = vchSecret.GetKey();
750 if (!key.IsValid())
751 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
752 tempKeystore.AddKey(key);
755 #ifdef ENABLE_WALLET
756 else if (pwallet) {
757 EnsureWalletIsUnlocked(pwallet);
759 #endif
761 // Add previous txouts given in the RPC call:
762 if (!request.params[1].isNull()) {
763 UniValue prevTxs = request.params[1].get_array();
764 for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
765 const UniValue& p = prevTxs[idx];
766 if (!p.isObject())
767 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
769 UniValue prevOut = p.get_obj();
771 RPCTypeCheckObj(prevOut,
773 {"txid", UniValueType(UniValue::VSTR)},
774 {"vout", UniValueType(UniValue::VNUM)},
775 {"scriptPubKey", UniValueType(UniValue::VSTR)},
778 uint256 txid = ParseHashO(prevOut, "txid");
780 int nOut = find_value(prevOut, "vout").get_int();
781 if (nOut < 0)
782 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
784 COutPoint out(txid, nOut);
785 std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
786 CScript scriptPubKey(pkData.begin(), pkData.end());
789 const Coin& coin = view.AccessCoin(out);
790 if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
791 std::string err("Previous output scriptPubKey mismatch:\n");
792 err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
793 ScriptToAsmStr(scriptPubKey);
794 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
796 Coin newcoin;
797 newcoin.out.scriptPubKey = scriptPubKey;
798 newcoin.out.nValue = 0;
799 if (prevOut.exists("amount")) {
800 newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
802 newcoin.nHeight = 1;
803 view.AddCoin(out, std::move(newcoin), true);
806 // if redeemScript given and not using the local wallet (private keys
807 // given), add redeemScript to the tempKeystore so it can be signed:
808 if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
809 RPCTypeCheckObj(prevOut,
811 {"txid", UniValueType(UniValue::VSTR)},
812 {"vout", UniValueType(UniValue::VNUM)},
813 {"scriptPubKey", UniValueType(UniValue::VSTR)},
814 {"redeemScript", UniValueType(UniValue::VSTR)},
816 UniValue v = find_value(prevOut, "redeemScript");
817 if (!v.isNull()) {
818 std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
819 CScript redeemScript(rsData.begin(), rsData.end());
820 tempKeystore.AddCScript(redeemScript);
826 #ifdef ENABLE_WALLET
827 const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
828 #else
829 const CKeyStore& keystore = tempKeystore;
830 #endif
832 int nHashType = SIGHASH_ALL;
833 if (!request.params[3].isNull()) {
834 static std::map<std::string, int> mapSigHashValues = {
835 {std::string("ALL"), int(SIGHASH_ALL)},
836 {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
837 {std::string("NONE"), int(SIGHASH_NONE)},
838 {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
839 {std::string("SINGLE"), int(SIGHASH_SINGLE)},
840 {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
842 std::string strHashType = request.params[3].get_str();
843 if (mapSigHashValues.count(strHashType))
844 nHashType = mapSigHashValues[strHashType];
845 else
846 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
849 bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
851 // Script verification errors
852 UniValue vErrors(UniValue::VARR);
854 // Use CTransaction for the constant parts of the
855 // transaction to avoid rehashing.
856 const CTransaction txConst(mtx);
857 // Sign what we can:
858 for (unsigned int i = 0; i < mtx.vin.size(); i++) {
859 CTxIn& txin = mtx.vin[i];
860 const Coin& coin = view.AccessCoin(txin.prevout);
861 if (coin.IsSpent()) {
862 TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
863 continue;
865 const CScript& prevPubKey = coin.out.scriptPubKey;
866 const CAmount& amount = coin.out.nValue;
868 SignatureData sigdata;
869 // Only sign SIGHASH_SINGLE if there's a corresponding output:
870 if (!fHashSingle || (i < mtx.vout.size()))
871 ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
872 sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
874 UpdateTransaction(mtx, i, sigdata);
876 ScriptError serror = SCRIPT_ERR_OK;
877 if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
878 if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
879 // Unable to sign input and verification failed (possible attempt to partially sign).
880 TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");
881 } else {
882 TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
886 bool fComplete = vErrors.empty();
888 UniValue result(UniValue::VOBJ);
889 result.push_back(Pair("hex", EncodeHexTx(mtx)));
890 result.push_back(Pair("complete", fComplete));
891 if (!vErrors.empty()) {
892 result.push_back(Pair("errors", vErrors));
895 return result;
898 UniValue sendrawtransaction(const JSONRPCRequest& request)
900 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
901 throw std::runtime_error(
902 "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
903 "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
904 "\nAlso see createrawtransaction and signrawtransaction calls.\n"
905 "\nArguments:\n"
906 "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
907 "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
908 "\nResult:\n"
909 "\"hex\" (string) The transaction hash in hex\n"
910 "\nExamples:\n"
911 "\nCreate a transaction\n"
912 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
913 "Sign the transaction, and get back the hex\n"
914 + HelpExampleCli("signrawtransaction", "\"myhex\"") +
915 "\nSend the transaction (signed hex)\n"
916 + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
917 "\nAs a json rpc call\n"
918 + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
921 ObserveSafeMode();
923 std::promise<void> promise;
925 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
927 // parse hex string from parameter
928 CMutableTransaction mtx;
929 if (!DecodeHexTx(mtx, request.params[0].get_str()))
930 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
931 CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
932 const uint256& hashTx = tx->GetHash();
934 CAmount nMaxRawTxFee = maxTxFee;
935 if (!request.params[1].isNull() && request.params[1].get_bool())
936 nMaxRawTxFee = 0;
938 { // cs_main scope
939 LOCK(cs_main);
940 CCoinsViewCache &view = *pcoinsTip;
941 bool fHaveChain = false;
942 for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
943 const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
944 fHaveChain = !existingCoin.IsSpent();
946 bool fHaveMempool = mempool.exists(hashTx);
947 if (!fHaveMempool && !fHaveChain) {
948 // push to local node and sync with wallets
949 CValidationState state;
950 bool fMissingInputs;
951 if (!AcceptToMemoryPool(mempool, state, std::move(tx), &fMissingInputs,
952 nullptr /* plTxnReplaced */, false /* bypass_limits */, nMaxRawTxFee)) {
953 if (state.IsInvalid()) {
954 throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
955 } else {
956 if (fMissingInputs) {
957 throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
959 throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
961 } else {
962 // If wallet is enabled, ensure that the wallet has been made aware
963 // of the new transaction prior to returning. This prevents a race
964 // where a user might call sendrawtransaction with a transaction
965 // to/from their wallet, immediately call some wallet RPC, and get
966 // a stale result because callbacks have not yet been processed.
967 CallFunctionInValidationInterfaceQueue([&promise] {
968 promise.set_value();
971 } else if (fHaveChain) {
972 throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
973 } else {
974 // Make sure we don't block forever if re-sending
975 // a transaction already in mempool.
976 promise.set_value();
979 } // cs_main
981 promise.get_future().wait();
983 if(!g_connman)
984 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
986 CInv inv(MSG_TX, hashTx);
987 g_connman->ForEachNode([&inv](CNode* pnode)
989 pnode->PushInventory(inv);
992 return hashTx.GetHex();
995 static const CRPCCommand commands[] =
996 { // category name actor (function) argNames
997 // --------------------- ------------------------ ----------------------- ----------
998 { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose"} },
999 { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} },
1000 { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring"} },
1001 { "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
1002 { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees"} },
1003 { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
1004 { "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
1006 { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
1007 { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
1010 void RegisterRawTransactionRPCCommands(CRPCTable &t)
1012 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1013 t.appendCommand(commands[vcidx].name, &commands[vcidx]);