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