Bitcoin ABC  0.22.12
P2P Digital Currency
rawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <blockdb.h>
7 #include <chain.h>
8 #include <chainparams.h>
9 #include <coins.h>
10 #include <config.h>
11 #include <consensus/validation.h>
12 #include <core_io.h>
13 #include <index/txindex.h>
14 #include <key_io.h>
15 #include <merkleblock.h>
16 #include <network.h>
17 #include <node/coin.h>
18 #include <node/context.h>
19 #include <node/psbt.h>
20 #include <node/transaction.h>
21 #include <policy/policy.h>
22 #include <primitives/transaction.h>
23 #include <psbt.h>
24 #include <random.h>
25 #include <rpc/blockchain.h>
27 #include <rpc/server.h>
28 #include <rpc/util.h>
29 #include <script/script.h>
30 #include <script/sign.h>
31 #include <script/signingprovider.h>
32 #include <script/standard.h>
33 #include <txmempool.h>
34 #include <uint256.h>
35 #include <util/error.h>
36 #include <util/moneystr.h>
37 #include <util/strencodings.h>
38 #include <util/string.h>
39 #include <validation.h>
40 #include <validationinterface.h>
41 
42 #include <cstdint>
43 #include <numeric>
44 
45 #include <univalue.h>
46 
47 static void TxToJSON(const CTransaction &tx, const BlockHash &hashBlock,
48  UniValue &entry) {
49  // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
50  //
51  // Blockchain contextual information (confirmations and blocktime) is not
52  // available to code in bitcoin-common, so we query them here and push the
53  // data into the returned UniValue.
54  TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
55 
56  if (!hashBlock.IsNull()) {
57  LOCK(cs_main);
58 
59  entry.pushKV("blockhash", hashBlock.GetHex());
60  CBlockIndex *pindex = LookupBlockIndex(hashBlock);
61  if (pindex) {
62  if (::ChainActive().Contains(pindex)) {
63  entry.pushKV("confirmations",
64  1 + ::ChainActive().Height() - pindex->nHeight);
65  entry.pushKV("time", pindex->GetBlockTime());
66  entry.pushKV("blocktime", pindex->GetBlockTime());
67  } else {
68  entry.pushKV("confirmations", 0);
69  }
70  }
71  }
72 }
73 
74 static UniValue getrawtransaction(const Config &config,
75  const JSONRPCRequest &request) {
76  RPCHelpMan{
77  "getrawtransaction",
78  "By default this function only works for mempool transactions. When "
79  "called with a blockhash\n"
80  "argument, getrawtransaction will return the transaction if the "
81  "specified block is available and\n"
82  "the transaction is found in that block. When called without a "
83  "blockhash argument, getrawtransaction\n"
84  "will return the transaction if it is in the mempool, or if -txindex "
85  "is enabled and the transaction\n"
86  "is in a block in the blockchain.\n"
87 
88  "\nReturn the raw transaction data.\n"
89  "\nIf verbose is 'true', returns an Object with information about "
90  "'txid'.\n"
91  "If verbose is 'false' or omitted, returns a string that is "
92  "serialized, hex-encoded data for 'txid'.\n",
93  {
95  "The transaction id"},
96  {"verbose", RPCArg::Type::BOOL, /* default */ "false",
97  "If false, return a string, otherwise return a json object"},
98  {"blockhash", RPCArg::Type::STR_HEX,
100  "The block in which to look for the transaction"},
101  },
102  {
103  RPCResult{"if verbose is not set or set to false",
104  RPCResult::Type::STR, "data",
105  "The serialized, hex-encoded data for 'txid'"},
106  RPCResult{
107  "if verbose is set to true",
109  "",
110  "",
111  {
112  {RPCResult::Type::BOOL, "in_active_chain",
113  "Whether specified block is in the active chain or not "
114  "(only present with explicit \"blockhash\" argument)"},
115  {RPCResult::Type::STR_HEX, "hex",
116  "The serialized, hex-encoded data for 'txid'"},
117  {RPCResult::Type::STR_HEX, "txid",
118  "The transaction id (same as provided)"},
119  {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
120  {RPCResult::Type::NUM, "size",
121  "The serialized transaction size"},
122  {RPCResult::Type::NUM, "version", "The version"},
123  {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
125  "vin",
126  "",
127  {
129  "",
130  "",
131  {
132  {RPCResult::Type::STR_HEX, "txid",
133  "The transaction id"},
134  {RPCResult::Type::STR, "vout", ""},
136  "scriptSig",
137  "The script",
138  {
139  {RPCResult::Type::STR, "asm", "asm"},
140  {RPCResult::Type::STR_HEX, "hex", "hex"},
141  }},
142  {RPCResult::Type::NUM, "sequence",
143  "The script sequence number"},
144  }},
145  }},
147  "vout",
148  "",
149  {
151  "",
152  "",
153  {
154  {RPCResult::Type::NUM, "value",
155  "The value in " + CURRENCY_UNIT},
156  {RPCResult::Type::NUM, "n", "index"},
158  "scriptPubKey",
159  "",
160  {
161  {RPCResult::Type::STR, "asm", "the asm"},
162  {RPCResult::Type::STR, "hex", "the hex"},
163  {RPCResult::Type::NUM, "reqSigs",
164  "The required sigs"},
165  {RPCResult::Type::STR, "type",
166  "The type, eg 'pubkeyhash'"},
168  "addresses",
169  "",
170  {
171  {RPCResult::Type::STR, "address",
172  "bitcoin address"},
173  }},
174  }},
175  }},
176  }},
177  {RPCResult::Type::STR_HEX, "blockhash", "the block hash"},
178  {RPCResult::Type::NUM, "confirmations",
179  "The confirmations"},
180  {RPCResult::Type::NUM_TIME, "blocktime",
181  "The block time expressed in " + UNIX_EPOCH_TIME},
182  {RPCResult::Type::NUM, "time", "Same as \"blocktime\""},
183  }},
184  },
185  RPCExamples{HelpExampleCli("getrawtransaction", "\"mytxid\"") +
186  HelpExampleCli("getrawtransaction", "\"mytxid\" true") +
187  HelpExampleRpc("getrawtransaction", "\"mytxid\", true") +
188  HelpExampleCli("getrawtransaction",
189  "\"mytxid\" false \"myblockhash\"") +
190  HelpExampleCli("getrawtransaction",
191  "\"mytxid\" true \"myblockhash\"")},
192  }
193  .Check(request);
194 
195  bool in_active_chain = true;
196  TxId txid = TxId(ParseHashV(request.params[0], "parameter 1"));
197  CBlockIndex *blockindex = nullptr;
198 
199  const CChainParams &params = config.GetChainParams();
200  if (txid == params.GenesisBlock().hashMerkleRoot) {
201  // Special exception for the genesis block coinbase transaction
203  "The genesis block coinbase is not considered an "
204  "ordinary transaction and cannot be retrieved");
205  }
206 
207  // Accept either a bool (true) or a num (>=1) to indicate verbose output.
208  bool fVerbose = false;
209  if (!request.params[1].isNull()) {
210  fVerbose = request.params[1].isNum()
211  ? (request.params[1].get_int() != 0)
212  : request.params[1].get_bool();
213  }
214 
215  if (!request.params[2].isNull()) {
216  LOCK(cs_main);
217 
218  BlockHash blockhash(ParseHashV(request.params[2], "parameter 3"));
219  blockindex = LookupBlockIndex(blockhash);
220  if (!blockindex) {
222  "Block hash not found");
223  }
224  in_active_chain = ::ChainActive().Contains(blockindex);
225  }
226 
227  bool f_txindex_ready = false;
228  if (g_txindex && !blockindex) {
229  f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
230  }
231 
232  CTransactionRef tx;
233  BlockHash hash_block;
234  if (!GetTransaction(txid, tx, params.GetConsensus(), hash_block,
235  blockindex)) {
236  std::string errmsg;
237  if (blockindex) {
238  if (!blockindex->nStatus.hasData()) {
239  throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
240  }
241  errmsg = "No such transaction found in the provided block";
242  } else if (!g_txindex) {
243  errmsg = "No such mempool transaction. Use -txindex or provide a "
244  "block hash to enable blockchain transaction queries";
245  } else if (!f_txindex_ready) {
246  errmsg = "No such mempool transaction. Blockchain transactions are "
247  "still in the process of being indexed";
248  } else {
249  errmsg = "No such mempool or blockchain transaction";
250  }
252  errmsg +
253  ". Use gettransaction for wallet transactions.");
254  }
255 
256  if (!fVerbose) {
257  return EncodeHexTx(*tx, RPCSerializationFlags());
258  }
259 
260  UniValue result(UniValue::VOBJ);
261  if (blockindex) {
262  result.pushKV("in_active_chain", in_active_chain);
263  }
264  TxToJSON(*tx, hash_block, result);
265  return result;
266 }
267 
268 static UniValue gettxoutproof(const Config &config,
269  const JSONRPCRequest &request) {
270  RPCHelpMan{
271  "gettxoutproof",
272  "Returns a hex-encoded proof that \"txid\" was included in a block.\n"
273  "\nNOTE: By default this function only works sometimes. "
274  "This is when there is an\n"
275  "unspent output in the utxo for this transaction. To make it always "
276  "work,\n"
277  "you need to maintain a transaction index, using the -txindex command "
278  "line option or\n"
279  "specify the block in which the transaction is included manually (by "
280  "blockhash).\n",
281  {
282  {
283  "txids",
286  "The txids to filter",
287  {
289  "A transaction hash"},
290  },
291  },
292  {"blockhash", RPCArg::Type::STR_HEX,
294  "If specified, looks for txid in the block with this hash"},
295  },
296  RPCResult{
297  RPCResult::Type::STR, "data",
298  "A string that is a serialized, hex-encoded data for the proof."},
299  RPCExamples{""},
300  }
301  .Check(request);
302 
303  std::set<TxId> setTxIds;
304  TxId oneTxId;
305  UniValue txids = request.params[0].get_array();
306  for (unsigned int idx = 0; idx < txids.size(); idx++) {
307  const UniValue &utxid = txids[idx];
308  TxId txid(ParseHashV(utxid, "txid"));
309  if (setTxIds.count(txid)) {
310  throw JSONRPCError(
312  std::string("Invalid parameter, duplicated txid: ") +
313  utxid.get_str());
314  }
315 
316  setTxIds.insert(txid);
317  oneTxId = txid;
318  }
319 
320  CBlockIndex *pblockindex = nullptr;
321 
322  BlockHash hashBlock;
323  if (!request.params[1].isNull()) {
324  LOCK(cs_main);
325  hashBlock = BlockHash(ParseHashV(request.params[1], "blockhash"));
326  pblockindex = LookupBlockIndex(hashBlock);
327  if (!pblockindex) {
328  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
329  }
330  } else {
331  LOCK(cs_main);
332  // Loop through txids and try to find which block they're in. Exit loop
333  // once a block is found.
334  for (const auto &txid : setTxIds) {
335  const Coin &coin =
336  AccessByTxid(::ChainstateActive().CoinsTip(), txid);
337  if (!coin.IsSpent()) {
338  pblockindex = ::ChainActive()[coin.GetHeight()];
339  break;
340  }
341  }
342  }
343 
344  // Allow txindex to catch up if we need to query it and before we acquire
345  // cs_main.
346  if (g_txindex && !pblockindex) {
347  g_txindex->BlockUntilSyncedToCurrentChain();
348  }
349 
350  const Consensus::Params &params = config.GetChainParams().GetConsensus();
351 
352  LOCK(cs_main);
353 
354  if (pblockindex == nullptr) {
355  CTransactionRef tx;
356  if (!GetTransaction(oneTxId, tx, params, hashBlock) ||
357  hashBlock.IsNull()) {
359  "Transaction not yet in block");
360  }
361 
362  pblockindex = LookupBlockIndex(hashBlock);
363  if (!pblockindex) {
364  throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
365  }
366  }
367 
368  CBlock block;
369  if (!ReadBlockFromDisk(block, pblockindex, params)) {
370  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
371  }
372 
373  unsigned int ntxFound = 0;
374  for (const auto &tx : block.vtx) {
375  if (setTxIds.count(tx->GetId())) {
376  ntxFound++;
377  }
378  }
379 
380  if (ntxFound != setTxIds.size()) {
381  throw JSONRPCError(
383  "Not all transactions found in specified or retrieved block");
384  }
385 
387  CMerkleBlock mb(block, setTxIds);
388  ssMB << mb;
389  std::string strHex = HexStr(ssMB.begin(), ssMB.end());
390  return strHex;
391 }
392 
393 static UniValue verifytxoutproof(const Config &config,
394  const JSONRPCRequest &request) {
395  RPCHelpMan{
396  "verifytxoutproof",
397  "Verifies that a proof points to a transaction in a block, returning "
398  "the transaction it commits to\n"
399  "and throwing an RPC error if the block is not in our best chain\n",
400  {
402  "The hex-encoded proof generated by gettxoutproof"},
403  },
405  "",
406  "",
407  {
408  {RPCResult::Type::STR_HEX, "txid",
409  "The txid(s) which the proof commits to, or empty array "
410  "if the proof can not be validated."},
411  }},
412  RPCExamples{""},
413  }
414  .Check(request);
415 
416  CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK,
418  CMerkleBlock merkleBlock;
419  ssMB >> merkleBlock;
420 
422 
423  std::vector<uint256> vMatch;
424  std::vector<size_t> vIndex;
425  if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) !=
426  merkleBlock.header.hashMerkleRoot) {
427  return res;
428  }
429 
430  LOCK(cs_main);
431 
432  const CBlockIndex *pindex = LookupBlockIndex(merkleBlock.header.GetHash());
433  if (!pindex || !::ChainActive().Contains(pindex) || pindex->nTx == 0) {
435  "Block not found in chain");
436  }
437 
438  // Check if proof is valid, only add results if so
439  if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) {
440  for (const uint256 &hash : vMatch) {
441  res.push_back(hash.GetHex());
442  }
443  }
444 
445  return res;
446 }
447 
448 static UniValue createrawtransaction(const Config &config,
449  const JSONRPCRequest &request) {
450  RPCHelpMan{
451  "createrawtransaction",
452  "Create a transaction spending the given inputs and creating new "
453  "outputs.\n"
454  "Outputs can be addresses or data.\n"
455  "Returns hex-encoded raw transaction.\n"
456  "Note that the transaction's inputs are not signed, and\n"
457  "it is not stored in the wallet or transmitted to the network.\n",
458  {
459  {
460  "inputs",
463  "The inputs",
464  {
465  {
466  "",
469  "",
470  {
471  {"txid", RPCArg::Type::STR_HEX,
472  RPCArg::Optional::NO, "The transaction id"},
474  "The output number"},
475  {"sequence", RPCArg::Type::NUM, /* default */
476  "depends on the value of the 'locktime' argument",
477  "The sequence number"},
478  },
479  },
480  },
481  },
482  {
483  "outputs",
486  "The outputs (key-value pairs), where none of "
487  "the keys are duplicated.\n"
488  "That is, each address can only appear once and there can only "
489  "be one 'data' object.\n"
490  "For compatibility reasons, a dictionary, which holds the "
491  "key-value pairs directly, is also\n"
492  " accepted as second parameter.",
493  {
494  {
495  "",
498  "",
499  {
500  {"address", RPCArg::Type::AMOUNT,
502  "A key-value pair. The key (string) is the "
503  "bitcoin address, the value (float or string) is "
504  "the amount in " +
505  CURRENCY_UNIT},
506  },
507  },
508  {
509  "",
512  "",
513  {
514  {"data", RPCArg::Type::STR_HEX,
516  "A key-value pair. The key must be \"data\", the "
517  "value is hex-encoded data"},
518  },
519  },
520  },
521  },
522  {"locktime", RPCArg::Type::NUM, /* default */ "0",
523  "Raw locktime. Non-0 value also locktime-activates inputs"},
524  },
525  RPCResult{RPCResult::Type::STR_HEX, "transaction",
526  "hex string of the transaction"},
527  RPCExamples{
528  HelpExampleCli("createrawtransaction",
529  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
530  "\" \"[{\\\"address\\\":0.01}]\"") +
531  HelpExampleCli("createrawtransaction",
532  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
533  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
534  HelpExampleRpc("createrawtransaction",
535  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
536  "\", \"[{\\\"address\\\":0.01}]\"") +
537  HelpExampleRpc("createrawtransaction",
538  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
539  "\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
540  }
541  .Check(request);
542 
543  RPCTypeCheck(request.params,
544  {UniValue::VARR,
545  UniValueType(), // ARR or OBJ, checked later
546  UniValue::VNUM},
547  true);
548 
549  CMutableTransaction rawTx =
550  ConstructTransaction(config.GetChainParams(), request.params[0],
551  request.params[1], request.params[2]);
552 
553  return EncodeHexTx(CTransaction(rawTx));
554 }
555 
556 static UniValue decoderawtransaction(const Config &config,
557  const JSONRPCRequest &request) {
558  RPCHelpMan{
559  "decoderawtransaction",
560  "Return a JSON object representing the serialized, hex-encoded "
561  "transaction.\n",
562  {
564  "The transaction hex string"},
565  },
566  RPCResult{
568  "",
569  "",
570  {
571  {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
572  {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
573  {RPCResult::Type::NUM, "size", "The transaction size"},
574  {RPCResult::Type::NUM, "version", "The version"},
575  {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
577  "vin",
578  "",
579  {
581  "",
582  "",
583  {
584  {RPCResult::Type::STR_HEX, "txid",
585  "The transaction id"},
586  {RPCResult::Type::NUM, "vout", "The output number"},
588  "scriptSig",
589  "The script",
590  {
591  {RPCResult::Type::STR, "asm", "asm"},
592  {RPCResult::Type::STR_HEX, "hex", "hex"},
593  }},
594  {RPCResult::Type::NUM, "sequence",
595  "The script sequence number"},
596  }},
597  }},
599  "vout",
600  "",
601  {
603  "",
604  "",
605  {
606  {RPCResult::Type::NUM, "value",
607  "The value in " + CURRENCY_UNIT},
608  {RPCResult::Type::NUM, "n", "index"},
610  "scriptPubKey",
611  "",
612  {
613  {RPCResult::Type::STR, "asm", "the asm"},
614  {RPCResult::Type::STR_HEX, "hex", "the hex"},
615  {RPCResult::Type::NUM, "reqSigs",
616  "The required sigs"},
617  {RPCResult::Type::STR, "type",
618  "The type, eg 'pubkeyhash'"},
620  "addresses",
621  "",
622  {
623  {RPCResult::Type::STR, "address",
624  "bitcoin address"},
625  }},
626  }},
627  }},
628  }},
629  }},
630  RPCExamples{HelpExampleCli("decoderawtransaction", "\"hexstring\"") +
631  HelpExampleRpc("decoderawtransaction", "\"hexstring\"")},
632  }
633  .Check(request);
634 
635  RPCTypeCheck(request.params, {UniValue::VSTR});
636 
638 
639  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
640  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
641  }
642 
643  UniValue result(UniValue::VOBJ);
644  TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
645 
646  return result;
647 }
648 
649 static std::string GetAllOutputTypes() {
650  std::string ret;
651  for (int i = TX_NONSTANDARD; i <= TX_NULL_DATA; ++i) {
652  if (i != TX_NONSTANDARD) {
653  ret += ", ";
654  }
655  ret += GetTxnOutputType(static_cast<txnouttype>(i));
656  }
657  return ret;
658 }
659 
660 static UniValue decodescript(const Config &config,
661  const JSONRPCRequest &request) {
662  RPCHelpMan{
663  "decodescript",
664  "Decode a hex-encoded script.\n",
665  {
667  "the hex-encoded script"},
668  },
669  RPCResult{
671  "",
672  "",
673  {
674  {RPCResult::Type::STR, "asm", "Script public key"},
675  {RPCResult::Type::STR, "type",
676  "The output type (e.g. " + GetAllOutputTypes() + ")"},
677  {RPCResult::Type::NUM, "reqSigs", "The required signatures"},
679  "addresses",
680  "",
681  {
682  {RPCResult::Type::STR, "address", "bitcoin address"},
683  }},
684  {RPCResult::Type::STR, "p2sh",
685  "address of P2SH script wrapping this redeem script (not "
686  "returned if the script is already a P2SH)"},
687  }},
688  RPCExamples{HelpExampleCli("decodescript", "\"hexstring\"") +
689  HelpExampleRpc("decodescript", "\"hexstring\"")},
690  }
691  .Check(request);
692 
693  RPCTypeCheck(request.params, {UniValue::VSTR});
694 
696  CScript script;
697  if (request.params[0].get_str().size() > 0) {
698  std::vector<uint8_t> scriptData(
699  ParseHexV(request.params[0], "argument"));
700  script = CScript(scriptData.begin(), scriptData.end());
701  } else {
702  // Empty scripts are valid.
703  }
704 
705  ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false);
706 
707  UniValue type;
708  type = find_value(r, "type");
709 
710  if (type.isStr() && type.get_str() != "scripthash") {
711  // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
712  // don't return the address for a P2SH of the P2SH.
713  r.pushKV("p2sh", EncodeDestination(ScriptHash(script), config));
714  }
715 
716  return r;
717 }
718 
719 static UniValue combinerawtransaction(const Config &config,
720  const JSONRPCRequest &request) {
721  RPCHelpMan{
722  "combinerawtransaction",
723  "Combine multiple partially signed transactions into one "
724  "transaction.\n"
725  "The combined transaction may be another partially signed transaction "
726  "or a \n"
727  "fully signed transaction.",
728  {
729  {
730  "txs",
733  "The hex strings of partially signed "
734  "transactions",
735  {
736  {"hexstring", RPCArg::Type::STR_HEX,
737  RPCArg::Optional::OMITTED, "A transaction hash"},
738  },
739  },
740  },
742  "The hex-encoded raw transaction with signature(s)"},
743  RPCExamples{HelpExampleCli("combinerawtransaction",
744  "[\"myhex1\", \"myhex2\", \"myhex3\"]")},
745  }
746  .Check(request);
747 
748  UniValue txs = request.params[0].get_array();
749  std::vector<CMutableTransaction> txVariants(txs.size());
750 
751  for (unsigned int idx = 0; idx < txs.size(); idx++) {
752  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
754  strprintf("TX decode failed for tx %d", idx));
755  }
756  }
757 
758  if (txVariants.empty()) {
759  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
760  }
761 
762  // mergedTx will end up with all the signatures; it
763  // starts as a clone of the rawtx:
764  CMutableTransaction mergedTx(txVariants[0]);
765 
766  // Fetch previous transactions (inputs):
767  CCoinsView viewDummy;
768  CCoinsViewCache view(&viewDummy);
769  {
770  const CTxMemPool &mempool = EnsureMemPool(request.context);
771  LOCK(cs_main);
772  LOCK(mempool.cs);
774  CCoinsViewMemPool viewMempool(&viewChain, mempool);
775  // temporarily switch cache backend to db+mempool view
776  view.SetBackend(viewMempool);
777 
778  for (const CTxIn &txin : mergedTx.vin) {
779  // Load entries from viewChain into view; can fail.
780  view.AccessCoin(txin.prevout);
781  }
782 
783  // switch back to avoid locking mempool for too long
784  view.SetBackend(viewDummy);
785  }
786 
787  // Use CTransaction for the constant parts of the
788  // transaction to avoid rehashing.
789  const CTransaction txConst(mergedTx);
790  // Sign what we can:
791  for (size_t i = 0; i < mergedTx.vin.size(); i++) {
792  CTxIn &txin = mergedTx.vin[i];
793  const Coin &coin = view.AccessCoin(txin.prevout);
794  if (coin.IsSpent()) {
796  "Input not found or already spent");
797  }
798  SignatureData sigdata;
799 
800  const CTxOut &txout = coin.GetTxOut();
801 
802  // ... and merge in other signatures:
803  for (const CMutableTransaction &txv : txVariants) {
804  if (txv.vin.size() > i) {
805  sigdata.MergeSignatureData(DataFromTransaction(txv, i, txout));
806  }
807  }
810  MutableTransactionSignatureCreator(&mergedTx, i, txout.nValue),
811  txout.scriptPubKey, sigdata);
812 
813  UpdateInput(txin, sigdata);
814  }
815 
816  return EncodeHexTx(CTransaction(mergedTx));
817 }
818 
820  const JSONRPCRequest &request) {
821  RPCHelpMan{
822  "signrawtransactionwithkey",
823  "Sign inputs for raw transaction (serialized, hex-encoded).\n"
824  "The second argument is an array of base58-encoded private\n"
825  "keys that will be the only keys used to sign the transaction.\n"
826  "The third optional argument (may be null) is an array of previous "
827  "transaction outputs that\n"
828  "this transaction depends on but may not yet be in the block chain.\n",
829  {
831  "The transaction hex string"},
832  {
833  "privkeys",
836  "The base58-encoded private keys for signing",
837  {
839  "private key in base58-encoding"},
840  },
841  },
842  {
843  "prevtxs",
846  "The previous dependent transaction outputs",
847  {
848  {
849  "",
852  "",
853  {
854  {"txid", RPCArg::Type::STR_HEX,
855  RPCArg::Optional::NO, "The transaction id"},
857  "The output number"},
858  {"scriptPubKey", RPCArg::Type::STR_HEX,
859  RPCArg::Optional::NO, "script key"},
860  {"redeemScript", RPCArg::Type::STR_HEX,
862  "(required for P2SH) redeem script"},
863  {"amount", RPCArg::Type::AMOUNT,
864  RPCArg::Optional::NO, "The amount spent"},
865  },
866  },
867  },
868  },
869  {"sighashtype", RPCArg::Type::STR, /* default */ "ALL|FORKID",
870  "The signature hash type. Must be one of:\n"
871  " \"ALL|FORKID\"\n"
872  " \"NONE|FORKID\"\n"
873  " \"SINGLE|FORKID\"\n"
874  " \"ALL|FORKID|ANYONECANPAY\"\n"
875  " \"NONE|FORKID|ANYONECANPAY\"\n"
876  " \"SINGLE|FORKID|ANYONECANPAY\""},
877  },
878  RPCResult{
880  "",
881  "",
882  {
883  {RPCResult::Type::STR_HEX, "hex",
884  "The hex-encoded raw transaction with signature(s)"},
885  {RPCResult::Type::BOOL, "complete",
886  "If the transaction has a complete set of signatures"},
888  "errors",
889  "Script verification errors (if there are any)",
890  {
892  "",
893  "",
894  {
895  {RPCResult::Type::STR_HEX, "txid",
896  "The hash of the referenced, previous transaction"},
897  {RPCResult::Type::NUM, "vout",
898  "The index of the output to spent and used as "
899  "input"},
900  {RPCResult::Type::STR_HEX, "scriptSig",
901  "The hex-encoded signature script"},
902  {RPCResult::Type::NUM, "sequence",
903  "Script sequence number"},
904  {RPCResult::Type::STR, "error",
905  "Verification or signing error related to the "
906  "input"},
907  }},
908  }},
909  }},
910  RPCExamples{
911  HelpExampleCli("signrawtransactionwithkey",
912  "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"") +
913  HelpExampleRpc("signrawtransactionwithkey",
914  "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")},
915  }
916  .Check(request);
917 
918  RPCTypeCheck(
919  request.params,
920  {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
921 
923  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
924  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
925  }
926 
927  FillableSigningProvider keystore;
928  const UniValue &keys = request.params[1].get_array();
929  for (size_t idx = 0; idx < keys.size(); ++idx) {
930  UniValue k = keys[idx];
931  CKey key = DecodeSecret(k.get_str());
932  if (!key.IsValid()) {
934  "Invalid private key");
935  }
936  keystore.AddKey(key);
937  }
938 
939  // Fetch previous transactions (inputs):
940  std::map<COutPoint, Coin> coins;
941  for (const CTxIn &txin : mtx.vin) {
942  // Create empty map entry keyed by prevout.
943  coins[txin.prevout];
944  }
945  NodeContext &node = EnsureNodeContext(request.context);
946  FindCoins(node, coins);
947 
948  // Parse the prevtxs array
949  ParsePrevouts(request.params[2], &keystore, coins);
950 
951  UniValue result(UniValue::VOBJ);
952  SignTransaction(mtx, &keystore, coins, request.params[3], result);
953  return result;
954 }
955 
956 static UniValue sendrawtransaction(const Config &config,
957  const JSONRPCRequest &request) {
958  RPCHelpMan{
959  "sendrawtransaction",
960  "Submits raw transaction (serialized, hex-encoded) to local node and "
961  "network.\n"
962  "\nAlso see createrawtransaction and "
963  "signrawtransactionwithkey calls.\n",
964  {
966  "The hex string of the raw transaction"},
967  {"maxfeerate", RPCArg::Type::AMOUNT,
968  /* default */
970  "Reject transactions whose fee rate is higher than the specified "
971  "value, expressed in " +
972  CURRENCY_UNIT + "/kB\nSet to 0 to accept any fee rate.\n"},
973  },
974  RPCResult{RPCResult::Type::STR_HEX, "", "The transaction hash in hex"},
975  RPCExamples{
976  "\nCreate a transaction\n" +
978  "createrawtransaction",
979  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
980  "\"{\\\"myaddress\\\":0.01}\"") +
981  "Sign the transaction, and get back the hex\n" +
982  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
983  "\nSend the transaction (signed hex)\n" +
984  HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
985  "\nAs a JSON-RPC call\n" +
986  HelpExampleRpc("sendrawtransaction", "\"signedhex\"")},
987  }
988  .Check(request);
989 
990  RPCTypeCheck(request.params,
991  {
992  UniValue::VSTR,
993  // VNUM or VSTR, checked inside AmountFromValue()
994  UniValueType(),
995  });
996 
997  // parse hex string from parameter
999  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
1000  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1001  }
1002 
1003  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
1004 
1005  const CFeeRate max_raw_tx_fee_rate =
1006  request.params[1].isNull()
1008  : CFeeRate(AmountFromValue(request.params[1]));
1009 
1010  int64_t virtual_size = GetVirtualTransactionSize(*tx);
1011  Amount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
1012 
1013  std::string err_string;
1015  NodeContext &node = EnsureNodeContext(request.context);
1017  node, config, tx, err_string, max_raw_tx_fee, /*relay*/ true,
1018  /*wait_callback*/ true);
1019  if (err != TransactionError::OK) {
1020  throw JSONRPCTransactionError(err, err_string);
1021  }
1022 
1023  return tx->GetHash().GetHex();
1024 }
1025 
1026 static UniValue testmempoolaccept(const Config &config,
1027  const JSONRPCRequest &request) {
1028  RPCHelpMan{
1029  "testmempoolaccept",
1030  "Returns result of mempool acceptance tests indicating if raw"
1031  " transaction (serialized, hex-encoded) would be accepted"
1032  " by mempool.\n"
1033  "\nThis checks if the transaction violates the consensus or policy "
1034  "rules.\n"
1035  "\nSee sendrawtransaction call.\n",
1036  {
1037  {
1038  "rawtxs",
1041  "An array of hex strings of raw transactions.\n"
1042  " Length must be one for now.",
1043  {
1045  ""},
1046  },
1047  },
1048  {"maxfeerate", RPCArg::Type::AMOUNT,
1049  /* default */
1051  "Reject transactions whose fee rate is higher than the specified "
1052  "value, expressed in " +
1053  CURRENCY_UNIT + "/kB\n"},
1054  },
1056  "",
1057  "The result of the mempool acceptance test for each raw "
1058  "transaction in the input array.\n"
1059  "Length is exactly one for now.",
1060  {
1062  "",
1063  "",
1064  {
1065  {RPCResult::Type::STR_HEX, "txid",
1066  "The transaction hash in hex"},
1067  {RPCResult::Type::BOOL, "allowed",
1068  "If the mempool allows this tx to be inserted"},
1069  {RPCResult::Type::STR, "reject-reason",
1070  "Rejection string (only present when 'allowed' is "
1071  "false)"},
1072  }},
1073  }},
1074  RPCExamples{
1075  "\nCreate a transaction\n" +
1077  "createrawtransaction",
1078  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
1079  "\"{\\\"myaddress\\\":0.01}\"") +
1080  "Sign the transaction, and get back the hex\n" +
1081  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
1082  "\nTest acceptance of the transaction (signed hex)\n" +
1083  HelpExampleCli("testmempoolaccept", "[\"signedhex\"]") +
1084  "\nAs a JSON-RPC call\n" +
1085  HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")},
1086  }
1087  .Check(request);
1088 
1089  RPCTypeCheck(request.params,
1090  {
1091  UniValue::VARR,
1092  // VNUM or VSTR, checked inside AmountFromValue()
1093  UniValueType(),
1094  });
1095 
1096  if (request.params[0].get_array().size() != 1) {
1097  throw JSONRPCError(
1099  "Array must contain exactly one raw transaction for now");
1100  }
1101 
1102  CMutableTransaction mtx;
1103  if (!DecodeHexTx(mtx, request.params[0].get_array()[0].get_str())) {
1104  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1105  }
1106  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
1107  const TxId &txid = tx->GetId();
1108 
1109  const CFeeRate max_raw_tx_fee_rate =
1110  request.params[1].isNull()
1112  : CFeeRate(AmountFromValue(request.params[1]));
1113 
1114  CTxMemPool &mempool = EnsureMemPool(request.context);
1115  int64_t virtual_size = GetVirtualTransactionSize(*tx);
1116  Amount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
1117 
1118  UniValue result(UniValue::VARR);
1119  UniValue result_0(UniValue::VOBJ);
1120  result_0.pushKV("txid", txid.GetHex());
1121 
1122  TxValidationState state;
1123  bool test_accept_res;
1124  {
1125  LOCK(cs_main);
1126  test_accept_res = AcceptToMemoryPool(
1127  config, mempool, state, std::move(tx), false /* bypass_limits */,
1128  max_raw_tx_fee, true /* test_accept */);
1129  }
1130  result_0.pushKV("allowed", test_accept_res);
1131  if (!test_accept_res) {
1132  if (state.IsInvalid()) {
1134  result_0.pushKV("reject-reason", "missing-inputs");
1135  } else {
1136  result_0.pushKV("reject-reason",
1137  strprintf("%s", state.GetRejectReason()));
1138  }
1139  } else {
1140  result_0.pushKV("reject-reason", state.GetRejectReason());
1141  }
1142  }
1143 
1144  result.push_back(std::move(result_0));
1145  return result;
1146 }
1147 
1148 static std::string WriteHDKeypath(std::vector<uint32_t> &keypath) {
1149  std::string keypath_str = "m";
1150  for (uint32_t num : keypath) {
1151  keypath_str += "/";
1152  bool hardened = false;
1153  if (num & 0x80000000) {
1154  hardened = true;
1155  num &= ~0x80000000;
1156  }
1157 
1158  keypath_str += ToString(num);
1159  if (hardened) {
1160  keypath_str += "'";
1161  }
1162  }
1163  return keypath_str;
1164 }
1165 
1166 static UniValue decodepsbt(const Config &config,
1167  const JSONRPCRequest &request) {
1168  RPCHelpMan{
1169  "decodepsbt",
1170  "Return a JSON object representing the serialized, base64-encoded "
1171  "partially signed Bitcoin transaction.\n",
1172  {
1174  "The PSBT base64 string"},
1175  },
1176  RPCResult{
1178  "",
1179  "",
1180  {
1182  "tx",
1183  "The decoded network-serialized unsigned transaction.",
1184  {
1186  "The layout is the same as the output of "
1187  "decoderawtransaction."},
1188  }},
1190  "unknown",
1191  "The unknown global fields",
1192  {
1193  {RPCResult::Type::STR_HEX, "key",
1194  "(key-value pair) An unknown key-value pair"},
1195  }},
1197  "inputs",
1198  "",
1199  {
1201  "",
1202  "",
1203  {
1205  "utxo",
1206  /* optional */ true,
1207  "Transaction output for UTXOs",
1208  {
1209  {RPCResult::Type::NUM, "amount",
1210  "The value in " + CURRENCY_UNIT},
1212  "scriptPubKey",
1213  "",
1214  {
1215  {RPCResult::Type::STR, "asm", "The asm"},
1216  {RPCResult::Type::STR_HEX, "hex",
1217  "The hex"},
1218  {RPCResult::Type::STR, "type",
1219  "The type, eg 'pubkeyhash'"},
1220  {RPCResult::Type::STR, "address",
1221  " Bitcoin address if there is one"},
1222  }},
1223  }},
1225  "partial_signatures",
1226  /* optional */ true,
1227  "",
1228  {
1229  {RPCResult::Type::STR, "pubkey",
1230  "The public key and signature that corresponds "
1231  "to it."},
1232  }},
1233  {RPCResult::Type::STR, "sighash", /* optional */ true,
1234  "The sighash type to be used"},
1236  "redeem_script",
1237  /* optional */ true,
1238  "",
1239  {
1240  {RPCResult::Type::STR, "asm", "The asm"},
1241  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1242  {RPCResult::Type::STR, "type",
1243  "The type, eg 'pubkeyhash'"},
1244  }},
1246  "bip32_derivs",
1247  /* optional */ true,
1248  "",
1249  {
1251  "pubkey",
1252  /* optional */ true,
1253  "The public key with the derivation path as "
1254  "the value.",
1255  {
1256  {RPCResult::Type::STR, "master_fingerprint",
1257  "The fingerprint of the master key"},
1258  {RPCResult::Type::STR, "path", "The path"},
1259  }},
1260  }},
1262  "final_scriptsig",
1263  /* optional */ true,
1264  "",
1265  {
1266  {RPCResult::Type::STR, "asm", "The asm"},
1267  {RPCResult::Type::STR, "hex", "The hex"},
1268  }},
1270  "unknown",
1271  "The unknown global fields",
1272  {
1273  {RPCResult::Type::STR_HEX, "key",
1274  "(key-value pair) An unknown key-value pair"},
1275  }},
1276  }},
1277  }},
1279  "outputs",
1280  "",
1281  {
1283  "",
1284  "",
1285  {
1287  "redeem_script",
1288  /* optional */ true,
1289  "",
1290  {
1291  {RPCResult::Type::STR, "asm", "The asm"},
1292  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1293  {RPCResult::Type::STR, "type",
1294  "The type, eg 'pubkeyhash'"},
1295  }},
1297  "bip32_derivs",
1298  /* optional */ true,
1299  "",
1300  {
1302  "",
1303  "",
1304  {
1305  {RPCResult::Type::STR, "pubkey",
1306  "The public key this path corresponds to"},
1307  {RPCResult::Type::STR, "master_fingerprint",
1308  "The fingerprint of the master key"},
1309  {RPCResult::Type::STR, "path", "The path"},
1310  }},
1311  }},
1313  "unknown",
1314  "The unknown global fields",
1315  {
1316  {RPCResult::Type::STR_HEX, "key",
1317  "(key-value pair) An unknown key-value pair"},
1318  }},
1319  }},
1320  }},
1321  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
1322  "The transaction fee paid if all UTXOs slots in the PSBT have "
1323  "been filled."},
1324  }},
1325  RPCExamples{HelpExampleCli("decodepsbt", "\"psbt\"")},
1326  }
1327  .Check(request);
1328 
1329  RPCTypeCheck(request.params, {UniValue::VSTR});
1330 
1331  // Unserialize the transactions
1333  std::string error;
1334  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1336  strprintf("TX decode failed %s", error));
1337  }
1338 
1339  UniValue result(UniValue::VOBJ);
1340 
1341  // Add the decoded tx
1342  UniValue tx_univ(UniValue::VOBJ);
1343  TxToUniv(CTransaction(*psbtx.tx), uint256(), tx_univ, false);
1344  result.pushKV("tx", tx_univ);
1345 
1346  // Unknown data
1347  if (psbtx.unknown.size() > 0) {
1348  UniValue unknowns(UniValue::VOBJ);
1349  for (auto entry : psbtx.unknown) {
1350  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1351  }
1352  result.pushKV("unknown", unknowns);
1353  }
1354 
1355  // inputs
1356  Amount total_in = Amount::zero();
1357  bool have_all_utxos = true;
1358  UniValue inputs(UniValue::VARR);
1359  for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
1360  const PSBTInput &input = psbtx.inputs[i];
1362  // UTXOs
1363  if (!input.utxo.IsNull()) {
1364  const CTxOut &txout = input.utxo;
1365 
1366  UniValue out(UniValue::VOBJ);
1367 
1368  out.pushKV("amount", ValueFromAmount(txout.nValue));
1369  if (MoneyRange(txout.nValue) &&
1370  MoneyRange(total_in + txout.nValue)) {
1371  total_in += txout.nValue;
1372  } else {
1373  // Hack to just not show fee later
1374  have_all_utxos = false;
1375  }
1376 
1378  ScriptToUniv(txout.scriptPubKey, o, true);
1379  out.pushKV("scriptPubKey", o);
1380  in.pushKV("utxo", out);
1381  } else {
1382  have_all_utxos = false;
1383  }
1384 
1385  // Partial sigs
1386  if (!input.partial_sigs.empty()) {
1387  UniValue partial_sigs(UniValue::VOBJ);
1388  for (const auto &sig : input.partial_sigs) {
1389  partial_sigs.pushKV(HexStr(sig.second.first),
1390  HexStr(sig.second.second));
1391  }
1392  in.pushKV("partial_signatures", partial_sigs);
1393  }
1394 
1395  // Sighash
1396  uint8_t sighashbyte = input.sighash_type.getRawSigHashType() & 0xff;
1397  if (sighashbyte > 0) {
1398  in.pushKV("sighash", SighashToStr(sighashbyte));
1399  }
1400 
1401  // Redeem script
1402  if (!input.redeem_script.empty()) {
1404  ScriptToUniv(input.redeem_script, r, false);
1405  in.pushKV("redeem_script", r);
1406  }
1407 
1408  // keypaths
1409  if (!input.hd_keypaths.empty()) {
1410  UniValue keypaths(UniValue::VARR);
1411  for (auto entry : input.hd_keypaths) {
1412  UniValue keypath(UniValue::VOBJ);
1413  keypath.pushKV("pubkey", HexStr(entry.first));
1414 
1415  keypath.pushKV(
1416  "master_fingerprint",
1417  strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1418  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1419  keypaths.push_back(keypath);
1420  }
1421  in.pushKV("bip32_derivs", keypaths);
1422  }
1423 
1424  // Final scriptSig
1425  if (!input.final_script_sig.empty()) {
1426  UniValue scriptsig(UniValue::VOBJ);
1427  scriptsig.pushKV("asm",
1428  ScriptToAsmStr(input.final_script_sig, true));
1429  scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1430  in.pushKV("final_scriptSig", scriptsig);
1431  }
1432 
1433  // Unknown data
1434  if (input.unknown.size() > 0) {
1435  UniValue unknowns(UniValue::VOBJ);
1436  for (auto entry : input.unknown) {
1437  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1438  }
1439  in.pushKV("unknown", unknowns);
1440  }
1441 
1442  inputs.push_back(in);
1443  }
1444  result.pushKV("inputs", inputs);
1445 
1446  // outputs
1447  Amount output_value = Amount::zero();
1448  UniValue outputs(UniValue::VARR);
1449  for (size_t i = 0; i < psbtx.outputs.size(); ++i) {
1450  const PSBTOutput &output = psbtx.outputs[i];
1451  UniValue out(UniValue::VOBJ);
1452  // Redeem script
1453  if (!output.redeem_script.empty()) {
1455  ScriptToUniv(output.redeem_script, r, false);
1456  out.pushKV("redeem_script", r);
1457  }
1458 
1459  // keypaths
1460  if (!output.hd_keypaths.empty()) {
1461  UniValue keypaths(UniValue::VARR);
1462  for (auto entry : output.hd_keypaths) {
1463  UniValue keypath(UniValue::VOBJ);
1464  keypath.pushKV("pubkey", HexStr(entry.first));
1465  keypath.pushKV(
1466  "master_fingerprint",
1467  strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1468  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1469  keypaths.push_back(keypath);
1470  }
1471  out.pushKV("bip32_derivs", keypaths);
1472  }
1473 
1474  // Unknown data
1475  if (output.unknown.size() > 0) {
1476  UniValue unknowns(UniValue::VOBJ);
1477  for (auto entry : output.unknown) {
1478  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1479  }
1480  out.pushKV("unknown", unknowns);
1481  }
1482 
1483  outputs.push_back(out);
1484 
1485  // Fee calculation
1486  if (MoneyRange(psbtx.tx->vout[i].nValue) &&
1487  MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
1488  output_value += psbtx.tx->vout[i].nValue;
1489  } else {
1490  // Hack to just not show fee later
1491  have_all_utxos = false;
1492  }
1493  }
1494  result.pushKV("outputs", outputs);
1495  if (have_all_utxos) {
1496  result.pushKV("fee", ValueFromAmount(total_in - output_value));
1497  }
1498 
1499  return result;
1500 }
1501 
1502 static UniValue combinepsbt(const Config &config,
1503  const JSONRPCRequest &request) {
1504  RPCHelpMan{
1505  "combinepsbt",
1506  "Combine multiple partially signed Bitcoin transactions into one "
1507  "transaction.\n"
1508  "Implements the Combiner role.\n",
1509  {
1510  {
1511  "txs",
1514  "The base64 strings of partially signed transactions",
1515  {
1517  "A base64 string of a PSBT"},
1518  },
1519  },
1520  },
1522  "The base64-encoded partially signed transaction"},
1524  "combinepsbt", "[\"mybase64_1\", \"mybase64_2\", \"mybase64_3\"]")},
1525  }
1526  .Check(request);
1527 
1528  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1529 
1530  // Unserialize the transactions
1531  std::vector<PartiallySignedTransaction> psbtxs;
1532  UniValue txs = request.params[0].get_array();
1533  if (txs.empty()) {
1535  "Parameter 'txs' cannot be empty");
1536  }
1537  for (size_t i = 0; i < txs.size(); ++i) {
1539  std::string error;
1540  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1542  strprintf("TX decode failed %s", error));
1543  }
1544  psbtxs.push_back(psbtx);
1545  }
1546 
1547  PartiallySignedTransaction merged_psbt;
1548  const TransactionError error = CombinePSBTs(merged_psbt, psbtxs);
1549  if (error != TransactionError::OK) {
1550  throw JSONRPCTransactionError(error);
1551  }
1552 
1554  ssTx << merged_psbt;
1555  return EncodeBase64((uint8_t *)ssTx.data(), ssTx.size());
1556 }
1557 
1558 static UniValue finalizepsbt(const Config &config,
1559  const JSONRPCRequest &request) {
1560  RPCHelpMan{
1561  "finalizepsbt",
1562  "Finalize the inputs of a PSBT. If the transaction is fully signed, it "
1563  "will produce a\n"
1564  "network serialized transaction which can be broadcast with "
1565  "sendrawtransaction. Otherwise a PSBT will be\n"
1566  "created which has the final_scriptSigfields filled for inputs that "
1567  "are complete.\n"
1568  "Implements the Finalizer and Extractor roles.\n",
1569  {
1571  "A base64 string of a PSBT"},
1572  {"extract", RPCArg::Type::BOOL, /* default */ "true",
1573  "If true and the transaction is complete,\n"
1574  " extract and return the complete "
1575  "transaction in normal network serialization instead of the "
1576  "PSBT."},
1577  },
1579  "",
1580  "",
1581  {
1582  {RPCResult::Type::STR, "psbt",
1583  "The base64-encoded partially signed transaction if not "
1584  "extracted"},
1585  {RPCResult::Type::STR_HEX, "hex",
1586  "The hex-encoded network transaction if extracted"},
1587  {RPCResult::Type::BOOL, "complete",
1588  "If the transaction has a complete set of signatures"},
1589  }},
1590  RPCExamples{HelpExampleCli("finalizepsbt", "\"psbt\"")},
1591  }
1592  .Check(request);
1593 
1594  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true);
1595 
1596  // Unserialize the transactions
1598  std::string error;
1599  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1601  strprintf("TX decode failed %s", error));
1602  }
1603 
1604  bool extract = request.params[1].isNull() || (!request.params[1].isNull() &&
1605  request.params[1].get_bool());
1606 
1607  CMutableTransaction mtx;
1608  bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1609 
1610  UniValue result(UniValue::VOBJ);
1612  std::string result_str;
1613 
1614  if (complete && extract) {
1615  ssTx << mtx;
1616  result_str = HexStr(ssTx.str());
1617  result.pushKV("hex", result_str);
1618  } else {
1619  ssTx << psbtx;
1620  result_str = EncodeBase64(ssTx.str());
1621  result.pushKV("psbt", result_str);
1622  }
1623  result.pushKV("complete", complete);
1624 
1625  return result;
1626 }
1627 
1628 static UniValue createpsbt(const Config &config,
1629  const JSONRPCRequest &request) {
1630  RPCHelpMan{
1631  "createpsbt",
1632  "Creates a transaction in the Partially Signed Transaction format.\n"
1633  "Implements the Creator role.\n",
1634  {
1635  {
1636  "inputs",
1639  "The json objects",
1640  {
1641  {
1642  "",
1645  "",
1646  {
1647  {"txid", RPCArg::Type::STR_HEX,
1648  RPCArg::Optional::NO, "The transaction id"},
1650  "The output number"},
1651  {"sequence", RPCArg::Type::NUM, /* default */
1652  "depends on the value of the 'locktime' argument",
1653  "The sequence number"},
1654  },
1655  },
1656  },
1657  },
1658  {
1659  "outputs",
1662  "The outputs (key-value pairs), where none of "
1663  "the keys are duplicated.\n"
1664  "That is, each address can only appear once and there can only "
1665  "be one 'data' object.\n"
1666  "For compatibility reasons, a dictionary, which holds the "
1667  "key-value pairs directly, is also\n"
1668  " accepted as second parameter.",
1669  {
1670  {
1671  "",
1674  "",
1675  {
1676  {"address", RPCArg::Type::AMOUNT,
1678  "A key-value pair. The key (string) is the "
1679  "bitcoin address, the value (float or string) is "
1680  "the amount in " +
1681  CURRENCY_UNIT},
1682  },
1683  },
1684  {
1685  "",
1688  "",
1689  {
1690  {"data", RPCArg::Type::STR_HEX,
1692  "A key-value pair. The key must be \"data\", the "
1693  "value is hex-encoded data"},
1694  },
1695  },
1696  },
1697  },
1698  {"locktime", RPCArg::Type::NUM, /* default */ "0",
1699  "Raw locktime. Non-0 value also locktime-activates inputs"},
1700  },
1702  "The resulting raw transaction (base64-encoded string)"},
1704  "createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1705  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
1706  }
1707  .Check(request);
1708 
1709  RPCTypeCheck(request.params,
1710  {
1711  UniValue::VARR,
1712  UniValueType(), // ARR or OBJ, checked later
1713  UniValue::VNUM,
1714  },
1715  true);
1716 
1717  CMutableTransaction rawTx =
1718  ConstructTransaction(config.GetChainParams(), request.params[0],
1719  request.params[1], request.params[2]);
1720 
1721  // Make a blank psbt
1723  psbtx.tx = rawTx;
1724  for (size_t i = 0; i < rawTx.vin.size(); ++i) {
1725  psbtx.inputs.push_back(PSBTInput());
1726  }
1727  for (size_t i = 0; i < rawTx.vout.size(); ++i) {
1728  psbtx.outputs.push_back(PSBTOutput());
1729  }
1730 
1731  // Serialize the PSBT
1733  ssTx << psbtx;
1734 
1735  return EncodeBase64((uint8_t *)ssTx.data(), ssTx.size());
1736 }
1737 
1738 static UniValue converttopsbt(const Config &config,
1739  const JSONRPCRequest &request) {
1740  RPCHelpMan{
1741  "converttopsbt",
1742  "Converts a network serialized transaction to a PSBT. "
1743  "This should be used only with createrawtransaction and "
1744  "fundrawtransaction\n"
1745  "createpsbt and walletcreatefundedpsbt should be used for new "
1746  "applications.\n",
1747  {
1749  "The hex string of a raw transaction"},
1750  {"permitsigdata", RPCArg::Type::BOOL, /* default */ "false",
1751  "If true, any signatures in the input will be discarded and "
1752  "conversion.\n"
1753  " will continue. If false, RPC will "
1754  "fail if any signatures are present."},
1755  },
1757  "The resulting raw transaction (base64-encoded string)"},
1758  RPCExamples{
1759  "\nCreate a transaction\n" +
1760  HelpExampleCli("createrawtransaction",
1761  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1762  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1763  "\nConvert the transaction to a PSBT\n" +
1764  HelpExampleCli("converttopsbt", "\"rawtransaction\"")},
1765  }
1766  .Check(request);
1767 
1768  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true);
1769 
1770  // parse hex string from parameter
1772  bool permitsigdata =
1773  request.params[1].isNull() ? false : request.params[1].get_bool();
1774  if (!DecodeHexTx(tx, request.params[0].get_str())) {
1775  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1776  }
1777 
1778  // Remove all scriptSigs from inputs
1779  for (CTxIn &input : tx.vin) {
1780  if (!input.scriptSig.empty() && !permitsigdata) {
1782  "Inputs must not have scriptSigs");
1783  }
1784  input.scriptSig.clear();
1785  }
1786 
1787  // Make a blank psbt
1789  psbtx.tx = tx;
1790  for (size_t i = 0; i < tx.vin.size(); ++i) {
1791  psbtx.inputs.push_back(PSBTInput());
1792  }
1793  for (size_t i = 0; i < tx.vout.size(); ++i) {
1794  psbtx.outputs.push_back(PSBTOutput());
1795  }
1796 
1797  // Serialize the PSBT
1799  ssTx << psbtx;
1800 
1801  return EncodeBase64((uint8_t *)ssTx.data(), ssTx.size());
1802 }
1803 
1804 UniValue utxoupdatepsbt(const Config &config, const JSONRPCRequest &request) {
1805  RPCHelpMan{
1806  "utxoupdatepsbt",
1807  "Updates all inputs and outputs in a PSBT with data from output "
1808  "descriptors, the UTXO set or the mempool.\n",
1809  {
1811  "A base64 string of a PSBT"},
1812  {"descriptors",
1815  "An array of either strings or objects",
1816  {
1818  "An output descriptor"},
1819  {"",
1822  "An object with an output descriptor and extra information",
1823  {
1825  "An output descriptor"},
1826  {"range", RPCArg::Type::RANGE, "1000",
1827  "Up to what index HD chains should be explored (either "
1828  "end or [begin,end])"},
1829  }},
1830  }},
1831  },
1833  "The base64-encoded partially signed transaction with inputs "
1834  "updated"},
1835  RPCExamples{HelpExampleCli("utxoupdatepsbt", "\"psbt\"")}}
1836  .Check(request);
1837 
1838  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR}, true);
1839 
1840  // Unserialize the transactions
1842  std::string error;
1843  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1845  strprintf("TX decode failed %s", error));
1846  }
1847 
1848  // Parse descriptors, if any.
1849  FlatSigningProvider provider;
1850  if (!request.params[1].isNull()) {
1851  auto descs = request.params[1].get_array();
1852  for (size_t i = 0; i < descs.size(); ++i) {
1853  EvalDescriptorStringOrObject(descs[i], provider);
1854  }
1855  }
1856  // We don't actually need private keys further on; hide them as a
1857  // precaution.
1858  HidingSigningProvider public_provider(&provider, /* nosign */ true,
1859  /* nobip32derivs */ false);
1860 
1861  // Fetch previous transactions (inputs):
1862  CCoinsView viewDummy;
1863  CCoinsViewCache view(&viewDummy);
1864  {
1865  const CTxMemPool &mempool = EnsureMemPool(request.context);
1866  LOCK2(cs_main, mempool.cs);
1867  CCoinsViewCache &viewChain = ::ChainstateActive().CoinsTip();
1868  CCoinsViewMemPool viewMempool(&viewChain, mempool);
1869  // temporarily switch cache backend to db+mempool view
1870  view.SetBackend(viewMempool);
1871 
1872  for (const CTxIn &txin : psbtx.tx->vin) {
1873  // Load entries from viewChain into view; can fail.
1874  view.AccessCoin(txin.prevout);
1875  }
1876 
1877  // switch back to avoid locking mempool for too long
1878  view.SetBackend(viewDummy);
1879  }
1880 
1881  // Fill the inputs
1882  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
1883  PSBTInput &input = psbtx.inputs.at(i);
1884 
1885  if (!input.utxo.IsNull()) {
1886  continue;
1887  }
1888 
1889  // Update script/keypath information using descriptor data.
1890  // Note that SignPSBTInput does a lot more than just constructing ECDSA
1891  // signatures we don't actually care about those here, in fact.
1892  SignPSBTInput(public_provider, psbtx, i,
1893  /* sighash_type */ SigHashType().withForkId());
1894  }
1895 
1896  // Update script/keypath information using descriptor data.
1897  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1898  UpdatePSBTOutput(public_provider, psbtx, i);
1899  }
1900 
1902  ssTx << psbtx;
1903  return EncodeBase64((uint8_t *)ssTx.data(), ssTx.size());
1904 }
1905 
1906 UniValue joinpsbts(const Config &config, const JSONRPCRequest &request) {
1907  RPCHelpMan{
1908  "joinpsbts",
1909  "Joins multiple distinct PSBTs with different inputs and outputs "
1910  "into one PSBT with inputs and outputs from all of the PSBTs\n"
1911  "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1912  {{"txs",
1915  "The base64 strings of partially signed transactions",
1917  "A base64 string of a PSBT"}}}},
1919  "The base64-encoded partially signed transaction"},
1920  RPCExamples{HelpExampleCli("joinpsbts", "\"psbt\"")}}
1921  .Check(request);
1922 
1923  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1924 
1925  // Unserialize the transactions
1926  std::vector<PartiallySignedTransaction> psbtxs;
1927  UniValue txs = request.params[0].get_array();
1928 
1929  if (txs.size() <= 1) {
1931  "At least two PSBTs are required to join PSBTs.");
1932  }
1933 
1934  int32_t best_version = 1;
1935  uint32_t best_locktime = 0xffffffff;
1936  for (size_t i = 0; i < txs.size(); ++i) {
1938  std::string error;
1939  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1941  strprintf("TX decode failed %s", error));
1942  }
1943  psbtxs.push_back(psbtx);
1944  // Choose the highest version number
1945  if (psbtx.tx->nVersion > best_version) {
1946  best_version = psbtx.tx->nVersion;
1947  }
1948  // Choose the lowest lock time
1949  if (psbtx.tx->nLockTime < best_locktime) {
1950  best_locktime = psbtx.tx->nLockTime;
1951  }
1952  }
1953 
1954  // Create a blank psbt where everything will be added
1955  PartiallySignedTransaction merged_psbt;
1956  merged_psbt.tx = CMutableTransaction();
1957  merged_psbt.tx->nVersion = best_version;
1958  merged_psbt.tx->nLockTime = best_locktime;
1959 
1960  // Merge
1961  for (auto &psbt : psbtxs) {
1962  for (size_t i = 0; i < psbt.tx->vin.size(); ++i) {
1963  if (!merged_psbt.AddInput(psbt.tx->vin[i], psbt.inputs[i])) {
1964  throw JSONRPCError(
1966  strprintf(
1967  "Input %s:%d exists in multiple PSBTs",
1968  psbt.tx->vin[i].prevout.GetTxId().ToString().c_str(),
1969  psbt.tx->vin[i].prevout.GetN()));
1970  }
1971  }
1972  for (size_t i = 0; i < psbt.tx->vout.size(); ++i) {
1973  merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1974  }
1975  merged_psbt.unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
1976  }
1977 
1978  // Generate list of shuffled indices for shuffling inputs and outputs of the
1979  // merged PSBT
1980  std::vector<int> input_indices(merged_psbt.inputs.size());
1981  std::iota(input_indices.begin(), input_indices.end(), 0);
1982  std::vector<int> output_indices(merged_psbt.outputs.size());
1983  std::iota(output_indices.begin(), output_indices.end(), 0);
1984 
1985  // Shuffle input and output indices lists
1986  Shuffle(input_indices.begin(), input_indices.end(), FastRandomContext());
1987  Shuffle(output_indices.begin(), output_indices.end(), FastRandomContext());
1988 
1989  PartiallySignedTransaction shuffled_psbt;
1990  shuffled_psbt.tx = CMutableTransaction();
1991  shuffled_psbt.tx->nVersion = merged_psbt.tx->nVersion;
1992  shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1993  for (int i : input_indices) {
1994  shuffled_psbt.AddInput(merged_psbt.tx->vin[i], merged_psbt.inputs[i]);
1995  }
1996  for (int i : output_indices) {
1997  shuffled_psbt.AddOutput(merged_psbt.tx->vout[i],
1998  merged_psbt.outputs[i]);
1999  }
2000  shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(),
2001  merged_psbt.unknown.end());
2002 
2004  ssTx << shuffled_psbt;
2005  return EncodeBase64((uint8_t *)ssTx.data(), ssTx.size());
2006 }
2007 
2008 UniValue analyzepsbt(const Config &config, const JSONRPCRequest &request) {
2009  RPCHelpMan{
2010  "analyzepsbt",
2011  "Analyzes and provides information about the current status of a "
2012  "PSBT and its inputs\n",
2014  "A base64 string of a PSBT"}},
2015  RPCResult{
2017  "",
2018  "",
2019  {
2021  "inputs",
2022  "",
2023  {
2025  "",
2026  "",
2027  {
2028  {RPCResult::Type::BOOL, "has_utxo",
2029  "Whether a UTXO is provided"},
2030  {RPCResult::Type::BOOL, "is_final",
2031  "Whether the input is finalized"},
2033  "missing",
2034  /* optional */ true,
2035  "Things that are missing that are required to "
2036  "complete this input",
2037  {
2039  "pubkeys",
2040  /* optional */ true,
2041  "",
2042  {
2043  {RPCResult::Type::STR_HEX, "keyid",
2044  "Public key ID, hash160 of the public "
2045  "key, of a public key whose BIP 32 "
2046  "derivation path is missing"},
2047  }},
2049  "signatures",
2050  /* optional */ true,
2051  "",
2052  {
2053  {RPCResult::Type::STR_HEX, "keyid",
2054  "Public key ID, hash160 of the public "
2055  "key, of a public key whose signature is "
2056  "missing"},
2057  }},
2058  {RPCResult::Type::STR_HEX, "redeemscript",
2059  /* optional */ true,
2060  "Hash160 of the redeemScript that is missing"},
2061  }},
2062  {RPCResult::Type::STR, "next", /* optional */ true,
2063  "Role of the next person that this input needs to "
2064  "go to"},
2065  }},
2066  }},
2067  {RPCResult::Type::NUM, "estimated_vsize", /* optional */ true,
2068  "Estimated vsize of the final signed transaction"},
2069  {RPCResult::Type::STR_AMOUNT, "estimated_feerate",
2070  /* optional */ true,
2071  "Estimated feerate of the final signed transaction in " +
2072  CURRENCY_UNIT +
2073  "/kB. Shown only if all UTXO slots in the PSBT have been "
2074  "filled"},
2075  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
2076  "The transaction fee paid. Shown only if all UTXO slots in "
2077  "the PSBT have been filled"},
2078  {RPCResult::Type::STR, "next",
2079  "Role of the next person that this psbt needs to go to"},
2080  {RPCResult::Type::STR, "error",
2081  "Error message if there is one"},
2082  }},
2083  RPCExamples{HelpExampleCli("analyzepsbt", "\"psbt\"")}}
2084  .Check(request);
2085 
2086  RPCTypeCheck(request.params, {UniValue::VSTR});
2087 
2088  // Unserialize the transaction
2090  std::string error;
2091  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
2093  strprintf("TX decode failed %s", error));
2094  }
2095 
2096  PSBTAnalysis psbta = AnalyzePSBT(psbtx);
2097 
2098  UniValue result(UniValue::VOBJ);
2099  UniValue inputs_result(UniValue::VARR);
2100  for (const auto &input : psbta.inputs) {
2101  UniValue input_univ(UniValue::VOBJ);
2102  UniValue missing(UniValue::VOBJ);
2103 
2104  input_univ.pushKV("has_utxo", input.has_utxo);
2105  input_univ.pushKV("is_final", input.is_final);
2106  input_univ.pushKV("next", PSBTRoleName(input.next));
2107 
2108  if (!input.missing_pubkeys.empty()) {
2109  UniValue missing_pubkeys_univ(UniValue::VARR);
2110  for (const CKeyID &pubkey : input.missing_pubkeys) {
2111  missing_pubkeys_univ.push_back(HexStr(pubkey));
2112  }
2113  missing.pushKV("pubkeys", missing_pubkeys_univ);
2114  }
2115  if (!input.missing_redeem_script.IsNull()) {
2116  missing.pushKV("redeemscript", HexStr(input.missing_redeem_script));
2117  }
2118  if (!input.missing_sigs.empty()) {
2119  UniValue missing_sigs_univ(UniValue::VARR);
2120  for (const CKeyID &pubkey : input.missing_sigs) {
2121  missing_sigs_univ.push_back(HexStr(pubkey));
2122  }
2123  missing.pushKV("signatures", missing_sigs_univ);
2124  }
2125  if (!missing.getKeys().empty()) {
2126  input_univ.pushKV("missing", missing);
2127  }
2128  inputs_result.push_back(input_univ);
2129  }
2130  if (!inputs_result.empty()) {
2131  result.pushKV("inputs", inputs_result);
2132  }
2133  if (psbta.estimated_vsize != std::nullopt) {
2134  result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
2135  }
2136  if (psbta.estimated_feerate != std::nullopt) {
2137  result.pushKV("estimated_feerate",
2138  ValueFromAmount(psbta.estimated_feerate->GetFeePerK()));
2139  }
2140  if (psbta.fee != std::nullopt) {
2141  result.pushKV("fee", ValueFromAmount(*psbta.fee));
2142  }
2143  result.pushKV("next", PSBTRoleName(psbta.next));
2144  if (!psbta.error.empty()) {
2145  result.pushKV("error", psbta.error);
2146  }
2147 
2148  return result;
2149 }
2150 
2152  // clang-format off
2153  static const CRPCCommand commands[] = {
2154  // category name actor (function) argNames
2155  // ------------------- ------------------------ ---------------------- ----------
2156  { "rawtransactions", "getrawtransaction", getrawtransaction, {"txid","verbose","blockhash"} },
2157  { "rawtransactions", "createrawtransaction", createrawtransaction, {"inputs","outputs","locktime"} },
2158  { "rawtransactions", "decoderawtransaction", decoderawtransaction, {"hexstring"} },
2159  { "rawtransactions", "decodescript", decodescript, {"hexstring"} },
2160  { "rawtransactions", "sendrawtransaction", sendrawtransaction, {"hexstring","maxfeerate"} },
2161  { "rawtransactions", "combinerawtransaction", combinerawtransaction, {"txs"} },
2162  { "rawtransactions", "signrawtransactionwithkey", signrawtransactionwithkey, {"hexstring","privkeys","prevtxs","sighashtype"} },
2163  { "rawtransactions", "testmempoolaccept", testmempoolaccept, {"rawtxs","maxfeerate"} },
2164  { "rawtransactions", "decodepsbt", decodepsbt, {"psbt"} },
2165  { "rawtransactions", "combinepsbt", combinepsbt, {"txs"} },
2166  { "rawtransactions", "finalizepsbt", finalizepsbt, {"psbt", "extract"} },
2167  { "rawtransactions", "createpsbt", createpsbt, {"inputs","outputs","locktime"} },
2168  { "rawtransactions", "converttopsbt", converttopsbt, {"hexstring","permitsigdata"} },
2169  { "rawtransactions", "utxoupdatepsbt", utxoupdatepsbt, {"psbt", "descriptors"} },
2170  { "rawtransactions", "joinpsbts", joinpsbts, {"txs"} },
2171  { "rawtransactions", "analyzepsbt", analyzepsbt, {"psbt"} },
2172  { "blockchain", "gettxoutproof", gettxoutproof, {"txids", "blockhash"} },
2173  { "blockchain", "verifytxoutproof", verifytxoutproof, {"proof"} },
2174  };
2175  // clang-format on
2176 
2177  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) {
2178  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
2179  }
2180 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
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:849
static UniValue decoderawtransaction(const Config &config, const JSONRPCRequest &request)
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:46
bool IsSpent() const
Definition: coins.h:46
static UniValue signrawtransactionwithkey(const Config &config, const JSONRPCRequest &request)
const util::Ref & context
Definition: request.h:42
NODISCARD bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:191
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:236
const std::string CURRENCY_UNIT
Definition: network.cpp:8
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.
std::array< uint8_t, 64 > sig
Definition: processor.cpp:248
static constexpr Amount zero()
Definition: amount.h:35
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &params)
Functions for disk access for blocks.
Definition: blockdb.cpp:33
Bitcoin RPC command dispatcher.
Definition: server.h:198
int64_t GetBlockTime() const
Definition: blockindex.h:160
CScript scriptPubKey
Definition: transaction.h:144
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:166
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.
static Amount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:562
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:45
Required arg.
UniValue utxoupdatepsbt(const Config &config, const JSONRPCRequest &request)
uint32_t getRawSigHashType() const
Definition: sighashtype.h:83
A UTXO entry.
Definition: coins.h:27
Definition: block.h:62
CChain & ChainActive()
Definition: validation.cpp:73
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:1201
static UniValue getrawtransaction(const Config &config, const JSONRPCRequest &request)
std::vector< PSBTInputAnalysis > inputs
More information about the individual inputs of the transaction.
Definition: psbt.h:40
BlockStatus nStatus
Verification status of this block. See enum BlockStatus.
Definition: blockindex.h:76
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:178
transaction was missing some of its inputs
std::string str() const
Definition: streams.h:270
bool hasData() const
Definition: blockstatus.h:54
std::string SighashToStr(uint8_t sighash_type)
Definition: core_write.cpp:90
#define ARRAYLEN(array)
Utilities for converting data from/to strings.
Definition: strencodings.h:19
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:339
Definition: amount.h:17
value_type * data()
Definition: streams.h:297
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:42
std::string EncodeBase64(const uint8_t *pch, size_t len)
static UniValue createrawtransaction(const Config &config, const JSONRPCRequest &request)
std::optional< CFeeRate > estimated_feerate
Estimated feerate (fee / weight) of the transaction.
Definition: psbt.h:36
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:32
const std::string & get_str() const
static std::string WriteHDKeypath(std::vector< uint32_t > &keypath)
bool isNum() const
Definition: univalue.h:94
const UniValue & get_array() const
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
std::vector< CTxOut > vout
Definition: transaction.h:300
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
bool isStr() const
Definition: univalue.h:93
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
A version of CTransaction with the PSBT format.
Definition: psbt.h:335
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:196
CTxMemPool & EnsureMemPool(const util::Ref &context)
Definition: blockchain.cpp:62
A signature creator for transactions.
Definition: sign.h:38
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:120
const std::vector< std::string > & getKeys() const
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:58
static UniValue decodescript(const Config &config, const JSONRPCRequest &request)
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:264
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:316
std::optional< size_t > estimated_vsize
Estimated weight of the transaction.
Definition: psbt.h:34
CScript redeem_script
Definition: psbt.h:45
bool IsNull() const
Definition: uint256.h:26
virtual const CChainParams & GetChainParams() const =0
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
static UniValue sendrawtransaction(const Config &config, const JSONRPCRequest &request)
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
bool IsNull() const
Definition: transaction.h:164
CChainState & ChainstateActive()
Definition: validation.cpp:67
std::vector< CTxIn > vin
Definition: transaction.h:299
CMutableTransaction ConstructTransaction(const CChainParams &params, const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime)
Create a transaction from univalue parameters.
A structure for PSBTs which contains per output information.
Definition: psbt.h:233
General error during transaction or block submission.
Definition: protocol.h:52
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
CTxOut utxo
Definition: psbt.h:44
std::vector< PSBTOutput > outputs
Definition: psbt.h:338
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:235
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
Special type that is a STR with only hex chars.
#define LOCK2(cs1, cs2)
Definition: sync.h:233
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:143
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
bool GetTransaction(const TxId &txid, CTransactionRef &txOut, const Consensus::Params &params, BlockHash &hashBlock, const CBlockIndex *const block_index)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Definition: validation.cpp:789
Used to create a Merkle proof (usually from a subset of transactions), which consists of a block head...
Definition: merkleblock.h:159
static UniValue testmempoolaccept(const Config &config, const JSONRPCRequest &request)
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:51
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Definition: config.h:19
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:107
size_type size() const
Definition: streams.h:279
uint256 hashMerkleRoot
Definition: block.h:27
Abstract view on the open txout dataset.
Definition: coins.h:148
UniValue params
Definition: request.h:37
An input of a transaction.
Definition: transaction.h:67
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:316
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
static const CFeeRate DEFAULT_MAX_RAW_TX_FEE_RATE
Maximum fee rate for sendrawtransaction and testmempoolaccept RPC calls.
Definition: transaction.h:24
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:21
static UniValue verifytxoutproof(const Config &config, const JSONRPCRequest &request)
const SigningProvider & DUMMY_SIGNING_PROVIDER
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:190
Fast randomness source.
Definition: random.h:111
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:47
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:48
Fillable signing provider that keeps keys in an address->secret map.
static std::string GetAllOutputTypes()
bool empty() const
Definition: univalue.h:78
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
const char * GetTxnOutputType(txnouttype t)
Get the name of a txnouttype as a C string, or nullptr if unknown.
Definition: standard.cpp:23
Result GetResult() const
Definition: validation.h:119
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
A structure for PSBTs which contain per-input information.
Definition: psbt.h:43
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
An output of a transaction.
Definition: transaction.h:141
int get_int() const
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:176
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:334
Invalid address or key.
Definition: protocol.h:42
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, SigHashType sighash, SignatureData *out_sigdata, bool use_dummy)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
Definition: psbt.cpp:198
Parameters that influence chain consensus.
Definition: params.h:59
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
bool isNull() const
Definition: univalue.h:89
std::vector< PSBTInput > inputs
Definition: psbt.h:337
Special numeric to denote unix epoch time.
void RegisterRawTransactionRPCCommands(CRPCTable &t)
Register raw transaction RPC commands.
Optional arg that is a named argument and has a default value of null.
static uint32_t ReadBE32(const uint8_t *ptr)
Definition: common.h:50
UniValue joinpsbts(const Config &config, const JSONRPCRequest &request)
static UniValue finalizepsbt(const Config &config, const JSONRPCRequest &request)
NodeContext & EnsureNodeContext(const util::Ref &context)
Definition: blockchain.cpp:55
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:99
SigHashType sighash_type
Definition: psbt.h:50
CScript scriptSig
Definition: transaction.h:70
Special type that is a NUM or [NUM,NUM].
#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:230
std::vector< CTransactionRef > vtx
Definition: block.h:65
static UniValue combinerawtransaction(const Config &config, const JSONRPCRequest &request)
const_iterator end() const
Definition: streams.h:277
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:468
static void TxToJSON(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry)
const_iterator begin() const
Definition: streams.h:275
static UniValue converttopsbt(const Config &config, const JSONRPCRequest &request)
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
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:274
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
Definition: server.cpp:559
A TxId is the identifier of a transaction.
Definition: txid.h:14
uint32_t GetHeight() const
Definition: coins.h:44
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
CTxOut & GetTxOut()
Definition: coins.h:48
CScript redeem_script
Definition: psbt.h:234
bool empty() const
Definition: prevector.h:386
UniValue analyzepsbt(const Config &config, const JSONRPCRequest &request)
A mutable version of CTransaction.
Definition: transaction.h:297
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:330
Special type representing a floating point amount (can be either NUM or STR)
CBlockIndex * LookupBlockIndex(const BlockHash &hash)
Definition: validation.cpp:140
std::string GetHex() const
Definition: uint256.cpp:16
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:172
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
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:88
bool IsInvalid() const
Definition: validation.h:117
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:197
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:193
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:831
std::string error
Error message.
Definition: psbt.h:44
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
Definition: core_write.cpp:220
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:310
static UniValue gettxoutproof(const Config &config, const JSONRPCRequest &request)
size_t size() const
Definition: univalue.h:80
An encapsulated secp256k1 private key.
Definition: key.h:25
CScript final_script_sig
Definition: psbt.h:46
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:211
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:286
Special dictionary with keys that are not literals.
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:80
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:204
std::optional< CMutableTransaction > tx
Definition: psbt.h:336
static UniValue decodepsbt(const Config &config, const JSONRPCRequest &request)
std::string GetRejectReason() const
Definition: validation.h:120
std::string PSBTRoleName(const PSBTRole role)
Definition: psbt.cpp:299
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:49
static UniValue combinepsbt(const Config &config, const JSONRPCRequest &request)
COutPoint prevout
Definition: transaction.h:69
TransactionError BroadcastTransaction(NodeContext &node, const Config &config, const CTransactionRef tx, std::string &err_string, const Amount 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:20
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOpCount, unsigned int bytes_per_sigop)
Compute the virtual transaction size (size, or more if sigops are too dense).
Definition: policy.cpp:161
void clear()
Definition: script.h:576
static UniValue createpsbt(const Config &config, const JSONRPCRequest &request)
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:893
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
bool AcceptToMemoryPool(const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, bool bypass_limits, const Amount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool
Definition: validation.cpp:776
Amount nValue
Definition: transaction.h:143
std::optional< Amount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:38
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:54
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:339
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:545
Error parsing or validating structure in raw format.
Definition: protocol.h:50
std::string FormatMoney(const Amount amt)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
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:21
Special type to denote elision (...)
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:87
Signature hash type wrapper class.
Definition: sighashtype.h:37
UniValue ValueFromAmount(const Amount &amount)
Definition: core_write.cpp:20
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:25
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:281