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