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