Bitcoin ABC 0.32.12
P2P Digital Currency
rawtransaction.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2016 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <chain.h>
7#include <chainparams.h>
8#include <coins.h>
9#include <config.h>
10#include <consensus/amount.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>
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>
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/strencodings.h>
39#include <util/string.h>
40#include <util/vector.h>
41#include <validation.h>
42#include <validationinterface.h>
43
44#include <cstdint>
45#include <numeric>
46
47#include <univalue.h>
48
50using node::FindCoins;
54
55static void TxToJSON(const CTransaction &tx, const BlockHash &hashBlock,
56 UniValue &entry, Chainstate &active_chainstate) {
57 // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
58 //
59 // Blockchain contextual information (confirmations and blocktime) is not
60 // available to code in bitcoin-common, so we query them here and push the
61 // data into the returned UniValue.
62 TxToUniv(tx, BlockHash(), entry, true);
63
64 if (!hashBlock.IsNull()) {
66
67 entry.pushKV("blockhash", hashBlock.GetHex());
68 const CBlockIndex *pindex =
69 active_chainstate.m_blockman.LookupBlockIndex(hashBlock);
70 if (pindex) {
71 if (active_chainstate.m_chain.Contains(pindex)) {
72 entry.pushKV("confirmations",
73 1 + active_chainstate.m_chain.Height() -
74 pindex->nHeight);
75 entry.pushKV("time", pindex->GetBlockTime());
76 entry.pushKV("blocktime", pindex->GetBlockTime());
77 } else {
78 entry.pushKV("confirmations", 0);
79 }
80 }
81 }
82}
83
85 return RPCHelpMan{
86 "getrawtransaction",
87 "Return the raw transaction data.\n"
88 "\nBy default, this call only returns a transaction if it is in the "
89 "mempool. If -txindex is enabled\n"
90 "and no blockhash argument is passed, it will return the transaction "
91 "if it is in the mempool or any block.\n"
92 "If a blockhash argument is passed, it will return the transaction if\n"
93 "the specified block is available and the transaction is in that "
94 "block.\n"
95 "\nIf verbose is 'true', returns an Object with information about "
96 "'txid'.\n"
97 "If verbose is 'false' or omitted, returns a string that is "
98 "serialized, hex-encoded data for 'txid'.",
99 {
101 "The transaction id"},
102 // Verbose is a boolean, but we accept an int for backward
103 // compatibility
104 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false},
105 "If false, return a string, otherwise return a json object",
108 "The block in which to look for the transaction"},
109 },
110 {
111 RPCResult{"if verbose is not set or set to false",
112 RPCResult::Type::STR, "data",
113 "The serialized, hex-encoded data for 'txid'"},
114 RPCResult{
115 "if verbose is set to true",
117 "",
118 "",
119 Cat<std::vector<RPCResult>>(
120 {
121 {RPCResult::Type::BOOL, "in_active_chain",
122 "Whether specified block is in the active chain or "
123 "not "
124 "(only present with explicit \"blockhash\" argument)"},
125 {RPCResult::Type::STR_HEX, "blockhash",
126 "the block hash"},
127 {RPCResult::Type::NUM, "confirmations",
128 "The confirmations"},
129 {RPCResult::Type::NUM_TIME, "blocktime",
130 "The block time expressed in " + UNIX_EPOCH_TIME},
131 {RPCResult::Type::NUM, "time", "Same as \"blocktime\""},
133 "The serialized, hex-encoded data for 'txid'"},
134 },
135 DecodeTxDoc(/*txid_field_doc=*/"The transaction id (same "
136 "as provided)",
137 /*wallet=*/false)),
138 },
139 },
140 RPCExamples{HelpExampleCli("getrawtransaction", "\"mytxid\"") +
141 HelpExampleCli("getrawtransaction", "\"mytxid\" true") +
142 HelpExampleRpc("getrawtransaction", "\"mytxid\", true") +
143 HelpExampleCli("getrawtransaction",
144 "\"mytxid\" false \"myblockhash\"") +
145 HelpExampleCli("getrawtransaction",
146 "\"mytxid\" true \"myblockhash\"")},
147 [&](const RPCHelpMan &self, const Config &config,
148 const JSONRPCRequest &request) -> UniValue {
149 const NodeContext &node = EnsureAnyNodeContext(request.context);
151
152 bool in_active_chain = true;
153 TxId txid = TxId(ParseHashV(request.params[0], "parameter 1"));
154 const CBlockIndex *blockindex = nullptr;
155
156 const CChainParams &params = config.GetChainParams();
157 if (txid == params.GenesisBlock().hashMerkleRoot) {
158 // Special exception for the genesis block coinbase transaction
159 throw JSONRPCError(
161 "The genesis block coinbase is not considered an "
162 "ordinary transaction and cannot be retrieved");
163 }
164
165 // Accept either a bool (true) or a num (>=1) to indicate verbose
166 // output.
167 bool fVerbose = false;
168 if (!request.params[1].isNull()) {
169 fVerbose = request.params[1].isNum()
170 ? (request.params[1].getInt<int>() != 0)
171 : request.params[1].get_bool();
172 }
173
174 if (!request.params[2].isNull()) {
175 LOCK(cs_main);
176
177 BlockHash blockhash(
178 ParseHashV(request.params[2], "parameter 3"));
179 blockindex = chainman.m_blockman.LookupBlockIndex(blockhash);
180 if (!blockindex) {
182 "Block hash not found");
183 }
184 in_active_chain = chainman.ActiveChain().Contains(blockindex);
185 }
186
187 bool f_txindex_ready = false;
188 if (g_txindex && !blockindex) {
189 f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
190 }
191
192 BlockHash hash_block;
193 const CTransactionRef tx =
194 GetTransaction(blockindex, node.mempool.get(), txid, hash_block,
195 chainman.m_blockman);
196 if (!tx) {
197 std::string errmsg;
198 if (blockindex) {
200 return !blockindex->nStatus.hasData())) {
202 "Block not available");
203 }
204 errmsg = "No such transaction found in the provided block";
205 } else if (!g_txindex) {
206 errmsg =
207 "No such mempool transaction. Use -txindex or provide "
208 "a block hash to enable blockchain transaction queries";
209 } else if (!f_txindex_ready) {
210 errmsg = "No such mempool transaction. Blockchain "
211 "transactions are still in the process of being "
212 "indexed";
213 } else {
214 errmsg = "No such mempool or blockchain transaction";
215 }
216 throw JSONRPCError(
218 errmsg + ". Use gettransaction for wallet transactions.");
219 }
220
221 if (!fVerbose) {
222 return EncodeHexTx(*tx);
223 }
224
225 UniValue result(UniValue::VOBJ);
226 if (blockindex) {
227 result.pushKV("in_active_chain", in_active_chain);
228 }
229 TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
230 return result;
231 },
232 };
233}
234
236 return RPCHelpMan{
237 "createrawtransaction",
238 "Create a transaction spending the given inputs and creating new "
239 "outputs.\n"
240 "Outputs can be addresses or data.\n"
241 "Returns hex-encoded raw transaction.\n"
242 "Note that the transaction's inputs are not signed, and\n"
243 "it is not stored in the wallet or transmitted to the network.\n",
244 {
245 {
246 "inputs",
249 "The inputs",
250 {
251 {
252 "",
255 "",
256 {
257 {"txid", RPCArg::Type::STR_HEX,
258 RPCArg::Optional::NO, "The transaction id"},
260 "The output number"},
261 {"sequence", RPCArg::Type::NUM,
262 RPCArg::DefaultHint{"depends on the value of the "
263 "'locktime' argument"},
264 "The sequence number"},
265 },
266 },
267 },
268 },
269 {"outputs",
272 "The outputs (key-value pairs), where none of "
273 "the keys are duplicated.\n"
274 "That is, each address can only appear once and there can only "
275 "be one 'data' object.\n"
276 "For compatibility reasons, a dictionary, which holds the "
277 "key-value pairs directly, is also\n"
278 " accepted as second parameter.",
279 {
280 {
281 "",
284 "",
285 {
287 "A key-value pair. The key (string) is the "
288 "bitcoin address, the value (float or string) is "
289 "the amount in " +
291 },
292 },
293 {
294 "",
297 "",
298 {
300 "A key-value pair. The key must be \"data\", the "
301 "value is hex-encoded data"},
302 },
303 },
304 },
306 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
307 "Raw locktime. Non-0 value also locktime-activates inputs"},
308 },
309 RPCResult{RPCResult::Type::STR_HEX, "transaction",
310 "hex string of the transaction"},
312 HelpExampleCli("createrawtransaction",
313 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
314 "\" \"[{\\\"address\\\":10000.00}]\"") +
315 HelpExampleCli("createrawtransaction",
316 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
317 "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
318 HelpExampleRpc("createrawtransaction",
319 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
320 "\", \"[{\\\"address\\\":10000.00}]\"") +
321 HelpExampleRpc("createrawtransaction",
322 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
323 "\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
324 [&](const RPCHelpMan &self, const Config &config,
325 const JSONRPCRequest &request) -> UniValue {
326 CMutableTransaction rawTx =
327 ConstructTransaction(config.GetChainParams(), request.params[0],
328 request.params[1], request.params[2]);
329
330 return EncodeHexTx(CTransaction(rawTx));
331 },
332 };
333}
334
336 return RPCHelpMan{
337 "decoderawtransaction",
338 "Return a JSON object representing the serialized, hex-encoded "
339 "transaction.\n",
340 {
342 "The transaction hex string"},
343 },
344 RPCResult{
346 "",
347 "",
348 DecodeTxDoc(/*txid_field_doc=*/"The transaction id",
349 /*wallet=*/false),
350 },
351 RPCExamples{HelpExampleCli("decoderawtransaction", "\"hexstring\"") +
352 HelpExampleRpc("decoderawtransaction", "\"hexstring\"")},
353 [&](const RPCHelpMan &self, const Config &config,
354 const JSONRPCRequest &request) -> UniValue {
356
357 if (!DecodeHexTx(mtx, request.params[0].get_str())) {
359 "TX decode failed");
360 }
361
362 UniValue result(UniValue::VOBJ);
363 TxToUniv(CTransaction(std::move(mtx)), BlockHash(), result, false);
364
365 return result;
366 },
367 };
368}
369
371 return RPCHelpMan{
372 "decodescript",
373 "Decode a hex-encoded script.\n",
374 {
376 "the hex-encoded script"},
377 },
378 RPCResult{
380 "",
381 "",
382 {
383 {RPCResult::Type::STR, "asm", "Script public key"},
384 {RPCResult::Type::STR, "type",
385 "The output type (e.g. " + GetAllOutputTypes() + ")"},
386 {RPCResult::Type::NUM, "reqSigs", "The required signatures"},
388 "addresses",
389 "",
390 {
391 {RPCResult::Type::STR, "address", "bitcoin address"},
392 }},
393 {RPCResult::Type::STR, "p2sh",
394 "address of P2SH script wrapping this redeem script (not "
395 "returned if the script is already a P2SH)"},
396 }},
397 RPCExamples{HelpExampleCli("decodescript", "\"hexstring\"") +
398 HelpExampleRpc("decodescript", "\"hexstring\"")},
399 [&](const RPCHelpMan &self, const Config &config,
400 const JSONRPCRequest &request) -> UniValue {
402 CScript script;
403 if (request.params[0].get_str().size() > 0) {
404 std::vector<uint8_t> scriptData(
405 ParseHexV(request.params[0], "argument"));
406 script = CScript(scriptData.begin(), scriptData.end());
407 } else {
408 // Empty scripts are valid.
409 }
410
411 ScriptPubKeyToUniv(script, r, /* fIncludeHex */ false);
412
413 UniValue type;
414 type = r.find_value("type");
415
416 if (type.isStr() && type.get_str() != "scripthash") {
417 // P2SH cannot be wrapped in a P2SH. If this script is already a
418 // P2SH, don't return the address for a P2SH of the P2SH.
419 r.pushKV("p2sh", EncodeDestination(ScriptHash(script), config));
420 }
421
422 return r;
423 },
424 };
425}
426
428 return RPCHelpMan{
429 "combinerawtransaction",
430 "Combine multiple partially signed transactions into one "
431 "transaction.\n"
432 "The combined transaction may be another partially signed transaction "
433 "or a \n"
434 "fully signed transaction.",
435 {
436 {
437 "txs",
440 "The hex strings of partially signed "
441 "transactions",
442 {
443 {"hexstring", RPCArg::Type::STR_HEX,
445 "A hex-encoded raw transaction"},
446 },
447 },
448 },
450 "The hex-encoded raw transaction with signature(s)"},
451 RPCExamples{HelpExampleCli("combinerawtransaction",
452 R"('["myhex1", "myhex2", "myhex3"]')")},
453 [&](const RPCHelpMan &self, const Config &config,
454 const JSONRPCRequest &request) -> UniValue {
455 const UniValue &txs = request.params[0].get_array();
456 std::vector<CMutableTransaction> txVariants(txs.size());
457
458 for (unsigned int idx = 0; idx < txs.size(); idx++) {
459 if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
460 throw JSONRPCError(
462 strprintf("TX decode failed for tx %d", idx));
463 }
464 }
465
466 if (txVariants.empty()) {
468 "Missing transactions");
469 }
470
471 // mergedTx will end up with all the signatures; it
472 // starts as a clone of the rawtx:
473 CMutableTransaction mergedTx(txVariants[0]);
474
475 // Fetch previous transactions (inputs):
476 CCoinsView viewDummy;
477 CCoinsViewCache view(&viewDummy);
478 {
479 NodeContext &node = EnsureAnyNodeContext(request.context);
480 const CTxMemPool &mempool = EnsureMemPool(node);
482 LOCK2(cs_main, mempool.cs);
483 CCoinsViewCache &viewChain =
484 chainman.ActiveChainstate().CoinsTip();
485 CCoinsViewMemPool viewMempool(&viewChain, mempool);
486 // temporarily switch cache backend to db+mempool view
487 view.SetBackend(viewMempool);
488
489 for (const CTxIn &txin : mergedTx.vin) {
490 // Load entries from viewChain into view; can fail.
491 view.AccessCoin(txin.prevout);
492 }
493
494 // switch back to avoid locking mempool for too long
495 view.SetBackend(viewDummy);
496 }
497
498 // Use CTransaction for the constant parts of the
499 // transaction to avoid rehashing.
500 const CTransaction txConst(mergedTx);
501 // Sign what we can:
502 for (size_t i = 0; i < mergedTx.vin.size(); i++) {
503 CTxIn &txin = mergedTx.vin[i];
504 const Coin &coin = view.AccessCoin(txin.prevout);
505 if (coin.IsSpent()) {
507 "Input not found or already spent");
508 }
509 SignatureData sigdata;
510
511 const CTxOut &txout = coin.GetTxOut();
512
513 // ... and merge in other signatures:
514 for (const CMutableTransaction &txv : txVariants) {
515 if (txv.vin.size() > i) {
516 sigdata.MergeSignatureData(
517 DataFromTransaction(txv, i, txout));
518 }
519 }
522 &mergedTx, i, txout.nValue),
523 txout.scriptPubKey, sigdata);
524
525 UpdateInput(txin, sigdata);
526 }
527
528 return EncodeHexTx(CTransaction(mergedTx));
529 },
530 };
531}
532
534 return RPCHelpMan{
535 "signrawtransactionwithkey",
536 "Sign inputs for raw transaction (serialized, hex-encoded).\n"
537 "The second argument is an array of base58-encoded private\n"
538 "keys that will be the only keys used to sign the transaction.\n"
539 "The third optional argument (may be null) is an array of previous "
540 "transaction outputs that\n"
541 "this transaction depends on but may not yet be in the block chain.\n",
542 {
544 "The transaction hex string"},
545 {
546 "privkeys",
549 "The base58-encoded private keys for signing",
550 {
552 "private key in base58-encoding"},
553 },
554 },
555 {
556 "prevtxs",
559 "The previous dependent transaction outputs",
560 {
561 {
562 "",
565 "",
566 {
567 {"txid", RPCArg::Type::STR_HEX,
568 RPCArg::Optional::NO, "The transaction id"},
570 "The output number"},
571 {"scriptPubKey", RPCArg::Type::STR_HEX,
572 RPCArg::Optional::NO, "script key"},
573 {"redeemScript", RPCArg::Type::STR_HEX,
575 "(required for P2SH) redeem script"},
576 {"amount", RPCArg::Type::AMOUNT,
577 RPCArg::Optional::NO, "The amount spent"},
578 },
579 },
580 },
581 },
582 {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"ALL|FORKID"},
583 "The signature hash type. Must be one of:\n"
584 " \"ALL|FORKID\"\n"
585 " \"NONE|FORKID\"\n"
586 " \"SINGLE|FORKID\"\n"
587 " \"ALL|FORKID|ANYONECANPAY\"\n"
588 " \"NONE|FORKID|ANYONECANPAY\"\n"
589 " \"SINGLE|FORKID|ANYONECANPAY\""},
590 },
591 RPCResult{
593 "",
594 "",
595 {
597 "The hex-encoded raw transaction with signature(s)"},
598 {RPCResult::Type::BOOL, "complete",
599 "If the transaction has a complete set of signatures"},
601 "errors",
602 /* optional */ true,
603 "Script verification errors (if there are any)",
604 {
606 "",
607 "",
608 {
610 "The hash of the referenced, previous transaction"},
611 {RPCResult::Type::NUM, "vout",
612 "The index of the output to spent and used as "
613 "input"},
614 {RPCResult::Type::STR_HEX, "scriptSig",
615 "The hex-encoded signature script"},
616 {RPCResult::Type::NUM, "sequence",
617 "Script sequence number"},
618 {RPCResult::Type::STR, "error",
619 "Verification or signing error related to the "
620 "input"},
621 }},
622 }},
623 }},
625 HelpExampleCli("signrawtransactionwithkey",
626 "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"") +
627 HelpExampleRpc("signrawtransactionwithkey",
628 "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")},
629 [&](const RPCHelpMan &self, const Config &config,
630 const JSONRPCRequest &request) -> UniValue {
632 if (!DecodeHexTx(mtx, request.params[0].get_str())) {
634 "TX decode failed");
635 }
636
638 const UniValue &keys = request.params[1].get_array();
639 for (size_t idx = 0; idx < keys.size(); ++idx) {
640 const UniValue &k = keys[idx];
641 CKey key = DecodeSecret(k.get_str());
642 if (!key.IsValid()) {
644 "Invalid private key");
645 }
646 keystore.AddKey(key);
647 }
648
649 // Fetch previous transactions (inputs):
650 std::map<COutPoint, Coin> coins;
651 for (const CTxIn &txin : mtx.vin) {
652 // Create empty map entry keyed by prevout.
653 coins[txin.prevout];
654 }
655 NodeContext &node = EnsureAnyNodeContext(request.context);
656 FindCoins(node, coins);
657
658 // Parse the prevtxs array
659 ParsePrevouts(request.params[2], &keystore, coins);
660
661 UniValue result(UniValue::VOBJ);
662 SignTransaction(mtx, &keystore, coins, request.params[3], result);
663 return result;
664 },
665 };
666}
667
669 return RPCHelpMan{
670 "decodepsbt",
671 "Return a JSON object representing the serialized, base64-encoded "
672 "partially signed Bitcoin transaction.\n",
673 {
675 "The PSBT base64 string"},
676 },
677 RPCResult{
679 "",
680 "",
681 {
683 "tx",
684 "The decoded network-serialized unsigned transaction.",
685 {
687 "The layout is the same as the output of "
688 "decoderawtransaction."},
689 }},
691 "unknown",
692 "The unknown global fields",
693 {
695 "(key-value pair) An unknown key-value pair"},
696 }},
698 "inputs",
699 "",
700 {
702 "",
703 "",
704 {
706 "utxo",
707 /* optional */ true,
708 "Transaction output for UTXOs",
709 {
710 {RPCResult::Type::NUM, "amount",
711 "The value in " + Currency::get().ticker},
713 "scriptPubKey",
714 "",
715 {
716 {RPCResult::Type::STR, "asm", "The asm"},
718 "The hex"},
719 {RPCResult::Type::STR, "type",
720 "The type, eg 'pubkeyhash'"},
721 {RPCResult::Type::STR, "address",
722 " Bitcoin address if there is one"},
723 }},
724 }},
726 "partial_signatures",
727 /* optional */ true,
728 "",
729 {
730 {RPCResult::Type::STR, "pubkey",
731 "The public key and signature that corresponds "
732 "to it."},
733 }},
734 {RPCResult::Type::STR, "sighash", /* optional */ true,
735 "The sighash type to be used"},
737 "redeem_script",
738 /* optional */ true,
739 "",
740 {
741 {RPCResult::Type::STR, "asm", "The asm"},
742 {RPCResult::Type::STR_HEX, "hex", "The hex"},
743 {RPCResult::Type::STR, "type",
744 "The type, eg 'pubkeyhash'"},
745 }},
747 "bip32_derivs",
748 /* optional */ true,
749 "",
750 {
752 "pubkey",
753 /* optional */ true,
754 "The public key with the derivation path as "
755 "the value.",
756 {
757 {RPCResult::Type::STR, "master_fingerprint",
758 "The fingerprint of the master key"},
759 {RPCResult::Type::STR, "path", "The path"},
760 }},
761 }},
763 "final_scriptsig",
764 /* optional */ true,
765 "",
766 {
767 {RPCResult::Type::STR, "asm", "The asm"},
768 {RPCResult::Type::STR, "hex", "The hex"},
769 }},
771 "unknown",
772 "The unknown global fields",
773 {
775 "(key-value pair) An unknown key-value pair"},
776 }},
777 }},
778 }},
780 "outputs",
781 "",
782 {
784 "",
785 "",
786 {
788 "redeem_script",
789 /* optional */ true,
790 "",
791 {
792 {RPCResult::Type::STR, "asm", "The asm"},
793 {RPCResult::Type::STR_HEX, "hex", "The hex"},
794 {RPCResult::Type::STR, "type",
795 "The type, eg 'pubkeyhash'"},
796 }},
798 "bip32_derivs",
799 /* optional */ true,
800 "",
801 {
803 "",
804 "",
805 {
806 {RPCResult::Type::STR, "pubkey",
807 "The public key this path corresponds to"},
808 {RPCResult::Type::STR, "master_fingerprint",
809 "The fingerprint of the master key"},
810 {RPCResult::Type::STR, "path", "The path"},
811 }},
812 }},
814 "unknown",
815 "The unknown global fields",
816 {
818 "(key-value pair) An unknown key-value pair"},
819 }},
820 }},
821 }},
822 {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
823 "The transaction fee paid if all UTXOs slots in the PSBT have "
824 "been filled."},
825 }},
826 RPCExamples{HelpExampleCli("decodepsbt", "\"psbt\"")},
827 [&](const RPCHelpMan &self, const Config &config,
828 const JSONRPCRequest &request) -> UniValue {
829 // Unserialize the transactions
831 std::string error;
832 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
834 strprintf("TX decode failed %s", error));
835 }
836
837 UniValue result(UniValue::VOBJ);
838
839 // Add the decoded tx
840 UniValue tx_univ(UniValue::VOBJ);
841 TxToUniv(CTransaction(*psbtx.tx), BlockHash(), tx_univ, false);
842 result.pushKV("tx", std::move(tx_univ));
843
844 // Unknown data
845 if (psbtx.unknown.size() > 0) {
846 UniValue unknowns(UniValue::VOBJ);
847 for (auto entry : psbtx.unknown) {
848 unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
849 }
850 result.pushKV("unknown", std::move(unknowns));
851 }
852
853 // inputs
854 Amount total_in = Amount::zero();
855 bool have_all_utxos = true;
856 UniValue inputs(UniValue::VARR);
857 for (size_t i = 0; i < psbtx.inputs.size(); ++i) {
858 const PSBTInput &input = psbtx.inputs[i];
860 // UTXOs
861 if (!input.utxo.IsNull()) {
862 const CTxOut &txout = input.utxo;
863
865
866 out.pushKV("amount", txout.nValue);
867 if (MoneyRange(txout.nValue) &&
868 MoneyRange(total_in + txout.nValue)) {
869 total_in += txout.nValue;
870 } else {
871 // Hack to just not show fee later
872 have_all_utxos = false;
873 }
874
876 ScriptToUniv(txout.scriptPubKey, o, true);
877 out.pushKV("scriptPubKey", std::move(o));
878 in.pushKV("utxo", std::move(out));
879 } else {
880 have_all_utxos = false;
881 }
882
883 // Partial sigs
884 if (!input.partial_sigs.empty()) {
885 UniValue partial_sigs(UniValue::VOBJ);
886 for (const auto &sig : input.partial_sigs) {
887 partial_sigs.pushKV(HexStr(sig.second.first),
888 HexStr(sig.second.second));
889 }
890 in.pushKV("partial_signatures", std::move(partial_sigs));
891 }
892
893 // Sighash
894 uint8_t sighashbyte =
895 input.sighash_type.getRawSigHashType() & 0xff;
896 if (sighashbyte > 0) {
897 in.pushKV("sighash", SighashToStr(sighashbyte));
898 }
899
900 // Redeem script
901 if (!input.redeem_script.empty()) {
903 ScriptToUniv(input.redeem_script, r, false);
904 in.pushKV("redeem_script", std::move(r));
905 }
906
907 // keypaths
908 if (!input.hd_keypaths.empty()) {
909 UniValue keypaths(UniValue::VARR);
910 for (auto entry : input.hd_keypaths) {
911 UniValue keypath(UniValue::VOBJ);
912 keypath.pushKV("pubkey", HexStr(entry.first));
913
914 keypath.pushKV(
915 "master_fingerprint",
916 strprintf("%08x",
917 ReadBE32(entry.second.fingerprint)));
918 keypath.pushKV("path",
919 WriteHDKeypath(entry.second.path));
920 keypaths.push_back(std::move(keypath));
921 }
922 in.pushKV("bip32_derivs", std::move(keypaths));
923 }
924
925 // Final scriptSig
926 if (!input.final_script_sig.empty()) {
927 UniValue scriptsig(UniValue::VOBJ);
928 scriptsig.pushKV(
929 "asm", ScriptToAsmStr(input.final_script_sig, true));
930 scriptsig.pushKV("hex", HexStr(input.final_script_sig));
931 in.pushKV("final_scriptSig", std::move(scriptsig));
932 }
933
934 // Unknown data
935 if (input.unknown.size() > 0) {
936 UniValue unknowns(UniValue::VOBJ);
937 for (auto entry : input.unknown) {
938 unknowns.pushKV(HexStr(entry.first),
939 HexStr(entry.second));
940 }
941 in.pushKV("unknown", std::move(unknowns));
942 }
943
944 inputs.push_back(std::move(in));
945 }
946 result.pushKV("inputs", std::move(inputs));
947
948 // outputs
949 Amount output_value = Amount::zero();
950 UniValue outputs(UniValue::VARR);
951 for (size_t i = 0; i < psbtx.outputs.size(); ++i) {
952 const PSBTOutput &output = psbtx.outputs[i];
954 // Redeem script
955 if (!output.redeem_script.empty()) {
957 ScriptToUniv(output.redeem_script, r, false);
958 out.pushKV("redeem_script", std::move(r));
959 }
960
961 // keypaths
962 if (!output.hd_keypaths.empty()) {
963 UniValue keypaths(UniValue::VARR);
964 for (auto entry : output.hd_keypaths) {
965 UniValue keypath(UniValue::VOBJ);
966 keypath.pushKV("pubkey", HexStr(entry.first));
967 keypath.pushKV(
968 "master_fingerprint",
969 strprintf("%08x",
970 ReadBE32(entry.second.fingerprint)));
971 keypath.pushKV("path",
972 WriteHDKeypath(entry.second.path));
973 keypaths.push_back(std::move(keypath));
974 }
975 out.pushKV("bip32_derivs", std::move(keypaths));
976 }
977
978 // Unknown data
979 if (output.unknown.size() > 0) {
980 UniValue unknowns(UniValue::VOBJ);
981 for (auto entry : output.unknown) {
982 unknowns.pushKV(HexStr(entry.first),
983 HexStr(entry.second));
984 }
985 out.pushKV("unknown", std::move(unknowns));
986 }
987
988 outputs.push_back(std::move(out));
989
990 // Fee calculation
991 if (MoneyRange(psbtx.tx->vout[i].nValue) &&
992 MoneyRange(output_value + psbtx.tx->vout[i].nValue)) {
993 output_value += psbtx.tx->vout[i].nValue;
994 } else {
995 // Hack to just not show fee later
996 have_all_utxos = false;
997 }
998 }
999 result.pushKV("outputs", std::move(outputs));
1000 if (have_all_utxos) {
1001 result.pushKV("fee", total_in - output_value);
1002 }
1003
1004 return result;
1005 },
1006 };
1007}
1008
1010 return RPCHelpMan{
1011 "combinepsbt",
1012 "Combine multiple partially signed Bitcoin transactions into one "
1013 "transaction.\n"
1014 "Implements the Combiner role.\n",
1015 {
1016 {
1017 "txs",
1020 "The base64 strings of partially signed transactions",
1021 {
1023 "A base64 string of a PSBT"},
1024 },
1025 },
1026 },
1028 "The base64-encoded partially signed transaction"},
1030 "combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")},
1031 [&](const RPCHelpMan &self, const Config &config,
1032 const JSONRPCRequest &request) -> UniValue {
1033 // Unserialize the transactions
1034 std::vector<PartiallySignedTransaction> psbtxs;
1035 const UniValue &txs = request.params[0].get_array();
1036 if (txs.empty()) {
1038 "Parameter 'txs' cannot be empty");
1039 }
1040 for (size_t i = 0; i < txs.size(); ++i) {
1042 std::string error;
1043 if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1045 strprintf("TX decode failed %s", error));
1046 }
1047 psbtxs.push_back(psbtx);
1048 }
1049
1050 PartiallySignedTransaction merged_psbt;
1051 if (!CombinePSBTs(merged_psbt, psbtxs)) {
1052 throw JSONRPCError(
1054 "PSBTs not compatible (different transactions)");
1055 }
1056
1057 DataStream ssTx{};
1058 ssTx << merged_psbt;
1059 return EncodeBase64(ssTx);
1060 },
1061 };
1062}
1063
1065 return RPCHelpMan{
1066 "finalizepsbt",
1067 "Finalize the inputs of a PSBT. If the transaction is fully signed, it "
1068 "will produce a\n"
1069 "network serialized transaction which can be broadcast with "
1070 "sendrawtransaction. Otherwise a PSBT will be\n"
1071 "created which has the final_scriptSigfields filled for inputs that "
1072 "are complete.\n"
1073 "Implements the Finalizer and Extractor roles.\n",
1074 {
1076 "A base64 string of a PSBT"},
1077 {"extract", RPCArg::Type::BOOL, RPCArg::Default{true},
1078 "If true and the transaction is complete,\n"
1079 " extract and return the complete "
1080 "transaction in normal network serialization instead of the "
1081 "PSBT."},
1082 },
1084 "",
1085 "",
1086 {
1087 {RPCResult::Type::STR, "psbt",
1088 "The base64-encoded partially signed transaction if not "
1089 "extracted"},
1091 "The hex-encoded network transaction if extracted"},
1092 {RPCResult::Type::BOOL, "complete",
1093 "If the transaction has a complete set of signatures"},
1094 }},
1095 RPCExamples{HelpExampleCli("finalizepsbt", "\"psbt\"")},
1096 [&](const RPCHelpMan &self, const Config &config,
1097 const JSONRPCRequest &request) -> UniValue {
1098 // Unserialize the transactions
1100 std::string error;
1101 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1103 strprintf("TX decode failed %s", error));
1104 }
1105
1106 bool extract =
1107 request.params[1].isNull() ||
1108 (!request.params[1].isNull() && request.params[1].get_bool());
1109
1111 bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1112
1113 UniValue result(UniValue::VOBJ);
1114 DataStream ssTx{};
1115 std::string result_str;
1116
1117 if (complete && extract) {
1118 ssTx << mtx;
1119 result_str = HexStr(ssTx);
1120 result.pushKV("hex", result_str);
1121 } else {
1122 ssTx << psbtx;
1123 result_str = EncodeBase64(ssTx.str());
1124 result.pushKV("psbt", result_str);
1125 }
1126 result.pushKV("complete", complete);
1127
1128 return result;
1129 },
1130 };
1131}
1132
1134 return RPCHelpMan{
1135 "createpsbt",
1136 "Creates a transaction in the Partially Signed Transaction format.\n"
1137 "Implements the Creator role.\n",
1138 {
1139 {
1140 "inputs",
1143 "The json objects",
1144 {
1145 {
1146 "",
1149 "",
1150 {
1151 {"txid", RPCArg::Type::STR_HEX,
1152 RPCArg::Optional::NO, "The transaction id"},
1154 "The output number"},
1155 {"sequence", RPCArg::Type::NUM,
1156 RPCArg::DefaultHint{"depends on the value of the "
1157 "'locktime' argument"},
1158 "The sequence number"},
1159 },
1160 },
1161 },
1162 },
1163 {"outputs",
1166 "The outputs (key-value pairs), where none of "
1167 "the keys are duplicated.\n"
1168 "That is, each address can only appear once and there can only "
1169 "be one 'data' object.\n"
1170 "For compatibility reasons, a dictionary, which holds the "
1171 "key-value pairs directly, is also\n"
1172 " accepted as second parameter.",
1173 {
1174 {
1175 "",
1178 "",
1179 {
1181 "A key-value pair. The key (string) is the "
1182 "bitcoin address, the value (float or string) is "
1183 "the amount in " +
1185 },
1186 },
1187 {
1188 "",
1191 "",
1192 {
1194 "A key-value pair. The key must be \"data\", the "
1195 "value is hex-encoded data"},
1196 },
1197 },
1198 },
1200 {"locktime", RPCArg::Type::NUM, RPCArg::Default{0},
1201 "Raw locktime. Non-0 value also locktime-activates inputs"},
1202 },
1204 "The resulting raw transaction (base64-encoded string)"},
1206 "createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1207 "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")},
1208 [&](const RPCHelpMan &self, const Config &config,
1209 const JSONRPCRequest &request) -> UniValue {
1210 CMutableTransaction rawTx =
1211 ConstructTransaction(config.GetChainParams(), request.params[0],
1212 request.params[1], request.params[2]);
1213
1214 // Make a blank psbt
1216 psbtx.tx = rawTx;
1217 for (size_t i = 0; i < rawTx.vin.size(); ++i) {
1218 psbtx.inputs.push_back(PSBTInput());
1219 }
1220 for (size_t i = 0; i < rawTx.vout.size(); ++i) {
1221 psbtx.outputs.push_back(PSBTOutput());
1222 }
1223
1224 // Serialize the PSBT
1225 DataStream ssTx{};
1226 ssTx << psbtx;
1227
1228 return EncodeBase64(ssTx);
1229 },
1230 };
1231}
1232
1234 return RPCHelpMan{
1235 "converttopsbt",
1236 "Converts a network serialized transaction to a PSBT. "
1237 "This should be used only with createrawtransaction and "
1238 "fundrawtransaction\n"
1239 "createpsbt and walletcreatefundedpsbt should be used for new "
1240 "applications.\n",
1241 {
1243 "The hex string of a raw transaction"},
1244 {"permitsigdata", RPCArg::Type::BOOL, RPCArg::Default{false},
1245 "If true, any signatures in the input will be discarded and "
1246 "conversion.\n"
1247 " will continue. If false, RPC will "
1248 "fail if any signatures are present."},
1249 },
1251 "The resulting raw transaction (base64-encoded string)"},
1253 "\nCreate a transaction\n" +
1254 HelpExampleCli("createrawtransaction",
1255 "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]"
1256 "\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1257 "\nConvert the transaction to a PSBT\n" +
1258 HelpExampleCli("converttopsbt", "\"rawtransaction\"")},
1259 [&](const RPCHelpMan &self, const Config &config,
1260 const JSONRPCRequest &request) -> UniValue {
1261 // parse hex string from parameter
1263 bool permitsigdata = request.params[1].isNull()
1264 ? false
1265 : request.params[1].get_bool();
1266 if (!DecodeHexTx(tx, request.params[0].get_str())) {
1268 "TX decode failed");
1269 }
1270
1271 // Remove all scriptSigs from inputs
1272 for (CTxIn &input : tx.vin) {
1273 if (!input.scriptSig.empty() && !permitsigdata) {
1275 "Inputs must not have scriptSigs");
1276 }
1277 input.scriptSig.clear();
1278 }
1279
1280 // Make a blank psbt
1282 psbtx.tx = tx;
1283 for (size_t i = 0; i < tx.vin.size(); ++i) {
1284 psbtx.inputs.push_back(PSBTInput());
1285 }
1286 for (size_t i = 0; i < tx.vout.size(); ++i) {
1287 psbtx.outputs.push_back(PSBTOutput());
1288 }
1289
1290 // Serialize the PSBT
1291 DataStream ssTx{};
1292 ssTx << psbtx;
1293
1294 return EncodeBase64(ssTx);
1295 },
1296 };
1297}
1298
1300 return RPCHelpMan{
1301 "utxoupdatepsbt",
1302 "Updates all inputs and outputs in a PSBT with data from output "
1303 "descriptors, the UTXO set or the mempool.\n",
1304 {
1306 "A base64 string of a PSBT"},
1307 {"descriptors",
1310 "An array of either strings or objects",
1311 {
1313 "An output descriptor"},
1314 {"",
1317 "An object with an output descriptor and extra information",
1318 {
1320 "An output descriptor"},
1321 {"range", RPCArg::Type::RANGE, RPCArg::Default{1000},
1322 "Up to what index HD chains should be explored (either "
1323 "end or [begin,end])"},
1324 }},
1325 }},
1326 },
1328 "The base64-encoded partially signed transaction with inputs "
1329 "updated"},
1330 RPCExamples{HelpExampleCli("utxoupdatepsbt", "\"psbt\"")},
1331 [&](const RPCHelpMan &self, const Config &config,
1332 const JSONRPCRequest &request) -> UniValue {
1333 // Unserialize the transactions
1335 std::string error;
1336 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1338 strprintf("TX decode failed %s", error));
1339 }
1340
1341 // Parse descriptors, if any.
1342 FlatSigningProvider provider;
1343 if (!request.params[1].isNull()) {
1344 auto descs = request.params[1].get_array();
1345 for (size_t i = 0; i < descs.size(); ++i) {
1346 EvalDescriptorStringOrObject(descs[i], provider);
1347 }
1348 }
1349 // We don't actually need private keys further on; hide them as a
1350 // precaution.
1351 HidingSigningProvider public_provider(&provider, /* nosign */ true,
1352 /* nobip32derivs */ false);
1353
1354 // Fetch previous transactions (inputs):
1355 CCoinsView viewDummy;
1356 CCoinsViewCache view(&viewDummy);
1357 {
1358 NodeContext &node = EnsureAnyNodeContext(request.context);
1359 const CTxMemPool &mempool = EnsureMemPool(node);
1361 LOCK2(cs_main, mempool.cs);
1362 CCoinsViewCache &viewChain =
1363 chainman.ActiveChainstate().CoinsTip();
1364 CCoinsViewMemPool viewMempool(&viewChain, mempool);
1365 // temporarily switch cache backend to db+mempool view
1366 view.SetBackend(viewMempool);
1367
1368 for (const CTxIn &txin : psbtx.tx->vin) {
1369 // Load entries from viewChain into view; can fail.
1370 view.AccessCoin(txin.prevout);
1371 }
1372
1373 // switch back to avoid locking mempool for too long
1374 view.SetBackend(viewDummy);
1375 }
1376
1377 // Fill the inputs
1378 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
1379 PSBTInput &input = psbtx.inputs.at(i);
1380
1381 if (!input.utxo.IsNull()) {
1382 continue;
1383 }
1384
1385 // Update script/keypath information using descriptor data.
1386 // Note that SignPSBTInput does a lot more than just
1387 // constructing ECDSA signatures we don't actually care about
1388 // those here, in fact.
1389 SignPSBTInput(public_provider, psbtx, i,
1390 /* sighash_type */ SigHashType().withForkId());
1391 }
1392
1393 // Update script/keypath information using descriptor data.
1394 for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1395 UpdatePSBTOutput(public_provider, psbtx, i);
1396 }
1397
1398 DataStream ssTx{};
1399 ssTx << psbtx;
1400 return EncodeBase64(ssTx);
1401 },
1402 };
1403}
1404
1406 return RPCHelpMan{
1407 "joinpsbts",
1408 "Joins multiple distinct PSBTs with different inputs and outputs "
1409 "into one PSBT with inputs and outputs from all of the PSBTs\n"
1410 "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1411 {{"txs",
1414 "The base64 strings of partially signed transactions",
1416 "A base64 string of a PSBT"}}}},
1418 "The base64-encoded partially signed transaction"},
1419 RPCExamples{HelpExampleCli("joinpsbts", "\"psbt\"")},
1420 [&](const RPCHelpMan &self, const Config &config,
1421 const JSONRPCRequest &request) -> UniValue {
1422 // Unserialize the transactions
1423 std::vector<PartiallySignedTransaction> psbtxs;
1424 const UniValue &txs = request.params[0].get_array();
1425
1426 if (txs.size() <= 1) {
1427 throw JSONRPCError(
1429 "At least two PSBTs are required to join PSBTs.");
1430 }
1431
1432 uint32_t best_version = 1;
1433 uint32_t best_locktime = 0xffffffff;
1434 for (size_t i = 0; i < txs.size(); ++i) {
1436 std::string error;
1437 if (!DecodeBase64PSBT(psbtx, txs[i].get_str(), error)) {
1439 strprintf("TX decode failed %s", error));
1440 }
1441 psbtxs.push_back(psbtx);
1442 // Choose the highest version number
1443 if (static_cast<uint32_t>(psbtx.tx->nVersion) > best_version) {
1444 best_version = static_cast<uint32_t>(psbtx.tx->nVersion);
1445 }
1446 // Choose the lowest lock time
1447 if (psbtx.tx->nLockTime < best_locktime) {
1448 best_locktime = psbtx.tx->nLockTime;
1449 }
1450 }
1451
1452 // Create a blank psbt where everything will be added
1453 PartiallySignedTransaction merged_psbt;
1454 merged_psbt.tx = CMutableTransaction();
1455 merged_psbt.tx->nVersion = static_cast<int32_t>(best_version);
1456 merged_psbt.tx->nLockTime = best_locktime;
1457
1458 // Merge
1459 for (auto &psbt : psbtxs) {
1460 for (size_t i = 0; i < psbt.tx->vin.size(); ++i) {
1461 if (!merged_psbt.AddInput(psbt.tx->vin[i],
1462 psbt.inputs[i])) {
1463 throw JSONRPCError(
1465 strprintf("Input %s:%d exists in multiple PSBTs",
1466 psbt.tx->vin[i]
1467 .prevout.GetTxId()
1468 .ToString()
1469 .c_str(),
1470 psbt.tx->vin[i].prevout.GetN()));
1471 }
1472 }
1473 for (size_t i = 0; i < psbt.tx->vout.size(); ++i) {
1474 merged_psbt.AddOutput(psbt.tx->vout[i], psbt.outputs[i]);
1475 }
1476 merged_psbt.unknown.insert(psbt.unknown.begin(),
1477 psbt.unknown.end());
1478 }
1479
1480 // Generate list of shuffled indices for shuffling inputs and
1481 // outputs of the merged PSBT
1482 std::vector<int> input_indices(merged_psbt.inputs.size());
1483 std::iota(input_indices.begin(), input_indices.end(), 0);
1484 std::vector<int> output_indices(merged_psbt.outputs.size());
1485 std::iota(output_indices.begin(), output_indices.end(), 0);
1486
1487 // Shuffle input and output indices lists
1488 Shuffle(input_indices.begin(), input_indices.end(),
1490 Shuffle(output_indices.begin(), output_indices.end(),
1492
1493 PartiallySignedTransaction shuffled_psbt;
1494 shuffled_psbt.tx = CMutableTransaction();
1495 shuffled_psbt.tx->nVersion = merged_psbt.tx->nVersion;
1496 shuffled_psbt.tx->nLockTime = merged_psbt.tx->nLockTime;
1497 for (int i : input_indices) {
1498 shuffled_psbt.AddInput(merged_psbt.tx->vin[i],
1499 merged_psbt.inputs[i]);
1500 }
1501 for (int i : output_indices) {
1502 shuffled_psbt.AddOutput(merged_psbt.tx->vout[i],
1503 merged_psbt.outputs[i]);
1504 }
1505 shuffled_psbt.unknown.insert(merged_psbt.unknown.begin(),
1506 merged_psbt.unknown.end());
1507
1508 DataStream ssTx{};
1509 ssTx << shuffled_psbt;
1510 return EncodeBase64(ssTx);
1511 },
1512 };
1513}
1514
1516 return RPCHelpMan{
1517 "analyzepsbt",
1518 "Analyzes and provides information about the current status of a "
1519 "PSBT and its inputs\n",
1521 "A base64 string of a PSBT"}},
1522 RPCResult{
1524 "",
1525 "",
1526 {
1528 "inputs",
1529 "",
1530 {
1532 "",
1533 "",
1534 {
1535 {RPCResult::Type::BOOL, "has_utxo",
1536 "Whether a UTXO is provided"},
1537 {RPCResult::Type::BOOL, "is_final",
1538 "Whether the input is finalized"},
1540 "missing",
1541 /* optional */ true,
1542 "Things that are missing that are required to "
1543 "complete this input",
1544 {
1546 "pubkeys",
1547 /* optional */ true,
1548 "",
1549 {
1550 {RPCResult::Type::STR_HEX, "keyid",
1551 "Public key ID, hash160 of the public "
1552 "key, of a public key whose BIP 32 "
1553 "derivation path is missing"},
1554 }},
1556 "signatures",
1557 /* optional */ true,
1558 "",
1559 {
1560 {RPCResult::Type::STR_HEX, "keyid",
1561 "Public key ID, hash160 of the public "
1562 "key, of a public key whose signature is "
1563 "missing"},
1564 }},
1565 {RPCResult::Type::STR_HEX, "redeemscript",
1566 /* optional */ true,
1567 "Hash160 of the redeemScript that is missing"},
1568 }},
1569 {RPCResult::Type::STR, "next", /* optional */ true,
1570 "Role of the next person that this input needs to "
1571 "go to"},
1572 }},
1573 }},
1574 {RPCResult::Type::NUM, "estimated_vsize", /* optional */ true,
1575 "Estimated vsize of the final signed transaction"},
1576 {RPCResult::Type::STR_AMOUNT, "estimated_feerate",
1577 /* optional */ true,
1578 "Estimated feerate of the final signed transaction in " +
1580 "/kB. Shown only if all UTXO slots in the PSBT have been "
1581 "filled"},
1582 {RPCResult::Type::STR_AMOUNT, "fee", /* optional */ true,
1583 "The transaction fee paid. Shown only if all UTXO slots in "
1584 "the PSBT have been filled"},
1585 {RPCResult::Type::STR, "next",
1586 "Role of the next person that this psbt needs to go to"},
1587 {RPCResult::Type::STR, "error", /* optional */ true,
1588 "Error message (if there is one)"},
1589 }},
1590 RPCExamples{HelpExampleCli("analyzepsbt", "\"psbt\"")},
1591 [&](const RPCHelpMan &self, const Config &config,
1592 const JSONRPCRequest &request) -> UniValue {
1593 // Unserialize the transaction
1595 std::string error;
1596 if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1598 strprintf("TX decode failed %s", error));
1599 }
1600
1601 PSBTAnalysis psbta = AnalyzePSBT(psbtx);
1602
1603 UniValue result(UniValue::VOBJ);
1604 UniValue inputs_result(UniValue::VARR);
1605 for (const auto &input : psbta.inputs) {
1606 UniValue input_univ(UniValue::VOBJ);
1607 UniValue missing(UniValue::VOBJ);
1608
1609 input_univ.pushKV("has_utxo", input.has_utxo);
1610 input_univ.pushKV("is_final", input.is_final);
1611 input_univ.pushKV("next", PSBTRoleName(input.next));
1612
1613 if (!input.missing_pubkeys.empty()) {
1614 UniValue missing_pubkeys_univ(UniValue::VARR);
1615 for (const CKeyID &pubkey : input.missing_pubkeys) {
1616 missing_pubkeys_univ.push_back(HexStr(pubkey));
1617 }
1618 missing.pushKV("pubkeys", std::move(missing_pubkeys_univ));
1619 }
1620 if (!input.missing_redeem_script.IsNull()) {
1621 missing.pushKV("redeemscript",
1622 HexStr(input.missing_redeem_script));
1623 }
1624 if (!input.missing_sigs.empty()) {
1625 UniValue missing_sigs_univ(UniValue::VARR);
1626 for (const CKeyID &pubkey : input.missing_sigs) {
1627 missing_sigs_univ.push_back(HexStr(pubkey));
1628 }
1629 missing.pushKV("signatures", std::move(missing_sigs_univ));
1630 }
1631 if (!missing.getKeys().empty()) {
1632 input_univ.pushKV("missing", std::move(missing));
1633 }
1634 inputs_result.push_back(std::move(input_univ));
1635 }
1636 if (!inputs_result.empty()) {
1637 result.pushKV("inputs", std::move(inputs_result));
1638 }
1639 if (psbta.estimated_vsize != std::nullopt) {
1640 result.pushKV("estimated_vsize", (int)*psbta.estimated_vsize);
1641 }
1642 if (psbta.estimated_feerate != std::nullopt) {
1643 result.pushKV("estimated_feerate",
1644 psbta.estimated_feerate->GetFeePerK());
1645 }
1646 if (psbta.fee != std::nullopt) {
1647 result.pushKV("fee", *psbta.fee);
1648 }
1649 result.pushKV("next", PSBTRoleName(psbta.next));
1650 if (!psbta.error.empty()) {
1651 result.pushKV("error", psbta.error);
1652 }
1653
1654 return result;
1655 },
1656 };
1657}
1658
1660 return RPCHelpMan{
1661 "gettransactionstatus",
1662 "Return the current pool a transaction belongs to\n",
1663 {
1665 "The transaction id"},
1666 },
1667 RPCResult{
1669 "",
1670 "",
1671 {
1672 {RPCResult::Type::STR, "pool",
1673 "In which pool the transaction is currently located, "
1674 "either none, mempool, orphanage or conflicting"},
1675 {RPCResult::Type::STR, "block",
1676 "If the transaction is mined, this is the blockhash of the "
1677 "mining block, otherwise \"none\". This field is only "
1678 "present if -txindex is enabled."},
1679 }},
1680 RPCExamples{HelpExampleCli("gettransactionstatus", "\"txid\"")},
1681 [&](const RPCHelpMan &self, const Config &config,
1682 const JSONRPCRequest &request) -> UniValue {
1683 const NodeContext &node = EnsureAnyNodeContext(request.context);
1684 CTxMemPool &mempool = EnsureMemPool(node);
1685
1686 TxId txid = TxId(ParseHashV(request.params[0], "parameter 1"));
1687
1689
1690 if (mempool.exists(txid)) {
1691 ret.pushKV("pool", "mempool");
1692 } else if (mempool.withOrphanage(
1693 [&txid](const TxOrphanage &orphanage) {
1694 return orphanage.HaveTx(txid);
1695 })) {
1696 ret.pushKV("pool", "orphanage");
1697 } else if (mempool.withConflicting(
1698 [&txid](const TxConflicting &conflicting) {
1699 return conflicting.HaveTx(txid);
1700 })) {
1701 ret.pushKV("pool", "conflicting");
1702 } else {
1703 ret.pushKV("pool", "none");
1704 }
1705
1706 if (g_txindex) {
1707 if (!g_txindex->BlockUntilSyncedToCurrentChain()) {
1708 throw JSONRPCError(
1710 "Blockchain transactions are still in the process of "
1711 "being indexed");
1712 }
1713
1714 CTransactionRef tx;
1715 BlockHash blockhash;
1716 if (g_txindex->FindTx(txid, blockhash, tx)) {
1717 ret.pushKV("block", blockhash.GetHex());
1718 } else {
1719 ret.pushKV("block", "none");
1720 }
1721 }
1722
1723 return ret;
1724 },
1725 };
1726}
1727
1729 // clang-format off
1730 static const CRPCCommand commands[] = {
1731 // category actor (function)
1732 // ------------------ ----------------------
1733 { "rawtransactions", getrawtransaction, },
1734 { "rawtransactions", createrawtransaction, },
1735 { "rawtransactions", decoderawtransaction, },
1736 { "rawtransactions", decodescript, },
1737 { "rawtransactions", combinerawtransaction, },
1738 { "rawtransactions", signrawtransactionwithkey, },
1739 { "rawtransactions", decodepsbt, },
1740 { "rawtransactions", combinepsbt, },
1741 { "rawtransactions", finalizepsbt, },
1742 { "rawtransactions", createpsbt, },
1743 { "rawtransactions", converttopsbt, },
1744 { "rawtransactions", utxoupdatepsbt, },
1745 { "rawtransactions", joinpsbts, },
1746 { "rawtransactions", analyzepsbt, },
1747 { "rawtransactions", gettransactionstatus, },
1748 };
1749 // clang-format on
1750 for (const auto &c : commands) {
1751 t.appendCommand(c.name, &c);
1752 }
1753}
bool MoneyRange(const Amount nValue)
Definition: amount.h:171
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
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:160
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:190
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:170
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:112
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:46
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:363
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:195
Abstract view on the open txout dataset.
Definition: coins.h:305
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:652
An encapsulated secp256k1 private key.
Definition: key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:97
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:330
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
bool exists(const TxId &txid) const
Definition: txmempool.h:535
auto withOrphanage(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_orphanage)
Definition: txmempool.h:595
auto withConflicting(Callable &&func) const EXCLUSIVE_LOCKS_REQUIRED(!cs_conflicting)
Definition: txmempool.h:603
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:733
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:832
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:790
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1436
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1437
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
A UTXO entry.
Definition: coins.h:29
CTxOut & GetTxOut()
Definition: coins.h:50
bool IsSpent() const
Definition: coins.h:48
Definition: config.h:19
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:118
Fast randomness source.
Definition: random.h:411
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< 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
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)
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:179
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:173
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:194
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:196
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:106
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS, std::function< bool(const CTxOut &)> is_change_func={})
Definition: core_write.cpp:221
static uint32_t ReadBE32(const uint8_t *ptr)
Definition: common.h:52
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
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
Definition: messages.h:12
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
Provides helpful miscellaneous information about where a PSBT is in the signing workflow.
Definition: psbt.cpp:16
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
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
SchnorrSig sig
Definition: processor.cpp:523
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:294
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:277
bool CombinePSBTs(PartiallySignedTransaction &out, const std::vector< PartiallySignedTransaction > &psbtxs)
Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial sign...
Definition: psbt.cpp:263
bool 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
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:512
RPCHelpMan joinpsbts()
static RPCHelpMan getrawtransaction()
static RPCHelpMan converttopsbt()
RPCHelpMan analyzepsbt()
static RPCHelpMan decoderawtransaction()
static RPCHelpMan combinepsbt()
static RPCHelpMan decodepsbt()
RPCHelpMan gettransactionstatus()
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 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.
std::vector< RPCResult > DecodeTxDoc(const std::string &txid_field_doc, bool wallet)
Explain the UniValue "decoded" transaction object, may include extra fields if processed by wallet.
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::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:163
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:107
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:180
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:1382
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:35
std::string GetAllOutputTypes()
Definition: util.cpp:318
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:86
#define extract(n)
Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits.
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
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
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:155
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
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:212
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
bool skip_type_check
Definition: util.h:146
@ 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:48
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 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:17
std::string EncodeBase64(Span< const uint8_t > input)