1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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.
9 #include <consensus/validation.h>
13 #include <validation.h>
14 #include <validationinterface.h>
15 #include <merkleblock.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>
28 #include <utilstrencodings.h>
30 #include <wallet/rpcwallet.h>
31 #include <wallet/wallet.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()));
60 entry
.push_back(Pair("confirmations", 0));
65 UniValue
getrawtransaction(const JSONRPCRequest
& request
)
67 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 3)
68 throw std::runtime_error(
69 "getrawtransaction \"txid\" ( verbose \"blockhash\" )\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. If the block which contains the transaction\n"
73 "is known, its hash can be provided even for nodes without -txindex. Note that if a blockhash is\n"
74 "provided, only that block will be searched and if the transaction is in the mempool or other\n"
75 "blocks, or if this node does not have the given block available, the transaction will not be found.\n"
76 "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
78 "\nReturn the raw transaction data.\n"
79 "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
80 "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
83 "1. \"txid\" (string, required) The transaction id\n"
84 "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
85 "3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
87 "\nResult (if verbose is not set or set to false):\n"
88 "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
90 "\nResult (if verbose is set to true):\n"
92 " \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
93 " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
94 " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
95 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
96 " \"size\" : n, (numeric) The serialized transaction size\n"
97 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
98 " \"version\" : n, (numeric) The version\n"
99 " \"locktime\" : ttt, (numeric) The lock time\n"
100 " \"vin\" : [ (array of json objects)\n"
102 " \"txid\": \"id\", (string) The transaction id\n"
103 " \"vout\": n, (numeric) \n"
104 " \"scriptSig\": { (json object) The script\n"
105 " \"asm\": \"asm\", (string) asm\n"
106 " \"hex\": \"hex\" (string) hex\n"
108 " \"sequence\": n (numeric) The script sequence number\n"
109 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
113 " \"vout\" : [ (array of json objects)\n"
115 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT
+ "\n"
116 " \"n\" : n, (numeric) index\n"
117 " \"scriptPubKey\" : { (json object)\n"
118 " \"asm\" : \"asm\", (string) the asm\n"
119 " \"hex\" : \"hex\", (string) the hex\n"
120 " \"reqSigs\" : n, (numeric) The required sigs\n"
121 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
122 " \"addresses\" : [ (json array of string)\n"
123 " \"address\" (string) bitcoin address\n"
130 " \"blockhash\" : \"hash\", (string) the block hash\n"
131 " \"confirmations\" : n, (numeric) The confirmations\n"
132 " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
133 " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
137 + HelpExampleCli("getrawtransaction", "\"mytxid\"")
138 + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
139 + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
140 + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
141 + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
146 bool in_active_chain
= true;
147 uint256 hash
= ParseHashV(request
.params
[0], "parameter 1");
148 CBlockIndex
* blockindex
= nullptr;
150 // Accept either a bool (true) or a num (>=1) to indicate verbose output.
151 bool fVerbose
= false;
152 if (!request
.params
[1].isNull()) {
153 fVerbose
= request
.params
[1].isNum() ? (request
.params
[1].get_int() != 0) : request
.params
[1].get_bool();
156 if (!request
.params
[2].isNull()) {
157 uint256 blockhash
= ParseHashV(request
.params
[2], "parameter 3");
158 BlockMap::iterator it
= mapBlockIndex
.find(blockhash
);
159 if (it
== mapBlockIndex
.end()) {
160 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Block hash not found");
162 blockindex
= it
->second
;
163 in_active_chain
= chainActive
.Contains(blockindex
);
168 if (!GetTransaction(hash
, tx
, Params().GetConsensus(), hash_block
, true, blockindex
)) {
171 if (!(blockindex
->nStatus
& BLOCK_HAVE_DATA
)) {
172 throw JSONRPCError(RPC_MISC_ERROR
, "Block not available");
174 errmsg
= "No such transaction found in the provided block";
177 ? "No such mempool or blockchain transaction"
178 : "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
180 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, errmsg
+ ". Use gettransaction for wallet transactions.");
184 return EncodeHexTx(*tx
, RPCSerializationFlags());
187 UniValue
result(UniValue::VOBJ
);
188 if (blockindex
) result
.push_back(Pair("in_active_chain", in_active_chain
));
189 TxToJSON(*tx
, hash_block
, result
);
193 UniValue
gettxoutproof(const JSONRPCRequest
& request
)
195 if (request
.fHelp
|| (request
.params
.size() != 1 && request
.params
.size() != 2))
196 throw std::runtime_error(
197 "gettxoutproof [\"txid\",...] ( blockhash )\n"
198 "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
199 "\nNOTE: By default this function only works sometimes. This is when there is an\n"
200 "unspent output in the utxo for this transaction. To make it always work,\n"
201 "you need to maintain a transaction index, using the -txindex command line option or\n"
202 "specify the block in which the transaction is included manually (by blockhash).\n"
204 "1. \"txids\" (string) A json array of txids to filter\n"
206 " \"txid\" (string) A transaction hash\n"
209 "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
211 "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
214 std::set
<uint256
> setTxids
;
216 UniValue txids
= request
.params
[0].get_array();
217 for (unsigned int idx
= 0; idx
< txids
.size(); idx
++) {
218 const UniValue
& txid
= txids
[idx
];
219 if (txid
.get_str().length() != 64 || !IsHex(txid
.get_str()))
220 throw JSONRPCError(RPC_INVALID_PARAMETER
, std::string("Invalid txid ")+txid
.get_str());
221 uint256
hash(uint256S(txid
.get_str()));
222 if (setTxids
.count(hash
))
223 throw JSONRPCError(RPC_INVALID_PARAMETER
, std::string("Invalid parameter, duplicated txid: ")+txid
.get_str());
224 setTxids
.insert(hash
);
230 CBlockIndex
* pblockindex
= nullptr;
233 if (!request
.params
[1].isNull())
235 hashBlock
= uint256S(request
.params
[1].get_str());
236 if (!mapBlockIndex
.count(hashBlock
))
237 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Block not found");
238 pblockindex
= mapBlockIndex
[hashBlock
];
240 // Loop through txids and try to find which block they're in. Exit loop once a block is found.
241 for (const auto& tx
: setTxids
) {
242 const Coin
& coin
= AccessByTxid(*pcoinsTip
, tx
);
243 if (!coin
.IsSpent()) {
244 pblockindex
= chainActive
[coin
.nHeight
];
250 if (pblockindex
== nullptr)
253 if (!GetTransaction(oneTxid
, tx
, Params().GetConsensus(), hashBlock
, false) || hashBlock
.IsNull())
254 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Transaction not yet in block");
255 if (!mapBlockIndex
.count(hashBlock
))
256 throw JSONRPCError(RPC_INTERNAL_ERROR
, "Transaction index corrupt");
257 pblockindex
= mapBlockIndex
[hashBlock
];
261 if(!ReadBlockFromDisk(block
, pblockindex
, Params().GetConsensus()))
262 throw JSONRPCError(RPC_INTERNAL_ERROR
, "Can't read block from disk");
264 unsigned int ntxFound
= 0;
265 for (const auto& tx
: block
.vtx
)
266 if (setTxids
.count(tx
->GetHash()))
268 if (ntxFound
!= setTxids
.size())
269 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Not all transactions found in specified or retrieved block");
271 CDataStream
ssMB(SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
);
272 CMerkleBlock
mb(block
, setTxids
);
274 std::string strHex
= HexStr(ssMB
.begin(), ssMB
.end());
278 UniValue
verifytxoutproof(const JSONRPCRequest
& request
)
280 if (request
.fHelp
|| request
.params
.size() != 1)
281 throw std::runtime_error(
282 "verifytxoutproof \"proof\"\n"
283 "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
284 "and throwing an RPC error if the block is not in our best chain\n"
286 "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
288 "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
291 CDataStream
ssMB(ParseHexV(request
.params
[0], "proof"), SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
);
292 CMerkleBlock merkleBlock
;
295 UniValue
res(UniValue::VARR
);
297 std::vector
<uint256
> vMatch
;
298 std::vector
<unsigned int> vIndex
;
299 if (merkleBlock
.txn
.ExtractMatches(vMatch
, vIndex
) != merkleBlock
.header
.hashMerkleRoot
)
304 if (!mapBlockIndex
.count(merkleBlock
.header
.GetHash()) || !chainActive
.Contains(mapBlockIndex
[merkleBlock
.header
.GetHash()]))
305 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Block not found in chain");
307 for (const uint256
& hash
: vMatch
)
308 res
.push_back(hash
.GetHex());
312 UniValue
createrawtransaction(const JSONRPCRequest
& request
)
314 if (request
.fHelp
|| request
.params
.size() < 2 || request
.params
.size() > 4)
315 throw std::runtime_error(
316 "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
317 "\nCreate a transaction spending the given inputs and creating new outputs.\n"
318 "Outputs can be addresses or data.\n"
319 "Returns hex-encoded raw transaction.\n"
320 "Note that the transaction's inputs are not signed, and\n"
321 "it is not stored in the wallet or transmitted to the network.\n"
324 "1. \"inputs\" (array, required) A json array of json objects\n"
327 " \"txid\":\"id\", (string, required) The transaction id\n"
328 " \"vout\":n, (numeric, required) The output number\n"
329 " \"sequence\":n (numeric, optional) The sequence number\n"
333 "2. \"outputs\" (object, required) a json object with outputs\n"
335 " \"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"
336 " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
339 "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
340 "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
341 " 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"
343 "\"transaction\" (string) hex string of the transaction\n"
346 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
347 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
348 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
349 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
352 RPCTypeCheck(request
.params
, {UniValue::VARR
, UniValue::VOBJ
, UniValue::VNUM
, UniValue::VBOOL
}, true);
353 if (request
.params
[0].isNull() || request
.params
[1].isNull())
354 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter, arguments 1 and 2 must be non-null");
356 UniValue inputs
= request
.params
[0].get_array();
357 UniValue sendTo
= request
.params
[1].get_obj();
359 CMutableTransaction rawTx
;
361 if (!request
.params
[2].isNull()) {
362 int64_t nLockTime
= request
.params
[2].get_int64();
363 if (nLockTime
< 0 || nLockTime
> std::numeric_limits
<uint32_t>::max())
364 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter, locktime out of range");
365 rawTx
.nLockTime
= nLockTime
;
368 bool rbfOptIn
= request
.params
[3].isTrue();
370 for (unsigned int idx
= 0; idx
< inputs
.size(); idx
++) {
371 const UniValue
& input
= inputs
[idx
];
372 const UniValue
& o
= input
.get_obj();
374 uint256 txid
= ParseHashO(o
, "txid");
376 const UniValue
& vout_v
= find_value(o
, "vout");
378 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter, missing vout key");
379 int nOutput
= vout_v
.get_int();
381 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter, vout must be positive");
385 nSequence
= MAX_BIP125_RBF_SEQUENCE
;
386 } else if (rawTx
.nLockTime
) {
387 nSequence
= std::numeric_limits
<uint32_t>::max() - 1;
389 nSequence
= std::numeric_limits
<uint32_t>::max();
392 // set the sequence number if passed in the parameters object
393 const UniValue
& sequenceObj
= find_value(o
, "sequence");
394 if (sequenceObj
.isNum()) {
395 int64_t seqNr64
= sequenceObj
.get_int64();
396 if (seqNr64
< 0 || seqNr64
> std::numeric_limits
<uint32_t>::max()) {
397 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter, sequence number is out of range");
399 nSequence
= (uint32_t)seqNr64
;
403 CTxIn
in(COutPoint(txid
, nOutput
), CScript(), nSequence
);
405 rawTx
.vin
.push_back(in
);
408 std::set
<CTxDestination
> destinations
;
409 std::vector
<std::string
> addrList
= sendTo
.getKeys();
410 for (const std::string
& name_
: addrList
) {
412 if (name_
== "data") {
413 std::vector
<unsigned char> data
= ParseHexV(sendTo
[name_
].getValStr(),"Data");
415 CTxOut
out(0, CScript() << OP_RETURN
<< data
);
416 rawTx
.vout
.push_back(out
);
418 CTxDestination destination
= DecodeDestination(name_
);
419 if (!IsValidDestination(destination
)) {
420 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, std::string("Invalid Bitcoin address: ") + name_
);
423 if (!destinations
.insert(destination
).second
) {
424 throw JSONRPCError(RPC_INVALID_PARAMETER
, std::string("Invalid parameter, duplicated address: ") + name_
);
427 CScript scriptPubKey
= GetScriptForDestination(destination
);
428 CAmount nAmount
= AmountFromValue(sendTo
[name_
]);
430 CTxOut
out(nAmount
, scriptPubKey
);
431 rawTx
.vout
.push_back(out
);
435 if (!request
.params
[3].isNull() && rbfOptIn
!= SignalsOptInRBF(rawTx
)) {
436 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
439 return EncodeHexTx(rawTx
);
442 UniValue
decoderawtransaction(const JSONRPCRequest
& request
)
444 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 2)
445 throw std::runtime_error(
446 "decoderawtransaction \"hexstring\" ( iswitness )\n"
447 "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
450 "1. \"hexstring\" (string, required) The transaction hex string\n"
451 "2. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction\n"
452 " If iswitness is not present, heuristic tests will be used in decoding\n"
456 " \"txid\" : \"id\", (string) The transaction id\n"
457 " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
458 " \"size\" : n, (numeric) The transaction size\n"
459 " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
460 " \"version\" : n, (numeric) The version\n"
461 " \"locktime\" : ttt, (numeric) The lock time\n"
462 " \"vin\" : [ (array of json objects)\n"
464 " \"txid\": \"id\", (string) The transaction id\n"
465 " \"vout\": n, (numeric) The output number\n"
466 " \"scriptSig\": { (json object) The script\n"
467 " \"asm\": \"asm\", (string) asm\n"
468 " \"hex\": \"hex\" (string) hex\n"
470 " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
471 " \"sequence\": n (numeric) The script sequence number\n"
475 " \"vout\" : [ (array of json objects)\n"
477 " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT
+ "\n"
478 " \"n\" : n, (numeric) index\n"
479 " \"scriptPubKey\" : { (json object)\n"
480 " \"asm\" : \"asm\", (string) the asm\n"
481 " \"hex\" : \"hex\", (string) the hex\n"
482 " \"reqSigs\" : n, (numeric) The required sigs\n"
483 " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
484 " \"addresses\" : [ (json array of string)\n"
485 " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n"
495 + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
496 + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
500 RPCTypeCheck(request
.params
, {UniValue::VSTR
, UniValue::VBOOL
});
502 CMutableTransaction mtx
;
504 bool try_witness
= request
.params
[1].isNull() ? true : request
.params
[1].get_bool();
505 bool try_no_witness
= request
.params
[1].isNull() ? true : !request
.params
[1].get_bool();
507 if (!DecodeHexTx(mtx
, request
.params
[0].get_str(), try_no_witness
, try_witness
)) {
508 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "TX decode failed");
511 UniValue
result(UniValue::VOBJ
);
512 TxToUniv(CTransaction(std::move(mtx
)), uint256(), result
, false);
517 UniValue
decodescript(const JSONRPCRequest
& request
)
519 if (request
.fHelp
|| request
.params
.size() != 1)
520 throw std::runtime_error(
521 "decodescript \"hexstring\"\n"
522 "\nDecode a hex-encoded script.\n"
524 "1. \"hexstring\" (string) the hex encoded script\n"
527 " \"asm\":\"asm\", (string) Script public key\n"
528 " \"hex\":\"hex\", (string) hex encoded public key\n"
529 " \"type\":\"type\", (string) The output type\n"
530 " \"reqSigs\": n, (numeric) The required signatures\n"
531 " \"addresses\": [ (json array of string)\n"
532 " \"address\" (string) bitcoin address\n"
535 " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
538 + HelpExampleCli("decodescript", "\"hexstring\"")
539 + HelpExampleRpc("decodescript", "\"hexstring\"")
542 RPCTypeCheck(request
.params
, {UniValue::VSTR
});
544 UniValue
r(UniValue::VOBJ
);
546 if (request
.params
[0].get_str().size() > 0){
547 std::vector
<unsigned char> scriptData(ParseHexV(request
.params
[0], "argument"));
548 script
= CScript(scriptData
.begin(), scriptData
.end());
550 // Empty scripts are valid
552 ScriptPubKeyToUniv(script
, r
, false);
555 type
= find_value(r
, "type");
557 if (type
.isStr() && type
.get_str() != "scripthash") {
558 // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
559 // don't return the address for a P2SH of the P2SH.
560 r
.push_back(Pair("p2sh", EncodeDestination(CScriptID(script
))));
566 /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
567 static void TxInErrorToJSON(const CTxIn
& txin
, UniValue
& vErrorsRet
, const std::string
& strMessage
)
569 UniValue
entry(UniValue::VOBJ
);
570 entry
.push_back(Pair("txid", txin
.prevout
.hash
.ToString()));
571 entry
.push_back(Pair("vout", (uint64_t)txin
.prevout
.n
));
572 UniValue
witness(UniValue::VARR
);
573 for (unsigned int i
= 0; i
< txin
.scriptWitness
.stack
.size(); i
++) {
574 witness
.push_back(HexStr(txin
.scriptWitness
.stack
[i
].begin(), txin
.scriptWitness
.stack
[i
].end()));
576 entry
.push_back(Pair("witness", witness
));
577 entry
.push_back(Pair("scriptSig", HexStr(txin
.scriptSig
.begin(), txin
.scriptSig
.end())));
578 entry
.push_back(Pair("sequence", (uint64_t)txin
.nSequence
));
579 entry
.push_back(Pair("error", strMessage
));
580 vErrorsRet
.push_back(entry
);
583 UniValue
combinerawtransaction(const JSONRPCRequest
& request
)
586 if (request
.fHelp
|| request
.params
.size() != 1)
587 throw std::runtime_error(
588 "combinerawtransaction [\"hexstring\",...]\n"
589 "\nCombine multiple partially signed transactions into one transaction.\n"
590 "The combined transaction may be another partially signed transaction or a \n"
591 "fully signed transaction."
594 "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
596 " \"hexstring\" (string) A transaction hash\n"
601 "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
604 + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
608 UniValue txs
= request
.params
[0].get_array();
609 std::vector
<CMutableTransaction
> txVariants(txs
.size());
611 for (unsigned int idx
= 0; idx
< txs
.size(); idx
++) {
612 if (!DecodeHexTx(txVariants
[idx
], txs
[idx
].get_str(), true)) {
613 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, strprintf("TX decode failed for tx %d", idx
));
617 if (txVariants
.empty()) {
618 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "Missing transactions");
621 // mergedTx will end up with all the signatures; it
622 // starts as a clone of the rawtx:
623 CMutableTransaction
mergedTx(txVariants
[0]);
625 // Fetch previous transactions (inputs):
626 CCoinsView viewDummy
;
627 CCoinsViewCache
view(&viewDummy
);
631 CCoinsViewCache
&viewChain
= *pcoinsTip
;
632 CCoinsViewMemPool
viewMempool(&viewChain
, mempool
);
633 view
.SetBackend(viewMempool
); // temporarily switch cache backend to db+mempool view
635 for (const CTxIn
& txin
: mergedTx
.vin
) {
636 view
.AccessCoin(txin
.prevout
); // Load entries from viewChain into view; can fail.
639 view
.SetBackend(viewDummy
); // switch back to avoid locking mempool for too long
642 // Use CTransaction for the constant parts of the
643 // transaction to avoid rehashing.
644 const CTransaction
txConst(mergedTx
);
646 for (unsigned int i
= 0; i
< mergedTx
.vin
.size(); i
++) {
647 CTxIn
& txin
= mergedTx
.vin
[i
];
648 const Coin
& coin
= view
.AccessCoin(txin
.prevout
);
649 if (coin
.IsSpent()) {
650 throw JSONRPCError(RPC_VERIFY_ERROR
, "Input not found or already spent");
652 const CScript
& prevPubKey
= coin
.out
.scriptPubKey
;
653 const CAmount
& amount
= coin
.out
.nValue
;
655 SignatureData sigdata
;
657 // ... and merge in other signatures:
658 for (const CMutableTransaction
& txv
: txVariants
) {
659 if (txv
.vin
.size() > i
) {
660 sigdata
= CombineSignatures(prevPubKey
, TransactionSignatureChecker(&txConst
, i
, amount
), sigdata
, DataFromTransaction(txv
, i
));
664 UpdateTransaction(mergedTx
, i
, sigdata
);
667 return EncodeHexTx(mergedTx
);
670 UniValue
signrawtransaction(const JSONRPCRequest
& request
)
673 CWallet
* const pwallet
= GetWalletForJSONRPCRequest(request
);
676 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 4)
677 throw std::runtime_error(
678 "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
679 "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
680 "The second optional argument (may be null) is an array of previous transaction outputs that\n"
681 "this transaction depends on but may not yet be in the block chain.\n"
682 "The third optional argument (may be null) is an array of base58-encoded private\n"
683 "keys that, if given, will be the only keys used to sign the transaction.\n"
685 + HelpRequiringPassphrase(pwallet
) + "\n"
689 "1. \"hexstring\" (string, required) The transaction hex string\n"
690 "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
691 " [ (json array of json objects, or 'null' if none provided)\n"
693 " \"txid\":\"id\", (string, required) The transaction id\n"
694 " \"vout\":n, (numeric, required) The output number\n"
695 " \"scriptPubKey\": \"hex\", (string, required) script key\n"
696 " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
697 " \"amount\": value (numeric, required) The amount spent\n"
701 "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
702 " [ (json array of strings, or 'null' if none provided)\n"
703 " \"privatekey\" (string) private key in base58-encoding\n"
706 "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
710 " \"ALL|ANYONECANPAY\"\n"
711 " \"NONE|ANYONECANPAY\"\n"
712 " \"SINGLE|ANYONECANPAY\"\n"
716 " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
717 " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
718 " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
720 " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
721 " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
722 " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
723 " \"sequence\" : n, (numeric) Script sequence number\n"
724 " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
731 + HelpExampleCli("signrawtransaction", "\"myhex\"")
732 + HelpExampleRpc("signrawtransaction", "\"myhex\"")
737 LOCK2(cs_main
, pwallet
? &pwallet
->cs_wallet
: nullptr);
741 RPCTypeCheck(request
.params
, {UniValue::VSTR
, UniValue::VARR
, UniValue::VARR
, UniValue::VSTR
}, true);
743 CMutableTransaction mtx
;
744 if (!DecodeHexTx(mtx
, request
.params
[0].get_str(), true))
745 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "TX decode failed");
747 // Fetch previous transactions (inputs):
748 CCoinsView viewDummy
;
749 CCoinsViewCache
view(&viewDummy
);
752 CCoinsViewCache
&viewChain
= *pcoinsTip
;
753 CCoinsViewMemPool
viewMempool(&viewChain
, mempool
);
754 view
.SetBackend(viewMempool
); // temporarily switch cache backend to db+mempool view
756 for (const CTxIn
& txin
: mtx
.vin
) {
757 view
.AccessCoin(txin
.prevout
); // Load entries from viewChain into view; can fail.
760 view
.SetBackend(viewDummy
); // switch back to avoid locking mempool for too long
763 bool fGivenKeys
= false;
764 CBasicKeyStore tempKeystore
;
765 if (!request
.params
[2].isNull()) {
767 UniValue keys
= request
.params
[2].get_array();
768 for (unsigned int idx
= 0; idx
< keys
.size(); idx
++) {
769 UniValue k
= keys
[idx
];
770 CBitcoinSecret vchSecret
;
771 bool fGood
= vchSecret
.SetString(k
.get_str());
773 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Invalid private key");
774 CKey key
= vchSecret
.GetKey();
776 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY
, "Private key outside allowed range");
777 tempKeystore
.AddKey(key
);
782 EnsureWalletIsUnlocked(pwallet
);
786 // Add previous txouts given in the RPC call:
787 if (!request
.params
[1].isNull()) {
788 UniValue prevTxs
= request
.params
[1].get_array();
789 for (unsigned int idx
= 0; idx
< prevTxs
.size(); idx
++) {
790 const UniValue
& p
= prevTxs
[idx
];
792 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
794 UniValue prevOut
= p
.get_obj();
796 RPCTypeCheckObj(prevOut
,
798 {"txid", UniValueType(UniValue::VSTR
)},
799 {"vout", UniValueType(UniValue::VNUM
)},
800 {"scriptPubKey", UniValueType(UniValue::VSTR
)},
803 uint256 txid
= ParseHashO(prevOut
, "txid");
805 int nOut
= find_value(prevOut
, "vout").get_int();
807 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "vout must be positive");
809 COutPoint
out(txid
, nOut
);
810 std::vector
<unsigned char> pkData(ParseHexO(prevOut
, "scriptPubKey"));
811 CScript
scriptPubKey(pkData
.begin(), pkData
.end());
814 const Coin
& coin
= view
.AccessCoin(out
);
815 if (!coin
.IsSpent() && coin
.out
.scriptPubKey
!= scriptPubKey
) {
816 std::string
err("Previous output scriptPubKey mismatch:\n");
817 err
= err
+ ScriptToAsmStr(coin
.out
.scriptPubKey
) + "\nvs:\n"+
818 ScriptToAsmStr(scriptPubKey
);
819 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, err
);
822 newcoin
.out
.scriptPubKey
= scriptPubKey
;
823 newcoin
.out
.nValue
= 0;
824 if (prevOut
.exists("amount")) {
825 newcoin
.out
.nValue
= AmountFromValue(find_value(prevOut
, "amount"));
828 view
.AddCoin(out
, std::move(newcoin
), true);
831 // if redeemScript given and not using the local wallet (private keys
832 // given), add redeemScript to the tempKeystore so it can be signed:
833 if (fGivenKeys
&& (scriptPubKey
.IsPayToScriptHash() || scriptPubKey
.IsPayToWitnessScriptHash())) {
834 RPCTypeCheckObj(prevOut
,
836 {"txid", UniValueType(UniValue::VSTR
)},
837 {"vout", UniValueType(UniValue::VNUM
)},
838 {"scriptPubKey", UniValueType(UniValue::VSTR
)},
839 {"redeemScript", UniValueType(UniValue::VSTR
)},
841 UniValue v
= find_value(prevOut
, "redeemScript");
843 std::vector
<unsigned char> rsData(ParseHexV(v
, "redeemScript"));
844 CScript
redeemScript(rsData
.begin(), rsData
.end());
845 tempKeystore
.AddCScript(redeemScript
);
852 const CKeyStore
& keystore
= ((fGivenKeys
|| !pwallet
) ? tempKeystore
: *pwallet
);
854 const CKeyStore
& keystore
= tempKeystore
;
857 int nHashType
= SIGHASH_ALL
;
858 if (!request
.params
[3].isNull()) {
859 static std::map
<std::string
, int> mapSigHashValues
= {
860 {std::string("ALL"), int(SIGHASH_ALL
)},
861 {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL
|SIGHASH_ANYONECANPAY
)},
862 {std::string("NONE"), int(SIGHASH_NONE
)},
863 {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE
|SIGHASH_ANYONECANPAY
)},
864 {std::string("SINGLE"), int(SIGHASH_SINGLE
)},
865 {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE
|SIGHASH_ANYONECANPAY
)},
867 std::string strHashType
= request
.params
[3].get_str();
868 if (mapSigHashValues
.count(strHashType
))
869 nHashType
= mapSigHashValues
[strHashType
];
871 throw JSONRPCError(RPC_INVALID_PARAMETER
, "Invalid sighash param");
874 bool fHashSingle
= ((nHashType
& ~SIGHASH_ANYONECANPAY
) == SIGHASH_SINGLE
);
876 // Script verification errors
877 UniValue
vErrors(UniValue::VARR
);
879 // Use CTransaction for the constant parts of the
880 // transaction to avoid rehashing.
881 const CTransaction
txConst(mtx
);
883 for (unsigned int i
= 0; i
< mtx
.vin
.size(); i
++) {
884 CTxIn
& txin
= mtx
.vin
[i
];
885 const Coin
& coin
= view
.AccessCoin(txin
.prevout
);
886 if (coin
.IsSpent()) {
887 TxInErrorToJSON(txin
, vErrors
, "Input not found or already spent");
890 const CScript
& prevPubKey
= coin
.out
.scriptPubKey
;
891 const CAmount
& amount
= coin
.out
.nValue
;
893 SignatureData sigdata
;
894 // Only sign SIGHASH_SINGLE if there's a corresponding output:
895 if (!fHashSingle
|| (i
< mtx
.vout
.size()))
896 ProduceSignature(MutableTransactionSignatureCreator(&keystore
, &mtx
, i
, amount
, nHashType
), prevPubKey
, sigdata
);
897 sigdata
= CombineSignatures(prevPubKey
, TransactionSignatureChecker(&txConst
, i
, amount
), sigdata
, DataFromTransaction(mtx
, i
));
899 UpdateTransaction(mtx
, i
, sigdata
);
901 ScriptError serror
= SCRIPT_ERR_OK
;
902 if (!VerifyScript(txin
.scriptSig
, prevPubKey
, &txin
.scriptWitness
, STANDARD_SCRIPT_VERIFY_FLAGS
, TransactionSignatureChecker(&txConst
, i
, amount
), &serror
)) {
903 if (serror
== SCRIPT_ERR_INVALID_STACK_OPERATION
) {
904 // Unable to sign input and verification failed (possible attempt to partially sign).
905 TxInErrorToJSON(txin
, vErrors
, "Unable to sign input, invalid stack size (possibly missing key)");
907 TxInErrorToJSON(txin
, vErrors
, ScriptErrorString(serror
));
911 bool fComplete
= vErrors
.empty();
913 UniValue
result(UniValue::VOBJ
);
914 result
.push_back(Pair("hex", EncodeHexTx(mtx
)));
915 result
.push_back(Pair("complete", fComplete
));
916 if (!vErrors
.empty()) {
917 result
.push_back(Pair("errors", vErrors
));
923 UniValue
sendrawtransaction(const JSONRPCRequest
& request
)
925 if (request
.fHelp
|| request
.params
.size() < 1 || request
.params
.size() > 2)
926 throw std::runtime_error(
927 "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
928 "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
929 "\nAlso see createrawtransaction and signrawtransaction calls.\n"
931 "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
932 "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
934 "\"hex\" (string) The transaction hash in hex\n"
936 "\nCreate a transaction\n"
937 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
938 "Sign the transaction, and get back the hex\n"
939 + HelpExampleCli("signrawtransaction", "\"myhex\"") +
940 "\nSend the transaction (signed hex)\n"
941 + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
942 "\nAs a json rpc call\n"
943 + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
948 std::promise
<void> promise
;
950 RPCTypeCheck(request
.params
, {UniValue::VSTR
, UniValue::VBOOL
});
952 // parse hex string from parameter
953 CMutableTransaction mtx
;
954 if (!DecodeHexTx(mtx
, request
.params
[0].get_str()))
955 throw JSONRPCError(RPC_DESERIALIZATION_ERROR
, "TX decode failed");
956 CTransactionRef
tx(MakeTransactionRef(std::move(mtx
)));
957 const uint256
& hashTx
= tx
->GetHash();
959 CAmount nMaxRawTxFee
= maxTxFee
;
960 if (!request
.params
[1].isNull() && request
.params
[1].get_bool())
965 CCoinsViewCache
&view
= *pcoinsTip
;
966 bool fHaveChain
= false;
967 for (size_t o
= 0; !fHaveChain
&& o
< tx
->vout
.size(); o
++) {
968 const Coin
& existingCoin
= view
.AccessCoin(COutPoint(hashTx
, o
));
969 fHaveChain
= !existingCoin
.IsSpent();
971 bool fHaveMempool
= mempool
.exists(hashTx
);
972 if (!fHaveMempool
&& !fHaveChain
) {
973 // push to local node and sync with wallets
974 CValidationState state
;
976 if (!AcceptToMemoryPool(mempool
, state
, std::move(tx
), &fMissingInputs
,
977 nullptr /* plTxnReplaced */, false /* bypass_limits */, nMaxRawTxFee
)) {
978 if (state
.IsInvalid()) {
979 throw JSONRPCError(RPC_TRANSACTION_REJECTED
, strprintf("%i: %s", state
.GetRejectCode(), state
.GetRejectReason()));
981 if (fMissingInputs
) {
982 throw JSONRPCError(RPC_TRANSACTION_ERROR
, "Missing inputs");
984 throw JSONRPCError(RPC_TRANSACTION_ERROR
, state
.GetRejectReason());
987 // If wallet is enabled, ensure that the wallet has been made aware
988 // of the new transaction prior to returning. This prevents a race
989 // where a user might call sendrawtransaction with a transaction
990 // to/from their wallet, immediately call some wallet RPC, and get
991 // a stale result because callbacks have not yet been processed.
992 CallFunctionInValidationInterfaceQueue([&promise
] {
996 } else if (fHaveChain
) {
997 throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN
, "transaction already in block chain");
999 // Make sure we don't block forever if re-sending
1000 // a transaction already in mempool.
1001 promise
.set_value();
1006 promise
.get_future().wait();
1009 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED
, "Error: Peer-to-peer functionality missing or disabled");
1011 CInv
inv(MSG_TX
, hashTx
);
1012 g_connman
->ForEachNode([&inv
](CNode
* pnode
)
1014 pnode
->PushInventory(inv
);
1017 return hashTx
.GetHex();
1020 static const CRPCCommand commands
[] =
1021 { // category name actor (function) argNames
1022 // --------------------- ------------------------ ----------------------- ----------
1023 { "rawtransactions", "getrawtransaction", &getrawtransaction
, {"txid","verbose","blockhash"} },
1024 { "rawtransactions", "createrawtransaction", &createrawtransaction
, {"inputs","outputs","locktime","replaceable"} },
1025 { "rawtransactions", "decoderawtransaction", &decoderawtransaction
, {"hexstring","iswitness"} },
1026 { "rawtransactions", "decodescript", &decodescript
, {"hexstring"} },
1027 { "rawtransactions", "sendrawtransaction", &sendrawtransaction
, {"hexstring","allowhighfees"} },
1028 { "rawtransactions", "combinerawtransaction", &combinerawtransaction
, {"txs"} },
1029 { "rawtransactions", "signrawtransaction", &signrawtransaction
, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
1031 { "blockchain", "gettxoutproof", &gettxoutproof
, {"txids", "blockhash"} },
1032 { "blockchain", "verifytxoutproof", &verifytxoutproof
, {"proof"} },
1035 void RegisterRawTransactionRPCCommands(CRPCTable
&t
)
1037 for (unsigned int vcidx
= 0; vcidx
< ARRAYLEN(commands
); vcidx
++)
1038 t
.appendCommand(commands
[vcidx
].name
, &commands
[vcidx
]);