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