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