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