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