Bitcoin ABC  0.29.2
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, Chainstate &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, RPCArg::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,
317  RPCArg::DefaultHint{"depends on the value of the "
318  "'locktime' argument"},
319  "The sequence number"},
320  },
321  },
322  },
323  },
324  {
325  "outputs",
328  "The outputs (key-value pairs), where none of "
329  "the keys are duplicated.\n"
330  "That is, each address can only appear once and there can only "
331  "be one 'data' object.\n"
332  "For compatibility reasons, a dictionary, which holds the "
333  "key-value pairs directly, is also\n"
334  " accepted as second parameter.",
335  {
336  {
337  "",
340  "",
341  {
342  {"address", RPCArg::Type::AMOUNT,
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  {
356  {"data", RPCArg::Type::STR_HEX,
358  "A key-value pair. The key must be \"data\", the "
359  "value is hex-encoded data"},
360  },
361  },
362  },
363  },
364  {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
365  "Raw locktime. Non-0 value also locktime-activates inputs"},
366  },
367  RPCResult{RPCResult::Type::STR_HEX, "transaction",
368  "hex string of the transaction"},
369  RPCExamples{
370  HelpExampleCli("createrawtransaction",
371  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
372  "\" \"[{\\\"address\\\":10000.00}]\"") +
373  HelpExampleCli("createrawtransaction",
374  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
375  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
376  HelpExampleRpc("createrawtransaction",
377  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
378  "\", \"[{\\\"address\\\":10000.00}]\"") +
379  HelpExampleRpc("createrawtransaction",
380  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
381  "\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
382  [&](const RPCHelpMan &self, const Config &config,
383  const JSONRPCRequest &request) -> UniValue {
384  RPCTypeCheck(request.params,
385  {UniValue::VARR,
386  UniValueType(), // ARR or OBJ, checked later
387  UniValue::VNUM},
388  true);
389 
390  CMutableTransaction rawTx =
391  ConstructTransaction(config.GetChainParams(), request.params[0],
392  request.params[1], request.params[2]);
393 
394  return EncodeHexTx(CTransaction(rawTx));
395  },
396  };
397 }
398 
400  return RPCHelpMan{
401  "decoderawtransaction",
402  "Return a JSON object representing the serialized, hex-encoded "
403  "transaction.\n",
404  {
406  "The transaction hex string"},
407  },
408  RPCResult{
410  "",
411  "",
412  {
413  {RPCResult::Type::STR_HEX, "txid", "The transaction id"},
414  {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
415  {RPCResult::Type::NUM, "size", "The transaction size"},
416  {RPCResult::Type::NUM, "version", "The version"},
417  {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
419  "vin",
420  "",
421  {
423  "",
424  "",
425  {
426  {RPCResult::Type::STR_HEX, "txid",
427  "The transaction id"},
428  {RPCResult::Type::NUM, "vout", "The output number"},
430  "scriptSig",
431  "The script",
432  {
433  {RPCResult::Type::STR, "asm", "asm"},
434  {RPCResult::Type::STR_HEX, "hex", "hex"},
435  }},
436  {RPCResult::Type::NUM, "sequence",
437  "The script sequence number"},
438  }},
439  }},
441  "vout",
442  "",
443  {
445  "",
446  "",
447  {
448  {RPCResult::Type::NUM, "value",
449  "The value in " + Currency::get().ticker},
450  {RPCResult::Type::NUM, "n", "index"},
452  "scriptPubKey",
453  "",
454  {
455  {RPCResult::Type::STR, "asm", "the asm"},
456  {RPCResult::Type::STR_HEX, "hex", "the hex"},
457  {RPCResult::Type::NUM, "reqSigs",
458  "The required sigs"},
459  {RPCResult::Type::STR, "type",
460  "The type, eg 'pubkeyhash'"},
462  "addresses",
463  "",
464  {
465  {RPCResult::Type::STR, "address",
466  "bitcoin address"},
467  }},
468  }},
469  }},
470  }},
471  }},
472  RPCExamples{HelpExampleCli("decoderawtransaction", "\"hexstring\"") +
473  HelpExampleRpc("decoderawtransaction", "\"hexstring\"")},
474  [&](const RPCHelpMan &self, const Config &config,
475  const JSONRPCRequest &request) -> UniValue {
476  RPCTypeCheck(request.params, {UniValue::VSTR});
477 
479 
480  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
482  "TX decode failed");
483  }
484 
485  UniValue result(UniValue::VOBJ);
486  TxToUniv(CTransaction(std::move(mtx)), BlockHash(), result, false);
487 
488  return result;
489  },
490  };
491 }
492 
494  return RPCHelpMan{
495  "decodescript",
496  "Decode a hex-encoded script.\n",
497  {
499  "the hex-encoded script"},
500  },
501  RPCResult{
503  "",
504  "",
505  {
506  {RPCResult::Type::STR, "asm", "Script public key"},
507  {RPCResult::Type::STR, "type",
508  "The output type (e.g. " + GetAllOutputTypes() + ")"},
509  {RPCResult::Type::NUM, "reqSigs", "The required signatures"},
511  "addresses",
512  "",
513  {
514  {RPCResult::Type::STR, "address", "bitcoin address"},
515  }},
516  {RPCResult::Type::STR, "p2sh",
517  "address of P2SH script wrapping this redeem script (not "
518  "returned if the script is already a P2SH)"},
519  }},
520  RPCExamples{HelpExampleCli("decodescript", "\"hexstring\"") +
521  HelpExampleRpc("decodescript", "\"hexstring\"")},
522  [&](const RPCHelpMan &self, const Config &config,
523  const JSONRPCRequest &request) -> UniValue {
524  RPCTypeCheck(request.params, {UniValue::VSTR});
525 
527  CScript script;
528  if (request.params[0].get_str().size() > 0) {
529  std::vector<uint8_t> scriptData(
530  ParseHexV(request.params[0], "argument"));
531  script = CScript(scriptData.begin(), scriptData.end());
532  } else {
533  // Empty scripts are valid.
534  }
535 
536  ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false);
537 
538  UniValue type;
539  type = r.find_value("type");
540 
541  if (type.isStr() && type.get_str() != "scripthash") {
542  // P2SH cannot be wrapped in a P2SH. If this script is already a
543  // P2SH, don't return the address for a P2SH of the P2SH.
544  r.pushKV("p2sh", EncodeDestination(ScriptHash(script), config));
545  }
546 
547  return r;
548  },
549  };
550 }
551 
553  return RPCHelpMan{
554  "combinerawtransaction",
555  "Combine multiple partially signed transactions into one "
556  "transaction.\n"
557  "The combined transaction may be another partially signed transaction "
558  "or a \n"
559  "fully signed transaction.",
560  {
561  {
562  "txs",
565  "The hex strings of partially signed "
566  "transactions",
567  {
568  {"hexstring", RPCArg::Type::STR_HEX,
570  "A hex-encoded raw transaction"},
571  },
572  },
573  },
575  "The hex-encoded raw transaction with signature(s)"},
576  RPCExamples{HelpExampleCli("combinerawtransaction",
577  R"('["myhex1", "myhex2", "myhex3"]')")},
578  [&](const RPCHelpMan &self, const Config &config,
579  const JSONRPCRequest &request) -> UniValue {
580  UniValue txs = request.params[0].get_array();
581  std::vector<CMutableTransaction> txVariants(txs.size());
582 
583  for (unsigned int idx = 0; idx < txs.size(); idx++) {
584  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
585  throw JSONRPCError(
587  strprintf("TX decode failed for tx %d", idx));
588  }
589  }
590 
591  if (txVariants.empty()) {
593  "Missing transactions");
594  }
595 
596  // mergedTx will end up with all the signatures; it
597  // starts as a clone of the rawtx:
598  CMutableTransaction mergedTx(txVariants[0]);
599 
600  // Fetch previous transactions (inputs):
601  CCoinsView viewDummy;
602  CCoinsViewCache view(&viewDummy);
603  {
604  NodeContext &node = EnsureAnyNodeContext(request.context);
605  const CTxMemPool &mempool = EnsureMemPool(node);
607  LOCK2(cs_main, mempool.cs);
608  CCoinsViewCache &viewChain =
609  chainman.ActiveChainstate().CoinsTip();
610  CCoinsViewMemPool viewMempool(&viewChain, mempool);
611  // temporarily switch cache backend to db+mempool view
612  view.SetBackend(viewMempool);
613 
614  for (const CTxIn &txin : mergedTx.vin) {
615  // Load entries from viewChain into view; can fail.
616  view.AccessCoin(txin.prevout);
617  }
618 
619  // switch back to avoid locking mempool for too long
620  view.SetBackend(viewDummy);
621  }
622 
623  // Use CTransaction for the constant parts of the
624  // transaction to avoid rehashing.
625  const CTransaction txConst(mergedTx);
626  // Sign what we can:
627  for (size_t i = 0; i < mergedTx.vin.size(); i++) {
628  CTxIn &txin = mergedTx.vin[i];
629  const Coin &coin = view.AccessCoin(txin.prevout);
630  if (coin.IsSpent()) {
632  "Input not found or already spent");
633  }
634  SignatureData sigdata;
635 
636  const CTxOut &txout = coin.GetTxOut();
637 
638  // ... and merge in other signatures:
639  for (const CMutableTransaction &txv : txVariants) {
640  if (txv.vin.size() > i) {
641  sigdata.MergeSignatureData(
642  DataFromTransaction(txv, i, txout));
643  }
644  }
647  &mergedTx, i, txout.nValue),
648  txout.scriptPubKey, sigdata);
649 
650  UpdateInput(txin, sigdata);
651  }
652 
653  return EncodeHexTx(CTransaction(mergedTx));
654  },
655  };
656 }
657 
659  return RPCHelpMan{
660  "signrawtransactionwithkey",
661  "Sign inputs for raw transaction (serialized, hex-encoded).\n"
662  "The second argument is an array of base58-encoded private\n"
663  "keys that will be the only keys used to sign the transaction.\n"
664  "The third optional argument (may be null) is an array of previous "
665  "transaction outputs that\n"
666  "this transaction depends on but may not yet be in the block chain.\n",
667  {
669  "The transaction hex string"},
670  {
671  "privkeys",
674  "The base58-encoded private keys for signing",
675  {
677  "private key in base58-encoding"},
678  },
679  },
680  {
681  "prevtxs",
684  "The previous dependent transaction outputs",
685  {
686  {
687  "",
690  "",
691  {
692  {"txid", RPCArg::Type::STR_HEX,
693  RPCArg::Optional::NO, "The transaction id"},
695  "The output number"},
696  {"scriptPubKey", RPCArg::Type::STR_HEX,
697  RPCArg::Optional::NO, "script key"},
698  {"redeemScript", RPCArg::Type::STR_HEX,
700  "(required for P2SH) redeem script"},
701  {"amount", RPCArg::Type::AMOUNT,
702  RPCArg::Optional::NO, "The amount spent"},
703  },
704  },
705  },
706  },
707  {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"ALL|FORKID"},
708  "The signature hash type. Must be one of:\n"
709  " \"ALL|FORKID\"\n"
710  " \"NONE|FORKID\"\n"
711  " \"SINGLE|FORKID\"\n"
712  " \"ALL|FORKID|ANYONECANPAY\"\n"
713  " \"NONE|FORKID|ANYONECANPAY\"\n"
714  " \"SINGLE|FORKID|ANYONECANPAY\""},
715  },
716  RPCResult{
718  "",
719  "",
720  {
721  {RPCResult::Type::STR_HEX, "hex",
722  "The hex-encoded raw transaction with signature(s)"},
723  {RPCResult::Type::BOOL, "complete",
724  "If the transaction has a complete set of signatures"},
726  "errors",
727  /* optional */ true,
728  "Script verification errors (if there are any)",
729  {
731  "",
732  "",
733  {
734  {RPCResult::Type::STR_HEX, "txid",
735  "The hash of the referenced, previous transaction"},
736  {RPCResult::Type::NUM, "vout",
737  "The index of the output to spent and used as "
738  "input"},
739  {RPCResult::Type::STR_HEX, "scriptSig",
740  "The hex-encoded signature script"},
741  {RPCResult::Type::NUM, "sequence",
742  "Script sequence number"},
743  {RPCResult::Type::STR, "error",
744  "Verification or signing error related to the "
745  "input"},
746  }},
747  }},
748  }},
749  RPCExamples{
750  HelpExampleCli("signrawtransactionwithkey",
751  "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"") +
752  HelpExampleRpc("signrawtransactionwithkey",
753  "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")},
754  [&](const RPCHelpMan &self, const Config &config,
755  const JSONRPCRequest &request) -> UniValue {
756  RPCTypeCheck(request.params,
757  {UniValue::VSTR, UniValue::VARR, UniValue::VARR,
758  UniValue::VSTR},
759  true);
760 
762  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
764  "TX decode failed");
765  }
766 
767  FillableSigningProvider keystore;
768  const UniValue &keys = request.params[1].get_array();
769  for (size_t idx = 0; idx < keys.size(); ++idx) {
770  UniValue k = keys[idx];
771  CKey key = DecodeSecret(k.get_str());
772  if (!key.IsValid()) {
774  "Invalid private key");
775  }
776  keystore.AddKey(key);
777  }
778 
779  // Fetch previous transactions (inputs):
780  std::map<COutPoint, Coin> coins;
781  for (const CTxIn &txin : mtx.vin) {
782  // Create empty map entry keyed by prevout.
783  coins[txin.prevout];
784  }
785  NodeContext &node = EnsureAnyNodeContext(request.context);
786  FindCoins(node, coins);
787 
788  // Parse the prevtxs array
789  ParsePrevouts(request.params[2], &keystore, coins);
790 
791  UniValue result(UniValue::VOBJ);
792  SignTransaction(mtx, &keystore, coins, request.params[3], result);
793  return result;
794  },
795  };
796 }
797 
799  return RPCHelpMan{
800  "sendrawtransaction",
801  "Submits raw transaction (serialized, hex-encoded) to local node and "
802  "network.\n"
803  "\nAlso see createrawtransaction and "
804  "signrawtransactionwithkey calls.\n",
805  {
807  "The hex string of the raw transaction"},
808  {"maxfeerate", RPCArg::Type::AMOUNT,
811  "Reject transactions whose fee rate is higher than the specified "
812  "value, expressed in " +
814  "/kB\nSet to 0 to accept any fee rate.\n"},
815  },
816  RPCResult{RPCResult::Type::STR_HEX, "", "The transaction hash in hex"},
817  RPCExamples{
818  "\nCreate a transaction\n" +
820  "createrawtransaction",
821  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
822  "\"{\\\"myaddress\\\":10000}\"") +
823  "Sign the transaction, and get back the hex\n" +
824  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
825  "\nSend the transaction (signed hex)\n" +
826  HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
827  "\nAs a JSON-RPC call\n" +
828  HelpExampleRpc("sendrawtransaction", "\"signedhex\"")},
829  [&](const RPCHelpMan &self, const Config &config,
830  const JSONRPCRequest &request) -> UniValue {
831  RPCTypeCheck(request.params,
832  {
833  UniValue::VSTR,
834  // VNUM or VSTR, checked inside AmountFromValue()
835  UniValueType(),
836  });
837 
838  // parse hex string from parameter
840  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
842  "TX decode failed");
843  }
844 
845  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
846 
847  const CFeeRate max_raw_tx_fee_rate =
848  request.params[1].isNull()
850  : CFeeRate(AmountFromValue(request.params[1]));
851 
852  int64_t virtual_size = GetVirtualTransactionSize(*tx);
853  Amount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size);
854 
855  std::string err_string;
857  NodeContext &node = EnsureAnyNodeContext(request.context);
859  node, tx, err_string, max_raw_tx_fee, /*relay*/ true,
860  /*wait_callback*/ true);
861  if (err != TransactionError::OK) {
862  throw JSONRPCTransactionError(err, err_string);
863  }
864 
865  // Block to make sure wallet/indexers sync before returning
867 
868  return tx->GetHash().GetHex();
869  },
870  };
871 }
872 
874  return RPCHelpMan{
875  "testmempoolaccept",
876  "\nReturns result of mempool acceptance tests indicating if raw "
877  "transaction(s) (serialized, hex-encoded) would be accepted by "
878  "mempool.\n"
879  "\nIf multiple transactions are passed in, parents must come before "
880  "children and package policies apply: the transactions cannot conflict "
881  "with any mempool transactions or each other.\n"
882  "\nIf one transaction fails, other transactions may not be fully "
883  "validated (the 'allowed' key will be blank).\n"
884  "\nThe maximum number of transactions allowed is " +
886  ".\n"
887  "\nThis checks if transactions violate the consensus or policy "
888  "rules.\n"
889  "\nSee sendrawtransaction call.\n",
890  {
891  {
892  "rawtxs",
895  "An array of hex strings of raw transactions.",
896  {
898  ""},
899  },
900  },
901  {"maxfeerate", RPCArg::Type::AMOUNT,
904  "Reject transactions whose fee rate is higher than the specified "
905  "value, expressed in " +
906  Currency::get().ticker + "/kB\n"},
907  },
908  RPCResult{
910  "",
911  "The result of the mempool acceptance test for each raw "
912  "transaction in the input array.\n"
913  "Returns results for each transaction in the same order they were "
914  "passed in.\n"
915  "Transactions that cannot be fully validated due to failures in "
916  "other transactions will not contain an 'allowed' result.\n",
917  {
919  "",
920  "",
921  {
922  {RPCResult::Type::STR_HEX, "txid",
923  "The transaction hash in hex"},
924  {RPCResult::Type::STR, "package-error",
925  "Package validation error, if any (only possible if "
926  "rawtxs had more than 1 transaction)."},
927  {RPCResult::Type::BOOL, "allowed",
928  "Whether this tx would be accepted to the mempool and "
929  "pass client-specified maxfeerate. "
930  "If not present, the tx was not fully validated due to a "
931  "failure in another tx in the list."},
932  {RPCResult::Type::NUM, "size", "The transaction size"},
934  "fees",
935  "Transaction fees (only present if 'allowed' is true)",
936  {
938  "transaction fee in " + Currency::get().ticker},
939  }},
940  {RPCResult::Type::STR, "reject-reason",
941  "Rejection string (only present when 'allowed' is "
942  "false)"},
943  }},
944  }},
945  RPCExamples{
946  "\nCreate a transaction\n" +
948  "createrawtransaction",
949  "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" "
950  "\"{\\\"myaddress\\\":10000}\"") +
951  "Sign the transaction, and get back the hex\n" +
952  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
953  "\nTest acceptance of the transaction (signed hex)\n" +
954  HelpExampleCli("testmempoolaccept", R"('["signedhex"]')") +
955  "\nAs a JSON-RPC call\n" +
956  HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")},
957  [&](const RPCHelpMan &self, const Config &config,
958  const JSONRPCRequest &request) -> UniValue {
959  RPCTypeCheck(request.params,
960  {
961  UniValue::VARR,
962  // VNUM or VSTR, checked inside AmountFromValue()
963  UniValueType(),
964  });
965  const UniValue raw_transactions = request.params[0].get_array();
966  if (raw_transactions.size() < 1 ||
967  raw_transactions.size() > MAX_PACKAGE_COUNT) {
969  "Array must contain between 1 and " +
971  " transactions.");
972  }
973 
974  const CFeeRate max_raw_tx_fee_rate =
975  request.params[1].isNull()
977  : CFeeRate(AmountFromValue(request.params[1]));
978 
979  std::vector<CTransactionRef> txns;
980  txns.reserve(raw_transactions.size());
981  for (const auto &rawtx : raw_transactions.getValues()) {
983  if (!DecodeHexTx(mtx, rawtx.get_str())) {
985  "TX decode failed: " + rawtx.get_str());
986  }
987  txns.emplace_back(MakeTransactionRef(std::move(mtx)));
988  }
989 
990  NodeContext &node = EnsureAnyNodeContext(request.context);
991  CTxMemPool &mempool = EnsureMemPool(node);
993  Chainstate &chainstate = chainman.ActiveChainstate();
994  const PackageMempoolAcceptResult package_result = [&] {
995  LOCK(::cs_main);
996  if (txns.size() > 1) {
997  return ProcessNewPackage(chainstate, mempool, txns,
998  /* test_accept */ true);
999  }
1001  txns[0]->GetId(),
1002  chainman.ProcessTransaction(txns[0],
1003  /* test_accept*/ true));
1004  }();
1005 
1006  UniValue rpc_result(UniValue::VARR);
1007  // We will check transaction fees while we iterate through txns in
1008  // order. If any transaction fee exceeds maxfeerate, we will leave
1009  // the rest of the validation results blank, because it doesn't make
1010  // sense to return a validation result for a transaction if its
1011  // ancestor(s) would not be submitted.
1012  bool exit_early{false};
1013  for (const auto &tx : txns) {
1014  UniValue result_inner(UniValue::VOBJ);
1015  result_inner.pushKV("txid", tx->GetId().GetHex());
1016  if (package_result.m_state.GetResult() ==
1018  result_inner.pushKV(
1019  "package-error",
1020  package_result.m_state.GetRejectReason());
1021  }
1022  auto it = package_result.m_tx_results.find(tx->GetId());
1023  if (exit_early || it == package_result.m_tx_results.end()) {
1024  // Validation unfinished. Just return the txid.
1025  rpc_result.push_back(result_inner);
1026  continue;
1027  }
1028  const auto &tx_result = it->second;
1029  // Package testmempoolaccept doesn't allow transactions to
1030  // already be in the mempool.
1031  CHECK_NONFATAL(tx_result.m_result_type !=
1033  if (tx_result.m_result_type ==
1035  const Amount fee = tx_result.m_base_fees.value();
1036  // Check that fee does not exceed maximum fee
1037  const int64_t virtual_size = tx_result.m_vsize.value();
1038  const Amount max_raw_tx_fee =
1039  max_raw_tx_fee_rate.GetFee(virtual_size);
1040  if (max_raw_tx_fee != Amount::zero() &&
1041  fee > max_raw_tx_fee) {
1042  result_inner.pushKV("allowed", false);
1043  result_inner.pushKV("reject-reason",
1044  "max-fee-exceeded");
1045  exit_early = true;
1046  } else {
1047  // Only return the fee and size if the transaction
1048  // would pass ATMP.
1049  // These can be used to calculate the feerate.
1050  result_inner.pushKV("allowed", true);
1051  result_inner.pushKV("size", virtual_size);
1052  UniValue fees(UniValue::VOBJ);
1053  fees.pushKV("base", fee);
1054  result_inner.pushKV("fees", fees);
1055  }
1056  } else {
1057  result_inner.pushKV("allowed", false);
1058  const TxValidationState state = tx_result.m_state;
1059  if (state.GetResult() ==
1061  result_inner.pushKV("reject-reason", "missing-inputs");
1062  } else {
1063  result_inner.pushKV("reject-reason",
1064  state.GetRejectReason());
1065  }
1066  }
1067  rpc_result.push_back(result_inner);
1068  }
1069  return rpc_result;
1070  },
1071  };
1072 }
1073 
1075  return RPCHelpMan{
1076  "decodepsbt",
1077  "Return a JSON object representing the serialized, base64-encoded "
1078  "partially signed Bitcoin transaction.\n",
1079  {
1081  "The PSBT base64 string"},
1082  },
1083  RPCResult{
1085  "",
1086  "",
1087  {
1089  "tx",
1090  "The decoded network-serialized unsigned transaction.",
1091  {
1093  "The layout is the same as the output of "
1094  "decoderawtransaction."},
1095  }},
1097  "unknown",
1098  "The unknown global fields",
1099  {
1100  {RPCResult::Type::STR_HEX, "key",
1101  "(key-value pair) An unknown key-value pair"},
1102  }},
1104  "inputs",
1105  "",
1106  {
1108  "",
1109  "",
1110  {
1112  "utxo",
1113  /* optional */ true,
1114  "Transaction output for UTXOs",
1115  {
1116  {RPCResult::Type::NUM, "amount",
1117  "The value in " + Currency::get().ticker},
1119  "scriptPubKey",
1120  "",
1121  {
1122  {RPCResult::Type::STR, "asm", "The asm"},
1123  {RPCResult::Type::STR_HEX, "hex",
1124  "The hex"},
1125  {RPCResult::Type::STR, "type",
1126  "The type, eg 'pubkeyhash'"},
1127  {RPCResult::Type::STR, "address",
1128  " Bitcoin address if there is one"},
1129  }},
1130  }},
1132  "partial_signatures",
1133  /* optional */ true,
1134  "",
1135  {
1136  {RPCResult::Type::STR, "pubkey",
1137  "The public key and signature that corresponds "
1138  "to it."},
1139  }},
1140  {RPCResult::Type::STR, "sighash", /* optional */ true,
1141  "The sighash type to be used"},
1143  "redeem_script",
1144  /* optional */ true,
1145  "",
1146  {
1147  {RPCResult::Type::STR, "asm", "The asm"},
1148  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1149  {RPCResult::Type::STR, "type",
1150  "The type, eg 'pubkeyhash'"},
1151  }},
1153  "bip32_derivs",
1154  /* optional */ true,
1155  "",
1156  {
1158  "pubkey",
1159  /* optional */ true,
1160  "The public key with the derivation path as "
1161  "the value.",
1162  {
1163  {RPCResult::Type::STR, "master_fingerprint",
1164  "The fingerprint of the master key"},
1165  {RPCResult::Type::STR, "path", "The path"},
1166  }},
1167  }},
1169  "final_scriptsig",
1170  /* optional */ true,
1171  "",
1172  {
1173  {RPCResult::Type::STR, "asm", "The asm"},
1174  {RPCResult::Type::STR, "hex", "The hex"},
1175  }},
1177  "unknown",
1178  "The unknown global fields",
1179  {
1180  {RPCResult::Type::STR_HEX, "key",
1181  "(key-value pair) An unknown key-value pair"},
1182  }},
1183  }},
1184  }},
1186  "outputs",
1187  "",
1188  {
1190  "",
1191  "",
1192  {
1194  "redeem_script",
1195  /* optional */ true,
1196  "",
1197  {
1198  {RPCResult::Type::STR, "asm", "The asm"},
1199  {RPCResult::Type::STR_HEX, "hex", "The hex"},
1200  {RPCResult::Type::STR, "type",
1201  "The type, eg 'pubkeyhash'"},
1202  }},
1204  "bip32_derivs",
1205  /* optional */ true,
1206  "",
1207  {
1209  "",
1210  "",
1211  {
1212  {RPCResult::Type::STR, "pubkey",
1213  "The public key this path corresponds to"},
1214  {RPCResult::Type::STR, "master_fingerprint",
1215  "The fingerprint of the master key"},
1216  {RPCResult::Type::STR, "path", "The path"},
1217  }},
1218  }},
1220  "unknown",
1221  "The unknown global fields",
1222  {
1223  {RPCResult::Type::STR_HEX, "key",
1224  "(key-value pair) An unknown key-value pair"},
1225  }},
1226  }},
1227  }},
1228  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
1229  "The transaction fee paid if all UTXOs slots in the PSBT have "
1230  "been filled."},
1231  }},
1232  RPCExamples{HelpExampleCli("decodepsbt", "\"psbt\"")},
1233  [&](const RPCHelpMan &self, const Config &config,
1234  const JSONRPCRequest &request) -> UniValue {
1235  RPCTypeCheck(request.params, {UniValue::VSTR});
1236 
1237  // Unserialize the transactions
1239  std::string error;
1240  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1242  strprintf("TX decode failed %s", error));
1243  }
1244 
1245  UniValue result(UniValue::VOBJ);
1246 
1247  // Add the decoded tx
1248  UniValue tx_univ(UniValue::VOBJ);
1249  TxToUniv(CTransaction(*psbtx.tx), BlockHash(), tx_univ, false);
1250  result.pushKV("tx", tx_univ);
1251 
1252  // Unknown data
1253  if (psbtx.unknown.size() > 0) {
1254  UniValue unknowns(UniValue::VOBJ);
1255  for (auto entry : psbtx.unknown) {
1256  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1257  }
1258  result.pushKV("unknown", unknowns);
1259  }
1260 
1261  // inputs
1262  Amount total_in = Amount::zero();
1263  bool have_all_utxos = true;
1264  UniValue inputs(UniValue::VARR);
1265  for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
1266  const PSBTInput &input = psbtx.inputs[i];
1268  // UTXOs
1269  if (!input.utxo.IsNull()) {
1270  const CTxOut &txout = input.utxo;
1271 
1272  UniValue out(UniValue::VOBJ);
1273 
1274  out.pushKV("amount", txout.nValue);
1275  if (MoneyRange(txout.nValue) &&
1276  MoneyRange(total_in + txout.nValue)) {
1277  total_in += txout.nValue;
1278  } else {
1279  // Hack to just not show fee later
1280  have_all_utxos = false;
1281  }
1282 
1284  ScriptToUniv(txout.scriptPubKey, o, true);
1285  out.pushKV("scriptPubKey", o);
1286  in.pushKV("utxo", out);
1287  } else {
1288  have_all_utxos = false;
1289  }
1290 
1291  // Partial sigs
1292  if (!input.partial_sigs.empty()) {
1293  UniValue partial_sigs(UniValue::VOBJ);
1294  for (const auto &sig : input.partial_sigs) {
1295  partial_sigs.pushKV(HexStr(sig.second.first),
1296  HexStr(sig.second.second));
1297  }
1298  in.pushKV("partial_signatures", partial_sigs);
1299  }
1300 
1301  // Sighash
1302  uint8_t sighashbyte =
1303  input.sighash_type.getRawSigHashType() & 0xff;
1304  if (sighashbyte > 0) {
1305  in.pushKV("sighash", SighashToStr(sighashbyte));
1306  }
1307 
1308  // Redeem script
1309  if (!input.redeem_script.empty()) {
1311  ScriptToUniv(input.redeem_script, r, false);
1312  in.pushKV("redeem_script", r);
1313  }
1314 
1315  // keypaths
1316  if (!input.hd_keypaths.empty()) {
1317  UniValue keypaths(UniValue::VARR);
1318  for (auto entry : input.hd_keypaths) {
1319  UniValue keypath(UniValue::VOBJ);
1320  keypath.pushKV("pubkey", HexStr(entry.first));
1321 
1322  keypath.pushKV(
1323  "master_fingerprint",
1324  strprintf("%08x",
1325  ReadBE32(entry.second.fingerprint)));
1326  keypath.pushKV("path",
1327  WriteHDKeypath(entry.second.path));
1328  keypaths.push_back(keypath);
1329  }
1330  in.pushKV("bip32_derivs", keypaths);
1331  }
1332 
1333  // Final scriptSig
1334  if (!input.final_script_sig.empty()) {
1335  UniValue scriptsig(UniValue::VOBJ);
1336  scriptsig.pushKV(
1337  "asm", ScriptToAsmStr(input.final_script_sig, true));
1338  scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1339  in.pushKV("final_scriptSig", scriptsig);
1340  }
1341 
1342  // Unknown data
1343  if (input.unknown.size() > 0) {
1344  UniValue unknowns(UniValue::VOBJ);
1345  for (auto entry : input.unknown) {
1346  unknowns.pushKV(HexStr(entry.first),
1347  HexStr(entry.second));
1348  }
1349  in.pushKV("unknown", unknowns);
1350  }
1351 
1352  inputs.push_back(in);
1353  }
1354  result.pushKV("inputs", inputs);
1355 
1356  // outputs
1357  Amount output_value = Amount::zero();
1358  UniValue outputs(UniValue::VARR);
1359  for (size_t i = 0; i < psbtx.outputs.size(); ++i) {
1360  const PSBTOutput &output = psbtx.outputs[i];
1361  UniValue out(UniValue::VOBJ);
1362  // Redeem script
1363  if (!output.redeem_script.empty()) {
1365  ScriptToUniv(output.redeem_script, r, false);
1366  out.pushKV("redeem_script", r);
1367  }
1368 
1369  // keypaths
1370  if (!output.hd_keypaths.empty()) {
1371  UniValue keypaths(UniValue::VARR);
1372  for (auto entry : output.hd_keypaths) {
1373  UniValue keypath(UniValue::VOBJ);
1374  keypath.pushKV("pubkey", HexStr(entry.first));
1375  keypath.pushKV(
1376  "master_fingerprint",
1377  strprintf("%08x",
1378  ReadBE32(entry.second.fingerprint)));
1379  keypath.pushKV("path",
1380  WriteHDKeypath(entry.second.path));
1381  keypaths.push_back(keypath);
1382  }
1383  out.pushKV("bip32_derivs", keypaths);
1384  }
1385 
1386  // Unknown data
1387  if (output.unknown.size() > 0) {
1388  UniValue unknowns(UniValue::VOBJ);
1389  for (auto entry : output.unknown) {
1390  unknowns.pushKV(HexStr(entry.first),
1391  HexStr(entry.second));
1392  }
1393  out.pushKV("unknown", unknowns);
1394  }
1395 
1396  outputs.push_back(out);
1397 
1398  // Fee calculation
1399  if (MoneyRange(psbtx.tx->vout[i].nValue) &&
1400  MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
1401  output_value += psbtx.tx->vout[i].nValue;
1402  } else {
1403  // Hack to just not show fee later
1404  have_all_utxos = false;
1405  }
1406  }
1407  result.pushKV("outputs", outputs);
1408  if (have_all_utxos) {
1409  result.pushKV("fee", total_in - output_value);
1410  }
1411 
1412  return result;
1413  },
1414  };
1415 }
1416 
1418  return RPCHelpMan{
1419  "combinepsbt",
1420  "Combine multiple partially signed Bitcoin transactions into one "
1421  "transaction.\n"
1422  "Implements the Combiner role.\n",
1423  {
1424  {
1425  "txs",
1428  "The base64 strings of partially signed transactions",
1429  {
1431  "A base64 string of a PSBT"},
1432  },
1433  },
1434  },
1436  "The base64-encoded partially signed transaction"},
1438  "combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")},
1439  [&](const RPCHelpMan &self, const Config &config,
1440  const JSONRPCRequest &request) -> UniValue {
1441  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1442 
1443  // Unserialize the transactions
1444  std::vector<PartiallySignedTransaction> psbtxs;
1445  UniValue txs = request.params[0].get_array();
1446  if (txs.empty()) {
1448  "Parameter 'txs' cannot be empty");
1449  }
1450  for (size_t i = 0; i < txs.size(); ++i) {
1452  std::string error;
1453  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1455  strprintf("TX decode failed %s", error));
1456  }
1457  psbtxs.push_back(psbtx);
1458  }
1459 
1460  PartiallySignedTransaction merged_psbt;
1461  const TransactionError error = CombinePSBTs(merged_psbt, psbtxs);
1462  if (error != TransactionError::OK) {
1464  }
1465 
1467  ssTx << merged_psbt;
1468  return EncodeBase64(ssTx);
1469  },
1470  };
1471 }
1472 
1474  return RPCHelpMan{
1475  "finalizepsbt",
1476  "Finalize the inputs of a PSBT. If the transaction is fully signed, it "
1477  "will produce a\n"
1478  "network serialized transaction which can be broadcast with "
1479  "sendrawtransaction. Otherwise a PSBT will be\n"
1480  "created which has the final_scriptSigfields filled for inputs that "
1481  "are complete.\n"
1482  "Implements the Finalizer and Extractor roles.\n",
1483  {
1485  "A base64 string of a PSBT"},
1486  {"extract", RPCArg::Type::BOOL, RPCArg::Default{true},
1487  "If true and the transaction is complete,\n"
1488  " extract and return the complete "
1489  "transaction in normal network serialization instead of the "
1490  "PSBT."},
1491  },
1493  "",
1494  "",
1495  {
1496  {RPCResult::Type::STR, "psbt",
1497  "The base64-encoded partially signed transaction if not "
1498  "extracted"},
1499  {RPCResult::Type::STR_HEX, "hex",
1500  "The hex-encoded network transaction if extracted"},
1501  {RPCResult::Type::BOOL, "complete",
1502  "If the transaction has a complete set of signatures"},
1503  }},
1504  RPCExamples{HelpExampleCli("finalizepsbt", "\"psbt\"")},
1505  [&](const RPCHelpMan &self, const Config &config,
1506  const JSONRPCRequest &request) -> UniValue {
1507  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL},
1508  true);
1509 
1510  // Unserialize the transactions
1512  std::string error;
1513  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1515  strprintf("TX decode failed %s", error));
1516  }
1517 
1518  bool extract =
1519  request.params[1].isNull() ||
1520  (!request.params[1].isNull() && request.params[1].get_bool());
1521 
1522  CMutableTransaction mtx;
1523  bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1524 
1525  UniValue result(UniValue::VOBJ);
1527  std::string result_str;
1528 
1529  if (complete && extract) {
1530  ssTx << mtx;
1531  result_str = HexStr(ssTx);
1532  result.pushKV("hex", result_str);
1533  } else {
1534  ssTx << psbtx;
1535  result_str = EncodeBase64(ssTx.str());
1536  result.pushKV("psbt", result_str);
1537  }
1538  result.pushKV("complete", complete);
1539 
1540  return result;
1541  },
1542  };
1543 }
1544 
1546  return RPCHelpMan{
1547  "createpsbt",
1548  "Creates a transaction in the Partially Signed Transaction format.\n"
1549  "Implements the Creator role.\n",
1550  {
1551  {
1552  "inputs",
1555  "The json objects",
1556  {
1557  {
1558  "",
1561  "",
1562  {
1563  {"txid", RPCArg::Type::STR_HEX,
1564  RPCArg::Optional::NO, "The transaction id"},
1566  "The output number"},
1567  {"sequence", RPCArg::Type::NUM,
1568  RPCArg::DefaultHint{"depends on the value of the "
1569  "'locktime' argument"},
1570  "The sequence number"},
1571  },
1572  },
1573  },
1574  },
1575  {
1576  "outputs",
1579  "The outputs (key-value pairs), where none of "
1580  "the keys are duplicated.\n"
1581  "That is, each address can only appear once and there can only "
1582  "be one 'data' object.\n"
1583  "For compatibility reasons, a dictionary, which holds the "
1584  "key-value pairs directly, is also\n"
1585  " accepted as second parameter.",
1586  {
1587  {
1588  "",
1591  "",
1592  {
1593  {"address", RPCArg::Type::AMOUNT,
1595  "A key-value pair. The key (string) is the "
1596  "bitcoin address, the value (float or string) is "
1597  "the amount in " +
1598  Currency::get().ticker},
1599  },
1600  },
1601  {
1602  "",
1605  "",
1606  {
1607  {"data", RPCArg::Type::STR_HEX,
1609  "A key-value pair. The key must be \"data\", the "
1610  "value is hex-encoded data"},
1611  },
1612  },
1613  },
1614  },
1615  {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
1616  "Raw locktime. Non-0 value also locktime-activates inputs"},
1617  },
1619  "The resulting raw transaction (base64-encoded string)"},
1621  "createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1622  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
1623  [&](const RPCHelpMan &self, const Config &config,
1624  const JSONRPCRequest &request) -> UniValue {
1625  RPCTypeCheck(request.params,
1626  {
1627  UniValue::VARR,
1628  UniValueType(), // ARR or OBJ, checked later
1629  UniValue::VNUM,
1630  },
1631  true);
1632 
1633  CMutableTransaction rawTx =
1634  ConstructTransaction(config.GetChainParams(), request.params[0],
1635  request.params[1], request.params[2]);
1636 
1637  // Make a blank psbt
1639  psbtx.tx = rawTx;
1640  for (size_t i = 0; i < rawTx.vin.size(); ++i) {
1641  psbtx.inputs.push_back(PSBTInput());
1642  }
1643  for (size_t i = 0; i < rawTx.vout.size(); ++i) {
1644  psbtx.outputs.push_back(PSBTOutput());
1645  }
1646 
1647  // Serialize the PSBT
1649  ssTx << psbtx;
1650 
1651  return EncodeBase64(ssTx);
1652  },
1653  };
1654 }
1655 
1657  return RPCHelpMan{
1658  "converttopsbt",
1659  "Converts a network serialized transaction to a PSBT. "
1660  "This should be used only with createrawtransaction and "
1661  "fundrawtransaction\n"
1662  "createpsbt and walletcreatefundedpsbt should be used for new "
1663  "applications.\n",
1664  {
1666  "The hex string of a raw transaction"},
1667  {"permitsigdata", RPCArg::Type::BOOL, RPCArg::Default{false},
1668  "If true, any signatures in the input will be discarded and "
1669  "conversion.\n"
1670  " will continue. If false, RPC will "
1671  "fail if any signatures are present."},
1672  },
1674  "The resulting raw transaction (base64-encoded string)"},
1675  RPCExamples{
1676  "\nCreate a transaction\n" +
1677  HelpExampleCli("createrawtransaction",
1678  "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1679  "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1680  "\nConvert the transaction to a PSBT\n" +
1681  HelpExampleCli("converttopsbt", "\"rawtransaction\"")},
1682  [&](const RPCHelpMan &self, const Config &config,
1683  const JSONRPCRequest &request) -> UniValue {
1684  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL},
1685  true);
1686 
1687  // parse hex string from parameter
1689  bool permitsigdata = request.params[1].isNull()
1690  ? false
1691  : request.params[1].get_bool();
1692  if (!DecodeHexTx(tx, request.params[0].get_str())) {
1694  "TX decode failed");
1695  }
1696 
1697  // Remove all scriptSigs from inputs
1698  for (CTxIn &input : tx.vin) {
1699  if (!input.scriptSig.empty() && !permitsigdata) {
1701  "Inputs must not have scriptSigs");
1702  }
1703  input.scriptSig.clear();
1704  }
1705 
1706  // Make a blank psbt
1708  psbtx.tx = tx;
1709  for (size_t i = 0; i < tx.vin.size(); ++i) {
1710  psbtx.inputs.push_back(PSBTInput());
1711  }
1712  for (size_t i = 0; i < tx.vout.size(); ++i) {
1713  psbtx.outputs.push_back(PSBTOutput());
1714  }
1715 
1716  // Serialize the PSBT
1718  ssTx << psbtx;
1719 
1720  return EncodeBase64(ssTx);
1721  },
1722  };
1723 }
1724 
1726  return RPCHelpMan{
1727  "utxoupdatepsbt",
1728  "Updates all inputs and outputs in a PSBT with data from output "
1729  "descriptors, the UTXO set or the mempool.\n",
1730  {
1732  "A base64 string of a PSBT"},
1733  {"descriptors",
1736  "An array of either strings or objects",
1737  {
1739  "An output descriptor"},
1740  {"",
1743  "An object with an output descriptor and extra information",
1744  {
1746  "An output descriptor"},
1747  {"range", RPCArg::Type::RANGE, RPCArg::Default{1000},
1748  "Up to what index HD chains should be explored (either "
1749  "end or [begin,end])"},
1750  }},
1751  }},
1752  },
1754  "The base64-encoded partially signed transaction with inputs "
1755  "updated"},
1756  RPCExamples{HelpExampleCli("utxoupdatepsbt", "\"psbt\"")},
1757  [&](const RPCHelpMan &self, const Config &config,
1758  const JSONRPCRequest &request) -> UniValue {
1759  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR},
1760  true);
1761 
1762  // Unserialize the transactions
1764  std::string error;
1765  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1767  strprintf("TX decode failed %s", error));
1768  }
1769 
1770  // Parse descriptors, if any.
1771  FlatSigningProvider provider;
1772  if (!request.params[1].isNull()) {
1773  auto descs = request.params[1].get_array();
1774  for (size_t i = 0; i < descs.size(); ++i) {
1775  EvalDescriptorStringOrObject(descs[i], provider);
1776  }
1777  }
1778  // We don't actually need private keys further on; hide them as a
1779  // precaution.
1780  HidingSigningProvider public_provider(&provider, /* nosign */ true,
1781  /* nobip32derivs */ false);
1782 
1783  // Fetch previous transactions (inputs):
1784  CCoinsView viewDummy;
1785  CCoinsViewCache view(&viewDummy);
1786  {
1787  NodeContext &node = EnsureAnyNodeContext(request.context);
1788  const CTxMemPool &mempool = EnsureMemPool(node);
1789  ChainstateManager &chainman = EnsureChainman(node);
1790  LOCK2(cs_main, mempool.cs);
1791  CCoinsViewCache &viewChain =
1792  chainman.ActiveChainstate().CoinsTip();
1793  CCoinsViewMemPool viewMempool(&viewChain, mempool);
1794  // temporarily switch cache backend to db+mempool view
1795  view.SetBackend(viewMempool);
1796 
1797  for (const CTxIn &txin : psbtx.tx->vin) {
1798  // Load entries from viewChain into view; can fail.
1799  view.AccessCoin(txin.prevout);
1800  }
1801 
1802  // switch back to avoid locking mempool for too long
1803  view.SetBackend(viewDummy);
1804  }
1805 
1806  // Fill the inputs
1807  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
1808  PSBTInput &input = psbtx.inputs.at(i);
1809 
1810  if (!input.utxo.IsNull()) {
1811  continue;
1812  }
1813 
1814  // Update script/keypath information using descriptor data.
1815  // Note that SignPSBTInput does a lot more than just
1816  // constructing ECDSA signatures we don't actually care about
1817  // those here, in fact.
1818  SignPSBTInput(public_provider, psbtx, i,
1819  /* sighash_type */ SigHashType().withForkId());
1820  }
1821 
1822  // Update script/keypath information using descriptor data.
1823  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1824  UpdatePSBTOutput(public_provider, psbtx, i);
1825  }
1826 
1828  ssTx << psbtx;
1829  return EncodeBase64(ssTx);
1830  },
1831  };
1832 }
1833 
1835  return RPCHelpMan{
1836  "joinpsbts",
1837  "Joins multiple distinct PSBTs with different inputs and outputs "
1838  "into one PSBT with inputs and outputs from all of the PSBTs\n"
1839  "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1840  {{"txs",
1843  "The base64 strings of partially signed transactions",
1845  "A base64 string of a PSBT"}}}},
1847  "The base64-encoded partially signed transaction"},
1848  RPCExamples{HelpExampleCli("joinpsbts", "\"psbt\"")},
1849  [&](const RPCHelpMan &self, const Config &config,
1850  const JSONRPCRequest &request) -> UniValue {
1851  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1852 
1853  // Unserialize the transactions
1854  std::vector<PartiallySignedTransaction> psbtxs;
1855  UniValue txs = request.params[0].get_array();
1856 
1857  if (txs.size() <= 1) {
1858  throw JSONRPCError(
1860  "At least two PSBTs are required to join PSBTs.");
1861  }
1862 
1863  uint32_t best_version = 1;
1864  uint32_t best_locktime = 0xffffffff;
1865  for (size_t i = 0; i < txs.size(); ++i) {
1867  std::string error;
1868  if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1870  strprintf("TX decode failed %s", error));
1871  }
1872  psbtxs.push_back(psbtx);
1873  // Choose the highest version number
1874  if (static_cast<uint32_t>(psbtx.tx->nVersion) > best_version) {
1875  best_version = static_cast<uint32_t>(psbtx.tx->nVersion);
1876  }
1877  // Choose the lowest lock time
1878  if (psbtx.tx->nLockTime < best_locktime) {
1879  best_locktime = psbtx.tx->nLockTime;
1880  }
1881  }
1882 
1883  // Create a blank psbt where everything will be added
1884  PartiallySignedTransaction merged_psbt;
1885  merged_psbt.tx = CMutableTransaction();
1886  merged_psbt.tx->nVersion = static_cast<int32_t>(best_version);
1887  merged_psbt.tx->nLockTime = best_locktime;
1888 
1889  // Merge
1890  for (auto &psbt : psbtxs) {
1891  for (size_t i = 0; i < psbt.tx->vin.size(); ++i) {
1892  if (!merged_psbt.AddInput(psbt.tx->vin[i],
1893  psbt.inputs[i])) {
1894  throw JSONRPCError(
1896  strprintf("Input %s:%d exists in multiple PSBTs",
1897  psbt.tx->vin[i]
1898  .prevout.GetTxId()
1899  .ToString()
1900  .c_str(),
1901  psbt.tx->vin[i].prevout.GetN()));
1902  }
1903  }
1904  for (size_t i = 0; i < psbt.tx->vout.size(); ++i) {
1905  merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1906  }
1907  merged_psbt.unknown.insert(psbt.unknown.begin(),
1908  psbt.unknown.end());
1909  }
1910 
1911  // Generate list of shuffled indices for shuffling inputs and
1912  // outputs of the merged PSBT
1913  std::vector<int> input_indices(merged_psbt.inputs.size());
1914  std::iota(input_indices.begin(), input_indices.end(), 0);
1915  std::vector<int> output_indices(merged_psbt.outputs.size());
1916  std::iota(output_indices.begin(), output_indices.end(), 0);
1917 
1918  // Shuffle input and output indices lists
1919  Shuffle(input_indices.begin(), input_indices.end(),
1920  FastRandomContext());
1921  Shuffle(output_indices.begin(), output_indices.end(),
1922  FastRandomContext());
1923 
1924  PartiallySignedTransaction shuffled_psbt;
1925  shuffled_psbt.tx = CMutableTransaction();
1926  shuffled_psbt.tx->nVersion = merged_psbt.tx->nVersion;
1927  shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1928  for (int i : input_indices) {
1929  shuffled_psbt.AddInput(merged_psbt.tx->vin[i],
1930  merged_psbt.inputs[i]);
1931  }
1932  for (int i : output_indices) {
1933  shuffled_psbt.AddOutput(merged_psbt.tx->vout[i],
1934  merged_psbt.outputs[i]);
1935  }
1936  shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(),
1937  merged_psbt.unknown.end());
1938 
1940  ssTx << shuffled_psbt;
1941  return EncodeBase64(ssTx);
1942  },
1943  };
1944 }
1945 
1947  return RPCHelpMan{
1948  "analyzepsbt",
1949  "Analyzes and provides information about the current status of a "
1950  "PSBT and its inputs\n",
1952  "A base64 string of a PSBT"}},
1953  RPCResult{
1955  "",
1956  "",
1957  {
1959  "inputs",
1960  "",
1961  {
1963  "",
1964  "",
1965  {
1966  {RPCResult::Type::BOOL, "has_utxo",
1967  "Whether a UTXO is provided"},
1968  {RPCResult::Type::BOOL, "is_final",
1969  "Whether the input is finalized"},
1971  "missing",
1972  /* optional */ true,
1973  "Things that are missing that are required to "
1974  "complete this input",
1975  {
1977  "pubkeys",
1978  /* optional */ true,
1979  "",
1980  {
1981  {RPCResult::Type::STR_HEX, "keyid",
1982  "Public key ID, hash160 of the public "
1983  "key, of a public key whose BIP 32 "
1984  "derivation path is missing"},
1985  }},
1987  "signatures",
1988  /* optional */ true,
1989  "",
1990  {
1991  {RPCResult::Type::STR_HEX, "keyid",
1992  "Public key ID, hash160 of the public "
1993  "key, of a public key whose signature is "
1994  "missing"},
1995  }},
1996  {RPCResult::Type::STR_HEX, "redeemscript",
1997  /* optional */ true,
1998  "Hash160 of the redeemScript that is missing"},
1999  }},
2000  {RPCResult::Type::STR, "next", /* optional */ true,
2001  "Role of the next person that this input needs to "
2002  "go to"},
2003  }},
2004  }},
2005  {RPCResult::Type::NUM, "estimated_vsize", /* optional */ true,
2006  "Estimated vsize of the final signed transaction"},
2007  {RPCResult::Type::STR_AMOUNT, "estimated_feerate",
2008  /* optional */ true,
2009  "Estimated feerate of the final signed transaction in " +
2010  Currency::get().ticker +
2011  "/kB. Shown only if all UTXO slots in the PSBT have been "
2012  "filled"},
2013  {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
2014  "The transaction fee paid. Shown only if all UTXO slots in "
2015  "the PSBT have been filled"},
2016  {RPCResult::Type::STR, "next",
2017  "Role of the next person that this psbt needs to go to"},
2018  {RPCResult::Type::STR, "error", /* optional */ true,
2019  "Error message (if there is one)"},
2020  }},
2021  RPCExamples{HelpExampleCli("analyzepsbt", "\"psbt\"")},
2022  [&](const RPCHelpMan &self, const Config &config,
2023  const JSONRPCRequest &request) -> UniValue {
2024  RPCTypeCheck(request.params, {UniValue::VSTR});
2025 
2026  // Unserialize the transaction
2028  std::string error;
2029  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
2031  strprintf("TX decode failed %s", error));
2032  }
2033 
2034  PSBTAnalysis psbta = AnalyzePSBT(psbtx);
2035 
2036  UniValue result(UniValue::VOBJ);
2037  UniValue inputs_result(UniValue::VARR);
2038  for (const auto &input : psbta.inputs) {
2039  UniValue input_univ(UniValue::VOBJ);
2040  UniValue missing(UniValue::VOBJ);
2041 
2042  input_univ.pushKV("has_utxo", input.has_utxo);
2043  input_univ.pushKV("is_final", input.is_final);
2044  input_univ.pushKV("next", PSBTRoleName(input.next));
2045 
2046  if (!input.missing_pubkeys.empty()) {
2047  UniValue missing_pubkeys_univ(UniValue::VARR);
2048  for (const CKeyID &pubkey : input.missing_pubkeys) {
2049  missing_pubkeys_univ.push_back(HexStr(pubkey));
2050  }
2051  missing.pushKV("pubkeys", missing_pubkeys_univ);
2052  }
2053  if (!input.missing_redeem_script.IsNull()) {
2054  missing.pushKV("redeemscript",
2055  HexStr(input.missing_redeem_script));
2056  }
2057  if (!input.missing_sigs.empty()) {
2058  UniValue missing_sigs_univ(UniValue::VARR);
2059  for (const CKeyID &pubkey : input.missing_sigs) {
2060  missing_sigs_univ.push_back(HexStr(pubkey));
2061  }
2062  missing.pushKV("signatures", missing_sigs_univ);
2063  }
2064  if (!missing.getKeys().empty()) {
2065  input_univ.pushKV("missing", missing);
2066  }
2067  inputs_result.push_back(input_univ);
2068  }
2069  if (!inputs_result.empty()) {
2070  result.pushKV("inputs", inputs_result);
2071  }
2072  if (psbta.estimated_vsize != std::nullopt) {
2073  result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
2074  }
2075  if (psbta.estimated_feerate != std::nullopt) {
2076  result.pushKV("estimated_feerate",
2077  psbta.estimated_feerate->GetFeePerK());
2078  }
2079  if (psbta.fee != std::nullopt) {
2080  result.pushKV("fee", *psbta.fee);
2081  }
2082  result.pushKV("next", PSBTRoleName(psbta.next));
2083  if (!psbta.error.empty()) {
2084  result.pushKV("error", psbta.error);
2085  }
2086 
2087  return result;
2088  },
2089  };
2090 }
2091 
2093  // clang-format off
2094  static const CRPCCommand commands[] = {
2095  // category actor (function)
2096  // ------------------ ----------------------
2097  { "rawtransactions", getrawtransaction, },
2098  { "rawtransactions", createrawtransaction, },
2099  { "rawtransactions", decoderawtransaction, },
2100  { "rawtransactions", decodescript, },
2101  { "rawtransactions", sendrawtransaction, },
2102  { "rawtransactions", combinerawtransaction, },
2103  { "rawtransactions", signrawtransactionwithkey, },
2104  { "rawtransactions", testmempoolaccept, },
2105  { "rawtransactions", decodepsbt, },
2106  { "rawtransactions", combinepsbt, },
2107  { "rawtransactions", finalizepsbt, },
2108  { "rawtransactions", createpsbt, },
2109  { "rawtransactions", converttopsbt, },
2110  { "rawtransactions", utxoupdatepsbt, },
2111  { "rawtransactions", joinpsbts, },
2112  { "rawtransactions", analyzepsbt, },
2113  };
2114  // clang-format on
2115  for (const auto &c : commands) {
2116  t.appendCommand(c.name, &c);
2117  }
2118 }
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:26
int64_t GetBlockTime() const
Definition: blockindex.h:178
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:192
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:172
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
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:589
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:183
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:330
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:628
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:737
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:701
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1142
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1348
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:1270
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: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
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:234
@ 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: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
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
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
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
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:32
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:491
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:57
@ 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:119
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:24
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:175
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:358
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:80
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:1060
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:192
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:20
std::string GetAllOutputTypes()
Definition: util.cpp:330
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:98
#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:606
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:50
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:87
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].
@ 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
Definition: util.h:173
@ 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: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
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
#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:17
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