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