rawtransaction.cpp raw

   1  // Copyright (c) 2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka 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 <node/types.h>
  20  #include <policy/packages.h>
  21  #include <policy/policy.h>
  22  #include <policy/rbf.h>
  23  #include <primitives/transaction.h>
  24  #include <psbt.h>
  25  #include <random.h>
  26  #include <rpc/blockchain.h>
  27  #include <rpc/rawtransaction.h>
  28  #include <rpc/rawtransaction_util.h>
  29  #include <rpc/server.h>
  30  #include <rpc/server_util.h>
  31  #include <rpc/util.h>
  32  #include <script/script.h>
  33  #include <script/sign.h>
  34  #include <script/signingprovider.h>
  35  #include <script/solver.h>
  36  #include <uint256.h>
  37  #include <undo.h>
  38  #include <util/bip32.h>
  39  #include <util/check.h>
  40  #include <util/strencodings.h>
  41  #include <util/string.h>
  42  #include <util/vector.h>
  43  #include <validation.h>
  44  #include <validationinterface.h>
  45  
  46  #include <numeric>
  47  #include <stdint.h>
  48  
  49  #include <univalue.h>
  50  
  51  using node::AnalyzePSBT;
  52  using node::FindCoins;
  53  using node::GetTransaction;
  54  using node::NodeContext;
  55  using node::PSBTAnalysis;
  56  
  57  static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry,
  58                       Chainstate& active_chainstate, const CTxUndo* txundo = nullptr,
  59                       TxVerbosity verbosity = TxVerbosity::SHOW_DETAILS)
  60  {
  61      CHECK_NONFATAL(verbosity >= TxVerbosity::SHOW_DETAILS);
  62      // Call into TxToUniv() in limenka-common to decode the transaction hex.
  63      //
  64      // Blockchain contextual information (confirmations and blocktime) is not
  65      // available to code in limenka-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, 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                  const auto assumed_base = active_chainstate.SnapshotBase();
  77                  if (assumed_base && pindex->nHeight < assumed_base->nHeight) {
  78                      entry.pushKV("confirmations", 0);
  79                      entry.pushKV("confirmations_assumed", 1 + active_chainstate.m_chain.Height() - pindex->nHeight);
  80                  } else {
  81                  entry.pushKV("confirmations", 1 + active_chainstate.m_chain.Height() - pindex->nHeight);
  82                  }
  83                  entry.pushKV("time", pindex->GetBlockTime());
  84                  entry.pushKV("blocktime", pindex->GetBlockTime());
  85              }
  86              else
  87                  entry.pushKV("confirmations", 0);
  88          }
  89      }
  90  }
  91  
  92  std::vector<RPCResult> DecodeTxDoc(const std::string& txid_field_doc)
  93  {
  94      return {
  95          {RPCResult::Type::STR_HEX, "txid", txid_field_doc},
  96          {RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)"},
  97          {RPCResult::Type::NUM, "size", "The serialized transaction size"},
  98          {RPCResult::Type::NUM, "vsize", "The virtual transaction size (differs from size for witness transactions)"},
  99          {RPCResult::Type::NUM, "weight", "The transaction's weight (between vsize*4-3 and vsize*4)"},
 100          {RPCResult::Type::NUM, "version", "The version"},
 101          {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
 102          {RPCResult::Type::ARR, "vin", "",
 103          {
 104              {RPCResult::Type::OBJ, "", "",
 105              {
 106                  {RPCResult::Type::STR_HEX, "coinbase", /*optional=*/true, "The coinbase value (only if coinbase transaction)"},
 107                  {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id (if not coinbase transaction)"},
 108                  {RPCResult::Type::NUM, "vout", /*optional=*/true, "The output number (if not coinbase transaction)"},
 109                  {RPCResult::Type::OBJ, "scriptSig", /*optional=*/true, "The script (if not coinbase transaction)",
 110                  {
 111                      {RPCResult::Type::STR, "asm", "Disassembly of the signature script"},
 112                      {RPCResult::Type::STR_HEX, "hex", "The raw signature script bytes, hex-encoded"},
 113                  }},
 114                  {RPCResult::Type::ARR, "txinwitness", /*optional=*/true, "",
 115                  {
 116                      {RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
 117                  }},
 118                  {RPCResult::Type::NUM, "sequence", "The script sequence number"},
 119              }},
 120          }},
 121          {RPCResult::Type::ARR, "vout", "",
 122          {
 123              {RPCResult::Type::OBJ, "", "",
 124              {
 125                  {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
 126                  {RPCResult::Type::NUM, "n", "index"},
 127                  {RPCResult::Type::OBJ, "scriptPubKey", "", ScriptPubKeyDoc()},
 128              }},
 129          }},
 130      };
 131  }
 132  
 133  static std::vector<RPCArg> CreateTxDoc()
 134  {
 135      return {
 136          {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The inputs",
 137              {
 138                  {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
 139                      {
 140                          {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
 141                          {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
 142                          {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
 143                      },
 144                  },
 145              },
 146          },
 147          {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
 148                  "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
 149                  "At least one output of either type must be specified.\n"
 150                  "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
 151                  "                             accepted as second parameter.",
 152              {
 153                  {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
 154                      {
 155                          {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the limenka address, the value (float or string) is the amount in " + CURRENCY_UNIT},
 156                      },
 157                  },
 158                  {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
 159                      {
 160                          {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data that becomes a part of an OP_RETURN output"},
 161                      },
 162                  },
 163              },
 164           RPCArgOptions{.skip_type_check = true}},
 165          {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
 166          {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true}, "Marks this transaction as BIP125-replaceable.\n"
 167                  "Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."},
 168      };
 169  }
 170  
 171  // Update PSBT with information from the mempool, the UTXO set, the txindex, and the provided descriptors.
 172  // Optionally, sign the inputs that we can using information from the descriptors.
 173  PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std::any& context, const HidingSigningProvider& provider, int sighash_type, const std::optional<std::vector<CTransactionRef>>& prev_txs, bool finalize)
 174  {
 175      // Unserialize the transactions
 176      PartiallySignedTransaction psbtx;
 177      std::string error;
 178      if (!DecodeBase64PSBT(psbtx, psbt_string, error)) {
 179          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
 180      }
 181  
 182      if (g_txindex) g_txindex->BlockUntilSyncedToCurrentChain();
 183      const NodeContext& node = EnsureAnyNodeContext(context);
 184  
 185      // If we can't find the corresponding full transaction for all of our inputs,
 186      // this will be used to find just the utxos for the segwit inputs for which
 187      // the full transaction isn't found
 188      std::map<COutPoint, Coin> coins;
 189  
 190      // Filter prev_txs to unique txids and create lookup
 191      std::map<Txid, CTransactionRef> prev_tx_map;
 192      if (prev_txs.has_value()) {
 193          for (const auto& tx : prev_txs.value()) {
 194              const auto txid = tx->GetHash();
 195              if (prev_tx_map.count(txid)) {
 196                  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Duplicate txids in prev_txs %s", txid.GetHex()));
 197              }
 198              prev_tx_map[txid] = tx;
 199          }
 200      }
 201  
 202      // Fetch previous transactions:
 203      // First, look in prev_txs, the txindex, and the mempool
 204      for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
 205          PSBTInput& psbt_input = psbtx.inputs.at(i);
 206          const CTxIn& tx_in = psbtx.tx->vin.at(i);
 207  
 208          // The `non_witness_utxo` is the whole previous transaction
 209          if (psbt_input.non_witness_utxo) continue;
 210  
 211          CTransactionRef tx;
 212  
 213          // First look in provided dependant transactions
 214          if (prev_tx_map.contains(tx_in.prevout.hash)) {
 215              tx = prev_tx_map[tx_in.prevout.hash];
 216              // Sanity check it has an output
 217              // at the right index
 218              if (tx_in.prevout.n >= tx->vout.size()) {
 219                  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Previous tx has too few outputs for PSBT input %s", tx->GetHash().GetHex()));
 220              }
 221          }
 222          // Then look in the txindex
 223          if (!tx && g_txindex) {
 224              uint256 block_hash;
 225              g_txindex->FindTx(tx_in.prevout.hash, block_hash, tx);
 226          }
 227          // If we still don't have it look in the mempool
 228          if (!tx) {
 229              tx = node.mempool->get(tx_in.prevout.hash);
 230          }
 231          if (tx) {
 232              psbt_input.non_witness_utxo = tx;
 233          } else {
 234              coins[tx_in.prevout]; // Create empty map entry keyed by prevout
 235          }
 236      }
 237  
 238      // If we still haven't found all of the inputs, look for the missing ones in the utxo set
 239      if (!coins.empty()) {
 240          FindCoins(node, coins);
 241          for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
 242              PSBTInput& input = psbtx.inputs.at(i);
 243  
 244              // If there are still missing utxos, add them if they were found in the utxo set
 245              if (!input.non_witness_utxo) {
 246                  const CTxIn& tx_in = psbtx.tx->vin.at(i);
 247                  const Coin& coin = coins.at(tx_in.prevout);
 248                  if (!coin.out.IsNull() && IsSegWitOutput(provider, coin.out.scriptPubKey)) {
 249                      input.witness_utxo = coin.out;
 250                  }
 251              }
 252          }
 253      }
 254  
 255      const PrecomputedTransactionData& txdata = PrecomputePSBTData(psbtx);
 256  
 257      for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
 258          if (PSBTInputSigned(psbtx.inputs.at(i))) {
 259              continue;
 260          }
 261  
 262          // Update script/keypath information using descriptor data.
 263          // Note that SignPSBTInput does a lot more than just constructing ECDSA signatures.
 264          // We only actually care about those if our signing provider doesn't hide private
 265          // information, as is the case with `descriptorprocesspsbt`
 266          SignPSBTInput(provider, psbtx, /*index=*/i, &txdata, sighash_type, /*out_sigdata=*/nullptr, finalize);
 267      }
 268  
 269      // Update script/keypath information using descriptor data.
 270      for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
 271          UpdatePSBTOutput(provider, psbtx, i);
 272      }
 273  
 274      RemoveUnnecessaryTransactions(psbtx, /*sighash_type=*/1);
 275  
 276      return psbtx;
 277  }
 278  
 279  static RPCHelpMan getrawtransaction()
 280  {
 281      return RPCHelpMan{
 282                  "getrawtransaction",
 283  
 284                  "By default, this call only returns a transaction if it is in the mempool. If -txindex is enabled\n"
 285                  "and no blockhash argument is passed, it will return the transaction if it is in the mempool or any block.\n"
 286                  "If a blockhash argument is passed, it will return the transaction if\n"
 287                  "the specified block is available and the transaction is in that block.\n\n"
 288                  "Hint: Use gettransaction for wallet transactions.\n\n"
 289  
 290                  "If verbosity is 0 or omitted, returns the serialized transaction as a hex-encoded string.\n"
 291                  "If verbosity is 1, returns a JSON Object with information about the transaction.\n"
 292                  "If verbosity is 2, returns a JSON Object with information about the transaction, including fee and prevout information.",
 293                  {
 294                      {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
 295                      {"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",
 296                       RPCArgOptions{.skip_type_check = true}},
 297                      {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The block in which to look for the transaction"},
 298                  },
 299                  {
 300                      RPCResult{"if verbosity is not set or set to 0",
 301                           RPCResult::Type::STR, "data", "The serialized transaction as a hex-encoded string for 'txid'"
 302                       },
 303                       RPCResult{"if verbosity is set to 1",
 304                           RPCResult::Type::OBJ, "", "",
 305                           Cat<std::vector<RPCResult>>(
 306                           {
 307                               {RPCResult::Type::BOOL, "in_active_chain", /*optional=*/true, "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},
 308                               {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "the block hash"},
 309                               {RPCResult::Type::NUM, "confirmations", /*optional=*/true, "The confirmations"},
 310                               {RPCResult::Type::NUM, "confirmations_assumed", /*optional=*/true, "The number of unverified confirmations (eg, in an assumed-valid UTXO set)"},
 311                               {RPCResult::Type::NUM_TIME, "blocktime", /*optional=*/true, "The block time expressed in " + UNIX_EPOCH_TIME},
 312                               {RPCResult::Type::NUM, "time", /*optional=*/true, "Same as \"blocktime\""},
 313                               {RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded data for 'txid'"},
 314                           },
 315                           DecodeTxDoc(/*txid_field_doc=*/"The transaction id (same as provided)")),
 316                      },
 317                      RPCResult{"for verbosity = 2",
 318                          RPCResult::Type::OBJ, "", "",
 319                          {
 320                              {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
 321                              {RPCResult::Type::NUM, "fee", /*optional=*/true, "transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
 322                              {RPCResult::Type::ARR, "vin", "",
 323                              {
 324                                  {RPCResult::Type::OBJ, "", "utxo being spent",
 325                                  {
 326                                      {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
 327                                      {RPCResult::Type::OBJ, "prevout", /*optional=*/true, "The previous output, omitted if block undo data is not available",
 328                                      {
 329                                          {RPCResult::Type::BOOL, "generated", "Coinbase or not"},
 330                                          {RPCResult::Type::NUM, "height", "The height of the prevout"},
 331                                          {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
 332                                          {RPCResult::Type::OBJ, "scriptPubKey", "", ScriptPubKeyDoc()},
 333                                      }},
 334                                  }},
 335                              }},
 336                          }},
 337                  },
 338                  RPCExamples{
 339                      HelpExampleCli("getrawtransaction", "\"mytxid\"")
 340              + HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
 341              + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
 342              + HelpExampleCli("getrawtransaction", "\"mytxid\" 0 \"myblockhash\"")
 343              + HelpExampleCli("getrawtransaction", "\"mytxid\" 1 \"myblockhash\"")
 344              + HelpExampleCli("getrawtransaction", "\"mytxid\" 2 \"myblockhash\"")
 345                  },
 346          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 347  {
 348      const NodeContext& node = EnsureAnyNodeContext(request.context);
 349      ChainstateManager& chainman = EnsureChainman(node);
 350  
 351      uint256 hash = ParseHashV(request.params[0], "parameter 1");
 352      const CBlockIndex* blockindex = nullptr;
 353  
 354      if (hash == chainman.GetParams().GenesisBlock().hashMerkleRoot) {
 355          // Special exception for the genesis block coinbase transaction
 356          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
 357      }
 358  
 359      int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/0, /*allow_bool=*/true)};
 360  
 361      if (!request.params[2].isNull()) {
 362          LOCK(cs_main);
 363  
 364          uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
 365          blockindex = chainman.m_blockman.LookupBlockIndex(blockhash);
 366          if (!blockindex) {
 367              throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
 368          }
 369      }
 370  
 371      bool f_txindex_ready = false;
 372      if (g_txindex && !blockindex) {
 373          f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
 374      }
 375  
 376      uint256 hash_block;
 377      const CTransactionRef tx = GetTransaction(blockindex, node.mempool.get(), hash, hash_block, chainman.m_blockman);
 378      if (!tx) {
 379          std::string errmsg;
 380          if (blockindex) {
 381              const bool block_has_data = WITH_LOCK(::cs_main, return blockindex->nStatus & BLOCK_HAVE_DATA);
 382              if (!block_has_data) {
 383                  throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
 384              }
 385              errmsg = "No such transaction found in the provided block";
 386          } else if (!g_txindex) {
 387              errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries";
 388          } else if (!f_txindex_ready) {
 389              errmsg = "No such mempool transaction. Blockchain transactions are still in the process of being indexed";
 390          } else {
 391              errmsg = "No such mempool or blockchain transaction";
 392          }
 393          throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
 394      }
 395  
 396      if (verbosity <= 0) {
 397          return EncodeHexTx(*tx);
 398      }
 399  
 400      UniValue result(UniValue::VOBJ);
 401      if (blockindex) {
 402          LOCK(cs_main);
 403          result.pushKV("in_active_chain", chainman.ActiveChain().Contains(blockindex));
 404      }
 405      // If request is verbosity >= 1 but no blockhash was given, then look up the blockindex
 406      if (request.params[2].isNull()) {
 407          LOCK(cs_main);
 408          blockindex = chainman.m_blockman.LookupBlockIndex(hash_block); // May be nullptr for mempool transactions
 409      }
 410      if (verbosity == 1) {
 411          TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
 412          return result;
 413      }
 414  
 415      CBlockUndo blockUndo;
 416      CBlock block;
 417  
 418      if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return !(blockindex->nStatus & BLOCK_HAVE_MASK))) {
 419          TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
 420          return result;
 421      }
 422      if (!chainman.m_blockman.ReadBlockUndo(blockUndo, *blockindex)) {
 423          throw JSONRPCError(RPC_INTERNAL_ERROR, "Undo data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
 424      }
 425      if (!chainman.m_blockman.ReadBlock(block, *blockindex)) {
 426          throw JSONRPCError(RPC_INTERNAL_ERROR, "Block data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
 427      }
 428  
 429      CTxUndo* undoTX {nullptr};
 430      auto it = std::find_if(block.vtx.begin(), block.vtx.end(), [tx](CTransactionRef t){ return *t == *tx; });
 431      if (it != block.vtx.end()) {
 432          // -1 as blockundo does not have coinbase tx
 433          undoTX = &blockUndo.vtxundo.at(it - block.vtx.begin() - 1);
 434      }
 435      TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate(), undoTX, TxVerbosity::SHOW_DETAILS_AND_PREVOUT);
 436      return result;
 437  },
 438      };
 439  }
 440  
 441  static RPCHelpMan createrawtransaction()
 442  {
 443      return RPCHelpMan{"createrawtransaction",
 444                  "\nCreate a transaction spending the given inputs and creating new outputs.\n"
 445                  "Outputs can be addresses or data.\n"
 446                  "Returns hex-encoded raw transaction.\n"
 447                  "Note that the transaction's inputs are not signed, and\n"
 448                  "it is not stored in the wallet or transmitted to the network.\n",
 449                  CreateTxDoc(),
 450                  RPCResult{
 451                      RPCResult::Type::STR_HEX, "transaction", "hex string of the transaction"
 452                  },
 453                  RPCExamples{
 454                      HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
 455              + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
 456              + HelpExampleRpc("createrawtransaction", "[{\"txid\":\"myid\",\"vout\":0}], [{\"address\":0.01}]")
 457              + HelpExampleRpc("createrawtransaction", "[{\"txid\":\"myid\",\"vout\":0}], [{\"data\":\"00010203\"}]")
 458                  },
 459          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 460  {
 461      std::optional<bool> rbf;
 462      if (!request.params[3].isNull()) {
 463          rbf = request.params[3].get_bool();
 464      }
 465      CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf);
 466  
 467      return EncodeHexTx(CTransaction(rawTx));
 468  },
 469      };
 470  }
 471  
 472  static RPCHelpMan decoderawtransaction()
 473  {
 474      return RPCHelpMan{"decoderawtransaction",
 475                  "Return a JSON object representing the serialized, hex-encoded transaction.",
 476                  {
 477                      {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction hex string"},
 478                      {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
 479                          "If iswitness is not present, heuristic tests will be used in decoding.\n"
 480                          "If true, only witness deserialization will be tried.\n"
 481                          "If false, only non-witness deserialization will be tried.\n"
 482                          "This boolean should reflect whether the transaction has inputs\n"
 483                          "(e.g. fully valid, or on-chain transactions), if known by the caller."
 484                      },
 485                  },
 486                  RPCResult{
 487                      RPCResult::Type::OBJ, "", "",
 488                      DecodeTxDoc(/*txid_field_doc=*/"The transaction id"),
 489                  },
 490                  RPCExamples{
 491                      HelpExampleCli("decoderawtransaction", "\"hexstring\"")
 492              + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
 493                  },
 494          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 495  {
 496      CMutableTransaction mtx;
 497  
 498      bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool();
 499      bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool();
 500  
 501      if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) {
 502          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
 503      }
 504  
 505      UniValue result(UniValue::VOBJ);
 506      TxToUniv(CTransaction(std::move(mtx)), /*block_hash=*/uint256(), /*entry=*/result, /*include_hex=*/false);
 507  
 508      return result;
 509  },
 510      };
 511  }
 512  
 513  static RPCHelpMan decodescript()
 514  {
 515      return RPCHelpMan{
 516          "decodescript",
 517          "\nDecode a hex-encoded script.\n",
 518          {
 519              {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded script"},
 520          },
 521          RPCResult{
 522              RPCResult::Type::OBJ, "", "",
 523              {
 524                  {RPCResult::Type::STR, "asm", "Disassembly of the script"},
 525                  {RPCResult::Type::STR, "desc", "Inferred descriptor for the script"},
 526                  {RPCResult::Type::STR, "type", "The output type (e.g. " + GetAllOutputTypes() + ")"},
 527                  {RPCResult::Type::STR, "address", /*optional=*/true, "The Limenka address (only if a well-defined address exists)"},
 528                  {RPCResult::Type::STR, "p2sh", /*optional=*/true,
 529                   "address of P2SH script wrapping this redeem script (not returned for types that should not be wrapped)"},
 530                  {RPCResult::Type::OBJ, "segwit", /*optional=*/true,
 531                   "Result of a witness output script wrapping this redeem script (not returned for types that should not be wrapped)",
 532                   {
 533                       {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
 534                       {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
 535                       {RPCResult::Type::STR, "address", /*optional=*/true, "The Limenka address (only if a well-defined address exists)"},
 536                       {RPCResult::Type::STR, "desc", "Inferred descriptor for the script"},
 537                       {RPCResult::Type::STR, "type", "The type of the output script (one of: " + GetAllOutputTypes() + ")"},
 538                       {RPCResult::Type::STR, "p2sh-segwit", "address of the P2SH script wrapping this witness redeem script"},
 539                   }},
 540              },
 541          },
 542          RPCExamples{
 543              HelpExampleCli("decodescript", "\"hexstring\"")
 544            + HelpExampleRpc("decodescript", "\"hexstring\"")
 545          },
 546          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 547  {
 548      UniValue r(UniValue::VOBJ);
 549      CScript script;
 550      if (request.params[0].get_str().size() > 0){
 551          std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
 552          script = CScript(scriptData.begin(), scriptData.end());
 553      } else {
 554          // Empty scripts are valid
 555      }
 556      ScriptToUniv(script, /*out=*/r, /*include_hex=*/false, /*include_address=*/true);
 557  
 558      std::vector<std::vector<unsigned char>> solutions_data;
 559      const TxoutType which_type{Solver(script, solutions_data)};
 560  
 561      const bool can_wrap{[&] {
 562          switch (which_type) {
 563          case TxoutType::MULTISIG:
 564          case TxoutType::NONSTANDARD:
 565          case TxoutType::PUBKEY:
 566          case TxoutType::PUBKEYHASH:
 567          case TxoutType::WITNESS_V0_KEYHASH:
 568          case TxoutType::WITNESS_V0_SCRIPTHASH:
 569              // Can be wrapped if the checks below pass
 570              break;
 571          case TxoutType::NULL_DATA:
 572          case TxoutType::SCRIPTHASH:
 573          case TxoutType::WITNESS_UNKNOWN:
 574          case TxoutType::WITNESS_V1_TAPROOT:
 575          case TxoutType::WITNESS_V3_SPKHASH:
 576          case TxoutType::ANCHOR:
 577              // Should not be wrapped
 578              return false;
 579          } // no default case, so the compiler can warn about missing cases
 580          if (!script.HasValidOps() || script.IsUnspendable()) {
 581              return false;
 582          }
 583          for (CScript::const_iterator it{script.begin()}; it != script.end();) {
 584              opcodetype op;
 585              CHECK_NONFATAL(script.GetOp(it, op));
 586              if (op == OP_CHECKSIGADD || IsOpSuccess(op)) {
 587                  return false;
 588              }
 589          }
 590          return true;
 591      }()};
 592  
 593      if (can_wrap) {
 594          r.pushKV("p2sh", EncodeDestination(ScriptHash(script)));
 595          // P2SH and witness programs cannot be wrapped in P2WSH, if this script
 596          // is a witness program, don't return addresses for a segwit programs.
 597          const bool can_wrap_P2WSH{[&] {
 598              switch (which_type) {
 599              case TxoutType::MULTISIG:
 600              case TxoutType::PUBKEY:
 601              // Uncompressed pubkeys cannot be used with segwit checksigs.
 602              // If the script contains an uncompressed pubkey, skip encoding of a segwit program.
 603                  for (const auto& solution : solutions_data) {
 604                      if ((solution.size() != 1) && !CPubKey(solution).IsCompressed()) {
 605                          return false;
 606                      }
 607                  }
 608                  return true;
 609              case TxoutType::NONSTANDARD:
 610              case TxoutType::PUBKEYHASH:
 611                  // Can be P2WSH wrapped
 612                  return true;
 613              case TxoutType::NULL_DATA:
 614              case TxoutType::SCRIPTHASH:
 615              case TxoutType::WITNESS_UNKNOWN:
 616              case TxoutType::WITNESS_V0_KEYHASH:
 617              case TxoutType::WITNESS_V0_SCRIPTHASH:
 618              case TxoutType::WITNESS_V1_TAPROOT:
 619              case TxoutType::WITNESS_V3_SPKHASH:
 620              case TxoutType::ANCHOR:
 621                  // Should not be wrapped
 622                  return false;
 623              } // no default case, so the compiler can warn about missing cases
 624              NONFATAL_UNREACHABLE();
 625          }()};
 626          if (can_wrap_P2WSH) {
 627              UniValue sr(UniValue::VOBJ);
 628              CScript segwitScr;
 629              FlatSigningProvider provider;
 630              if (which_type == TxoutType::PUBKEY) {
 631                  segwitScr = GetScriptForDestination(WitnessV0KeyHash(Hash160(solutions_data[0])));
 632              } else if (which_type == TxoutType::PUBKEYHASH) {
 633                  segwitScr = GetScriptForDestination(WitnessV0KeyHash(uint160{solutions_data[0]}));
 634              } else {
 635                  // Scripts that are not fit for P2WPKH are encoded as P2WSH.
 636                  provider.scripts[CScriptID(script)] = script;
 637                  segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script));
 638              }
 639              ScriptToUniv(segwitScr, /*out=*/sr, /*include_hex=*/true, /*include_address=*/true, /*provider=*/&provider);
 640              sr.pushKV("p2sh-segwit", EncodeDestination(ScriptHash(segwitScr)));
 641              r.pushKV("segwit", std::move(sr));
 642          }
 643      }
 644  
 645      return r;
 646  },
 647      };
 648  }
 649  
 650  static RPCHelpMan combinerawtransaction()
 651  {
 652      return RPCHelpMan{"combinerawtransaction",
 653                  "\nCombine multiple partially signed transactions into one transaction.\n"
 654                  "The combined transaction may be another partially signed transaction or a \n"
 655                  "fully signed transaction.",
 656                  {
 657                      {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex strings of partially signed transactions",
 658                          {
 659                              {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A hex-encoded raw transaction"},
 660                          },
 661                          },
 662                  },
 663                  RPCResult{
 664                      RPCResult::Type::STR, "", "The hex-encoded raw transaction with signature(s)"
 665                  },
 666                  RPCExamples{
 667                      HelpExampleCli("combinerawtransaction", R"('["myhex1", "myhex2", "myhex3"]')")
 668                  },
 669          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 670  {
 671  
 672      UniValue txs = request.params[0].get_array();
 673      std::vector<CMutableTransaction> txVariants(txs.size());
 674  
 675      for (unsigned int idx = 0; idx < txs.size(); idx++) {
 676          if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
 677              throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d. Make sure the tx has at least one input.", idx));
 678          }
 679      }
 680  
 681      if (txVariants.empty()) {
 682          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
 683      }
 684  
 685      // mergedTx will end up with all the signatures; it
 686      // starts as a clone of the rawtx:
 687      CMutableTransaction mergedTx(txVariants[0]);
 688  
 689      // Fetch previous transactions (inputs):
 690      CCoinsView viewDummy;
 691      CCoinsViewCache view(&viewDummy);
 692      {
 693          NodeContext& node = EnsureAnyNodeContext(request.context);
 694          const CTxMemPool& mempool = EnsureMemPool(node);
 695          ChainstateManager& chainman = EnsureChainman(node);
 696          LOCK2(cs_main, mempool.cs);
 697          CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip();
 698          CCoinsViewMemPool viewMempool(&viewChain, mempool);
 699          view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
 700  
 701          for (const CTxIn& txin : mergedTx.vin) {
 702              view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
 703          }
 704  
 705          view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
 706      }
 707  
 708      // Use CTransaction for the constant parts of the
 709      // transaction to avoid rehashing.
 710      const CTransaction txConst(mergedTx);
 711      // Sign what we can:
 712      for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
 713          CTxIn& txin = mergedTx.vin[i];
 714          const Coin& coin = view.AccessCoin(txin.prevout);
 715          if (coin.IsSpent()) {
 716              throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
 717          }
 718          SignatureData sigdata;
 719  
 720          // ... and merge in other signatures:
 721          for (const CMutableTransaction& txv : txVariants) {
 722              if (txv.vin.size() > i) {
 723                  sigdata.MergeSignatureData(DataFromTransaction(txv, i, coin.out));
 724              }
 725          }
 726          ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(mergedTx, i, coin.out.nValue, 1), coin.out.scriptPubKey, sigdata);
 727  
 728          UpdateInput(txin, sigdata);
 729      }
 730  
 731      return EncodeHexTx(CTransaction(mergedTx));
 732  },
 733      };
 734  }
 735  
 736  static RPCHelpMan signrawtransactionwithkey()
 737  {
 738      return RPCHelpMan{"signrawtransactionwithkey",
 739                  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
 740                  "The second argument is an array of base58-encoded private\n"
 741                  "keys that will be the only keys used to sign the transaction.\n"
 742                  "The third optional argument (may be null) is an array of previous transaction outputs that\n"
 743                  "this transaction depends on but may not yet be in the block chain.\n",
 744                  {
 745                      {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
 746                      {"privkeys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base58-encoded private keys for signing",
 747                          {
 748                              {"privatekey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "private key in base58-encoding"},
 749                          },
 750                          },
 751                      {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The previous dependent transaction outputs",
 752                          {
 753                              {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
 754                                  {
 755                                      {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
 756                                      {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
 757                                      {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "output script"},
 758                                      {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
 759                                      {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
 760                                      {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
 761                                  },
 762                                  },
 763                          },
 764                          },
 765                      {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of:\n"
 766              "       \"DEFAULT\"\n"
 767              "       \"ALL\"\n"
 768              "       \"NONE\"\n"
 769              "       \"SINGLE\"\n"
 770              "       \"ALL|ANYONECANPAY\"\n"
 771              "       \"NONE|ANYONECANPAY\"\n"
 772              "       \"SINGLE|ANYONECANPAY\"\n"
 773                      },
 774                  },
 775                  RPCResult{
 776                      RPCResult::Type::OBJ, "", "",
 777                      {
 778                          {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
 779                          {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
 780                          {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The fee (input amounts minus output amounts), if known"},
 781                          {RPCResult::Type::STR_AMOUNT, "feerate", /*optional=*/true, "The fee rate (in " + CURRENCY_UNIT + "/kB), if fee is known"},
 782                          {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)",
 783                          {
 784                              {RPCResult::Type::OBJ, "", "",
 785                              {
 786                                  {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
 787                                  {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
 788                                  {RPCResult::Type::ARR, "witness", "",
 789                                  {
 790                                      {RPCResult::Type::STR_HEX, "witness", ""},
 791                                  }},
 792                                  {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
 793                                  {RPCResult::Type::NUM, "sequence", "Script sequence number"},
 794                                  {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
 795                              }},
 796                          }},
 797                      }
 798                  },
 799                  RPCExamples{
 800                      HelpExampleCli("signrawtransactionwithkey", "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"")
 801              + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\", [\"key1\",\"key2\"]")
 802                  },
 803          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
 804  {
 805      CMutableTransaction mtx;
 806      if (!DecodeHexTx(mtx, request.params[0].get_str())) {
 807          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
 808      }
 809  
 810      FlatSigningProvider keystore;
 811      const UniValue& keys = request.params[1].get_array();
 812      for (unsigned int idx = 0; idx < keys.size(); ++idx) {
 813          UniValue k = keys[idx];
 814          CKey key = DecodeSecret(k.get_str());
 815          if (!key.IsValid()) {
 816              throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
 817          }
 818  
 819          CPubKey pubkey = key.GetPubKey();
 820          CKeyID key_id = pubkey.GetID();
 821          keystore.pubkeys.emplace(key_id, pubkey);
 822          keystore.keys.emplace(key_id, key);
 823      }
 824  
 825      // Fetch previous transactions (inputs):
 826      std::map<COutPoint, Coin> coins;
 827      for (const CTxIn& txin : mtx.vin) {
 828          coins[txin.prevout]; // Create empty map entry keyed by prevout.
 829      }
 830      NodeContext& node = EnsureAnyNodeContext(request.context);
 831      FindCoins(node, coins);
 832  
 833      // Parse the prevtxs array
 834      ParsePrevouts(request.params[2], &keystore, coins);
 835  
 836      UniValue result(UniValue::VOBJ);
 837      SignTransaction(mtx, &keystore, coins, request.params[3], result);
 838      return result;
 839  },
 840      };
 841  }
 842  
 843  const RPCResult& DecodePSBTInputs()
 844  {
 845      static const RPCResult decodepsbt_inputs{
 846      RPCResult::Type::ARR, "inputs", "",
 847      {
 848          {RPCResult::Type::OBJ, "", "",
 849          {
 850              {RPCResult::Type::OBJ, "non_witness_utxo", /*optional=*/true, "Decoded network transaction for non-witness UTXOs",
 851              {
 852                  {RPCResult::Type::ELISION, "",""},
 853              }},
 854              {RPCResult::Type::OBJ, "witness_utxo", /*optional=*/true, "Transaction output for witness UTXOs",
 855              {
 856                  {RPCResult::Type::NUM, "amount", "The value in " + CURRENCY_UNIT},
 857                  {RPCResult::Type::OBJ, "scriptPubKey", "",
 858                  {
 859                      {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
 860                      {RPCResult::Type::STR, "desc", "Inferred descriptor for the script"},
 861                      {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
 862                      {RPCResult::Type::STR, "address", /*optional=*/true, "The Limenka address (only if a well-defined address exists)"},
 863                      {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
 864                  }},
 865              }},
 866              {RPCResult::Type::OBJ_DYN, "partial_signatures", /*optional=*/true, "",
 867              {
 868                  {RPCResult::Type::STR, "pubkey", "The public key and signature that corresponds to it."},
 869              }},
 870              {RPCResult::Type::STR, "sighash", /*optional=*/true, "The sighash type to be used"},
 871              {RPCResult::Type::OBJ, "redeem_script", /*optional=*/true, "",
 872              {
 873                  {RPCResult::Type::STR, "asm", "Disassembly of the redeem script"},
 874                  {RPCResult::Type::STR_HEX, "hex", "The raw redeem script bytes, hex-encoded"},
 875                  {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
 876              }},
 877              {RPCResult::Type::OBJ, "witness_script", /*optional=*/true, "",
 878              {
 879                  {RPCResult::Type::STR, "asm", "Disassembly of the witness script"},
 880                  {RPCResult::Type::STR_HEX, "hex", "The raw witness script bytes, hex-encoded"},
 881                  {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
 882              }},
 883              {RPCResult::Type::ARR, "bip32_derivs", /*optional=*/true, "",
 884              {
 885                  {RPCResult::Type::OBJ, "", "",
 886                  {
 887                      {RPCResult::Type::STR, "pubkey", "The public key with the derivation path as the value."},
 888                      {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
 889                      {RPCResult::Type::STR, "path", "The path"},
 890                  }},
 891              }},
 892              {RPCResult::Type::OBJ, "final_scriptSig", /*optional=*/true, "",
 893              {
 894                  {RPCResult::Type::STR, "asm", "Disassembly of the final signature script"},
 895                  {RPCResult::Type::STR_HEX, "hex", "The raw final signature script bytes, hex-encoded"},
 896              }},
 897              {RPCResult::Type::ARR, "final_scriptwitness", /*optional=*/true, "",
 898              {
 899                  {RPCResult::Type::STR_HEX, "", "hex-encoded witness data (if any)"},
 900              }},
 901              {RPCResult::Type::OBJ_DYN, "ripemd160_preimages", /*optional=*/ true, "",
 902              {
 903                  {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
 904              }},
 905              {RPCResult::Type::OBJ_DYN, "sha256_preimages", /*optional=*/ true, "",
 906              {
 907                  {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
 908              }},
 909              {RPCResult::Type::OBJ_DYN, "hash160_preimages", /*optional=*/ true, "",
 910              {
 911                  {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
 912              }},
 913              {RPCResult::Type::OBJ_DYN, "hash256_preimages", /*optional=*/ true, "",
 914              {
 915                  {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
 916              }},
 917              {RPCResult::Type::STR_HEX, "taproot_key_path_sig", /*optional=*/ true, "hex-encoded signature for the Taproot key path spend"},
 918              {RPCResult::Type::ARR, "taproot_script_path_sigs", /*optional=*/ true, "",
 919              {
 920                  {RPCResult::Type::OBJ, "signature", /*optional=*/ true, "The signature for the pubkey and leaf hash combination",
 921                  {
 922                      {RPCResult::Type::STR, "pubkey", "The x-only pubkey for this signature"},
 923                      {RPCResult::Type::STR, "leaf_hash", "The leaf hash for this signature"},
 924                      {RPCResult::Type::STR, "sig", "The signature itself"},
 925                  }},
 926              }},
 927              {RPCResult::Type::ARR, "taproot_scripts", /*optional=*/ true, "",
 928              {
 929                  {RPCResult::Type::OBJ, "", "",
 930                  {
 931                      {RPCResult::Type::STR_HEX, "script", "A leaf script"},
 932                      {RPCResult::Type::NUM, "leaf_ver", "The version number for the leaf script"},
 933                      {RPCResult::Type::ARR, "control_blocks", "The control blocks for this script",
 934                      {
 935                          {RPCResult::Type::STR_HEX, "control_block", "A hex-encoded control block for this script"},
 936                      }},
 937                  }},
 938              }},
 939              {RPCResult::Type::ARR, "taproot_bip32_derivs", /*optional=*/ true, "",
 940              {
 941                  {RPCResult::Type::OBJ, "", "",
 942                  {
 943                      {RPCResult::Type::STR, "pubkey", "The x-only public key this path corresponds to"},
 944                      {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
 945                      {RPCResult::Type::STR, "path", "The path"},
 946                      {RPCResult::Type::ARR, "leaf_hashes", "The hashes of the leaves this pubkey appears in",
 947                      {
 948                          {RPCResult::Type::STR_HEX, "hash", "The hash of a leaf this pubkey appears in"},
 949                      }},
 950                  }},
 951              }},
 952              {RPCResult::Type::STR_HEX, "taproot_internal_key", /*optional=*/ true, "The hex-encoded Taproot x-only internal key"},
 953              {RPCResult::Type::STR_HEX, "taproot_merkle_root", /*optional=*/ true, "The hex-encoded Taproot merkle root"},
 954              {RPCResult::Type::OBJ_DYN, "unknown", /*optional=*/ true, "The unknown input fields",
 955              {
 956                  {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
 957              }},
 958              {RPCResult::Type::ARR, "proprietary", /*optional=*/true, "The input proprietary map",
 959              {
 960                  {RPCResult::Type::OBJ, "", "",
 961                  {
 962                      {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
 963                      {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
 964                      {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
 965                      {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
 966                  }},
 967              }},
 968          }},
 969      }
 970  };
 971      return decodepsbt_inputs;
 972  }
 973  
 974  const RPCResult& DecodePSBTOutputs()
 975  {
 976      static const RPCResult decodepsbt_outputs{
 977      RPCResult::Type::ARR, "outputs", "",
 978      {
 979          {RPCResult::Type::OBJ, "", "",
 980          {
 981              {RPCResult::Type::OBJ, "redeem_script", /*optional=*/true, "",
 982              {
 983                  {RPCResult::Type::STR, "asm", "Disassembly of the redeem script"},
 984                  {RPCResult::Type::STR_HEX, "hex", "The raw redeem script bytes, hex-encoded"},
 985                  {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
 986              }},
 987              {RPCResult::Type::OBJ, "witness_script", /*optional=*/true, "",
 988              {
 989                  {RPCResult::Type::STR, "asm", "Disassembly of the witness script"},
 990                  {RPCResult::Type::STR_HEX, "hex", "The raw witness script bytes, hex-encoded"},
 991                  {RPCResult::Type::STR, "type", "The type (one of: " + GetAllOutputTypes() + ")"},
 992              }},
 993              {RPCResult::Type::ARR, "bip32_derivs", /*optional=*/true, "",
 994              {
 995                  {RPCResult::Type::OBJ, "", "",
 996                  {
 997                      {RPCResult::Type::STR, "pubkey", "The public key this path corresponds to"},
 998                      {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
 999                      {RPCResult::Type::STR, "path", "The path"},
1000                  }},
1001              }},
1002              {RPCResult::Type::STR_HEX, "taproot_internal_key", /*optional=*/ true, "The hex-encoded Taproot x-only internal key"},
1003              {RPCResult::Type::ARR, "taproot_tree", /*optional=*/ true, "The tuples that make up the Taproot tree, in depth first search order",
1004              {
1005                  {RPCResult::Type::OBJ, "tuple", /*optional=*/ true, "A single leaf script in the taproot tree",
1006                  {
1007                      {RPCResult::Type::NUM, "depth", "The depth of this element in the tree"},
1008                      {RPCResult::Type::NUM, "leaf_ver", "The version of this leaf"},
1009                      {RPCResult::Type::STR, "script", "The hex-encoded script itself"},
1010                  }},
1011              }},
1012              {RPCResult::Type::ARR, "taproot_bip32_derivs", /*optional=*/ true, "",
1013              {
1014                  {RPCResult::Type::OBJ, "", "",
1015                  {
1016                      {RPCResult::Type::STR, "pubkey", "The x-only public key this path corresponds to"},
1017                      {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
1018                      {RPCResult::Type::STR, "path", "The path"},
1019                      {RPCResult::Type::ARR, "leaf_hashes", "The hashes of the leaves this pubkey appears in",
1020                      {
1021                          {RPCResult::Type::STR_HEX, "hash", "The hash of a leaf this pubkey appears in"},
1022                      }},
1023                  }},
1024              }},
1025              {RPCResult::Type::OBJ_DYN, "unknown", /*optional=*/true, "The unknown output fields",
1026              {
1027                  {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1028              }},
1029              {RPCResult::Type::ARR, "proprietary", /*optional=*/true, "The output proprietary map",
1030              {
1031                  {RPCResult::Type::OBJ, "", "",
1032                  {
1033                      {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
1034                      {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
1035                      {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
1036                      {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
1037                  }},
1038              }},
1039          }},
1040      }
1041  };
1042      return decodepsbt_outputs;
1043  }
1044  
1045  static RPCHelpMan decodepsbt()
1046  {
1047      return RPCHelpMan{
1048          "decodepsbt",
1049          "Return a JSON object representing the serialized, base64-encoded partially signed Limenka transaction.",
1050                  {
1051                      {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The PSBT base64 string"},
1052                  },
1053                  RPCResult{
1054                      RPCResult::Type::OBJ, "", "",
1055                      {
1056                          {RPCResult::Type::OBJ, "tx", "The decoded network-serialized unsigned transaction.",
1057                          {
1058                              {RPCResult::Type::ELISION, "", "The layout is the same as the output of decoderawtransaction."},
1059                          }},
1060                          {RPCResult::Type::ARR, "global_xpubs", "",
1061                          {
1062                              {RPCResult::Type::OBJ, "", "",
1063                              {
1064                                  {RPCResult::Type::STR, "xpub", "The extended public key this path corresponds to"},
1065                                  {RPCResult::Type::STR_HEX, "master_fingerprint", "The fingerprint of the master key"},
1066                                  {RPCResult::Type::STR, "path", "The path"},
1067                              }},
1068                          }},
1069                          {RPCResult::Type::NUM, "psbt_version", "The PSBT version number. Not to be confused with the unsigned transaction version"},
1070                          {RPCResult::Type::ARR, "proprietary", "The global proprietary map",
1071                          {
1072                              {RPCResult::Type::OBJ, "", "",
1073                              {
1074                                  {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
1075                                  {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
1076                                  {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
1077                                  {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
1078                              }},
1079                          }},
1080                          {RPCResult::Type::OBJ_DYN, "unknown", "The unknown global fields",
1081                          {
1082                               {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1083                          }},
1084                          DecodePSBTInputs(),
1085                          DecodePSBTOutputs(),
1086                          {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The transaction fee paid if all UTXOs slots in the PSBT have been filled."},
1087                      }
1088                  },
1089                  RPCExamples{
1090                      HelpExampleCli("decodepsbt", "\"psbt\"")
1091                  },
1092          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1093  {
1094      // Unserialize the transactions
1095      PartiallySignedTransaction psbtx;
1096      std::string error;
1097      if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1098          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1099      }
1100  
1101      UniValue result(UniValue::VOBJ);
1102  
1103      // Add the decoded tx
1104      UniValue tx_univ(UniValue::VOBJ);
1105      TxToUniv(CTransaction(*psbtx.tx), /*block_hash=*/uint256(), /*entry=*/tx_univ, /*include_hex=*/false);
1106      result.pushKV("tx", std::move(tx_univ));
1107  
1108      // Add the global xpubs
1109      UniValue global_xpubs(UniValue::VARR);
1110      for (std::pair<KeyOriginInfo, std::set<CExtPubKey>> xpub_pair : psbtx.m_xpubs) {
1111          for (auto& xpub : xpub_pair.second) {
1112              std::vector<unsigned char> ser_xpub;
1113              ser_xpub.assign(BIP32_EXTKEY_WITH_VERSION_SIZE, 0);
1114              xpub.EncodeWithVersion(ser_xpub.data());
1115  
1116              UniValue keypath(UniValue::VOBJ);
1117              keypath.pushKV("xpub", EncodeBase58Check(ser_xpub));
1118              keypath.pushKV("master_fingerprint", HexStr(Span<unsigned char>(xpub_pair.first.fingerprint, xpub_pair.first.fingerprint + 4)));
1119              keypath.pushKV("path", WriteHDKeypath(xpub_pair.first.path));
1120              global_xpubs.push_back(std::move(keypath));
1121          }
1122      }
1123      result.pushKV("global_xpubs", std::move(global_xpubs));
1124  
1125      // PSBT version
1126      result.pushKV("psbt_version", static_cast<uint64_t>(psbtx.GetVersion()));
1127  
1128      // Proprietary
1129      UniValue proprietary(UniValue::VARR);
1130      for (const auto& entry : psbtx.m_proprietary) {
1131          UniValue this_prop(UniValue::VOBJ);
1132          this_prop.pushKV("identifier", HexStr(entry.identifier));
1133          this_prop.pushKV("subtype", entry.subtype);
1134          this_prop.pushKV("key", HexStr(entry.key));
1135          this_prop.pushKV("value", HexStr(entry.value));
1136          proprietary.push_back(std::move(this_prop));
1137      }
1138      result.pushKV("proprietary", std::move(proprietary));
1139  
1140      // Unknown data
1141      UniValue unknowns(UniValue::VOBJ);
1142      for (auto entry : psbtx.unknown) {
1143          unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1144      }
1145      result.pushKV("unknown", std::move(unknowns));
1146  
1147      // inputs
1148      CAmount total_in = 0;
1149      bool have_all_utxos = true;
1150      UniValue inputs(UniValue::VARR);
1151      for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1152          const PSBTInput& input = psbtx.inputs[i];
1153          UniValue in(UniValue::VOBJ);
1154          // UTXOs
1155          bool have_a_utxo = false;
1156          CTxOut txout;
1157          if (!input.witness_utxo.IsNull()) {
1158              txout = input.witness_utxo;
1159  
1160              UniValue o(UniValue::VOBJ);
1161              ScriptToUniv(txout.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1162  
1163              UniValue out(UniValue::VOBJ);
1164              out.pushKV("amount", ValueFromAmount(txout.nValue));
1165              out.pushKV("scriptPubKey", std::move(o));
1166  
1167              in.pushKV("witness_utxo", std::move(out));
1168  
1169              have_a_utxo = true;
1170          }
1171          if (input.non_witness_utxo) {
1172              txout = input.non_witness_utxo->vout[psbtx.tx->vin[i].prevout.n];
1173  
1174              UniValue non_wit(UniValue::VOBJ);
1175              TxToUniv(*input.non_witness_utxo, /*block_hash=*/uint256(), /*entry=*/non_wit, /*include_hex=*/false);
1176              in.pushKV("non_witness_utxo", std::move(non_wit));
1177  
1178              have_a_utxo = true;
1179          }
1180          if (have_a_utxo) {
1181              if (MoneyRange(txout.nValue) && MoneyRange(total_in + txout.nValue)) {
1182                  total_in += txout.nValue;
1183              } else {
1184                  // Hack to just not show fee later
1185                  have_all_utxos = false;
1186              }
1187          } else {
1188              have_all_utxos = false;
1189          }
1190  
1191          // Partial sigs
1192          if (!input.partial_sigs.empty()) {
1193              UniValue partial_sigs(UniValue::VOBJ);
1194              for (const auto& sig : input.partial_sigs) {
1195                  partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second));
1196              }
1197              in.pushKV("partial_signatures", std::move(partial_sigs));
1198          }
1199  
1200          // Sighash
1201          if (input.sighash_type != std::nullopt) {
1202              in.pushKV("sighash", SighashToStr((unsigned char)*input.sighash_type));
1203          }
1204  
1205          // Redeem script and witness script
1206          if (!input.redeem_script.empty()) {
1207              UniValue r(UniValue::VOBJ);
1208              ScriptToUniv(input.redeem_script, /*out=*/r);
1209              in.pushKV("redeem_script", std::move(r));
1210          }
1211          if (!input.witness_script.empty()) {
1212              UniValue r(UniValue::VOBJ);
1213              ScriptToUniv(input.witness_script, /*out=*/r);
1214              in.pushKV("witness_script", std::move(r));
1215          }
1216  
1217          // keypaths
1218          if (!input.hd_keypaths.empty()) {
1219              UniValue keypaths(UniValue::VARR);
1220              for (auto entry : input.hd_keypaths) {
1221                  UniValue keypath(UniValue::VOBJ);
1222                  keypath.pushKV("pubkey", HexStr(entry.first));
1223  
1224                  keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1225                  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1226                  keypaths.push_back(std::move(keypath));
1227              }
1228              in.pushKV("bip32_derivs", std::move(keypaths));
1229          }
1230  
1231          // Final scriptSig and scriptwitness
1232          if (!input.final_script_sig.empty()) {
1233              UniValue scriptsig(UniValue::VOBJ);
1234              scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true));
1235              scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1236              in.pushKV("final_scriptSig", std::move(scriptsig));
1237          }
1238          if (!input.final_script_witness.IsNull()) {
1239              UniValue txinwitness(UniValue::VARR);
1240              for (const auto& item : input.final_script_witness.stack) {
1241                  txinwitness.push_back(HexStr(item));
1242              }
1243              in.pushKV("final_scriptwitness", std::move(txinwitness));
1244          }
1245  
1246          // Ripemd160 hash preimages
1247          if (!input.ripemd160_preimages.empty()) {
1248              UniValue ripemd160_preimages(UniValue::VOBJ);
1249              for (const auto& [hash, preimage] : input.ripemd160_preimages) {
1250                  ripemd160_preimages.pushKV(HexStr(hash), HexStr(preimage));
1251              }
1252              in.pushKV("ripemd160_preimages", std::move(ripemd160_preimages));
1253          }
1254  
1255          // Sha256 hash preimages
1256          if (!input.sha256_preimages.empty()) {
1257              UniValue sha256_preimages(UniValue::VOBJ);
1258              for (const auto& [hash, preimage] : input.sha256_preimages) {
1259                  sha256_preimages.pushKV(HexStr(hash), HexStr(preimage));
1260              }
1261              in.pushKV("sha256_preimages", std::move(sha256_preimages));
1262          }
1263  
1264          // Hash160 hash preimages
1265          if (!input.hash160_preimages.empty()) {
1266              UniValue hash160_preimages(UniValue::VOBJ);
1267              for (const auto& [hash, preimage] : input.hash160_preimages) {
1268                  hash160_preimages.pushKV(HexStr(hash), HexStr(preimage));
1269              }
1270              in.pushKV("hash160_preimages", std::move(hash160_preimages));
1271          }
1272  
1273          // Hash256 hash preimages
1274          if (!input.hash256_preimages.empty()) {
1275              UniValue hash256_preimages(UniValue::VOBJ);
1276              for (const auto& [hash, preimage] : input.hash256_preimages) {
1277                  hash256_preimages.pushKV(HexStr(hash), HexStr(preimage));
1278              }
1279              in.pushKV("hash256_preimages", std::move(hash256_preimages));
1280          }
1281  
1282          // Taproot key path signature
1283          if (!input.m_tap_key_sig.empty()) {
1284              in.pushKV("taproot_key_path_sig", HexStr(input.m_tap_key_sig));
1285          }
1286  
1287          // Taproot script path signatures
1288          if (!input.m_tap_script_sigs.empty()) {
1289              UniValue script_sigs(UniValue::VARR);
1290              for (const auto& [pubkey_leaf, sig] : input.m_tap_script_sigs) {
1291                  const auto& [xonly, leaf_hash] = pubkey_leaf;
1292                  UniValue sigobj(UniValue::VOBJ);
1293                  sigobj.pushKV("pubkey", HexStr(xonly));
1294                  sigobj.pushKV("leaf_hash", HexStr(leaf_hash));
1295                  sigobj.pushKV("sig", HexStr(sig));
1296                  script_sigs.push_back(std::move(sigobj));
1297              }
1298              in.pushKV("taproot_script_path_sigs", std::move(script_sigs));
1299          }
1300  
1301          // Taproot leaf scripts
1302          if (!input.m_tap_scripts.empty()) {
1303              UniValue tap_scripts(UniValue::VARR);
1304              for (const auto& [leaf, control_blocks] : input.m_tap_scripts) {
1305                  const auto& [script, leaf_ver] = leaf;
1306                  UniValue script_info(UniValue::VOBJ);
1307                  script_info.pushKV("script", HexStr(script));
1308                  script_info.pushKV("leaf_ver", leaf_ver);
1309                  UniValue control_blocks_univ(UniValue::VARR);
1310                  for (const auto& control_block : control_blocks) {
1311                      control_blocks_univ.push_back(HexStr(control_block));
1312                  }
1313                  script_info.pushKV("control_blocks", std::move(control_blocks_univ));
1314                  tap_scripts.push_back(std::move(script_info));
1315              }
1316              in.pushKV("taproot_scripts", std::move(tap_scripts));
1317          }
1318  
1319          // Taproot bip32 keypaths
1320          if (!input.m_tap_bip32_paths.empty()) {
1321              UniValue keypaths(UniValue::VARR);
1322              for (const auto& [xonly, leaf_origin] : input.m_tap_bip32_paths) {
1323                  const auto& [leaf_hashes, origin] = leaf_origin;
1324                  UniValue path_obj(UniValue::VOBJ);
1325                  path_obj.pushKV("pubkey", HexStr(xonly));
1326                  path_obj.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(origin.fingerprint)));
1327                  path_obj.pushKV("path", WriteHDKeypath(origin.path));
1328                  UniValue leaf_hashes_arr(UniValue::VARR);
1329                  for (const auto& leaf_hash : leaf_hashes) {
1330                      leaf_hashes_arr.push_back(HexStr(leaf_hash));
1331                  }
1332                  path_obj.pushKV("leaf_hashes", std::move(leaf_hashes_arr));
1333                  keypaths.push_back(std::move(path_obj));
1334              }
1335              in.pushKV("taproot_bip32_derivs", std::move(keypaths));
1336          }
1337  
1338          // Taproot internal key
1339          if (!input.m_tap_internal_key.IsNull()) {
1340              in.pushKV("taproot_internal_key", HexStr(input.m_tap_internal_key));
1341          }
1342  
1343          // Write taproot merkle root
1344          if (!input.m_tap_merkle_root.IsNull()) {
1345              in.pushKV("taproot_merkle_root", HexStr(input.m_tap_merkle_root));
1346          }
1347  
1348          // Proprietary
1349          if (!input.m_proprietary.empty()) {
1350              UniValue proprietary(UniValue::VARR);
1351              for (const auto& entry : input.m_proprietary) {
1352                  UniValue this_prop(UniValue::VOBJ);
1353                  this_prop.pushKV("identifier", HexStr(entry.identifier));
1354                  this_prop.pushKV("subtype", entry.subtype);
1355                  this_prop.pushKV("key", HexStr(entry.key));
1356                  this_prop.pushKV("value", HexStr(entry.value));
1357                  proprietary.push_back(std::move(this_prop));
1358              }
1359              in.pushKV("proprietary", std::move(proprietary));
1360          }
1361  
1362          // Unknown data
1363          if (input.unknown.size() > 0) {
1364              UniValue unknowns(UniValue::VOBJ);
1365              for (auto entry : input.unknown) {
1366                  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1367              }
1368              in.pushKV("unknown", std::move(unknowns));
1369          }
1370  
1371          inputs.push_back(std::move(in));
1372      }
1373      result.pushKV("inputs", std::move(inputs));
1374  
1375      // outputs
1376      CAmount output_value = 0;
1377      UniValue outputs(UniValue::VARR);
1378      for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1379          const PSBTOutput& output = psbtx.outputs[i];
1380          UniValue out(UniValue::VOBJ);
1381          // Redeem script and witness script
1382          if (!output.redeem_script.empty()) {
1383              UniValue r(UniValue::VOBJ);
1384              ScriptToUniv(output.redeem_script, /*out=*/r);
1385              out.pushKV("redeem_script", std::move(r));
1386          }
1387          if (!output.witness_script.empty()) {
1388              UniValue r(UniValue::VOBJ);
1389              ScriptToUniv(output.witness_script, /*out=*/r);
1390              out.pushKV("witness_script", std::move(r));
1391          }
1392  
1393          // keypaths
1394          if (!output.hd_keypaths.empty()) {
1395              UniValue keypaths(UniValue::VARR);
1396              for (auto entry : output.hd_keypaths) {
1397                  UniValue keypath(UniValue::VOBJ);
1398                  keypath.pushKV("pubkey", HexStr(entry.first));
1399                  keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1400                  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1401                  keypaths.push_back(std::move(keypath));
1402              }
1403              out.pushKV("bip32_derivs", std::move(keypaths));
1404          }
1405  
1406          // Taproot internal key
1407          if (!output.m_tap_internal_key.IsNull()) {
1408              out.pushKV("taproot_internal_key", HexStr(output.m_tap_internal_key));
1409          }
1410  
1411          // Taproot tree
1412          if (!output.m_tap_tree.empty()) {
1413              UniValue tree(UniValue::VARR);
1414              for (const auto& [depth, leaf_ver, script] : output.m_tap_tree) {
1415                  UniValue elem(UniValue::VOBJ);
1416                  elem.pushKV("depth", (int)depth);
1417                  elem.pushKV("leaf_ver", (int)leaf_ver);
1418                  elem.pushKV("script", HexStr(script));
1419                  tree.push_back(std::move(elem));
1420              }
1421              out.pushKV("taproot_tree", std::move(tree));
1422          }
1423  
1424          // Taproot bip32 keypaths
1425          if (!output.m_tap_bip32_paths.empty()) {
1426              UniValue keypaths(UniValue::VARR);
1427              for (const auto& [xonly, leaf_origin] : output.m_tap_bip32_paths) {
1428                  const auto& [leaf_hashes, origin] = leaf_origin;
1429                  UniValue path_obj(UniValue::VOBJ);
1430                  path_obj.pushKV("pubkey", HexStr(xonly));
1431                  path_obj.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(origin.fingerprint)));
1432                  path_obj.pushKV("path", WriteHDKeypath(origin.path));
1433                  UniValue leaf_hashes_arr(UniValue::VARR);
1434                  for (const auto& leaf_hash : leaf_hashes) {
1435                      leaf_hashes_arr.push_back(HexStr(leaf_hash));
1436                  }
1437                  path_obj.pushKV("leaf_hashes", std::move(leaf_hashes_arr));
1438                  keypaths.push_back(std::move(path_obj));
1439              }
1440              out.pushKV("taproot_bip32_derivs", std::move(keypaths));
1441          }
1442  
1443          // Proprietary
1444          if (!output.m_proprietary.empty()) {
1445              UniValue proprietary(UniValue::VARR);
1446              for (const auto& entry : output.m_proprietary) {
1447                  UniValue this_prop(UniValue::VOBJ);
1448                  this_prop.pushKV("identifier", HexStr(entry.identifier));
1449                  this_prop.pushKV("subtype", entry.subtype);
1450                  this_prop.pushKV("key", HexStr(entry.key));
1451                  this_prop.pushKV("value", HexStr(entry.value));
1452                  proprietary.push_back(std::move(this_prop));
1453              }
1454              out.pushKV("proprietary", std::move(proprietary));
1455          }
1456  
1457          // Unknown data
1458          if (output.unknown.size() > 0) {
1459              UniValue unknowns(UniValue::VOBJ);
1460              for (auto entry : output.unknown) {
1461                  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1462              }
1463              out.pushKV("unknown", std::move(unknowns));
1464          }
1465  
1466          outputs.push_back(std::move(out));
1467  
1468          // Fee calculation
1469          if (MoneyRange(psbtx.tx->vout[i].nValue) && MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
1470              output_value += psbtx.tx->vout[i].nValue;
1471          } else {
1472              // Hack to just not show fee later
1473              have_all_utxos = false;
1474          }
1475      }
1476      result.pushKV("outputs", std::move(outputs));
1477      if (have_all_utxos) {
1478          result.pushKV("fee", ValueFromAmount(total_in - output_value));
1479      }
1480  
1481      return result;
1482  },
1483      };
1484  }
1485  
1486  static RPCHelpMan combinepsbt()
1487  {
1488      return RPCHelpMan{"combinepsbt",
1489                  "\nCombine multiple partially signed Limenka transactions into one transaction.\n"
1490                  "Implements the Combiner role.\n",
1491                  {
1492                      {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1493                          {
1494                              {"psbt", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A base64 string of a PSBT"},
1495                          },
1496                          },
1497                  },
1498                  RPCResult{
1499                      RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1500                  },
1501                  RPCExamples{
1502                      HelpExampleCli("combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")
1503                  },
1504          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1505  {
1506      // Unserialize the transactions
1507      std::vector<PartiallySignedTransaction> psbtxs;
1508      UniValue txs = request.params[0].get_array();
1509      if (txs.empty()) {
1510          throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txs' cannot be empty");
1511      }
1512      for (unsigned int i = 0; i < txs.size(); ++i) {
1513          PartiallySignedTransaction psbtx;
1514          std::string error;
1515          if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1516              throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1517          }
1518          psbtxs.push_back(psbtx);
1519      }
1520  
1521      PartiallySignedTransaction merged_psbt;
1522      if (!CombinePSBTs(merged_psbt, psbtxs)) {
1523          throw JSONRPCError(RPC_INVALID_PARAMETER, "PSBTs not compatible (different transactions)");
1524      }
1525  
1526      DataStream ssTx{};
1527      ssTx << merged_psbt;
1528      return EncodeBase64(ssTx);
1529  },
1530      };
1531  }
1532  
1533  static RPCHelpMan finalizepsbt()
1534  {
1535      return RPCHelpMan{"finalizepsbt",
1536                  "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n"
1537                  "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n"
1538                  "created which has the final_scriptSig and final_scriptwitness fields filled for inputs that are complete.\n"
1539                  "Implements the Finalizer and Extractor roles.\n",
1540                  {
1541                      {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1542                      {"extract", RPCArg::Type::BOOL, RPCArg::Default{true}, "If true and the transaction is complete,\n"
1543              "                             extract and return the complete transaction in normal network serialization instead of the PSBT."},
1544                  },
1545                  RPCResult{
1546                      RPCResult::Type::OBJ, "", "",
1547                      {
1548                          {RPCResult::Type::STR, "psbt", /*optional=*/true, "The base64-encoded partially signed transaction if not extracted"},
1549                          {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if extracted"},
1550                          {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1551                      }
1552                  },
1553                  RPCExamples{
1554                      HelpExampleCli("finalizepsbt", "\"psbt\"")
1555                  },
1556          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1557  {
1558      // Unserialize the transactions
1559      PartiallySignedTransaction psbtx;
1560      std::string error;
1561      if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1562          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1563      }
1564  
1565      bool extract = request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool());
1566  
1567      CMutableTransaction mtx;
1568      bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1569  
1570      UniValue result(UniValue::VOBJ);
1571      DataStream ssTx{};
1572      std::string result_str;
1573  
1574      if (complete && extract) {
1575          ssTx << TX_WITH_WITNESS(mtx);
1576          result_str = HexStr(ssTx);
1577          result.pushKV("hex", result_str);
1578      } else {
1579          ssTx << psbtx;
1580          result_str = EncodeBase64(ssTx.str());
1581          result.pushKV("psbt", result_str);
1582      }
1583      result.pushKV("complete", complete);
1584  
1585      return result;
1586  },
1587      };
1588  }
1589  
1590  static RPCHelpMan createpsbt()
1591  {
1592      return RPCHelpMan{"createpsbt",
1593                  "\nCreates a transaction in the Partially Signed Transaction format.\n"
1594                  "Implements the Creator role.\n"
1595                  "Note that the transaction's inputs are not signed, and\n"
1596                  "it is not stored in the wallet or transmitted to the network.\n",
1597                  CreateTxDoc(),
1598                  RPCResult{
1599                      RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1600                  },
1601                  RPCExamples{
1602                      HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
1603                  },
1604          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1605  {
1606  
1607      std::optional<bool> rbf;
1608      if (!request.params[3].isNull()) {
1609          rbf = request.params[3].get_bool();
1610      }
1611      CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf);
1612  
1613      // Make a blank psbt
1614      PartiallySignedTransaction psbtx;
1615      psbtx.tx = rawTx;
1616      for (unsigned int i = 0; i < rawTx.vin.size(); ++i) {
1617          psbtx.inputs.emplace_back();
1618      }
1619      for (unsigned int i = 0; i < rawTx.vout.size(); ++i) {
1620          psbtx.outputs.emplace_back();
1621      }
1622  
1623      // Serialize the PSBT
1624      DataStream ssTx{};
1625      ssTx << psbtx;
1626  
1627      return EncodeBase64(ssTx);
1628  },
1629      };
1630  }
1631  
1632  static RPCHelpMan converttopsbt()
1633  {
1634      return RPCHelpMan{"converttopsbt",
1635                  "\nConverts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n"
1636                  "createpsbt and walletcreatefundedpsbt should be used for new applications.\n",
1637                  {
1638                      {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of a raw transaction"},
1639                      {"permitsigdata", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, any signatures in the input will be discarded and conversion\n"
1640                              "                              will continue. If false, RPC will fail if any signatures are present."},
1641                      {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
1642                          "If iswitness is not present, heuristic tests will be used in decoding.\n"
1643                          "If true, only witness deserialization will be tried.\n"
1644                          "If false, only non-witness deserialization will be tried.\n"
1645                          "This boolean should reflect whether the transaction has inputs\n"
1646                          "(e.g. fully valid, or on-chain transactions), if known by the caller."
1647                      },
1648                  },
1649                  RPCResult{
1650                      RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1651                  },
1652                  RPCExamples{
1653                              "\nCreate a transaction\n"
1654                              + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1655                              "\nConvert the transaction to a PSBT\n"
1656                              + HelpExampleCli("converttopsbt", "\"rawtransaction\"")
1657                  },
1658          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1659  {
1660      // parse hex string from parameter
1661      CMutableTransaction tx;
1662      bool permitsigdata = request.params[1].isNull() ? false : request.params[1].get_bool();
1663      bool witness_specified = !request.params[2].isNull();
1664      bool iswitness = witness_specified ? request.params[2].get_bool() : false;
1665      const bool try_witness = witness_specified ? iswitness : true;
1666      const bool try_no_witness = witness_specified ? !iswitness : true;
1667      if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
1668          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1669      }
1670  
1671      // Remove all scriptSigs and scriptWitnesses from inputs
1672      for (CTxIn& input : tx.vin) {
1673          if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && !permitsigdata) {
1674              throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
1675          }
1676          input.scriptSig.clear();
1677          input.scriptWitness.SetNull();
1678      }
1679  
1680      // Make a blank psbt
1681      PartiallySignedTransaction psbtx;
1682      psbtx.tx = tx;
1683      for (unsigned int i = 0; i < tx.vin.size(); ++i) {
1684          psbtx.inputs.emplace_back();
1685      }
1686      for (unsigned int i = 0; i < tx.vout.size(); ++i) {
1687          psbtx.outputs.emplace_back();
1688      }
1689  
1690      // Serialize the PSBT
1691      DataStream ssTx{};
1692      ssTx << psbtx;
1693  
1694      return EncodeBase64(ssTx);
1695  },
1696      };
1697  }
1698  
1699  static RPCHelpMan utxoupdatepsbt()
1700  {
1701      return RPCHelpMan{"utxoupdatepsbt",
1702              "\nUpdates all segwit inputs and outputs in a PSBT with data from output descriptors, provided dependant transactions, the UTXO set, txindex, or the mempool.\n",
1703              {
1704                  {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1705                  {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of either strings or objects", {
1706                      {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
1707                      {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", {
1708                           {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
1709                           {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "Up to what index HD chains should be explored (either end or [begin,end])"},
1710                      }},
1711                  }},
1712                  {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of dependant serialized transactions as hex", {
1713                      {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A serialized previous transaction in hex"},
1714                  }},
1715              },
1716              RPCResult {
1717                      RPCResult::Type::STR, "", "The base64-encoded partially signed transaction with inputs updated"
1718              },
1719              RPCExamples {
1720                  HelpExampleCli("utxoupdatepsbt", "\"psbt\"")
1721              },
1722          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1723  {
1724      // Parse descriptors, if any.
1725      FlatSigningProvider provider;
1726      if (!request.params[1].isNull()) {
1727          auto descs = request.params[1].get_array();
1728          for (size_t i = 0; i < descs.size(); ++i) {
1729              EvalDescriptorStringOrObject(descs[i], provider);
1730          }
1731      }
1732  
1733      std::vector<CTransactionRef> prev_txns;
1734      if (!request.params[2].isNull()) {
1735          prev_txns = ParseTransactionVector(request.params[2]);
1736      }
1737  
1738      // We don't actually need private keys further on; hide them as a precaution.
1739      const PartiallySignedTransaction& psbtx = ProcessPSBT(
1740          request.params[0].get_str(),
1741          request.context,
1742          HidingSigningProvider(&provider, /*hide_secret=*/true, /*hide_origin=*/false),
1743          /*sighash_type=*/SIGHASH_ALL,
1744          /*prev_txs=*/prev_txns,
1745          /*finalize=*/false);
1746  
1747      DataStream ssTx{};
1748      ssTx << psbtx;
1749      return EncodeBase64(ssTx);
1750  },
1751      };
1752  }
1753  
1754  static RPCHelpMan joinpsbts()
1755  {
1756      return RPCHelpMan{"joinpsbts",
1757              "\nJoins multiple distinct PSBTs with different inputs and outputs into one PSBT with inputs and outputs from all of the PSBTs\n"
1758              "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1759              {
1760                  {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1761                      {
1762                          {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1763                      }}
1764              },
1765              RPCResult {
1766                      RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1767              },
1768              RPCExamples {
1769                  HelpExampleCli("joinpsbts", "\"psbt\"")
1770              },
1771          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1772  {
1773      // Unserialize the transactions
1774      std::vector<PartiallySignedTransaction> psbtxs;
1775      UniValue txs = request.params[0].get_array();
1776  
1777      if (txs.size() <= 1) {
1778          throw JSONRPCError(RPC_INVALID_PARAMETER, "At least two PSBTs are required to join PSBTs.");
1779      }
1780  
1781      uint32_t best_version = 1;
1782      uint32_t best_locktime = 0xffffffff;
1783      for (unsigned int i = 0; i < txs.size(); ++i) {
1784          PartiallySignedTransaction psbtx;
1785          std::string error;
1786          if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1787              throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1788          }
1789          psbtxs.push_back(psbtx);
1790          // Choose the highest version number
1791          if (psbtx.tx->version > best_version) {
1792              best_version = psbtx.tx->version;
1793          }
1794          // Choose the lowest lock time
1795          if (psbtx.tx->nLockTime < best_locktime) {
1796              best_locktime = psbtx.tx->nLockTime;
1797          }
1798      }
1799  
1800      // Create a blank psbt where everything will be added
1801      PartiallySignedTransaction merged_psbt;
1802      merged_psbt.tx = CMutableTransaction();
1803      merged_psbt.tx->version = best_version;
1804      merged_psbt.tx->nLockTime = best_locktime;
1805  
1806      // Merge
1807      for (auto& psbt : psbtxs) {
1808          for (unsigned int i = 0; i < psbt.tx->vin.size(); ++i) {
1809              if (!merged_psbt.AddInput(psbt.tx->vin[i], psbt.inputs[i])) {
1810                  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));
1811              }
1812          }
1813          for (unsigned int i = 0; i < psbt.tx->vout.size(); ++i) {
1814              merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1815          }
1816          for (auto& xpub_pair : psbt.m_xpubs) {
1817              if (merged_psbt.m_xpubs.count(xpub_pair.first) == 0) {
1818                  merged_psbt.m_xpubs[xpub_pair.first] = xpub_pair.second;
1819              } else {
1820                  merged_psbt.m_xpubs[xpub_pair.first].insert(xpub_pair.second.begin(), xpub_pair.second.end());
1821              }
1822          }
1823          merged_psbt.unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
1824      }
1825  
1826      // Generate list of shuffled indices for shuffling inputs and outputs of the merged PSBT
1827      std::vector<int> input_indices(merged_psbt.inputs.size());
1828      std::iota(input_indices.begin(), input_indices.end(), 0);
1829      std::vector<int> output_indices(merged_psbt.outputs.size());
1830      std::iota(output_indices.begin(), output_indices.end(), 0);
1831  
1832      // Shuffle input and output indices lists
1833      std::shuffle(input_indices.begin(), input_indices.end(), FastRandomContext());
1834      std::shuffle(output_indices.begin(), output_indices.end(), FastRandomContext());
1835  
1836      PartiallySignedTransaction shuffled_psbt;
1837      shuffled_psbt.tx = CMutableTransaction();
1838      shuffled_psbt.tx->version = merged_psbt.tx->version;
1839      shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1840      for (int i : input_indices) {
1841          shuffled_psbt.AddInput(merged_psbt.tx->vin[i], merged_psbt.inputs[i]);
1842      }
1843      for (int i : output_indices) {
1844          shuffled_psbt.AddOutput(merged_psbt.tx->vout[i], merged_psbt.outputs[i]);
1845      }
1846      shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(), merged_psbt.unknown.end());
1847  
1848      DataStream ssTx{};
1849      ssTx << shuffled_psbt;
1850      return EncodeBase64(ssTx);
1851  },
1852      };
1853  }
1854  
1855  static RPCHelpMan analyzepsbt()
1856  {
1857      return RPCHelpMan{"analyzepsbt",
1858              "\nAnalyzes and provides information about the current status of a PSBT and its inputs\n",
1859              {
1860                  {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1861              },
1862              RPCResult {
1863                  RPCResult::Type::OBJ, "", "",
1864                  {
1865                      {RPCResult::Type::ARR, "inputs", /*optional=*/true, "",
1866                      {
1867                          {RPCResult::Type::OBJ, "", "",
1868                          {
1869                              {RPCResult::Type::BOOL, "has_utxo", "Whether a UTXO is provided"},
1870                              {RPCResult::Type::BOOL, "is_final", "Whether the input is finalized"},
1871                              {RPCResult::Type::OBJ, "missing", /*optional=*/true, "Things that are missing that are required to complete this input",
1872                              {
1873                                  {RPCResult::Type::ARR, "pubkeys", /*optional=*/true, "",
1874                                  {
1875                                      {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose BIP 32 derivation path is missing"},
1876                                  }},
1877                                  {RPCResult::Type::ARR, "signatures", /*optional=*/true, "",
1878                                  {
1879                                      {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose signature is missing"},
1880                                  }},
1881                                  {RPCResult::Type::STR_HEX, "redeemscript", /*optional=*/true, "Hash160 of the redeem script that is missing"},
1882                                  {RPCResult::Type::STR_HEX, "witnessscript", /*optional=*/true, "SHA256 of the witness script that is missing"},
1883                              }},
1884                              {RPCResult::Type::STR, "next", /*optional=*/true, "Role of the next person that this input needs to go to"},
1885                          }},
1886                      }},
1887                      {RPCResult::Type::NUM, "estimated_vsize", /*optional=*/true, "Estimated vsize of the final signed transaction"},
1888                      {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"},
1889                      {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The transaction fee paid. Shown only if all UTXO slots in the PSBT have been filled"},
1890                      {RPCResult::Type::STR, "next", "Role of the next person that this psbt needs to go to"},
1891                      {RPCResult::Type::STR, "error", /*optional=*/true, "Error message (if there is one)"},
1892                  }
1893              },
1894              RPCExamples {
1895                  HelpExampleCli("analyzepsbt", "\"psbt\"")
1896              },
1897          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1898  {
1899      // Unserialize the transaction
1900      PartiallySignedTransaction psbtx;
1901      std::string error;
1902      if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1903          throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1904      }
1905  
1906      PSBTAnalysis psbta = AnalyzePSBT(psbtx);
1907  
1908      UniValue result(UniValue::VOBJ);
1909      UniValue inputs_result(UniValue::VARR);
1910      for (const auto& input : psbta.inputs) {
1911          UniValue input_univ(UniValue::VOBJ);
1912          UniValue missing(UniValue::VOBJ);
1913  
1914          input_univ.pushKV("has_utxo", input.has_utxo);
1915          input_univ.pushKV("is_final", input.is_final);
1916          input_univ.pushKV("next", PSBTRoleName(input.next));
1917  
1918          if (!input.missing_pubkeys.empty()) {
1919              UniValue missing_pubkeys_univ(UniValue::VARR);
1920              for (const CKeyID& pubkey : input.missing_pubkeys) {
1921                  missing_pubkeys_univ.push_back(HexStr(pubkey));
1922              }
1923              missing.pushKV("pubkeys", std::move(missing_pubkeys_univ));
1924          }
1925          if (!input.missing_redeem_script.IsNull()) {
1926              missing.pushKV("redeemscript", HexStr(input.missing_redeem_script));
1927          }
1928          if (!input.missing_witness_script.IsNull()) {
1929              missing.pushKV("witnessscript", HexStr(input.missing_witness_script));
1930          }
1931          if (!input.missing_sigs.empty()) {
1932              UniValue missing_sigs_univ(UniValue::VARR);
1933              for (const CKeyID& pubkey : input.missing_sigs) {
1934                  missing_sigs_univ.push_back(HexStr(pubkey));
1935              }
1936              missing.pushKV("signatures", std::move(missing_sigs_univ));
1937          }
1938          if (!missing.getKeys().empty()) {
1939              input_univ.pushKV("missing", std::move(missing));
1940          }
1941          inputs_result.push_back(std::move(input_univ));
1942      }
1943      if (!inputs_result.empty()) result.pushKV("inputs", std::move(inputs_result));
1944  
1945      if (psbta.estimated_vsize != std::nullopt) {
1946          result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
1947      }
1948      if (psbta.estimated_feerate != std::nullopt) {
1949          result.pushKV("estimated_feerate", ValueFromAmount(psbta.estimated_feerate->GetFeePerK()));
1950      }
1951      if (psbta.fee != std::nullopt) {
1952          result.pushKV("fee", ValueFromAmount(*psbta.fee));
1953      }
1954      result.pushKV("next", PSBTRoleName(psbta.next));
1955      if (!psbta.error.empty()) {
1956          result.pushKV("error", psbta.error);
1957      }
1958  
1959      return result;
1960  },
1961      };
1962  }
1963  
1964  RPCHelpMan descriptorprocesspsbt()
1965  {
1966      return RPCHelpMan{"descriptorprocesspsbt",
1967                  "\nUpdate all segwit inputs in a PSBT with information from output descriptors, the UTXO set or the mempool. \n"
1968                  "Then, sign the inputs we are able to with information from the output descriptors. ",
1969                  {
1970                      {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
1971                      {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of either strings or objects", {
1972                          {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
1973                          {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", {
1974                               {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
1975                               {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "Up to what index HD chains should be explored (either end or [begin,end])"},
1976                          }},
1977                      }},
1978                      {"options|sighashtype", {RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Type::STR}, RPCArg::Optional::OMITTED, "",
1979                          {
1980                      {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
1981              "       \"DEFAULT\"\n"
1982              "       \"ALL\"\n"
1983              "       \"NONE\"\n"
1984              "       \"SINGLE\"\n"
1985              "       \"ALL|ANYONECANPAY\"\n"
1986              "       \"NONE|ANYONECANPAY\"\n"
1987                      "       \"SINGLE|ANYONECANPAY\"",
1988                                  RPCArgOptions{.also_positional = true}},
1989                              {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them", RPCArgOptions{.also_positional = true}},
1990                              {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible", RPCArgOptions{.also_positional = true}},
1991                              {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of dependant serialized transactions as hex", {
1992                                  {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A serialized previous transaction in hex"},
1993                              }},
1994                          },
1995                      RPCArgOptions{.oneline_description="options"}},
1996                      {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "for backwards compatibility", RPCArgOptions{.hidden=true}},
1997                      {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "for backwards compatibility", RPCArgOptions{.hidden=true}},
1998                  },
1999                  RPCResult{
2000                      RPCResult::Type::OBJ, "", "",
2001                      {
2002                          {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"},
2003                          {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
2004                          {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if complete"},
2005                      }
2006                  },
2007                  RPCExamples{
2008                      HelpExampleCli("descriptorprocesspsbt", "\"psbt\" \"[\\\"descriptor1\\\", \\\"descriptor2\\\"]\"") +
2009                      HelpExampleCli("descriptorprocesspsbt", "\"psbt\" \"[{\\\"desc\\\":\\\"mydescriptor\\\", \\\"range\\\":21}]\"")
2010                  },
2011          [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
2012  {
2013      // Add descriptor information to a signing provider
2014      FlatSigningProvider provider;
2015  
2016      auto descs = request.params[1].get_array();
2017      for (size_t i = 0; i < descs.size(); ++i) {
2018          EvalDescriptorStringOrObject(descs[i], provider, /*expand_priv=*/true);
2019      }
2020  
2021      // Get options
2022      bool bip32derivs = true;
2023      bool finalize = true;
2024      int sighash_type = ParseSighashString(NullUniValue); // Use ParseSighashString default
2025      std::vector<CTransactionRef> prev_txns;
2026      if (request.params[2].isStr() || request.params[2].isNull()) {
2027          // Old style positional parameters
2028          sighash_type = ParseSighashString(request.params[2]);
2029          bip32derivs = request.params[3].isNull() ? true : request.params[3].get_bool();
2030          finalize = request.params[4].isNull() ? true : request.params[4].get_bool();
2031      } else {
2032          // New style options are in an object
2033          UniValue options = request.params[2];
2034          RPCTypeCheckObj(options,
2035              {
2036                  {"bip32derivs", UniValueType(UniValue::VBOOL)},
2037                  {"finalize", UniValueType(UniValue::VBOOL)},
2038                  {"prevtxs", UniValueType(UniValue::VARR)},
2039                  {"sighashtype", UniValueType(UniValue::VSTR)},
2040              },
2041              true, true);
2042          if (options.exists("bip32derivs")) {
2043              bip32derivs = options["bip32derivs"].get_bool();
2044          }
2045          if (options.exists("finalize")) {
2046              finalize = options["finalize"].get_bool();
2047          }
2048          if (options.exists("prevtxs")) {
2049              prev_txns = ParseTransactionVector(options["prevtxs"]);
2050          }
2051          if (options.exists("sighashtype")) {
2052              sighash_type = ParseSighashString(options["sighashtype"]);
2053          }
2054          if (request.params.size() > 3) {
2055              // Same behaviour as too many args passed normally
2056              throw std::runtime_error(self.ToString());
2057          }
2058      }
2059  
2060      const PartiallySignedTransaction& psbtx = ProcessPSBT(
2061          request.params[0].get_str(),
2062          request.context,
2063          HidingSigningProvider(&provider, /*hide_secret=*/false, !bip32derivs),
2064          sighash_type,
2065          /*prev_txs=*/prev_txns,
2066          finalize);
2067  
2068      // Check whether or not all of the inputs are now signed
2069      bool complete = true;
2070      for (const auto& input : psbtx.inputs) {
2071          complete &= PSBTInputSigned(input);
2072      }
2073  
2074      DataStream ssTx{};
2075      ssTx << psbtx;
2076  
2077      UniValue result(UniValue::VOBJ);
2078  
2079      result.pushKV("psbt", EncodeBase64(ssTx));
2080      result.pushKV("complete", complete);
2081      if (complete) {
2082          CMutableTransaction mtx;
2083          PartiallySignedTransaction psbtx_copy = psbtx;
2084          CHECK_NONFATAL(FinalizeAndExtractPSBT(psbtx_copy, mtx));
2085          DataStream ssTx_final;
2086          ssTx_final << TX_WITH_WITNESS(mtx);
2087          result.pushKV("hex", HexStr(ssTx_final));
2088      }
2089      return result;
2090  },
2091      };
2092  }
2093  
2094  void RegisterRawTransactionRPCCommands(CRPCTable& t)
2095  {
2096      static const CRPCCommand commands[]{
2097          {"rawtransactions", &getrawtransaction},
2098          {"rawtransactions", &createrawtransaction},
2099          {"rawtransactions", &decoderawtransaction},
2100          {"rawtransactions", &decodescript},
2101          {"rawtransactions", &combinerawtransaction},
2102          {"rawtransactions", &signrawtransactionwithkey},
2103          {"rawtransactions", &decodepsbt},
2104          {"rawtransactions", &combinepsbt},
2105          {"rawtransactions", &finalizepsbt},
2106          {"rawtransactions", &createpsbt},
2107          {"rawtransactions", &converttopsbt},
2108          {"rawtransactions", &utxoupdatepsbt},
2109          {"rawtransactions", &descriptorprocesspsbt},
2110          {"rawtransactions", &joinpsbts},
2111          {"rawtransactions", &analyzepsbt},
2112      };
2113      for (const auto& c : commands) {
2114          t.appendCommand(c.name, &c);
2115      }
2116  }
2117