Bitcoin Core 22.99.0
P2P Digital Currency
rawtransaction.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <chain.h>
7#include <coins.h>
8#include <consensus/amount.h>
10#include <core_io.h>
11#include <index/txindex.h>
12#include <key_io.h>
13#include <merkleblock.h>
14#include <node/blockstorage.h>
15#include <node/coin.h>
16#include <node/context.h>
17#include <node/psbt.h>
18#include <node/transaction.h>
19#include <policy/packages.h>
20#include <policy/policy.h>
21#include <policy/rbf.h>
23#include <psbt.h>
24#include <random.h>
25#include <rpc/blockchain.h>
27#include <rpc/server.h>
28#include <rpc/util.h>
29#include <script/script.h>
30#include <script/sign.h>
32#include <script/standard.h>
33#include <uint256.h>
34#include <util/bip32.h>
35#include <util/moneystr.h>
36#include <util/strencodings.h>
37#include <util/string.h>
38#include <validation.h>
39#include <validationinterface.h>
40
41#include <numeric>
42#include <stdint.h>
43
44#include <univalue.h>
45
46static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry, CChainState& active_chainstate)
47{
48 // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
49 //
50 // Blockchain contextual information (confirmations and blocktime) is not
51 // available to code in bitcoin-common, so we query them here and push the
52 // data into the returned UniValue.
53 TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
54
55 if (!hashBlock.IsNull()) {
57
58 entry.pushKV("blockhash", hashBlock.GetHex());
59 CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(hashBlock);
60 if (pindex) {
61 if (active_chainstate.m_chain.Contains(pindex)) {
62 entry.pushKV("confirmations", 1 + active_chainstate.m_chain.Height() - pindex->nHeight);
63 entry.pushKV("time", pindex->GetBlockTime());
64 entry.pushKV("blocktime", pindex->GetBlockTime());
65 }
66 else
67 entry.pushKV("confirmations", 0);
68 }
69 }
70}
71
73{
74 return RPCHelpMan{
75 "getrawtransaction",
76 "\nReturn the raw transaction data.\n"
77
78 "\nBy default, this call only returns a transaction if it is in the mempool. If -txindex is enabled\n"
79 "and no blockhash argument is passed, it will return the transaction if it is in the mempool or any block.\n"
80 "If a blockhash argument is passed, it will return the transaction if\n"
81 "the specified block is available and the transaction is in that block.\n"
82 "\nHint: Use gettransaction for wallet transactions.\n"
83
84 "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
85 "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n",
86 {
87 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
88 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If false, return a string, otherwise return a json object"},
89 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "The block in which to look for the transaction"},
90 },
91 {
92 RPCResult{"if verbose is not set or set to false",
93 RPCResult::Type::STR, "data", "The serialized, hex-encoded data for 'txid'"
94 },
95 RPCResult{"if verbose is set to true",
97 {
98 {RPCResult::Type::BOOL, "in_active_chain", /* optional */ true, "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},
99 {RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded data for 'txid'"},
100 {RPCResult::Type::STR_HEX, "txid", "The transaction id (same as provided)"},
101 {RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)"},
102 {RPCResult::Type::NUM, "size", "The serialized transaction size"},
103 {RPCResult::Type::NUM, "vsize", "The virtual transaction size (differs from size for witness transactions)"},
104 {RPCResult::Type::NUM, "weight", "The transaction's weight (between vsize*4-3 and vsize*4)"},
105 {RPCResult::Type::NUM, "version", "The version"},
106 {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
107 {RPCResult::Type::ARR, "vin", "",
108 {
109 {RPCResult::Type::OBJ, "", "",
110 {
111 {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
112 {RPCResult::Type::NUM, "vout", "The output number"},
113 {RPCResult::Type::OBJ, "scriptSig", "The script",
114 {
115 {RPCResult::Type::STR, "asm", "asm"},
116 {RPCResult::Type::STR_HEX, "hex", "hex"},
117 }},
118 {RPCResult::Type::NUM, "sequence", "The script sequence number"},
119 {RPCResult::Type::ARR, "txinwitness", /* optional */ true, "",
120 {
121 {RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
122 }},
123 }},
124 }},
125 {RPCResult::Type::ARR, "vout", "",
126 {
127 {RPCResult::Type::OBJ, "", "",
128 {
129 {RPCResult::Type::NUM, "value", "The value in " + CURRENCY_UNIT},
130 {RPCResult::Type::NUM, "n", "index"},
131 {RPCResult::Type::OBJ, "scriptPubKey", "",
132 {
133 {RPCResult::Type::STR, "asm", "the asm"},
134 {RPCResult::Type::STR, "hex", "the hex"},
135 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
136 {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
137 }},
138 }},
139 }},
140 {RPCResult::Type::STR_HEX, "blockhash", /* optional */ true, "the block hash"},
141 {RPCResult::Type::NUM, "confirmations", /* optional */ true, "The confirmations"},
142 {RPCResult::Type::NUM_TIME, "blocktime", /* optional */ true, "The block time expressed in " + UNIX_EPOCH_TIME},
143 {RPCResult::Type::NUM, "time", /* optional */ true, "Same as \"blocktime\""},
144 }
145 },
146 },
148 HelpExampleCli("getrawtransaction", "\"mytxid\"")
149 + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
150 + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
151 + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
152 + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
153 },
154 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
155{
156 const NodeContext& node = EnsureAnyNodeContext(request.context);
158
159 bool in_active_chain = true;
160 uint256 hash = ParseHashV(request.params[0], "parameter 1");
161 CBlockIndex* blockindex = nullptr;
162
163 if (hash == Params().GenesisBlock().hashMerkleRoot) {
164 // Special exception for the genesis block coinbase transaction
165 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
166 }
167
168 // Accept either a bool (true) or a num (>=1) to indicate verbose output.
169 bool fVerbose = false;
170 if (!request.params[1].isNull()) {
171 fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool();
172 }
173
174 if (!request.params[2].isNull()) {
175 LOCK(cs_main);
176
177 uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
178 blockindex = chainman.m_blockman.LookupBlockIndex(blockhash);
179 if (!blockindex) {
180 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
181 }
182 in_active_chain = chainman.ActiveChain().Contains(blockindex);
183 }
184
185 bool f_txindex_ready = false;
186 if (g_txindex && !blockindex) {
187 f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
188 }
189
190 uint256 hash_block;
191 const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, Params().GetConsensus(), hash_block);
192 if (!tx) {
193 std::string errmsg;
194 if (blockindex) {
195 if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
196 throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
197 }
198 errmsg = "No such transaction found in the provided block";
199 } else if (!g_txindex) {
200 errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries";
201 } else if (!f_txindex_ready) {
202 errmsg = "No such mempool transaction. Blockchain transactions are still in the process of being indexed";
203 } else {
204 errmsg = "No such mempool or blockchain transaction";
205 }
206 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
207 }
208
209 if (!fVerbose) {
210 return EncodeHexTx(*tx, RPCSerializationFlags());
211 }
212
213 UniValue result(UniValue::VOBJ);
214 if (blockindex) result.pushKV("in_active_chain", in_active_chain);
215 TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
216 return result;
217},
218 };
219}
220
222{
223 return RPCHelpMan{"gettxoutproof",
224 "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
225 "\nNOTE: By default this function only works sometimes. This is when there is an\n"
226 "unspent output in the utxo for this transaction. To make it always work,\n"
227 "you need to maintain a transaction index, using the -txindex command line option or\n"
228 "specify the block in which the transaction is included manually (by blockhash).\n",
229 {
230 {"txids", RPCArg::Type::ARR, RPCArg::Optional::NO, "The txids to filter",
231 {
232 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A transaction hash"},
233 },
234 },
235 {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "If specified, looks for txid in the block with this hash"},
236 },
237 RPCResult{
238 RPCResult::Type::STR, "data", "A string that is a serialized, hex-encoded data for the proof."
239 },
240 RPCExamples{""},
241 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
242{
243 std::set<uint256> setTxids;
244 UniValue txids = request.params[0].get_array();
245 if (txids.empty()) {
246 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txids' cannot be empty");
247 }
248 for (unsigned int idx = 0; idx < txids.size(); idx++) {
249 auto ret = setTxids.insert(ParseHashV(txids[idx], "txid"));
250 if (!ret.second) {
251 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ") + txids[idx].get_str());
252 }
253 }
254
255 CBlockIndex* pblockindex = nullptr;
256 uint256 hashBlock;
257 ChainstateManager& chainman = EnsureAnyChainman(request.context);
258 if (!request.params[1].isNull()) {
259 LOCK(cs_main);
260 hashBlock = ParseHashV(request.params[1], "blockhash");
261 pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
262 if (!pblockindex) {
263 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
264 }
265 } else {
266 LOCK(cs_main);
267 CChainState& active_chainstate = chainman.ActiveChainstate();
268
269 // Loop through txids and try to find which block they're in. Exit loop once a block is found.
270 for (const auto& tx : setTxids) {
271 const Coin& coin = AccessByTxid(active_chainstate.CoinsTip(), tx);
272 if (!coin.IsSpent()) {
273 pblockindex = active_chainstate.m_chain[coin.nHeight];
274 break;
275 }
276 }
277 }
278
279
280 // Allow txindex to catch up if we need to query it and before we acquire cs_main.
281 if (g_txindex && !pblockindex) {
282 g_txindex->BlockUntilSyncedToCurrentChain();
283 }
284
285 LOCK(cs_main);
286
287 if (pblockindex == nullptr) {
288 const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, /* mempool */ nullptr, *setTxids.begin(), Params().GetConsensus(), hashBlock);
289 if (!tx || hashBlock.IsNull()) {
290 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
291 }
292 pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock);
293 if (!pblockindex) {
294 throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
295 }
296 }
297
298 CBlock block;
299 if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
300 throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
301 }
302
303 unsigned int ntxFound = 0;
304 for (const auto& tx : block.vtx) {
305 if (setTxids.count(tx->GetHash())) {
306 ntxFound++;
307 }
308 }
309 if (ntxFound != setTxids.size()) {
310 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
311 }
312
314 CMerkleBlock mb(block, setTxids);
315 ssMB << mb;
316 std::string strHex = HexStr(ssMB);
317 return strHex;
318},
319 };
320}
321
323{
324 return RPCHelpMan{"verifytxoutproof",
325 "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
326 "and throwing an RPC error if the block is not in our best chain\n",
327 {
328 {"proof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded proof generated by gettxoutproof"},
329 },
330 RPCResult{
331 RPCResult::Type::ARR, "", "",
332 {
333 {RPCResult::Type::STR_HEX, "txid", "The txid(s) which the proof commits to, or empty array if the proof can not be validated."},
334 }
335 },
336 RPCExamples{""},
337 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
338{
340 CMerkleBlock merkleBlock;
341 ssMB >> merkleBlock;
342
344
345 std::vector<uint256> vMatch;
346 std::vector<unsigned int> vIndex;
347 if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
348 return res;
349
350 ChainstateManager& chainman = EnsureAnyChainman(request.context);
351 LOCK(cs_main);
352
353 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash());
354 if (!pindex || !chainman.ActiveChain().Contains(pindex) || pindex->nTx == 0) {
355 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
356 }
357
358 // Check if proof is valid, only add results if so
359 if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) {
360 for (const uint256& hash : vMatch) {
361 res.push_back(hash.GetHex());
362 }
363 }
364
365 return res;
366},
367 };
368}
369
371{
372 return RPCHelpMan{"createrawtransaction",
373 "\nCreate a transaction spending the given inputs and creating new outputs.\n"
374 "Outputs can be addresses or data.\n"
375 "Returns hex-encoded raw transaction.\n"
376 "Note that the transaction's inputs are not signed, and\n"
377 "it is not stored in the wallet or transmitted to the network.\n",
378 {
379 {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The inputs",
380 {
382 {
383 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
384 {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
385 {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
386 },
387 },
388 },
389 },
390 {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs (key-value pairs), where none of the keys are duplicated.\n"
391 "That is, each address can only appear once and there can only be one 'data' object.\n"
392 "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
393 " accepted as second parameter.",
394 {
396 {
397 {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT},
398 },
399 },
401 {
402 {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"},
403 },
404 },
405 },
406 },
407 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
408 {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{false}, "Marks this transaction as BIP125-replaceable.\n"
409 " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."},
410 },
411 RPCResult{
412 RPCResult::Type::STR_HEX, "transaction", "hex string of the transaction"
413 },
415 HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
416 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
417 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"")
418 + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
419 },
420 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
421{
422 RPCTypeCheck(request.params, {
423 UniValue::VARR,
424 UniValueType(), // ARR or OBJ, checked later
425 UniValue::VNUM,
426 UniValue::VBOOL
427 }, true
428 );
429
430 bool rbf = false;
431 if (!request.params[3].isNull()) {
432 rbf = request.params[3].isTrue();
433 }
434 CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf);
435
436 return EncodeHexTx(CTransaction(rawTx));
437},
438 };
439}
440
442{
443 return RPCHelpMan{"decoderawtransaction",
444 "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n",
445 {
446 {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction hex string"},
447 {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
448 "If iswitness is not present, heuristic tests will be used in decoding.\n"
449 "If true, only witness deserialization will be tried.\n"
450 "If false, only non-witness deserialization will be tried.\n"
451 "This boolean should reflect whether the transaction has inputs\n"
452 "(e.g. fully valid, or on-chain transactions), if known by the caller."
453 },
454 },
455 RPCResult{
456 RPCResult::Type::OBJ, "", "",
457 {
458 {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
459 {RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)"},
460 {RPCResult::Type::NUM, "size", "The transaction size"},
461 {RPCResult::Type::NUM, "vsize", "The virtual transaction size (differs from size for witness transactions)"},
462 {RPCResult::Type::NUM, "weight", "The transaction's weight (between vsize*4 - 3 and vsize*4)"},
463 {RPCResult::Type::NUM, "version", "The version"},
464 {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
465 {RPCResult::Type::ARR, "vin", "",
466 {
467 {RPCResult::Type::OBJ, "", "",
468 {
469 {RPCResult::Type::STR_HEX, "coinbase", /* optional */ true, ""},
470 {RPCResult::Type::STR_HEX, "txid", /* optional */ true, "The transaction id"},
471 {RPCResult::Type::NUM, "vout", /* optional */ true, "The output number"},
472 {RPCResult::Type::OBJ, "scriptSig", /* optional */ true, "The script",
473 {
474 {RPCResult::Type::STR, "asm", "asm"},
475 {RPCResult::Type::STR_HEX, "hex", "hex"},
476 }},
477 {RPCResult::Type::ARR, "txinwitness", /* optional */ true, "",
478 {
479 {RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
480 }},
481 {RPCResult::Type::NUM, "sequence", "The script sequence number"},
482 }},
483 }},
484 {RPCResult::Type::ARR, "vout", "",
485 {
486 {RPCResult::Type::OBJ, "", "",
487 {
488 {RPCResult::Type::NUM, "value", "The value in " + CURRENCY_UNIT},
489 {RPCResult::Type::NUM, "n", "index"},
490 {RPCResult::Type::OBJ, "scriptPubKey", "",
491 {
492 {RPCResult::Type::STR, "asm", "the asm"},
493 {RPCResult::Type::STR_HEX, "hex", "the hex"},
494 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
495 {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
496 }},
497 }},
498 }},
499 }
500 },
502 HelpExampleCli("decoderawtransaction", "\"hexstring\"")
503 + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
504 },
505 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
506{
507 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
508
510
511 bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool();
512 bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool();
513
514 if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) {
515 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
516 }
517
518 UniValue result(UniValue::VOBJ);
519 TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
520
521 return result;
522},
523 };
524}
525
526static std::string GetAllOutputTypes()
527{
528 std::vector<std::string> ret;
529 using U = std::underlying_type<TxoutType>::type;
530 for (U i = (U)TxoutType::NONSTANDARD; i <= (U)TxoutType::WITNESS_UNKNOWN; ++i) {
531 ret.emplace_back(GetTxnOutputType(static_cast<TxoutType>(i)));
532 }
533 return Join(ret, ", ");
534}
535
537{
538 return RPCHelpMan{"decodescript",
539 "\nDecode a hex-encoded script.\n",
540 {
541 {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded script"},
542 },
543 RPCResult{
544 RPCResult::Type::OBJ, "", "",
545 {
546 {RPCResult::Type::STR, "asm", "Script public key"},
547 {RPCResult::Type::STR, "type", "The output type (e.g. "+GetAllOutputTypes()+")"},
548 {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
549 {RPCResult::Type::STR, "p2sh", /* optional */ true, "address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH)"},
550 {RPCResult::Type::OBJ, "segwit", /* optional */ true, "Result of a witness script public key wrapping this redeem script (not returned if the script is a P2SH or witness)",
551 {
552 {RPCResult::Type::STR, "asm", "String representation of the script public key"},
553 {RPCResult::Type::STR_HEX, "hex", "Hex string of the script public key"},
554 {RPCResult::Type::STR, "type", "The type of the script public key (e.g. witness_v0_keyhash or witness_v0_scripthash)"},
555 {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
556 {RPCResult::Type::STR, "p2sh-segwit", "address of the P2SH script wrapping this witness redeem script"},
557 }},
558 }
559 },
561 HelpExampleCli("decodescript", "\"hexstring\"")
562 + HelpExampleRpc("decodescript", "\"hexstring\"")
563 },
564 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
565{
566 RPCTypeCheck(request.params, {UniValue::VSTR});
567
569 CScript script;
570 if (request.params[0].get_str().size() > 0){
571 std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
572 script = CScript(scriptData.begin(), scriptData.end());
573 } else {
574 // Empty scripts are valid
575 }
576 ScriptPubKeyToUniv(script, r, /* include_hex */ false);
577
578 UniValue type;
579 type = find_value(r, "type");
580
581 if (type.isStr() && type.get_str() != "scripthash") {
582 // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
583 // don't return the address for a P2SH of the P2SH.
584 r.pushKV("p2sh", EncodeDestination(ScriptHash(script)));
585 // P2SH and witness programs cannot be wrapped in P2WSH, if this script
586 // is a witness program, don't return addresses for a segwit programs.
587 if (type.get_str() == "pubkey" || type.get_str() == "pubkeyhash" || type.get_str() == "multisig" || type.get_str() == "nonstandard") {
588 std::vector<std::vector<unsigned char>> solutions_data;
589 TxoutType which_type = Solver(script, solutions_data);
590 // Uncompressed pubkeys cannot be used with segwit checksigs.
591 // If the script contains an uncompressed pubkey, skip encoding of a segwit program.
592 if ((which_type == TxoutType::PUBKEY) || (which_type == TxoutType::MULTISIG)) {
593 for (const auto& solution : solutions_data) {
594 if ((solution.size() != 1) && !CPubKey(solution).IsCompressed()) {
595 return r;
596 }
597 }
598 }
600 CScript segwitScr;
601 if (which_type == TxoutType::PUBKEY) {
602 segwitScr = GetScriptForDestination(WitnessV0KeyHash(Hash160(solutions_data[0])));
603 } else if (which_type == TxoutType::PUBKEYHASH) {
604 segwitScr = GetScriptForDestination(WitnessV0KeyHash(uint160{solutions_data[0]}));
605 } else {
606 // Scripts that are not fit for P2WPKH are encoded as P2WSH.
607 // Newer segwit program versions should be considered when then become available.
608 segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script));
609 }
610 ScriptPubKeyToUniv(segwitScr, sr, /* include_hex */ true);
611 sr.pushKV("p2sh-segwit", EncodeDestination(ScriptHash(segwitScr)));
612 r.pushKV("segwit", sr);
613 }
614 }
615
616 return r;
617},
618 };
619}
620
622{
623 return RPCHelpMan{"combinerawtransaction",
624 "\nCombine multiple partially signed transactions into one transaction.\n"
625 "The combined transaction may be another partially signed transaction or a \n"
626 "fully signed transaction.",
627 {
628 {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex strings of partially signed transactions",
629 {
630 {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A hex-encoded raw transaction"},
631 },
632 },
633 },
634 RPCResult{
635 RPCResult::Type::STR, "", "The hex-encoded raw transaction with signature(s)"
636 },
638 HelpExampleCli("combinerawtransaction", R"('["myhex1", "myhex2", "myhex3"]')")
639 },
640 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
641{
642
643 UniValue txs = request.params[0].get_array();
644 std::vector<CMutableTransaction> txVariants(txs.size());
645
646 for (unsigned int idx = 0; idx < txs.size(); idx++) {
647 if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
648 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d. Make sure the tx has at least one input.", idx));
649 }
650 }
651
652 if (txVariants.empty()) {
653 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
654 }
655
656 // mergedTx will end up with all the signatures; it
657 // starts as a clone of the rawtx:
658 CMutableTransaction mergedTx(txVariants[0]);
659
660 // Fetch previous transactions (inputs):
661 CCoinsView viewDummy;
662 CCoinsViewCache view(&viewDummy);
663 {
664 NodeContext& node = EnsureAnyNodeContext(request.context);
665 const CTxMemPool& mempool = EnsureMemPool(node);
667 LOCK2(cs_main, mempool.cs);
668 CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip();
669 CCoinsViewMemPool viewMempool(&viewChain, mempool);
670 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
671
672 for (const CTxIn& txin : mergedTx.vin) {
673 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
674 }
675
676 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
677 }
678
679 // Use CTransaction for the constant parts of the
680 // transaction to avoid rehashing.
681 const CTransaction txConst(mergedTx);
682 // Sign what we can:
683 for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
684 CTxIn& txin = mergedTx.vin[i];
685 const Coin& coin = view.AccessCoin(txin.prevout);
686 if (coin.IsSpent()) {
687 throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
688 }
689 SignatureData sigdata;
690
691 // ... and merge in other signatures:
692 for (const CMutableTransaction& txv : txVariants) {
693 if (txv.vin.size() > i) {
694 sigdata.MergeSignatureData(DataFromTransaction(txv, i, coin.out));
695 }
696 }
698
699 UpdateInput(txin, sigdata);
700 }
701
702 return EncodeHexTx(CTransaction(mergedTx));
703},
704 };
705}
706
708{
709 return RPCHelpMan{"signrawtransactionwithkey",
710 "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
711 "The second argument is an array of base58-encoded private\n"
712 "keys that will be the only keys used to sign the transaction.\n"
713 "The third optional argument (may be null) is an array of previous transaction outputs that\n"
714 "this transaction depends on but may not yet be in the block chain.\n",
715 {
716 {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
717 {"privkeys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base58-encoded private keys for signing",
718 {
719 {"privatekey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "private key in base58-encoding"},
720 },
721 },
722 {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The previous dependent transaction outputs",
723 {
725 {
726 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
727 {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
728 {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "script key"},
729 {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
730 {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
731 {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
732 },
733 },
734 },
735 },
736 {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT"}, "The signature hash type. Must be one of:\n"
737 " \"DEFAULT\"\n"
738 " \"ALL\"\n"
739 " \"NONE\"\n"
740 " \"SINGLE\"\n"
741 " \"ALL|ANYONECANPAY\"\n"
742 " \"NONE|ANYONECANPAY\"\n"
743 " \"SINGLE|ANYONECANPAY\"\n"
744 },
745 },
746 RPCResult{
747 RPCResult::Type::OBJ, "", "",
748 {
749 {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
750 {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
751 {RPCResult::Type::ARR, "errors", /* optional */ true, "Script verification errors (if there are any)",
752 {
753 {RPCResult::Type::OBJ, "", "",
754 {
755 {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
756 {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
757 {RPCResult::Type::ARR, "witness", "",
758 {
759 {RPCResult::Type::STR_HEX, "witness", ""},
760 }},
761 {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
762 {RPCResult::Type::NUM, "sequence", "Script sequence number"},
763 {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
764 }},
765 }},
766 }
767 },
769 HelpExampleCli("signrawtransactionwithkey", "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"")
770 + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")
771 },
772 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
773{
774 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
775
777 if (!DecodeHexTx(mtx, request.params[0].get_str())) {
778 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
779 }
780
782 const UniValue& keys = request.params[1].get_array();
783 for (unsigned int idx = 0; idx < keys.size(); ++idx) {
784 UniValue k = keys[idx];
785 CKey key = DecodeSecret(k.get_str());
786 if (!key.IsValid()) {
787 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
788 }
789 keystore.AddKey(key);
790 }
791
792 // Fetch previous transactions (inputs):
793 std::map<COutPoint, Coin> coins;
794 for (const CTxIn& txin : mtx.vin) {
795 coins[txin.prevout]; // Create empty map entry keyed by prevout.
796 }
797 NodeContext& node = EnsureAnyNodeContext(request.context);
798 FindCoins(node, coins);
799
800 // Parse the prevtxs array
801 ParsePrevouts(request.params[2], &keystore, coins);
802
803 UniValue result(UniValue::VOBJ);
804 SignTransaction(mtx, &keystore, coins, request.params[3], result);
805 return result;
806},
807 };
808}
809
811{
812 return RPCHelpMan{"sendrawtransaction",
813 "\nSubmit a raw transaction (serialized, hex-encoded) to local node and network.\n"
814 "\nThe transaction will be sent unconditionally to all peers, so using sendrawtransaction\n"
815 "for manual rebroadcast may degrade privacy by leaking the transaction's origin, as\n"
816 "nodes will normally not rebroadcast non-wallet transactions already in their mempool.\n"
817 "\nA specific exception, RPC_TRANSACTION_ALREADY_IN_CHAIN, may throw if the transaction cannot be added to the mempool.\n"
818 "\nRelated RPCs: createrawtransaction, signrawtransactionwithkey\n",
819 {
820 {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
822 "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT +
823 "/kvB.\nSet to 0 to accept any fee rate.\n"},
824 },
825 RPCResult{
826 RPCResult::Type::STR_HEX, "", "The transaction hash in hex"
827 },
829 "\nCreate a transaction\n"
830 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
831 "Sign the transaction, and get back the hex\n"
832 + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
833 "\nSend the transaction (signed hex)\n"
834 + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
835 "\nAs a JSON-RPC call\n"
836 + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
837 },
838 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
839{
840 RPCTypeCheck(request.params, {
841 UniValue::VSTR,
842 UniValueType(), // VNUM or VSTR, checked inside AmountFromValue()
843 });
844
846 if (!DecodeHexTx(mtx, request.params[0].get_str())) {
847 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
848 }
849 CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
850
851 const CFeeRate max_raw_tx_fee_rate = request.params[1].isNull() ?
853 CFeeRate(AmountFromValue(request.params[1]));
854
855 int64_t virtual_size = GetVirtualTransactionSize(*tx);
856 CAmount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
857
858 std::string err_string;
860 NodeContext& node = EnsureAnyNodeContext(request.context);
861 const TransactionError err = BroadcastTransaction(node, tx, err_string, max_raw_tx_fee, /*relay*/ true, /*wait_callback*/ true);
862 if (TransactionError::OK != err) {
863 throw JSONRPCTransactionError(err, err_string);
864 }
865
866 return tx->GetHash().GetHex();
867},
868 };
869}
870
872{
873 return RPCHelpMan{"testmempoolaccept",
874 "\nReturns result of mempool acceptance tests indicating if raw transaction(s) (serialized, hex-encoded) would be accepted by mempool.\n"
875 "\nIf multiple transactions are passed in, parents must come before children and package policies apply: the transactions cannot conflict with any mempool transactions or each other.\n"
876 "\nIf one transaction fails, other transactions may not be fully validated (the 'allowed' key will be blank).\n"
877 "\nThe maximum number of transactions allowed is " + ToString(MAX_PACKAGE_COUNT) + ".\n"
878 "\nThis checks if transactions violate the consensus or policy rules.\n"
879 "\nSee sendrawtransaction call.\n",
880 {
881 {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings of raw transactions.",
882 {
884 },
885 },
887 "Reject transactions whose fee rate is higher than the specified value, expressed in " + CURRENCY_UNIT + "/kvB\n"},
888 },
889 RPCResult{
890 RPCResult::Type::ARR, "", "The result of the mempool acceptance test for each raw transaction in the input array.\n"
891 "Returns results for each transaction in the same order they were passed in.\n"
892 "Transactions that cannot be fully validated due to failures in other transactions will not contain an 'allowed' result.\n",
893 {
894 {RPCResult::Type::OBJ, "", "",
895 {
896 {RPCResult::Type::STR_HEX, "txid", "The transaction hash in hex"},
897 {RPCResult::Type::STR_HEX, "wtxid", "The transaction witness hash in hex"},
898 {RPCResult::Type::STR, "package-error", /* optional */ true, "Package validation error, if any (only possible if rawtxs had more than 1 transaction)."},
899 {RPCResult::Type::BOOL, "allowed", /* optional */ true, "Whether this tx would be accepted to the mempool and pass client-specified maxfeerate. "
900 "If not present, the tx was not fully validated due to a failure in another tx in the list."},
901 {RPCResult::Type::NUM, "vsize", /* optional */ true, "Virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted (only present when 'allowed' is true)"},
902 {RPCResult::Type::OBJ, "fees", /* optional */ true, "Transaction fees (only present if 'allowed' is true)",
903 {
904 {RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
905 }},
906 {RPCResult::Type::STR, "reject-reason", /* optional */ true, "Rejection string (only present when 'allowed' is false)"},
907 }},
908 }
909 },
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("signrawtransactionwithwallet", "\"myhex\"") +
915 "\nTest acceptance of the transaction (signed hex)\n"
916 + HelpExampleCli("testmempoolaccept", R"('["signedhex"]')") +
917 "\nAs a JSON-RPC call\n"
918 + HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")
919 },
920 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
921{
922 RPCTypeCheck(request.params, {
923 UniValue::VARR,
924 UniValueType(), // VNUM or VSTR, checked inside AmountFromValue()
925 });
926 const UniValue raw_transactions = request.params[0].get_array();
927 if (raw_transactions.size() < 1 || raw_transactions.size() > MAX_PACKAGE_COUNT) {
929 "Array must contain between 1 and " + ToString(MAX_PACKAGE_COUNT) + " transactions.");
930 }
931
932 const CFeeRate max_raw_tx_fee_rate = request.params[1].isNull() ?
934 CFeeRate(AmountFromValue(request.params[1]));
935
936 std::vector<CTransactionRef> txns;
937 txns.reserve(raw_transactions.size());
938 for (const auto& rawtx : raw_transactions.getValues()) {
940 if (!DecodeHexTx(mtx, rawtx.get_str())) {
942 "TX decode failed: " + rawtx.get_str() + " Make sure the tx has at least one input.");
943 }
944 txns.emplace_back(MakeTransactionRef(std::move(mtx)));
945 }
946
947 NodeContext& node = EnsureAnyNodeContext(request.context);
948 CTxMemPool& mempool = EnsureMemPool(node);
950 const PackageMempoolAcceptResult package_result = [&] {
951 LOCK(::cs_main);
952 if (txns.size() > 1) return ProcessNewPackage(chainstate, mempool, txns, /* test_accept */ true);
953 return PackageMempoolAcceptResult(txns[0]->GetWitnessHash(),
954 AcceptToMemoryPool(chainstate, mempool, txns[0], /* bypass_limits */ false, /* test_accept*/ true));
955 }();
956
957 UniValue rpc_result(UniValue::VARR);
958 // We will check transaction fees while we iterate through txns in order. If any transaction fee
959 // exceeds maxfeerate, we will leave the rest of the validation results blank, because it
960 // doesn't make sense to return a validation result for a transaction if its ancestor(s) would
961 // not be submitted.
962 bool exit_early{false};
963 for (const auto& tx : txns) {
964 UniValue result_inner(UniValue::VOBJ);
965 result_inner.pushKV("txid", tx->GetHash().GetHex());
966 result_inner.pushKV("wtxid", tx->GetWitnessHash().GetHex());
968 result_inner.pushKV("package-error", package_result.m_state.GetRejectReason());
969 }
970 auto it = package_result.m_tx_results.find(tx->GetWitnessHash());
971 if (exit_early || it == package_result.m_tx_results.end()) {
972 // Validation unfinished. Just return the txid and wtxid.
973 rpc_result.push_back(result_inner);
974 continue;
975 }
976 const auto& tx_result = it->second;
977 if (tx_result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
978 const CAmount fee = tx_result.m_base_fees.value();
979 // Check that fee does not exceed maximum fee
980 const int64_t virtual_size = GetVirtualTransactionSize(*tx);
981 const CAmount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
982 if (max_raw_tx_fee && fee > max_raw_tx_fee) {
983 result_inner.pushKV("allowed", false);
984 result_inner.pushKV("reject-reason", "max-fee-exceeded");
985 exit_early = true;
986 } else {
987 // Only return the fee and vsize if the transaction would pass ATMP.
988 // These can be used to calculate the feerate.
989 result_inner.pushKV("allowed", true);
990 result_inner.pushKV("vsize", virtual_size);
992 fees.pushKV("base", ValueFromAmount(fee));
993 result_inner.pushKV("fees", fees);
994 }
995 } else {
996 result_inner.pushKV("allowed", false);
997 const TxValidationState state = tx_result.m_state;
999 result_inner.pushKV("reject-reason", "missing-inputs");
1000 } else {
1001 result_inner.pushKV("reject-reason", state.GetRejectReason());
1002 }
1003 }
1004 rpc_result.push_back(result_inner);
1005 }
1006 return rpc_result;
1007},
1008 };
1009}
1010
1012{
1013 return RPCHelpMan{"decodepsbt",
1014 "\nReturn a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.\n",
1015 {
1016 {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The PSBT base64 string"},
1017 },
1018 RPCResult{
1019 RPCResult::Type::OBJ, "", "",
1020 {
1021 {RPCResult::Type::OBJ, "tx", "The decoded network-serialized unsigned transaction.",
1022 {
1023 {RPCResult::Type::ELISION, "", "The layout is the same as the output of decoderawtransaction."},
1024 }},
1025 {RPCResult::Type::OBJ_DYN, "unknown", "The unknown global fields",
1026 {
1027 {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1028 }},
1029 {RPCResult::Type::ARR, "inputs", "",
1030 {
1031 {RPCResult::Type::OBJ, "", "",
1032 {
1033 {RPCResult::Type::OBJ, "non_witness_utxo", /* optional */ true, "Decoded network transaction for non-witness UTXOs",
1034 {
1035 {RPCResult::Type::ELISION, "",""},
1036 }},
1037 {RPCResult::Type::OBJ, "witness_utxo", /* optional */ true, "Transaction output for witness UTXOs",
1038 {
1039 {RPCResult::Type::NUM, "amount", "The value in " + CURRENCY_UNIT},
1040 {RPCResult::Type::OBJ, "scriptPubKey", "",
1041 {
1042 {RPCResult::Type::STR, "asm", "The asm"},
1043 {RPCResult::Type::STR_HEX, "hex", "The hex"},
1044 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1045 {RPCResult::Type::STR, "address", /* optional */ true, "The Bitcoin address (only if a well-defined address exists)"},
1046 }},
1047 }},
1048 {RPCResult::Type::OBJ_DYN, "partial_signatures", /* optional */ true, "",
1049 {
1050 {RPCResult::Type::STR, "pubkey", "The public key and signature that corresponds to it."},
1051 }},
1052 {RPCResult::Type::STR, "sighash", /* optional */ true, "The sighash type to be used"},
1053 {RPCResult::Type::OBJ, "redeem_script", /* optional */ true, "",
1054 {
1055 {RPCResult::Type::STR, "asm", "The asm"},
1056 {RPCResult::Type::STR_HEX, "hex", "The hex"},
1057 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1058 }},
1059 {RPCResult::Type::OBJ, "witness_script", /* optional */ true, "",
1060 {
1061 {RPCResult::Type::STR, "asm", "The asm"},
1062 {RPCResult::Type::STR_HEX, "hex", "The hex"},
1063 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1064 }},
1065 {RPCResult::Type::ARR, "bip32_derivs", /* optional */ true, "",
1066 {
1067 {RPCResult::Type::OBJ, "", "",
1068 {
1069 {RPCResult::Type::STR, "pubkey", "The public key with the derivation path as the value."},
1070 {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
1071 {RPCResult::Type::STR, "path", "The path"},
1072 }},
1073 }},
1074 {RPCResult::Type::OBJ, "final_scriptSig", /* optional */ true, "",
1075 {
1076 {RPCResult::Type::STR, "asm", "The asm"},
1077 {RPCResult::Type::STR, "hex", "The hex"},
1078 }},
1079 {RPCResult::Type::ARR, "final_scriptwitness", /* optional */ true, "",
1080 {
1081 {RPCResult::Type::STR_HEX, "", "hex-encoded witness data (if any)"},
1082 }},
1083 {RPCResult::Type::OBJ_DYN, "unknown", /* optional */ true, "The unknown global fields",
1084 {
1085 {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1086 }},
1087 }},
1088 }},
1089 {RPCResult::Type::ARR, "outputs", "",
1090 {
1091 {RPCResult::Type::OBJ, "", "",
1092 {
1093 {RPCResult::Type::OBJ, "redeem_script", /* optional */ true, "",
1094 {
1095 {RPCResult::Type::STR, "asm", "The asm"},
1096 {RPCResult::Type::STR_HEX, "hex", "The hex"},
1097 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1098 }},
1099 {RPCResult::Type::OBJ, "witness_script", /* optional */ true, "",
1100 {
1101 {RPCResult::Type::STR, "asm", "The asm"},
1102 {RPCResult::Type::STR_HEX, "hex", "The hex"},
1103 {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1104 }},
1105 {RPCResult::Type::ARR, "bip32_derivs", /* optional */ true, "",
1106 {
1107 {RPCResult::Type::OBJ, "", "",
1108 {
1109 {RPCResult::Type::STR, "pubkey", "The public key this path corresponds to"},
1110 {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
1111 {RPCResult::Type::STR, "path", "The path"},
1112 }},
1113 }},
1114 {RPCResult::Type::OBJ_DYN, "unknown", /* optional */ true, "The unknown global fields",
1115 {
1116 {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1117 }},
1118 }},
1119 }},
1120 {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The transaction fee paid if all UTXOs slots in the PSBT have been filled."},
1121 }
1122 },
1124 HelpExampleCli("decodepsbt", "\"psbt\"")
1125 },
1126 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1127{
1128 RPCTypeCheck(request.params, {UniValue::VSTR});
1129
1130 // Unserialize the transactions
1132 std::string error;
1133 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1134 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1135 }
1136
1137 UniValue result(UniValue::VOBJ);
1138
1139 // Add the decoded tx
1140 UniValue tx_univ(UniValue::VOBJ);
1141 TxToUniv(CTransaction(*psbtx.tx), uint256(), tx_univ, false);
1142 result.pushKV("tx", tx_univ);
1143
1144 // Unknown data
1145 UniValue unknowns(UniValue::VOBJ);
1146 for (auto entry : psbtx.unknown) {
1147 unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1148 }
1149 result.pushKV("unknown", unknowns);
1150
1151 // inputs
1152 CAmount total_in = 0;
1153 bool have_all_utxos = true;
1154 UniValue inputs(UniValue::VARR);
1155 for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1156 const PSBTInput& input = psbtx.inputs[i];
1158 // UTXOs
1159 bool have_a_utxo = false;
1160 CTxOut txout;
1161 if (!input.witness_utxo.IsNull()) {
1162 txout = input.witness_utxo;
1163
1165 ScriptPubKeyToUniv(txout.scriptPubKey, o, /* include_hex */ true);
1166
1168 out.pushKV("amount", ValueFromAmount(txout.nValue));
1169 out.pushKV("scriptPubKey", o);
1170
1171 in.pushKV("witness_utxo", out);
1172
1173 have_a_utxo = true;
1174 }
1175 if (input.non_witness_utxo) {
1176 txout = input.non_witness_utxo->vout[psbtx.tx->vin[i].prevout.n];
1177
1178 UniValue non_wit(UniValue::VOBJ);
1179 TxToUniv(*input.non_witness_utxo, uint256(), non_wit, false);
1180 in.pushKV("non_witness_utxo", non_wit);
1181
1182 have_a_utxo = true;
1183 }
1184 if (have_a_utxo) {
1185 if (MoneyRange(txout.nValue) && MoneyRange(total_in + txout.nValue)) {
1186 total_in += txout.nValue;
1187 } else {
1188 // Hack to just not show fee later
1189 have_all_utxos = false;
1190 }
1191 } else {
1192 have_all_utxos = false;
1193 }
1194
1195 // Partial sigs
1196 if (!input.partial_sigs.empty()) {
1197 UniValue partial_sigs(UniValue::VOBJ);
1198 for (const auto& sig : input.partial_sigs) {
1199 partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second));
1200 }
1201 in.pushKV("partial_signatures", partial_sigs);
1202 }
1203
1204 // Sighash
1205 if (input.sighash_type > 0) {
1206 in.pushKV("sighash", SighashToStr((unsigned char)input.sighash_type));
1207 }
1208
1209 // Redeem script and witness script
1210 if (!input.redeem_script.empty()) {
1212 ScriptToUniv(input.redeem_script, r);
1213 in.pushKV("redeem_script", r);
1214 }
1215 if (!input.witness_script.empty()) {
1217 ScriptToUniv(input.witness_script, r);
1218 in.pushKV("witness_script", r);
1219 }
1220
1221 // keypaths
1222 if (!input.hd_keypaths.empty()) {
1223 UniValue keypaths(UniValue::VARR);
1224 for (auto entry : input.hd_keypaths) {
1225 UniValue keypath(UniValue::VOBJ);
1226 keypath.pushKV("pubkey", HexStr(entry.first));
1227
1228 keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1229 keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1230 keypaths.push_back(keypath);
1231 }
1232 in.pushKV("bip32_derivs", keypaths);
1233 }
1234
1235 // Final scriptSig and scriptwitness
1236 if (!input.final_script_sig.empty()) {
1237 UniValue scriptsig(UniValue::VOBJ);
1238 scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true));
1239 scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1240 in.pushKV("final_scriptSig", scriptsig);
1241 }
1242 if (!input.final_script_witness.IsNull()) {
1243 UniValue txinwitness(UniValue::VARR);
1244 for (const auto& item : input.final_script_witness.stack) {
1245 txinwitness.push_back(HexStr(item));
1246 }
1247 in.pushKV("final_scriptwitness", txinwitness);
1248 }
1249
1250 // Unknown data
1251 if (input.unknown.size() > 0) {
1252 UniValue unknowns(UniValue::VOBJ);
1253 for (auto entry : input.unknown) {
1254 unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1255 }
1256 in.pushKV("unknown", unknowns);
1257 }
1258
1259 inputs.push_back(in);
1260 }
1261 result.pushKV("inputs", inputs);
1262
1263 // outputs
1264 CAmount output_value = 0;
1265 UniValue outputs(UniValue::VARR);
1266 for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1267 const PSBTOutput& output = psbtx.outputs[i];
1269 // Redeem script and witness script
1270 if (!output.redeem_script.empty()) {
1272 ScriptToUniv(output.redeem_script, r);
1273 out.pushKV("redeem_script", r);
1274 }
1275 if (!output.witness_script.empty()) {
1277 ScriptToUniv(output.witness_script, r);
1278 out.pushKV("witness_script", r);
1279 }
1280
1281 // keypaths
1282 if (!output.hd_keypaths.empty()) {
1283 UniValue keypaths(UniValue::VARR);
1284 for (auto entry : output.hd_keypaths) {
1285 UniValue keypath(UniValue::VOBJ);
1286 keypath.pushKV("pubkey", HexStr(entry.first));
1287 keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1288 keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1289 keypaths.push_back(keypath);
1290 }
1291 out.pushKV("bip32_derivs", keypaths);
1292 }
1293
1294 // Unknown data
1295 if (output.unknown.size() > 0) {
1296 UniValue unknowns(UniValue::VOBJ);
1297 for (auto entry : output.unknown) {
1298 unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1299 }
1300 out.pushKV("unknown", unknowns);
1301 }
1302
1303 outputs.push_back(out);
1304
1305 // Fee calculation
1306 if (MoneyRange(psbtx.tx->vout[i].nValue) && MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
1307 output_value += psbtx.tx->vout[i].nValue;
1308 } else {
1309 // Hack to just not show fee later
1310 have_all_utxos = false;
1311 }
1312 }
1313 result.pushKV("outputs", outputs);
1314 if (have_all_utxos) {
1315 result.pushKV("fee", ValueFromAmount(total_in - output_value));
1316 }
1317
1318 return result;
1319},
1320 };
1321}
1322
1324{
1325 return RPCHelpMan{"combinepsbt",
1326 "\nCombine multiple partially signed Bitcoin transactions into one transaction.\n"
1327 "Implements the Combiner role.\n",
1328 {
1329 {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1330 {
1331 {"psbt", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A base64 string of a PSBT"},
1332 },
1333 },
1334 },
1335 RPCResult{
1336 RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1337 },
1339 HelpExampleCli("combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")
1340 },
1341 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1342{
1343 RPCTypeCheck(request.params, {UniValue::VARR}, true);
1344
1345 // Unserialize the transactions
1346 std::vector<PartiallySignedTransaction> psbtxs;
1347 UniValue txs = request.params[0].get_array();
1348 if (txs.empty()) {
1349 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txs' cannot be empty");
1350 }
1351 for (unsigned int i = 0; i < txs.size(); ++i) {
1353 std::string error;
1354 if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1355 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1356 }
1357 psbtxs.push_back(psbtx);
1358 }
1359
1360 PartiallySignedTransaction merged_psbt;
1361 const TransactionError error = CombinePSBTs(merged_psbt, psbtxs);
1362 if (error != TransactionError::OK) {
1364 }
1365
1367 ssTx << merged_psbt;
1368 return EncodeBase64(ssTx);
1369},
1370 };
1371}
1372
1374{
1375 return RPCHelpMan{"finalizepsbt",
1376 "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n"
1377 "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n"
1378 "created which has the final_scriptSig and final_scriptWitness fields filled for inputs that are complete.\n"
1379 "Implements the Finalizer and Extractor roles.\n",
1380 {
1381 {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1382 {"extract", RPCArg::Type::BOOL, RPCArg::Default{true}, "If true and the transaction is complete,\n"
1383 " extract and return the complete transaction in normal network serialization instead of the PSBT."},
1384 },
1385 RPCResult{
1386 RPCResult::Type::OBJ, "", "",
1387 {
1388 {RPCResult::Type::STR, "psbt", /* optional */ true, "The base64-encoded partially signed transaction if not extracted"},
1389 {RPCResult::Type::STR_HEX, "hex", /* optional */ true, "The hex-encoded network transaction if extracted"},
1390 {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1391 }
1392 },
1394 HelpExampleCli("finalizepsbt", "\"psbt\"")
1395 },
1396 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1397{
1398 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true);
1399
1400 // Unserialize the transactions
1402 std::string error;
1403 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1404 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1405 }
1406
1407 bool extract = request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool());
1408
1410 bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1411
1412 UniValue result(UniValue::VOBJ);
1414 std::string result_str;
1415
1416 if (complete && extract) {
1417 ssTx << mtx;
1418 result_str = HexStr(ssTx);
1419 result.pushKV("hex", result_str);
1420 } else {
1421 ssTx << psbtx;
1422 result_str = EncodeBase64(ssTx.str());
1423 result.pushKV("psbt", result_str);
1424 }
1425 result.pushKV("complete", complete);
1426
1427 return result;
1428},
1429 };
1430}
1431
1433{
1434 return RPCHelpMan{"createpsbt",
1435 "\nCreates a transaction in the Partially Signed Transaction format.\n"
1436 "Implements the Creator role.\n",
1437 {
1438 {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The json objects",
1439 {
1441 {
1442 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1443 {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1444 {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
1445 },
1446 },
1447 },
1448 },
1449 {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs (key-value pairs), where none of the keys are duplicated.\n"
1450 "That is, each address can only appear once and there can only be one 'data' object.\n"
1451 "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
1452 " accepted as second parameter.",
1453 {
1455 {
1456 {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT},
1457 },
1458 },
1460 {
1461 {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"},
1462 },
1463 },
1464 },
1465 },
1466 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
1467 {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{false}, "Marks this transaction as BIP125 replaceable.\n"
1468 " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."},
1469 },
1470 RPCResult{
1471 RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1472 },
1474 HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
1475 },
1476 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1477{
1478
1479 RPCTypeCheck(request.params, {
1480 UniValue::VARR,
1481 UniValueType(), // ARR or OBJ, checked later
1482 UniValue::VNUM,
1483 UniValue::VBOOL,
1484 }, true
1485 );
1486
1487 bool rbf = false;
1488 if (!request.params[3].isNull()) {
1489 rbf = request.params[3].isTrue();
1490 }
1491 CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf);
1492
1493 // Make a blank psbt
1495 psbtx.tx = rawTx;
1496 for (unsigned int i = 0; i < rawTx.vin.size(); ++i) {
1497 psbtx.inputs.push_back(PSBTInput());
1498 }
1499 for (unsigned int i = 0; i < rawTx.vout.size(); ++i) {
1500 psbtx.outputs.push_back(PSBTOutput());
1501 }
1502
1503 // Serialize the PSBT
1505 ssTx << psbtx;
1506
1507 return EncodeBase64(ssTx);
1508},
1509 };
1510}
1511
1513{
1514 return RPCHelpMan{"converttopsbt",
1515 "\nConverts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n"
1516 "createpsbt and walletcreatefundedpsbt should be used for new applications.\n",
1517 {
1518 {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of a raw transaction"},
1519 {"permitsigdata", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, any signatures in the input will be discarded and conversion\n"
1520 " will continue. If false, RPC will fail if any signatures are present."},
1521 {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
1522 "If iswitness is not present, heuristic tests will be used in decoding.\n"
1523 "If true, only witness deserialization will be tried.\n"
1524 "If false, only non-witness deserialization will be tried.\n"
1525 "This boolean should reflect whether the transaction has inputs\n"
1526 "(e.g. fully valid, or on-chain transactions), if known by the caller."
1527 },
1528 },
1529 RPCResult{
1530 RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1531 },
1533 "\nCreate a transaction\n"
1534 + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1535 "\nConvert the transaction to a PSBT\n"
1536 + HelpExampleCli("converttopsbt", "\"rawtransaction\"")
1537 },
1538 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1539{
1540 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL}, true);
1541
1542 // parse hex string from parameter
1544 bool permitsigdata = request.params[1].isNull() ? false : request.params[1].get_bool();
1545 bool witness_specified = !request.params[2].isNull();
1546 bool iswitness = witness_specified ? request.params[2].get_bool() : false;
1547 const bool try_witness = witness_specified ? iswitness : true;
1548 const bool try_no_witness = witness_specified ? !iswitness : true;
1549 if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
1550 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1551 }
1552
1553 // Remove all scriptSigs and scriptWitnesses from inputs
1554 for (CTxIn& input : tx.vin) {
1555 if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && !permitsigdata) {
1556 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
1557 }
1558 input.scriptSig.clear();
1559 input.scriptWitness.SetNull();
1560 }
1561
1562 // Make a blank psbt
1564 psbtx.tx = tx;
1565 for (unsigned int i = 0; i < tx.vin.size(); ++i) {
1566 psbtx.inputs.push_back(PSBTInput());
1567 }
1568 for (unsigned int i = 0; i < tx.vout.size(); ++i) {
1569 psbtx.outputs.push_back(PSBTOutput());
1570 }
1571
1572 // Serialize the PSBT
1574 ssTx << psbtx;
1575
1576 return EncodeBase64(ssTx);
1577},
1578 };
1579}
1580
1582{
1583 return RPCHelpMan{"utxoupdatepsbt",
1584 "\nUpdates all segwit inputs and outputs in a PSBT with data from output descriptors, the UTXO set or the mempool.\n",
1585 {
1586 {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1587 {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "An array of either strings or objects", {
1588 {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
1589 {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", {
1590 {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
1591 {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "Up to what index HD chains should be explored (either end or [begin,end])"},
1592 }},
1593 }},
1594 },
1595 RPCResult {
1596 RPCResult::Type::STR, "", "The base64-encoded partially signed transaction with inputs updated"
1597 },
1598 RPCExamples {
1599 HelpExampleCli("utxoupdatepsbt", "\"psbt\"")
1600 },
1601 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1602{
1603 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR}, true);
1604
1605 // Unserialize the transactions
1607 std::string error;
1608 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1609 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1610 }
1611
1612 // Parse descriptors, if any.
1613 FlatSigningProvider provider;
1614 if (!request.params[1].isNull()) {
1615 auto descs = request.params[1].get_array();
1616 for (size_t i = 0; i < descs.size(); ++i) {
1617 EvalDescriptorStringOrObject(descs[i], provider);
1618 }
1619 }
1620 // We don't actually need private keys further on; hide them as a precaution.
1621 HidingSigningProvider public_provider(&provider, /* nosign */ true, /* nobip32derivs */ false);
1622
1623 // Fetch previous transactions (inputs):
1624 CCoinsView viewDummy;
1625 CCoinsViewCache view(&viewDummy);
1626 {
1627 NodeContext& node = EnsureAnyNodeContext(request.context);
1628 const CTxMemPool& mempool = EnsureMemPool(node);
1630 LOCK2(cs_main, mempool.cs);
1631 CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip();
1632 CCoinsViewMemPool viewMempool(&viewChain, mempool);
1633 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
1634
1635 for (const CTxIn& txin : psbtx.tx->vin) {
1636 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
1637 }
1638
1639 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
1640 }
1641
1642 // Fill the inputs
1643 const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
1644 for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1645 PSBTInput& input = psbtx.inputs.at(i);
1646
1647 if (input.non_witness_utxo || !input.witness_utxo.IsNull()) {
1648 continue;
1649 }
1650
1651 const Coin& coin = view.AccessCoin(psbtx.tx->vin[i].prevout);
1652
1653 if (IsSegWitOutput(provider, coin.out.scriptPubKey)) {
1654 input.witness_utxo = coin.out;
1655 }
1656
1657 // Update script/keypath information using descriptor data.
1658 // Note that SignPSBTInput does a lot more than just constructing ECDSA signatures
1659 // we don't actually care about those here, in fact.
1660 SignPSBTInput(public_provider, psbtx, i, &txdata, /* sighash_type */ 1);
1661 }
1662
1663 // Update script/keypath information using descriptor data.
1664 for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1665 UpdatePSBTOutput(public_provider, psbtx, i);
1666 }
1667
1669 ssTx << psbtx;
1670 return EncodeBase64(ssTx);
1671},
1672 };
1673}
1674
1676{
1677 return RPCHelpMan{"joinpsbts",
1678 "\nJoins multiple distinct PSBTs with different inputs and outputs into one PSBT with inputs and outputs from all of the PSBTs\n"
1679 "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1680 {
1681 {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1682 {
1683 {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1684 }}
1685 },
1686 RPCResult {
1687 RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1688 },
1689 RPCExamples {
1690 HelpExampleCli("joinpsbts", "\"psbt\"")
1691 },
1692 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1693{
1694 RPCTypeCheck(request.params, {UniValue::VARR}, true);
1695
1696 // Unserialize the transactions
1697 std::vector<PartiallySignedTransaction> psbtxs;
1698 UniValue txs = request.params[0].get_array();
1699
1700 if (txs.size() <= 1) {
1701 throw JSONRPCError(RPC_INVALID_PARAMETER, "At least two PSBTs are required to join PSBTs.");
1702 }
1703
1704 uint32_t best_version = 1;
1705 uint32_t best_locktime = 0xffffffff;
1706 for (unsigned int i = 0; i < txs.size(); ++i) {
1708 std::string error;
1709 if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1710 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1711 }
1712 psbtxs.push_back(psbtx);
1713 // Choose the highest version number
1714 if (static_cast<uint32_t>(psbtx.tx->nVersion) > best_version) {
1715 best_version = static_cast<uint32_t>(psbtx.tx->nVersion);
1716 }
1717 // Choose the lowest lock time
1718 if (psbtx.tx->nLockTime < best_locktime) {
1719 best_locktime = psbtx.tx->nLockTime;
1720 }
1721 }
1722
1723 // Create a blank psbt where everything will be added
1724 PartiallySignedTransaction merged_psbt;
1725 merged_psbt.tx = CMutableTransaction();
1726 merged_psbt.tx->nVersion = static_cast<int32_t>(best_version);
1727 merged_psbt.tx->nLockTime = best_locktime;
1728
1729 // Merge
1730 for (auto& psbt : psbtxs) {
1731 for (unsigned int i = 0; i < psbt.tx->vin.size(); ++i) {
1732 if (!merged_psbt.AddInput(psbt.tx->vin[i], psbt.inputs[i])) {
1733 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input %s:%d exists in multiple PSBTs", psbt.tx->vin[i].prevout.hash.ToString(), psbt.tx->vin[i].prevout.n));
1734 }
1735 }
1736 for (unsigned int i = 0; i < psbt.tx->vout.size(); ++i) {
1737 merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1738 }
1739 merged_psbt.unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
1740 }
1741
1742 // Generate list of shuffled indices for shuffling inputs and outputs of the merged PSBT
1743 std::vector<int> input_indices(merged_psbt.inputs.size());
1744 std::iota(input_indices.begin(), input_indices.end(), 0);
1745 std::vector<int> output_indices(merged_psbt.outputs.size());
1746 std::iota(output_indices.begin(), output_indices.end(), 0);
1747
1748 // Shuffle input and output indices lists
1749 Shuffle(input_indices.begin(), input_indices.end(), FastRandomContext());
1750 Shuffle(output_indices.begin(), output_indices.end(), FastRandomContext());
1751
1752 PartiallySignedTransaction shuffled_psbt;
1753 shuffled_psbt.tx = CMutableTransaction();
1754 shuffled_psbt.tx->nVersion = merged_psbt.tx->nVersion;
1755 shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1756 for (int i : input_indices) {
1757 shuffled_psbt.AddInput(merged_psbt.tx->vin[i], merged_psbt.inputs[i]);
1758 }
1759 for (int i : output_indices) {
1760 shuffled_psbt.AddOutput(merged_psbt.tx->vout[i], merged_psbt.outputs[i]);
1761 }
1762 shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(), merged_psbt.unknown.end());
1763
1765 ssTx << shuffled_psbt;
1766 return EncodeBase64(ssTx);
1767},
1768 };
1769}
1770
1772{
1773 return RPCHelpMan{"analyzepsbt",
1774 "\nAnalyzes and provides information about the current status of a PSBT and its inputs\n",
1775 {
1776 {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1777 },
1778 RPCResult {
1779 RPCResult::Type::OBJ, "", "",
1780 {
1781 {RPCResult::Type::ARR, "inputs", /* optional */ true, "",
1782 {
1783 {RPCResult::Type::OBJ, "", "",
1784 {
1785 {RPCResult::Type::BOOL, "has_utxo", "Whether a UTXO is provided"},
1786 {RPCResult::Type::BOOL, "is_final", "Whether the input is finalized"},
1787 {RPCResult::Type::OBJ, "missing", /* optional */ true, "Things that are missing that are required to complete this input",
1788 {
1789 {RPCResult::Type::ARR, "pubkeys", /* optional */ true, "",
1790 {
1791 {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose BIP 32 derivation path is missing"},
1792 }},
1793 {RPCResult::Type::ARR, "signatures", /* optional */ true, "",
1794 {
1795 {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose signature is missing"},
1796 }},
1797 {RPCResult::Type::STR_HEX, "redeemscript", /* optional */ true, "Hash160 of the redeemScript that is missing"},
1798 {RPCResult::Type::STR_HEX, "witnessscript", /* optional */ true, "SHA256 of the witnessScript that is missing"},
1799 }},
1800 {RPCResult::Type::STR, "next", /* optional */ true, "Role of the next person that this input needs to go to"},
1801 }},
1802 }},
1803 {RPCResult::Type::NUM, "estimated_vsize", /* optional */ true, "Estimated vsize of the final signed transaction"},
1804 {RPCResult::Type::STR_AMOUNT, "estimated_feerate", /* optional */ true, "Estimated feerate of the final signed transaction in " + CURRENCY_UNIT + "/kvB. Shown only if all UTXO slots in the PSBT have been filled"},
1805 {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true, "The transaction fee paid. Shown only if all UTXO slots in the PSBT have been filled"},
1806 {RPCResult::Type::STR, "next", "Role of the next person that this psbt needs to go to"},
1807 {RPCResult::Type::STR, "error", /* optional */ true, "Error message (if there is one)"},
1808 }
1809 },
1810 RPCExamples {
1811 HelpExampleCli("analyzepsbt", "\"psbt\"")
1812 },
1813 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1814{
1815 RPCTypeCheck(request.params, {UniValue::VSTR});
1816
1817 // Unserialize the transaction
1819 std::string error;
1820 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1821 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1822 }
1823
1824 PSBTAnalysis psbta = AnalyzePSBT(psbtx);
1825
1826 UniValue result(UniValue::VOBJ);
1827 UniValue inputs_result(UniValue::VARR);
1828 for (const auto& input : psbta.inputs) {
1829 UniValue input_univ(UniValue::VOBJ);
1830 UniValue missing(UniValue::VOBJ);
1831
1832 input_univ.pushKV("has_utxo", input.has_utxo);
1833 input_univ.pushKV("is_final", input.is_final);
1834 input_univ.pushKV("next", PSBTRoleName(input.next));
1835
1836 if (!input.missing_pubkeys.empty()) {
1837 UniValue missing_pubkeys_univ(UniValue::VARR);
1838 for (const CKeyID& pubkey : input.missing_pubkeys) {
1839 missing_pubkeys_univ.push_back(HexStr(pubkey));
1840 }
1841 missing.pushKV("pubkeys", missing_pubkeys_univ);
1842 }
1843 if (!input.missing_redeem_script.IsNull()) {
1844 missing.pushKV("redeemscript", HexStr(input.missing_redeem_script));
1845 }
1846 if (!input.missing_witness_script.IsNull()) {
1847 missing.pushKV("witnessscript", HexStr(input.missing_witness_script));
1848 }
1849 if (!input.missing_sigs.empty()) {
1850 UniValue missing_sigs_univ(UniValue::VARR);
1851 for (const CKeyID& pubkey : input.missing_sigs) {
1852 missing_sigs_univ.push_back(HexStr(pubkey));
1853 }
1854 missing.pushKV("signatures", missing_sigs_univ);
1855 }
1856 if (!missing.getKeys().empty()) {
1857 input_univ.pushKV("missing", missing);
1858 }
1859 inputs_result.push_back(input_univ);
1860 }
1861 if (!inputs_result.empty()) result.pushKV("inputs", inputs_result);
1862
1863 if (psbta.estimated_vsize != std::nullopt) {
1864 result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
1865 }
1866 if (psbta.estimated_feerate != std::nullopt) {
1867 result.pushKV("estimated_feerate", ValueFromAmount(psbta.estimated_feerate->GetFeePerK()));
1868 }
1869 if (psbta.fee != std::nullopt) {
1870 result.pushKV("fee", ValueFromAmount(*psbta.fee));
1871 }
1872 result.pushKV("next", PSBTRoleName(psbta.next));
1873 if (!psbta.error.empty()) {
1874 result.pushKV("error", psbta.error);
1875 }
1876
1877 return result;
1878},
1879 };
1880}
1881
1883{
1884// clang-format off
1885static const CRPCCommand commands[] =
1886{ // category actor (function)
1887 // --------------------- -----------------------
1888 { "rawtransactions", &getrawtransaction, },
1889 { "rawtransactions", &createrawtransaction, },
1890 { "rawtransactions", &decoderawtransaction, },
1891 { "rawtransactions", &decodescript, },
1892 { "rawtransactions", &sendrawtransaction, },
1893 { "rawtransactions", &combinerawtransaction, },
1894 { "rawtransactions", &signrawtransactionwithkey, },
1895 { "rawtransactions", &testmempoolaccept, },
1896 { "rawtransactions", &decodepsbt, },
1897 { "rawtransactions", &combinepsbt, },
1898 { "rawtransactions", &finalizepsbt, },
1899 { "rawtransactions", &createpsbt, },
1900 { "rawtransactions", &converttopsbt, },
1901 { "rawtransactions", &utxoupdatepsbt, },
1902 { "rawtransactions", &joinpsbts, },
1903 { "rawtransactions", &analyzepsbt, },
1904
1905 { "blockchain", &gettxoutproof, },
1906 { "blockchain", &verifytxoutproof, },
1907};
1908// clang-format on
1909 for (const auto& c : commands) {
1910 t.appendCommand(c.name, &c);
1911 }
1912}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:63
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:550
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: blockchain.cpp:95
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: blockchain.cpp:65
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: blockchain.cpp:74
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: blockchain.cpp:87
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
const CChainParams & Params()
Return the currently selected parameters.
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:150
uint256 hashMerkleRoot
Definition: block.h:26
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:63
std::vector< CTransactionRef > vtx
Definition: block.h:66
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
int64_t GetBlockTime() const
Definition: chain.h:268
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:177
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:433
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:638
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:583
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:29
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:214
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
Abstract view on the open txout dataset.
Definition: coins.h:158
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:852
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:205
std::string str() const
Definition: streams.h:242
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:57
An encapsulated private key.
Definition: key.h:27
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:93
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:125
CBlockHeader header
Public only for unit testing.
Definition: merkleblock.h:128
CPartialMerkleTree txn
Definition: merkleblock.h:129
uint256 ExtractMatches(std::vector< uint256 > &vMatch, std::vector< unsigned int > &vnIndex)
extract the matching txid's represented by this partial merkle tree and their respective indices with...
unsigned int GetNumTransactions() const
Get number of transactions the merkle proof is indicating for cross-reference with local blockchain k...
Definition: merkleblock.h:113
An encapsulated public key.
Definition: pubkey.h:33
RPC command dispatcher.
Definition: server.h:126
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:270
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
void clear()
Definition: script.h:549
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
An input of a transaction.
Definition: transaction.h:66
CScript scriptSig
Definition: transaction.h:69
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:71
COutPoint prevout
Definition: transaction.h:68
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:511
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
CAmount nValue
Definition: transaction.h:131
bool IsNull() const
Definition: transaction.h:149
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
CChainState & ActiveChainstate() const
The most-work chain.
CChain & ActiveChain() const
Definition: validation.h:945
A UTXO entry.
Definition: coins.h:31
CTxOut out
unspent transaction output
Definition: coins.h:34
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
Fast randomness source.
Definition: random.h:120
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKey(const CKey &key)
A signature creator for transactions.
Definition: sign.h:39
const std::string & get_str() const
@ VOBJ
Definition: univalue.h:19
@ VARR
Definition: univalue.h:19
size_t size() const
Definition: univalue.h:66
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:64
bool isStr() const
Definition: univalue.h:79
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
const UniValue & get_array() const
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
std::string GetRejectReason() const
Definition: validation.h:123
Result GetResult() const
Definition: validation.h:122
bool IsNull() const
Definition: uint256.h:31
std::string GetHex() const
Definition: uint256.cpp:20
bool empty() const
Definition: prevector.h:286
160-bit opaque blob.
Definition: uint256.h:113
256-bit opaque blob.
Definition: uint256.h:124
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:11
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:265
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
std::string SighashToStr(unsigned char sighash_type)
Definition: core_write.cpp:79
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:93
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool include_hex, bool include_address=true)
Definition: core_write.cpp:150
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:138
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
Definition: core_write.cpp:166
void ScriptToUniv(const CScript &script, UniValue &out)
Definition: core_write.cpp:145
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:21
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:189
static uint32_t ReadBE32(const unsigned char *ptr)
Definition: common.h:63
TransactionError
Definition: error.h:22
const std::string CURRENCY_UNIT
Definition: feerate.h:14
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:256
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:178
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:15
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:15
TransactionError BroadcastTransaction(NodeContext &node, const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, bool relay, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
Definition: transaction.cpp:32
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
Return transaction with a given hash.
static const CFeeRate DEFAULT_MAX_RAW_TX_FEE_RATE
Maximum fee rate for sendrawtransaction and testmempoolaccept RPC calls.
Definition: transaction.h:25
static constexpr uint32_t MAX_PACKAGE_COUNT
Default maximum number of transactions in a package.
Definition: packages.h:15
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:285
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:23
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:374
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:213
std::string PSBTRoleName(PSBTRole role)
Definition: psbt.cpp:362
bool FinalizeAndExtractPSBT(PartiallySignedTransaction &psbtx, CMutableTransaction &result)
Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
Definition: psbt.cpp:333
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, int sighash, SignatureData *out_sigdata)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:250
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:233
TransactionError CombinePSBTs(PartiallySignedTransaction &out, const std::vector< PartiallySignedTransaction > &psbtxs)
Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial sign...
Definition: psbt.cpp:349
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:231
static RPCHelpMan getrawtransaction()
static RPCHelpMan sendrawtransaction()
static RPCHelpMan utxoupdatepsbt()
static std::string GetAllOutputTypes()
static RPCHelpMan gettxoutproof()
static RPCHelpMan converttopsbt()
static RPCHelpMan analyzepsbt()
static RPCHelpMan decoderawtransaction()
static void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry, CChainState &active_chainstate)
static RPCHelpMan combinepsbt()
static RPCHelpMan decodepsbt()
static RPCHelpMan decodescript()
static RPCHelpMan createpsbt()
static RPCHelpMan joinpsbts()
static RPCHelpMan combinerawtransaction()
static RPCHelpMan testmempoolaccept()
static RPCHelpMan verifytxoutproof()
static RPCHelpMan signrawtransactionwithkey()
static RPCHelpMan createrawtransaction()
static RPCHelpMan finalizepsbt()
void RegisterRawTransactionRPCCommands(CRPCTable &t)
Register raw transaction RPC commands.
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, bool rbf)
Create a transaction from univalue parameters.
void ParsePrevouts(const UniValue &prevTxsUnival, FillableSigningProvider *keystore, std::map< COutPoint, Coin > &coins)
Parse a prevtxs UniValue array and get the map of coins from it.
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:39
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:46
@ RPC_INTERNAL_ERROR
Definition: protocol.h:35
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:45
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:41
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:103
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:24
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:359
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
Definition: util.cpp:992
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:21
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:90
#define extract(n)
Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits.
@ SER_NETWORK
Definition: serialize.h:138
int RPCSerializationFlags()
Definition: server.cpp:540
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:331
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:492
bool IsSegWitOutput(const SigningProvider &provider, const CScript &script)
Check whether a scriptPubKey is known to be segwit.
Definition: sign.cpp:600
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:427
const SigningProvider & DUMMY_SIGNING_PROVIDER
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:144
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:49
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:310
TxoutType
Definition: standard.h:59
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string EncodeBase64(Span< const unsigned char > input)
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:44
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
A mutable version of CTransaction.
Definition: transaction.h:345
std::vector< CTxOut > vout
Definition: transaction.h:347
std::vector< CTxIn > vin
Definition: transaction.h:346
std::vector< std::vector< unsigned char > > stack
Definition: script.h:561
bool IsNull() const
Definition: script.h:566
void SetNull()
Definition: script.h:568
NodeContext struct containing references to chain state and connection state.
Definition: context.h:39
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:29
std::optional< size_t > estimated_vsize
Estimated weight of the transaction.
Definition: psbt.h:30
std::optional< CAmount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:32
std::vector< PSBTInputAnalysis > inputs
More information about the individual inputs of the transaction.
Definition: psbt.h:33
std::string error
Error message.
Definition: psbt.h:35
std::optional< CFeeRate > estimated_feerate
Estimated feerate (fee / weight) of the transaction.
Definition: psbt.h:31
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:34
A structure for PSBTs which contain per-input information.
Definition: psbt.h:50
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:57
CScriptWitness final_script_witness
Definition: psbt.h:56
CTransactionRef non_witness_utxo
Definition: psbt.h:51
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:58
int sighash_type
Definition: psbt.h:60
CScript redeem_script
Definition: psbt.h:53
CScript final_script_sig
Definition: psbt.h:55
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:59
CTxOut witness_utxo
Definition: psbt.h:52
CScript witness_script
Definition: psbt.h:54
A structure for PSBTs which contains per output information.
Definition: psbt.h:277
CScript witness_script
Definition: psbt.h:279
CScript redeem_script
Definition: psbt.h:278
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:280
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:281
Validation result for package mempool acceptance.
Definition: validation.h:189
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:197
const PackageValidationState m_state
Definition: validation.h:190
A version of CTransaction with the PSBT format.
Definition: psbt.h:392
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:396
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:53
std::vector< PSBTInput > inputs
Definition: psbt.h:394
std::optional< CMutableTransaction > tx
Definition: psbt.h:393
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:40
std::vector< PSBTOutput > outputs
Definition: psbt.h:395
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ OBJ_USER_KEYS
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e....
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
std::string DefaultHint
Definition: util.h:155
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:498
#define AssertLockNotHeld(cs)
Definition: sync.h:84
#define LOCK2(cs1, cs2)
Definition: sync.h:227
#define LOCK(cs)
Definition: sync.h:226
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:14
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Atomically test acceptance of a package.
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept)
(Try to) add a transaction to the memory pool.
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12