Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <rpc/register.h> // IWYU pragma: associated8#include <addresstype.h>9#include <base58.h>10#include <chain.h>11#include <coins.h>12#include <common/types.h>13#include <consensus/amount.h>14#include <core_io.h>15#include <crypto/common.h>16#include <crypto/hex_base.h>17#include <hash.h>18#include <index/txindex.h>19#include <kernel/chainparams.h>20#include <key.h>21#include <key_io.h>22#include <node/blockstorage.h>23#include <node/coin.h>24#include <node/context.h>25#include <node/psbt.h>26#include <node/transaction.h>27#include <policy/feerate.h>28#include <primitives/block.h>29#include <primitives/transaction.h>30#include <psbt.h>31#include <pubkey.h>32#include <random.h>33#include <rpc/protocol.h>34#include <rpc/rawtransaction_util.h>35#include <rpc/request.h>36#include <rpc/server.h>37#include <rpc/server_util.h>38#include <rpc/util.h>39#include <script/interpreter.h>40#include <script/keyorigin.h>41#include <script/script.h>42#include <script/sign.h>43#include <script/signingprovider.h>44#include <script/solver.h>45#include <serialize.h>46#include <streams.h>47#include <sync.h>48#include <tinyformat.h>49#include <txmempool.h>50#include <uint256.h>51#include <undo.h>52#include <univalue.h>53#include <util/bip32.h>54#include <util/check.h>55#include <util/expected.h>56#include <util/result.h>57#include <util/strencodings.h>58#include <util/translation.h>59#include <util/vector.h>60#include <validation.h>62#include <algorithm>63#include <any>64#include <bitset>65#include <cstddef>66#include <cstdint>67#include <map>68#include <memory>69#include <optional>70#include <set>71#include <span>72#include <tuple>73#include <utility>74#include <vector>76using node::AnalyzePSBT;77using node::FindCoins;78using node::GetTransaction;79using node::NodeContext;80using node::PSBTAnalysis;82static constexpr decltype(CTransaction::version) DEFAULT_RAWTX_VERSION{CTransaction::CURRENT_VERSION};84static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry,85Chainstate& active_chainstate, const CTxUndo* txundo = nullptr,86TxVerbosity verbosity = TxVerbosity::SHOW_DETAILS)87{88CHECK_NONFATAL(verbosity >= TxVerbosity::SHOW_DETAILS);89// Call into TxToUniv() in bitcoin-common to decode the transaction hex.90//91// Blockchain contextual information (confirmations and blocktime) is not92// available to code in bitcoin-common, so we query them here and push the93// data into the returned UniValue.94TxToUniv(tx, /*block_hash=*/uint256(), entry, /*include_hex=*/true, txundo, verbosity);96if (!hashBlock.IsNull()) {97LOCK(cs_main);99entry.pushKV("blockhash", hashBlock.GetHex());100const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(hashBlock);101if (pindex) {102if (active_chainstate.m_chain.Contains(*pindex)) {103entry.pushKV("confirmations", 1 + active_chainstate.m_chain.Height() - pindex->nHeight);104entry.pushKV("time", pindex->GetBlockTime());105entry.pushKV("blocktime", pindex->GetBlockTime());106}107else108entry.pushKV("confirmations", 0);109}110}111}113static std::vector<RPCArg> CreateTxDoc()114{115return {116{"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The inputs",117{118{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",119{120{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},121{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},122{"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},123},124},125},126},127{"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"128"Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"129"At least one output of either type must be specified.\n"130"For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"131" accepted as second parameter.",132{133{"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",134{135{"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT},136},137},138{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",139{140{"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data that becomes a part of an OP_RETURN output"},141},142},143},144RPCArgOptions{.skip_type_check = true}},145{"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},146{"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true}, "Marks this transaction as BIP125-replaceable.\n"147"Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."},148{"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_RAWTX_VERSION}, "Transaction version"},149};150}152// Update PSBT with information from the mempool, the UTXO set, the txindex, and the provided descriptors.153// Optionally, sign the inputs that we can using information from the descriptors.154PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std::any& context, const HidingSigningProvider& provider, std::optional<int> sighash_type, bool finalize)155{156// Unserialize the transactions157util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(psbt_string);158if (!psbt_res) {159throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));160}161PartiallySignedTransaction psbtx = *psbt_res;163if (g_txindex) g_txindex->BlockUntilSyncedToCurrentChain();164const NodeContext& node = EnsureAnyNodeContext(context);166// If we can't find the corresponding full transaction for all of our inputs,167// this will be used to find just the utxos for the segwit inputs for which168// the full transaction isn't found169std::map<COutPoint, Coin> coins;171// Fetch previous transactions:172// First, look in the txindex and the mempool173for (PSBTInput& psbt_input : psbtx.inputs) {174// The `non_witness_utxo` is the whole previous transaction175if (psbt_input.non_witness_utxo) continue;177CTransactionRef tx;179// Look in the txindex180if (g_txindex) {181if (auto result{g_txindex->FindTx(psbt_input.prev_txid)}) tx = result->tx;182}183// If we still don't have it look in the mempool184if (!tx) {185tx = node.mempool->get(psbt_input.prev_txid);186}187if (tx) {188psbt_input.non_witness_utxo = tx;189} else {190coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout191}192}194// If we still haven't found all of the inputs, look for the missing ones in the utxo set195if (!coins.empty()) {196FindCoins(node, coins);197for (PSBTInput& input : psbtx.inputs) {198// If there are still missing utxos, add them if they were found in the utxo set199if (!input.non_witness_utxo) {200const Coin& coin = coins.at(input.GetOutPoint());201if (!coin.out.IsNull() && IsSegWitOutput(provider, coin.out.scriptPubKey)) {202input.witness_utxo = coin.out;203}204}205}206}208std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);209if (!txdata_res) {210throw JSONRPCPSBTError(common::PSBTError::INVALID_TX);211}212const PrecomputedTransactionData& txdata = *txdata_res;214for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {215if (PSBTInputSigned(psbtx.inputs.at(i))) {216continue;217}219// Update script/keypath information using descriptor data.220// Note that SignPSBTInput does a lot more than just constructing ECDSA signatures.221// We only actually care about those if our signing provider doesn't hide private222// information, as is the case with `descriptorprocesspsbt`223// Only error for mismatching sighash types as it is critical that the sighash to sign with matches the PSBT's224const auto sign_result = SignPSBTInput(provider, psbtx, /*index=*/i, &txdata, {.sighash_type = sighash_type, .finalize = finalize}, /*out_sigdata=*/nullptr);225if (!sign_result.has_value() && sign_result.error() == common::PSBTError::SIGHASH_MISMATCH) {226throw JSONRPCPSBTError(common::PSBTError::SIGHASH_MISMATCH);227}228}230// Update script/keypath information using descriptor data.231for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {232UpdatePSBTOutput(provider, psbtx, i);233}235RemoveUnnecessaryTransactions(psbtx);237return psbtx;238}240static RPCMethod getrawtransaction()241{242const std::vector<RPCResult> verbosity_1_block{243{RPCResult::Type::BOOL, "in_active_chain", /*optional=*/true, "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},244{RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "the block hash"},245{RPCResult::Type::NUM, "vsize_adjusted", /*optional=*/true, "Sigop-adjusted virtual size in bytes, present for mempool transactions."},246{RPCResult::Type::NUM, "confirmations", /*optional=*/true, "The confirmations"},247{RPCResult::Type::NUM_TIME, "blocktime", /*optional=*/true, "The block time expressed in " + UNIX_EPOCH_TIME},248{RPCResult::Type::NUM, "time", /*optional=*/true, "Same as \"blocktime\""},249{RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded data for 'txid'"},250};