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