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