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