Bitcoin ABC  0.26.3
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 <chain.h>
7 #include <chainparams.h>
8 #include <coins.h>
9 #include <config.h>
10 #include <consensus/amount.h>
11 #include <consensus/validation.h>
12 #include <core_io.h>
13 #include <index/txindex.h>
14 #include <key_io.h>
15 #include <node/blockstorage.h>
16 #include <node/coin.h>
17 #include <node/context.h>
18 #include <node/psbt.h>
19 #include <node/transaction.h>
20 #include <policy/packages.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/server_util.h>
29 #include <rpc/util.h>
30 #include <script/script.h>
31 #include <script/sign.h>
32 #include <script/signingprovider.h>
33 #include <script/standard.h>
34 #include <txmempool.h>
35 #include <uint256.h>
36 #include <util/bip32.h>
37 #include <util/check.h>
38 #include <util/error.h>
39 #include <util/moneystr.h>
40 #include <util/strencodings.h>
41 #include <util/string.h>
42 #include <validation.h>
43 #include <validationinterface.h>
44 
45 #include <cstdint>
46 #include <numeric>
47 
48 #include <univalue.h>
49 
50 using node::AnalyzePSBT;
53 using node::FindCoins;
55 using node::NodeContext;
56 using node::PSBTAnalysis;
58 
59 static void TxToJSON(const CTransaction &tx, const BlockHash &hashBlock,
60  UniValue &entry, CChainState &active_chainstate) {
61  // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
62  //
63  // Blockchain contextual information (confirmations and blocktime) is not
64  // available to code in bitcoin-common, so we query them here and push the
65  // data into the returned UniValue.
66  TxToUniv(tx, BlockHash(), entry, true, RPCSerializationFlags());
67 
68  if (!hashBlock.IsNull()) {
69  LOCK(cs_main);
70 
71  entry.pushKV("blockhash", hashBlock.GetHex());
72  const CBlockIndex *pindex =
73  active_chainstate.m_blockman.LookupBlockIndex(hashBlock);
74  if (pindex) {
75  if (active_chainstate.m_chain.Contains(pindex)) {
76  entry.pushKV("confirmations",
77  1 + active_chainstate.m_chain.Height() -
78  pindex->nHeight);
79  entry.pushKV("time", pindex->GetBlockTime());
80  entry.pushKV("blocktime", pindex->GetBlockTime());
81  } else {
82  entry.pushKV("confirmations", 0);
83  }
84  }
85  }
86 }
87 
89  return RPCHelpMan{
90  "getrawtransaction",
91  "\nReturn the raw transaction data.\n"
92  "\nBy default, this call only returns a transaction if it is in the "
93  "mempool. If -txindex is enabled\n"
94  "and no blockhash argument is passed, it will return the transaction "
95  "if it is in the mempool or any block.\n"
96  "If a blockhash argument is passed, it will return the transaction if\n"
97  "the specified block is available and the transaction is in that "
98  "block.\n"
99  "\nIf verbose is 'true', returns an Object with information about "
100  "'txid'.\n"
101  "If verbose is 'false' or omitted, returns a string that is "
102  "serialized, hex-encoded data for 'txid'.\n",
103  {
105  "The transaction id"},
106  {"verbose", RPCArg::Type::BOOL, /* default */ "false",
107  "If false, return a string, otherwise return a json object"},
108  {"blockhash", RPCArg::Type::STR_HEX,
110  "The block in which to look for the transaction"},
111  },
112  {
113  RPCResult{"if verbose is not set or set to false",
114  RPCResult::Type::STR, "data",
115  "The serialized, hex-encoded data for 'txid'"},
116  RPCResult{
117  "if verbose is set to true",
119  "",
120  "",
121  {
122  {RPCResult::Type::BOOL, "in_active_chain",
123  "Whether specified block is in the active chain or not "
124  "(only present with explicit \"blockhash\" argument)"},
125  {RPCResult::Type::STR_HEX, "hex",
126  "The serialized, hex-encoded data for 'txid'"},
127  {RPCResult::Type::STR_HEX, "txid",
128  "The transaction id (same as provided)"},
129  {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
130  {RPCResult::Type::NUM, "size",
131  "The serialized transaction size"},
132  {RPCResult::Type::NUM, "version", "The version"},
133  {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
135  "vin",
136  "",
137  {
139  "",
140  "",
141  {
142  {RPCResult::Type::STR_HEX, "txid",
143  "The transaction id"},
144  {RPCResult::Type::STR, "vout", ""},
146  "scriptSig",
147  "The script",
148  {
149  {RPCResult::Type::STR, "asm", "asm"},
150  {RPCResult::Type::STR_HEX, "hex", "hex"},
151  }},
152  {RPCResult::Type::NUM, "sequence",
153  "The script sequence number"},
154  }},
155  }},
157  "vout",
158  "",
159  {
161  "",
162  "",
163  {
164  {RPCResult::Type::NUM, "value",
165  "The value in " + Currency::get().ticker},
166  {RPCResult::Type::NUM, "n", "index"},
168  "scriptPubKey",
169  "",
170  {
171  {RPCResult::Type::STR, "asm", "the asm"},
172  {RPCResult::Type::STR, "hex", "the hex"},
173  {RPCResult::Type::NUM, "reqSigs",
174  "The required sigs"},
175  {RPCResult::Type::STR, "type",
176  "The type, eg 'pubkeyhash'"},
178  "addresses",
179  "",
180  {
181  {RPCResult::Type::STR, "address",
182  "bitcoin address"},
183  }},
184  }},
185  }},
186  }},
187  {RPCResult::Type::STR_HEX, "blockhash", "the block hash"},
188  {RPCResult::Type::NUM, "confirmations",
189  "The confirmations"},
190  {RPCResult::Type::NUM_TIME, "blocktime",
191  "The block time expressed in " + UNIX_EPOCH_TIME},
192  {RPCResult::Type::NUM, "time", "Same as \"blocktime\""},
193  }},
194  },
195  RPCExamples{HelpExampleCli("getrawtransaction", "\"mytxid\"") +
196  HelpExampleCli("getrawtransaction", "\"mytxid\" true") +
197  HelpExampleRpc("getrawtransaction", "\"mytxid\", true") +
198  HelpExampleCli("getrawtransaction",
199  "\"mytxid\" false \"myblockhash\"") +
200  HelpExampleCli("getrawtransaction",
201  "\"mytxid\" true \"myblockhash\"")},
202  [&](const RPCHelpMan &self, const Config &config,
203  const JSONRPCRequest &request) -> UniValue {
204  const NodeContext &node = EnsureAnyNodeContext(request.context);
206 
207  bool in_active_chain = true;
208  TxId txid = TxId(ParseHashV(request.params[0], "parameter 1"));
209  const CBlockIndex *blockindex = nullptr;
210 
211  const CChainParams &params = config.GetChainParams();
212  if (txid == params.GenesisBlock().hashMerkleRoot) {
213  // Special exception for the genesis block coinbase transaction
214  throw JSONRPCError(
216  "The genesis block coinbase is not considered an "
217  "ordinary transaction and cannot be retrieved");
218  }
219 
220  // Accept either a bool (true) or a num (>=1) to indicate verbose
221  // output.
222  bool fVerbose = false;
223  if (!request.params[1].isNull()) {
224  fVerbose = request.params[1].isNum()
225  ? (request.params[1].get_int() != 0)
226  : request.params[1].get_bool();
227  }
228 
229  if (!request.params[2].isNull()) {
230  LOCK(cs_main);
231 
232  BlockHash blockhash(
233  ParseHashV(request.params[2], "parameter 3"));
234  blockindex = chainman.m_blockman.LookupBlockIndex(blockhash);
235  if (!blockindex) {
237  "Block hash not found");
238  }
239  in_active_chain = chainman.ActiveChain().Contains(blockindex);
240  }
241 
242  bool f_txindex_ready = false;
243  if (g_txindex && !blockindex) {
244  f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
245  }
246 
247  BlockHash hash_block;
248  const CTransactionRef tx =
249  GetTransaction(blockindex, node.mempool.get(), txid,
250  params.GetConsensus(), hash_block);
251  if (!tx) {
252  std::string errmsg;
253  if (blockindex) {
254  if (WITH_LOCK(::cs_main,
255  return !blockindex->nStatus.hasData())) {
257  "Block not available");
258  }
259  errmsg = "No such transaction found in the provided block";
260  } else if (!g_txindex) {
261  errmsg =
262  "No such mempool transaction. Use -txindex or provide "
263  "a block hash to enable blockchain transaction queries";
264  } else if (!f_txindex_ready) {
265  errmsg = "No such mempool transaction. Blockchain "
266  "transactions are still in the process of being "
267  "indexed";
268  } else {
269  errmsg = "No such mempool or blockchain transaction";
270  }
271  throw JSONRPCError(
273  errmsg + ". Use gettransaction for wallet transactions.");
274  }
275 
276  if (!fVerbose) {
277  return EncodeHexTx(*tx, RPCSerializationFlags());
278  }
279 
280  UniValue result(UniValue::VOBJ);
281  if (blockindex) {
282  result.pushKV("in_active_chain", in_active_chain);
283  }
284  TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
285  return result;
286  },
287  };
288 }
289 
291  return RPCHelpMan{
292  "createrawtransaction",
293  "Create a transaction spending the given inputs and creating new "
294  "outputs.\n"
295  "Outputs can be addresses or data.\n"
296  "Returns hex-encoded raw transaction.\n"
297  "Note that the transaction's inputs are not signed, and\n"
298  "it is not stored in the wallet or transmitted to the network.\n",
299  {
300  {
301  "inputs",
304  "The inputs",
305  {
306  {
307  "",
310  "",
311  {
312  {"txid", RPCArg::Type::STR_HEX,
313  RPCArg::Optional::NO, "The transaction id"},
315  "The output number"},
316  {"sequence", RPCArg::Type::NUM, /* default */
317  "depends on the value of the 'locktime' argument",
318  "The sequence number"},
319  },
320  },
321  },
322  },
323  {
324  "outputs",
327  "The outputs (key-value pairs), where none of "
328  "the keys are duplicated.\n"
329  "That is, each address can only appear once and there can only "
330  "be one 'data' object.\n"
331  "For compatibility reasons, a dictionary, which holds the "
332  "key-value pairs directly, is also\n"
333  " accepted as second parameter.",
334  {
335  {
336  "",
339  "",
340  {
341  {"address", RPCArg::Type::AMOUNT,
343  "A key-value pair. The key (string) is the "
344  "bitcoin address, the value (float or string) is "
345  "the amount in " +
347  },
348  },
349  {
350  "",
353  "",
354  {
355  {"data", RPCArg::Type::STR_HEX,
357  "A key-value pair. The key must be \"data\", the "
358  "value is hex-encoded data"},
359  },
360  },
361  },
362  },
363  {"locktime", RPCArg::Type::NUM, /* default */ "0",
364  "Raw locktime. Non-0 value also locktime-activates inputs"},
365  },
366  RPCResult{RPCResult::Type::STR_HEX, "transaction",
367  "hex string of the transaction"},
368  RPCExamples{
369  HelpExampleCli("createrawtransaction",
370  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
371  "\" \"[{\\\"address\\\":10000.00}]\"") +
372  HelpExampleCli("createrawtransaction",
373  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
374  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
375  HelpExampleRpc("createrawtransaction",
376  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
377  "\", \"[{\\\"address\\\":10000.00}]\"") +
378  HelpExampleRpc("createrawtransaction",
379  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
380  "\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
381  [&](const RPCHelpMan &self, const Config &config,
382  const JSONRPCRequest &request) -> UniValue {
383  RPCTypeCheck(request.params,
384  {UniValue::VARR,
385  UniValueType(), // ARR or OBJ, checked later
386  UniValue::VNUM},
387  true);
388 
389  CMutableTransaction rawTx =
390  ConstructTransaction(config.GetChainParams(), request.params[0],
391  request.params[1], request.params[2]);
392 
393  return EncodeHexTx(CTransaction(rawTx));
394  },
395  };
396 }
397 
399  return RPCHelpMan{
400  "decoderawtransaction",
401  "Return a JSON object representing the serialized, hex-encoded "
402  "transaction.\n",
403  {
405  "The transaction hex string"},
406  },
407  RPCResult{
409  "",
410  "",
411  {
412  {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
413  {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
414  {RPCResult::Type::NUM, "size", "The transaction size"},
415  {RPCResult::Type::NUM, "version", "The version"},
416  {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
418  "vin",
419  "",
420  {
422  "",
423  "",
424  {
425  {RPCResult::Type::STR_HEX, "txid",
426  "The transaction id"},
427  {RPCResult::Type::NUM, "vout", "The output number"},
429  "scriptSig",
430  "The script",
431  {
432  {RPCResult::Type::STR, "asm", "asm"},
433  {RPCResult::Type::STR_HEX, "hex", "hex"},
434  }},
435  {RPCResult::Type::NUM, "sequence",
436  "The script sequence number"},
437  }},
438  }},
440  "vout",
441  "",
442  {
444  "",
445  "",
446  {
447  {RPCResult::Type::NUM, "value",
448  "The value in " + Currency::get().ticker},
449  {RPCResult::Type::NUM, "n", "index"},
451  "scriptPubKey",
452  "",
453  {
454  {RPCResult::Type::STR, "asm", "the asm"},
455  {RPCResult::Type::STR_HEX, "hex", "the hex"},
456  {RPCResult::Type::NUM, "reqSigs",
457  "The required sigs"},
458  {RPCResult::Type::STR, "type",
459  "The type, eg 'pubkeyhash'"},
461  "addresses",
462  "",
463  {
464  {RPCResult::Type::STR, "address",
465  "bitcoin address"},
466  }},
467  }},
468  }},
469  }},
470  }},
471  RPCExamples{HelpExampleCli("decoderawtransaction", "\"hexstring\"") +
472  HelpExampleRpc("decoderawtransaction", "\"hexstring\"")},
473  [&](const RPCHelpMan &self, const Config &config,
474  const JSONRPCRequest &request) -> UniValue {
475  RPCTypeCheck(request.params, {UniValue::VSTR});
476 
478 
479  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
481  "TX decode failed");
482  }
483 
484  UniValue result(UniValue::VOBJ);
485  TxToUniv(CTransaction(std::move(mtx)), BlockHash(), result, false);
486 
487  return result;
488  },
489  };
490 }
491 
493  return RPCHelpMan{
494  "decodescript",
495  "Decode a hex-encoded script.\n",
496  {
498  "the hex-encoded script"},
499  },
500  RPCResult{
502  "",
503  "",
504  {
505  {RPCResult::Type::STR, "asm", "Script public key"},
506  {RPCResult::Type::STR, "type",
507  "The output type (e.g. " + GetAllOutputTypes() + ")"},
508  {RPCResult::Type::NUM, "reqSigs", "The required signatures"},
510  "addresses",
511  "",
512  {
513  {RPCResult::Type::STR, "address", "bitcoin address"},
514  }},
515  {RPCResult::Type::STR, "p2sh",
516  "address of P2SH script wrapping this redeem script (not "
517  "returned if the script is already a P2SH)"},
518  }},
519  RPCExamples{HelpExampleCli("decodescript", "\"hexstring\"") +
520  HelpExampleRpc("decodescript", "\"hexstring\"")},
521  [&](const RPCHelpMan &self, const Config &config,
522  const JSONRPCRequest &request) -> UniValue {
523  RPCTypeCheck(request.params, {UniValue::VSTR});
524 
526  CScript script;
527  if (request.params[0].get_str().size() > 0) {
528  std::vector<uint8_t> scriptData(
529  ParseHexV(request.params[0], "argument"));
530  script = CScript(scriptData.begin(), scriptData.end());
531  } else {
532  // Empty scripts are valid.
533  }
534 
535  ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false);
536 
537  UniValue type;
538  type = find_value(r, "type");
539 
540  if (type.isStr() && type.get_str() != "scripthash") {
541  // P2SH cannot be wrapped in a P2SH. If this script is already a
542  // P2SH, don't return the address for a P2SH of the P2SH.
543  r.pushKV("p2sh", EncodeDestination(ScriptHash(script), config));
544  }
545 
546  return r;
547  },
548  };
549 }
550 
552  return RPCHelpMan{
553  "combinerawtransaction",
554  "Combine multiple partially signed transactions into one "
555  "transaction.\n"
556  "The combined transaction may be another partially signed transaction "
557  "or a \n"
558  "fully signed transaction.",
559  {
560  {
561  "txs",
564  "The hex strings of partially signed "
565  "transactions",
566  {
567  {"hexstring", RPCArg::Type::STR_HEX,
569  "A hex-encoded raw transaction"},
570  },
571  },
572  },
574  "The hex-encoded raw transaction with signature(s)"},
575  RPCExamples{HelpExampleCli("combinerawtransaction",
576  R"('["myhex1", "myhex2", "myhex3"]')")},
577  [&](const RPCHelpMan &self, const Config &config,
578  const JSONRPCRequest &request) -> UniValue {
579  UniValue txs = request.params[0].get_array();
580  std::vector<CMutableTransaction> txVariants(txs.size());
581 
582  for (unsigned int idx = 0; idx < txs.size(); idx++) {
583  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
584  throw JSONRPCError(
586  strprintf("TX decode failed for tx %d", idx));
587  }
588  }
589 
590  if (txVariants.empty()) {
592  "Missing transactions");
593  }
594 
595  // mergedTx will end up with all the signatures; it
596  // starts as a clone of the rawtx:
597  CMutableTransaction mergedTx(txVariants[0]);
598 
599  // Fetch previous transactions (inputs):
600  CCoinsView viewDummy;
601  CCoinsViewCache view(&viewDummy);
602  {
603  NodeContext &node = EnsureAnyNodeContext(request.context);
604  const CTxMemPool &mempool = EnsureMemPool(node);
606  LOCK2(cs_main, mempool.cs);
607  CCoinsViewCache &viewChain =
608  chainman.ActiveChainstate().CoinsTip();
609  CCoinsViewMemPool viewMempool(&viewChain, mempool);
610  // temporarily switch cache backend to db+mempool view
611  view.SetBackend(viewMempool);
612 
613  for (const CTxIn &txin : mergedTx.vin) {
614  // Load entries from viewChain into view; can fail.
615  view.AccessCoin(txin.prevout);
616  }
617 
618  // switch back to avoid locking mempool for too long
619  view.SetBackend(viewDummy);
620  }
621 
622  // Use CTransaction for the constant parts of the
623  // transaction to avoid rehashing.
624  const CTransaction txConst(mergedTx);
625  // Sign what we can:
626  for (size_t i = 0; i < mergedTx.vin.size(); i++) {
627  CTxIn &txin = mergedTx.vin[i];
628  const Coin &coin = view.AccessCoin(txin.prevout);
629  if (coin.IsSpent()) {
631  "Input not found or already spent");
632  }
633  SignatureData sigdata;
634 
635  const CTxOut &txout = coin.GetTxOut();
636 
637  // ... and merge in other signatures:
638  for (const CMutableTransaction &txv : txVariants) {
639  if (txv.vin.size() > i) {
640  sigdata.MergeSignatureData(
641  DataFromTransaction(txv, i, txout));
642  }
643  }
646  &mergedTx, i, txout.nValue),
647  txout.scriptPubKey, sigdata);
648 
649  UpdateInput(txin, sigdata);
650  }
651 
652  return EncodeHexTx(CTransaction(mergedTx));
653  },
654  };
655 }
656 
658  return RPCHelpMan{
659  "signrawtransactionwithkey",
660  "Sign inputs for raw transaction (serialized, hex-encoded).\n"
661  "The second argument is an array of base58-encoded private\n"
662  "keys that will be the only keys used to sign the transaction.\n"
663  "The third optional argument (may be null) is an array of previous "
664  "transaction outputs that\n"
665  "this transaction depends on but may not yet be in the block chain.\n",
666  {
668  "The transaction hex string"},
669  {
670  "privkeys",
673  "The base58-encoded private keys for signing",
674  {
676  "private key in base58-encoding"},
677  },
678  },
679  {
680  "prevtxs",
683  "The previous dependent transaction outputs",
684  {
685  {
686  "",
689  "",
690  {
691  {"txid", RPCArg::Type::STR_HEX,
692  RPCArg::Optional::NO, "The transaction id"},
694  "The output number"},
695  {"scriptPubKey", RPCArg::Type::STR_HEX,
696  RPCArg::Optional::NO, "script key"},
697  {"redeemScript", RPCArg::Type::STR_HEX,
699  "(required for P2SH) redeem script"},
700  {"amount", RPCArg::Type::AMOUNT,
701  RPCArg::Optional::NO, "The amount spent"},
702  },
703  },
704  },
705  },
706  {"sighashtype", RPCArg::Type::STR, /* default */ "ALL|FORKID",
707  "The signature hash type. Must be one of:\n"
708  " \"ALL|FORKID\"\n"
709  " \"NONE|FORKID\"\n"
710  " \"SINGLE|FORKID\"\n"
711  " \"ALL|FORKID|ANYONECANPAY\"\n"
712  " \"NONE|FORKID|ANYONECANPAY\"\n"
713  " \"SINGLE|FORKID|ANYONECANPAY\""},
714  },
715  RPCResult{
717  "",
718  "",
719  {
720  {RPCResult::Type::STR_HEX, "hex",
721  "The hex-encoded raw transaction with signature(s)"},
722  {RPCResult::Type::BOOL, "complete",
723  "If the transaction has a complete set of signatures"},
725  "errors",
726  /* optional */ true,
727  "Script verification errors (if there are any)",
728  {
730  "",
731  "",
732  {
733  {RPCResult::Type::STR_HEX, "txid",
734  "The hash of the referenced, previous transaction"},
735  {RPCResult::Type::NUM, "vout",
736  "The index of the output to spent and used as "
737  "input"},
738  {RPCResult::Type::STR_HEX, "scriptSig",
739  "The hex-encoded signature script"},
740  {RPCResult::Type::NUM, "sequence",
741  "Script sequence number"},
742  {RPCResult::Type::STR, "error",
743  "Verification or signing error related to the "
744  "input"},
745  }},
746  }},
747  }},
748  RPCExamples{
749  HelpExampleCli("signrawtransactionwithkey",
750  "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"") +
751  HelpExampleRpc("signrawtransactionwithkey",
752  "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")},
753  [&](const RPCHelpMan &self, const Config &config,
754  const JSONRPCRequest &request) -> UniValue {
755  RPCTypeCheck(request.params,
756  {UniValue::VSTR, UniValue::VARR, UniValue::VARR,
757  UniValue::VSTR},
758  true);
759 
761  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
763  "TX decode failed");
764  }
765 
766  FillableSigningProvider keystore;
767  const UniValue &keys = request.params[1].get_array();
768  for (size_t idx = 0; idx < keys.size(); ++idx) {
769  UniValue k = keys[idx];
770  CKey key = DecodeSecret(k.get_str());
771  if (!key.IsValid()) {
773  "Invalid private key");
774  }
775  keystore.AddKey(key);
776  }
777 
778  // Fetch previous transactions (inputs):
779  std::map<COutPoint, Coin> coins;
780  for (const CTxIn &txin : mtx.vin) {
781  // Create empty map entry keyed by prevout.
782  coins[txin.prevout];
783  }
784  NodeContext &node = EnsureAnyNodeContext(request.context);
785  FindCoins(node, coins);
786 
787  // Parse the prevtxs array
788  ParsePrevouts(request.params[2], &keystore, coins);
789 
790  UniValue result(UniValue::VOBJ);
791  SignTransaction(mtx, &keystore, coins, request.params[3], result);
792  return result;
793  },
794  };
795 }
796 
798  return RPCHelpMan{
799  "sendrawtransaction",
800  "Submits raw transaction (serialized, hex-encoded) to local node and "
801  "network.\n"
802  "\nAlso see createrawtransaction and "
803  "signrawtransactionwithkey calls.\n",
804  {
806  "The hex string of the raw transaction"},
807  {"maxfeerate", RPCArg::Type::AMOUNT,
808  /* default */
810  "Reject transactions whose fee rate is higher than the specified "
811  "value, expressed in " +
813  "/kB\nSet to 0 to accept any fee rate.\n"},
814  },
815  RPCResult{RPCResult::Type::STR_HEX, "", "The transaction hash in hex"},
816  RPCExamples{
817  "\nCreate a transaction\n" +
819  "createrawtransaction",
820  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
821  "\"{\\\"myaddress\\\":10000}\"") +
822  "Sign the transaction, and get back the hex\n" +
823  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
824  "\nSend the transaction (signed hex)\n" +
825  HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
826  "\nAs a JSON-RPC call\n" +
827  HelpExampleRpc("sendrawtransaction", "\"signedhex\"")},
828  [&](const RPCHelpMan &self, const Config &config,
829  const JSONRPCRequest &request) -> UniValue {
830  RPCTypeCheck(request.params,
831  {
832  UniValue::VSTR,
833  // VNUM or VSTR, checked inside AmountFromValue()
834  UniValueType(),
835  });
836 
837  // parse hex string from parameter
839  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
841  "TX decode failed");
842  }
843 
844  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
845 
846  const CFeeRate max_raw_tx_fee_rate =
847  request.params[1].isNull()
849  : CFeeRate(AmountFromValue(request.params[1]));
850 
851  int64_t virtual_size = GetVirtualTransactionSize(*tx);
852  Amount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
853 
854  std::string err_string;
856  NodeContext &node = EnsureAnyNodeContext(request.context);
858  node, config, tx, err_string, max_raw_tx_fee, /*relay*/ true,
859  /*wait_callback*/ true);
860  if (err != TransactionError::OK) {
861  throw JSONRPCTransactionError(err, err_string);
862  }
863 
864  return tx->GetHash().GetHex();
865  },
866  };
867 }
868 
870  return RPCHelpMan{
871  "testmempoolaccept",
872  "\nReturns result of mempool acceptance tests indicating if raw "
873  "transaction(s) (serialized, hex-encoded) would be accepted by "
874  "mempool.\n"
875  "\nIf multiple transactions are passed in, parents must come before "
876  "children and package policies apply: the transactions cannot conflict "
877  "with any mempool transactions or each other.\n"
878  "\nIf one transaction fails, other transactions may not be fully "
879  "validated (the 'allowed' key will be blank).\n"
880  "\nThe maximum number of transactions allowed is " +
882  ".\n"
883  "\nThis checks if transactions violate the consensus or policy "
884  "rules.\n"
885  "\nSee sendrawtransaction call.\n",
886  {
887  {
888  "rawtxs",
891  "An array of hex strings of raw transactions.",
892  {
894  ""},
895  },
896  },
897  {"maxfeerate", RPCArg::Type::AMOUNT,
898  /* default */
900  "Reject transactions whose fee rate is higher than the specified "
901  "value, expressed in " +
902  Currency::get().ticker + "/kB\n"},
903  },
904  RPCResult{
906  "",
907  "The result of the mempool acceptance test for each raw "
908  "transaction in the input array.\n"
909  "Returns results for each transaction in the same order they were "
910  "passed in.\n"
911  "Transactions that cannot be fully validated due to failures in "
912  "other transactions will not contain an 'allowed' result.\n",
913  {
915  "",
916  "",
917  {
918  {RPCResult::Type::STR_HEX, "txid",
919  "The transaction hash in hex"},
920  {RPCResult::Type::STR, "package-error",
921  "Package validation error, if any (only possible if "
922  "rawtxs had more than 1 transaction)."},
923  {RPCResult::Type::BOOL, "allowed",
924  "Whether this tx would be accepted to the mempool and "
925  "pass client-specified maxfeerate. "
926  "If not present, the tx was not fully validated due to a "
927  "failure in another tx in the list."},
928  {RPCResult::Type::NUM, "size", "The transaction size"},
930  "fees",
931  "Transaction fees (only present if 'allowed' is true)",
932  {
934  "transaction fee in " + Currency::get().ticker},
935  }},
936  {RPCResult::Type::STR, "reject-reason",
937  "Rejection string (only present when 'allowed' is "
938  "false)"},
939  }},
940  }},
941  RPCExamples{
942  "\nCreate a transaction\n" +
944  "createrawtransaction",
945  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
946  "\"{\\\"myaddress\\\":10000}\"") +
947  "Sign the transaction, and get back the hex\n" +
948  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
949  "\nTest acceptance of the transaction (signed hex)\n" +
950  HelpExampleCli("testmempoolaccept", R"('["signedhex"]')") +
951  "\nAs a JSON-RPC call\n" +
952  HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")},
953  [&](const RPCHelpMan &self, const Config &config,
954  const JSONRPCRequest &request) -> UniValue {
955  RPCTypeCheck(request.params,
956  {
957  UniValue::VARR,
958  // VNUM or VSTR, checked inside AmountFromValue()
959  UniValueType(),
960  });
961  const UniValue raw_transactions = request.params[0].get_array();
962  if (raw_transactions.size() < 1 ||
963  raw_transactions.size() > MAX_PACKAGE_COUNT) {
965  "Array must contain between 1 and " +
967  " transactions.");
968  }
969 
970  const CFeeRate max_raw_tx_fee_rate =
971  request.params[1].isNull()
973  : CFeeRate(AmountFromValue(request.params[1]));
974 
975  std::vector<CTransactionRef> txns;
976  txns.reserve(raw_transactions.size());
977  for (const auto &rawtx : raw_transactions.getValues()) {
979  if (!DecodeHexTx(mtx, rawtx.get_str())) {
981  "TX decode failed: " + rawtx.get_str());
982  }
983  txns.emplace_back(MakeTransactionRef(std::move(mtx)));
984  }
985 
986  NodeContext &node = EnsureAnyNodeContext(request.context);
987  CTxMemPool &mempool = EnsureMemPool(node);
989  CChainState &chainstate = chainman.ActiveChainstate();
990  const PackageMempoolAcceptResult package_result = [&] {
991  LOCK(::cs_main);
992  if (txns.size() > 1) {
993  return ProcessNewPackage(config, chainstate, mempool, txns,
994  /* test_accept */ true);
995  }
997  txns[0]->GetId(),
998  chainman.ProcessTransaction(txns[0],
999  /* test_accept*/ true));
1000  }();
1001 
1002  UniValue rpc_result(UniValue::VARR);
1003  // We will check transaction fees while we iterate through txns in
1004  // order. If any transaction fee exceeds maxfeerate, we will leave
1005  // the rest of the validation results blank, because it doesn't make
1006  // sense to return a validation result for a transaction if its
1007  // ancestor(s) would not be submitted.
1008  bool exit_early{false};
1009  for (const auto &tx : txns) {
1010  UniValue result_inner(UniValue::VOBJ);
1011  result_inner.pushKV("txid", tx->GetId().GetHex());
1012  if (package_result.m_state.GetResult() ==
1014  result_inner.pushKV(
1015  "package-error",
1016  package_result.m_state.GetRejectReason());
1017  }
1018  auto it = package_result.m_tx_results.find(tx->GetId());
1019  if (exit_early || it == package_result.m_tx_results.end()) {
1020  // Validation unfinished. Just return the txid.
1021  rpc_result.push_back(result_inner);
1022  continue;
1023  }
1024  const auto &tx_result = it->second;
1025  // Package testmempoolaccept doesn't allow transactions to
1026  // already be in the mempool.
1027  CHECK_NONFATAL(tx_result.m_result_type !=
1029  if (tx_result.m_result_type ==
1031  const Amount fee = tx_result.m_base_fees.value();
1032  // Check that fee does not exceed maximum fee
1033  const int64_t virtual_size = tx_result.m_vsize.value();
1034  const Amount max_raw_tx_fee =
1035  max_raw_tx_fee_rate.GetFee(virtual_size);
1036  if (max_raw_tx_fee != Amount::zero() &&
1037  fee > max_raw_tx_fee) {
1038  result_inner.pushKV("allowed", false);
1039  result_inner.pushKV("reject-reason",
1040  "max-fee-exceeded");
1041  exit_early = true;
1042  } else {
1043  // Only return the fee and size if the transaction
1044  // would pass ATMP.
1045  // These can be used to calculate the feerate.
1046  result_inner.pushKV("allowed", true);
1047  result_inner.pushKV("size", virtual_size);
1048  UniValue fees(UniValue::VOBJ);
1049  fees.pushKV("base", fee);
1050  result_inner.pushKV("fees", fees);
1051  }
1052  } else {
1053  result_inner.pushKV("allowed", false);
1054  const TxValidationState state = tx_result.m_state;
1055  if (state.GetResult() ==
1057  result_inner.pushKV("reject-reason", "missing-inputs");
1058  } else {
1059  result_inner.pushKV("reject-reason",
1060  state.GetRejectReason());
1061  }
1062  }
1063  rpc_result.push_back(result_inner);
1064  }
1065  return rpc_result;
1066  },
1067  };
1068 }
1069 
1071  return RPCHelpMan{
1072  "decodepsbt",
1073  "Return a JSON object representing the serialized, base64-encoded "
1074  "partially signed Bitcoin transaction.\n",
1075  {
1077  "The PSBT base64 string"},
1078  },
1079  RPCResult{
1081  "",
1082  "",
1083  {
1085  "tx",
1086  "The decoded network-serialized unsigned transaction.",
1087  {
1089  "The layout is the same as the output of "
1090  "decoderawtransaction."},
1091  }},
1093  "unknown",
1094  "The unknown global fields",
1095  {
1096  {RPCResult::Type::STR_HEX, "key",
1097  "(key-value pair) An unknown key-value pair"},
1098  }},
1100  "inputs",
1101  "",
1102  {
1104  "",
1105  "",
1106  {
1108  "utxo",
1109  /* optional */ true,
1110  "Transaction output for UTXOs",
1111  {
1112  {RPCResult::Type::NUM, "amount",
1113  "The value in " + Currency::get().ticker},
1115  "scriptPubKey",
1116  "",
1117  {
1118  {RPCResult::Type::STR, "asm", "The asm"},
1119  {RPCResult::Type::STR_HEX, "hex",
1120  "The hex"},
1121  {RPCResult::Type::STR, "type",
1122  "The type, eg 'pubkeyhash'"},
1123  {RPCResult::Type::STR, "address",
1124  " Bitcoin address if there is one"},
1125  }},
1126  }},
1128  "partial_signatures",
1129  /* optional */ true,
1130  "",
1131  {
1132  {RPCResult::Type::STR, "pubkey",
1133  "The public key and signature that corresponds "
1134  "to it."},
1135  }},
1136  {RPCResult::Type::STR, "sighash", /* optional */ true,
1137  "The sighash type to be used"},
1139  "redeem_script",
1140  /* optional */ true,
1141  "",
1142  {
1143  {RPCResult::Type::STR, "asm", "The asm"},
1144  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1145  {RPCResult::Type::STR, "type",
1146  "The type, eg 'pubkeyhash'"},
1147  }},
1149  "bip32_derivs",
1150  /* optional */ true,
1151  "",
1152  {
1154  "pubkey",
1155  /* optional */ true,
1156  "The public key with the derivation path as "
1157  "the value.",
1158  {
1159  {RPCResult::Type::STR, "master_fingerprint",
1160  "The fingerprint of the master key"},
1161  {RPCResult::Type::STR, "path", "The path"},
1162  }},
1163  }},
1165  "final_scriptsig",
1166  /* optional */ true,
1167  "",
1168  {
1169  {RPCResult::Type::STR, "asm", "The asm"},
1170  {RPCResult::Type::STR, "hex", "The hex"},
1171  }},
1173  "unknown",
1174  "The unknown global fields",
1175  {
1176  {RPCResult::Type::STR_HEX, "key",
1177  "(key-value pair) An unknown key-value pair"},
1178  }},
1179  }},
1180  }},
1182  "outputs",
1183  "",
1184  {
1186  "",
1187  "",
1188  {
1190  "redeem_script",
1191  /* optional */ true,
1192  "",
1193  {
1194  {RPCResult::Type::STR, "asm", "The asm"},
1195  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1196  {RPCResult::Type::STR, "type",
1197  "The type, eg 'pubkeyhash'"},
1198  }},
1200  "bip32_derivs",
1201  /* optional */ true,
1202  "",
1203  {
1205  "",
1206  "",
1207  {
1208  {RPCResult::Type::STR, "pubkey",
1209  "The public key this path corresponds to"},
1210  {RPCResult::Type::STR, "master_fingerprint",
1211  "The fingerprint of the master key"},
1212  {RPCResult::Type::STR, "path", "The path"},
1213  }},
1214  }},
1216  "unknown",
1217  "The unknown global fields",
1218  {
1219  {RPCResult::Type::STR_HEX, "key",
1220  "(key-value pair) An unknown key-value pair"},
1221  }},
1222  }},
1223  }},
1224  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
1225  "The transaction fee paid if all UTXOs slots in the PSBT have "
1226  "been filled."},
1227  }},
1228  RPCExamples{HelpExampleCli("decodepsbt", "\"psbt\"")},
1229  [&](const RPCHelpMan &self, const Config &config,
1230  const JSONRPCRequest &request) -> UniValue {
1231  RPCTypeCheck(request.params, {UniValue::VSTR});
1232 
1233  // Unserialize the transactions
1235  std::string error;
1236  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1238  strprintf("TX decode failed %s", error));
1239  }
1240 
1241  UniValue result(UniValue::VOBJ);
1242 
1243  // Add the decoded tx
1244  UniValue tx_univ(UniValue::VOBJ);
1245  TxToUniv(CTransaction(*psbtx.tx), BlockHash(), tx_univ, false);
1246  result.pushKV("tx", tx_univ);
1247 
1248  // Unknown data
1249  if (psbtx.unknown.size() > 0) {
1250  UniValue unknowns(UniValue::VOBJ);
1251  for (auto entry : psbtx.unknown) {
1252  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1253  }
1254  result.pushKV("unknown", unknowns);
1255  }
1256 
1257  // inputs
1258  Amount total_in = Amount::zero();
1259  bool have_all_utxos = true;
1260  UniValue inputs(UniValue::VARR);
1261  for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
1262  const PSBTInput &input = psbtx.inputs[i];
1264  // UTXOs
1265  if (!input.utxo.IsNull()) {
1266  const CTxOut &txout = input.utxo;
1267 
1268  UniValue out(UniValue::VOBJ);
1269 
1270  out.pushKV("amount", txout.nValue);
1271  if (MoneyRange(txout.nValue) &&
1272  MoneyRange(total_in + txout.nValue)) {
1273  total_in += txout.nValue;
1274  } else {
1275  // Hack to just not show fee later
1276  have_all_utxos = false;
1277  }
1278 
1280  ScriptToUniv(txout.scriptPubKey, o, true);
1281  out.pushKV("scriptPubKey", o);
1282  in.pushKV("utxo", out);
1283  } else {
1284  have_all_utxos = false;
1285  }
1286 
1287  // Partial sigs
1288  if (!input.partial_sigs.empty()) {
1289  UniValue partial_sigs(UniValue::VOBJ);
1290  for (const auto &sig : input.partial_sigs) {
1291  partial_sigs.pushKV(HexStr(sig.second.first),
1292  HexStr(sig.second.second));
1293  }
1294  in.pushKV("partial_signatures", partial_sigs);
1295  }
1296 
1297  // Sighash
1298  uint8_t sighashbyte =
1299  input.sighash_type.getRawSigHashType() & 0xff;
1300  if (sighashbyte > 0) {
1301  in.pushKV("sighash", SighashToStr(sighashbyte));
1302  }
1303 
1304  // Redeem script
1305  if (!input.redeem_script.empty()) {
1307  ScriptToUniv(input.redeem_script, r, false);
1308  in.pushKV("redeem_script", r);
1309  }
1310 
1311  // keypaths
1312  if (!input.hd_keypaths.empty()) {
1313  UniValue keypaths(UniValue::VARR);
1314  for (auto entry : input.hd_keypaths) {
1315  UniValue keypath(UniValue::VOBJ);
1316  keypath.pushKV("pubkey", HexStr(entry.first));
1317 
1318  keypath.pushKV(
1319  "master_fingerprint",
1320  strprintf("%08x",
1321  ReadBE32(entry.second.fingerprint)));
1322  keypath.pushKV("path",
1323  WriteHDKeypath(entry.second.path));
1324  keypaths.push_back(keypath);
1325  }
1326  in.pushKV("bip32_derivs", keypaths);
1327  }
1328 
1329  // Final scriptSig
1330  if (!input.final_script_sig.empty()) {
1331  UniValue scriptsig(UniValue::VOBJ);
1332  scriptsig.pushKV(
1333  "asm", ScriptToAsmStr(input.final_script_sig, true));
1334  scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1335  in.pushKV("final_scriptSig", scriptsig);
1336  }
1337 
1338  // Unknown data
1339  if (input.unknown.size() > 0) {
1340  UniValue unknowns(UniValue::VOBJ);
1341  for (auto entry : input.unknown) {
1342  unknowns.pushKV(HexStr(entry.first),
1343  HexStr(entry.second));
1344  }
1345  in.pushKV("unknown", unknowns);
1346  }
1347 
1348  inputs.push_back(in);
1349  }
1350  result.pushKV("inputs", inputs);
1351 
1352  // outputs
1353  Amount output_value = Amount::zero();
1354  UniValue outputs(UniValue::VARR);
1355  for (size_t i = 0; i < psbtx.outputs.size(); ++i) {
1356  const PSBTOutput &output = psbtx.outputs[i];
1357  UniValue out(UniValue::VOBJ);
1358  // Redeem script
1359  if (!output.redeem_script.empty()) {
1361  ScriptToUniv(output.redeem_script, r, false);
1362  out.pushKV("redeem_script", r);
1363  }
1364 
1365  // keypaths
1366  if (!output.hd_keypaths.empty()) {
1367  UniValue keypaths(UniValue::VARR);
1368  for (auto entry : output.hd_keypaths) {
1369  UniValue keypath(UniValue::VOBJ);
1370  keypath.pushKV("pubkey", HexStr(entry.first));
1371  keypath.pushKV(
1372  "master_fingerprint",
1373  strprintf("%08x",
1374  ReadBE32(entry.second.fingerprint)));
1375  keypath.pushKV("path",
1376  WriteHDKeypath(entry.second.path));
1377  keypaths.push_back(keypath);
1378  }
1379  out.pushKV("bip32_derivs", keypaths);
1380  }
1381 
1382  // Unknown data
1383  if (output.unknown.size() > 0) {
1384  UniValue unknowns(UniValue::VOBJ);
1385  for (auto entry : output.unknown) {
1386  unknowns.pushKV(HexStr(entry.first),
1387  HexStr(entry.second));
1388  }
1389  out.pushKV("unknown", unknowns);
1390  }
1391 
1392  outputs.push_back(out);
1393 
1394  // Fee calculation
1395  if (MoneyRange(psbtx.tx->vout[i].nValue) &&
1396  MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
1397  output_value += psbtx.tx->vout[i].nValue;
1398  } else {
1399  // Hack to just not show fee later
1400  have_all_utxos = false;
1401  }
1402  }
1403  result.pushKV("outputs", outputs);
1404  if (have_all_utxos) {
1405  result.pushKV("fee", total_in - output_value);
1406  }
1407 
1408  return result;
1409  },
1410  };
1411 }
1412 
1414  return RPCHelpMan{
1415  "combinepsbt",
1416  "Combine multiple partially signed Bitcoin transactions into one "
1417  "transaction.\n"
1418  "Implements the Combiner role.\n",
1419  {
1420  {
1421  "txs",
1424  "The base64 strings of partially signed transactions",
1425  {
1427  "A base64 string of a PSBT"},
1428  },
1429  },
1430  },
1432  "The base64-encoded partially signed transaction"},
1434  "combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")},
1435  [&](const RPCHelpMan &self, const Config &config,
1436  const JSONRPCRequest &request) -> UniValue {
1437  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1438 
1439  // Unserialize the transactions
1440  std::vector<PartiallySignedTransaction> psbtxs;
1441  UniValue txs = request.params[0].get_array();
1442  if (txs.empty()) {
1444  "Parameter 'txs' cannot be empty");
1445  }
1446  for (size_t i = 0; i < txs.size(); ++i) {
1448  std::string error;
1449  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1451  strprintf("TX decode failed %s", error));
1452  }
1453  psbtxs.push_back(psbtx);
1454  }
1455 
1456  PartiallySignedTransaction merged_psbt;
1457  const TransactionError error = CombinePSBTs(merged_psbt, psbtxs);
1458  if (error != TransactionError::OK) {
1460  }
1461 
1463  ssTx << merged_psbt;
1464  return EncodeBase64(MakeUCharSpan(ssTx));
1465  },
1466  };
1467 }
1468 
1470  return RPCHelpMan{
1471  "finalizepsbt",
1472  "Finalize the inputs of a PSBT. If the transaction is fully signed, it "
1473  "will produce a\n"
1474  "network serialized transaction which can be broadcast with "
1475  "sendrawtransaction. Otherwise a PSBT will be\n"
1476  "created which has the final_scriptSigfields filled for inputs that "
1477  "are complete.\n"
1478  "Implements the Finalizer and Extractor roles.\n",
1479  {
1481  "A base64 string of a PSBT"},
1482  {"extract", RPCArg::Type::BOOL, /* default */ "true",
1483  "If true and the transaction is complete,\n"
1484  " extract and return the complete "
1485  "transaction in normal network serialization instead of the "
1486  "PSBT."},
1487  },
1489  "",
1490  "",
1491  {
1492  {RPCResult::Type::STR, "psbt",
1493  "The base64-encoded partially signed transaction if not "
1494  "extracted"},
1495  {RPCResult::Type::STR_HEX, "hex",
1496  "The hex-encoded network transaction if extracted"},
1497  {RPCResult::Type::BOOL, "complete",
1498  "If the transaction has a complete set of signatures"},
1499  }},
1500  RPCExamples{HelpExampleCli("finalizepsbt", "\"psbt\"")},
1501  [&](const RPCHelpMan &self, const Config &config,
1502  const JSONRPCRequest &request) -> UniValue {
1503  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL},
1504  true);
1505 
1506  // Unserialize the transactions
1508  std::string error;
1509  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1511  strprintf("TX decode failed %s", error));
1512  }
1513 
1514  bool extract =
1515  request.params[1].isNull() ||
1516  (!request.params[1].isNull() && request.params[1].get_bool());
1517 
1518  CMutableTransaction mtx;
1519  bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1520 
1521  UniValue result(UniValue::VOBJ);
1523  std::string result_str;
1524 
1525  if (complete && extract) {
1526  ssTx << mtx;
1527  result_str = HexStr(ssTx);
1528  result.pushKV("hex", result_str);
1529  } else {
1530  ssTx << psbtx;
1531  result_str = EncodeBase64(ssTx.str());
1532  result.pushKV("psbt", result_str);
1533  }
1534  result.pushKV("complete", complete);
1535 
1536  return result;
1537  },
1538  };
1539 }
1540 
1542  return RPCHelpMan{
1543  "createpsbt",
1544  "Creates a transaction in the Partially Signed Transaction format.\n"
1545  "Implements the Creator role.\n",
1546  {
1547  {
1548  "inputs",
1551  "The json objects",
1552  {
1553  {
1554  "",
1557  "",
1558  {
1559  {"txid", RPCArg::Type::STR_HEX,
1560  RPCArg::Optional::NO, "The transaction id"},
1562  "The output number"},
1563  {"sequence", RPCArg::Type::NUM, /* default */
1564  "depends on the value of the 'locktime' argument",
1565  "The sequence number"},
1566  },
1567  },
1568  },
1569  },
1570  {
1571  "outputs",
1574  "The outputs (key-value pairs), where none of "
1575  "the keys are duplicated.\n"
1576  "That is, each address can only appear once and there can only "
1577  "be one 'data' object.\n"
1578  "For compatibility reasons, a dictionary, which holds the "
1579  "key-value pairs directly, is also\n"
1580  " accepted as second parameter.",
1581  {
1582  {
1583  "",
1586  "",
1587  {
1588  {"address", RPCArg::Type::AMOUNT,
1590  "A key-value pair. The key (string) is the "
1591  "bitcoin address, the value (float or string) is "
1592  "the amount in " +
1593  Currency::get().ticker},
1594  },
1595  },
1596  {
1597  "",
1600  "",
1601  {
1602  {"data", RPCArg::Type::STR_HEX,
1604  "A key-value pair. The key must be \"data\", the "
1605  "value is hex-encoded data"},
1606  },
1607  },
1608  },
1609  },
1610  {"locktime", RPCArg::Type::NUM, /* default */ "0",
1611  "Raw locktime. Non-0 value also locktime-activates inputs"},
1612  },
1614  "The resulting raw transaction (base64-encoded string)"},
1616  "createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1617  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
1618  [&](const RPCHelpMan &self, const Config &config,
1619  const JSONRPCRequest &request) -> UniValue {
1620  RPCTypeCheck(request.params,
1621  {
1622  UniValue::VARR,
1623  UniValueType(), // ARR or OBJ, checked later
1624  UniValue::VNUM,
1625  },
1626  true);
1627 
1628  CMutableTransaction rawTx =
1629  ConstructTransaction(config.GetChainParams(), request.params[0],
1630  request.params[1], request.params[2]);
1631 
1632  // Make a blank psbt
1634  psbtx.tx = rawTx;
1635  for (size_t i = 0; i < rawTx.vin.size(); ++i) {
1636  psbtx.inputs.push_back(PSBTInput());
1637  }
1638  for (size_t i = 0; i < rawTx.vout.size(); ++i) {
1639  psbtx.outputs.push_back(PSBTOutput());
1640  }
1641 
1642  // Serialize the PSBT
1644  ssTx << psbtx;
1645 
1646  return EncodeBase64(MakeUCharSpan(ssTx));
1647  },
1648  };
1649 }
1650 
1652  return RPCHelpMan{
1653  "converttopsbt",
1654  "Converts a network serialized transaction to a PSBT. "
1655  "This should be used only with createrawtransaction and "
1656  "fundrawtransaction\n"
1657  "createpsbt and walletcreatefundedpsbt should be used for new "
1658  "applications.\n",
1659  {
1661  "The hex string of a raw transaction"},
1662  {"permitsigdata", RPCArg::Type::BOOL, /* default */ "false",
1663  "If true, any signatures in the input will be discarded and "
1664  "conversion.\n"
1665  " will continue. If false, RPC will "
1666  "fail if any signatures are present."},
1667  },
1669  "The resulting raw transaction (base64-encoded string)"},
1670  RPCExamples{
1671  "\nCreate a transaction\n" +
1672  HelpExampleCli("createrawtransaction",
1673  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1674  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1675  "\nConvert the transaction to a PSBT\n" +
1676  HelpExampleCli("converttopsbt", "\"rawtransaction\"")},
1677  [&](const RPCHelpMan &self, const Config &config,
1678  const JSONRPCRequest &request) -> UniValue {
1679  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL},
1680  true);
1681 
1682  // parse hex string from parameter
1684  bool permitsigdata = request.params[1].isNull()
1685  ? false
1686  : request.params[1].get_bool();
1687  if (!DecodeHexTx(tx, request.params[0].get_str())) {
1689  "TX decode failed");
1690  }
1691 
1692  // Remove all scriptSigs from inputs
1693  for (CTxIn &input : tx.vin) {
1694  if (!input.scriptSig.empty() && !permitsigdata) {
1696  "Inputs must not have scriptSigs");
1697  }
1698  input.scriptSig.clear();
1699  }
1700 
1701  // Make a blank psbt
1703  psbtx.tx = tx;
1704  for (size_t i = 0; i < tx.vin.size(); ++i) {
1705  psbtx.inputs.push_back(PSBTInput());
1706  }
1707  for (size_t i = 0; i < tx.vout.size(); ++i) {
1708  psbtx.outputs.push_back(PSBTOutput());
1709  }
1710 
1711  // Serialize the PSBT
1713  ssTx << psbtx;
1714 
1715  return EncodeBase64(MakeUCharSpan(ssTx));
1716  },
1717  };
1718 }
1719 
1721  return RPCHelpMan{
1722  "utxoupdatepsbt",
1723  "Updates all inputs and outputs in a PSBT with data from output "
1724  "descriptors, the UTXO set or the mempool.\n",
1725  {
1727  "A base64 string of a PSBT"},
1728  {"descriptors",
1731  "An array of either strings or objects",
1732  {
1734  "An output descriptor"},
1735  {"",
1738  "An object with an output descriptor and extra information",
1739  {
1741  "An output descriptor"},
1742  {"range", RPCArg::Type::RANGE, "1000",
1743  "Up to what index HD chains should be explored (either "
1744  "end or [begin,end])"},
1745  }},
1746  }},
1747  },
1749  "The base64-encoded partially signed transaction with inputs "
1750  "updated"},
1751  RPCExamples{HelpExampleCli("utxoupdatepsbt", "\"psbt\"")},
1752  [&](const RPCHelpMan &self, const Config &config,
1753  const JSONRPCRequest &request) -> UniValue {
1754  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR},
1755  true);
1756 
1757  // Unserialize the transactions
1759  std::string error;
1760  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1762  strprintf("TX decode failed %s", error));
1763  }
1764 
1765  // Parse descriptors, if any.
1766  FlatSigningProvider provider;
1767  if (!request.params[1].isNull()) {
1768  auto descs = request.params[1].get_array();
1769  for (size_t i = 0; i < descs.size(); ++i) {
1770  EvalDescriptorStringOrObject(descs[i], provider);
1771  }
1772  }
1773  // We don't actually need private keys further on; hide them as a
1774  // precaution.
1775  HidingSigningProvider public_provider(&provider, /* nosign */ true,
1776  /* nobip32derivs */ false);
1777 
1778  // Fetch previous transactions (inputs):
1779  CCoinsView viewDummy;
1780  CCoinsViewCache view(&viewDummy);
1781  {
1782  NodeContext &node = EnsureAnyNodeContext(request.context);
1783  const CTxMemPool &mempool = EnsureMemPool(node);
1784  ChainstateManager &chainman = EnsureChainman(node);
1785  LOCK2(cs_main, mempool.cs);
1786  CCoinsViewCache &viewChain =
1787  chainman.ActiveChainstate().CoinsTip();
1788  CCoinsViewMemPool viewMempool(&viewChain, mempool);
1789  // temporarily switch cache backend to db+mempool view
1790  view.SetBackend(viewMempool);
1791 
1792  for (const CTxIn &txin : psbtx.tx->vin) {
1793  // Load entries from viewChain into view; can fail.
1794  view.AccessCoin(txin.prevout);
1795  }
1796 
1797  // switch back to avoid locking mempool for too long
1798  view.SetBackend(viewDummy);
1799  }
1800 
1801  // Fill the inputs
1802  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
1803  PSBTInput &input = psbtx.inputs.at(i);
1804 
1805  if (!input.utxo.IsNull()) {
1806  continue;
1807  }
1808 
1809  // Update script/keypath information using descriptor data.
1810  // Note that SignPSBTInput does a lot more than just
1811  // constructing ECDSA signatures we don't actually care about
1812  // those here, in fact.
1813  SignPSBTInput(public_provider, psbtx, i,
1814  /* sighash_type */ SigHashType().withForkId());
1815  }
1816 
1817  // Update script/keypath information using descriptor data.
1818  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1819  UpdatePSBTOutput(public_provider, psbtx, i);
1820  }
1821 
1823  ssTx << psbtx;
1824  return EncodeBase64(MakeUCharSpan(ssTx));
1825  },
1826  };
1827 }
1828 
1830  return RPCHelpMan{
1831  "joinpsbts",
1832  "Joins multiple distinct PSBTs with different inputs and outputs "
1833  "into one PSBT with inputs and outputs from all of the PSBTs\n"
1834  "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1835  {{"txs",
1838  "The base64 strings of partially signed transactions",
1840  "A base64 string of a PSBT"}}}},
1842  "The base64-encoded partially signed transaction"},
1843  RPCExamples{HelpExampleCli("joinpsbts", "\"psbt\"")},
1844  [&](const RPCHelpMan &self, const Config &config,
1845  const JSONRPCRequest &request) -> UniValue {
1846  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1847 
1848  // Unserialize the transactions
1849  std::vector<PartiallySignedTransaction> psbtxs;
1850  UniValue txs = request.params[0].get_array();
1851 
1852  if (txs.size() <= 1) {
1853  throw JSONRPCError(
1855  "At least two PSBTs are required to join PSBTs.");
1856  }
1857 
1858  uint32_t best_version = 1;
1859  uint32_t best_locktime = 0xffffffff;
1860  for (size_t i = 0; i < txs.size(); ++i) {
1862  std::string error;
1863  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1865  strprintf("TX decode failed %s", error));
1866  }
1867  psbtxs.push_back(psbtx);
1868  // Choose the highest version number
1869  if (static_cast<uint32_t>(psbtx.tx->nVersion) > best_version) {
1870  best_version = static_cast<uint32_t>(psbtx.tx->nVersion);
1871  }
1872  // Choose the lowest lock time
1873  if (psbtx.tx->nLockTime < best_locktime) {
1874  best_locktime = psbtx.tx->nLockTime;
1875  }
1876  }
1877 
1878  // Create a blank psbt where everything will be added
1879  PartiallySignedTransaction merged_psbt;
1880  merged_psbt.tx = CMutableTransaction();
1881  merged_psbt.tx->nVersion = static_cast<int32_t>(best_version);
1882  merged_psbt.tx->nLockTime = best_locktime;
1883 
1884  // Merge
1885  for (auto &psbt : psbtxs) {
1886  for (size_t i = 0; i < psbt.tx->vin.size(); ++i) {
1887  if (!merged_psbt.AddInput(psbt.tx->vin[i],
1888  psbt.inputs[i])) {
1889  throw JSONRPCError(
1891  strprintf("Input %s:%d exists in multiple PSBTs",
1892  psbt.tx->vin[i]
1893  .prevout.GetTxId()
1894  .ToString()
1895  .c_str(),
1896  psbt.tx->vin[i].prevout.GetN()));
1897  }
1898  }
1899  for (size_t i = 0; i < psbt.tx->vout.size(); ++i) {
1900  merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1901  }
1902  merged_psbt.unknown.insert(psbt.unknown.begin(),
1903  psbt.unknown.end());
1904  }
1905 
1906  // Generate list of shuffled indices for shuffling inputs and
1907  // outputs of the merged PSBT
1908  std::vector<int> input_indices(merged_psbt.inputs.size());
1909  std::iota(input_indices.begin(), input_indices.end(), 0);
1910  std::vector<int> output_indices(merged_psbt.outputs.size());
1911  std::iota(output_indices.begin(), output_indices.end(), 0);
1912 
1913  // Shuffle input and output indices lists
1914  Shuffle(input_indices.begin(), input_indices.end(),
1915  FastRandomContext());
1916  Shuffle(output_indices.begin(), output_indices.end(),
1917  FastRandomContext());
1918 
1919  PartiallySignedTransaction shuffled_psbt;
1920  shuffled_psbt.tx = CMutableTransaction();
1921  shuffled_psbt.tx->nVersion = merged_psbt.tx->nVersion;
1922  shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1923  for (int i : input_indices) {
1924  shuffled_psbt.AddInput(merged_psbt.tx->vin[i],
1925  merged_psbt.inputs[i]);
1926  }
1927  for (int i : output_indices) {
1928  shuffled_psbt.AddOutput(merged_psbt.tx->vout[i],
1929  merged_psbt.outputs[i]);
1930  }
1931  shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(),
1932  merged_psbt.unknown.end());
1933 
1935  ssTx << shuffled_psbt;
1936  return EncodeBase64(MakeUCharSpan(ssTx));
1937  },
1938  };
1939 }
1940 
1942  return RPCHelpMan{
1943  "analyzepsbt",
1944  "Analyzes and provides information about the current status of a "
1945  "PSBT and its inputs\n",
1947  "A base64 string of a PSBT"}},
1948  RPCResult{
1950  "",
1951  "",
1952  {
1954  "inputs",
1955  "",
1956  {
1958  "",
1959  "",
1960  {
1961  {RPCResult::Type::BOOL, "has_utxo",
1962  "Whether a UTXO is provided"},
1963  {RPCResult::Type::BOOL, "is_final",
1964  "Whether the input is finalized"},
1966  "missing",
1967  /* optional */ true,
1968  "Things that are missing that are required to "
1969  "complete this input",
1970  {
1972  "pubkeys",
1973  /* optional */ true,
1974  "",
1975  {
1976  {RPCResult::Type::STR_HEX, "keyid",
1977  "Public key ID, hash160 of the public "
1978  "key, of a public key whose BIP 32 "
1979  "derivation path is missing"},
1980  }},
1982  "signatures",
1983  /* optional */ true,
1984  "",
1985  {
1986  {RPCResult::Type::STR_HEX, "keyid",
1987  "Public key ID, hash160 of the public "
1988  "key, of a public key whose signature is "
1989  "missing"},
1990  }},
1991  {RPCResult::Type::STR_HEX, "redeemscript",
1992  /* optional */ true,
1993  "Hash160 of the redeemScript that is missing"},
1994  }},
1995  {RPCResult::Type::STR, "next", /* optional */ true,
1996  "Role of the next person that this input needs to "
1997  "go to"},
1998  }},
1999  }},
2000  {RPCResult::Type::NUM, "estimated_vsize", /* optional */ true,
2001  "Estimated vsize of the final signed transaction"},
2002  {RPCResult::Type::STR_AMOUNT, "estimated_feerate",
2003  /* optional */ true,
2004  "Estimated feerate of the final signed transaction in " +
2005  Currency::get().ticker +
2006  "/kB. Shown only if all UTXO slots in the PSBT have been "
2007  "filled"},
2008  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
2009  "The transaction fee paid. Shown only if all UTXO slots in "
2010  "the PSBT have been filled"},
2011  {RPCResult::Type::STR, "next",
2012  "Role of the next person that this psbt needs to go to"},
2013  {RPCResult::Type::STR, "error", /* optional */ true,
2014  "Error message (if there is one)"},
2015  }},
2016  RPCExamples{HelpExampleCli("analyzepsbt", "\"psbt\"")},
2017  [&](const RPCHelpMan &self, const Config &config,
2018  const JSONRPCRequest &request) -> UniValue {
2019  RPCTypeCheck(request.params, {UniValue::VSTR});
2020 
2021  // Unserialize the transaction
2023  std::string error;
2024  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
2026  strprintf("TX decode failed %s", error));
2027  }
2028 
2029  PSBTAnalysis psbta = AnalyzePSBT(psbtx);
2030 
2031  UniValue result(UniValue::VOBJ);
2032  UniValue inputs_result(UniValue::VARR);
2033  for (const auto &input : psbta.inputs) {
2034  UniValue input_univ(UniValue::VOBJ);
2035  UniValue missing(UniValue::VOBJ);
2036 
2037  input_univ.pushKV("has_utxo", input.has_utxo);
2038  input_univ.pushKV("is_final", input.is_final);
2039  input_univ.pushKV("next", PSBTRoleName(input.next));
2040 
2041  if (!input.missing_pubkeys.empty()) {
2042  UniValue missing_pubkeys_univ(UniValue::VARR);
2043  for (const CKeyID &pubkey : input.missing_pubkeys) {
2044  missing_pubkeys_univ.push_back(HexStr(pubkey));
2045  }
2046  missing.pushKV("pubkeys", missing_pubkeys_univ);
2047  }
2048  if (!input.missing_redeem_script.IsNull()) {
2049  missing.pushKV("redeemscript",
2050  HexStr(input.missing_redeem_script));
2051  }
2052  if (!input.missing_sigs.empty()) {
2053  UniValue missing_sigs_univ(UniValue::VARR);
2054  for (const CKeyID &pubkey : input.missing_sigs) {
2055  missing_sigs_univ.push_back(HexStr(pubkey));
2056  }
2057  missing.pushKV("signatures", missing_sigs_univ);
2058  }
2059  if (!missing.getKeys().empty()) {
2060  input_univ.pushKV("missing", missing);
2061  }
2062  inputs_result.push_back(input_univ);
2063  }
2064  if (!inputs_result.empty()) {
2065  result.pushKV("inputs", inputs_result);
2066  }
2067  if (psbta.estimated_vsize != std::nullopt) {
2068  result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
2069  }
2070  if (psbta.estimated_feerate != std::nullopt) {
2071  result.pushKV("estimated_feerate",
2072  psbta.estimated_feerate->GetFeePerK());
2073  }
2074  if (psbta.fee != std::nullopt) {
2075  result.pushKV("fee", *psbta.fee);
2076  }
2077  result.pushKV("next", PSBTRoleName(psbta.next));
2078  if (!psbta.error.empty()) {
2079  result.pushKV("error", psbta.error);
2080  }
2081 
2082  return result;
2083  },
2084  };
2085 }
2086 
2088  // clang-format off
2089  static const CRPCCommand commands[] = {
2090  // category actor (function)
2091  // ------------------ ----------------------
2092  { "rawtransactions", getrawtransaction, },
2093  { "rawtransactions", createrawtransaction, },
2094  { "rawtransactions", decoderawtransaction, },
2095  { "rawtransactions", decodescript, },
2096  { "rawtransactions", sendrawtransaction, },
2097  { "rawtransactions", combinerawtransaction, },
2098  { "rawtransactions", signrawtransactionwithkey, },
2099  { "rawtransactions", testmempoolaccept, },
2100  { "rawtransactions", decodepsbt, },
2101  { "rawtransactions", combinepsbt, },
2102  { "rawtransactions", finalizepsbt, },
2103  { "rawtransactions", createpsbt, },
2104  { "rawtransactions", converttopsbt, },
2105  { "rawtransactions", utxoupdatepsbt, },
2106  { "rawtransactions", joinpsbts, },
2107  { "rawtransactions", analyzepsbt, },
2108  };
2109  // clang-format on
2110  for (const auto &c : commands) {
2111  t.appendCommand(c.name, &c);
2112  }
2113 }
bool MoneyRange(const Amount nValue)
Definition: amount.h:176
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:111
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:52
uint256 hashMerkleRoot
Definition: block.h:27
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
int64_t GetBlockTime() const
Definition: blockindex.h:174
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:39
int Height() const
Return the maximal height in the chain.
Definition: chain.h:193
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:173
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:99
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:642
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:757
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:692
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:731
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:46
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:203
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:192
Abstract view on the open txout dataset.
Definition: coins.h:147
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:960
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:197
std::string str() const
Definition: streams.h:271
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:49
An encapsulated secp256k1 private key.
Definition: key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:94
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
A mutable version of CTransaction.
Definition: transaction.h:278
std::vector< CTxOut > vout
Definition: transaction.h:281
std::vector< CTxIn > vin
Definition: transaction.h:280
RPC command dispatcher.
Definition: server.h:183
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:325
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
void clear()
Definition: script.h:554
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
An input of a transaction.
Definition: transaction.h:61
CScript scriptSig
Definition: transaction.h:64
COutPoint prevout
Definition: transaction.h:63
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:435
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:518
An output of a transaction.
Definition: transaction.h:130
CScript scriptPubKey
Definition: transaction.h:133
Amount nValue
Definition: transaction.h:132
bool IsNull() const
Definition: transaction.h:147
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1046
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
CChainState & ActiveChainstate() const
The most-work chain.
CChain & ActiveChain() const
Definition: validation.h:1185
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1113
A UTXO entry.
Definition: coins.h:27
bool IsSpent() const
Definition: coins.h:46
CTxOut & GetTxOut()
Definition: coins.h:48
Definition: config.h:17
Fast randomness source.
Definition: random.h:129
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddKey(const CKey &key)
A signature creator for transactions.
Definition: sign.h:38
Signature hash type wrapper class.
Definition: sighashtype.h:37
uint32_t getRawSigHashType() const
Definition: sighashtype.h:83
const std::string & get_str() const
@ VOBJ
Definition: univalue.h:27
@ VARR
Definition: univalue.h:27
size_t size() const
Definition: univalue.h:80
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:78
bool isStr() const
Definition: univalue.h:93
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
const UniValue & get_array() const
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
std::string GetRejectReason() const
Definition: validation.h:124
Result GetResult() const
Definition: validation.h:123
bool IsNull() const
Definition: uint256.h:30
std::string GetHex() const
Definition: uint256.cpp:16
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool empty() const
Definition: prevector.h:388
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:175
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
Definition: core_write.cpp:217
std::string SighashToStr(uint8_t sighash_type)
Definition: core_write.cpp:89
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:190
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:196
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:106
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:169
static uint32_t ReadBE32(const uint8_t *ptr)
Definition: common.h:56
TransactionError
Definition: error.h:22
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:80
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition: moneystr.cpp:13
Definition: init.h:28
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:37
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const TxId &txid, const Consensus::Params &consensusParams, BlockHash &hashBlock)
Return transaction with a given txid.
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:16
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &params)
Functions for disk access for blocks.
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:12
static const CFeeRate DEFAULT_MAX_RAW_TX_FEE_RATE
Maximum fee rate for sendrawtransaction and testmempoolaccept RPC calls.
Definition: transaction.h:33
static constexpr uint32_t MAX_PACKAGE_COUNT
Default maximum number of transactions in a package.
Definition: packages.h:15
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigChecks, unsigned int bytes_per_sigCheck)
Compute the virtual transaction size (size, or more if sigChecks are too dense).
Definition: policy.cpp:162
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:320
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
SchnorrSig sig
Definition: processor.cpp:423
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:295
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:163
std::string PSBTRoleName(const PSBTRole role)
Definition: psbt.cpp:278
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:246
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:263
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:185
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:251
RPCHelpMan joinpsbts()
static RPCHelpMan getrawtransaction()
static RPCHelpMan sendrawtransaction()
static RPCHelpMan converttopsbt()
RPCHelpMan analyzepsbt()
static RPCHelpMan decoderawtransaction()
static RPCHelpMan combinepsbt()
static RPCHelpMan decodepsbt()
static RPCHelpMan decodescript()
static RPCHelpMan createpsbt()
RPCHelpMan utxoupdatepsbt()
static void TxToJSON(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, CChainState &active_chainstate)
static RPCHelpMan combinerawtransaction()
static RPCHelpMan testmempoolaccept()
static RPCHelpMan signrawtransactionwithkey()
static RPCHelpMan createrawtransaction()
static RPCHelpMan finalizepsbt()
void RegisterRawTransactionRPCCommands(CRPCTable &t)
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.
CMutableTransaction ConstructTransaction(const CChainParams &params, const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime)
Create a transaction from univalue parameters.
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.
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:52
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:122
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:27
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:178
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:361
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:83
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:1030
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:195
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:23
std::string GetAllOutputTypes()
Definition: util.cpp:333
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:101
#define extract(n)
Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits.
@ SER_NETWORK
Definition: serialize.h:166
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
Definition: server.cpp:603
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:19
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:27
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:39
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:198
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:331
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:275
const SigningProvider & DUMMY_SIGNING_PROVIDER
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(MakeSpan(std::forward< V >(v))))
Like MakeSpan, but for (const) uint8_t member types only.
Definition: span.h:311
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string EncodeBase64(Span< const uint8_t > input)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:77
Definition: amount.h:19
static constexpr Amount zero()
Definition: amount.h:42
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:160
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
A structure for PSBTs which contain per-input information.
Definition: psbt.h:45
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:49
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:50
SigHashType sighash_type
Definition: psbt.h:52
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:51
CScript redeem_script
Definition: psbt.h:47
CScript final_script_sig
Definition: psbt.h:48
CTxOut utxo
Definition: psbt.h:46
A structure for PSBTs which contains per output information.
Definition: psbt.h:234
CScript redeem_script
Definition: psbt.h:235
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:236
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:237
Validation result for package mempool acceptance.
Definition: validation.h:277
std::map< const TxId, const MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:286
const PackageValidationState m_state
Definition: validation.h:278
A version of CTransaction with the PSBT format.
Definition: psbt.h:335
std::map< std::vector< uint8_t >, std::vector< uint8_t > > unknown
Definition: psbt.h:339
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:49
std::vector< PSBTInput > inputs
Definition: psbt.h:337
std::optional< CMutableTransaction > tx
Definition: psbt.h:336
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:37
std::vector< PSBTOutput > outputs
Definition: psbt.h:338
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:335
A TxId is the identifier of a transaction.
Definition: txid.h:14
NodeContext struct containing references to chain state and connection state.
Definition: context.h:38
Holds the results of AnalyzePSBT (miscellaneous information about a PSBT)
Definition: psbt.h:35
std::vector< PSBTInputAnalysis > inputs
More information about the individual inputs of the transaction.
Definition: psbt.h:43
std::string error
Error message.
Definition: psbt.h:47
std::optional< Amount > fee
Amount of fee being paid by the transaction.
Definition: psbt.h:41
std::optional< size_t > estimated_vsize
Estimated weight of the transaction.
Definition: psbt.h:37
std::optional< CFeeRate > estimated_feerate
Estimated feerate (fee / weight) of the transaction.
Definition: psbt.h:39
PSBTRole next
Which of the BIP 174 roles needs to handle the transaction next.
Definition: psbt.h:45
#define AssertLockNotHeld(cs)
Definition: sync.h:97
#define LOCK2(cs1, cs2)
Definition: sync.h:246
#define LOCK(cs)
Definition: sync.h:243
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
bool error(const char *fmt, const Args &...args)
Definition: system.h:46
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
PackageMempoolAcceptResult ProcessNewPackage(const Config &config, CChainState &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11